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.

1147 lines
34 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. if(array_key_exists('weight_unit', $params) && $params['weight_unit'])
  355. $user->weight_unit = $params['weight_unit'];
  356. $user->save();
  357. $app->response()['Content-type'] = 'application/json';
  358. $app->response()->body(json_encode(array(
  359. 'result' => 'ok'
  360. )));
  361. }
  362. });
  363. $app->post('/settings/html-content', function() use($app) {
  364. if($user=require_login($app)) {
  365. $params = $app->request()->params();
  366. $user->micropub_optin_html_content = $params['html'] ? 1 : 0;
  367. $user->save();
  368. $app->response()['Content-type'] = 'application/json';
  369. $app->response()->body(json_encode(array(
  370. 'html' => $user->micropub_optin_html_content
  371. )));
  372. }
  373. });
  374. $app->get('/settings/html-content', function() use($app) {
  375. if($user=require_login($app)) {
  376. $app->response()['Content-type'] = 'application/json';
  377. $app->response()->body(json_encode(array(
  378. 'html' => $user->micropub_optin_html_content
  379. )));
  380. }
  381. });
  382. $app->post('/twitter/preview', function() use($app) {
  383. if($user=require_login($app)) {
  384. $params = $app->request()->params();
  385. if($user->twitter_access_token) {
  386. $xray_opts['twitter_api_key'] = Config::$twitterClientID;
  387. $xray_opts['twitter_api_secret'] = Config::$twitterClientSecret;
  388. $xray_opts['twitter_access_token'] = $user->twitter_access_token;
  389. $xray_opts['twitter_access_token_secret'] = $user->twitter_token_secret;
  390. }
  391. $tweet_url = $params['tweet_url'];
  392. // Pass to X-Ray to download all the twitter data in a useful format
  393. $xray = new p3k\XRay();
  394. $xray->http = new p3k\HTTP('Quill ('.Config::$base_url.')');
  395. $data = $xray->parse($tweet_url, $xray_opts);
  396. $postdata = tweet_to_micropub_request($data['data']);
  397. $response = [
  398. 'json' => json_encode($postdata, JSON_PRETTY_PRINT+JSON_UNESCAPED_SLASHES)
  399. ];
  400. $app->response()['Content-type'] = 'application/json';
  401. $app->response()->body(json_encode($response));
  402. }
  403. });
  404. $app->post('/twitter', function() use($app) {
  405. if($user=require_login($app)) {
  406. $params = $app->request()->params();
  407. if($user->twitter_access_token) {
  408. $xray_opts['twitter_api_key'] = Config::$twitterClientID;
  409. $xray_opts['twitter_api_secret'] = Config::$twitterClientSecret;
  410. $xray_opts['twitter_access_token'] = $user->twitter_access_token;
  411. $xray_opts['twitter_access_token_secret'] = $user->twitter_token_secret;
  412. }
  413. $tweet_url = $params['tweet_url'];
  414. // Pass to X-Ray to download all the twitter data in a useful format
  415. $xray = new p3k\XRay();
  416. $xray->http = new p3k\HTTP('Quill ('.Config::$base_url.')');
  417. $data = $xray->parse($tweet_url, $xray_opts);
  418. $location = null;
  419. if(isset($data['data']) && $data['data']['type'] == 'entry') {
  420. $tweet = $data['data'];
  421. $postdata = tweet_to_micropub_request($tweet);
  422. $r = micropub_post_for_user($user, $postdata, null, true);
  423. $app->response()['Content-type'] = 'application/json';
  424. $app->response()->body(json_encode([
  425. 'location' => (isset($r['location']) && $r['location'] ? Mf2\resolveUrl($user->micropub_endpoint, $r['location']) : null),
  426. 'error' => $r['error'],
  427. 'response' => $r['response']
  428. ]));
  429. } else {
  430. $app->response()['Content-type'] = 'application/json';
  431. $app->response()->body(json_encode([
  432. 'location' => null,
  433. 'error' => 'Error fetching tweet',
  434. ]));
  435. }
  436. }
  437. });
  438. function tweet_to_micropub_request($tweet) {
  439. // Convert to a micropub post
  440. $postdata = [
  441. 'type' => ['h-entry'],
  442. 'properties' => [
  443. 'content' => [$tweet['content']['text']],
  444. 'published' => [$tweet['published']],
  445. 'syndication' => [$tweet['url']],
  446. ]
  447. ];
  448. if(isset($tweet['in-reply-to']))
  449. $postdata['properties']['in-reply-to'] = $tweet['in-reply-to'];
  450. if(isset($tweet['category']))
  451. $postdata['properties']['category'] = $tweet['category'];
  452. if(isset($tweet['photo']))
  453. $postdata['properties']['photo'] = $tweet['photo'];
  454. if(isset($tweet['video']))
  455. $postdata['properties']['video'] = $tweet['video'];
  456. return $postdata;
  457. }
  458. function create_favorite(&$user, $url) {
  459. $tweet_id = false;
  460. $twitter_syndication = false;
  461. // POSSE favorites to Twitter
  462. if($user->twitter_access_token && preg_match('/https?:\/\/(?:www\.)?twitter\.com\/[^\/]+\/status(?:es)?\/(\d+)/', $url, $match)) {
  463. $tweet_id = $match[1];
  464. $twitter = new TwitterOAuth(Config::$twitterClientID, Config::$twitterClientSecret,
  465. $user->twitter_access_token, $user->twitter_token_secret);
  466. $result = $twitter->post('favorites/create', array(
  467. 'id' => $tweet_id
  468. ));
  469. if(property_exists($result, 'id_str')) {
  470. $twitter_syndication = 'https://twitter.com/'.$user->twitter_username.'/status/'.$result->id_str;
  471. }
  472. }
  473. $micropub_request = array(
  474. 'like-of' => $url
  475. );
  476. if($twitter_syndication) {
  477. $micropub_request['syndication'] = $twitter_syndication;
  478. }
  479. $r = micropub_post_for_user($user, $micropub_request);
  480. return $r;
  481. }
  482. function edit_favorite(&$user, $post_url, $like_of) {
  483. $micropub_request = [
  484. 'action' => 'update',
  485. 'url' => $post_url,
  486. 'replace' => [
  487. 'like-of' => [$like_of]
  488. ]
  489. ];
  490. $r = micropub_post_for_user($user, $micropub_request, null, true);
  491. return $r;
  492. }
  493. function create_repost(&$user, $url) {
  494. $tweet_id = false;
  495. $twitter_syndication = false;
  496. if($user->twitter_access_token && preg_match('/https?:\/\/(?:www\.)?twitter\.com\/[^\/]+\/status(?:es)?\/(\d+)/', $url, $match)) {
  497. $tweet_id = $match[1];
  498. $twitter = new TwitterOAuth(Config::$twitterClientID, Config::$twitterClientSecret,
  499. $user->twitter_access_token, $user->twitter_token_secret);
  500. $result = $twitter->post('statuses/retweet/'.$tweet_id);
  501. if(property_exists($result, 'id_str')) {
  502. $twitter_syndication = 'https://twitter.com/'.$user->twitter_username.'/status/'.$result->id_str;
  503. }
  504. }
  505. $micropub_request = array(
  506. 'repost-of' => $url
  507. );
  508. if($twitter_syndication) {
  509. $micropub_request['syndication'] = $twitter_syndication;
  510. }
  511. $r = micropub_post_for_user($user, $micropub_request);
  512. return $r;
  513. }
  514. function edit_repost(&$user, $post_url, $repost_of) {
  515. $micropub_request = [
  516. 'action' => 'update',
  517. 'url' => $post_url,
  518. 'replace' => [
  519. 'repost-of' => [$repost_of]
  520. ]
  521. ];
  522. $r = micropub_post_for_user($user, $micropub_request, null, true);
  523. return $r;
  524. }
  525. $app->post('/favorite', function() use($app) {
  526. if($user=require_login($app)) {
  527. $params = $app->request()->params();
  528. $error = false;
  529. if(isset($params['edit']) && $params['edit']) {
  530. $r = edit_favorite($user, $params['edit'], $params['like_of']);
  531. if(isset($r['location']) && $r['location'])
  532. $location = $r['location'];
  533. elseif(in_array($r['code'], [200,201,204]))
  534. $location = $params['edit'];
  535. elseif(in_array($r['code'], [401,403])) {
  536. $location = false;
  537. $error = 'Your Micropub endpoint denied the request. Check that Quill is authorized to update posts.';
  538. } else {
  539. $location = false;
  540. $error = 'Your Micropub endpoint did not return a location header or a recognized response code';
  541. }
  542. } else {
  543. $r = create_favorite($user, $params['like_of']);
  544. $location = $r['location'];
  545. }
  546. $app->response()['Content-type'] = 'application/json';
  547. $app->response()->body(json_encode(array(
  548. 'location' => $location,
  549. 'error' => $r['error'],
  550. 'error_details' => $error,
  551. )));
  552. }
  553. });
  554. $app->post('/repost', function() use($app) {
  555. if($user=require_login($app)) {
  556. $params = $app->request()->params();
  557. $error = false;
  558. if(isset($params['edit']) && $params['edit']) {
  559. $r = edit_repost($user, $params['edit'], $params['repost_of']);
  560. if(isset($r['location']) && $r['location'])
  561. $location = $r['location'];
  562. elseif(in_array($r['code'], [200,201,204]))
  563. $location = $params['edit'];
  564. elseif(in_array($r['code'], [401,403])) {
  565. $location = false;
  566. $error = 'Your Micropub endpoint denied the request. Check that Quill is authorized to update posts.';
  567. } else {
  568. $location = false;
  569. $error = 'Your Micropub endpoint did not return a location header or a recognized response code';
  570. }
  571. } else {
  572. $r = create_repost($user, $params['repost_of']);
  573. $location = $r['location'];
  574. }
  575. $app->response()['Content-type'] = 'application/json';
  576. $app->response()->body(json_encode(array(
  577. 'location' => $location,
  578. 'error' => $r['error'],
  579. 'error_details' => $error,
  580. )));
  581. }
  582. });
  583. $app->get('/code', function() use($app) {
  584. if($user=require_login($app)) {
  585. $params = $app->request()->params();
  586. $edit_data = ['content'=>'','name'=>''];
  587. if(array_key_exists('edit', $params)) {
  588. $source = get_micropub_source($user, $params['edit'], ['content','name']);
  589. if(isset($source['content']) && is_array($source['content']) && isset($source['content'][0]))
  590. $edit_data['content'] = $source['content'][0];
  591. if(isset($source['name']) && is_array($source['name']) && isset($source['name'][0]))
  592. $edit_data['name'] = $source['name'][0];
  593. $url = $params['edit'];
  594. } else {
  595. $url = false;
  596. }
  597. $languages = [
  598. 'php' => ['php'],
  599. 'ruby' => ['rb'],
  600. 'python' => ['py'],
  601. 'perl' => ['pl'],
  602. 'javascript' => ['js'],
  603. 'html' => ['html','htm'],
  604. 'css' => ['css'],
  605. 'bash' => ['sh'],
  606. 'nginx' => ['conf'],
  607. 'apache' => [],
  608. 'text' => ['txt'],
  609. ];
  610. ksort($languages);
  611. $language_map = [];
  612. foreach($languages as $lang=>$exts) {
  613. foreach($exts as $ext)
  614. $language_map[$ext] = $lang;
  615. }
  616. render('new-code', array(
  617. 'title' => 'New Code Snippet',
  618. 'url' => $url,
  619. 'edit_data' => $edit_data,
  620. 'token' => generate_login_token(),
  621. 'languages' => $languages,
  622. 'language_map' => $language_map,
  623. 'my_hostname' => parse_url($user->url, PHP_URL_HOST),
  624. 'authorizing' => false,
  625. ));
  626. }
  627. });
  628. $app->post('/code', function() use($app) {
  629. if($user=require_login($app)) {
  630. $params = $app->request()->params();
  631. $error = false;
  632. if(isset($params['edit']) && $params['edit']) {
  633. $micropub_request = [
  634. 'action' => 'update',
  635. 'url' => $params['edit'],
  636. 'replace' => [
  637. 'content' => [$params['content']]
  638. ]
  639. ];
  640. if(isset($params['name']) && $params['name']) {
  641. $micropub_request['replace']['name'] = [$params['name']];
  642. }
  643. $r = micropub_post_for_user($user, $micropub_request, null, true);
  644. if(isset($r['location']) && $r['location'])
  645. $location = $r['location'];
  646. elseif(in_array($r['code'], [200,201,204]))
  647. $location = $params['edit'];
  648. elseif(in_array($r['code'], [401,403])) {
  649. $location = false;
  650. $error = 'Your Micropub endpoint denied the request. Check that Quill is authorized to update posts.';
  651. } else {
  652. $location = false;
  653. $error = 'Your Micropub endpoint did not return a location header or a recognized response code';
  654. }
  655. } else {
  656. $micropub_request = array(
  657. 'p3k-content-type' => 'code/' . $params['language'],
  658. 'content' => $params['content'],
  659. );
  660. if(isset($params['name']) && $params['name'])
  661. $micropub_request['name'] = $params['name'];
  662. $r = micropub_post_for_user($user, $micropub_request);
  663. $location = $r['location'];
  664. }
  665. $app->response()['Content-type'] = 'application/json';
  666. $app->response()->body(json_encode(array(
  667. 'location' => $location,
  668. 'error' => $r['error'],
  669. 'error_details' => $error,
  670. )));
  671. }
  672. });
  673. $app->get('/reply/preview', function() use($app) {
  674. if($user=require_login($app)) {
  675. $params = $app->request()->params();
  676. if(!isset($params['url']) || !$params['url']) {
  677. return '';
  678. }
  679. $reply_url = trim($params['url']);
  680. if(preg_match('/twtr\.io\/([0-9a-z]+)/i', $reply_url, $match)) {
  681. $twtr = 'https://twitter.com/_/status/' . sxg_to_num($match[1]);
  682. $ch = curl_init($twtr);
  683. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  684. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  685. curl_exec($ch);
  686. $expanded_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
  687. if($expanded_url) $reply_url = $expanded_url;
  688. }
  689. $entry = false;
  690. $xray_opts = [];
  691. if(preg_match('/twitter\.com\/(?:[^\/]+)\/statuse?s?\/(.+)/', $reply_url, $match)) {
  692. if($user->twitter_access_token) {
  693. $xray_opts['twitter_api_key'] = Config::$twitterClientID;
  694. $xray_opts['twitter_api_secret'] = Config::$twitterClientSecret;
  695. $xray_opts['twitter_access_token'] = $user->twitter_access_token;
  696. $xray_opts['twitter_access_token_secret'] = $user->twitter_token_secret;
  697. }
  698. }
  699. // Pass to X-Ray to see if it can expand the entry
  700. $xray = new p3k\XRay();
  701. $xray->http = new p3k\HTTP('Quill ('.Config::$base_url.')');
  702. $data = $xray->parse($reply_url, $xray_opts);
  703. if($data && isset($data['data'])) {
  704. if($data['data']['type'] == 'entry') {
  705. $entry = $data['data'];
  706. } elseif($data['data']['type'] == 'event') {
  707. $entry = $data['data'];
  708. $content = '';
  709. if(isset($entry['start']) && isset($entry['end'])) {
  710. $formatted = DateFormatter::format($entry['start'], $entry['end'], false);
  711. if($formatted)
  712. $content .= $formatted;
  713. else {
  714. $start = new DateTime($entry['start']);
  715. $end = new DateTime($entry['end']);
  716. if($start && $end)
  717. $content .= 'from '.$start->format('Y-m-d g:ia').' to '.$end->format('Y-m-d g:ia');
  718. }
  719. } elseif(isset($entry['start'])) {
  720. $formatted = DateFormatter::format($entry['start'], false, false);
  721. if($formatted)
  722. $content .= $formatted;
  723. else {
  724. $start = new DateTime($entry['start']);
  725. if($start)
  726. $content .= $start->format('Y-m-d g:ia');
  727. }
  728. }
  729. $entry['content']['text'] = $content;
  730. }
  731. // Create a nickname based on the author URL
  732. if($entry && array_key_exists('author', $entry)) {
  733. if($entry['author']['url']) {
  734. if(!isset($entry['author']['nickname']) || !$entry['author']['nickname'])
  735. $entry['author']['nickname'] = display_url($entry['author']['url']);
  736. }
  737. }
  738. }
  739. $mentions = [];
  740. if($entry) {
  741. if(array_key_exists('author', $entry) && isset($entry['author']['nickname'])) {
  742. // Find all @-names in the post, as well as the author name
  743. $mentions[] = strtolower($entry['author']['nickname']);
  744. }
  745. if(isset($entry['content']) && $entry['content'] && isset($entry['content']['text'])) {
  746. if(preg_match_all('/(^|(?<=[\s\/]))@([a-z0-9_]+([a-z0-9_\.]*)?)/i', $entry['content']['text'], $matches)) {
  747. foreach($matches[0] as $nick) {
  748. if(trim($nick,'@') != $user->twitter_username && trim($nick,'@') != display_url($user->url))
  749. $mentions[] = strtolower(trim($nick,'@'));
  750. }
  751. }
  752. }
  753. $mentions = array_values(array_unique($mentions));
  754. }
  755. $syndications = [];
  756. if($entry && isset($entry['syndication'])) {
  757. foreach($entry['syndication'] as $s) {
  758. $host = parse_url($s, PHP_URL_HOST);
  759. switch($host) {
  760. case 'twitter.com':
  761. case 'www.twitter.com':
  762. $icon = 'twitter.ico'; break;
  763. case 'facebook.com':
  764. case 'www.facebook.com':
  765. $icon = 'facebook.ico'; break;
  766. case 'github.com':
  767. case 'www.github.com':
  768. $icon = 'github.ico'; break;
  769. default:
  770. $icon = 'default.png'; break;
  771. }
  772. $syndications[] = [
  773. 'url' => $s,
  774. 'icon' => $icon
  775. ];
  776. }
  777. }
  778. $app->response()['Content-type'] = 'application/json';
  779. $app->response()->body(json_encode([
  780. 'canonical_reply_url' => $reply_url,
  781. 'entry' => $entry,
  782. 'mentions' => $mentions,
  783. 'syndications' => $syndications,
  784. ]));
  785. }
  786. });
  787. $app->get('/edit', function() use($app) {
  788. if($user=require_login($app)) {
  789. $params = $app->request()->params();
  790. if(!isset($params['url']) || !$params['url']) {
  791. $app->response()->body('no URL specified');
  792. }
  793. // Query the micropub endpoint for the source properties
  794. $source = micropub_get($user->micropub_endpoint, [
  795. 'q' => 'source',
  796. 'url' => $params['url']
  797. ], $user->micropub_access_token);
  798. $data = $source['data'];
  799. if(array_key_exists('error', $data)) {
  800. render('edit/error', [
  801. 'title' => 'Error',
  802. 'summary' => 'Your Micropub endpoint returned an error:',
  803. 'error' => $data['error'],
  804. 'error_description' => $data['error_description']
  805. ]);
  806. return;
  807. }
  808. if(!array_key_exists('properties', $data) || !array_key_exists('type', $data)) {
  809. render('edit/error', [
  810. 'title' => 'Error',
  811. 'summary' => '',
  812. 'error' => 'Invalid Response',
  813. 'error_description' => 'Your endpoint did not return "properties" and "type" in the response.'
  814. ]);
  815. return;
  816. }
  817. // Start checking for content types
  818. $type = $data['type'][0];
  819. $error = false;
  820. $url = false;
  821. if($type == 'h-review') {
  822. $url = '/review';
  823. } elseif($type == 'h-event') {
  824. $url = '/event';
  825. } elseif($type != 'h-entry') {
  826. $error = 'This type of post is not supported by any of Quill\'s editing interfaces. Type: '.$type;
  827. } else {
  828. if(array_key_exists('bookmark-of', $data['properties'])) {
  829. $url = '/bookmark';
  830. } elseif(array_key_exists('like-of', $data['properties'])) {
  831. $url = '/favorite';
  832. } elseif(array_key_exists('repost-of', $data['properties'])) {
  833. $url = '/repost';
  834. }
  835. }
  836. if($error) {
  837. render('edit/error', [
  838. 'title' => 'Error',
  839. 'summary' => '',
  840. 'error' => 'There was a problem!',
  841. 'error_description' => $error
  842. ]);
  843. return;
  844. }
  845. // Until all interfaces are complete, show an error here for unsupported ones
  846. if(!in_array($url, ['/favorite','/repost','/code'])) {
  847. render('edit/error', [
  848. 'title' => 'Not Yet Supported',
  849. 'summary' => '',
  850. 'error' => 'Not Yet Supported',
  851. 'error_description' => 'Editing is not yet supported for this type of post.'
  852. ]);
  853. return;
  854. }
  855. $app->redirect($url . '?edit=' . $params['url'], 302);
  856. }
  857. });
  858. $app->get('/airport-info', function() use($app){
  859. if($user=require_login($app)) {
  860. $params = $app->request()->params();
  861. if(!isset($params['code'])) return;
  862. $ch = curl_init('https://atlas.p3k.io/api/timezone?airport='.urlencode($params['code']));
  863. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  864. $data = json_decode(curl_exec($ch), true);
  865. if(!$data)
  866. $response = ['error' => 'unknown'];
  867. else {
  868. $response = $data;
  869. }
  870. $app->response()['Content-type'] = 'application/json';
  871. $app->response()->body(json_encode($response));
  872. }
  873. });
  874. $app->get('/map-img', function() use($app) {
  875. $params = $app->request()->params();
  876. $app->response()['Content-type'] = 'image/png';
  877. $params = [
  878. 'marker[]' => 'lat:'.$params['lat'].';lng:'.$params['lng'].';icon:small-blue-cutout',
  879. 'basemap' => 'custom',
  880. 'width' => $params['w'],
  881. 'height' => $params['h'],
  882. 'zoom' => $params['z'],
  883. 'attribution' => 'mapbox',
  884. 'tileurl' => Config::$mapTileURL,
  885. 'token' => Config::$atlasToken,
  886. ];
  887. $ch = curl_init('https://atlas.p3k.io/map/img');
  888. curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
  889. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
  890. curl_exec($ch);
  891. });
  892. function create_weight(&$user, $weight_num, $weight_unit, $published) {
  893. $micropub_request = array(
  894. 'type' => ['h-entry'],
  895. 'properties' => [
  896. 'weight' => [[
  897. 'type' => ['h-measure'],
  898. 'properties' => [
  899. 'num' => [$weight_num],
  900. 'unit' => [$weight_unit]
  901. ]
  902. ]]
  903. ]
  904. );
  905. try {
  906. $date = new DateTime($published);
  907. $micropub_request['properties']['published'] = [$date->format('c')];
  908. } catch(Exception $e) {
  909. }
  910. $r = micropub_post_for_user($user, $micropub_request, null, true);
  911. return $r;
  912. }
  913. $app->get('/weight', function() use($app){
  914. if($user=require_login($app)) {
  915. render('new-weight', array(
  916. 'title' => 'New Weight',
  917. 'unit' => $user->weight_unit
  918. ));
  919. }
  920. });
  921. $app->post('/weight', function() use($app) {
  922. if($user=require_login($app)) {
  923. $params = $app->request()->params();
  924. $r = create_weight($user, $params['weight_num'], $user->weight_unit, $params['published']);
  925. $location = $r['location'];
  926. $app->response()['Content-type'] = 'application/json';
  927. $app->response()->body(json_encode(array(
  928. 'location' => $location,
  929. 'error' => $r['error']
  930. )));
  931. }
  932. });
  933. function create_exercise(&$user, $activity, $minutes, $heartrate, $published) {
  934. $micropub_request = array(
  935. 'type' => ['h-entry'],
  936. 'properties' => [
  937. 'workout' => [[
  938. 'type' => ['h-workout'],
  939. 'properties' => [
  940. 'activity' => [$activity],
  941. 'duration' => [[
  942. 'type' => ['h-measure'],
  943. 'properties' => [
  944. 'num' => [($minutes*60)],
  945. 'unit' => ['second']
  946. ],
  947. ]],
  948. 'heartrate' => [[
  949. 'type' => 'h-measure',
  950. 'properties' => [
  951. 'num' => [$heartrate],
  952. 'unit' => ['bpm'],
  953. ]
  954. ]]
  955. ]
  956. ]]
  957. ]
  958. );
  959. try {
  960. $date = new DateTime($published);
  961. $micropub_request['properties']['published'] = [$date->format('c')];
  962. } catch(Exception $e) {
  963. }
  964. $r = micropub_post_for_user($user, $micropub_request, null, true);
  965. return $r;
  966. }
  967. $app->get('/exercise', function() use($app){
  968. if($user=require_login($app)) {
  969. render('new-exercise', array(
  970. 'title' => 'New Exercise',
  971. ));
  972. }
  973. });
  974. $app->post('/exercise', function() use($app) {
  975. if($user=require_login($app)) {
  976. $params = $app->request()->params();
  977. $r = create_exercise($user, $params['activity'], $params['minutes'], $params['heartrate'], $params['published']);
  978. $location = $r['location'];
  979. $app->response()['Content-type'] = 'application/json';
  980. $app->response()->body(json_encode(array(
  981. 'location' => $location,
  982. 'error' => $r['error']
  983. )));
  984. }
  985. });