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.

732 lines
21 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
7 years ago
9 years ago
9 years ago
9 years ago
9 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. ));
  48. }
  49. });
  50. $app->get('/new', function() use($app) {
  51. if($user=require_login($app)) {
  52. $params = $app->request()->params();
  53. $entry = false;
  54. $in_reply_to = '';
  55. if(array_key_exists('reply', $params))
  56. $in_reply_to = $params['reply'];
  57. $test_response = '';
  58. if($user->last_micropub_response) {
  59. try {
  60. if(@json_decode($user->last_micropub_response)) {
  61. $d = json_decode($user->last_micropub_response);
  62. $test_response = $d->response;
  63. }
  64. } catch(Exception $e) {
  65. }
  66. }
  67. render('new-post', array(
  68. 'title' => 'New Post',
  69. 'in_reply_to' => $in_reply_to,
  70. 'micropub_endpoint' => $user->micropub_endpoint,
  71. 'media_endpoint' => $user->micropub_media_endpoint,
  72. 'micropub_scope' => $user->micropub_scope,
  73. 'micropub_access_token' => $user->micropub_access_token,
  74. 'response_date' => $user->last_micropub_response_date,
  75. 'syndication_targets' => json_decode($user->syndication_targets, true),
  76. 'test_response' => $test_response,
  77. 'location_enabled' => $user->location_enabled,
  78. 'user' => $user,
  79. 'authorizing' => false
  80. ));
  81. }
  82. });
  83. $app->get('/bookmark', function() use($app) {
  84. if($user=require_login($app)) {
  85. $params = $app->request()->params();
  86. $url = '';
  87. $name = '';
  88. $content = '';
  89. $tags = '';
  90. if(array_key_exists('url', $params))
  91. $url = $params['url'];
  92. if(array_key_exists('name', $params))
  93. $name = $params['name'];
  94. if(array_key_exists('content', $params))
  95. $content = $params['content'];
  96. render('new-bookmark', array(
  97. 'title' => 'New Bookmark',
  98. 'bookmark_url' => $url,
  99. 'bookmark_name' => $name,
  100. 'bookmark_content' => $content,
  101. 'bookmark_tags' => $tags,
  102. 'token' => generate_login_token(),
  103. 'syndication_targets' => json_decode($user->syndication_targets, true),
  104. 'user' => $user,
  105. 'authorizing' => false
  106. ));
  107. }
  108. });
  109. $app->get('/favorite', function() use($app) {
  110. if($user=require_login($app)) {
  111. $params = $app->request()->params();
  112. $like_of = '';
  113. if(array_key_exists('url', $params))
  114. $like_of = $params['url'];
  115. // Check if there was a login token in the query string and whether it has autosubmit=true
  116. $autosubmit = false;
  117. if(array_key_exists('token', $params)) {
  118. try {
  119. $data = JWT::decode($params['token'], Config::$jwtSecret, ['HS256']);
  120. if(isset($data->autosubmit) && $data->autosubmit) {
  121. // Only allow this token to be used for the user who created it
  122. if($data->user_id == $_SESSION['user_id']) {
  123. $autosubmit = true;
  124. }
  125. }
  126. } catch(Exception $e) {
  127. }
  128. }
  129. if(array_key_exists('edit', $params)) {
  130. $edit_data = get_micropub_source($user, $params['edit'], 'like-of');
  131. $url = $params['edit'];
  132. if(isset($edit_data['like-of'])) {
  133. $like_of = $edit_data['like-of'][0];
  134. }
  135. } else {
  136. $edit_data = false;
  137. $url = false;
  138. }
  139. render('new-favorite', array(
  140. 'title' => 'New Favorite',
  141. 'like_of' => $like_of,
  142. 'token' => generate_login_token(['autosubmit'=>true]),
  143. 'authorizing' => false,
  144. 'autosubmit' => $autosubmit,
  145. 'url' => $url
  146. ));
  147. }
  148. });
  149. $app->get('/event', function() use($app) {
  150. if($user=require_login($app)) {
  151. $params = $app->request()->params();
  152. render('event', array(
  153. 'title' => 'Event',
  154. 'authorizing' => false
  155. ));
  156. }
  157. });
  158. $app->get('/itinerary', function() use($app) {
  159. if($user=require_login($app)) {
  160. $params = $app->request()->params();
  161. render('new-itinerary', array(
  162. 'title' => 'Itinerary',
  163. 'authorizing' => false
  164. ));
  165. }
  166. });
  167. $app->get('/photo', function() use($app) {
  168. if($user=require_login($app)) {
  169. $params = $app->request()->params();
  170. render('photo', array(
  171. 'title' => 'New Photo',
  172. 'note_content' => '',
  173. 'authorizing' => false
  174. ));
  175. }
  176. });
  177. $app->get('/review', function() use($app) {
  178. if($user=require_login($app)) {
  179. $params = $app->request()->params();
  180. render('review', array(
  181. 'title' => 'Review',
  182. 'authorizing' => false
  183. ));
  184. }
  185. });
  186. $app->get('/repost', function() use($app) {
  187. if($user=require_login($app)) {
  188. $params = $app->request()->params();
  189. $repost_of = '';
  190. if(array_key_exists('url', $params))
  191. $repost_of = $params['url'];
  192. if(array_key_exists('edit', $params)) {
  193. $edit_data = get_micropub_source($user, $params['edit'], 'repost-of');
  194. $url = $params['edit'];
  195. if(isset($edit_data['repost-of'])) {
  196. $repost = $edit_data['repost-of'][0];
  197. if(is_string($edit_data['repost-of'][0])) {
  198. $repost_of = $repost;
  199. } elseif(is_array($repost)) {
  200. if(array_key_exists('type', $repost) && in_array('h-cite', $repost)) {
  201. if(array_key_exists('url', $repost['properties'])) {
  202. $repost_of = $repost['properties']['url'][0];
  203. }
  204. } else {
  205. // Error
  206. }
  207. } else {
  208. // Error: don't know what type of post this is
  209. }
  210. }
  211. } else {
  212. $edit_data = false;
  213. $url = false;
  214. }
  215. render('new-repost', array(
  216. 'title' => 'New Repost',
  217. 'repost_of' => $repost_of,
  218. 'token' => generate_login_token(),
  219. 'authorizing' => false,
  220. 'url' => $url,
  221. ));
  222. }
  223. });
  224. $app->post('/prefs', function() use($app) {
  225. if($user=require_login($app)) {
  226. $params = $app->request()->params();
  227. $user->location_enabled = $params['enabled'];
  228. $user->save();
  229. }
  230. $app->response()['Content-type'] = 'application/json';
  231. $app->response()->body(json_encode(array(
  232. 'result' => 'ok'
  233. )));
  234. });
  235. $app->post('/prefs/timezone', function() use($app) {
  236. // Called when the interface finds the user's location.
  237. // Look up the timezone for this location and store it as their default.
  238. $timezone = false;
  239. if($user=require_login($app)) {
  240. $params = $app->request()->params();
  241. $timezone = p3k\Timezone::timezone_for_location($params['latitude'], $params['longitude']);
  242. if($timezone) {
  243. $user->default_timezone = $timezone;
  244. $user->save();
  245. }
  246. }
  247. $app->response()['Content-type'] = 'application/json';
  248. $app->response()->body(json_encode(array(
  249. 'result' => 'ok',
  250. 'timezone' => $timezone,
  251. )));
  252. });
  253. $app->get('/add-to-home', function() use($app) {
  254. $params = $app->request()->params();
  255. header("Cache-Control: no-cache, must-revalidate");
  256. if(array_key_exists('token', $params) && !session('add-to-home-started')) {
  257. unset($_SESSION['add-to-home-started']);
  258. // Verify the token and sign the user in
  259. try {
  260. $data = JWT::decode($params['token'], Config::$jwtSecret, array('HS256'));
  261. $_SESSION['user_id'] = $data->user_id;
  262. $_SESSION['me'] = $data->me;
  263. $app->redirect('/new', 302);
  264. } catch(DomainException $e) {
  265. header('X-Error: DomainException');
  266. $app->redirect('/', 302);
  267. } catch(UnexpectedValueException $e) {
  268. header('X-Error: UnexpectedValueException');
  269. $app->redirect('/', 302);
  270. }
  271. } else {
  272. if($user=require_login($app)) {
  273. if(array_key_exists('start', $params)) {
  274. $_SESSION['add-to-home-started'] = true;
  275. $token = JWT::encode(array(
  276. 'user_id' => $_SESSION['user_id'],
  277. 'me' => $_SESSION['me'],
  278. 'created_at' => time()
  279. ), Config::$jwtSecret);
  280. $app->redirect('/add-to-home?token='.$token, 302);
  281. } else {
  282. unset($_SESSION['add-to-home-started']);
  283. render('add-to-home', array('title' => 'Quill'));
  284. }
  285. }
  286. }
  287. });
  288. $app->get('/email', function() use($app) {
  289. if($user=require_login($app)) {
  290. $test_response = '';
  291. if($user->last_micropub_response) {
  292. try {
  293. if(@json_decode($user->last_micropub_response)) {
  294. $d = json_decode($user->last_micropub_response);
  295. $test_response = $d->response;
  296. }
  297. } catch(Exception $e) {
  298. }
  299. }
  300. if(!$user->email_username) {
  301. $host = parse_url($user->url, PHP_URL_HOST);
  302. $user->email_username = $host . '.' . rand(100000,999999);
  303. $user->save();
  304. }
  305. render('email', array(
  306. 'title' => 'Post-by-Email',
  307. 'micropub_endpoint' => $user->micropub_endpoint,
  308. 'test_response' => $test_response,
  309. 'user' => $user
  310. ));
  311. }
  312. });
  313. $app->get('/settings', function() use($app) {
  314. if($user=require_login($app)) {
  315. render('settings', [
  316. 'title' => 'Settings',
  317. 'user' => $user,
  318. 'authorizing' => false
  319. ]);
  320. }
  321. });
  322. $app->post('/settings/save', function() use($app) {
  323. if($user=require_login($app)) {
  324. $params = $app->request()->params();
  325. if(array_key_exists('html_content', $params))
  326. $user->micropub_optin_html_content = $params['html_content'] ? 1 : 0;
  327. if(array_key_exists('slug_field', $params) && $params['slug_field'])
  328. $user->micropub_slug_field = $params['slug_field'];
  329. if(array_key_exists('syndicate_field', $params) && $params['syndicate_field']) {
  330. if(in_array($params['syndicate_field'], ['syndicate-to','mp-syndicate-to']))
  331. $user->micropub_syndicate_field = $params['syndicate_field'];
  332. }
  333. $user->save();
  334. $app->response()['Content-type'] = 'application/json';
  335. $app->response()->body(json_encode(array(
  336. 'result' => 'ok'
  337. )));
  338. }
  339. });
  340. $app->post('/settings/html-content', function() use($app) {
  341. if($user=require_login($app)) {
  342. $params = $app->request()->params();
  343. $user->micropub_optin_html_content = $params['html'] ? 1 : 0;
  344. $user->save();
  345. $app->response()['Content-type'] = 'application/json';
  346. $app->response()->body(json_encode(array(
  347. 'html' => $user->micropub_optin_html_content
  348. )));
  349. }
  350. });
  351. $app->get('/settings/html-content', function() use($app) {
  352. if($user=require_login($app)) {
  353. $app->response()['Content-type'] = 'application/json';
  354. $app->response()->body(json_encode(array(
  355. 'html' => $user->micropub_optin_html_content
  356. )));
  357. }
  358. });
  359. function create_favorite(&$user, $url) {
  360. $micropub_request = array(
  361. 'like-of' => $url
  362. );
  363. $r = micropub_post_for_user($user, $micropub_request);
  364. $tweet_id = false;
  365. // POSSE favorites to Twitter
  366. if($user->twitter_access_token && preg_match('/https?:\/\/(?:www\.)?twitter\.com\/[^\/]+\/status(?:es)?\/(\d+)/', $url, $match)) {
  367. $tweet_id = $match[1];
  368. $twitter = new TwitterOAuth(Config::$twitterClientID, Config::$twitterClientSecret,
  369. $user->twitter_access_token, $user->twitter_token_secret);
  370. $result = $twitter->post('favorites/create', array(
  371. 'id' => $tweet_id
  372. ));
  373. }
  374. return $r;
  375. }
  376. function edit_favorite(&$user, $post_url, $like_of) {
  377. $micropub_request = [
  378. 'action' => 'update',
  379. 'url' => $post_url,
  380. 'replace' => [
  381. 'like-of' => [$like_of]
  382. ]
  383. ];
  384. $r = micropub_post_for_user($user, $micropub_request, null, true);
  385. return $r;
  386. }
  387. function create_repost(&$user, $url) {
  388. $micropub_request = array(
  389. 'repost-of' => $url
  390. );
  391. $r = micropub_post_for_user($user, $micropub_request);
  392. $tweet_id = false;
  393. if($user->twitter_access_token && preg_match('/https?:\/\/(?:www\.)?twitter\.com\/[^\/]+\/status(?:es)?\/(\d+)/', $url, $match)) {
  394. $tweet_id = $match[1];
  395. $twitter = new TwitterOAuth(Config::$twitterClientID, Config::$twitterClientSecret,
  396. $user->twitter_access_token, $user->twitter_token_secret);
  397. $result = $twitter->post('statuses/retweet/'.$tweet_id);
  398. }
  399. return $r;
  400. }
  401. function edit_repost(&$user, $post_url, $repost_of) {
  402. $micropub_request = [
  403. 'action' => 'update',
  404. 'url' => $post_url,
  405. 'replace' => [
  406. 'repost-of' => [$repost_of]
  407. ]
  408. ];
  409. $r = micropub_post_for_user($user, $micropub_request, null, true);
  410. return $r;
  411. }
  412. $app->post('/favorite', function() use($app) {
  413. if($user=require_login($app)) {
  414. $params = $app->request()->params();
  415. $error = false;
  416. if(isset($params['edit']) && $params['edit']) {
  417. $r = edit_favorite($user, $params['edit'], $params['like_of']);
  418. if(isset($r['location']) && $r['location'])
  419. $location = $r['location'];
  420. elseif(in_array($r['code'], [200,201,204]))
  421. $location = $params['edit'];
  422. elseif(in_array($r['code'], [401,403])) {
  423. $location = false;
  424. $error = 'Your Micropub endpoint denied the request. Check that Quill is authorized to update posts.';
  425. } else {
  426. $location = false;
  427. $error = 'Your Micropub endpoint did not return a location header or a recognized response code';
  428. }
  429. } else {
  430. $r = create_favorite($user, $params['like_of']);
  431. $location = $r['location'];
  432. }
  433. $app->response()['Content-type'] = 'application/json';
  434. $app->response()->body(json_encode(array(
  435. 'location' => $location,
  436. 'error' => $r['error'],
  437. 'error_details' => $error,
  438. )));
  439. }
  440. });
  441. $app->post('/repost', function() use($app) {
  442. if($user=require_login($app)) {
  443. $params = $app->request()->params();
  444. $error = false;
  445. if(isset($params['edit']) && $params['edit']) {
  446. $r = edit_repost($user, $params['edit'], $params['repost_of']);
  447. if(isset($r['location']) && $r['location'])
  448. $location = $r['location'];
  449. elseif(in_array($r['code'], [200,201,204]))
  450. $location = $params['edit'];
  451. elseif(in_array($r['code'], [401,403])) {
  452. $location = false;
  453. $error = 'Your Micropub endpoint denied the request. Check that Quill is authorized to update posts.';
  454. } else {
  455. $location = false;
  456. $error = 'Your Micropub endpoint did not return a location header or a recognized response code';
  457. }
  458. } else {
  459. $r = create_repost($user, $params['repost_of']);
  460. $location = $r['location'];
  461. }
  462. $app->response()['Content-type'] = 'application/json';
  463. $app->response()->body(json_encode(array(
  464. 'location' => $location,
  465. 'error' => $r['error'],
  466. 'error_details' => $error,
  467. )));
  468. }
  469. });
  470. $app->get('/reply/preview', function() use($app) {
  471. if($user=require_login($app)) {
  472. $params = $app->request()->params();
  473. if(!isset($params['url']) || !$params['url']) {
  474. return '';
  475. }
  476. $reply_url = trim($params['url']);
  477. if(preg_match('/twtr\.io\/([0-9a-z]+)/i', $reply_url, $match)) {
  478. $twtr = 'https://twitter.com/_/status/' . sxg_to_num($match[1]);
  479. $ch = curl_init($twtr);
  480. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  481. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  482. curl_exec($ch);
  483. $expanded_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
  484. if($expanded_url) $reply_url = $expanded_url;
  485. }
  486. $entry = false;
  487. $xray = [
  488. 'url' => $reply_url
  489. ];
  490. if(preg_match('/twitter\.com\/(?:[^\/]+)\/statuse?s?\/(.+)/', $reply_url, $match)) {
  491. if($user->twitter_access_token) {
  492. $xray['twitter_api_key'] = Config::$twitterClientID;
  493. $xray['twitter_api_secret'] = Config::$twitterClientSecret;
  494. $xray['twitter_access_token'] = $user->twitter_access_token;
  495. $xray['twitter_access_token_secret'] = $user->twitter_token_secret;
  496. }
  497. }
  498. // Pass to X-Ray to see if it can expand the entry
  499. $ch = curl_init('https://xray.p3k.io/parse');
  500. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  501. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($xray));
  502. $response = curl_exec($ch);
  503. $data = @json_decode($response, true);
  504. if($data && isset($data['data'])) {
  505. if($data['data']['type'] == 'entry') {
  506. $entry = $data['data'];
  507. } elseif($data['data']['type'] == 'event') {
  508. $entry = $data['data'];
  509. $content = '';
  510. if(isset($entry['start']) && isset($entry['end'])) {
  511. $formatted = DateFormatter::format($entry['start'], $entry['end'], false);
  512. if($formatted)
  513. $content .= $formatted;
  514. else {
  515. $start = new DateTime($entry['start']);
  516. $end = new DateTime($entry['end']);
  517. if($start && $end)
  518. $content .= 'from '.$start->format('Y-m-d g:ia').' to '.$end->format('Y-m-d g:ia');
  519. }
  520. } elseif(isset($entry['start'])) {
  521. $formatted = DateFormatter::format($entry['start'], false, false);
  522. if($formatted)
  523. $content .= $formatted;
  524. else {
  525. $start = new DateTime($entry['start']);
  526. if($start)
  527. $content .= $start->format('Y-m-d g:ia');
  528. }
  529. }
  530. $entry['content']['text'] = $content;
  531. }
  532. // Create a nickname based on the author URL
  533. if(array_key_exists('author', $entry)) {
  534. if($entry['author']['url']) {
  535. if(!isset($entry['author']['nickname']) || !$entry['author']['nickname'])
  536. $entry['author']['nickname'] = display_url($entry['author']['url']);
  537. }
  538. }
  539. }
  540. $mentions = [];
  541. if($entry) {
  542. if(array_key_exists('author', $entry)) {
  543. // Find all @-names in the post, as well as the author name
  544. $mentions[] = strtolower($entry['author']['nickname']);
  545. }
  546. if(isset($entry['content']) && $entry['content'] && isset($entry['content']['text'])) {
  547. if(preg_match_all('/(^|(?<=[\s\/]))@([a-z0-9_]+([a-z0-9_\.]*)?)/i', $entry['content']['text'], $matches)) {
  548. foreach($matches[0] as $nick) {
  549. if(trim($nick,'@') != $user->twitter_username && trim($nick,'@') != display_url($user->url))
  550. $mentions[] = strtolower(trim($nick,'@'));
  551. }
  552. }
  553. }
  554. $mentions = array_values(array_unique($mentions));
  555. }
  556. $app->response()['Content-type'] = 'application/json';
  557. $app->response()->body(json_encode([
  558. 'canonical_reply_url' => $reply_url,
  559. 'entry' => $entry,
  560. 'mentions' => $mentions
  561. ]));
  562. }
  563. });
  564. $app->get('/edit', function() use($app) {
  565. if($user=require_login($app)) {
  566. $params = $app->request()->params();
  567. if(!isset($params['url']) || !$params['url']) {
  568. $app->response()->body('no URL specified');
  569. }
  570. // Query the micropub endpoint for the source properties
  571. $source = micropub_get($user->micropub_endpoint, [
  572. 'q' => 'source',
  573. 'url' => $params['url']
  574. ], $user->micropub_access_token);
  575. $data = $source['data'];
  576. if(array_key_exists('error', $data)) {
  577. render('edit/error', [
  578. 'title' => 'Error',
  579. 'summary' => 'Your Micropub endpoint returned an error:',
  580. 'error' => $data['error'],
  581. 'error_description' => $data['error_description']
  582. ]);
  583. return;
  584. }
  585. if(!array_key_exists('properties', $data) || !array_key_exists('type', $data)) {
  586. render('edit/error', [
  587. 'title' => 'Error',
  588. 'summary' => '',
  589. 'error' => 'Invalid Response',
  590. 'error_description' => 'Your endpoint did not return "properties" and "type" in the response.'
  591. ]);
  592. return;
  593. }
  594. // Start checking for content types
  595. $type = $data['type'][0];
  596. $error = false;
  597. $url = false;
  598. if($type == 'h-review') {
  599. $url = '/review';
  600. } elseif($type == 'h-event') {
  601. $url = '/event';
  602. } elseif($type != 'h-entry') {
  603. $error = 'This type of post is not supported by any of Quill\'s editing interfaces. Type: '.$type;
  604. } else {
  605. if(array_key_exists('bookmark-of', $data['properties'])) {
  606. $url = '/bookmark';
  607. } elseif(array_key_exists('like-of', $data['properties'])) {
  608. $url = '/favorite';
  609. } elseif(array_key_exists('repost-of', $data['properties'])) {
  610. $url = '/repost';
  611. }
  612. }
  613. if($error) {
  614. render('edit/error', [
  615. 'title' => 'Error',
  616. 'summary' => '',
  617. 'error' => 'There was a problem!',
  618. 'error_description' => $error
  619. ]);
  620. return;
  621. }
  622. // Until all interfaces are complete, show an error here for unsupported ones
  623. if(!in_array($url, ['/favorite','/repost'])) {
  624. render('edit/error', [
  625. 'title' => 'Not Yet Supported',
  626. 'summary' => '',
  627. 'error' => 'Not Yet Supported',
  628. 'error_description' => 'Editing is not yet supported for this type of post.'
  629. ]);
  630. return;
  631. }
  632. $app->redirect($url . '?edit=' . $params['url'], 302);
  633. }
  634. });