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

10 years ago
10 years ago
10 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_request = array(
  214. 'h' => 'entry',
  215. 'published' => $published,
  216. 'created' => $published,
  217. 'location' => k($params, 'location'),
  218. 'summary' => $text_content
  219. );
  220. if($entry->photo_url) {
  221. $mp_request['photo'] = $entry->photo_url;
  222. }
  223. if($user->enable_array_micropub) {
  224. $mp_request[$verb] = [
  225. 'type' => 'h-food',
  226. 'properties' => [
  227. 'name' => $entry->content
  228. ]
  229. ];
  230. } else {
  231. $mp_request['p3k-food'] = $entry->content;
  232. $mp_request['p3k-type'] = $type;
  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. ));