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.

409 lines
11 KiB

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