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.

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