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.

359 lines
11 KiB

  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);
  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) {
  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('photo', $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(array_key_exists('media_endpoint', $r['data'])) {
  211. $user->micropub_media_endpoint = $r['data']['media_endpoint'];
  212. }
  213. if(count($targets) || $media_endpoint) {
  214. $user->save();
  215. }
  216. return [
  217. 'targets' => $targets,
  218. 'response' => $r
  219. ];
  220. }
  221. function static_map($latitude, $longitude, $height=180, $width=700, $zoom=14) {
  222. return 'https://atlas.p3k.io/map/img?marker[]=lat:' . $latitude . ';lng:' . $longitude . ';icon:small-blue-cutout&basemap=gray&width=' . $width . '&height=' . $height . '&zoom=' . $zoom;
  223. }
  224. function relative_time($date) {
  225. static $rel;
  226. if(!isset($rel)) {
  227. $config = array(
  228. 'language' => '\RelativeTime\Languages\English',
  229. 'separator' => ', ',
  230. 'suffix' => true,
  231. 'truncate' => 1,
  232. );
  233. $rel = new \RelativeTime\RelativeTime($config);
  234. }
  235. return $rel->timeAgo($date);
  236. }
  237. function instagram_client() {
  238. return new Andreyco\Instagram\Client(array(
  239. 'apiKey' => Config::$instagramClientID,
  240. 'apiSecret' => Config::$instagramClientSecret,
  241. 'apiCallback' => Config::$base_url . 'auth/instagram/callback',
  242. 'scope' => array('basic','likes'),
  243. ));
  244. }
  245. function validate_photo(&$file) {
  246. try {
  247. if ($_SERVER['REQUEST_METHOD'] == 'POST' && count($_POST) < 1 ) {
  248. throw new RuntimeException('File upload size exceeded.');
  249. }
  250. // Undefined | Multiple Files | $_FILES Corruption Attack
  251. // If this request falls under any of them, treat it invalid.
  252. if (
  253. !isset($file['error']) ||
  254. is_array($file['error'])
  255. ) {
  256. throw new RuntimeException('Invalid parameters.');
  257. }
  258. // Check $file['error'] value.
  259. switch ($file['error']) {
  260. case UPLOAD_ERR_OK:
  261. break;
  262. case UPLOAD_ERR_NO_FILE:
  263. throw new RuntimeException('No file sent.');
  264. case UPLOAD_ERR_INI_SIZE:
  265. case UPLOAD_ERR_FORM_SIZE:
  266. throw new RuntimeException('Exceeded filesize limit.');
  267. default:
  268. throw new RuntimeException('Unknown errors.');
  269. }
  270. // You should also check filesize here.
  271. if ($file['size'] > 4000000) {
  272. throw new RuntimeException('Exceeded filesize limit.');
  273. }
  274. // DO NOT TRUST $file['mime'] VALUE !!
  275. // Check MIME Type by yourself.
  276. $finfo = new finfo(FILEINFO_MIME_TYPE);
  277. if (false === $ext = array_search(
  278. $finfo->file($file['tmp_name']),
  279. array(
  280. 'jpg' => 'image/jpeg',
  281. 'png' => 'image/png',
  282. 'gif' => 'image/gif',
  283. ),
  284. true
  285. )) {
  286. throw new RuntimeException('Invalid file format.');
  287. }
  288. } catch (RuntimeException $e) {
  289. return $e->getMessage();
  290. }
  291. }
  292. // Reads the exif rotation data and actually rotates the photo.
  293. // Only does anything if the exif library is loaded, otherwise is a noop.
  294. function correct_photo_rotation($filename) {
  295. if(class_exists('IMagick')) {
  296. $image = new IMagick($filename);
  297. $orientation = $image->getImageOrientation();
  298. switch($orientation) {
  299. case IMagick::ORIENTATION_BOTTOMRIGHT:
  300. $image->rotateImage(new ImagickPixel('#00000000'), 180);
  301. break;
  302. case IMagick::ORIENTATION_RIGHTTOP:
  303. $image->rotateImage(new ImagickPixel('#00000000'), 90);
  304. break;
  305. case IMagick::ORIENTATION_LEFTBOTTOM:
  306. $image->rotateImage(new ImagickPixel('#00000000'), -90);
  307. break;
  308. }
  309. $image->setImageOrientation(IMagick::ORIENTATION_TOPLEFT);
  310. $image->writeImage($filename);
  311. }
  312. }