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.

382 lines
12 KiB

7 years ago
7 years ago
8 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 display_url($url) {
  54. $parts = parse_url($url);
  55. if(isset($parts['path']) && $parts['path'] != '' && $parts['path'] != '/') {
  56. return preg_replace('/^https?:\/\//','', $url);
  57. } else {
  58. return $parts['host'];
  59. }
  60. }
  61. if(!function_exists('http_build_url')) {
  62. function http_build_url($parsed_url) {
  63. $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
  64. $host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
  65. $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
  66. $user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
  67. $pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
  68. $pass = ($user || $pass) ? "$pass@" : '';
  69. $path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
  70. $query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
  71. $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
  72. return "$scheme$user$pass$host$port$path$query$fragment";
  73. }
  74. }
  75. function micropub_post_for_user(&$user, $params, $file_path = NULL, $json = false) {
  76. // Now send to the micropub endpoint
  77. $r = micropub_post($user->micropub_endpoint, $params, $user->micropub_access_token, $file_path, $json);
  78. $user->last_micropub_response = substr(json_encode($r), 0, 1024);
  79. $user->last_micropub_response_date = date('Y-m-d H:i:s');
  80. // Check the response and look for a "Location" header containing the URL
  81. if($r['response'] && ($r['code'] == 201 || $r['code'] == 202)
  82. && isset($r['headers']['Location'])) {
  83. $r['location'] = $r['headers']['Location'][0];
  84. $user->micropub_success = 1;
  85. } else {
  86. $r['location'] = false;
  87. }
  88. $user->save();
  89. return $r;
  90. }
  91. function micropub_media_post_for_user(&$user, $file_path) {
  92. // Send to the media endpoint
  93. $r = micropub_post($user->micropub_media_endpoint, [], $user->micropub_access_token, $file_path, true, 'file');
  94. // Check the response and look for a "Location" header containing the URL
  95. if($r['response'] && preg_match('/Location: (.+)/', $r['response'], $match)) {
  96. $r['location'] = trim($match[1]);
  97. } else {
  98. $r['location'] = false;
  99. }
  100. return $r;
  101. }
  102. function micropub_post($endpoint, $params, $access_token, $file_path = NULL, $json = false, $file_prop = 'photo') {
  103. $ch = curl_init();
  104. curl_setopt($ch, CURLOPT_URL, $endpoint);
  105. curl_setopt($ch, CURLOPT_POST, true);
  106. // Send the access token in both the header and post body to support more clients
  107. // https://github.com/aaronpk/Quill/issues/4
  108. // http://indiewebcamp.com/irc/2015-02-14#t1423955287064
  109. $httpheaders = array('Authorization: Bearer ' . $access_token);
  110. if(!$json) {
  111. $params = array_merge(array(
  112. 'h' => 'entry',
  113. 'access_token' => $access_token
  114. ), $params);
  115. }
  116. if(!$file_path) {
  117. if($json) {
  118. $params['access_token'] = $access_token;
  119. $httpheaders[] = 'Content-type: application/json';
  120. $post = json_encode($params);
  121. } else {
  122. $post = http_build_query($params);
  123. $post = preg_replace('/%5B[0-9]+%5D/', '%5B%5D', $post); // change [0] to []
  124. }
  125. } else {
  126. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  127. $mimetype = finfo_file($finfo, $file_path);
  128. $multipart = new p3k\Multipart();
  129. $multipart->addArray($params);
  130. $multipart->addFile($file_prop, $file_path, $mimetype);
  131. $post = $multipart->data();
  132. array_push($httpheaders, 'Content-Type: ' . $multipart->contentType());
  133. }
  134. curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheaders);
  135. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  136. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  137. curl_setopt($ch, CURLOPT_HEADER, true);
  138. curl_setopt($ch, CURLINFO_HEADER_OUT, true);
  139. $response = curl_exec($ch);
  140. $error = curl_error($ch);
  141. $sent_headers = curl_getinfo($ch, CURLINFO_HEADER_OUT);
  142. $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  143. $header_str = trim(substr($response, 0, $header_size));
  144. $request = $sent_headers . (is_string($post) ? $post : http_build_query($post));
  145. return array(
  146. 'request' => $request,
  147. 'response' => $response,
  148. 'code' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
  149. 'headers' => parse_headers($header_str),
  150. 'error' => $error,
  151. 'curlinfo' => curl_getinfo($ch)
  152. );
  153. }
  154. function micropub_get($endpoint, $params, $access_token) {
  155. $url = parse_url($endpoint);
  156. if(!k($url, 'query')) {
  157. $url['query'] = http_build_query($params);
  158. } else {
  159. $url['query'] .= '&' . http_build_query($params);
  160. }
  161. $endpoint = http_build_url($url);
  162. $ch = curl_init();
  163. curl_setopt($ch, CURLOPT_URL, $endpoint);
  164. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  165. 'Authorization: Bearer ' . $access_token,
  166. 'Accept: application/json'
  167. ));
  168. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  169. $response = curl_exec($ch);
  170. $data = array();
  171. if($response) {
  172. $data = json_decode($response, true);
  173. }
  174. $error = curl_error($ch);
  175. return array(
  176. 'response' => $response,
  177. 'data' => $data,
  178. 'error' => $error,
  179. 'curlinfo' => curl_getinfo($ch)
  180. );
  181. }
  182. function parse_headers($headers) {
  183. $retVal = array();
  184. $fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $headers));
  185. foreach($fields as $field) {
  186. if(preg_match('/([^:]+): (.+)/m', $field, $match)) {
  187. $match[1] = preg_replace_callback('/(?<=^|[\x09\x20\x2D])./', function($m) {
  188. return strtoupper($m[0]);
  189. }, strtolower(trim($match[1])));
  190. // If there's already a value set for the header name being returned, turn it into an array and add the new value
  191. $match[1] = preg_replace_callback('/(?<=^|[\x09\x20\x2D])./', function($m) {
  192. return strtoupper($m[0]);
  193. }, strtolower(trim($match[1])));
  194. if(isset($retVal[$match[1]])) {
  195. $retVal[$match[1]][] = trim($match[2]);
  196. } else {
  197. $retVal[$match[1]] = [trim($match[2])];
  198. }
  199. }
  200. }
  201. return $retVal;
  202. }
  203. function get_micropub_config(&$user, $query=[]) {
  204. $targets = [];
  205. $r = micropub_get($user->micropub_endpoint, $query, $user->micropub_access_token);
  206. if($r['data'] && is_array($r['data']) && array_key_exists('syndicate-to', $r['data'])) {
  207. if(is_array($r['data']['syndicate-to'])) {
  208. $data = $r['data']['syndicate-to'];
  209. } else {
  210. $data = [];
  211. }
  212. foreach($data as $t) {
  213. if(is_array($t) && array_key_exists('service', $t) && array_key_exists('photo', $t['service'])) {
  214. $icon = $t['service']['photo'];
  215. } else {
  216. $icon = false;
  217. }
  218. if(is_array($t) && array_key_exists('uid', $t) && array_key_exists('name', $t)) {
  219. $targets[] = [
  220. 'target' => $t['name'],
  221. 'uid' => $t['uid'],
  222. 'favicon' => $icon
  223. ];
  224. }
  225. }
  226. }
  227. if(count($targets))
  228. $user->syndication_targets = json_encode($targets);
  229. $media_endpoint = false;
  230. if($r['data'] && is_array($r['data']) && array_key_exists('media-endpoint', $r['data'])) {
  231. $media_endpoint = $r['data']['media-endpoint'];
  232. $user->micropub_media_endpoint = $media_endpoint;
  233. }
  234. if(count($targets) || $media_endpoint) {
  235. $user->save();
  236. }
  237. return [
  238. 'targets' => $targets,
  239. 'response' => $r
  240. ];
  241. }
  242. function static_map($latitude, $longitude, $height=180, $width=700, $zoom=14) {
  243. return 'https://atlas.p3k.io/map/img?marker[]=lat:' . $latitude . ';lng:' . $longitude . ';icon:small-blue-cutout&basemap=gray&width=' . $width . '&height=' . $height . '&zoom=' . $zoom;
  244. }
  245. function relative_time($date) {
  246. static $rel;
  247. if(!isset($rel)) {
  248. $config = array(
  249. 'language' => '\RelativeTime\Languages\English',
  250. 'separator' => ', ',
  251. 'suffix' => true,
  252. 'truncate' => 1,
  253. );
  254. $rel = new \RelativeTime\RelativeTime($config);
  255. }
  256. return $rel->timeAgo($date);
  257. }
  258. function instagram_client() {
  259. return new Andreyco\Instagram\Client(array(
  260. 'apiKey' => Config::$instagramClientID,
  261. 'apiSecret' => Config::$instagramClientSecret,
  262. 'apiCallback' => Config::$base_url . 'auth/instagram/callback',
  263. 'scope' => array('basic','likes'),
  264. ));
  265. }
  266. function validate_photo(&$file) {
  267. try {
  268. if ($_SERVER['REQUEST_METHOD'] == 'POST' && count($_POST) < 1 ) {
  269. throw new RuntimeException('File upload size exceeded.');
  270. }
  271. // Undefined | Multiple Files | $_FILES Corruption Attack
  272. // If this request falls under any of them, treat it invalid.
  273. if (
  274. !isset($file['error']) ||
  275. is_array($file['error'])
  276. ) {
  277. throw new RuntimeException('Invalid parameters.');
  278. }
  279. // Check $file['error'] value.
  280. switch ($file['error']) {
  281. case UPLOAD_ERR_OK:
  282. break;
  283. case UPLOAD_ERR_NO_FILE:
  284. throw new RuntimeException('No file sent.');
  285. case UPLOAD_ERR_INI_SIZE:
  286. case UPLOAD_ERR_FORM_SIZE:
  287. throw new RuntimeException('Exceeded filesize limit.');
  288. default:
  289. throw new RuntimeException('Unknown errors.');
  290. }
  291. // You should also check filesize here.
  292. if ($file['size'] > 4000000) {
  293. throw new RuntimeException('Exceeded filesize limit.');
  294. }
  295. // DO NOT TRUST $file['mime'] VALUE !!
  296. // Check MIME Type by yourself.
  297. $finfo = new finfo(FILEINFO_MIME_TYPE);
  298. if (false === $ext = array_search(
  299. $finfo->file($file['tmp_name']),
  300. array(
  301. 'jpg' => 'image/jpeg',
  302. 'png' => 'image/png',
  303. 'gif' => 'image/gif',
  304. ),
  305. true
  306. )) {
  307. throw new RuntimeException('Invalid file format.');
  308. }
  309. } catch (RuntimeException $e) {
  310. return $e->getMessage();
  311. }
  312. }
  313. // Reads the exif rotation data and actually rotates the photo.
  314. // Only does anything if the exif library is loaded, otherwise is a noop.
  315. function correct_photo_rotation($filename) {
  316. if(class_exists('IMagick')) {
  317. $image = new IMagick($filename);
  318. $orientation = $image->getImageOrientation();
  319. switch($orientation) {
  320. case IMagick::ORIENTATION_BOTTOMRIGHT:
  321. $image->rotateImage(new ImagickPixel('#00000000'), 180);
  322. break;
  323. case IMagick::ORIENTATION_RIGHTTOP:
  324. $image->rotateImage(new ImagickPixel('#00000000'), 90);
  325. break;
  326. case IMagick::ORIENTATION_LEFTBOTTOM:
  327. $image->rotateImage(new ImagickPixel('#00000000'), -90);
  328. break;
  329. }
  330. $image->setImageOrientation(IMagick::ORIENTATION_TOPLEFT);
  331. $image->writeImage($filename);
  332. }
  333. }