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.

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