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.

646 lines
18 KiB

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