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.

553 lines
17 KiB

9 years ago
  1. <?php
  2. ORM::configure('mysql:host=' . Config::$dbHost . ';dbname=' . Config::$dbName);
  3. ORM::configure('username', Config::$dbUsername);
  4. ORM::configure('password', Config::$dbPassword);
  5. function render($page, $data) {
  6. global $app;
  7. return $app->render('layout.php', array_merge($data, array('page' => $page)));
  8. };
  9. function partial($template, $data=array(), $debug=false) {
  10. global $app;
  11. if($debug) {
  12. $tpl = new Savant3(\Slim\Extras\Views\Savant::$savantOptions);
  13. echo '<pre>' . $tpl->fetch($template . '.php') . '</pre>';
  14. return '';
  15. }
  16. ob_start();
  17. $tpl = new Savant3(\Slim\Extras\Views\Savant::$savantOptions);
  18. foreach($data as $k=>$v) {
  19. $tpl->{$k} = $v;
  20. }
  21. $tpl->display($template . '.php');
  22. return ob_get_clean();
  23. }
  24. function js_bookmarklet($partial, $context) {
  25. return str_replace('+','%20',urlencode(str_replace(array("\n"),array(''),partial($partial, $context))));
  26. }
  27. function session($key) {
  28. if(array_key_exists($key, $_SESSION))
  29. return $_SESSION[$key];
  30. else
  31. return null;
  32. }
  33. function k($a, $k, $default=null) {
  34. if(is_array($k)) {
  35. $result = true;
  36. foreach($k as $key) {
  37. $result = $result && array_key_exists($key, $a);
  38. }
  39. return $result;
  40. } else {
  41. if(is_array($a) && array_key_exists($k, $a) && $a[$k])
  42. return $a[$k];
  43. elseif(is_object($a) && property_exists($a, $k) && $a->$k)
  44. return $a->$k;
  45. else
  46. return $default;
  47. }
  48. }
  49. function parse_geo_uri($uri) {
  50. if(preg_match('/geo:([\-\+]?[0-9\.]+),([\-\+]?[0-9\.]+)/', $uri, $match)) {
  51. return array(
  52. 'latitude' => (double)$match[1],
  53. 'longitude' => (double)$match[2],
  54. );
  55. } else {
  56. return false;
  57. }
  58. }
  59. function get_timezone($lat, $lng) {
  60. try {
  61. $ch = curl_init();
  62. curl_setopt($ch, CURLOPT_URL, 'http://atlas.p3k.io/api/timezone?latitude='.$lat.'&longitude='.$lng);
  63. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  64. $response = curl_exec($ch);
  65. $tz = @json_decode($response);
  66. if($tz)
  67. return new DateTimeZone($tz->timezone);
  68. } catch(Exception $e) {
  69. return null;
  70. }
  71. return null;
  72. }
  73. if(!function_exists('http_build_url')) {
  74. function http_build_url($parsed_url) {
  75. $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
  76. $host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
  77. $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
  78. $user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
  79. $pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
  80. $pass = ($user || $pass) ? "$pass@" : '';
  81. $path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
  82. $query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
  83. $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
  84. return "$scheme$user$pass$host$port$path$query$fragment";
  85. }
  86. }
  87. function micropub_post($endpoint, $params, $access_token) {
  88. $ch = curl_init();
  89. curl_setopt($ch, CURLOPT_URL, $endpoint);
  90. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  91. 'Authorization: Bearer ' . $access_token
  92. ));
  93. curl_setopt($ch, CURLOPT_POST, true);
  94. $post = http_build_query(array_merge(array(
  95. 'access_token' => $access_token,
  96. 'h' => 'entry'
  97. ), $params));
  98. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  99. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  100. curl_setopt($ch, CURLOPT_HEADER, true);
  101. curl_setopt($ch, CURLINFO_HEADER_OUT, true);
  102. $response = curl_exec($ch);
  103. $error = curl_error($ch);
  104. $sent_headers = curl_getinfo($ch, CURLINFO_HEADER_OUT);
  105. $request = $sent_headers . $post;
  106. return array(
  107. 'request' => $request,
  108. 'response' => $response,
  109. 'error' => $error,
  110. 'curlinfo' => curl_getinfo($ch)
  111. );
  112. }
  113. function micropub_media_post($endpoint, $access_token, $file) {
  114. $ch = curl_init();
  115. curl_setopt($ch, CURLOPT_URL, $endpoint);
  116. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  117. 'Authorization: Bearer ' . $access_token
  118. ));
  119. curl_setopt($ch, CURLOPT_POST, true);
  120. $post = [
  121. 'photo' => new CURLFile($file)
  122. ];
  123. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  124. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  125. curl_setopt($ch, CURLOPT_HEADER, true);
  126. curl_setopt($ch, CURLINFO_HEADER_OUT, true);
  127. $response = curl_exec($ch);
  128. $error = curl_error($ch);
  129. $sent_headers = curl_getinfo($ch, CURLINFO_HEADER_OUT);
  130. return array(
  131. 'response' => $response,
  132. 'error' => $error,
  133. 'curlinfo' => curl_getinfo($ch)
  134. );
  135. }
  136. function micropub_get($endpoint, $params, $access_token) {
  137. $url = parse_url($endpoint);
  138. if(!k($url, 'query')) {
  139. $url['query'] = http_build_query($params);
  140. } else {
  141. $url['query'] .= '&' . http_build_query($params);
  142. }
  143. $endpoint = http_build_url($url);
  144. $ch = curl_init();
  145. curl_setopt($ch, CURLOPT_URL, $endpoint);
  146. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  147. 'Authorization: Bearer ' . $access_token,
  148. 'Accept: application/json',
  149. ));
  150. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  151. $response = curl_exec($ch);
  152. $data = array();
  153. if($response) {
  154. $data = @json_decode($response, true);
  155. }
  156. $error = curl_error($ch);
  157. return array(
  158. 'response' => $response,
  159. 'data' => $data,
  160. 'error' => $error,
  161. 'curlinfo' => curl_getinfo($ch)
  162. );
  163. }
  164. function get_micropub_config(&$user) {
  165. $targets = array();
  166. $r = micropub_get($user->micropub_endpoint, [], $user->access_token);
  167. if(array_key_exists('media_endpoint', $r['data'])) {
  168. $user->micropub_media_endpoint = $r['data']['media_endpoint'];
  169. $user->save();
  170. }
  171. return array(
  172. 'response' => $r
  173. );
  174. }
  175. function build_static_map_url($latitude, $longitude, $height, $width, $zoom) {
  176. return '/map.png?marker[]=lat:' . $latitude . ';lng:' . $longitude . ';icon:small-green-cutout&basemap=topo&width=' . $width . '&height=' . $height . '&zoom=' . $zoom;
  177. }
  178. function static_map_service($query) {
  179. return 'https://atlas.p3k.io/map/img?' . $query;
  180. }
  181. function relative_time($date) {
  182. static $rel;
  183. if(!isset($rel)) {
  184. $config = array(
  185. 'language' => '\RelativeTime\Languages\English',
  186. 'separator' => ', ',
  187. 'suffix' => true,
  188. 'truncate' => 1,
  189. );
  190. $rel = new \RelativeTime\RelativeTime($config);
  191. }
  192. return $rel->timeAgo($date);
  193. }
  194. function date_iso8601($date_string, $tz_offset) {
  195. $date = new DateTime($date_string);
  196. if($tz_offset > 0)
  197. $date->add(new DateInterval('PT'.$tz_offset.'S'));
  198. elseif($tz_offset < 0)
  199. $date->sub(new DateInterval('PT'.abs($tz_offset).'S'));
  200. $tz = tz_seconds_to_offset($tz_offset);
  201. return $date->format('Y-m-d\TH:i:s') . $tz;
  202. }
  203. function tz_seconds_to_offset($seconds) {
  204. return ($seconds < 0 ? '-' : '+') . sprintf('%02d:%02d', abs($seconds/60/60), ($seconds/60)%60);
  205. }
  206. function tz_offset_to_seconds($offset) {
  207. if(preg_match('/([+-])(\d{2}):?(\d{2})/', $offset, $match)) {
  208. $sign = ($match[1] == '-' ? -1 : 1);
  209. return (($match[2] * 60 * 60) + ($match[3] * 60)) * $sign;
  210. } else {
  211. return 0;
  212. }
  213. }
  214. function entry_url($entry, $user) {
  215. return $entry->canonical_url ?: Config::$base_url . $user->url . '/' . $entry->id;
  216. }
  217. function entry_date($entry, $user) {
  218. $date = new DateTime($entry->published);
  219. if($entry->tz_offset > 0)
  220. $date->add(new DateInterval('PT'.$entry->tz_offset.'S'));
  221. elseif($entry->tz_offset < 0)
  222. $date->sub(new DateInterval('PT'.abs($entry->tz_offset).'S'));
  223. $tz = tz_seconds_to_offset($entry->tz_offset);
  224. return new DateTime($date->format('Y-m-d\TH:i:s') . $tz);
  225. // Can switch back to this later if I prompt the user for a named timezone instead of just an offset
  226. // $tz = new DateTimeZone($entry->timezone);
  227. // $date->setTimeZone($tz);
  228. // return $date;
  229. }
  230. function validate_photo(&$file) {
  231. try {
  232. if ($_SERVER['REQUEST_METHOD'] == 'POST' && count($_POST) < 1 ) {
  233. throw new RuntimeException('File upload size exceeded.');
  234. }
  235. // Undefined | Multiple Files | $_FILES Corruption Attack
  236. // If this request falls under any of them, treat it invalid.
  237. if (
  238. !isset($file['error']) ||
  239. is_array($file['error'])
  240. ) {
  241. throw new RuntimeException('Invalid parameters.');
  242. }
  243. // Check $file['error'] value.
  244. switch ($file['error']) {
  245. case UPLOAD_ERR_OK:
  246. break;
  247. case UPLOAD_ERR_NO_FILE:
  248. throw new RuntimeException('No file sent.');
  249. case UPLOAD_ERR_INI_SIZE:
  250. case UPLOAD_ERR_FORM_SIZE:
  251. throw new RuntimeException('Exceeded filesize limit.');
  252. default:
  253. throw new RuntimeException('Unknown errors.');
  254. }
  255. // You should also check filesize here.
  256. if ($file['size'] > 4000000) {
  257. throw new RuntimeException('Exceeded filesize limit.');
  258. }
  259. // DO NOT TRUST $file['mime'] VALUE !!
  260. // Check MIME Type by yourself.
  261. $finfo = new finfo(FILEINFO_MIME_TYPE);
  262. if (false === $ext = array_search(
  263. $finfo->file($file['tmp_name']),
  264. array(
  265. 'jpg' => 'image/jpeg',
  266. 'png' => 'image/png',
  267. 'gif' => 'image/gif',
  268. ),
  269. true
  270. )) {
  271. throw new RuntimeException('Invalid file format.');
  272. }
  273. } catch (RuntimeException $e) {
  274. return $e->getMessage();
  275. }
  276. }
  277. // Reads the exif rotation data and actually rotates the photo.
  278. // Only does anything if the exif library is loaded, otherwise is a noop.
  279. function correct_photo_rotation($filename) {
  280. if(class_exists('IMagick')) {
  281. $image = new IMagick($filename);
  282. $orientation = $image->getImageOrientation();
  283. switch($orientation) {
  284. case IMagick::ORIENTATION_BOTTOMRIGHT:
  285. $image->rotateImage(new ImagickPixel('#00000000'), 180);
  286. break;
  287. case IMagick::ORIENTATION_RIGHTTOP:
  288. $image->rotateImage(new ImagickPixel('#00000000'), 90);
  289. break;
  290. case IMagick::ORIENTATION_LEFTBOTTOM:
  291. $image->rotateImage(new ImagickPixel('#00000000'), -90);
  292. break;
  293. }
  294. $image->setImageOrientation(IMagick::ORIENTATION_TOPLEFT);
  295. $image->writeImage($filename);
  296. }
  297. }
  298. function default_drink_options() {
  299. return [
  300. ['title'=>'Coffee','subtitle'=>'','type'=>'drink'],
  301. ['title'=>'Beer','subtitle'=>'','type'=>'drink'],
  302. ['title'=>'Cocktail','subtitle'=>'','type'=>'drink'],
  303. ['title'=>'Tea','subtitle'=>'','type'=>'drink'],
  304. ['title'=>'Mimosa','subtitle'=>'','type'=>'drink'],
  305. ['title'=>'Latte','subtitle'=>'','type'=>'drink'],
  306. ['title'=>'Champagne','subtitle'=>'','type'=>'drink']
  307. ];
  308. }
  309. function default_food_options() {
  310. return [
  311. ['title'=>'Burrito','subtitle'=>'','type'=>'eat'],
  312. ['title'=>'Banana','subtitle'=>'','type'=>'eat'],
  313. ['title'=>'Pizza','subtitle'=>'','type'=>'eat'],
  314. ['title'=>'Soup','subtitle'=>'','type'=>'eat'],
  315. ['title'=>'Tacos','subtitle'=>'','type'=>'eat'],
  316. ['title'=>'Mac and Cheese','subtitle'=>'','type'=>'eat']
  317. ];
  318. }
  319. function query_user_nearby_options($type, $user_id, $latitude, $longitude) {
  320. $published = date('Y-m-d H:i:s', strtotime('-4 months'));
  321. $options = [];
  322. $bin_size = 1000;
  323. $optionsQ = ORM::for_table('entries')->raw_query('
  324. SELECT *, SUM(num) AS num FROM
  325. (
  326. SELECT id, published, content, type,
  327. round(gc_distance(latitude, longitude, :latitude, :longitude) / '.$bin_size.') AS dist,
  328. COUNT(1) AS num
  329. FROM entries
  330. WHERE user_id = :user_id
  331. AND type = :type
  332. AND gc_distance(latitude, longitude, :latitude, :longitude) IS NOT NULL
  333. AND published > :published /* only look at the last 4 months of posts */
  334. GROUP BY content, round(gc_distance(latitude, longitude, :latitude, :longitude) / '.$bin_size.') /* group by 1km buckets */
  335. ORDER BY round(gc_distance(latitude, longitude, :latitude, :longitude) / '.$bin_size.'), COUNT(1) DESC /* order by distance and frequency */
  336. ) AS tmp
  337. WHERE num >= 1 /* only include things that have been used more than 2 times in this bucket */
  338. AND dist < 1000
  339. GROUP BY content /* group by name again */
  340. ORDER BY SUM(num) DESC /* order by overall frequency */
  341. LIMIT 6
  342. ', ['user_id'=>$user_id, 'type'=>$type, 'latitude'=>$latitude, 'longitude'=>$longitude, 'published'=>$published])->find_many();
  343. foreach($optionsQ as $o) {
  344. $options[] = [
  345. 'title' => $o->content,
  346. 'subtitle' => query_last_eaten($user_id, $o->type, $o->content),
  347. 'type' => $o->type
  348. ];
  349. }
  350. return $options;
  351. }
  352. function query_user_frequent_options($type, $user_id) {
  353. $published = date('Y-m-d H:i:s', strtotime('-4 months'));
  354. $options = [];
  355. $optionsQ = ORM::for_table('entries')->raw_query('
  356. SELECT type, content, MAX(published) AS published
  357. FROM entries
  358. WHERE user_id = :user_id
  359. AND type = :type
  360. AND published > :published
  361. GROUP BY content
  362. ORDER BY COUNT(1) DESC
  363. LIMIT 6
  364. ', ['user_id'=>$user_id, 'type'=>$type, 'published'=>$published])->find_many();
  365. foreach($optionsQ as $o) {
  366. $options[] = [
  367. 'title' => $o->content,
  368. 'subtitle' => query_last_eaten($user_id, $o->type, $o->content),
  369. 'type' => $o->type
  370. ];
  371. }
  372. return $options;
  373. }
  374. function query_last_eaten($user_id, $type, $content) {
  375. $lastQ = ORM::for_table('entries')->raw_query('
  376. SELECT published, timezone, tz_offset
  377. FROM entries
  378. WHERE user_id=:user_id
  379. AND type=:type
  380. AND content=:content
  381. ORDER BY published DESC
  382. LIMIT 1;
  383. ', ['user_id'=>$user_id, 'type'=>$type, 'content'=>$content])->find_one();
  384. if(!$lastQ)
  385. return '';
  386. $timestamp = strtotime($lastQ->published);
  387. // If less than 8 hours ago, use relative time, otherwise show the actual time
  388. if(time() - $timestamp > 60*60*8) {
  389. if($lastQ->timezone) {
  390. $date = new DateTime($lastQ->published);
  391. $date->setTimeZone(new DateTimeZone($lastQ->timezone));
  392. } else {
  393. $iso = date_iso8601($lastQ->published, $lastQ->tz_offset);
  394. $date = new DateTime($iso);
  395. }
  396. return $date->format('D, M j, g:ia');
  397. } else {
  398. $config = array(
  399. 'language' => '\RelativeTime\Languages\English',
  400. 'separator' => ', ',
  401. 'suffix' => true,
  402. 'truncate' => 1,
  403. );
  404. $relativeTime = new \RelativeTime\RelativeTime($config);
  405. return $relativeTime->timeAgo($lastQ->published);
  406. }
  407. }
  408. function get_entry_options($user_id, $latitude=null, $longitude=null) {
  409. /*
  410. Sections:
  411. * Recent posts (food + drink combined)
  412. * Drinks (based on location)
  413. * custom box below
  414. * Food (based on location)
  415. * custom box below
  416. If no recent entries, remove that section.
  417. If no nearby food/drinks, use a default list
  418. */
  419. $recent = [];
  420. $drinks = [];
  421. $food = [];
  422. $recentQ = ORM::for_table('entries')->raw_query('
  423. SELECT type, content FROM
  424. (SELECT *
  425. FROM entries
  426. WHERE user_id = :user_id
  427. ORDER BY published DESC) AS tmp
  428. GROUP BY content, type
  429. ORDER BY MAX(published) DESC
  430. LIMIT 6', ['user_id'=>$user_id])->find_many();
  431. $last_latitude = false;
  432. $last_longitude = false;
  433. foreach($recentQ as $r) {
  434. if($last_latitude == false && $r->latitude) {
  435. $last_latitude = $r->latitude;
  436. $last_longitude = $r->longitude;
  437. }
  438. $recent[] = [
  439. 'title' => $r->content,
  440. 'subtitle' => query_last_eaten($user_id, $r->type, $r->content),
  441. 'type' => $r->type
  442. ];
  443. }
  444. // If no location was provided, but there is a location in the most recent entry, use that
  445. if($latitude == null && $last_latitude) {
  446. $latitude = $last_latitude;
  447. $longitude = $last_longitude;
  448. }
  449. $num_options = 6;
  450. if($latitude) {
  451. $drinks = query_user_nearby_options('drink', $user_id, $latitude, $longitude);
  452. }
  453. // If there's no nearby data (like if the user isn't including location) then return the most frequently used ones instead
  454. if(count($drinks) < $num_options) {
  455. $frequent_drinks = query_user_frequent_options('drink', $user_id);
  456. $drinks = array_merge($drinks, $frequent_drinks);
  457. }
  458. // If there's less than 4 options available, fill the list with the default options
  459. if(count($drinks) < $num_options) {
  460. $default_drinks = default_drink_options();
  461. $drinks = array_merge($drinks, $default_drinks);
  462. }
  463. $drinks = array_slice($drinks, 0, $num_options);
  464. if($latitude) {
  465. $food = query_user_nearby_options('eat', $user_id, $latitude, $longitude);
  466. }
  467. if(count($food) == 0) {
  468. $frequent_food = query_user_frequent_options('eat', $user_id);
  469. $food = array_merge($food, $frequent_food);
  470. }
  471. if(count($food) < $num_options) {
  472. $default_food = default_food_options();
  473. $food = array_merge($food, $default_food);
  474. }
  475. $food = array_slice($food, 0, $num_options);
  476. $options = [
  477. 'sections' => [
  478. [
  479. 'title' => 'Recent',
  480. 'items' => $recent
  481. ],
  482. [
  483. 'title' => 'Drinks',
  484. 'items' => $drinks
  485. ],
  486. [
  487. 'title' => 'Food',
  488. 'items' => $food
  489. ]
  490. ]
  491. ];
  492. if(count($options['sections'][0]['items']) == 0)
  493. array_shift($options['sections']);
  494. return $options;
  495. }