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.

576 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 get_micropub_checkin(&$user) {
  176. $r = micropub_get($user->micropub_endpoint, ['q' => 'source', 'limit' => 1, 'post-type' => 'checkin'], $user->access_token);
  177. $url = null;
  178. $name = null;
  179. $lat = null;
  180. $lng = null;
  181. if($r['data'] && is_array($r['data'])) {
  182. if(isset($r['data']['items'][0]['properties']['checkin'][0]) &&
  183. isset($r['data']['items'][0]['properties']['checkin'][0]['properties']['name'][0])) {
  184. $checkin = $r['data']['items'][0]['properties']['checkin'][0];
  185. $url = $r['data']['items'][0]['properties']['url'][0];
  186. $name = $checkin['properties']['name'][0];
  187. $lat = $checkin['properties']['latitude'][0];
  188. $lng = $checkin['properties']['longitude'][0];
  189. }
  190. }
  191. return [
  192. 'url' => $url,
  193. 'name' => $name,
  194. 'lat' => $lat,
  195. 'lng' => $lng,
  196. ];
  197. }
  198. function build_static_map_url($latitude, $longitude, $height, $width, $zoom) {
  199. return '/map.png?marker[]=lat:' . $latitude . ';lng:' . $longitude . ';icon:small-green-cutout&width=' . $width . '&height=' . $height . '&zoom=' . $zoom;
  200. }
  201. function relative_time($date) {
  202. static $rel;
  203. if(!isset($rel)) {
  204. $config = array(
  205. 'language' => '\RelativeTime\Languages\English',
  206. 'separator' => ', ',
  207. 'suffix' => true,
  208. 'truncate' => 1,
  209. );
  210. $rel = new \RelativeTime\RelativeTime($config);
  211. }
  212. return $rel->timeAgo($date);
  213. }
  214. function date_iso8601($date_string, $tz_offset) {
  215. $date = new DateTime($date_string);
  216. if($tz_offset > 0)
  217. $date->add(new DateInterval('PT'.$tz_offset.'S'));
  218. elseif($tz_offset < 0)
  219. $date->sub(new DateInterval('PT'.abs($tz_offset).'S'));
  220. $tz = tz_seconds_to_offset($tz_offset);
  221. return $date->format('Y-m-d\TH:i:s') . $tz;
  222. }
  223. function tz_seconds_to_offset($seconds) {
  224. return ($seconds < 0 ? '-' : '+') . sprintf('%02d:%02d', abs($seconds/60/60), ($seconds/60)%60);
  225. }
  226. function tz_offset_to_seconds($offset) {
  227. if(preg_match('/([+-])(\d{2}):?(\d{2})/', $offset, $match)) {
  228. $sign = ($match[1] == '-' ? -1 : 1);
  229. return (($match[2] * 60 * 60) + ($match[3] * 60)) * $sign;
  230. } else {
  231. return 0;
  232. }
  233. }
  234. function entry_url($entry, $user) {
  235. return $entry->canonical_url ?: Config::$base_url . $user->url . '/' . $entry->id;
  236. }
  237. function entry_date($entry, $user) {
  238. $date = new DateTime($entry->published);
  239. if($entry->tz_offset > 0)
  240. $date->add(new DateInterval('PT'.$entry->tz_offset.'S'));
  241. elseif($entry->tz_offset < 0)
  242. $date->sub(new DateInterval('PT'.abs($entry->tz_offset).'S'));
  243. $tz = tz_seconds_to_offset($entry->tz_offset);
  244. return new DateTime($date->format('Y-m-d\TH:i:s') . $tz);
  245. // Can switch back to this later if I prompt the user for a named timezone instead of just an offset
  246. // $tz = new DateTimeZone($entry->timezone);
  247. // $date->setTimeZone($tz);
  248. // return $date;
  249. }
  250. function validate_photo(&$file) {
  251. try {
  252. if ($_SERVER['REQUEST_METHOD'] == 'POST' && count($_POST) < 1 ) {
  253. throw new RuntimeException('File upload size exceeded.');
  254. }
  255. // Undefined | Multiple Files | $_FILES Corruption Attack
  256. // If this request falls under any of them, treat it invalid.
  257. if (
  258. !isset($file['error']) ||
  259. is_array($file['error'])
  260. ) {
  261. throw new RuntimeException('Invalid parameters.');
  262. }
  263. // Check $file['error'] value.
  264. switch ($file['error']) {
  265. case UPLOAD_ERR_OK:
  266. break;
  267. case UPLOAD_ERR_NO_FILE:
  268. throw new RuntimeException('No file sent.');
  269. case UPLOAD_ERR_INI_SIZE:
  270. case UPLOAD_ERR_FORM_SIZE:
  271. throw new RuntimeException('Exceeded filesize limit.');
  272. default:
  273. throw new RuntimeException('Unknown errors.');
  274. }
  275. // You should also check filesize here.
  276. if ($file['size'] > 4000000) {
  277. throw new RuntimeException('Exceeded filesize limit.');
  278. }
  279. // DO NOT TRUST $file['mime'] VALUE !!
  280. // Check MIME Type by yourself.
  281. $finfo = new finfo(FILEINFO_MIME_TYPE);
  282. if (false === $ext = array_search(
  283. $finfo->file($file['tmp_name']),
  284. array(
  285. 'jpg' => 'image/jpeg',
  286. 'png' => 'image/png',
  287. 'gif' => 'image/gif',
  288. ),
  289. true
  290. )) {
  291. throw new RuntimeException('Invalid file format.');
  292. }
  293. } catch (RuntimeException $e) {
  294. return $e->getMessage();
  295. }
  296. }
  297. // Reads the exif rotation data and actually rotates the photo.
  298. // Only does anything if the exif library is loaded, otherwise is a noop.
  299. function correct_photo_rotation($filename) {
  300. if(class_exists('IMagick')) {
  301. $image = new IMagick($filename);
  302. $orientation = $image->getImageOrientation();
  303. switch($orientation) {
  304. case IMagick::ORIENTATION_BOTTOMRIGHT:
  305. $image->rotateImage(new ImagickPixel('#00000000'), 180);
  306. break;
  307. case IMagick::ORIENTATION_RIGHTTOP:
  308. $image->rotateImage(new ImagickPixel('#00000000'), 90);
  309. break;
  310. case IMagick::ORIENTATION_LEFTBOTTOM:
  311. $image->rotateImage(new ImagickPixel('#00000000'), -90);
  312. break;
  313. }
  314. $image->setImageOrientation(IMagick::ORIENTATION_TOPLEFT);
  315. $image->writeImage($filename);
  316. }
  317. }
  318. function default_drink_options() {
  319. return [
  320. ['title'=>'Coffee','subtitle'=>'','type'=>'drink'],
  321. ['title'=>'Beer','subtitle'=>'','type'=>'drink'],
  322. ['title'=>'Cocktail','subtitle'=>'','type'=>'drink'],
  323. ['title'=>'Tea','subtitle'=>'','type'=>'drink'],
  324. ['title'=>'Mimosa','subtitle'=>'','type'=>'drink'],
  325. ['title'=>'Latte','subtitle'=>'','type'=>'drink'],
  326. ['title'=>'Champagne','subtitle'=>'','type'=>'drink']
  327. ];
  328. }
  329. function default_food_options() {
  330. return [
  331. ['title'=>'Burrito','subtitle'=>'','type'=>'eat'],
  332. ['title'=>'Banana','subtitle'=>'','type'=>'eat'],
  333. ['title'=>'Pizza','subtitle'=>'','type'=>'eat'],
  334. ['title'=>'Soup','subtitle'=>'','type'=>'eat'],
  335. ['title'=>'Tacos','subtitle'=>'','type'=>'eat'],
  336. ['title'=>'Mac and Cheese','subtitle'=>'','type'=>'eat']
  337. ];
  338. }
  339. function query_user_nearby_options($type, $user_id, $latitude, $longitude) {
  340. $published = date('Y-m-d H:i:s', strtotime('-4 months'));
  341. $options = [];
  342. $bin_size = 1000;
  343. $optionsQ = ORM::for_table('entries')->raw_query('
  344. SELECT *, SUM(num) AS num FROM
  345. (
  346. SELECT id, published, content, type,
  347. round(gc_distance(latitude, longitude, :latitude, :longitude) / '.$bin_size.') AS dist,
  348. COUNT(1) AS num
  349. FROM entries
  350. WHERE user_id = :user_id
  351. AND type = :type
  352. AND gc_distance(latitude, longitude, :latitude, :longitude) IS NOT NULL
  353. AND published > :published /* only look at the last 4 months of posts */
  354. GROUP BY content, round(gc_distance(latitude, longitude, :latitude, :longitude) / '.$bin_size.') /* group by 1km buckets */
  355. ORDER BY round(gc_distance(latitude, longitude, :latitude, :longitude) / '.$bin_size.'), COUNT(1) DESC /* order by distance and frequency */
  356. ) AS tmp
  357. WHERE num >= 1 /* only include things that have been used more than 2 times in this bucket */
  358. AND dist < 1000
  359. GROUP BY content /* group by name again */
  360. ORDER BY SUM(num) DESC /* order by overall frequency */
  361. LIMIT 6
  362. ', ['user_id'=>$user_id, 'type'=>$type, 'latitude'=>$latitude, 'longitude'=>$longitude, 'published'=>$published])->find_many();
  363. foreach($optionsQ as $o) {
  364. $options[] = [
  365. 'title' => $o->content,
  366. 'subtitle' => query_last_eaten($user_id, $o->type, $o->content),
  367. 'type' => $o->type
  368. ];
  369. }
  370. return $options;
  371. }
  372. function query_user_frequent_options($type, $user_id) {
  373. $published = date('Y-m-d H:i:s', strtotime('-4 months'));
  374. $options = [];
  375. $optionsQ = ORM::for_table('entries')->raw_query('
  376. SELECT type, content, MAX(published) AS published
  377. FROM entries
  378. WHERE user_id = :user_id
  379. AND type = :type
  380. AND published > :published
  381. GROUP BY content
  382. ORDER BY COUNT(1) DESC
  383. LIMIT 6
  384. ', ['user_id'=>$user_id, 'type'=>$type, 'published'=>$published])->find_many();
  385. foreach($optionsQ as $o) {
  386. $options[] = [
  387. 'title' => $o->content,
  388. 'subtitle' => query_last_eaten($user_id, $o->type, $o->content),
  389. 'type' => $o->type
  390. ];
  391. }
  392. return $options;
  393. }
  394. function query_last_eaten($user_id, $type, $content) {
  395. $lastQ = ORM::for_table('entries')->raw_query('
  396. SELECT published, timezone, tz_offset
  397. FROM entries
  398. WHERE user_id=:user_id
  399. AND type=:type
  400. AND content=:content
  401. ORDER BY published DESC
  402. LIMIT 1;
  403. ', ['user_id'=>$user_id, 'type'=>$type, 'content'=>$content])->find_one();
  404. if(!$lastQ)
  405. return '';
  406. $timestamp = strtotime($lastQ->published);
  407. // If less than 8 hours ago, use relative time, otherwise show the actual time
  408. if(time() - $timestamp > 60*60*8) {
  409. if($lastQ->timezone) {
  410. $date = new DateTime($lastQ->published);
  411. $date->setTimeZone(new DateTimeZone($lastQ->timezone));
  412. } else {
  413. $iso = date_iso8601($lastQ->published, $lastQ->tz_offset);
  414. $date = new DateTime($iso);
  415. }
  416. return $date->format('D, M j, g:ia');
  417. } else {
  418. $config = array(
  419. 'language' => '\RelativeTime\Languages\English',
  420. 'separator' => ', ',
  421. 'suffix' => true,
  422. 'truncate' => 1,
  423. );
  424. $relativeTime = new \RelativeTime\RelativeTime($config);
  425. return $relativeTime->timeAgo($lastQ->published);
  426. }
  427. }
  428. function get_entry_options($user_id, $latitude=null, $longitude=null) {
  429. /*
  430. Sections:
  431. * Recent posts (food + drink combined)
  432. * Drinks (based on location)
  433. * custom box below
  434. * Food (based on location)
  435. * custom box below
  436. If no recent entries, remove that section.
  437. If no nearby food/drinks, use a default list
  438. */
  439. $recent = [];
  440. $drinks = [];
  441. $food = [];
  442. $recentQ = ORM::for_table('entries')->raw_query('
  443. SELECT type, content FROM
  444. (SELECT *
  445. FROM entries
  446. WHERE user_id = :user_id
  447. ORDER BY published DESC) AS tmp
  448. GROUP BY content, type
  449. ORDER BY MAX(published) DESC
  450. LIMIT 6', ['user_id'=>$user_id])->find_many();
  451. $last_latitude = false;
  452. $last_longitude = false;
  453. foreach($recentQ as $r) {
  454. if($last_latitude == false && $r->latitude) {
  455. $last_latitude = $r->latitude;
  456. $last_longitude = $r->longitude;
  457. }
  458. $recent[] = [
  459. 'title' => $r->content,
  460. 'subtitle' => query_last_eaten($user_id, $r->type, $r->content),
  461. 'type' => $r->type
  462. ];
  463. }
  464. // If no location was provided, but there is a location in the most recent entry, use that
  465. if($latitude == null && $last_latitude) {
  466. $latitude = $last_latitude;
  467. $longitude = $last_longitude;
  468. }
  469. $num_options = 6;
  470. if($latitude) {
  471. $drinks = query_user_nearby_options('drink', $user_id, $latitude, $longitude);
  472. }
  473. // If there's no nearby data (like if the user isn't including location) then return the most frequently used ones instead
  474. if(count($drinks) < $num_options) {
  475. $frequent_drinks = query_user_frequent_options('drink', $user_id);
  476. $drinks = array_merge($drinks, $frequent_drinks);
  477. }
  478. // If there's less than 4 options available, fill the list with the default options
  479. if(count($drinks) < $num_options) {
  480. $default_drinks = default_drink_options();
  481. $drinks = array_merge($drinks, $default_drinks);
  482. }
  483. $drinks = array_slice($drinks, 0, $num_options);
  484. if($latitude) {
  485. $food = query_user_nearby_options('eat', $user_id, $latitude, $longitude);
  486. }
  487. if(count($food) == 0) {
  488. $frequent_food = query_user_frequent_options('eat', $user_id);
  489. $food = array_merge($food, $frequent_food);
  490. }
  491. if(count($food) < $num_options) {
  492. $default_food = default_food_options();
  493. $food = array_merge($food, $default_food);
  494. }
  495. $food = array_slice($food, 0, $num_options);
  496. $options = [
  497. 'sections' => [
  498. [
  499. 'title' => 'Recent',
  500. 'items' => $recent
  501. ],
  502. [
  503. 'title' => 'Drinks',
  504. 'items' => $drinks
  505. ],
  506. [
  507. 'title' => 'Food',
  508. 'items' => $food
  509. ]
  510. ]
  511. ];
  512. if(count($options['sections'][0]['items']) == 0)
  513. array_shift($options['sections']);
  514. return $options;
  515. }