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.

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