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.

463 lines
14 KiB

9 years ago
1 year ago
1 year ago
9 years ago
1 year ago
9 years ago
9 years ago
  1. <?php
  2. use \Firebase\JWT\JWT;
  3. function require_login(&$app) {
  4. $params = $app->request()->params();
  5. if(!array_key_exists('user_id', $_SESSION)) {
  6. $app->redirect('/');
  7. return false;
  8. } else {
  9. return ORM::for_table('users')->find_one($_SESSION['user_id']);
  10. }
  11. }
  12. function get_login(&$app) {
  13. if(array_key_exists('user_id', $_SESSION)) {
  14. return ORM::for_table('users')->find_one($_SESSION['user_id']);
  15. } else {
  16. return false;
  17. }
  18. }
  19. function generate_login_token() {
  20. return JWT::encode(array(
  21. 'user_id' => $_SESSION['user_id'],
  22. 'me' => $_SESSION['me'],
  23. 'created_at' => time()
  24. ), Config::$jwtSecret);
  25. }
  26. $app->get('/new', function() use($app) {
  27. if($user=require_login($app)) {
  28. // Get the last post and set the timezone offset to match
  29. $date_str = date('Y-m-d');
  30. $time_str = date('H:i:s');
  31. $tz_offset = '+0000';
  32. $last = ORM::for_table('entries')->where('user_id', $user->id)
  33. ->order_by_desc('published')->find_one();
  34. if(false && $last) {
  35. $seconds = $last->tz_offset;
  36. $tz_offset = tz_seconds_to_offset($seconds);
  37. // Create a date object in the local timezone given the offset
  38. $date = new DateTime();
  39. if($seconds > 0)
  40. $date->add(new DateInterval('PT'.$seconds.'S'));
  41. elseif($seconds < 0)
  42. $date->sub(new DateInterval('PT'.abs($seconds).'S'));
  43. $date_str = $date->format('Y-m-d');
  44. $time_str = $date->format('H:i:s');
  45. }
  46. // Initially populate the page with the list of options without considering location.
  47. // This way if browser location is disabled or not available, or JS is disabled, there
  48. // will still be a list of options presented on the page by the time it loads.
  49. // Javascript will replace the options after location is available.
  50. render('new-post', array(
  51. 'title' => 'New Post',
  52. 'micropub_endpoint' => $user->micropub_endpoint,
  53. 'micropub_media_endpoint' => $user->micropub_media_endpoint,
  54. 'token_scope' => $user->token_scope,
  55. 'access_token' => $user->access_token,
  56. 'response_date' => $user->last_micropub_response_date,
  57. 'location_enabled' => $user->location_enabled,
  58. 'default_options' => get_entry_options($user->id),
  59. 'tz_offset' => $tz_offset,
  60. 'date_str' => $date_str,
  61. 'time_str' => $time_str,
  62. 'enable_array_micropub' => $user->enable_array_micropub
  63. ));
  64. }
  65. });
  66. $app->get('/settings', function() use($app) {
  67. if($user=require_login($app)) {
  68. render('settings', [
  69. 'title' => 'Settings',
  70. ]);
  71. }
  72. });
  73. $app->post('/settings/device-code', function() use($app) {
  74. if($user=require_login($app)) {
  75. $code = mt_rand(100000,999999);
  76. $user->device_code = $code;
  77. $user->device_code_expires = date('Y-m-d H:i:s', time()+300);
  78. $user->save();
  79. $app->response()['Content-Type'] = 'application/json';
  80. $app->response()->body(json_encode([
  81. 'code' => $code
  82. ]));
  83. }
  84. });
  85. $app->post('/prefs/enable-h-food', function() use($app){
  86. if($user=require_login($app)) {
  87. $user->enable_array_micropub = 1;
  88. $user->save();
  89. }
  90. $app->redirect('/new', 302);
  91. });
  92. $app->post('/prefs', function() use($app) {
  93. if($user=require_login($app)) {
  94. $params = $app->request()->params();
  95. $user->location_enabled = $params['enabled'];
  96. $user->save();
  97. }
  98. $app->response()->body(json_encode(array(
  99. 'result' => 'ok'
  100. )));
  101. });
  102. $app->get('/creating-a-token-endpoint', function() use($app) {
  103. $app->redirect('https://indieweb.org/token-endpoint', 301);
  104. });
  105. $app->get('/creating-a-micropub-endpoint', function() use($app) {
  106. $app->redirect('https://indieweb.org/Micropub', 301);
  107. });
  108. $app->get('/docs', function() use($app) {
  109. render('docs', array('title' => 'Documentation'));
  110. });
  111. $app->get('/privacy', function() use($app) {
  112. render('privacy', array('title' => 'Privacy Policy'));
  113. });
  114. $app->get('/add-to-home', function() use($app) {
  115. $params = $app->request()->params();
  116. header("Cache-Control: no-cache, must-revalidate");
  117. if(array_key_exists('token', $params) && !isset($_SESSION['add-to-home-started'])) {
  118. // Verify the token and sign the user in
  119. try {
  120. $data = JWT::decode($params['token'], Config::$jwtSecret, ['HS256']);
  121. $_SESSION['user_id'] = $data->user_id;
  122. $_SESSION['me'] = $data->me;
  123. $app->redirect('/new', 302);
  124. } catch(DomainException $e) {
  125. header('X-Error: DomainException');
  126. $app->redirect('/?error=domain', 302);
  127. } catch(SignatureInvalidException $e) {
  128. header('X-Error: SignatureInvalidException');
  129. $app->redirect('/?error=invalid', 302);
  130. } catch(ErrorException $e) {
  131. $app->redirect('/?error=unknown', 302);
  132. }
  133. } else {
  134. if($user=require_login($app)) {
  135. if(array_key_exists('start', $params)) {
  136. $_SESSION['add-to-home-started'] = 1;
  137. $token = JWT::encode(array(
  138. 'user_id' => $_SESSION['user_id'],
  139. 'me' => $_SESSION['me'],
  140. 'created_at' => time()
  141. ), Config::$jwtSecret);
  142. $app->redirect('/add-to-home?token='.$token, 302);
  143. } else {
  144. unset($_SESSION['add-to-home-started']);
  145. render('add-to-home', array('title' => 'Teacup'));
  146. }
  147. }
  148. }
  149. });
  150. $app->post('/post', function() use($app) {
  151. if($user=require_login($app)) {
  152. $params = $app->request()->params();
  153. // Remove any blank params
  154. $params = array_filter($params, function($v){
  155. return $v !== '';
  156. });
  157. // Store the post in the database
  158. $entry = ORM::for_table('entries')->create();
  159. $entry->user_id = $user->id;
  160. $location = false;
  161. if(k($params, 'venue_url')) {
  162. $entry->checkin_url = $params['venue_url'];
  163. } else {
  164. if(k($params, 'location') && $location=parse_geo_uri($params['location'])) {
  165. $entry->latitude = $location['latitude'];
  166. $entry->longitude = $location['longitude'];
  167. }
  168. }
  169. if(k($params,'note_date')) {
  170. // The post request is always going to have a date now
  171. $date_string = $params['note_date'] . 'T' . $params['note_time'] . $params['note_tzoffset'];
  172. $entry->published = date('Y-m-d H:i:s', strtotime($date_string));
  173. $entry->tz_offset = tz_offset_to_seconds($params['note_tzoffset']);
  174. $published = $date_string;
  175. } else {
  176. $entry->published = date('Y-m-d H:i:s');
  177. $published = date('c'); // for the micropub post
  178. if($location && ($timezone=get_timezone($location['latitude'], $location['longitude']))) {
  179. $entry->timezone = $timezone->getName();
  180. $entry->tz_offset = $timezone->getOffset(new DateTime());
  181. $now = new DateTime();
  182. $now->setTimeZone(new DateTimeZone($entry->timezone));
  183. $published = $now->format('c');
  184. }
  185. }
  186. if(k($params, 'drank')) {
  187. $entry->content = trim($params['drank']);
  188. $type = 'drink';
  189. $verb = 'drank';
  190. } elseif(k($params, 'drink')) {
  191. $entry->content = trim($params['drink']);
  192. $type = 'drink';
  193. $verb = 'drank';
  194. } elseif(k($params, 'eat')) {
  195. $entry->content = trim($params['eat']);
  196. $type = 'eat';
  197. $verb = 'ate';
  198. } elseif(k($params, 'custom_drink')) {
  199. $entry->content = trim($params['custom_drink']);
  200. $type = 'drink';
  201. $verb = 'drank';
  202. } elseif(k($params, 'custom_eat')) {
  203. $entry->content = trim($params['custom_eat']);
  204. $type = 'eat';
  205. $verb = 'ate';
  206. }
  207. if($user->micropub_media_endpoint && k($params, 'note_photo')) {
  208. $entry->photo_url = $params['note_photo'];
  209. }
  210. $entry->type = $type;
  211. $entry->save();
  212. // Send to the micropub endpoint if one is defined, and store the result
  213. $url = false;
  214. if($user->micropub_endpoint) {
  215. $text_content = 'Just ' . $verb . ': ' . $entry->content;
  216. $mp_properties = array(
  217. 'published' => [$published],
  218. 'created' => [$published],
  219. 'summary' => [$text_content]
  220. );
  221. if($venue = k($params, 'venue_url')) {
  222. $mp_properties['location'] = [$venue];
  223. } elseif($location = k($params, 'location')) {
  224. $mp_properties['location'] = [$location];
  225. }
  226. if($entry->photo_url) {
  227. $mp_properties['photo'] = [$entry->photo_url];
  228. }
  229. $mp_properties[$verb] = [[
  230. 'type' => ['h-food'],
  231. 'properties' => [
  232. 'name' => $entry->content
  233. ]
  234. ]];
  235. $mp_request = array(
  236. 'type' => ['h-entry'],
  237. 'properties' => $mp_properties
  238. );
  239. $r = micropub_post($user->micropub_endpoint, $mp_request, $user->access_token);
  240. $request = $r['request'];
  241. $response = $r['response'];
  242. $entry->micropub_response = $response;
  243. // Check the response and look for a "Location" header containing the URL
  244. if($response && preg_match('/Location: (.+)/', $response, $match)) {
  245. $url = $match[1];
  246. $user->micropub_success = 1;
  247. $entry->micropub_success = 1;
  248. $entry->canonical_url = $url;
  249. } else {
  250. $entry->micropub_success = 0;
  251. }
  252. $entry->save();
  253. }
  254. if($url) {
  255. $app->redirect($url);
  256. } else {
  257. // TODO: Redirect to an error page or show an error on the teacup post page
  258. $url = Config::$base_url . $user->url . '/' . $entry->id;
  259. $app->redirect($url);
  260. }
  261. }
  262. });
  263. $app->post('/micropub/media', function() use($app) {
  264. if($user=require_login($app)) {
  265. $file = isset($_FILES['file']) ? $_FILES['file'] : null;
  266. $error = validate_photo($file);
  267. unset($_POST['null']);
  268. if(!$error) {
  269. $file_path = $file['tmp_name'];
  270. correct_photo_rotation($file_path);
  271. $r = micropub_media_post($user->micropub_media_endpoint, $user->access_token, $file_path);
  272. } else {
  273. $r = array('error' => $error);
  274. }
  275. $response = $r['response'];
  276. $url = null;
  277. if($response && preg_match('/Location: (.+)/', $response, $match)) {
  278. $url = trim($match[1]);
  279. } else {
  280. $r['error'] = "No 'Location' header in response.";
  281. $r['debug'] = $response;
  282. }
  283. $app->response()['Content-type'] = 'application/json';
  284. $app->response()->body(json_encode(array(
  285. 'location' => $url,
  286. 'error' => (isset($r['error']) ? $r['error'] : null),
  287. 'debug' => (isset($r['debug']) ? $r['debug'] : null),
  288. )));
  289. }
  290. });
  291. $app->get('/micropub/config', function() use($app) {
  292. if($user=require_login($app)) {
  293. $config = get_micropub_config($user);
  294. $app->response()['Content-type'] = 'application/json';
  295. $app->response()->body(json_encode($config));
  296. }
  297. });
  298. $app->get('/micropub/last-checkin', function() use($app){
  299. if($user=require_login($app)) {
  300. $checkin = get_micropub_checkin($user);
  301. $app->response()['Content-type'] = 'application/json';
  302. $app->response()->body(json_encode($checkin));
  303. }
  304. });
  305. $app->get('/options.json', function() use($app) {
  306. if($user=require_login($app)) {
  307. $params = $app->request()->params();
  308. $options = get_entry_options($user->id, k($params,'latitude'), k($params,'longitude'));
  309. $html = partial('partials/entry-buttons', ['options'=>$options]);
  310. $app->response()['Content-type'] = 'application/json';
  311. $app->response()->body(json_encode([
  312. 'buttons'=>$html
  313. ]));
  314. }
  315. });
  316. $app->get('/map.png', function() use($app) {
  317. $params = $app->request()->params();
  318. $params['basemap'] = 'custom';
  319. $params['attribution'] = 'mapbox';
  320. $params['tileurl'] = Config::$mapTileURL;
  321. $params['token'] = Config::$atlasToken;
  322. $ch = curl_init('https://atlas.p3k.io/map/img');
  323. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  324. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
  325. $img = curl_exec($ch);
  326. header('Expires: ' . gmdate('D, d M Y H:i:s', strtotime('+30 days')) . ' GMT');
  327. header('Pragma: cache');
  328. header('Cache-Control: private');
  329. $app->response()['Content-type'] = 'image/png';
  330. $app->response()->body($img);
  331. });
  332. $app->get('/:domain', function($domain) use($app) {
  333. $params = $app->request()->params();
  334. $user = ORM::for_table('users')->where('url', $domain)->find_one();
  335. if(!$user) {
  336. $app->notFound();
  337. return;
  338. }
  339. $per_page = 10;
  340. $entries = ORM::for_table('entries')->where('user_id', $user->id);
  341. if(array_key_exists('before', $params)) {
  342. $entries->where_lte('id', $params['before']);
  343. }
  344. $entries = $entries->limit($per_page)->order_by_desc('published')->find_many();
  345. if(count($entries) > 1) {
  346. $older = ORM::for_table('entries')->where('user_id', $user->id)
  347. ->where_lt('id', $entries[count($entries)-1]->id)->order_by_desc('published')->find_one();
  348. } else {
  349. $older = null;
  350. }
  351. if(count($entries) > 1) {
  352. $newer = ORM::for_table('entries')->where('user_id', $user->id)
  353. ->where_gte('id', $entries[0]->id)->order_by_asc('published')->offset($per_page)->find_one();
  354. } else {
  355. $newer = null;
  356. }
  357. if(!$newer) {
  358. // no new entry was found at the specific offset, so find the newest post to link to instead
  359. $newer = ORM::for_table('entries')->where('user_id', $user->id)
  360. ->order_by_desc('published')->limit(1)->find_one();
  361. if($newer && $newer->id == $entries[0]->id)
  362. $newer = false;
  363. }
  364. render('entries', array(
  365. 'title' => 'Teacup',
  366. 'entries' => $entries,
  367. 'user' => $user,
  368. 'older' => ($older ? $older->id : false),
  369. 'newer' => ($newer ? $newer->id : false)
  370. ));
  371. })->conditions(array(
  372. 'domain' => '[a-zA-Z0-9\.-]+\.[a-z]+'
  373. ));
  374. $app->get('/:domain/:entry', function($domain, $entry_id) use($app) {
  375. $user = ORM::for_table('users')->where('url', $domain)->find_one();
  376. if(!$user) {
  377. $app->notFound();
  378. return;
  379. }
  380. $entry = ORM::for_table('entries')->where('user_id', $user->id)->where('id', $entry_id)->find_one();
  381. if(!$entry) {
  382. $app->notFound();
  383. return;
  384. }
  385. render('entry', array(
  386. 'title' => 'Teacup',
  387. 'entry' => $entry,
  388. 'user' => $user
  389. ));
  390. })->conditions(array(
  391. 'domain' => '[a-zA-Z0-9\.-]+\.[a-z]+',
  392. 'entry' => '\d+'
  393. ));