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