Mirror of Quill
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.

389 lines
12 KiB

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