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.

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