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.

583 lines
18 KiB

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