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.

1007 lines
29 KiB

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