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.

549 lines
17 KiB

7 years ago
2 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, 'https://atlas.p3k.io/api/timezone?latitude='.$lat.'&longitude='.$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. if(!function_exists('http_build_url')) {
  74. function http_build_url($parsed_url) {
  75. $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
  76. $host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
  77. $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
  78. $user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
  79. $pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
  80. $pass = ($user || $pass) ? "$pass@" : '';
  81. $path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
  82. $query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
  83. $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
  84. return "$scheme$user$pass$host$port$path$query$fragment";
  85. }
  86. }
  87. function micropub_post($endpoint, $params, $access_token) {
  88. $ch = curl_init();
  89. curl_setopt($ch, CURLOPT_URL, $endpoint);
  90. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  91. 'Authorization: Bearer ' . $access_token,
  92. 'Content-Type: application/json',
  93. 'Accept: application/json'
  94. ));
  95. curl_setopt($ch, CURLOPT_POST, true);
  96. $post = json_encode($params);
  97. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  98. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  99. curl_setopt($ch, CURLOPT_HEADER, true);
  100. curl_setopt($ch, CURLINFO_HEADER_OUT, true);
  101. $response = curl_exec($ch);
  102. $error = curl_error($ch);
  103. $sent_headers = curl_getinfo($ch, CURLINFO_HEADER_OUT);
  104. $request = $sent_headers . $post;
  105. return array(
  106. 'request' => $request,
  107. 'response' => $response,
  108. 'error' => $error,
  109. 'curlinfo' => curl_getinfo($ch)
  110. );
  111. }
  112. function micropub_media_post($endpoint, $access_token, $file) {
  113. $ch = curl_init();
  114. curl_setopt($ch, CURLOPT_URL, $endpoint);
  115. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  116. 'Authorization: Bearer ' . $access_token
  117. ));
  118. curl_setopt($ch, CURLOPT_POST, true);
  119. $post = [
  120. 'file' => new CURLFile($file)
  121. ];
  122. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  123. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  124. curl_setopt($ch, CURLOPT_HEADER, true);
  125. curl_setopt($ch, CURLINFO_HEADER_OUT, true);
  126. curl_setopt($ch, CURLOPT_TIMEOUT, 20);
  127. $response = curl_exec($ch);
  128. $error = curl_error($ch);
  129. $sent_headers = curl_getinfo($ch, CURLINFO_HEADER_OUT);
  130. return array(
  131. 'response' => $response,
  132. 'error' => $error,
  133. 'curlinfo' => curl_getinfo($ch)
  134. );
  135. }
  136. function micropub_get($endpoint, $params, $access_token) {
  137. $url = parse_url($endpoint);
  138. if(!k($url, 'query')) {
  139. $url['query'] = http_build_query($params);
  140. } else {
  141. $url['query'] .= '&' . http_build_query($params);
  142. }
  143. $endpoint = http_build_url($url);
  144. $ch = curl_init();
  145. curl_setopt($ch, CURLOPT_URL, $endpoint);
  146. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  147. 'Authorization: Bearer ' . $access_token,
  148. 'Accept: application/json',
  149. ));
  150. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  151. $response = curl_exec($ch);
  152. $data = array();
  153. if($response) {
  154. $data = @json_decode($response, true);
  155. }
  156. $error = curl_error($ch);
  157. return array(
  158. 'response' => $response,
  159. 'data' => $data,
  160. 'error' => $error,
  161. 'curlinfo' => curl_getinfo($ch)
  162. );
  163. }
  164. function get_micropub_config(&$user) {
  165. $targets = array();
  166. $r = micropub_get($user->micropub_endpoint, ['q'=>'config'], $user->access_token);
  167. if($r['data'] && is_array($r['data']) && array_key_exists('media-endpoint', $r['data'])) {
  168. $user->micropub_media_endpoint = $r['data']['media-endpoint'];
  169. $user->save();
  170. }
  171. return array(
  172. 'response' => $r
  173. );
  174. }
  175. function build_static_map_url($latitude, $longitude, $height, $width, $zoom) {
  176. return '/map.png?marker[]=lat:' . $latitude . ';lng:' . $longitude . ';icon:small-green-cutout&width=' . $width . '&height=' . $height . '&zoom=' . $zoom;
  177. }
  178. function relative_time($date) {
  179. static $rel;
  180. if(!isset($rel)) {
  181. $config = array(
  182. 'language' => '\RelativeTime\Languages\English',
  183. 'separator' => ', ',
  184. 'suffix' => true,
  185. 'truncate' => 1,
  186. );
  187. $rel = new \RelativeTime\RelativeTime($config);
  188. }
  189. return $rel->timeAgo($date);
  190. }
  191. function date_iso8601($date_string, $tz_offset) {
  192. $date = new DateTime($date_string);
  193. if($tz_offset > 0)
  194. $date->add(new DateInterval('PT'.$tz_offset.'S'));
  195. elseif($tz_offset < 0)
  196. $date->sub(new DateInterval('PT'.abs($tz_offset).'S'));
  197. $tz = tz_seconds_to_offset($tz_offset);
  198. return $date->format('Y-m-d\TH:i:s') . $tz;
  199. }
  200. function tz_seconds_to_offset($seconds) {
  201. return ($seconds < 0 ? '-' : '+') . sprintf('%02d:%02d', abs($seconds/60/60), ($seconds/60)%60);
  202. }
  203. function tz_offset_to_seconds($offset) {
  204. if(preg_match('/([+-])(\d{2}):?(\d{2})/', $offset, $match)) {
  205. $sign = ($match[1] == '-' ? -1 : 1);
  206. return (($match[2] * 60 * 60) + ($match[3] * 60)) * $sign;
  207. } else {
  208. return 0;
  209. }
  210. }
  211. function entry_url($entry, $user) {
  212. return $entry->canonical_url ?: Config::$base_url . $user->url . '/' . $entry->id;
  213. }
  214. function entry_date($entry, $user) {
  215. $date = new DateTime($entry->published);
  216. if($entry->tz_offset > 0)
  217. $date->add(new DateInterval('PT'.$entry->tz_offset.'S'));
  218. elseif($entry->tz_offset < 0)
  219. $date->sub(new DateInterval('PT'.abs($entry->tz_offset).'S'));
  220. $tz = tz_seconds_to_offset($entry->tz_offset);
  221. return new DateTime($date->format('Y-m-d\TH:i:s') . $tz);
  222. // Can switch back to this later if I prompt the user for a named timezone instead of just an offset
  223. // $tz = new DateTimeZone($entry->timezone);
  224. // $date->setTimeZone($tz);
  225. // return $date;
  226. }
  227. function validate_photo(&$file) {
  228. try {
  229. if ($_SERVER['REQUEST_METHOD'] == 'POST' && count($_POST) < 1 ) {
  230. throw new RuntimeException('File upload size exceeded.');
  231. }
  232. // Undefined | Multiple Files | $_FILES Corruption Attack
  233. // If this request falls under any of them, treat it invalid.
  234. if (
  235. !isset($file['error']) ||
  236. is_array($file['error'])
  237. ) {
  238. throw new RuntimeException('Invalid parameters.');
  239. }
  240. // Check $file['error'] value.
  241. switch ($file['error']) {
  242. case UPLOAD_ERR_OK:
  243. break;
  244. case UPLOAD_ERR_NO_FILE:
  245. throw new RuntimeException('No file sent.');
  246. case UPLOAD_ERR_INI_SIZE:
  247. case UPLOAD_ERR_FORM_SIZE:
  248. throw new RuntimeException('Exceeded filesize limit.');
  249. default:
  250. throw new RuntimeException('Unknown errors.');
  251. }
  252. // You should also check filesize here.
  253. if ($file['size'] > 4000000) {
  254. throw new RuntimeException('Exceeded filesize limit.');
  255. }
  256. // DO NOT TRUST $file['mime'] VALUE !!
  257. // Check MIME Type by yourself.
  258. $finfo = new finfo(FILEINFO_MIME_TYPE);
  259. if (false === $ext = array_search(
  260. $finfo->file($file['tmp_name']),
  261. array(
  262. 'jpg' => 'image/jpeg',
  263. 'png' => 'image/png',
  264. 'gif' => 'image/gif',
  265. ),
  266. true
  267. )) {
  268. throw new RuntimeException('Invalid file format.');
  269. }
  270. } catch (RuntimeException $e) {
  271. return $e->getMessage();
  272. }
  273. }
  274. // Reads the exif rotation data and actually rotates the photo.
  275. // Only does anything if the exif library is loaded, otherwise is a noop.
  276. function correct_photo_rotation($filename) {
  277. if(class_exists('IMagick')) {
  278. $image = new IMagick($filename);
  279. $orientation = $image->getImageOrientation();
  280. switch($orientation) {
  281. case IMagick::ORIENTATION_BOTTOMRIGHT:
  282. $image->rotateImage(new ImagickPixel('#00000000'), 180);
  283. break;
  284. case IMagick::ORIENTATION_RIGHTTOP:
  285. $image->rotateImage(new ImagickPixel('#00000000'), 90);
  286. break;
  287. case IMagick::ORIENTATION_LEFTBOTTOM:
  288. $image->rotateImage(new ImagickPixel('#00000000'), -90);
  289. break;
  290. }
  291. $image->setImageOrientation(IMagick::ORIENTATION_TOPLEFT);
  292. $image->writeImage($filename);
  293. }
  294. }
  295. function default_drink_options() {
  296. return [
  297. ['title'=>'Coffee','subtitle'=>'','type'=>'drink'],
  298. ['title'=>'Beer','subtitle'=>'','type'=>'drink'],
  299. ['title'=>'Cocktail','subtitle'=>'','type'=>'drink'],
  300. ['title'=>'Tea','subtitle'=>'','type'=>'drink'],
  301. ['title'=>'Mimosa','subtitle'=>'','type'=>'drink'],
  302. ['title'=>'Latte','subtitle'=>'','type'=>'drink'],
  303. ['title'=>'Champagne','subtitle'=>'','type'=>'drink']
  304. ];
  305. }
  306. function default_food_options() {
  307. return [
  308. ['title'=>'Burrito','subtitle'=>'','type'=>'eat'],
  309. ['title'=>'Banana','subtitle'=>'','type'=>'eat'],
  310. ['title'=>'Pizza','subtitle'=>'','type'=>'eat'],
  311. ['title'=>'Soup','subtitle'=>'','type'=>'eat'],
  312. ['title'=>'Tacos','subtitle'=>'','type'=>'eat'],
  313. ['title'=>'Mac and Cheese','subtitle'=>'','type'=>'eat']
  314. ];
  315. }
  316. function query_user_nearby_options($type, $user_id, $latitude, $longitude) {
  317. $published = date('Y-m-d H:i:s', strtotime('-4 months'));
  318. $options = [];
  319. $bin_size = 1000;
  320. $optionsQ = ORM::for_table('entries')->raw_query('
  321. SELECT *, SUM(num) AS num FROM
  322. (
  323. SELECT id, published, content, type,
  324. round(gc_distance(latitude, longitude, :latitude, :longitude) / '.$bin_size.') AS dist,
  325. COUNT(1) AS num
  326. FROM entries
  327. WHERE user_id = :user_id
  328. AND type = :type
  329. AND gc_distance(latitude, longitude, :latitude, :longitude) IS NOT NULL
  330. AND published > :published /* only look at the last 4 months of posts */
  331. GROUP BY content, round(gc_distance(latitude, longitude, :latitude, :longitude) / '.$bin_size.') /* group by 1km buckets */
  332. ORDER BY round(gc_distance(latitude, longitude, :latitude, :longitude) / '.$bin_size.'), COUNT(1) DESC /* order by distance and frequency */
  333. ) AS tmp
  334. WHERE num >= 1 /* only include things that have been used more than 2 times in this bucket */
  335. AND dist < 1000
  336. GROUP BY content /* group by name again */
  337. ORDER BY SUM(num) DESC /* order by overall frequency */
  338. LIMIT 6
  339. ', ['user_id'=>$user_id, 'type'=>$type, 'latitude'=>$latitude, 'longitude'=>$longitude, 'published'=>$published])->find_many();
  340. foreach($optionsQ as $o) {
  341. $options[] = [
  342. 'title' => $o->content,
  343. 'subtitle' => query_last_eaten($user_id, $o->type, $o->content),
  344. 'type' => $o->type
  345. ];
  346. }
  347. return $options;
  348. }
  349. function query_user_frequent_options($type, $user_id) {
  350. $published = date('Y-m-d H:i:s', strtotime('-4 months'));
  351. $options = [];
  352. $optionsQ = ORM::for_table('entries')->raw_query('
  353. SELECT type, content, MAX(published) AS published
  354. FROM entries
  355. WHERE user_id = :user_id
  356. AND type = :type
  357. AND published > :published
  358. GROUP BY content
  359. ORDER BY COUNT(1) DESC
  360. LIMIT 6
  361. ', ['user_id'=>$user_id, 'type'=>$type, 'published'=>$published])->find_many();
  362. foreach($optionsQ as $o) {
  363. $options[] = [
  364. 'title' => $o->content,
  365. 'subtitle' => query_last_eaten($user_id, $o->type, $o->content),
  366. 'type' => $o->type
  367. ];
  368. }
  369. return $options;
  370. }
  371. function query_last_eaten($user_id, $type, $content) {
  372. $lastQ = ORM::for_table('entries')->raw_query('
  373. SELECT published, timezone, tz_offset
  374. FROM entries
  375. WHERE user_id=:user_id
  376. AND type=:type
  377. AND content=:content
  378. ORDER BY published DESC
  379. LIMIT 1;
  380. ', ['user_id'=>$user_id, 'type'=>$type, 'content'=>$content])->find_one();
  381. if(!$lastQ)
  382. return '';
  383. $timestamp = strtotime($lastQ->published);
  384. // If less than 8 hours ago, use relative time, otherwise show the actual time
  385. if(time() - $timestamp > 60*60*8) {
  386. if($lastQ->timezone) {
  387. $date = new DateTime($lastQ->published);
  388. $date->setTimeZone(new DateTimeZone($lastQ->timezone));
  389. } else {
  390. $iso = date_iso8601($lastQ->published, $lastQ->tz_offset);
  391. $date = new DateTime($iso);
  392. }
  393. return $date->format('D, M j, g:ia');
  394. } else {
  395. $config = array(
  396. 'language' => '\RelativeTime\Languages\English',
  397. 'separator' => ', ',
  398. 'suffix' => true,
  399. 'truncate' => 1,
  400. );
  401. $relativeTime = new \RelativeTime\RelativeTime($config);
  402. return $relativeTime->timeAgo($lastQ->published);
  403. }
  404. }
  405. function get_entry_options($user_id, $latitude=null, $longitude=null) {
  406. /*
  407. Sections:
  408. * Recent posts (food + drink combined)
  409. * Drinks (based on location)
  410. * custom box below
  411. * Food (based on location)
  412. * custom box below
  413. If no recent entries, remove that section.
  414. If no nearby food/drinks, use a default list
  415. */
  416. $recent = [];
  417. $drinks = [];
  418. $food = [];
  419. $recentQ = ORM::for_table('entries')->raw_query('
  420. SELECT type, content FROM
  421. (SELECT *
  422. FROM entries
  423. WHERE user_id = :user_id
  424. ORDER BY published DESC) AS tmp
  425. GROUP BY content, type
  426. ORDER BY MAX(published) DESC
  427. LIMIT 6', ['user_id'=>$user_id])->find_many();
  428. $last_latitude = false;
  429. $last_longitude = false;
  430. foreach($recentQ as $r) {
  431. if($last_latitude == false && $r->latitude) {
  432. $last_latitude = $r->latitude;
  433. $last_longitude = $r->longitude;
  434. }
  435. $recent[] = [
  436. 'title' => $r->content,
  437. 'subtitle' => query_last_eaten($user_id, $r->type, $r->content),
  438. 'type' => $r->type
  439. ];
  440. }
  441. // If no location was provided, but there is a location in the most recent entry, use that
  442. if($latitude == null && $last_latitude) {
  443. $latitude = $last_latitude;
  444. $longitude = $last_longitude;
  445. }
  446. $num_options = 6;
  447. if($latitude) {
  448. $drinks = query_user_nearby_options('drink', $user_id, $latitude, $longitude);
  449. }
  450. // If there's no nearby data (like if the user isn't including location) then return the most frequently used ones instead
  451. if(count($drinks) < $num_options) {
  452. $frequent_drinks = query_user_frequent_options('drink', $user_id);
  453. $drinks = array_merge($drinks, $frequent_drinks);
  454. }
  455. // If there's less than 4 options available, fill the list with the default options
  456. if(count($drinks) < $num_options) {
  457. $default_drinks = default_drink_options();
  458. $drinks = array_merge($drinks, $default_drinks);
  459. }
  460. $drinks = array_slice($drinks, 0, $num_options);
  461. if($latitude) {
  462. $food = query_user_nearby_options('eat', $user_id, $latitude, $longitude);
  463. }
  464. if(count($food) == 0) {
  465. $frequent_food = query_user_frequent_options('eat', $user_id);
  466. $food = array_merge($food, $frequent_food);
  467. }
  468. if(count($food) < $num_options) {
  469. $default_food = default_food_options();
  470. $food = array_merge($food, $default_food);
  471. }
  472. $food = array_slice($food, 0, $num_options);
  473. $options = [
  474. 'sections' => [
  475. [
  476. 'title' => 'Recent',
  477. 'items' => $recent
  478. ],
  479. [
  480. 'title' => 'Drinks',
  481. 'items' => $drinks
  482. ],
  483. [
  484. 'title' => 'Food',
  485. 'items' => $food
  486. ]
  487. ]
  488. ];
  489. if(count($options['sections'][0]['items']) == 0)
  490. array_shift($options['sections']);
  491. return $options;
  492. }