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.

416 lines
12 KiB

9 years ago
10 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 static_map($latitude, $longitude, $height=174, $width=300, $zoom=14) {
  155. #return 'http://static-maps.pdx.esri.com/img.php?marker[]=lat:' . $latitude . ';lng:' . $longitude . ';icon:small-green-cutout&basemap=topo&width=' . $width . '&height=' . $height . '&zoom=' . $zoom;
  156. return '/map.png?marker[]=lat:' . $latitude . ';lng:' . $longitude . ';icon:small-green-cutout&basemap=topo&width=' . $width . '&height=' . $height . '&zoom=' . $zoom;
  157. }
  158. function get_static_map($query) {
  159. return 'http://static-maps.pdx.esri.com/img.php?' . $query;
  160. }
  161. function relative_time($date) {
  162. static $rel;
  163. if(!isset($rel)) {
  164. $config = array(
  165. 'language' => '\RelativeTime\Languages\English',
  166. 'separator' => ', ',
  167. 'suffix' => true,
  168. 'truncate' => 1,
  169. );
  170. $rel = new \RelativeTime\RelativeTime($config);
  171. }
  172. return $rel->timeAgo($date);
  173. }
  174. function entry_url($entry, $user) {
  175. return $entry->canonical_url ?: Config::$base_url . $user->url . '/' . $entry->id;
  176. }
  177. function entry_date($entry, $user) {
  178. $date = new DateTime($entry->published);
  179. $tz = new DateTimeZone($entry->timezone);
  180. $date->setTimeZone($tz);
  181. return $date;
  182. }
  183. function default_drink_options() {
  184. return [
  185. 'Coffee',
  186. 'Beer',
  187. 'Cocktail',
  188. 'Tea',
  189. 'Mimosa',
  190. 'Latte',
  191. 'Champagne'
  192. ];
  193. }
  194. function default_food_options() {
  195. return [
  196. 'Burrito',
  197. 'Banana',
  198. 'Pizza',
  199. 'Soup',
  200. 'Tacos',
  201. 'Mac and Cheese'
  202. ];
  203. }
  204. function query_user_nearby_options($type, $user_id, $latitude, $longitude) {
  205. $published = date('Y-m-d H:i:s', strtotime('-4 months'));
  206. $options = [];
  207. $bin_size = 1000;
  208. $optionsQ = ORM::for_table('entries')->raw_query('
  209. SELECT *, SUM(num) AS num FROM
  210. (
  211. SELECT id, published, content, type,
  212. round(gc_distance(latitude, longitude, :latitude, :longitude) / '.$bin_size.') AS dist,
  213. COUNT(1) AS num
  214. FROM entries
  215. WHERE user_id = :user_id
  216. AND type = :type
  217. AND gc_distance(latitude, longitude, :latitude, :longitude) IS NOT NULL
  218. AND published > :published /* only look at the last 4 months of posts */
  219. GROUP BY content, round(gc_distance(latitude, longitude, :latitude, :longitude) / '.$bin_size.') /* group by 1km buckets */
  220. ORDER BY round(gc_distance(latitude, longitude, :latitude, :longitude) / '.$bin_size.'), COUNT(1) DESC /* order by distance and frequency */
  221. ) AS tmp
  222. WHERE num > 2 /* only include things that have been used more than 2 times in this bucket */
  223. GROUP BY content /* group by name again */
  224. ORDER BY SUM(num) DESC /* order by overall frequency */
  225. LIMIT 4
  226. ', ['user_id'=>$user_id, 'type'=>$type, 'latitude'=>$latitude, 'longitude'=>$longitude, 'published'=>$published])->find_many();
  227. foreach($optionsQ as $o) {
  228. $options[] = [
  229. 'title' => $o->content,
  230. 'subtitle' => query_last_eaten($user_id, $o->type, $o->content),
  231. 'type' => $o->type
  232. ];
  233. }
  234. return $options;
  235. }
  236. function query_user_frequent_options($type, $user_id) {
  237. $published = date('Y-m-d H:i:s', strtotime('-4 months'));
  238. $options = [];
  239. $optionsQ = ORM::for_table('entries')->raw_query('
  240. SELECT type, content, MAX(published) AS published
  241. FROM entries
  242. WHERE user_id = :user_id
  243. AND type = :type
  244. AND published > :published
  245. GROUP BY content
  246. ORDER BY COUNT(1) DESC
  247. LIMIT 4
  248. ', ['user_id'=>$user_id, 'type'=>$type, 'published'=>$published])->find_many();
  249. foreach($optionsQ as $o) {
  250. $options[] = [
  251. 'title' => $o->content,
  252. 'subtitle' => query_last_eaten($user_id, $o->type, $o->content),
  253. 'type' => $o->type
  254. ];
  255. }
  256. return $options;
  257. }
  258. function query_last_eaten($user_id, $type, $content) {
  259. $lastQ = ORM::for_table('entries')->raw_query('
  260. SELECT published, timezone
  261. FROM entries
  262. WHERE user_id=:user_id
  263. AND type=:type
  264. AND content=:content
  265. ORDER BY published DESC
  266. LIMIT 1;
  267. ', ['user_id'=>$user_id, 'type'=>$type, 'content'=>$content])->find_one();
  268. if(!$lastQ)
  269. return '';
  270. $timestamp = strtotime($lastQ->published);
  271. // If less than 8 hours ago, use relative time, otherwise show the actual time
  272. if(time() - $timestamp > 60*60*8) {
  273. $date = new DateTime($lastQ->published);
  274. $date->setTimeZone(new DateTimeZone($lastQ->timezone));
  275. return $date->format('D, M j, g:ia');
  276. } else {
  277. $config = array(
  278. 'language' => '\RelativeTime\Languages\English',
  279. 'separator' => ', ',
  280. 'suffix' => true,
  281. 'truncate' => 1,
  282. );
  283. $relativeTime = new \RelativeTime\RelativeTime($config);
  284. return $relativeTime->timeAgo($lastQ->published);
  285. }
  286. }
  287. function get_entry_options($user_id, $latitude=null, $longitude=null) {
  288. /*
  289. Sections:
  290. * Recent 2 posts (food + drink combined)
  291. * Drinks (based on location)
  292. * custom box below
  293. * Food (based on location)
  294. * custom box below
  295. If no recent entries, remove that section.
  296. If no nearby food/drinks, use a default list
  297. */
  298. $recent = [];
  299. $drinks = [];
  300. $food = [];
  301. $recentQ = ORM::for_table('entries')->raw_query('
  302. SELECT type, content FROM
  303. (SELECT *
  304. FROM entries
  305. WHERE user_id = :user_id
  306. ORDER BY published DESC) AS tmp
  307. GROUP BY content
  308. ORDER BY MAX(published) DESC
  309. LIMIT 4', ['user_id'=>$user_id])->find_many();
  310. foreach($recentQ as $r) {
  311. $recent[] = [
  312. 'title' => $r->content,
  313. 'subtitle' => query_last_eaten($user_id, $r->type, $r->content),
  314. 'type' => $r->type
  315. ];
  316. }
  317. if($latitude) {
  318. $drinks = query_user_nearby_options('drink', $user_id, $latitude, $longitude);
  319. }
  320. // If there's no nearby data (like if the user isn't including location) then return the most frequently used ones instead
  321. if(count($drinks) == 0) {
  322. $drinks = query_user_frequent_options('drink', $user_id);
  323. }
  324. // If there's less than 4 options available, fill the list with the default options
  325. if(count($drinks) < 4) {
  326. $default = default_drink_options();
  327. while(count($drinks) < 4) {
  328. $next = array_shift($default);
  329. if(!in_array(['title'=>$next,'type'=>'drink'], $drinks)) {
  330. $drinks[] = [
  331. 'title' => $next,
  332. 'subtitle' => query_last_eaten($user_id, 'drink', $next),
  333. 'type' => 'drink'
  334. ];
  335. }
  336. }
  337. }
  338. if($latitude) {
  339. $food = query_user_nearby_options('eat', $user_id, $latitude, $longitude);
  340. }
  341. if(count($food) == 0) {
  342. $food = query_user_frequent_options('eat', $user_id);
  343. }
  344. if(count($food) < 4) {
  345. $default = default_food_options();
  346. while(count($food) < 4) {
  347. $next = array_shift($default);
  348. if(!in_array(['title'=>$next,'type'=>'eat'], $food)) {
  349. $food[] = [
  350. 'title' => $next,
  351. 'subtitle' => query_last_eaten($user_id, 'eat', $next),
  352. 'type' => 'eat'
  353. ];
  354. }
  355. }
  356. }
  357. $options = [
  358. 'sections' => [
  359. [
  360. 'title' => 'Recent',
  361. 'items' => $recent
  362. ],
  363. [
  364. 'title' => 'Drinks',
  365. 'items' => $drinks
  366. ],
  367. [
  368. 'title' => 'Food',
  369. 'items' => $food
  370. ]
  371. ]
  372. ];
  373. if(count($options['sections'][0]['items']) == 0)
  374. array_shift($options['sections']);
  375. return $options;
  376. }