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.

986 lines
29 KiB

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