You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

987 lines
29 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
6 years ago
  1. <?php
  2. use Abraham\TwitterOAuth\TwitterOAuth;
  3. use IndieWeb\DateFormatter;
  4. function require_login(&$app, $redirect=true) {
  5. $params = $app->request()->params();
  6. if(array_key_exists('token', $params)) {
  7. try {
  8. $data = JWT::decode($params['token'], Config::$jwtSecret, array('HS256'));
  9. $_SESSION['user_id'] = $data->user_id;
  10. $_SESSION['me'] = $data->me;
  11. } catch(DomainException $e) {
  12. if($redirect) {
  13. header('X-Error: DomainException');
  14. $app->redirect('/', 302);
  15. } else {
  16. return false;
  17. }
  18. } catch(UnexpectedValueException $e) {
  19. if($redirect) {
  20. header('X-Error: UnexpectedValueException');
  21. $app->redirect('/', 302);
  22. } else {
  23. return false;
  24. }
  25. }
  26. }
  27. if(!array_key_exists('user_id', $_SESSION)) {
  28. if($redirect)
  29. $app->redirect('/', 302);
  30. return false;
  31. } else {
  32. return ORM::for_table('users')->find_one($_SESSION['user_id']);
  33. }
  34. }
  35. function generate_login_token($opts=[]) {
  36. return JWT::encode(array_merge([
  37. 'user_id' => $_SESSION['user_id'],
  38. 'me' => $_SESSION['me'],
  39. 'created_at' => time()
  40. ], $opts), Config::$jwtSecret);
  41. }
  42. $app->get('/dashboard', function() use($app) {
  43. if($user=require_login($app)) {
  44. render('dashboard', array(
  45. 'title' => 'Dashboard',
  46. 'authorizing' => false,
  47. 'user' => $user,
  48. ));
  49. }
  50. });
  51. $app->get('/new', function() use($app) {
  52. if($user=require_login($app)) {
  53. $params = $app->request()->params();
  54. $entry = false;
  55. $in_reply_to = '';
  56. if(array_key_exists('reply', $params))
  57. $in_reply_to = $params['reply'];
  58. render('new-post', array(
  59. 'title' => 'New Post',
  60. 'in_reply_to' => $in_reply_to,
  61. 'micropub_endpoint' => $user->micropub_endpoint,
  62. 'media_endpoint' => $user->micropub_media_endpoint,
  63. 'micropub_scope' => $user->micropub_scope,
  64. 'micropub_access_token' => $user->micropub_access_token,
  65. 'response_date' => $user->last_micropub_response_date,
  66. 'syndication_targets' => json_decode($user->syndication_targets, true),
  67. 'supported_visibility' => json_decode($user->supported_visibility, true),
  68. 'location_enabled' => $user->location_enabled,
  69. 'user' => $user,
  70. 'authorizing' => false
  71. ));
  72. }
  73. });
  74. $app->get('/new/last-photo.json', function() use($app) {
  75. if($user=require_login($app)) {
  76. $url = null;
  77. if($user->micropub_media_endpoint) {
  78. // Request the last file uploaded from the media endpoint
  79. $response = micropub_get($user->micropub_media_endpoint, ['q'=>'last'], $user->micropub_access_token);
  80. if(isset($response['data']['url'])) {
  81. $url = $response['data']['url'];
  82. }
  83. }
  84. $app->response()['Content-type'] = 'application/json';
  85. $app->response()->body(json_encode(array(
  86. 'url' => $url
  87. )));
  88. }
  89. });
  90. $app->get('/bookmark', function() use($app) {
  91. if($user=require_login($app)) {
  92. $params = $app->request()->params();
  93. $url = '';
  94. $name = '';
  95. $content = '';
  96. $tags = '';
  97. if(array_key_exists('url', $params))
  98. $url = $params['url'];
  99. if(array_key_exists('name', $params))
  100. $name = $params['name'];
  101. if(array_key_exists('content', $params))
  102. $content = $params['content'];
  103. render('new-bookmark', array(
  104. 'title' => 'New Bookmark',
  105. 'bookmark_url' => $url,
  106. 'bookmark_name' => $name,
  107. 'bookmark_content' => $content,
  108. 'bookmark_tags' => $tags,
  109. 'token' => generate_login_token(),
  110. 'syndication_targets' => json_decode($user->syndication_targets, true),
  111. 'user' => $user,
  112. 'authorizing' => false
  113. ));
  114. }
  115. });
  116. $app->get('/favorite', function() use($app) {
  117. if($user=require_login($app)) {
  118. $params = $app->request()->params();
  119. $like_of = '';
  120. if(array_key_exists('url', $params))
  121. $like_of = $params['url'];
  122. // Check if there was a login token in the query string and whether it has autosubmit=true
  123. $autosubmit = false;
  124. if(array_key_exists('token', $params)) {
  125. try {
  126. $data = JWT::decode($params['token'], Config::$jwtSecret, ['HS256']);
  127. if(isset($data->autosubmit) && $data->autosubmit) {
  128. // Only allow this token to be used for the user who created it
  129. if($data->user_id == $_SESSION['user_id']) {
  130. $autosubmit = true;
  131. }
  132. }
  133. } catch(Exception $e) {
  134. }
  135. }
  136. if(array_key_exists('edit', $params)) {
  137. $edit_data = get_micropub_source($user, $params['edit'], 'like-of');
  138. $url = $params['edit'];
  139. if(isset($edit_data['like-of'])) {
  140. $like_of = $edit_data['like-of'][0];
  141. }
  142. } else {
  143. $edit_data = false;
  144. $url = false;
  145. }
  146. render('new-favorite', array(
  147. 'title' => 'New Favorite',
  148. 'like_of' => $like_of,
  149. 'token' => generate_login_token(['autosubmit'=>true]),
  150. 'authorizing' => false,
  151. 'autosubmit' => $autosubmit,
  152. 'url' => $url
  153. ));
  154. }
  155. });
  156. $app->get('/event', function() use($app) {
  157. if($user=require_login($app)) {
  158. $params = $app->request()->params();
  159. render('event', array(
  160. 'title' => 'Event',
  161. 'authorizing' => false
  162. ));
  163. }
  164. });
  165. $app->get('/itinerary', function() use($app) {
  166. if($user=require_login($app)) {
  167. $params = $app->request()->params();
  168. render('new-itinerary', array(
  169. 'title' => 'Itinerary',
  170. 'authorizing' => false
  171. ));
  172. }
  173. });
  174. $app->get('/flight', function() use($app) {
  175. if($user=require_login($app)) {
  176. $params = $app->request()->params();
  177. render('new-flight', array(
  178. 'title' => 'Flight',
  179. 'authorizing' => false
  180. ));
  181. }
  182. });
  183. $app->post('/flight', function() use($app) {
  184. if($user=require_login($app)) {
  185. $params = $app->request()->params();
  186. $location = false;
  187. if($params['action'] == 'find') {
  188. } elseif($params['action'] == 'checkin') {
  189. $payload = [
  190. 'type' => ['h-entry'],
  191. 'properties' => [
  192. 'checkin' => [
  193. [
  194. 'type' => ['h-card'],
  195. 'properties' => [
  196. 'name' => [$params['flight']],
  197. 'url' => ['http://flightaware.com/live/flight/'.$params['flight']],
  198. ]
  199. ]
  200. ]
  201. ]
  202. ];
  203. $r = micropub_post_for_user($user, $payload, null, true);
  204. $location = $r['location'];
  205. if($location) {
  206. // Store the checkin in the database to enable the cron job tracking the flight
  207. $flight = ORM::for_table('flights')->create();
  208. $flight->user_id = $_SESSION['user_id'];
  209. $flight->date_created = date('Y-m-d H:i:s');
  210. $flight->active = 1;
  211. $flight->url = $location;
  212. $flight->flight = $params['flight'];
  213. $flight->save();
  214. }
  215. }
  216. $app->response()['Content-type'] = 'application/json';
  217. $app->response()->body(json_encode(array(
  218. 'result' => 'ok',
  219. 'location' => $location
  220. )));
  221. }
  222. });
  223. $app->get('/flight/:id/:flightID/route.json', function($id, $flightID) use($app) {
  224. $route = false;
  225. $flight = ORM::for_table('flights')->where('id', $id)->find_one();
  226. if($flight) {
  227. $lastPosition = json_decode($flight->lastposition, true);
  228. if($lastPosition['InFlightInfoResult']['faFlightID'] == $flightID) {
  229. // {"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[-122.638351,45.52217]},"properties":{"date":"2016-01-02T23:13:49Z","altitude":42.666666666667}}
  230. $route = [
  231. 'type' => 'FeatureCollection',
  232. 'features' => []
  233. ];
  234. $positions = json_decode($flight->positions, true);
  235. foreach($positions as $p) {
  236. $route['features'][] = [
  237. 'type' => 'Feature',
  238. 'geometry' => [
  239. 'type' => 'Point',
  240. 'coordinates' => [$p['lng'], $p['lat']]
  241. ],
  242. 'properties' => [
  243. 'date' => $p['date'],
  244. 'altitude' => $p['altitude'],
  245. 'heading' => $p['heading'],
  246. 'speed' => $p['speed']
  247. ]
  248. ];
  249. }
  250. }
  251. }
  252. $app->response()['Content-type'] = 'application/json';
  253. $app->response()->body(json_encode($route));
  254. });
  255. $app->get('/photo', function() use($app) {
  256. if($user=require_login($app)) {
  257. $params = $app->request()->params();
  258. render('photo', array(
  259. 'title' => 'New Photo',
  260. 'note_content' => '',
  261. 'authorizing' => false
  262. ));
  263. }
  264. });
  265. $app->get('/review', function() use($app) {
  266. if($user=require_login($app)) {
  267. $params = $app->request()->params();
  268. render('review', array(
  269. 'title' => 'Review',
  270. 'authorizing' => false
  271. ));
  272. }
  273. });
  274. $app->get('/repost', function() use($app) {
  275. if($user=require_login($app)) {
  276. $params = $app->request()->params();
  277. $repost_of = '';
  278. if(array_key_exists('url', $params))
  279. $repost_of = $params['url'];
  280. if(array_key_exists('edit', $params)) {
  281. $edit_data = get_micropub_source($user, $params['edit'], 'repost-of');
  282. $url = $params['edit'];
  283. if(isset($edit_data['repost-of'])) {
  284. $repost = $edit_data['repost-of'][0];
  285. if(is_string($edit_data['repost-of'][0])) {
  286. $repost_of = $repost;
  287. } elseif(is_array($repost)) {
  288. if(array_key_exists('type', $repost) && in_array('h-cite', $repost)) {
  289. if(array_key_exists('url', $repost['properties'])) {
  290. $repost_of = $repost['properties']['url'][0];
  291. }
  292. } else {
  293. // Error
  294. }
  295. } else {
  296. // Error: don't know what type of post this is
  297. }
  298. }
  299. } else {
  300. $edit_data = false;
  301. $url = false;
  302. }
  303. render('new-repost', array(
  304. 'title' => 'New Repost',
  305. 'repost_of' => $repost_of,
  306. 'token' => generate_login_token(),
  307. 'authorizing' => false,
  308. 'url' => $url,
  309. ));
  310. }
  311. });
  312. $app->post('/prefs', function() use($app) {
  313. if($user=require_login($app)) {
  314. $params = $app->request()->params();
  315. $user->location_enabled = $params['enabled'];
  316. $user->save();
  317. }
  318. $app->response()['Content-type'] = 'application/json';
  319. $app->response()->body(json_encode(array(
  320. 'result' => 'ok'
  321. )));
  322. });
  323. $app->post('/prefs/timezone', function() use($app) {
  324. // Called when the interface finds the user's location.
  325. // Look up the timezone for this location and store it as their default.
  326. $timezone = false;
  327. if($user=require_login($app)) {
  328. $params = $app->request()->params();
  329. $timezone = p3k\Timezone::timezone_for_location($params['latitude'], $params['longitude']);
  330. if($timezone) {
  331. $user->default_timezone = $timezone;
  332. $user->save();
  333. }
  334. }
  335. $app->response()['Content-type'] = 'application/json';
  336. $app->response()->body(json_encode(array(
  337. 'result' => 'ok',
  338. 'timezone' => $timezone,
  339. )));
  340. });
  341. $app->get('/add-to-home', function() use($app) {
  342. $params = $app->request()->params();
  343. header("Cache-Control: no-cache, must-revalidate");
  344. if(array_key_exists('token', $params) && !session('add-to-home-started')) {
  345. unset($_SESSION['add-to-home-started']);
  346. // Verify the token and sign the user in
  347. try {
  348. $data = JWT::decode($params['token'], Config::$jwtSecret, array('HS256'));
  349. $_SESSION['user_id'] = $data->user_id;
  350. $_SESSION['me'] = $data->me;
  351. $app->redirect('/new', 302);
  352. } catch(DomainException $e) {
  353. header('X-Error: DomainException');
  354. $app->redirect('/', 302);
  355. } catch(UnexpectedValueException $e) {
  356. header('X-Error: UnexpectedValueException');
  357. $app->redirect('/', 302);
  358. }
  359. } else {
  360. if($user=require_login($app)) {
  361. if(array_key_exists('start', $params)) {
  362. $_SESSION['add-to-home-started'] = true;
  363. $token = JWT::encode(array(
  364. 'user_id' => $_SESSION['user_id'],
  365. 'me' => $_SESSION['me'],
  366. 'created_at' => time()
  367. ), Config::$jwtSecret);
  368. $app->redirect('/add-to-home?token='.$token, 302);
  369. } else {
  370. unset($_SESSION['add-to-home-started']);
  371. render('add-to-home', array('title' => 'Quill'));
  372. }
  373. }
  374. }
  375. });
  376. $app->get('/email', function() use($app) {
  377. if($user=require_login($app)) {
  378. if(!$user->email_username) {
  379. $host = parse_url($user->url, PHP_URL_HOST);
  380. $user->email_username = $host . '.' . rand(100000,999999);
  381. $user->save();
  382. }
  383. render('email', array(
  384. 'title' => 'Post-by-Email',
  385. 'micropub_endpoint' => $user->micropub_endpoint,
  386. 'user' => $user
  387. ));
  388. }
  389. });
  390. $app->get('/settings', function() use($app) {
  391. if($user=require_login($app)) {
  392. render('settings', [
  393. 'title' => 'Settings',
  394. 'user' => $user,
  395. 'syndication_targets' => json_decode($user->syndication_targets, true),
  396. 'authorizing' => false
  397. ]);
  398. }
  399. });
  400. $app->post('/settings/save', function() use($app) {
  401. if($user=require_login($app)) {
  402. $params = $app->request()->params();
  403. if(array_key_exists('html_content', $params))
  404. $user->micropub_optin_html_content = $params['html_content'] ? 1 : 0;
  405. if(array_key_exists('slug_field', $params) && $params['slug_field'])
  406. $user->micropub_slug_field = $params['slug_field'];
  407. if(array_key_exists('syndicate_field', $params) && $params['syndicate_field']) {
  408. if(in_array($params['syndicate_field'], ['syndicate-to','mp-syndicate-to']))
  409. $user->micropub_syndicate_field = $params['syndicate_field'];
  410. }
  411. $user->save();
  412. $app->response()['Content-type'] = 'application/json';
  413. $app->response()->body(json_encode(array(
  414. 'result' => 'ok'
  415. )));
  416. }
  417. });
  418. $app->post('/settings/html-content', function() use($app) {
  419. if($user=require_login($app)) {
  420. $params = $app->request()->params();
  421. $user->micropub_optin_html_content = $params['html'] ? 1 : 0;
  422. $user->save();
  423. $app->response()['Content-type'] = 'application/json';
  424. $app->response()->body(json_encode(array(
  425. 'html' => $user->micropub_optin_html_content
  426. )));
  427. }
  428. });
  429. $app->get('/settings/html-content', function() use($app) {
  430. if($user=require_login($app)) {
  431. $app->response()['Content-type'] = 'application/json';
  432. $app->response()->body(json_encode(array(
  433. 'html' => $user->micropub_optin_html_content
  434. )));
  435. }
  436. });
  437. function create_favorite(&$user, $url) {
  438. $tweet_id = false;
  439. $twitter_syndication = false;
  440. // POSSE favorites to Twitter
  441. if($user->twitter_access_token && preg_match('/https?:\/\/(?:www\.)?twitter\.com\/[^\/]+\/status(?:es)?\/(\d+)/', $url, $match)) {
  442. $tweet_id = $match[1];
  443. $twitter = new TwitterOAuth(Config::$twitterClientID, Config::$twitterClientSecret,
  444. $user->twitter_access_token, $user->twitter_token_secret);
  445. $result = $twitter->post('favorites/create', array(
  446. 'id' => $tweet_id
  447. ));
  448. if(property_exists($result, 'id_str')) {
  449. $twitter_syndication = 'https://twitter.com/'.$user->twitter_username.'/status/'.$result->id_str;
  450. }
  451. }
  452. $micropub_request = array(
  453. 'like-of' => $url
  454. );
  455. if($twitter_syndication) {
  456. $micropub_request['syndication'] = $twitter_syndication;
  457. }
  458. $r = micropub_post_for_user($user, $micropub_request);
  459. return $r;
  460. }
  461. function edit_favorite(&$user, $post_url, $like_of) {
  462. $micropub_request = [
  463. 'action' => 'update',
  464. 'url' => $post_url,
  465. 'replace' => [
  466. 'like-of' => [$like_of]
  467. ]
  468. ];
  469. $r = micropub_post_for_user($user, $micropub_request, null, true);
  470. return $r;
  471. }
  472. function create_repost(&$user, $url) {
  473. $tweet_id = false;
  474. $twitter_syndication = false;
  475. if($user->twitter_access_token && preg_match('/https?:\/\/(?:www\.)?twitter\.com\/[^\/]+\/status(?:es)?\/(\d+)/', $url, $match)) {
  476. $tweet_id = $match[1];
  477. $twitter = new TwitterOAuth(Config::$twitterClientID, Config::$twitterClientSecret,
  478. $user->twitter_access_token, $user->twitter_token_secret);
  479. $result = $twitter->post('statuses/retweet/'.$tweet_id);
  480. if(property_exists($result, 'id_str')) {
  481. $twitter_syndication = 'https://twitter.com/'.$user->twitter_username.'/status/'.$result->id_str;
  482. }
  483. }
  484. $micropub_request = array(
  485. 'repost-of' => $url
  486. );
  487. if($twitter_syndication) {
  488. $micropub_request['syndication'] = $twitter_syndication;
  489. }
  490. $r = micropub_post_for_user($user, $micropub_request);
  491. return $r;
  492. }
  493. function edit_repost(&$user, $post_url, $repost_of) {
  494. $micropub_request = [
  495. 'action' => 'update',
  496. 'url' => $post_url,
  497. 'replace' => [
  498. 'repost-of' => [$repost_of]
  499. ]
  500. ];
  501. $r = micropub_post_for_user($user, $micropub_request, null, true);
  502. return $r;
  503. }
  504. $app->post('/favorite', function() use($app) {
  505. if($user=require_login($app)) {
  506. $params = $app->request()->params();
  507. $error = false;
  508. if(isset($params['edit']) && $params['edit']) {
  509. $r = edit_favorite($user, $params['edit'], $params['like_of']);
  510. if(isset($r['location']) && $r['location'])
  511. $location = $r['location'];
  512. elseif(in_array($r['code'], [200,201,204]))
  513. $location = $params['edit'];
  514. elseif(in_array($r['code'], [401,403])) {
  515. $location = false;
  516. $error = 'Your Micropub endpoint denied the request. Check that Quill is authorized to update posts.';
  517. } else {
  518. $location = false;
  519. $error = 'Your Micropub endpoint did not return a location header or a recognized response code';
  520. }
  521. } else {
  522. $r = create_favorite($user, $params['like_of']);
  523. $location = $r['location'];
  524. }
  525. $app->response()['Content-type'] = 'application/json';
  526. $app->response()->body(json_encode(array(
  527. 'location' => $location,
  528. 'error' => $r['error'],
  529. 'error_details' => $error,
  530. )));
  531. }
  532. });
  533. $app->post('/repost', function() use($app) {
  534. if($user=require_login($app)) {
  535. $params = $app->request()->params();
  536. $error = false;
  537. if(isset($params['edit']) && $params['edit']) {
  538. $r = edit_repost($user, $params['edit'], $params['repost_of']);
  539. if(isset($r['location']) && $r['location'])
  540. $location = $r['location'];
  541. elseif(in_array($r['code'], [200,201,204]))
  542. $location = $params['edit'];
  543. elseif(in_array($r['code'], [401,403])) {
  544. $location = false;
  545. $error = 'Your Micropub endpoint denied the request. Check that Quill is authorized to update posts.';
  546. } else {
  547. $location = false;
  548. $error = 'Your Micropub endpoint did not return a location header or a recognized response code';
  549. }
  550. } else {
  551. $r = create_repost($user, $params['repost_of']);
  552. $location = $r['location'];
  553. }
  554. $app->response()['Content-type'] = 'application/json';
  555. $app->response()->body(json_encode(array(
  556. 'location' => $location,
  557. 'error' => $r['error'],
  558. 'error_details' => $error,
  559. )));
  560. }
  561. });
  562. $app->get('/code', function() use($app) {
  563. if($user=require_login($app)) {
  564. $params = $app->request()->params();
  565. $edit_data = ['content'=>'','name'=>''];
  566. if(array_key_exists('edit', $params)) {
  567. $source = get_micropub_source($user, $params['edit'], ['content','name']);
  568. if(isset($source['content']) && is_array($source['content']) && isset($source['content'][0]))
  569. $edit_data['content'] = $source['content'][0];
  570. if(isset($source['name']) && is_array($source['name']) && isset($source['name'][0]))
  571. $edit_data['name'] = $source['name'][0];
  572. $url = $params['edit'];
  573. } else {
  574. $url = false;
  575. }
  576. $languages = [
  577. 'php' => ['php'],
  578. 'ruby' => ['rb'],
  579. 'python' => ['py'],
  580. 'perl' => ['pl'],
  581. 'javascript' => ['js'],
  582. 'html' => ['html','htm'],
  583. 'css' => ['css'],
  584. 'bash' => ['sh'],
  585. 'nginx' => ['conf'],
  586. 'apache' => [],
  587. 'text' => ['txt'],
  588. ];
  589. ksort($languages);
  590. $language_map = [];
  591. foreach($languages as $lang=>$exts) {
  592. foreach($exts as $ext)
  593. $language_map[$ext] = $lang;
  594. }
  595. render('new-code', array(
  596. 'title' => 'New Code Snippet',
  597. 'url' => $url,
  598. 'edit_data' => $edit_data,
  599. 'token' => generate_login_token(),
  600. 'languages' => $languages,
  601. 'language_map' => $language_map,
  602. 'my_hostname' => parse_url($user->url, PHP_URL_HOST),
  603. 'authorizing' => false,
  604. ));
  605. }
  606. });
  607. $app->post('/code', function() use($app) {
  608. if($user=require_login($app)) {
  609. $params = $app->request()->params();
  610. $error = false;
  611. if(isset($params['edit']) && $params['edit']) {
  612. $micropub_request = [
  613. 'action' => 'update',
  614. 'url' => $params['edit'],
  615. 'replace' => [
  616. 'content' => [$params['content']]
  617. ]
  618. ];
  619. if(isset($params['name']) && $params['name']) {
  620. $micropub_request['replace']['name'] = [$params['name']];
  621. }
  622. $r = micropub_post_for_user($user, $micropub_request, null, true);
  623. if(isset($r['location']) && $r['location'])
  624. $location = $r['location'];
  625. elseif(in_array($r['code'], [200,201,204]))
  626. $location = $params['edit'];
  627. elseif(in_array($r['code'], [401,403])) {
  628. $location = false;
  629. $error = 'Your Micropub endpoint denied the request. Check that Quill is authorized to update posts.';
  630. } else {
  631. $location = false;
  632. $error = 'Your Micropub endpoint did not return a location header or a recognized response code';
  633. }
  634. } else {
  635. $micropub_request = array(
  636. 'p3k-content-type' => 'code/' . $params['language'],
  637. 'content' => $params['content'],
  638. );
  639. if(isset($params['name']) && $params['name'])
  640. $micropub_request['name'] = $params['name'];
  641. $r = micropub_post_for_user($user, $micropub_request);
  642. $location = $r['location'];
  643. }
  644. $app->response()['Content-type'] = 'application/json';
  645. $app->response()->body(json_encode(array(
  646. 'location' => $location,
  647. 'error' => $r['error'],
  648. 'error_details' => $error,
  649. )));
  650. }
  651. });
  652. $app->get('/reply/preview', function() use($app) {
  653. if($user=require_login($app)) {
  654. $params = $app->request()->params();
  655. if(!isset($params['url']) || !$params['url']) {
  656. return '';
  657. }
  658. $reply_url = trim($params['url']);
  659. if(preg_match('/twtr\.io\/([0-9a-z]+)/i', $reply_url, $match)) {
  660. $twtr = 'https://twitter.com/_/status/' . sxg_to_num($match[1]);
  661. $ch = curl_init($twtr);
  662. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  663. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  664. curl_exec($ch);
  665. $expanded_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
  666. if($expanded_url) $reply_url = $expanded_url;
  667. }
  668. $entry = false;
  669. $xray_opts = [];
  670. if(preg_match('/twitter\.com\/(?:[^\/]+)\/statuse?s?\/(.+)/', $reply_url, $match)) {
  671. if($user->twitter_access_token) {
  672. $xray_opts['twitter_api_key'] = Config::$twitterClientID;
  673. $xray_opts['twitter_api_secret'] = Config::$twitterClientSecret;
  674. $xray_opts['twitter_access_token'] = $user->twitter_access_token;
  675. $xray_opts['twitter_access_token_secret'] = $user->twitter_token_secret;
  676. }
  677. }
  678. // Pass to X-Ray to see if it can expand the entry
  679. $xray = new p3k\XRay();
  680. $xray->http = new p3k\HTTP('Quill ('.Config::$base_url.')');
  681. $data = $xray->parse($reply_url, $xray_opts);
  682. if($data && isset($data['data'])) {
  683. if($data['data']['type'] == 'entry') {
  684. $entry = $data['data'];
  685. } elseif($data['data']['type'] == 'event') {
  686. $entry = $data['data'];
  687. $content = '';
  688. if(isset($entry['start']) && isset($entry['end'])) {
  689. $formatted = DateFormatter::format($entry['start'], $entry['end'], false);
  690. if($formatted)
  691. $content .= $formatted;
  692. else {
  693. $start = new DateTime($entry['start']);
  694. $end = new DateTime($entry['end']);
  695. if($start && $end)
  696. $content .= 'from '.$start->format('Y-m-d g:ia').' to '.$end->format('Y-m-d g:ia');
  697. }
  698. } elseif(isset($entry['start'])) {
  699. $formatted = DateFormatter::format($entry['start'], false, false);
  700. if($formatted)
  701. $content .= $formatted;
  702. else {
  703. $start = new DateTime($entry['start']);
  704. if($start)
  705. $content .= $start->format('Y-m-d g:ia');
  706. }
  707. }
  708. $entry['content']['text'] = $content;
  709. }
  710. // Create a nickname based on the author URL
  711. if($entry && array_key_exists('author', $entry)) {
  712. if($entry['author']['url']) {
  713. if(!isset($entry['author']['nickname']) || !$entry['author']['nickname'])
  714. $entry['author']['nickname'] = display_url($entry['author']['url']);
  715. }
  716. }
  717. }
  718. $mentions = [];
  719. if($entry) {
  720. if(array_key_exists('author', $entry) && isset($entry['author']['nickname'])) {
  721. // Find all @-names in the post, as well as the author name
  722. $mentions[] = strtolower($entry['author']['nickname']);
  723. }
  724. if(isset($entry['content']) && $entry['content'] && isset($entry['content']['text'])) {
  725. if(preg_match_all('/(^|(?<=[\s\/]))@([a-z0-9_]+([a-z0-9_\.]*)?)/i', $entry['content']['text'], $matches)) {
  726. foreach($matches[0] as $nick) {
  727. if(trim($nick,'@') != $user->twitter_username && trim($nick,'@') != display_url($user->url))
  728. $mentions[] = strtolower(trim($nick,'@'));
  729. }
  730. }
  731. }
  732. $mentions = array_values(array_unique($mentions));
  733. }
  734. $syndications = [];
  735. if($entry && isset($entry['syndication'])) {
  736. foreach($entry['syndication'] as $s) {
  737. $host = parse_url($s, PHP_URL_HOST);
  738. switch($host) {
  739. case 'twitter.com':
  740. case 'www.twitter.com':
  741. $icon = 'twitter.ico'; break;
  742. case 'facebook.com':
  743. case 'www.facebook.com':
  744. $icon = 'facebook.ico'; break;
  745. case 'github.com':
  746. case 'www.github.com':
  747. $icon = 'github.ico'; break;
  748. default:
  749. $icon = 'default.png'; break;
  750. }
  751. $syndications[] = [
  752. 'url' => $s,
  753. 'icon' => $icon
  754. ];
  755. }
  756. }
  757. $app->response()['Content-type'] = 'application/json';
  758. $app->response()->body(json_encode([
  759. 'canonical_reply_url' => $reply_url,
  760. 'entry' => $entry,
  761. 'mentions' => $mentions,
  762. 'syndications' => $syndications,
  763. ]));
  764. }
  765. });
  766. $app->get('/edit', function() use($app) {
  767. if($user=require_login($app)) {
  768. $params = $app->request()->params();
  769. if(!isset($params['url']) || !$params['url']) {
  770. $app->response()->body('no URL specified');
  771. }
  772. // Query the micropub endpoint for the source properties
  773. $source = micropub_get($user->micropub_endpoint, [
  774. 'q' => 'source',
  775. 'url' => $params['url']
  776. ], $user->micropub_access_token);
  777. $data = $source['data'];
  778. if(array_key_exists('error', $data)) {
  779. render('edit/error', [
  780. 'title' => 'Error',
  781. 'summary' => 'Your Micropub endpoint returned an error:',
  782. 'error' => $data['error'],
  783. 'error_description' => $data['error_description']
  784. ]);
  785. return;
  786. }
  787. if(!array_key_exists('properties', $data) || !array_key_exists('type', $data)) {
  788. render('edit/error', [
  789. 'title' => 'Error',
  790. 'summary' => '',
  791. 'error' => 'Invalid Response',
  792. 'error_description' => 'Your endpoint did not return "properties" and "type" in the response.'
  793. ]);
  794. return;
  795. }
  796. // Start checking for content types
  797. $type = $data['type'][0];
  798. $error = false;
  799. $url = false;
  800. if($type == 'h-review') {
  801. $url = '/review';
  802. } elseif($type == 'h-event') {
  803. $url = '/event';
  804. } elseif($type != 'h-entry') {
  805. $error = 'This type of post is not supported by any of Quill\'s editing interfaces. Type: '.$type;
  806. } else {
  807. if(array_key_exists('bookmark-of', $data['properties'])) {
  808. $url = '/bookmark';
  809. } elseif(array_key_exists('like-of', $data['properties'])) {
  810. $url = '/favorite';
  811. } elseif(array_key_exists('repost-of', $data['properties'])) {
  812. $url = '/repost';
  813. }
  814. }
  815. if($error) {
  816. render('edit/error', [
  817. 'title' => 'Error',
  818. 'summary' => '',
  819. 'error' => 'There was a problem!',
  820. 'error_description' => $error
  821. ]);
  822. return;
  823. }
  824. // Until all interfaces are complete, show an error here for unsupported ones
  825. if(!in_array($url, ['/favorite','/repost','/code'])) {
  826. render('edit/error', [
  827. 'title' => 'Not Yet Supported',
  828. 'summary' => '',
  829. 'error' => 'Not Yet Supported',
  830. 'error_description' => 'Editing is not yet supported for this type of post.'
  831. ]);
  832. return;
  833. }
  834. $app->redirect($url . '?edit=' . $params['url'], 302);
  835. }
  836. });
  837. $app->get('/airport-info', function() use($app){
  838. if($user=require_login($app)) {
  839. $params = $app->request()->params();
  840. if(!isset($params['code'])) return;
  841. $ch = curl_init('https://atlas.p3k.io/api/timezone?airport='.urlencode($params['code']));
  842. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  843. $data = json_decode(curl_exec($ch), true);
  844. if(!$data)
  845. $response = ['error' => 'unknown'];
  846. else {
  847. $response = $data;
  848. }
  849. $app->response()['Content-type'] = 'application/json';
  850. $app->response()->body(json_encode($response));
  851. }
  852. });