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.

442 lines
13 KiB

9 years 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, 'location') && $location=parse_geo_uri($params['location'])) {
  162. $entry->latitude = $location['latitude'];
  163. $entry->longitude = $location['longitude'];
  164. }
  165. if(k($params,'note_date')) {
  166. // The post request is always going to have a date now
  167. $date_string = $params['note_date'] . 'T' . $params['note_time'] . $params['note_tzoffset'];
  168. $entry->published = date('Y-m-d H:i:s', strtotime($date_string));
  169. $entry->tz_offset = tz_offset_to_seconds($params['note_tzoffset']);
  170. $published = $date_string;
  171. } else {
  172. $entry->published = date('Y-m-d H:i:s');
  173. $published = date('c'); // for the micropub post
  174. if($location && ($timezone=get_timezone($location['latitude'], $location['longitude']))) {
  175. $entry->timezone = $timezone->getName();
  176. $entry->tz_offset = $timezone->getOffset(new DateTime());
  177. $now = new DateTime();
  178. $now->setTimeZone(new DateTimeZone($entry->timezone));
  179. $published = $now->format('c');
  180. }
  181. }
  182. if(k($params, 'drank')) {
  183. $entry->content = trim($params['drank']);
  184. $type = 'drink';
  185. $verb = 'drank';
  186. } elseif(k($params, 'drink')) {
  187. $entry->content = trim($params['drink']);
  188. $type = 'drink';
  189. $verb = 'drank';
  190. } elseif(k($params, 'eat')) {
  191. $entry->content = trim($params['eat']);
  192. $type = 'eat';
  193. $verb = 'ate';
  194. } elseif(k($params, 'custom_drink')) {
  195. $entry->content = trim($params['custom_drink']);
  196. $type = 'drink';
  197. $verb = 'drank';
  198. } elseif(k($params, 'custom_eat')) {
  199. $entry->content = trim($params['custom_eat']);
  200. $type = 'eat';
  201. $verb = 'ate';
  202. }
  203. if($user->micropub_media_endpoint && k($params, 'note_photo')) {
  204. $entry->photo_url = $params['note_photo'];
  205. }
  206. $entry->type = $type;
  207. $entry->save();
  208. // Send to the micropub endpoint if one is defined, and store the result
  209. $url = false;
  210. if($user->micropub_endpoint) {
  211. $text_content = 'Just ' . $verb . ': ' . $entry->content;
  212. $mp_properties = array(
  213. 'published' => [$published],
  214. 'created' => [$published],
  215. 'summary' => [$text_content]
  216. );
  217. $location = k($params, 'location');
  218. if($location) {
  219. $mp_properties['location'] = [$location];
  220. }
  221. if($entry->photo_url) {
  222. $mp_properties['photo'] = [$entry->photo_url];
  223. }
  224. $mp_properties[$verb] = [[
  225. 'type' => ['h-food'],
  226. 'properties' => [
  227. 'name' => $entry->content
  228. ]
  229. ]];
  230. $mp_request = array(
  231. 'type' => ['h-entry'],
  232. 'properties' => $mp_properties
  233. );
  234. $r = micropub_post($user->micropub_endpoint, $mp_request, $user->access_token);
  235. $request = $r['request'];
  236. $response = $r['response'];
  237. $entry->micropub_response = $response;
  238. // Check the response and look for a "Location" header containing the URL
  239. if($response && preg_match('/Location: (.+)/', $response, $match)) {
  240. $url = $match[1];
  241. $user->micropub_success = 1;
  242. $entry->micropub_success = 1;
  243. $entry->canonical_url = $url;
  244. } else {
  245. $entry->micropub_success = 0;
  246. }
  247. $entry->save();
  248. }
  249. if($url) {
  250. $app->redirect($url);
  251. } else {
  252. // TODO: Redirect to an error page or show an error on the teacup post page
  253. $url = Config::$base_url . $user->url . '/' . $entry->id;
  254. $app->redirect($url);
  255. }
  256. }
  257. });
  258. $app->post('/micropub/media', function() use($app) {
  259. if($user=require_login($app)) {
  260. $file = isset($_FILES['file']) ? $_FILES['file'] : null;
  261. $error = validate_photo($file);
  262. unset($_POST['null']);
  263. if(!$error) {
  264. $file_path = $file['tmp_name'];
  265. correct_photo_rotation($file_path);
  266. $r = micropub_media_post($user->micropub_media_endpoint, $user->access_token, $file_path);
  267. } else {
  268. $r = array('error' => $error);
  269. }
  270. $response = $r['response'];
  271. $url = null;
  272. if($response && preg_match('/Location: (.+)/', $response, $match)) {
  273. $url = trim($match[1]);
  274. } else {
  275. $r['error'] = "No 'Location' header in response.";
  276. $r['debug'] = $response;
  277. }
  278. $app->response()['Content-type'] = 'application/json';
  279. $app->response()->body(json_encode(array(
  280. 'location' => $url,
  281. 'error' => (isset($r['error']) ? $r['error'] : null),
  282. 'debug' => (isset($r['debug']) ? $r['debug'] : null),
  283. )));
  284. }
  285. });
  286. $app->get('/micropub/config', function() use($app) {
  287. if($user=require_login($app)) {
  288. $config = get_micropub_config($user);
  289. $app->response()['Content-type'] = 'application/json';
  290. $app->response()->body(json_encode($config));
  291. }
  292. });
  293. $app->get('/options.json', function() use($app) {
  294. if($user=require_login($app)) {
  295. $params = $app->request()->params();
  296. $options = get_entry_options($user->id, k($params,'latitude'), k($params,'longitude'));
  297. $html = partial('partials/entry-buttons', ['options'=>$options]);
  298. $app->response()['Content-type'] = 'application/json';
  299. $app->response()->body(json_encode([
  300. 'buttons'=>$html
  301. ]));
  302. }
  303. });
  304. $app->get('/map.png', function() use($app) {
  305. $url = static_map_service($_SERVER['QUERY_STRING']);
  306. $ch = curl_init($url);
  307. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  308. $img = curl_exec($ch);
  309. header('Expires: ' . gmdate('D, d M Y H:i:s', strtotime('+30 days')) . ' GMT');
  310. header('Pragma: cache');
  311. header('Cache-Control: private');
  312. $app->response()['Content-type'] = 'image/png';
  313. $app->response()->body($img);
  314. });
  315. $app->get('/:domain', function($domain) use($app) {
  316. $params = $app->request()->params();
  317. $user = ORM::for_table('users')->where('url', $domain)->find_one();
  318. if(!$user) {
  319. $app->notFound();
  320. return;
  321. }
  322. $per_page = 10;
  323. $entries = ORM::for_table('entries')->where('user_id', $user->id);
  324. if(array_key_exists('before', $params)) {
  325. $entries->where_lte('id', $params['before']);
  326. }
  327. $entries = $entries->limit($per_page)->order_by_desc('published')->find_many();
  328. if(count($entries) > 1) {
  329. $older = ORM::for_table('entries')->where('user_id', $user->id)
  330. ->where_lt('id', $entries[count($entries)-1]->id)->order_by_desc('published')->find_one();
  331. } else {
  332. $older = null;
  333. }
  334. if(count($entries) > 1) {
  335. $newer = ORM::for_table('entries')->where('user_id', $user->id)
  336. ->where_gte('id', $entries[0]->id)->order_by_asc('published')->offset($per_page)->find_one();
  337. } else {
  338. $newer = null;
  339. }
  340. if(!$newer) {
  341. // no new entry was found at the specific offset, so find the newest post to link to instead
  342. $newer = ORM::for_table('entries')->where('user_id', $user->id)
  343. ->order_by_desc('published')->limit(1)->find_one();
  344. if($newer && $newer->id == $entries[0]->id)
  345. $newer = false;
  346. }
  347. render('entries', array(
  348. 'title' => 'Teacup',
  349. 'entries' => $entries,
  350. 'user' => $user,
  351. 'older' => ($older ? $older->id : false),
  352. 'newer' => ($newer ? $newer->id : false)
  353. ));
  354. })->conditions(array(
  355. 'domain' => '[a-zA-Z0-9\.-]+\.[a-z]+'
  356. ));
  357. $app->get('/:domain/:entry', function($domain, $entry_id) use($app) {
  358. $user = ORM::for_table('users')->where('url', $domain)->find_one();
  359. if(!$user) {
  360. $app->notFound();
  361. return;
  362. }
  363. $entry = ORM::for_table('entries')->where('user_id', $user->id)->where('id', $entry_id)->find_one();
  364. if(!$entry) {
  365. $app->notFound();
  366. return;
  367. }
  368. render('entry', array(
  369. 'title' => 'Teacup',
  370. 'entry' => $entry,
  371. 'user' => $user
  372. ));
  373. })->conditions(array(
  374. 'domain' => '[a-zA-Z0-9\.-]+\.[a-z]+',
  375. 'entry' => '\d+'
  376. ));