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.

360 lines
11 KiB

6 years ago
  1. <?php
  2. if(isset(Config::$dbType) && Config::$dbType == 'sqlite') {
  3. ORM::configure('sqlite:' . Config::$dbFilePath);
  4. } else {
  5. ORM::configure('mysql:host=' . Config::$dbHost . ';dbname=' . Config::$dbName);
  6. ORM::configure('username', Config::$dbUsername);
  7. ORM::configure('password', Config::$dbPassword);
  8. }
  9. function render($page, $data) {
  10. global $app;
  11. return $app->render('layout.php', array_merge($data, array('page' => $page)));
  12. };
  13. function partial($template, $data=array(), $debug=false) {
  14. global $app;
  15. if($debug) {
  16. $tpl = new Savant3(\Slim\Extras\Views\Savant::$savantOptions);
  17. echo '<pre>' . $tpl->fetch($template . '.php') . '</pre>';
  18. return '';
  19. }
  20. ob_start();
  21. $tpl = new Savant3(\Slim\Extras\Views\Savant::$savantOptions);
  22. foreach($data as $k=>$v) {
  23. $tpl->{$k} = $v;
  24. }
  25. $tpl->display($template . '.php');
  26. return ob_get_clean();
  27. }
  28. function js_bookmarklet($partial, $context) {
  29. return str_replace('+','%20',urlencode(str_replace(array("\n"),array(''),partial($partial, $context))));
  30. }
  31. function session($key) {
  32. if(array_key_exists($key, $_SESSION))
  33. return $_SESSION[$key];
  34. else
  35. return null;
  36. }
  37. function k($a, $k, $default=null) {
  38. if(is_array($k)) {
  39. $result = true;
  40. foreach($k as $key) {
  41. $result = $result && array_key_exists($key, $a);
  42. }
  43. return $result;
  44. } else {
  45. if(is_array($a) && array_key_exists($k, $a) && $a[$k])
  46. return $a[$k];
  47. elseif(is_object($a) && property_exists($a, $k) && $a->$k)
  48. return $a->$k;
  49. else
  50. return $default;
  51. }
  52. }
  53. function get_timezone($lat, $lng) {
  54. try {
  55. $ch = curl_init();
  56. curl_setopt($ch, CURLOPT_URL, 'http://atlas.p3k.io/api/timezone?latitude='.$lat.'&longitude='.$lng);
  57. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  58. $response = curl_exec($ch);
  59. $tz = @json_decode($response);
  60. if($tz)
  61. return new DateTimeZone($tz->timezone);
  62. } catch(Exception $e) {
  63. return null;
  64. }
  65. return null;
  66. }
  67. if(!function_exists('http_build_url')) {
  68. function http_build_url($parsed_url) {
  69. $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
  70. $host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
  71. $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
  72. $user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
  73. $pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
  74. $pass = ($user || $pass) ? "$pass@" : '';
  75. $path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
  76. $query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
  77. $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
  78. return "$scheme$user$pass$host$port$path$query$fragment";
  79. }
  80. }
  81. function micropub_post_for_user(&$user, $params, $file_path = NULL, $json = false) {
  82. // Now send to the micropub endpoint
  83. $r = micropub_post($user->micropub_endpoint, $params, $user->micropub_access_token, $file_path, $json);
  84. $user->last_micropub_response = substr(json_encode($r), 0, 1024);
  85. $user->last_micropub_response_date = date('Y-m-d H:i:s');
  86. // Check the response and look for a "Location" header containing the URL
  87. if($r['response'] && preg_match('/Location: (.+)/', $r['response'], $match)) {
  88. $r['location'] = trim($match[1]);
  89. $user->micropub_success = 1;
  90. } else {
  91. $r['location'] = false;
  92. }
  93. $user->save();
  94. return $r;
  95. }
  96. function micropub_media_post_for_user(&$user, $file_path) {
  97. // Send to the media endpoint
  98. $r = micropub_post($user->micropub_media_endpoint, [], $user->micropub_access_token, $file_path, true, 'file');
  99. // Check the response and look for a "Location" header containing the URL
  100. if($r['response'] && preg_match('/Location: (.+)/', $r['response'], $match)) {
  101. $r['location'] = trim($match[1]);
  102. } else {
  103. $r['location'] = false;
  104. }
  105. return $r;
  106. }
  107. function micropub_post($endpoint, $params, $access_token, $file_path = NULL, $json = false, $file_prop = 'photo') {
  108. $ch = curl_init();
  109. curl_setopt($ch, CURLOPT_URL, $endpoint);
  110. curl_setopt($ch, CURLOPT_POST, true);
  111. // Send the access token in both the header and post body to support more clients
  112. // https://github.com/aaronpk/Quill/issues/4
  113. // http://indiewebcamp.com/irc/2015-02-14#t1423955287064
  114. $httpheaders = array('Authorization: Bearer ' . $access_token);
  115. if(!$json) {
  116. $params = array_merge(array(
  117. 'h' => 'entry',
  118. 'access_token' => $access_token
  119. ), $params);
  120. }
  121. if(!$file_path) {
  122. if($json) {
  123. $params['access_token'] = $access_token;
  124. $httpheaders[] = 'Content-type: application/json';
  125. $post = json_encode($params);
  126. } else {
  127. $post = http_build_query($params);
  128. $post = preg_replace('/%5B[0-9]+%5D/', '%5B%5D', $post); // change [0] to []
  129. }
  130. } else {
  131. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  132. $mimetype = finfo_file($finfo, $file_path);
  133. $multipart = new p3k\Multipart();
  134. $multipart->addArray($params);
  135. $multipart->addFile($file_prop, $file_path, $mimetype);
  136. $post = $multipart->data();
  137. array_push($httpheaders, 'Content-Type: ' . $multipart->contentType());
  138. }
  139. curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheaders);
  140. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  141. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  142. curl_setopt($ch, CURLOPT_HEADER, true);
  143. curl_setopt($ch, CURLINFO_HEADER_OUT, true);
  144. $response = curl_exec($ch);
  145. $error = curl_error($ch);
  146. $sent_headers = curl_getinfo($ch, CURLINFO_HEADER_OUT);
  147. $request = $sent_headers . (is_string($post) ? $post : http_build_query($post));
  148. return array(
  149. 'request' => $request,
  150. 'response' => $response,
  151. 'error' => $error,
  152. 'curlinfo' => curl_getinfo($ch)
  153. );
  154. }
  155. function micropub_get($endpoint, $params, $access_token) {
  156. $url = parse_url($endpoint);
  157. if(!k($url, 'query')) {
  158. $url['query'] = http_build_query($params);
  159. } else {
  160. $url['query'] .= '&' . http_build_query($params);
  161. }
  162. $endpoint = http_build_url($url);
  163. $ch = curl_init();
  164. curl_setopt($ch, CURLOPT_URL, $endpoint);
  165. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  166. 'Authorization: Bearer ' . $access_token,
  167. 'Accept: application/json'
  168. ));
  169. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  170. $response = curl_exec($ch);
  171. $data = array();
  172. if($response) {
  173. $data = json_decode($response, true);
  174. }
  175. $error = curl_error($ch);
  176. return array(
  177. 'response' => $response,
  178. 'data' => $data,
  179. 'error' => $error,
  180. 'curlinfo' => curl_getinfo($ch)
  181. );
  182. }
  183. function get_micropub_config(&$user, $query=[]) {
  184. $targets = [];
  185. $r = micropub_get($user->micropub_endpoint, $query, $user->micropub_access_token);
  186. if($r['data'] && array_key_exists('syndicate-to', $r['data'])) {
  187. if(is_array($r['data']['syndicate-to'])) {
  188. $data = $r['data']['syndicate-to'];
  189. } else {
  190. $data = [];
  191. }
  192. foreach($data as $t) {
  193. if(array_key_exists('service', $t) && array_key_exists('photo', $t['service'])) {
  194. $icon = $t['service']['photo'];
  195. } else {
  196. $icon = false;
  197. }
  198. if(array_key_exists('uid', $t) && array_key_exists('name', $t)) {
  199. $targets[] = [
  200. 'target' => $t['name'],
  201. 'uid' => $t['uid'],
  202. 'favicon' => $icon
  203. ];
  204. }
  205. }
  206. }
  207. if(count($targets))
  208. $user->syndication_targets = json_encode($targets);
  209. $media_endpoint = false;
  210. if($r['data'] && is_array($r['data']) && array_key_exists('media-endpoint', $r['data'])) {
  211. $media_endpoint = $r['data']['media-endpoint'];
  212. $user->micropub_media_endpoint = $media_endpoint;
  213. }
  214. if(count($targets) || $media_endpoint) {
  215. $user->save();
  216. }
  217. return [
  218. 'targets' => $targets,
  219. 'response' => $r
  220. ];
  221. }
  222. function static_map($latitude, $longitude, $height=180, $width=700, $zoom=14) {
  223. return 'https://atlas.p3k.io/map/img?marker[]=lat:' . $latitude . ';lng:' . $longitude . ';icon:small-blue-cutout&basemap=gray&width=' . $width . '&height=' . $height . '&zoom=' . $zoom;
  224. }
  225. function relative_time($date) {
  226. static $rel;
  227. if(!isset($rel)) {
  228. $config = array(
  229. 'language' => '\RelativeTime\Languages\English',
  230. 'separator' => ', ',
  231. 'suffix' => true,
  232. 'truncate' => 1,
  233. );
  234. $rel = new \RelativeTime\RelativeTime($config);
  235. }
  236. return $rel->timeAgo($date);
  237. }
  238. function instagram_client() {
  239. return new Andreyco\Instagram\Client(array(
  240. 'apiKey' => Config::$instagramClientID,
  241. 'apiSecret' => Config::$instagramClientSecret,
  242. 'apiCallback' => Config::$base_url . 'auth/instagram/callback',
  243. 'scope' => array('basic','likes'),
  244. ));
  245. }
  246. function validate_photo(&$file) {
  247. try {
  248. if ($_SERVER['REQUEST_METHOD'] == 'POST' && count($_POST) < 1 ) {
  249. throw new RuntimeException('File upload size exceeded.');
  250. }
  251. // Undefined | Multiple Files | $_FILES Corruption Attack
  252. // If this request falls under any of them, treat it invalid.
  253. if (
  254. !isset($file['error']) ||
  255. is_array($file['error'])
  256. ) {
  257. throw new RuntimeException('Invalid parameters.');
  258. }
  259. // Check $file['error'] value.
  260. switch ($file['error']) {
  261. case UPLOAD_ERR_OK:
  262. break;
  263. case UPLOAD_ERR_NO_FILE:
  264. throw new RuntimeException('No file sent.');
  265. case UPLOAD_ERR_INI_SIZE:
  266. case UPLOAD_ERR_FORM_SIZE:
  267. throw new RuntimeException('Exceeded filesize limit.');
  268. default:
  269. throw new RuntimeException('Unknown errors.');
  270. }
  271. // You should also check filesize here.
  272. if ($file['size'] > 4000000) {
  273. throw new RuntimeException('Exceeded filesize limit.');
  274. }
  275. // DO NOT TRUST $file['mime'] VALUE !!
  276. // Check MIME Type by yourself.
  277. $finfo = new finfo(FILEINFO_MIME_TYPE);
  278. if (false === $ext = array_search(
  279. $finfo->file($file['tmp_name']),
  280. array(
  281. 'jpg' => 'image/jpeg',
  282. 'png' => 'image/png',
  283. 'gif' => 'image/gif',
  284. ),
  285. true
  286. )) {
  287. throw new RuntimeException('Invalid file format.');
  288. }
  289. } catch (RuntimeException $e) {
  290. return $e->getMessage();
  291. }
  292. }
  293. // Reads the exif rotation data and actually rotates the photo.
  294. // Only does anything if the exif library is loaded, otherwise is a noop.
  295. function correct_photo_rotation($filename) {
  296. if(class_exists('IMagick')) {
  297. $image = new IMagick($filename);
  298. $orientation = $image->getImageOrientation();
  299. switch($orientation) {
  300. case IMagick::ORIENTATION_BOTTOMRIGHT:
  301. $image->rotateImage(new ImagickPixel('#00000000'), 180);
  302. break;
  303. case IMagick::ORIENTATION_RIGHTTOP:
  304. $image->rotateImage(new ImagickPixel('#00000000'), 90);
  305. break;
  306. case IMagick::ORIENTATION_LEFTBOTTOM:
  307. $image->rotateImage(new ImagickPixel('#00000000'), -90);
  308. break;
  309. }
  310. $image->setImageOrientation(IMagick::ORIENTATION_TOPLEFT);
  311. $image->writeImage($filename);
  312. }
  313. }