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.

373 lines
10 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. '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. 'type' => $o->type
  225. ];
  226. }
  227. return $options;
  228. }
  229. function query_user_frequent_options($type, $user_id) {
  230. $published = date('Y-m-d H:i:s', strtotime('-4 months'));
  231. $options = [];
  232. $optionsQ = ORM::for_table('entries')->raw_query('
  233. SELECT type, content
  234. FROM entries
  235. WHERE user_id = :user_id
  236. AND type = :type
  237. AND published > :published
  238. GROUP BY content
  239. ORDER BY COUNT(1) DESC
  240. LIMIT 2
  241. ', ['user_id'=>$user_id, 'type'=>$type, 'published'=>$published])->find_many();
  242. foreach($optionsQ as $o) {
  243. $options[] = [
  244. 'title' => $o->content,
  245. 'type' => $o->type
  246. ];
  247. }
  248. return $options;
  249. }
  250. function get_entry_options($user_id, $latitude=null, $longitude=null) {
  251. /*
  252. Sections:
  253. * Recent 2 posts (food + drink combined)
  254. * Drinks (based on location)
  255. * custom box below
  256. * Food (based on location)
  257. * custom box below
  258. If no recent entries, remove that section.
  259. If no nearby food/drinks, use a default list
  260. */
  261. $recent = [];
  262. $drinks = [];
  263. $food = [];
  264. $recentQ = ORM::for_table('entries')->raw_query('
  265. SELECT type, content FROM
  266. (SELECT *
  267. FROM entries
  268. WHERE user_id = :user_id
  269. ORDER BY published DESC) AS tmp
  270. GROUP BY content
  271. ORDER BY MAX(published) DESC
  272. LIMIT 4', ['user_id'=>$user_id])->find_many();
  273. foreach($recentQ as $r) {
  274. $recent[] = [
  275. 'title' => $r->content,
  276. 'type' => $r->type
  277. ];
  278. }
  279. if($latitude) {
  280. $drinks = query_user_nearby_options('drink', $user_id, $latitude, $longitude);
  281. }
  282. // If there's no nearby data (like if the user isn't including location) then return the most frequently used ones instead
  283. if(count($drinks) == 0) {
  284. $drinks = query_user_frequent_options('drink', $user_id);
  285. }
  286. // If there's less than 4 options available, fill the list with the default options
  287. if(count($drinks) < 4) {
  288. $default = default_drink_options();
  289. while(count($drinks) < 4) {
  290. $next = array_shift($default);
  291. if(!in_array(['title'=>$next,'type'=>'drink'], $drinks)) {
  292. $drinks[] = [
  293. 'title' => $next,
  294. 'type' => 'drink'
  295. ];
  296. }
  297. }
  298. }
  299. if($latitude) {
  300. $food = query_user_nearby_options('eat', $user_id, $latitude, $longitude);
  301. }
  302. if(count($food) == 0) {
  303. $food = query_user_frequent_options('eat', $user_id);
  304. }
  305. if(count($food) < 4) {
  306. $default = default_food_options();
  307. while(count($food) < 4) {
  308. $next = array_shift($default);
  309. if(!in_array(['title'=>$next,'type'=>'eat'], $food)) {
  310. $food[] = [
  311. 'title' => $next,
  312. 'type' => 'eat'
  313. ];
  314. }
  315. }
  316. }
  317. $options = [
  318. 'sections' => [
  319. [
  320. 'title' => 'Recent',
  321. 'items' => $recent
  322. ],
  323. [
  324. 'title' => 'Drinks',
  325. 'items' => $drinks
  326. ],
  327. [
  328. 'title' => 'Food',
  329. 'items' => $food
  330. ]
  331. ]
  332. ];
  333. if(count($options['sections'][0]['items']) == 0)
  334. array_shift($options['sections']);
  335. return $options;
  336. }