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.

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