Mirror of Quill
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.

1010 lines
29 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 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. 'syndication_targets' => json_decode($user->syndication_targets, true),
  417. 'authorizing' => false
  418. ]);
  419. }
  420. });
  421. $app->post('/settings/save', function() use($app) {
  422. if($user=require_login($app)) {
  423. $params = $app->request()->params();
  424. if(array_key_exists('html_content', $params))
  425. $user->micropub_optin_html_content = $params['html_content'] ? 1 : 0;
  426. if(array_key_exists('slug_field', $params) && $params['slug_field'])
  427. $user->micropub_slug_field = $params['slug_field'];
  428. if(array_key_exists('syndicate_field', $params) && $params['syndicate_field']) {
  429. if(in_array($params['syndicate_field'], ['syndicate-to','mp-syndicate-to']))
  430. $user->micropub_syndicate_field = $params['syndicate_field'];
  431. }
  432. $user->save();
  433. $app->response()['Content-type'] = 'application/json';
  434. $app->response()->body(json_encode(array(
  435. 'result' => 'ok'
  436. )));
  437. }
  438. });
  439. $app->post('/settings/html-content', function() use($app) {
  440. if($user=require_login($app)) {
  441. $params = $app->request()->params();
  442. $user->micropub_optin_html_content = $params['html'] ? 1 : 0;
  443. $user->save();
  444. $app->response()['Content-type'] = 'application/json';
  445. $app->response()->body(json_encode(array(
  446. 'html' => $user->micropub_optin_html_content
  447. )));
  448. }
  449. });
  450. $app->get('/settings/html-content', function() use($app) {
  451. if($user=require_login($app)) {
  452. $app->response()['Content-type'] = 'application/json';
  453. $app->response()->body(json_encode(array(
  454. 'html' => $user->micropub_optin_html_content
  455. )));
  456. }
  457. });
  458. function create_favorite(&$user, $url) {
  459. $tweet_id = false;
  460. $twitter_syndication = false;
  461. // POSSE favorites to Twitter
  462. if($user->twitter_access_token && preg_match('/https?:\/\/(?:www\.)?twitter\.com\/[^\/]+\/status(?:es)?\/(\d+)/', $url, $match)) {
  463. $tweet_id = $match[1];
  464. $twitter = new TwitterOAuth(Config::$twitterClientID, Config::$twitterClientSecret,
  465. $user->twitter_access_token, $user->twitter_token_secret);
  466. $result = $twitter->post('favorites/create', array(
  467. 'id' => $tweet_id
  468. ));
  469. if(property_exists($result, 'id_str')) {
  470. $twitter_syndication = 'https://twitter.com/'.$user->twitter_username.'/status/'.$result->id_str;
  471. }
  472. }
  473. $micropub_request = array(
  474. 'like-of' => $url
  475. );
  476. if($twitter_syndication) {
  477. $micropub_request['syndication'] = $twitter_syndication;
  478. }
  479. $r = micropub_post_for_user($user, $micropub_request);
  480. return $r;
  481. }
  482. function edit_favorite(&$user, $post_url, $like_of) {
  483. $micropub_request = [
  484. 'action' => 'update',
  485. 'url' => $post_url,
  486. 'replace' => [
  487. 'like-of' => [$like_of]
  488. ]
  489. ];
  490. $r = micropub_post_for_user($user, $micropub_request, null, true);
  491. return $r;
  492. }
  493. function create_repost(&$user, $url) {
  494. $tweet_id = false;
  495. $twitter_syndication = false;
  496. if($user->twitter_access_token && preg_match('/https?:\/\/(?:www\.)?twitter\.com\/[^\/]+\/status(?:es)?\/(\d+)/', $url, $match)) {
  497. $tweet_id = $match[1];
  498. $twitter = new TwitterOAuth(Config::$twitterClientID, Config::$twitterClientSecret,
  499. $user->twitter_access_token, $user->twitter_token_secret);
  500. $result = $twitter->post('statuses/retweet/'.$tweet_id);
  501. if(property_exists($result, 'id_str')) {
  502. $twitter_syndication = 'https://twitter.com/'.$user->twitter_username.'/status/'.$result->id_str;
  503. }
  504. }
  505. $micropub_request = array(
  506. 'repost-of' => $url
  507. );
  508. if($twitter_syndication) {
  509. $micropub_request['syndication'] = $twitter_syndication;
  510. }
  511. $r = micropub_post_for_user($user, $micropub_request);
  512. return $r;
  513. }
  514. function edit_repost(&$user, $post_url, $repost_of) {
  515. $micropub_request = [
  516. 'action' => 'update',
  517. 'url' => $post_url,
  518. 'replace' => [
  519. 'repost-of' => [$repost_of]
  520. ]
  521. ];
  522. $r = micropub_post_for_user($user, $micropub_request, null, true);
  523. return $r;
  524. }
  525. $app->post('/favorite', function() use($app) {
  526. if($user=require_login($app)) {
  527. $params = $app->request()->params();
  528. $error = false;
  529. if(isset($params['edit']) && $params['edit']) {
  530. $r = edit_favorite($user, $params['edit'], $params['like_of']);
  531. if(isset($r['location']) && $r['location'])
  532. $location = $r['location'];
  533. elseif(in_array($r['code'], [200,201,204]))
  534. $location = $params['edit'];
  535. elseif(in_array($r['code'], [401,403])) {
  536. $location = false;
  537. $error = 'Your Micropub endpoint denied the request. Check that Quill is authorized to update posts.';
  538. } else {
  539. $location = false;
  540. $error = 'Your Micropub endpoint did not return a location header or a recognized response code';
  541. }
  542. } else {
  543. $r = create_favorite($user, $params['like_of']);
  544. $location = $r['location'];
  545. }
  546. $app->response()['Content-type'] = 'application/json';
  547. $app->response()->body(json_encode(array(
  548. 'location' => $location,
  549. 'error' => $r['error'],
  550. 'error_details' => $error,
  551. )));
  552. }
  553. });
  554. $app->post('/repost', function() use($app) {
  555. if($user=require_login($app)) {
  556. $params = $app->request()->params();
  557. $error = false;
  558. if(isset($params['edit']) && $params['edit']) {
  559. $r = edit_repost($user, $params['edit'], $params['repost_of']);
  560. if(isset($r['location']) && $r['location'])
  561. $location = $r['location'];
  562. elseif(in_array($r['code'], [200,201,204]))
  563. $location = $params['edit'];
  564. elseif(in_array($r['code'], [401,403])) {
  565. $location = false;
  566. $error = 'Your Micropub endpoint denied the request. Check that Quill is authorized to update posts.';
  567. } else {
  568. $location = false;
  569. $error = 'Your Micropub endpoint did not return a location header or a recognized response code';
  570. }
  571. } else {
  572. $r = create_repost($user, $params['repost_of']);
  573. $location = $r['location'];
  574. }
  575. $app->response()['Content-type'] = 'application/json';
  576. $app->response()->body(json_encode(array(
  577. 'location' => $location,
  578. 'error' => $r['error'],
  579. 'error_details' => $error,
  580. )));
  581. }
  582. });
  583. $app->get('/code', function() use($app) {
  584. if($user=require_login($app)) {
  585. $params = $app->request()->params();
  586. $edit_data = ['content'=>'','name'=>''];
  587. if(array_key_exists('edit', $params)) {
  588. $source = get_micropub_source($user, $params['edit'], ['content','name']);
  589. if(isset($source['content']) && is_array($source['content']) && isset($source['content'][0]))
  590. $edit_data['content'] = $source['content'][0];
  591. if(isset($source['name']) && is_array($source['name']) && isset($source['name'][0]))
  592. $edit_data['name'] = $source['name'][0];
  593. $url = $params['edit'];
  594. } else {
  595. $url = false;
  596. }
  597. $languages = [
  598. 'php' => ['php'],
  599. 'ruby' => ['rb'],
  600. 'python' => ['py'],
  601. 'perl' => ['pl'],
  602. 'javascript' => ['js'],
  603. 'html' => ['html','htm'],
  604. 'css' => ['css'],
  605. 'bash' => ['sh'],
  606. 'nginx' => ['conf'],
  607. 'apache' => [],
  608. 'text' => ['txt'],
  609. ];
  610. ksort($languages);
  611. $language_map = [];
  612. foreach($languages as $lang=>$exts) {
  613. foreach($exts as $ext)
  614. $language_map[$ext] = $lang;
  615. }
  616. render('new-code', array(
  617. 'title' => 'New Code Snippet',
  618. 'url' => $url,
  619. 'edit_data' => $edit_data,
  620. 'token' => generate_login_token(),
  621. 'languages' => $languages,
  622. 'language_map' => $language_map,
  623. 'my_hostname' => parse_url($user->url, PHP_URL_HOST),
  624. 'authorizing' => false,
  625. ));
  626. }
  627. });
  628. $app->post('/code', function() use($app) {
  629. if($user=require_login($app)) {
  630. $params = $app->request()->params();
  631. $error = false;
  632. if(isset($params['edit']) && $params['edit']) {
  633. $micropub_request = [
  634. 'action' => 'update',
  635. 'url' => $params['edit'],
  636. 'replace' => [
  637. 'content' => [$params['content']]
  638. ]
  639. ];
  640. if(isset($params['name']) && $params['name']) {
  641. $micropub_request['replace']['name'] = [$params['name']];
  642. }
  643. $r = micropub_post_for_user($user, $micropub_request, null, true);
  644. if(isset($r['location']) && $r['location'])
  645. $location = $r['location'];
  646. elseif(in_array($r['code'], [200,201,204]))
  647. $location = $params['edit'];
  648. elseif(in_array($r['code'], [401,403])) {
  649. $location = false;
  650. $error = 'Your Micropub endpoint denied the request. Check that Quill is authorized to update posts.';
  651. } else {
  652. $location = false;
  653. $error = 'Your Micropub endpoint did not return a location header or a recognized response code';
  654. }
  655. } else {
  656. $micropub_request = array(
  657. 'p3k-content-type' => 'code/' . $params['language'],
  658. 'content' => $params['content'],
  659. );
  660. if(isset($params['name']) && $params['name'])
  661. $micropub_request['name'] = $params['name'];
  662. $r = micropub_post_for_user($user, $micropub_request);
  663. $location = $r['location'];
  664. }
  665. $app->response()['Content-type'] = 'application/json';
  666. $app->response()->body(json_encode(array(
  667. 'location' => $location,
  668. 'error' => $r['error'],
  669. 'error_details' => $error,
  670. )));
  671. }
  672. });
  673. $app->get('/reply/preview', function() use($app) {
  674. if($user=require_login($app)) {
  675. $params = $app->request()->params();
  676. if(!isset($params['url']) || !$params['url']) {
  677. return '';
  678. }
  679. $reply_url = trim($params['url']);
  680. if(preg_match('/twtr\.io\/([0-9a-z]+)/i', $reply_url, $match)) {
  681. $twtr = 'https://twitter.com/_/status/' . sxg_to_num($match[1]);
  682. $ch = curl_init($twtr);
  683. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  684. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  685. curl_exec($ch);
  686. $expanded_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
  687. if($expanded_url) $reply_url = $expanded_url;
  688. }
  689. $entry = false;
  690. $xray_opts = [];
  691. if(preg_match('/twitter\.com\/(?:[^\/]+)\/statuse?s?\/(.+)/', $reply_url, $match)) {
  692. if($user->twitter_access_token) {
  693. $xray_opts['twitter_api_key'] = Config::$twitterClientID;
  694. $xray_opts['twitter_api_secret'] = Config::$twitterClientSecret;
  695. $xray_opts['twitter_access_token'] = $user->twitter_access_token;
  696. $xray_opts['twitter_access_token_secret'] = $user->twitter_token_secret;
  697. }
  698. }
  699. // Pass to X-Ray to see if it can expand the entry
  700. $xray = new p3k\XRay();
  701. $xray->http = new p3k\HTTP('Quill ('.Config::$base_url.')');
  702. $data = $xray->parse($reply_url, $xray_opts);
  703. if($data && isset($data['data'])) {
  704. if($data['data']['type'] == 'entry') {
  705. $entry = $data['data'];
  706. } elseif($data['data']['type'] == 'event') {
  707. $entry = $data['data'];
  708. $content = '';
  709. if(isset($entry['start']) && isset($entry['end'])) {
  710. $formatted = DateFormatter::format($entry['start'], $entry['end'], false);
  711. if($formatted)
  712. $content .= $formatted;
  713. else {
  714. $start = new DateTime($entry['start']);
  715. $end = new DateTime($entry['end']);
  716. if($start && $end)
  717. $content .= 'from '.$start->format('Y-m-d g:ia').' to '.$end->format('Y-m-d g:ia');
  718. }
  719. } elseif(isset($entry['start'])) {
  720. $formatted = DateFormatter::format($entry['start'], false, false);
  721. if($formatted)
  722. $content .= $formatted;
  723. else {
  724. $start = new DateTime($entry['start']);
  725. if($start)
  726. $content .= $start->format('Y-m-d g:ia');
  727. }
  728. }
  729. $entry['content']['text'] = $content;
  730. }
  731. // Create a nickname based on the author URL
  732. if($entry && array_key_exists('author', $entry)) {
  733. if($entry['author']['url']) {
  734. if(!isset($entry['author']['nickname']) || !$entry['author']['nickname'])
  735. $entry['author']['nickname'] = display_url($entry['author']['url']);
  736. }
  737. }
  738. }
  739. $mentions = [];
  740. if($entry) {
  741. if(array_key_exists('author', $entry) && isset($entry['author']['nickname'])) {
  742. // Find all @-names in the post, as well as the author name
  743. $mentions[] = strtolower($entry['author']['nickname']);
  744. }
  745. if(isset($entry['content']) && $entry['content'] && isset($entry['content']['text'])) {
  746. if(preg_match_all('/(^|(?<=[\s\/]))@([a-z0-9_]+([a-z0-9_\.]*)?)/i', $entry['content']['text'], $matches)) {
  747. foreach($matches[0] as $nick) {
  748. if(trim($nick,'@') != $user->twitter_username && trim($nick,'@') != display_url($user->url))
  749. $mentions[] = strtolower(trim($nick,'@'));
  750. }
  751. }
  752. }
  753. $mentions = array_values(array_unique($mentions));
  754. }
  755. $syndications = [];
  756. if($entry && isset($entry['syndication'])) {
  757. foreach($entry['syndication'] as $s) {
  758. $host = parse_url($s, PHP_URL_HOST);
  759. switch($host) {
  760. case 'twitter.com':
  761. case 'www.twitter.com':
  762. $icon = 'twitter.ico'; break;
  763. case 'facebook.com':
  764. case 'www.facebook.com':
  765. $icon = 'facebook.ico'; break;
  766. case 'github.com':
  767. case 'www.github.com':
  768. $icon = 'github.ico'; break;
  769. default:
  770. $icon = 'default.png'; break;
  771. }
  772. $syndications[] = [
  773. 'url' => $s,
  774. 'icon' => $icon
  775. ];
  776. }
  777. }
  778. $app->response()['Content-type'] = 'application/json';
  779. $app->response()->body(json_encode([
  780. 'canonical_reply_url' => $reply_url,
  781. 'entry' => $entry,
  782. 'mentions' => $mentions,
  783. 'syndications' => $syndications,
  784. ]));
  785. }
  786. });
  787. $app->get('/edit', function() use($app) {
  788. if($user=require_login($app)) {
  789. $params = $app->request()->params();
  790. if(!isset($params['url']) || !$params['url']) {
  791. $app->response()->body('no URL specified');
  792. }
  793. // Query the micropub endpoint for the source properties
  794. $source = micropub_get($user->micropub_endpoint, [
  795. 'q' => 'source',
  796. 'url' => $params['url']
  797. ], $user->micropub_access_token);
  798. $data = $source['data'];
  799. if(array_key_exists('error', $data)) {
  800. render('edit/error', [
  801. 'title' => 'Error',
  802. 'summary' => 'Your Micropub endpoint returned an error:',
  803. 'error' => $data['error'],
  804. 'error_description' => $data['error_description']
  805. ]);
  806. return;
  807. }
  808. if(!array_key_exists('properties', $data) || !array_key_exists('type', $data)) {
  809. render('edit/error', [
  810. 'title' => 'Error',
  811. 'summary' => '',
  812. 'error' => 'Invalid Response',
  813. 'error_description' => 'Your endpoint did not return "properties" and "type" in the response.'
  814. ]);
  815. return;
  816. }
  817. // Start checking for content types
  818. $type = $data['type'][0];
  819. $error = false;
  820. $url = false;
  821. if($type == 'h-review') {
  822. $url = '/review';
  823. } elseif($type == 'h-event') {
  824. $url = '/event';
  825. } elseif($type != 'h-entry') {
  826. $error = 'This type of post is not supported by any of Quill\'s editing interfaces. Type: '.$type;
  827. } else {
  828. if(array_key_exists('bookmark-of', $data['properties'])) {
  829. $url = '/bookmark';
  830. } elseif(array_key_exists('like-of', $data['properties'])) {
  831. $url = '/favorite';
  832. } elseif(array_key_exists('repost-of', $data['properties'])) {
  833. $url = '/repost';
  834. }
  835. }
  836. if($error) {
  837. render('edit/error', [
  838. 'title' => 'Error',
  839. 'summary' => '',
  840. 'error' => 'There was a problem!',
  841. 'error_description' => $error
  842. ]);
  843. return;
  844. }
  845. // Until all interfaces are complete, show an error here for unsupported ones
  846. if(!in_array($url, ['/favorite','/repost','/code'])) {
  847. render('edit/error', [
  848. 'title' => 'Not Yet Supported',
  849. 'summary' => '',
  850. 'error' => 'Not Yet Supported',
  851. 'error_description' => 'Editing is not yet supported for this type of post.'
  852. ]);
  853. return;
  854. }
  855. $app->redirect($url . '?edit=' . $params['url'], 302);
  856. }
  857. });
  858. $app->get('/airport-info', function() use($app){
  859. if($user=require_login($app)) {
  860. $params = $app->request()->params();
  861. if(!isset($params['code'])) return;
  862. $ch = curl_init('https://atlas.p3k.io/api/timezone?airport='.urlencode($params['code']));
  863. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  864. $data = json_decode(curl_exec($ch), true);
  865. if(!$data)
  866. $response = ['error' => 'unknown'];
  867. else {
  868. $response = $data;
  869. }
  870. $app->response()['Content-type'] = 'application/json';
  871. $app->response()->body(json_encode($response));
  872. }
  873. });