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.

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