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.

518 lines
15 KiB

8 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 = NULL, $json = false) {
  76. // Now send to the micropub endpoint
  77. $r = micropub_post($user->micropub_endpoint, $params, $user->micropub_access_token, $file, $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) {
  92. // Send to the media endpoint
  93. $r = micropub_post($user->micropub_media_endpoint, [], $user->micropub_access_token, $file, 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 = 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. if($file) {
  107. if(is_string($file)) {
  108. $file_path = $file;
  109. $file_content = file_get_contents($file_path);
  110. $filename = 'file';
  111. } else {
  112. $file_path = $file['tmp_name'];
  113. $file_content = file_get_contents($file_path);
  114. $filename = $file['name'];
  115. }
  116. } else {
  117. $file_path = false;
  118. }
  119. // Send the access token in both the header and post body to support more clients
  120. // https://github.com/aaronpk/Quill/issues/4
  121. // http://indiewebcamp.com/irc/2015-02-14#t1423955287064
  122. $httpheaders = array('Authorization: Bearer ' . $access_token);
  123. if(!$json) {
  124. $params = array_merge(array(
  125. 'h' => 'entry',
  126. 'access_token' => $access_token
  127. ), $params);
  128. }
  129. if(!$file_path) {
  130. $httpheaders[] = 'Accept: application/json';
  131. if($json) {
  132. // $params['access_token'] = $access_token;
  133. $httpheaders[] = 'Content-type: application/json';
  134. $post = json_encode($params);
  135. } else {
  136. $post = http_build_query($params);
  137. $post = preg_replace('/%5B[0-9]+%5D/', '%5B%5D', $post); // change [0] to []
  138. }
  139. } else {
  140. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  141. $mimetype = finfo_file($finfo, $file_path);
  142. $multipart = new p3k\Multipart();
  143. $multipart->addArray($params);
  144. $multipart->addFile($file_prop, $filename, $mimetype, $file_content);
  145. $post = $multipart->data();
  146. $httpheaders[] = 'Content-Type: ' . $multipart->contentType();
  147. }
  148. curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheaders);
  149. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  150. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  151. curl_setopt($ch, CURLOPT_HEADER, true);
  152. curl_setopt($ch, CURLINFO_HEADER_OUT, true);
  153. $response = curl_exec($ch);
  154. $error = curl_error($ch);
  155. $sent_headers = curl_getinfo($ch, CURLINFO_HEADER_OUT);
  156. $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  157. $header_str = trim(substr($response, 0, $header_size));
  158. $request = $sent_headers . (is_string($post) ? $post : http_build_query($post));
  159. return array(
  160. 'request' => $request,
  161. 'response' => $response,
  162. 'code' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
  163. 'headers' => parse_headers($header_str),
  164. 'error' => $error,
  165. 'curlinfo' => curl_getinfo($ch)
  166. );
  167. }
  168. function micropub_get($endpoint, $params, $access_token) {
  169. $url = parse_url($endpoint);
  170. if(!k($url, 'query')) {
  171. $url['query'] = http_build_query($params);
  172. } else {
  173. $url['query'] .= '&' . http_build_query($params);
  174. }
  175. $endpoint = http_build_url($url);
  176. $ch = curl_init();
  177. curl_setopt($ch, CURLOPT_URL, $endpoint);
  178. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  179. 'Authorization: Bearer ' . $access_token,
  180. 'Accept: application/json'
  181. ));
  182. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  183. $response = curl_exec($ch);
  184. $data = array();
  185. if($response) {
  186. $data = json_decode($response, true);
  187. }
  188. $error = curl_error($ch);
  189. return array(
  190. 'response' => $response,
  191. 'data' => $data,
  192. 'error' => $error,
  193. 'curlinfo' => curl_getinfo($ch)
  194. );
  195. }
  196. function revoke_micropub_token($access_token, $token_endpoint) {
  197. $ch = curl_init();
  198. curl_setopt($ch, CURLOPT_URL, $token_endpoint);
  199. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  200. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
  201. 'action' => 'revoke',
  202. 'token' => $access_token,
  203. ]));
  204. curl_exec($ch);
  205. }
  206. function parse_headers($headers) {
  207. $retVal = array();
  208. $fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $headers));
  209. foreach($fields as $field) {
  210. if(preg_match('/([^:]+): (.+)/m', $field, $match)) {
  211. $match[1] = preg_replace_callback('/(?<=^|[\x09\x20\x2D])./', function($m) {
  212. return strtoupper($m[0]);
  213. }, strtolower(trim($match[1])));
  214. // If there's already a value set for the header name being returned, turn it into an array and add the new value
  215. $match[1] = preg_replace_callback('/(?<=^|[\x09\x20\x2D])./', function($m) {
  216. return strtoupper($m[0]);
  217. }, strtolower(trim($match[1])));
  218. if(isset($retVal[$match[1]])) {
  219. $retVal[$match[1]][] = trim($match[2]);
  220. } else {
  221. $retVal[$match[1]] = [trim($match[2])];
  222. }
  223. }
  224. }
  225. return $retVal;
  226. }
  227. function get_micropub_config(&$user, $query=[]) {
  228. $targets = [];
  229. $r = micropub_get($user->micropub_endpoint, $query, $user->micropub_access_token);
  230. if($r['data'] && is_array($r['data']) && array_key_exists('syndicate-to', $r['data'])) {
  231. if(is_array($r['data']['syndicate-to'])) {
  232. $data = $r['data']['syndicate-to'];
  233. } else {
  234. $data = [];
  235. }
  236. foreach($data as $t) {
  237. if(is_array($t) && array_key_exists('service', $t) && array_key_exists('photo', $t['service'])) {
  238. $icon = $t['service']['photo'];
  239. } else {
  240. $icon = false;
  241. }
  242. if(is_array($t) && array_key_exists('uid', $t) && array_key_exists('name', $t)) {
  243. $targets[] = [
  244. 'target' => $t['name'],
  245. 'uid' => $t['uid'],
  246. 'favicon' => $icon
  247. ];
  248. }
  249. }
  250. }
  251. if(count($targets))
  252. $user->syndication_targets = json_encode($targets);
  253. $media_endpoint = false;
  254. $supported_post_types = false;
  255. if($r['data'] && is_array($r['data'])) {
  256. if(isset($r['data']['media-endpoint'])) {
  257. $media_endpoint = $r['data']['media-endpoint'];
  258. $user->micropub_media_endpoint = $media_endpoint;
  259. }
  260. if(isset($r['data']['post-types'])) {
  261. $supported_post_types = json_encode($r['data']['post-types']);
  262. $user->supported_post_types = $supported_post_types;
  263. }
  264. }
  265. if(count($targets) || $media_endpoint || $supported_post_types) {
  266. $user->save();
  267. }
  268. return [
  269. 'targets' => $targets,
  270. 'response' => $r
  271. ];
  272. }
  273. function supports_post_type(&$user, $type) {
  274. if(!$user->supported_post_types)
  275. return true;
  276. $types = json_decode($user->supported_post_types, true);
  277. if(!is_array($types))
  278. return true; // syntax error in response, fail safely
  279. foreach($types as $t) {
  280. if(is_array($t) && isset($t['type']) && $t['type'] == $type) {
  281. return true;
  282. }
  283. }
  284. return false;
  285. }
  286. function get_micropub_source(&$user, $url, $properties) {
  287. $r = micropub_get($user->micropub_endpoint, [
  288. 'q' => 'source',
  289. 'url' => $url,
  290. 'properties' => $properties
  291. ], $user->micropub_access_token);
  292. if(isset($r['data']) && isset($r['data']['properties'])) {
  293. return $r['data']['properties'];
  294. } else {
  295. return false;
  296. }
  297. }
  298. function static_map($latitude, $longitude, $height=180, $width=700, $zoom=14) {
  299. return 'https://atlas.p3k.io/map/img?marker[]=lat:' . $latitude . ';lng:' . $longitude . ';icon:small-blue-cutout&basemap=gray&width=' . $width . '&height=' . $height . '&zoom=' . $zoom;
  300. }
  301. function relative_time($date) {
  302. static $rel;
  303. if(!isset($rel)) {
  304. $config = array(
  305. 'language' => '\RelativeTime\Languages\English',
  306. 'separator' => ', ',
  307. 'suffix' => true,
  308. 'truncate' => 1,
  309. );
  310. $rel = new \RelativeTime\RelativeTime($config);
  311. }
  312. return $rel->timeAgo($date);
  313. }
  314. function instagram_client() {
  315. return new Andreyco\Instagram\Client(array(
  316. 'apiKey' => Config::$instagramClientID,
  317. 'apiSecret' => Config::$instagramClientSecret,
  318. 'apiCallback' => Config::$base_url . 'auth/instagram/callback',
  319. 'scope' => array('basic','likes'),
  320. ));
  321. }
  322. function validate_photo(&$file) {
  323. try {
  324. if ($_SERVER['REQUEST_METHOD'] == 'POST' && count($_POST) < 1 ) {
  325. throw new RuntimeException('File upload size exceeded.');
  326. }
  327. // Undefined | Multiple Files | $_FILES Corruption Attack
  328. // If this request falls under any of them, treat it invalid.
  329. if (
  330. !isset($file['error']) ||
  331. is_array($file['error'])
  332. ) {
  333. throw new RuntimeException('Invalid parameters.');
  334. }
  335. // Check $file['error'] value.
  336. switch ($file['error']) {
  337. case UPLOAD_ERR_OK:
  338. break;
  339. case UPLOAD_ERR_NO_FILE:
  340. throw new RuntimeException('No file sent.');
  341. case UPLOAD_ERR_INI_SIZE:
  342. case UPLOAD_ERR_FORM_SIZE:
  343. throw new RuntimeException('Exceeded filesize limit.');
  344. default:
  345. throw new RuntimeException('Unknown errors.');
  346. }
  347. // You should also check filesize here.
  348. if ($file['size'] > 4000000) {
  349. throw new RuntimeException('Exceeded filesize limit.');
  350. }
  351. // DO NOT TRUST $file['mime'] VALUE !!
  352. // Check MIME Type by yourself.
  353. $finfo = new finfo(FILEINFO_MIME_TYPE);
  354. if (false === $ext = array_search(
  355. $finfo->file($file['tmp_name']),
  356. array(
  357. 'jpg' => 'image/jpeg',
  358. 'png' => 'image/png',
  359. 'gif' => 'image/gif',
  360. ),
  361. true
  362. )) {
  363. throw new RuntimeException('Invalid file format.');
  364. }
  365. } catch (RuntimeException $e) {
  366. return $e->getMessage();
  367. }
  368. }
  369. // Reads the exif rotation data and actually rotates the photo.
  370. // Only does anything if the exif library is loaded, otherwise is a noop.
  371. function correct_photo_rotation($filename) {
  372. if(class_exists('IMagick')) {
  373. try {
  374. $image = new IMagick($filename);
  375. $orientation = $image->getImageOrientation();
  376. switch($orientation) {
  377. case IMagick::ORIENTATION_BOTTOMRIGHT:
  378. $image->rotateImage(new ImagickPixel('#00000000'), 180);
  379. break;
  380. case IMagick::ORIENTATION_RIGHTTOP:
  381. $image->rotateImage(new ImagickPixel('#00000000'), 90);
  382. break;
  383. case IMagick::ORIENTATION_LEFTBOTTOM:
  384. $image->rotateImage(new ImagickPixel('#00000000'), -90);
  385. break;
  386. }
  387. $image->setImageOrientation(IMagick::ORIENTATION_TOPLEFT);
  388. $image->writeImage($filename);
  389. } catch(Exception $e){}
  390. }
  391. }
  392. function sanitize_editor_html($html) {
  393. #error_log($html."\n");
  394. $config = HTMLPurifier_Config::createDefault();
  395. $config->autoFinalize = false;
  396. $config->set('Cache.DefinitionImpl', null);
  397. $config->set('HTML.AllowedElements', [
  398. 'a',
  399. 'abbr',
  400. 'b',
  401. 'br',
  402. 'code',
  403. 'del',
  404. 'em',
  405. 'i',
  406. 'img',
  407. 'q',
  408. 'strike',
  409. 'strong',
  410. 'blockquote',
  411. 'pre',
  412. 'p',
  413. 'h1',
  414. 'h2',
  415. 'h3',
  416. 'h4',
  417. 'h5',
  418. 'h6',
  419. 'ul',
  420. 'li',
  421. 'ol',
  422. 'figcaption',
  423. 'figure'
  424. ]);
  425. $def = $config->getHTMLDefinition(true);
  426. // http://developers.whatwg.org/grouping-content.html
  427. $def->addElement('figure', 'Block', 'Optional: (figcaption, Flow) | (Flow, figcaption) | Flow', 'Common');
  428. $def->addElement('figcaption', 'Inline', 'Flow', 'Common');
  429. // Allow data: URIs
  430. $config->set('URI.AllowedSchemes', array('data' => true, 'http' => true, 'https' => true));
  431. // Strip all classes from elements
  432. $config->set('Attr.AllowedClasses', '');
  433. // $def = $config->getHTMLDefinition(true);
  434. $purifier = new HTMLPurifier($config);
  435. $sanitized = $purifier->purify($html);
  436. $sanitized = str_replace("&#xD;","\r",$sanitized);
  437. # Remove empty paragraphs
  438. $sanitized = str_replace('<p><br /></p>','',$sanitized);
  439. $sanitized = str_replace('<p></p>','',$sanitized);
  440. $indenter = new \Gajus\Dindent\Indenter([
  441. 'indentation_character' => ' '
  442. ]);
  443. $indenter->setElementType('h1', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  444. $indenter->setElementType('h2', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  445. $indenter->setElementType('h3', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  446. $indenter->setElementType('h4', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  447. $indenter->setElementType('h5', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  448. $indenter->setElementType('h6', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  449. $sanitized = $indenter->indent($sanitized);
  450. #error_log($sanitized."\n");
  451. return $sanitized;
  452. }