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.

430 lines
13 KiB

10 years ago
10 years ago
10 years ago
9 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. $html = 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. $app->response()->body($html);
  65. }
  66. });
  67. $app->post('/prefs/enable-h-food', function() use($app){
  68. if($user=require_login($app)) {
  69. $user->enable_array_micropub = 1;
  70. $user->save();
  71. }
  72. $app->redirect('/new', 302);
  73. });
  74. $app->post('/prefs', function() use($app) {
  75. if($user=require_login($app)) {
  76. $params = $app->request()->params();
  77. $user->location_enabled = $params['enabled'];
  78. $user->save();
  79. }
  80. $app->response()->body(json_encode(array(
  81. 'result' => 'ok'
  82. )));
  83. });
  84. $app->get('/creating-a-token-endpoint', function() use($app) {
  85. $app->redirect('http://indiewebcamp.com/token-endpoint', 301);
  86. });
  87. $app->get('/creating-a-micropub-endpoint', function() use($app) {
  88. $html = render('creating-a-micropub-endpoint', array('title' => 'Creating a Micropub Endpoint'));
  89. $app->response()->body($html);
  90. });
  91. $app->get('/docs', function() use($app) {
  92. $html = render('docs', array('title' => 'Documentation'));
  93. $app->response()->body($html);
  94. });
  95. $app->get('/add-to-home', function() use($app) {
  96. $params = $app->request()->params();
  97. header("Cache-Control: no-cache, must-revalidate");
  98. if(array_key_exists('token', $params) && !isset($_SESSION['add-to-home-started'])) {
  99. // Verify the token and sign the user in
  100. try {
  101. $data = JWT::decode($params['token'], Config::$jwtSecret, ['HS256']);
  102. $_SESSION['user_id'] = $data->user_id;
  103. $_SESSION['me'] = $data->me;
  104. $app->redirect('/new', 302);
  105. } catch(DomainException $e) {
  106. header('X-Error: DomainException');
  107. $app->redirect('/?error=domain', 302);
  108. } catch(SignatureInvalidException $e) {
  109. header('X-Error: SignatureInvalidException');
  110. $app->redirect('/?error=invalid', 302);
  111. } catch(ErrorException $e) {
  112. $app->redirect('/?error=unknown', 302);
  113. }
  114. } else {
  115. if($user=require_login($app)) {
  116. if(array_key_exists('start', $params)) {
  117. $_SESSION['add-to-home-started'] = 1;
  118. $token = JWT::encode(array(
  119. 'user_id' => $_SESSION['user_id'],
  120. 'me' => $_SESSION['me'],
  121. 'created_at' => time()
  122. ), Config::$jwtSecret);
  123. $app->redirect('/add-to-home?token='.$token, 302);
  124. } else {
  125. unset($_SESSION['add-to-home-started']);
  126. $html = render('add-to-home', array('title' => 'Teacup'));
  127. $app->response()->body($html);
  128. }
  129. }
  130. }
  131. });
  132. $app->post('/post', function() use($app) {
  133. if($user=require_login($app)) {
  134. $params = $app->request()->params();
  135. // Remove any blank params
  136. $params = array_filter($params, function($v){
  137. return $v !== '';
  138. });
  139. // Store the post in the database
  140. $entry = ORM::for_table('entries')->create();
  141. $entry->user_id = $user->id;
  142. $location = false;
  143. if(k($params, 'location') && $location=parse_geo_uri($params['location'])) {
  144. $entry->latitude = $location['latitude'];
  145. $entry->longitude = $location['longitude'];
  146. }
  147. if(k($params,'note_date')) {
  148. // The post request is always going to have a date now
  149. $date_string = $params['note_date'] . 'T' . $params['note_time'] . $params['note_tzoffset'];
  150. $entry->published = date('Y-m-d H:i:s', strtotime($date_string));
  151. $entry->tz_offset = tz_offset_to_seconds($params['note_tzoffset']);
  152. $published = $date_string;
  153. } else {
  154. // Pebble doesn't send the date/time/timezone
  155. $entry->published = date('Y-m-d H:i:s');
  156. $published = date('c'); // for the micropub post
  157. if($location && ($timezone=get_timezone($location['latitude'], $location['longitude']))) {
  158. $entry->timezone = $timezone->getName();
  159. $entry->tz_offset = $timezone->getOffset(new DateTime());
  160. $now = new DateTime();
  161. $now->setTimeZone(new DateTimeZone($entry->timezone));
  162. $published = $now->format('c');
  163. }
  164. }
  165. if(k($params, 'drank')) {
  166. $entry->content = trim($params['drank']);
  167. $type = 'drink';
  168. $verb = 'drank';
  169. } elseif(k($params, 'drink')) {
  170. $entry->content = trim($params['drink']);
  171. $type = 'drink';
  172. $verb = 'drank';
  173. } elseif(k($params, 'eat')) {
  174. $entry->content = trim($params['eat']);
  175. $type = 'eat';
  176. $verb = 'ate';
  177. } elseif(k($params, 'custom_drink')) {
  178. $entry->content = trim($params['custom_drink']);
  179. $type = 'drink';
  180. $verb = 'drank';
  181. } elseif(k($params, 'custom_eat')) {
  182. $entry->content = trim($params['custom_eat']);
  183. $type = 'eat';
  184. $verb = 'ate';
  185. }
  186. if($user->micropub_media_endpoint && k($params, 'note_photo')) {
  187. $entry->photo_url = $params['note_photo'];
  188. }
  189. $entry->type = $type;
  190. $entry->save();
  191. // Send to the micropub endpoint if one is defined, and store the result
  192. $url = false;
  193. if($user->micropub_endpoint) {
  194. $text_content = 'Just ' . $verb . ': ' . $entry->content;
  195. $mp_request = array(
  196. 'h' => 'entry',
  197. 'published' => $published,
  198. 'created' => $published,
  199. 'location' => k($params, 'location'),
  200. 'summary' => $text_content
  201. );
  202. if($entry->photo_url) {
  203. $mp_request['photo'] = $entry->photo_url;
  204. }
  205. if($user->enable_array_micropub) {
  206. $mp_request[$verb] = [
  207. 'type' => 'h-food',
  208. 'properties' => [
  209. 'name' => $entry->content
  210. ]
  211. ];
  212. } else {
  213. $mp_request['p3k-food'] = $entry->content;
  214. $mp_request['p3k-type'] = $type;
  215. }
  216. $r = micropub_post($user->micropub_endpoint, $mp_request, $user->access_token);
  217. $request = $r['request'];
  218. $response = $r['response'];
  219. $entry->micropub_response = $response;
  220. // Check the response and look for a "Location" header containing the URL
  221. if($response && preg_match('/Location: (.+)/', $response, $match)) {
  222. $url = $match[1];
  223. $user->micropub_success = 1;
  224. $entry->micropub_success = 1;
  225. $entry->canonical_url = $url;
  226. } else {
  227. $entry->micropub_success = 0;
  228. }
  229. $entry->save();
  230. }
  231. if($url) {
  232. $app->redirect($url);
  233. } else {
  234. // TODO: Redirect to an error page or show an error on the teacup post page
  235. $url = Config::$base_url . $user->url . '/' . $entry->id;
  236. $app->redirect($url);
  237. }
  238. }
  239. });
  240. $app->post('/micropub/media', function() use($app) {
  241. if($user=require_login($app)) {
  242. $file = isset($_FILES['file']) ? $_FILES['file'] : null;
  243. $error = validate_photo($file);
  244. unset($_POST['null']);
  245. if(!$error) {
  246. $file_path = $file['tmp_name'];
  247. correct_photo_rotation($file_path);
  248. $r = micropub_media_post($user->micropub_media_endpoint, $user->access_token, $file_path);
  249. } else {
  250. $r = array('error' => $error);
  251. }
  252. $response = $r['response'];
  253. $url = null;
  254. if($response && preg_match('/Location: (.+)/', $response, $match)) {
  255. $url = trim($match[1]);
  256. } else {
  257. $r['error'] = "No 'Location' header in response.";
  258. $r['debug'] = $response;
  259. }
  260. $app->response()['Content-type'] = 'application/json';
  261. $app->response()->body(json_encode(array(
  262. 'location' => $url,
  263. 'error' => (isset($r['error']) ? $r['error'] : null),
  264. 'debug' => (isset($r['debug']) ? $r['debug'] : null),
  265. )));
  266. }
  267. });
  268. $app->get('/micropub/config', function() use($app) {
  269. if($user=require_login($app)) {
  270. $config = get_micropub_config($user);
  271. $app->response()['Content-type'] = 'application/json';
  272. $app->response()->body(json_encode($config));
  273. }
  274. });
  275. $app->get('/options.json', function() use($app) {
  276. if($user=require_login($app)) {
  277. $params = $app->request()->params();
  278. $options = get_entry_options($user->id, k($params,'latitude'), k($params,'longitude'));
  279. $html = partial('partials/entry-buttons', ['options'=>$options]);
  280. $app->response()['Content-type'] = 'application/json';
  281. $app->response()->body(json_encode([
  282. 'buttons'=>$html
  283. ]));
  284. }
  285. });
  286. $app->get('/map.png', function() use($app) {
  287. $url = static_map_service($_SERVER['QUERY_STRING']);
  288. $ch = curl_init($url);
  289. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  290. $img = curl_exec($ch);
  291. header('Expires: ' . gmdate('D, d M Y H:i:s', strtotime('+30 days')) . ' GMT');
  292. header('Pragma: cache');
  293. header('Cache-Control: private');
  294. $app->response()['Content-type'] = 'image/png';
  295. $app->response()->body($img);
  296. });
  297. /*
  298. $app->get('/teacup.appcache', function() use($app) {
  299. $content = partial('appcache');
  300. $app->response()['Content-type'] = 'text/cache-manifest';
  301. $app->response()->body($content);
  302. });
  303. */
  304. $app->get('/:domain', function($domain) use($app) {
  305. $params = $app->request()->params();
  306. $user = ORM::for_table('users')->where('url', $domain)->find_one();
  307. if(!$user) {
  308. $app->notFound();
  309. return;
  310. }
  311. $per_page = 10;
  312. $entries = ORM::for_table('entries')->where('user_id', $user->id);
  313. if(array_key_exists('before', $params)) {
  314. $entries->where_lte('id', $params['before']);
  315. }
  316. $entries = $entries->limit($per_page)->order_by_desc('published')->find_many();
  317. if(count($entries) > 1) {
  318. $older = ORM::for_table('entries')->where('user_id', $user->id)
  319. ->where_lt('id', $entries[count($entries)-1]->id)->order_by_desc('published')->find_one();
  320. } else {
  321. $older = null;
  322. }
  323. if(count($entries) > 1) {
  324. $newer = ORM::for_table('entries')->where('user_id', $user->id)
  325. ->where_gte('id', $entries[0]->id)->order_by_asc('published')->offset($per_page)->find_one();
  326. } else {
  327. $newer = null;
  328. }
  329. if(!$newer) {
  330. // no new entry was found at the specific offset, so find the newest post to link to instead
  331. $newer = ORM::for_table('entries')->where('user_id', $user->id)
  332. ->order_by_desc('published')->limit(1)->find_one();
  333. if($newer && $newer->id == $entries[0]->id)
  334. $newer = false;
  335. }
  336. $html = render('entries', array(
  337. 'title' => 'Teacup',
  338. 'entries' => $entries,
  339. 'user' => $user,
  340. 'older' => ($older ? $older->id : false),
  341. 'newer' => ($newer ? $newer->id : false)
  342. ));
  343. $app->response()->body($html);
  344. })->conditions(array(
  345. 'domain' => '[a-zA-Z0-9\.-]+\.[a-z]+'
  346. ));
  347. $app->get('/:domain/:entry', function($domain, $entry_id) use($app) {
  348. $user = ORM::for_table('users')->where('url', $domain)->find_one();
  349. if(!$user) {
  350. $app->notFound();
  351. return;
  352. }
  353. $entry = ORM::for_table('entries')->where('user_id', $user->id)->where('id', $entry_id)->find_one();
  354. if(!$entry) {
  355. $app->notFound();
  356. return;
  357. }
  358. $html = render('entry', array(
  359. 'title' => 'Teacup',
  360. 'entry' => $entry,
  361. 'user' => $user
  362. ));
  363. $app->response()->body($html);
  364. })->conditions(array(
  365. 'domain' => '[a-zA-Z0-9\.-]+\.[a-z]+',
  366. 'entry' => '\d+'
  367. ));