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.

385 lines
11 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_appcache' => true
  74. ));
  75. $app->response()->body($html);
  76. }
  77. });
  78. $app->post('/prefs', function() use($app) {
  79. if($user=require_login($app)) {
  80. $params = $app->request()->params();
  81. $user->location_enabled = $params['enabled'];
  82. $user->save();
  83. }
  84. $app->response()->body(json_encode(array(
  85. 'result' => 'ok'
  86. )));
  87. });
  88. $app->get('/creating-a-token-endpoint', function() use($app) {
  89. $app->redirect('http://indiewebcamp.com/token-endpoint', 301);
  90. });
  91. $app->get('/creating-a-micropub-endpoint', function() use($app) {
  92. $html = render('creating-a-micropub-endpoint', array('title' => 'Creating a Micropub Endpoint'));
  93. $app->response()->body($html);
  94. });
  95. $app->get('/docs', function() use($app) {
  96. $html = render('docs', array('title' => 'Documentation'));
  97. $app->response()->body($html);
  98. });
  99. $app->get('/add-to-home', function() use($app) {
  100. $params = $app->request()->params();
  101. header("Cache-Control: no-cache, must-revalidate");
  102. if(array_key_exists('token', $params) && !session('add-to-home-started')) {
  103. unset($_SESSION['add-to-home-started']);
  104. // Verify the token and sign the user in
  105. try {
  106. $data = JWT::decode($params['token'], Config::$jwtSecret);
  107. $_SESSION['user_id'] = $data->user_id;
  108. $_SESSION['me'] = $data->me;
  109. $app->redirect('/new', 301);
  110. } catch(DomainException $e) {
  111. header('X-Error: DomainException');
  112. $app->redirect('/', 301);
  113. } catch(UnexpectedValueException $e) {
  114. header('X-Error: UnexpectedValueException');
  115. $app->redirect('/', 301);
  116. }
  117. } else {
  118. if($user=require_login($app)) {
  119. if(array_key_exists('start', $params)) {
  120. $_SESSION['add-to-home-started'] = true;
  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, 301);
  127. } else {
  128. unset($_SESSION['add-to-home-started']);
  129. $html = render('add-to-home', array('title' => 'Teacup'));
  130. $app->response()->body($html);
  131. }
  132. }
  133. }
  134. });
  135. $app->post('/post', function() use($app) {
  136. if($user=require_login($app)) {
  137. $params = $app->request()->params();
  138. // Remove any blank params
  139. $params = array_filter($params, function($v){
  140. return $v !== '';
  141. });
  142. // Store the post in the database
  143. $entry = ORM::for_table('entries')->create();
  144. $entry->user_id = $user->id;
  145. $location = false;
  146. if(k($params, 'location') && $location=parse_geo_uri($params['location'])) {
  147. $entry->latitude = $location['latitude'];
  148. $entry->longitude = $location['longitude'];
  149. }
  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. if(k($params, 'drank')) {
  156. $entry->content = trim($params['drank']);
  157. $type = 'drink';
  158. $verb = 'drank';
  159. } elseif(k($params, 'drink')) {
  160. $entry->content = trim($params['drink']);
  161. $type = 'drink';
  162. $verb = 'drank';
  163. } elseif(k($params, 'eat')) {
  164. $entry->content = trim($params['eat']);
  165. $type = 'eat';
  166. $verb = 'ate';
  167. } elseif(k($params, 'custom_drink')) {
  168. $entry->content = trim($params['custom_drink']);
  169. $type = 'drink';
  170. $verb = 'drank';
  171. } elseif(k($params, 'custom_eat')) {
  172. $entry->content = trim($params['custom_eat']);
  173. $type = 'eat';
  174. $verb = 'ate';
  175. }
  176. $entry->type = $type;
  177. $entry->save();
  178. // Send to the micropub endpoint if one is defined, and store the result
  179. $url = false;
  180. if($user->micropub_endpoint) {
  181. $text_content = 'Just ' . $verb . ': ' . $entry->content;
  182. $mp_request = array(
  183. 'h' => 'entry',
  184. 'published' => $published,
  185. 'p3k-food' => $entry->content,
  186. 'p3k-type' => $type,
  187. 'location' => k($params, 'location'),
  188. 'summary' => $text_content
  189. );
  190. $r = micropub_post($user->micropub_endpoint, $mp_request, $user->access_token);
  191. $request = $r['request'];
  192. $response = $r['response'];
  193. $entry->micropub_response = $response;
  194. // Check the response and look for a "Location" header containing the URL
  195. if($response && preg_match('/Location: (.+)/', $response, $match)) {
  196. $url = $match[1];
  197. $user->micropub_success = 1;
  198. $entry->micropub_success = 1;
  199. $entry->canonical_url = $url;
  200. } else {
  201. $entry->micropub_success = 0;
  202. }
  203. $entry->save();
  204. }
  205. if($url) {
  206. $app->redirect($url);
  207. } else {
  208. // TODO: Redirect to an error page or show an error on the teacup post page
  209. $url = Config::$base_url . $user->url . '/' . $entry->id;
  210. $app->redirect($url);
  211. }
  212. }
  213. });
  214. $app->get('/options.json', function() use($app) {
  215. if($user=require_login($app)) {
  216. $params = $app->request()->params();
  217. $options = get_entry_options($user->id, k($params,'latitude'), k($params,'longitude'));
  218. $html = partial('partials/entry-buttons', ['options'=>$options]);
  219. $tz_offset = '+0000';
  220. $date_str = date('Y-m-d');
  221. $time_str = date('H:i:s');
  222. if(k($params,'latitude')) {
  223. if($timezone=get_timezone($params['latitude'], $params['longitude'])) {
  224. $seconds = $timezone->getOffset(new DateTime());
  225. $tz_offset = tz_seconds_to_offset($seconds);
  226. // Create a date object in the local timezone given the offset
  227. $date = new DateTime();
  228. if($seconds > 0)
  229. $date->add(new DateInterval('PT'.$seconds.'S'));
  230. elseif($seconds < 0)
  231. $date->sub(new DateInterval('PT'.abs($seconds).'S'));
  232. $date_str = $date->format('Y-m-d');
  233. $time_str = $date->format('H:i:s');
  234. }
  235. }
  236. $app->response()['Content-type'] = 'application/json';
  237. $app->response()->body(json_encode([
  238. 'buttons'=>$html,
  239. 'tz_offset'=>$tz_offset,
  240. 'date_str'=>$date_str,
  241. 'time_str'=>$time_str
  242. ]));
  243. }
  244. });
  245. $app->get('/map.png', function() use($app) {
  246. $url = static_map_service($_SERVER['QUERY_STRING']);
  247. $ch = curl_init($url);
  248. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  249. $img = curl_exec($ch);
  250. header('Expires: ' . gmdate('D, d M Y H:i:s', strtotime('+30 days')) . ' GMT');
  251. header('Pragma: cache');
  252. header('Cache-Control: private');
  253. $app->response()['Content-type'] = 'image/png';
  254. $app->response()->body($img);
  255. });
  256. $app->get('/-teacup.appcache', function() use($app) {
  257. $content = partial('appcache');
  258. $app->response()['Content-type'] = 'text/cache-manifest';
  259. $app->response()->body($content);
  260. });
  261. $app->get('/:domain', function($domain) use($app) {
  262. $params = $app->request()->params();
  263. $user = ORM::for_table('users')->where('url', $domain)->find_one();
  264. if(!$user) {
  265. $app->notFound();
  266. return;
  267. }
  268. $per_page = 10;
  269. $entries = ORM::for_table('entries')->where('user_id', $user->id);
  270. if(array_key_exists('before', $params)) {
  271. $entries->where_lte('id', $params['before']);
  272. }
  273. $entries = $entries->limit($per_page)->order_by_desc('published')->find_many();
  274. if(count($entries) > 1) {
  275. $older = ORM::for_table('entries')->where('user_id', $user->id)
  276. ->where_lt('id', $entries[count($entries)-1]->id)->order_by_desc('published')->find_one();
  277. } else {
  278. $older = null;
  279. }
  280. if(count($entries) > 1) {
  281. $newer = ORM::for_table('entries')->where('user_id', $user->id)
  282. ->where_gte('id', $entries[0]->id)->order_by_asc('published')->offset($per_page)->find_one();
  283. } else {
  284. $newer = null;
  285. }
  286. if(!$newer) {
  287. // no new entry was found at the specific offset, so find the newest post to link to instead
  288. $newer = ORM::for_table('entries')->where('user_id', $user->id)
  289. ->order_by_desc('published')->limit(1)->find_one();
  290. if($newer && $newer->id == $entries[0]->id)
  291. $newer = false;
  292. }
  293. $html = render('entries', array(
  294. 'title' => 'Teacup',
  295. 'entries' => $entries,
  296. 'user' => $user,
  297. 'older' => ($older ? $older->id : false),
  298. 'newer' => ($newer ? $newer->id : false)
  299. ));
  300. $app->response()->body($html);
  301. })->conditions(array(
  302. 'domain' => '[a-zA-Z0-9\.-]+\.[a-z]+'
  303. ));
  304. $app->get('/:domain/:entry', function($domain, $entry_id) use($app) {
  305. $user = ORM::for_table('users')->where('url', $domain)->find_one();
  306. if(!$user) {
  307. $app->notFound();
  308. return;
  309. }
  310. $entry = ORM::for_table('entries')->where('user_id', $user->id)->where('id', $entry_id)->find_one();
  311. if(!$entry) {
  312. $app->notFound();
  313. return;
  314. }
  315. $html = render('entry', array(
  316. 'title' => 'Teacup',
  317. 'entry' => $entry,
  318. 'user' => $user
  319. ));
  320. $app->response()->body($html);
  321. })->conditions(array(
  322. 'domain' => '[a-zA-Z0-9\.-]+\.[a-z]+',
  323. 'entry' => '\d+'
  324. ));