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.

415 lines
12 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://timezone-api.geoloqi.com/timezone/'.$lat.'/'.$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. function micropub_post($endpoint, $params, $access_token) {
  74. $ch = curl_init();
  75. curl_setopt($ch, CURLOPT_URL, $endpoint);
  76. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  77. 'Authorization: Bearer ' . $access_token
  78. ));
  79. curl_setopt($ch, CURLOPT_POST, true);
  80. $post = http_build_query(array_merge(array(
  81. 'access_token' => $access_token,
  82. 'h' => 'entry'
  83. ), $params));
  84. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  85. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  86. curl_setopt($ch, CURLOPT_HEADER, true);
  87. curl_setopt($ch, CURLINFO_HEADER_OUT, true);
  88. $response = curl_exec($ch);
  89. $error = curl_error($ch);
  90. $sent_headers = curl_getinfo($ch, CURLINFO_HEADER_OUT);
  91. $request = $sent_headers . $post;
  92. return array(
  93. 'request' => $request,
  94. 'response' => $response,
  95. 'error' => $error,
  96. 'curlinfo' => curl_getinfo($ch)
  97. );
  98. }
  99. function micropub_get($endpoint, $params, $access_token) {
  100. $ch = curl_init();
  101. curl_setopt($ch, CURLOPT_URL, $endpoint . '?' . http_build_query($params));
  102. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  103. 'Authorization: Bearer ' . $access_token
  104. ));
  105. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  106. $response = curl_exec($ch);
  107. $data = array();
  108. if($response) {
  109. parse_str($response, $data);
  110. }
  111. $error = curl_error($ch);
  112. return array(
  113. 'response' => $response,
  114. 'data' => $data,
  115. 'error' => $error,
  116. 'curlinfo' => curl_getinfo($ch)
  117. );
  118. }
  119. function get_syndication_targets(&$user) {
  120. $targets = array();
  121. $r = micropub_get($user->micropub_endpoint, array('q'=>'syndicate-to'), $user->micropub_access_token);
  122. if($r['data'] && array_key_exists('syndicate-to', $r['data'])) {
  123. $targetURLs = preg_split('/, ?/', $r['data']['syndicate-to']);
  124. foreach($targetURLs as $t) {
  125. // If the syndication target doesn't have a scheme, add http
  126. if(!preg_match('/^http/', $t))
  127. $tmp = 'http://' . $t;
  128. // Parse the target expecting it to be a URL
  129. $url = parse_url($tmp);
  130. // If there's a host, and the host contains a . then we can assume there's a favicon
  131. // parse_url will parse strings like http://twitter into an array with a host of twitter, which is not resolvable
  132. if(array_key_exists('host', $url) && strpos($url['host'], '.') !== false) {
  133. $targets[] = array(
  134. 'target' => $t,
  135. 'favicon' => 'http://' . $url['host'] . '/favicon.ico'
  136. );
  137. } else {
  138. $targets[] = array(
  139. 'target' => $t,
  140. 'favicon' => false
  141. );
  142. }
  143. }
  144. }
  145. if(count($targets)) {
  146. $user->syndication_targets = json_encode($targets);
  147. $user->save();
  148. }
  149. return array(
  150. 'targets' => $targets,
  151. 'response' => $r
  152. );
  153. }
  154. function build_static_map_url($latitude, $longitude, $height, $width, $zoom) {
  155. return '/map.png?marker[]=lat:' . $latitude . ';lng:' . $longitude . ';icon:small-green-cutout&basemap=topo&width=' . $width . '&height=' . $height . '&zoom=' . $zoom;
  156. }
  157. function static_map_service($query) {
  158. return 'http://static-maps.pdx.esri.com/img.php?' . $query;
  159. }
  160. function relative_time($date) {
  161. static $rel;
  162. if(!isset($rel)) {
  163. $config = array(
  164. 'language' => '\RelativeTime\Languages\English',
  165. 'separator' => ', ',
  166. 'suffix' => true,
  167. 'truncate' => 1,
  168. );
  169. $rel = new \RelativeTime\RelativeTime($config);
  170. }
  171. return $rel->timeAgo($date);
  172. }
  173. function entry_url($entry, $user) {
  174. return $entry->canonical_url ?: Config::$base_url . $user->url . '/' . $entry->id;
  175. }
  176. function entry_date($entry, $user) {
  177. $date = new DateTime($entry->published);
  178. $tz = new DateTimeZone($entry->timezone);
  179. $date->setTimeZone($tz);
  180. return $date;
  181. }
  182. function default_drink_options() {
  183. return [
  184. 'Coffee',
  185. 'Beer',
  186. 'Cocktail',
  187. 'Tea',
  188. 'Mimosa',
  189. 'Latte',
  190. 'Champagne'
  191. ];
  192. }
  193. function default_food_options() {
  194. return [
  195. 'Burrito',
  196. 'Banana',
  197. 'Pizza',
  198. 'Soup',
  199. 'Tacos',
  200. 'Mac and Cheese'
  201. ];
  202. }
  203. function query_user_nearby_options($type, $user_id, $latitude, $longitude) {
  204. $published = date('Y-m-d H:i:s', strtotime('-4 months'));
  205. $options = [];
  206. $bin_size = 1000;
  207. $optionsQ = ORM::for_table('entries')->raw_query('
  208. SELECT *, SUM(num) AS num FROM
  209. (
  210. SELECT id, published, content, type,
  211. round(gc_distance(latitude, longitude, :latitude, :longitude) / '.$bin_size.') AS dist,
  212. COUNT(1) AS num
  213. FROM entries
  214. WHERE user_id = :user_id
  215. AND type = :type
  216. AND gc_distance(latitude, longitude, :latitude, :longitude) IS NOT NULL
  217. AND published > :published /* only look at the last 4 months of posts */
  218. GROUP BY content, round(gc_distance(latitude, longitude, :latitude, :longitude) / '.$bin_size.') /* group by 1km buckets */
  219. ORDER BY round(gc_distance(latitude, longitude, :latitude, :longitude) / '.$bin_size.'), COUNT(1) DESC /* order by distance and frequency */
  220. ) AS tmp
  221. WHERE num > 2 /* only include things that have been used more than 2 times in this bucket */
  222. GROUP BY content /* group by name again */
  223. ORDER BY SUM(num) DESC /* order by overall frequency */
  224. LIMIT 4
  225. ', ['user_id'=>$user_id, 'type'=>$type, 'latitude'=>$latitude, 'longitude'=>$longitude, 'published'=>$published])->find_many();
  226. foreach($optionsQ as $o) {
  227. $options[] = [
  228. 'title' => $o->content,
  229. 'subtitle' => query_last_eaten($user_id, $o->type, $o->content),
  230. 'type' => $o->type
  231. ];
  232. }
  233. return $options;
  234. }
  235. function query_user_frequent_options($type, $user_id) {
  236. $published = date('Y-m-d H:i:s', strtotime('-4 months'));
  237. $options = [];
  238. $optionsQ = ORM::for_table('entries')->raw_query('
  239. SELECT type, content, MAX(published) AS published
  240. FROM entries
  241. WHERE user_id = :user_id
  242. AND type = :type
  243. AND published > :published
  244. GROUP BY content
  245. ORDER BY COUNT(1) DESC
  246. LIMIT 4
  247. ', ['user_id'=>$user_id, 'type'=>$type, 'published'=>$published])->find_many();
  248. foreach($optionsQ as $o) {
  249. $options[] = [
  250. 'title' => $o->content,
  251. 'subtitle' => query_last_eaten($user_id, $o->type, $o->content),
  252. 'type' => $o->type
  253. ];
  254. }
  255. return $options;
  256. }
  257. function query_last_eaten($user_id, $type, $content) {
  258. $lastQ = ORM::for_table('entries')->raw_query('
  259. SELECT published, timezone
  260. FROM entries
  261. WHERE user_id=:user_id
  262. AND type=:type
  263. AND content=:content
  264. ORDER BY published DESC
  265. LIMIT 1;
  266. ', ['user_id'=>$user_id, 'type'=>$type, 'content'=>$content])->find_one();
  267. if(!$lastQ)
  268. return '';
  269. $timestamp = strtotime($lastQ->published);
  270. // If less than 8 hours ago, use relative time, otherwise show the actual time
  271. if(time() - $timestamp > 60*60*8) {
  272. $date = new DateTime($lastQ->published);
  273. $date->setTimeZone(new DateTimeZone($lastQ->timezone));
  274. return $date->format('D, M j, g:ia');
  275. } else {
  276. $config = array(
  277. 'language' => '\RelativeTime\Languages\English',
  278. 'separator' => ', ',
  279. 'suffix' => true,
  280. 'truncate' => 1,
  281. );
  282. $relativeTime = new \RelativeTime\RelativeTime($config);
  283. return $relativeTime->timeAgo($lastQ->published);
  284. }
  285. }
  286. function get_entry_options($user_id, $latitude=null, $longitude=null) {
  287. /*
  288. Sections:
  289. * Recent 2 posts (food + drink combined)
  290. * Drinks (based on location)
  291. * custom box below
  292. * Food (based on location)
  293. * custom box below
  294. If no recent entries, remove that section.
  295. If no nearby food/drinks, use a default list
  296. */
  297. $recent = [];
  298. $drinks = [];
  299. $food = [];
  300. $recentQ = ORM::for_table('entries')->raw_query('
  301. SELECT type, content FROM
  302. (SELECT *
  303. FROM entries
  304. WHERE user_id = :user_id
  305. ORDER BY published DESC) AS tmp
  306. GROUP BY content
  307. ORDER BY MAX(published) DESC
  308. LIMIT 4', ['user_id'=>$user_id])->find_many();
  309. foreach($recentQ as $r) {
  310. $recent[] = [
  311. 'title' => $r->content,
  312. 'subtitle' => query_last_eaten($user_id, $r->type, $r->content),
  313. 'type' => $r->type
  314. ];
  315. }
  316. if($latitude) {
  317. $drinks = query_user_nearby_options('drink', $user_id, $latitude, $longitude);
  318. }
  319. // If there's no nearby data (like if the user isn't including location) then return the most frequently used ones instead
  320. if(count($drinks) == 0) {
  321. $drinks = query_user_frequent_options('drink', $user_id);
  322. }
  323. // If there's less than 4 options available, fill the list with the default options
  324. if(count($drinks) < 4) {
  325. $default = default_drink_options();
  326. while(count($drinks) < 4) {
  327. $next = array_shift($default);
  328. if(!in_array(['title'=>$next,'type'=>'drink'], $drinks)) {
  329. $drinks[] = [
  330. 'title' => $next,
  331. 'subtitle' => query_last_eaten($user_id, 'drink', $next),
  332. 'type' => 'drink'
  333. ];
  334. }
  335. }
  336. }
  337. if($latitude) {
  338. $food = query_user_nearby_options('eat', $user_id, $latitude, $longitude);
  339. }
  340. if(count($food) == 0) {
  341. $food = query_user_frequent_options('eat', $user_id);
  342. }
  343. if(count($food) < 4) {
  344. $default = default_food_options();
  345. while(count($food) < 4) {
  346. $next = array_shift($default);
  347. if(!in_array(['title'=>$next,'type'=>'eat'], $food)) {
  348. $food[] = [
  349. 'title' => $next,
  350. 'subtitle' => query_last_eaten($user_id, 'eat', $next),
  351. 'type' => 'eat'
  352. ];
  353. }
  354. }
  355. }
  356. $options = [
  357. 'sections' => [
  358. [
  359. 'title' => 'Recent',
  360. 'items' => $recent
  361. ],
  362. [
  363. 'title' => 'Drinks',
  364. 'items' => $drinks
  365. ],
  366. [
  367. 'title' => 'Food',
  368. 'items' => $food
  369. ]
  370. ]
  371. ];
  372. if(count($options['sections'][0]['items']) == 0)
  373. array_shift($options['sections']);
  374. return $options;
  375. }