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.

473 lines
14 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_get($endpoint, $params, $access_token) {
  114. $url = parse_url($endpoint);
  115. if(!k($url, 'query')) {
  116. $url['query'] = http_build_query($params);
  117. } else {
  118. $url['query'] .= '&' . http_build_query($params);
  119. }
  120. $endpoint = http_build_url($url);
  121. $ch = curl_init();
  122. curl_setopt($ch, CURLOPT_URL, $endpoint);
  123. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  124. 'Authorization: Bearer ' . $access_token
  125. ));
  126. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  127. $response = curl_exec($ch);
  128. $data = array();
  129. if($response) {
  130. parse_str($response, $data);
  131. }
  132. $error = curl_error($ch);
  133. return array(
  134. 'response' => $response,
  135. 'data' => $data,
  136. 'error' => $error,
  137. 'curlinfo' => curl_getinfo($ch)
  138. );
  139. }
  140. function get_syndication_targets(&$user) {
  141. $targets = array();
  142. $r = micropub_get($user->micropub_endpoint, array('q'=>'syndicate-to'), $user->micropub_access_token);
  143. if($r['data'] && array_key_exists('syndicate-to', $r['data'])) {
  144. $targetURLs = preg_split('/, ?/', $r['data']['syndicate-to']);
  145. foreach($targetURLs as $t) {
  146. // If the syndication target doesn't have a scheme, add http
  147. if(!preg_match('/^http/', $t))
  148. $tmp = 'http://' . $t;
  149. // Parse the target expecting it to be a URL
  150. $url = parse_url($tmp);
  151. // If there's a host, and the host contains a . then we can assume there's a favicon
  152. // parse_url will parse strings like http://twitter into an array with a host of twitter, which is not resolvable
  153. if(array_key_exists('host', $url) && strpos($url['host'], '.') !== false) {
  154. $targets[] = array(
  155. 'target' => $t,
  156. 'favicon' => 'http://' . $url['host'] . '/favicon.ico'
  157. );
  158. } else {
  159. $targets[] = array(
  160. 'target' => $t,
  161. 'favicon' => false
  162. );
  163. }
  164. }
  165. }
  166. if(count($targets)) {
  167. $user->syndication_targets = json_encode($targets);
  168. $user->save();
  169. }
  170. return array(
  171. 'targets' => $targets,
  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 default_drink_options() {
  231. return [
  232. ['title'=>'Coffee','subtitle'=>'','type'=>'drink'],
  233. ['title'=>'Beer','subtitle'=>'','type'=>'drink'],
  234. ['title'=>'Cocktail','subtitle'=>'','type'=>'drink'],
  235. ['title'=>'Tea','subtitle'=>'','type'=>'drink'],
  236. ['title'=>'Mimosa','subtitle'=>'','type'=>'drink'],
  237. ['title'=>'Latte','subtitle'=>'','type'=>'drink'],
  238. ['title'=>'Champagne','subtitle'=>'','type'=>'drink']
  239. ];
  240. }
  241. function default_food_options() {
  242. return [
  243. ['title'=>'Burrito','subtitle'=>'','type'=>'eat'],
  244. ['title'=>'Banana','subtitle'=>'','type'=>'eat'],
  245. ['title'=>'Pizza','subtitle'=>'','type'=>'eat'],
  246. ['title'=>'Soup','subtitle'=>'','type'=>'eat'],
  247. ['title'=>'Tacos','subtitle'=>'','type'=>'eat'],
  248. ['title'=>'Mac and Cheese','subtitle'=>'','type'=>'eat']
  249. ];
  250. }
  251. function query_user_nearby_options($type, $user_id, $latitude, $longitude) {
  252. $published = date('Y-m-d H:i:s', strtotime('-4 months'));
  253. $options = [];
  254. $bin_size = 1000;
  255. $optionsQ = ORM::for_table('entries')->raw_query('
  256. SELECT *, SUM(num) AS num FROM
  257. (
  258. SELECT id, published, content, type,
  259. round(gc_distance(latitude, longitude, :latitude, :longitude) / '.$bin_size.') AS dist,
  260. COUNT(1) AS num
  261. FROM entries
  262. WHERE user_id = :user_id
  263. AND type = :type
  264. AND gc_distance(latitude, longitude, :latitude, :longitude) IS NOT NULL
  265. AND published > :published /* only look at the last 4 months of posts */
  266. GROUP BY content, round(gc_distance(latitude, longitude, :latitude, :longitude) / '.$bin_size.') /* group by 1km buckets */
  267. ORDER BY round(gc_distance(latitude, longitude, :latitude, :longitude) / '.$bin_size.'), COUNT(1) DESC /* order by distance and frequency */
  268. ) AS tmp
  269. WHERE num >= 1 /* only include things that have been used more than 2 times in this bucket */
  270. AND dist < 1000
  271. GROUP BY content /* group by name again */
  272. ORDER BY SUM(num) DESC /* order by overall frequency */
  273. LIMIT 6
  274. ', ['user_id'=>$user_id, 'type'=>$type, 'latitude'=>$latitude, 'longitude'=>$longitude, 'published'=>$published])->find_many();
  275. foreach($optionsQ as $o) {
  276. $options[] = [
  277. 'title' => $o->content,
  278. 'subtitle' => query_last_eaten($user_id, $o->type, $o->content),
  279. 'type' => $o->type
  280. ];
  281. }
  282. return $options;
  283. }
  284. function query_user_frequent_options($type, $user_id) {
  285. $published = date('Y-m-d H:i:s', strtotime('-4 months'));
  286. $options = [];
  287. $optionsQ = ORM::for_table('entries')->raw_query('
  288. SELECT type, content, MAX(published) AS published
  289. FROM entries
  290. WHERE user_id = :user_id
  291. AND type = :type
  292. AND published > :published
  293. GROUP BY content
  294. ORDER BY COUNT(1) DESC
  295. LIMIT 6
  296. ', ['user_id'=>$user_id, 'type'=>$type, 'published'=>$published])->find_many();
  297. foreach($optionsQ as $o) {
  298. $options[] = [
  299. 'title' => $o->content,
  300. 'subtitle' => query_last_eaten($user_id, $o->type, $o->content),
  301. 'type' => $o->type
  302. ];
  303. }
  304. return $options;
  305. }
  306. function query_last_eaten($user_id, $type, $content) {
  307. $lastQ = ORM::for_table('entries')->raw_query('
  308. SELECT published, timezone, tz_offset
  309. FROM entries
  310. WHERE user_id=:user_id
  311. AND type=:type
  312. AND content=:content
  313. ORDER BY published DESC
  314. LIMIT 1;
  315. ', ['user_id'=>$user_id, 'type'=>$type, 'content'=>$content])->find_one();
  316. if(!$lastQ)
  317. return '';
  318. $timestamp = strtotime($lastQ->published);
  319. // If less than 8 hours ago, use relative time, otherwise show the actual time
  320. if(time() - $timestamp > 60*60*8) {
  321. if($lastQ->timezone) {
  322. $date = new DateTime($lastQ->published);
  323. $date->setTimeZone(new DateTimeZone($lastQ->timezone));
  324. } else {
  325. $iso = date_iso8601($lastQ->published, $lastQ->tz_offset);
  326. $date = new DateTime($iso);
  327. }
  328. return $date->format('D, M j, g:ia');
  329. } else {
  330. $config = array(
  331. 'language' => '\RelativeTime\Languages\English',
  332. 'separator' => ', ',
  333. 'suffix' => true,
  334. 'truncate' => 1,
  335. );
  336. $relativeTime = new \RelativeTime\RelativeTime($config);
  337. return $relativeTime->timeAgo($lastQ->published);
  338. }
  339. }
  340. function get_entry_options($user_id, $latitude=null, $longitude=null) {
  341. /*
  342. Sections:
  343. * Recent posts (food + drink combined)
  344. * Drinks (based on location)
  345. * custom box below
  346. * Food (based on location)
  347. * custom box below
  348. If no recent entries, remove that section.
  349. If no nearby food/drinks, use a default list
  350. */
  351. $recent = [];
  352. $drinks = [];
  353. $food = [];
  354. $recentQ = ORM::for_table('entries')->raw_query('
  355. SELECT type, content FROM
  356. (SELECT *
  357. FROM entries
  358. WHERE user_id = :user_id
  359. ORDER BY published DESC) AS tmp
  360. GROUP BY content
  361. ORDER BY MAX(published) DESC
  362. LIMIT 6', ['user_id'=>$user_id])->find_many();
  363. $last_latitude = false;
  364. $last_longitude = false;
  365. foreach($recentQ as $r) {
  366. if($last_latitude == false && $r->latitude) {
  367. $last_latitude = $r->latitude;
  368. $last_longitude = $r->longitude;
  369. }
  370. $recent[] = [
  371. 'title' => $r->content,
  372. 'subtitle' => query_last_eaten($user_id, $r->type, $r->content),
  373. 'type' => $r->type
  374. ];
  375. }
  376. // If no location was provided, but there is a location in the most recent entry, use that
  377. if($latitude == null && $last_latitude) {
  378. $latitude = $last_latitude;
  379. $longitude = $last_longitude;
  380. }
  381. $num_options = 6;
  382. if($latitude) {
  383. $drinks = query_user_nearby_options('drink', $user_id, $latitude, $longitude);
  384. }
  385. // If there's no nearby data (like if the user isn't including location) then return the most frequently used ones instead
  386. if(count($drinks) < $num_options) {
  387. $frequent_drinks = query_user_frequent_options('drink', $user_id);
  388. $drinks = array_merge($drinks, $frequent_drinks);
  389. }
  390. // If there's less than 4 options available, fill the list with the default options
  391. if(count($drinks) < $num_options) {
  392. $default_drinks = default_drink_options();
  393. $drinks = array_merge($drinks, $default_drinks);
  394. }
  395. $drinks = array_slice($drinks, 0, $num_options);
  396. if($latitude) {
  397. $food = query_user_nearby_options('eat', $user_id, $latitude, $longitude);
  398. }
  399. if(count($food) == 0) {
  400. $frequent_food = query_user_frequent_options('eat', $user_id);
  401. $food = array_merge($food, $frequent_food);
  402. }
  403. if(count($food) < $num_options) {
  404. $default_food = default_food_options();
  405. $food = array_merge($food, $default_food);
  406. }
  407. $food = array_slice($food, 0, $num_options);
  408. $options = [
  409. 'sections' => [
  410. [
  411. 'title' => 'Recent',
  412. 'items' => $recent
  413. ],
  414. [
  415. 'title' => 'Drinks',
  416. 'items' => $drinks
  417. ],
  418. [
  419. 'title' => 'Food',
  420. 'items' => $food
  421. ]
  422. ]
  423. ];
  424. if(count($options['sections'][0]['items']) == 0)
  425. array_shift($options['sections']);
  426. return $options;
  427. }