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.

546 lines
16 KiB

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