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.

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