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.

394 lines
12 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. <?php
  2. function require_login(&$app) {
  3. $params = $app->request()->params();
  4. if(array_key_exists('token', $params)) {
  5. try {
  6. $data = JWT::decode($params['token'], Config::$jwtSecret);
  7. $_SESSION['user_id'] = $data->user_id;
  8. $_SESSION['me'] = $data->me;
  9. } catch(DomainException $e) {
  10. header('X-Error: DomainException');
  11. $app->redirect('/', 301);
  12. } catch(UnexpectedValueException $e) {
  13. header('X-Error: UnexpectedValueException');
  14. $app->redirect('/', 301);
  15. }
  16. }
  17. if(!array_key_exists('user_id', $_SESSION)) {
  18. $app->redirect('/');
  19. return false;
  20. } else {
  21. return ORM::for_table('users')->find_one($_SESSION['user_id']);
  22. }
  23. }
  24. function get_login(&$app) {
  25. if(array_key_exists('user_id', $_SESSION)) {
  26. return ORM::for_table('users')->find_one($_SESSION['user_id']);
  27. } else {
  28. return false;
  29. }
  30. }
  31. function generate_login_token() {
  32. return JWT::encode(array(
  33. 'user_id' => $_SESSION['user_id'],
  34. 'me' => $_SESSION['me'],
  35. 'created_at' => time()
  36. ), Config::$jwtSecret);
  37. }
  38. $app->get('/new', function() use($app) {
  39. if($user=require_login($app)) {
  40. // Get the last post and set the timezone offset to match
  41. $date_str = date('Y-m-d');
  42. $time_str = date('H:i:s');
  43. $tz_offset = '+0000';
  44. $last = ORM::for_table('entries')->where('user_id', $user->id)
  45. ->order_by_desc('published')->find_one();
  46. if(false && $last) {
  47. $seconds = $last->tz_offset;
  48. $tz_offset = tz_seconds_to_offset($seconds);
  49. // Create a date object in the local timezone given the offset
  50. $date = new DateTime();
  51. if($seconds > 0)
  52. $date->add(new DateInterval('PT'.$seconds.'S'));
  53. elseif($seconds < 0)
  54. $date->sub(new DateInterval('PT'.abs($seconds).'S'));
  55. $date_str = $date->format('Y-m-d');
  56. $time_str = $date->format('H:i:s');
  57. }
  58. // Initially populate the page with the list of options without considering location.
  59. // This way if browser location is disabled or not available, or JS is disabled, there
  60. // will still be a list of options presented on the page by the time it loads.
  61. // Javascript will replace the options after location is available.
  62. $html = render('new-post', array(
  63. 'title' => 'New Post',
  64. 'micropub_endpoint' => $user->micropub_endpoint,
  65. 'token_scope' => $user->token_scope,
  66. 'access_token' => $user->access_token,
  67. 'response_date' => $user->last_micropub_response_date,
  68. 'location_enabled' => $user->location_enabled,
  69. 'default_options' => get_entry_options($user->id),
  70. 'tz_offset' => $tz_offset,
  71. 'date_str' => $date_str,
  72. 'time_str' => $time_str,
  73. 'enable_array_micropub' => $user->enable_array_micropub
  74. ));
  75. $app->response()->body($html);
  76. }
  77. });
  78. $app->post('/prefs/enable-h-food', function() use($app){
  79. if($user=require_login($app)) {
  80. $user->enable_array_micropub = 1;
  81. $user->save();
  82. }
  83. $app->redirect('/new', 302);
  84. });
  85. $app->post('/prefs', function() use($app) {
  86. if($user=require_login($app)) {
  87. $params = $app->request()->params();
  88. $user->location_enabled = $params['enabled'];
  89. $user->save();
  90. }
  91. $app->response()->body(json_encode(array(
  92. 'result' => 'ok'
  93. )));
  94. });
  95. $app->get('/creating-a-token-endpoint', function() use($app) {
  96. $app->redirect('http://indiewebcamp.com/token-endpoint', 301);
  97. });
  98. $app->get('/creating-a-micropub-endpoint', function() use($app) {
  99. $html = render('creating-a-micropub-endpoint', array('title' => 'Creating a Micropub Endpoint'));
  100. $app->response()->body($html);
  101. });
  102. $app->get('/docs', function() use($app) {
  103. $html = render('docs', array('title' => 'Documentation'));
  104. $app->response()->body($html);
  105. });
  106. $app->get('/add-to-home', function() use($app) {
  107. $params = $app->request()->params();
  108. header("Cache-Control: no-cache, must-revalidate");
  109. if(array_key_exists('token', $params) && !session('add-to-home-started')) {
  110. unset($_SESSION['add-to-home-started']);
  111. // Verify the token and sign the user in
  112. try {
  113. $data = JWT::decode($params['token'], Config::$jwtSecret);
  114. $_SESSION['user_id'] = $data->user_id;
  115. $_SESSION['me'] = $data->me;
  116. $app->redirect('/new', 301);
  117. } catch(DomainException $e) {
  118. header('X-Error: DomainException');
  119. $app->redirect('/', 301);
  120. } catch(UnexpectedValueException $e) {
  121. header('X-Error: UnexpectedValueException');
  122. $app->redirect('/', 301);
  123. }
  124. } else {
  125. if($user=require_login($app)) {
  126. if(array_key_exists('start', $params)) {
  127. $_SESSION['add-to-home-started'] = true;
  128. $token = JWT::encode(array(
  129. 'user_id' => $_SESSION['user_id'],
  130. 'me' => $_SESSION['me'],
  131. 'created_at' => time()
  132. ), Config::$jwtSecret);
  133. $app->redirect('/add-to-home?token='.$token, 301);
  134. } else {
  135. unset($_SESSION['add-to-home-started']);
  136. $html = render('add-to-home', array('title' => 'Teacup'));
  137. $app->response()->body($html);
  138. }
  139. }
  140. }
  141. });
  142. $app->post('/post', function() use($app) {
  143. if($user=require_login($app)) {
  144. $params = $app->request()->params();
  145. // Remove any blank params
  146. $params = array_filter($params, function($v){
  147. return $v !== '';
  148. });
  149. // Store the post in the database
  150. $entry = ORM::for_table('entries')->create();
  151. $entry->user_id = $user->id;
  152. $location = false;
  153. if(k($params, 'location') && $location=parse_geo_uri($params['location'])) {
  154. $entry->latitude = $location['latitude'];
  155. $entry->longitude = $location['longitude'];
  156. }
  157. if(k($params,'note_date')) {
  158. // The post request is always going to have a date now
  159. $date_string = $params['note_date'] . 'T' . $params['note_time'] . $params['note_tzoffset'];
  160. $entry->published = date('Y-m-d H:i:s', strtotime($date_string));
  161. $entry->tz_offset = tz_offset_to_seconds($params['note_tzoffset']);
  162. $published = $date_string;
  163. } else {
  164. // Pebble doesn't send the date/time/timezone
  165. $entry->published = date('Y-m-d H:i:s');
  166. $published = date('c'); // for the micropub post
  167. if($location && ($timezone=get_timezone($location['latitude'], $location['longitude']))) {
  168. $entry->timezone = $timezone->getName();
  169. $entry->tz_offset = $timezone->getOffset(new DateTime());
  170. $now = new DateTime();
  171. $now->setTimeZone(new DateTimeZone($entry->timezone));
  172. $published = $now->format('c');
  173. }
  174. }
  175. if(k($params, 'drank')) {
  176. $entry->content = trim($params['drank']);
  177. $type = 'drink';
  178. $verb = 'drank';
  179. } elseif(k($params, 'drink')) {
  180. $entry->content = trim($params['drink']);
  181. $type = 'drink';
  182. $verb = 'drank';
  183. } elseif(k($params, 'eat')) {
  184. $entry->content = trim($params['eat']);
  185. $type = 'eat';
  186. $verb = 'ate';
  187. } elseif(k($params, 'custom_drink')) {
  188. $entry->content = trim($params['custom_drink']);
  189. $type = 'drink';
  190. $verb = 'drank';
  191. } elseif(k($params, 'custom_eat')) {
  192. $entry->content = trim($params['custom_eat']);
  193. $type = 'eat';
  194. $verb = 'ate';
  195. }
  196. $entry->type = $type;
  197. $entry->save();
  198. // Send to the micropub endpoint if one is defined, and store the result
  199. $url = false;
  200. if($user->micropub_endpoint) {
  201. $text_content = 'Just ' . $verb . ': ' . $entry->content;
  202. $mp_request = array(
  203. 'h' => 'entry',
  204. 'published' => $published,
  205. 'created' => $published,
  206. 'location' => k($params, 'location'),
  207. 'summary' => $text_content
  208. );
  209. if($user->enable_array_micropub) {
  210. $mp_request[$verb] = [
  211. 'type' => 'h-food',
  212. 'properties' => [
  213. 'name' => $entry->content
  214. ]
  215. ];
  216. } else {
  217. $mp_request['p3k-food'] = $entry->content;
  218. $mp_request['p3k-type'] = $type;
  219. }
  220. $r = micropub_post($user->micropub_endpoint, $mp_request, $user->access_token);
  221. $request = $r['request'];
  222. $response = $r['response'];
  223. $entry->micropub_response = $response;
  224. // Check the response and look for a "Location" header containing the URL
  225. if($response && preg_match('/Location: (.+)/', $response, $match)) {
  226. $url = $match[1];
  227. $user->micropub_success = 1;
  228. $entry->micropub_success = 1;
  229. $entry->canonical_url = $url;
  230. } else {
  231. $entry->micropub_success = 0;
  232. }
  233. $entry->save();
  234. }
  235. if($url) {
  236. $app->redirect($url);
  237. } else {
  238. // TODO: Redirect to an error page or show an error on the teacup post page
  239. $url = Config::$base_url . $user->url . '/' . $entry->id;
  240. $app->redirect($url);
  241. }
  242. }
  243. });
  244. $app->get('/options.json', function() use($app) {
  245. if($user=require_login($app)) {
  246. $params = $app->request()->params();
  247. $options = get_entry_options($user->id, k($params,'latitude'), k($params,'longitude'));
  248. $html = partial('partials/entry-buttons', ['options'=>$options]);
  249. $app->response()['Content-type'] = 'application/json';
  250. $app->response()->body(json_encode([
  251. 'buttons'=>$html
  252. ]));
  253. }
  254. });
  255. $app->get('/map.png', function() use($app) {
  256. $url = static_map_service($_SERVER['QUERY_STRING']);
  257. $ch = curl_init($url);
  258. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  259. $img = curl_exec($ch);
  260. header('Expires: ' . gmdate('D, d M Y H:i:s', strtotime('+30 days')) . ' GMT');
  261. header('Pragma: cache');
  262. header('Cache-Control: private');
  263. $app->response()['Content-type'] = 'image/png';
  264. $app->response()->body($img);
  265. });
  266. /*
  267. $app->get('/teacup.appcache', function() use($app) {
  268. $content = partial('appcache');
  269. $app->response()['Content-type'] = 'text/cache-manifest';
  270. $app->response()->body($content);
  271. });
  272. */
  273. $app->get('/:domain', function($domain) use($app) {
  274. $params = $app->request()->params();
  275. $user = ORM::for_table('users')->where('url', $domain)->find_one();
  276. if(!$user) {
  277. $app->notFound();
  278. return;
  279. }
  280. $per_page = 10;
  281. $entries = ORM::for_table('entries')->where('user_id', $user->id);
  282. if(array_key_exists('before', $params)) {
  283. $entries->where_lte('id', $params['before']);
  284. }
  285. $entries = $entries->limit($per_page)->order_by_desc('published')->find_many();
  286. if(count($entries) > 1) {
  287. $older = ORM::for_table('entries')->where('user_id', $user->id)
  288. ->where_lt('id', $entries[count($entries)-1]->id)->order_by_desc('published')->find_one();
  289. } else {
  290. $older = null;
  291. }
  292. if(count($entries) > 1) {
  293. $newer = ORM::for_table('entries')->where('user_id', $user->id)
  294. ->where_gte('id', $entries[0]->id)->order_by_asc('published')->offset($per_page)->find_one();
  295. } else {
  296. $newer = null;
  297. }
  298. if(!$newer) {
  299. // no new entry was found at the specific offset, so find the newest post to link to instead
  300. $newer = ORM::for_table('entries')->where('user_id', $user->id)
  301. ->order_by_desc('published')->limit(1)->find_one();
  302. if($newer && $newer->id == $entries[0]->id)
  303. $newer = false;
  304. }
  305. $html = render('entries', array(
  306. 'title' => 'Teacup',
  307. 'entries' => $entries,
  308. 'user' => $user,
  309. 'older' => ($older ? $older->id : false),
  310. 'newer' => ($newer ? $newer->id : false)
  311. ));
  312. $app->response()->body($html);
  313. })->conditions(array(
  314. 'domain' => '[a-zA-Z0-9\.-]+\.[a-z]+'
  315. ));
  316. $app->get('/:domain/:entry', function($domain, $entry_id) use($app) {
  317. $user = ORM::for_table('users')->where('url', $domain)->find_one();
  318. if(!$user) {
  319. $app->notFound();
  320. return;
  321. }
  322. $entry = ORM::for_table('entries')->where('user_id', $user->id)->where('id', $entry_id)->find_one();
  323. if(!$entry) {
  324. $app->notFound();
  325. return;
  326. }
  327. $html = render('entry', array(
  328. 'title' => 'Teacup',
  329. 'entry' => $entry,
  330. 'user' => $user
  331. ));
  332. $app->response()->body($html);
  333. })->conditions(array(
  334. 'domain' => '[a-zA-Z0-9\.-]+\.[a-z]+',
  335. 'entry' => '\d+'
  336. ));