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.

528 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. $r = micropub_get($user->micropub_endpoint, $query, $user->micropub_access_token);
  240. if($r['data'] && is_array($r['data']) && array_key_exists('syndicate-to', $r['data'])) {
  241. if(is_array($r['data']['syndicate-to'])) {
  242. $data = $r['data']['syndicate-to'];
  243. } else {
  244. $data = [];
  245. }
  246. foreach($data as $t) {
  247. if(is_array($t) && array_key_exists('service', $t) && array_key_exists('photo', $t['service'])) {
  248. $icon = $t['service']['photo'];
  249. } else {
  250. $icon = false;
  251. }
  252. if(is_array($t) && array_key_exists('uid', $t) && array_key_exists('name', $t)) {
  253. $targets[] = [
  254. 'target' => $t['name'],
  255. 'uid' => $t['uid'],
  256. 'favicon' => $icon
  257. ];
  258. }
  259. }
  260. }
  261. // Reset the values so they can be overwritten
  262. $user->syndication_targets = '';
  263. $user->supported_post_types = '';
  264. $user->supported_visibility = '';
  265. $user->micropub_media_endpoint = '';
  266. if(count($targets))
  267. $user->syndication_targets = json_encode($targets);
  268. $media_endpoint = false;
  269. $supported_post_types = false;
  270. if($r['data'] && is_array($r['data'])) {
  271. if(isset($r['data']['media-endpoint'])) {
  272. $media_endpoint = $r['data']['media-endpoint'];
  273. $user->micropub_media_endpoint = $media_endpoint;
  274. }
  275. if(isset($r['data']['post-types'])) {
  276. $supported_post_types = json_encode($r['data']['post-types']);
  277. $user->supported_post_types = $supported_post_types;
  278. }
  279. }
  280. if(isset($r['data']['visibility']) && is_array($r['data']['visibility'])) {
  281. $user->supported_visibility = json_encode($r['data']['visibility']);
  282. }
  283. $user->save();
  284. return [
  285. 'targets' => $targets,
  286. 'response' => $r
  287. ];
  288. }
  289. function supports_post_type(&$user, $type) {
  290. if(!$user->supported_post_types)
  291. return true;
  292. $types = json_decode($user->supported_post_types, true);
  293. if(!is_array($types))
  294. return true; // syntax error in response, fail safely
  295. foreach($types as $t) {
  296. if(is_array($t) && isset($t['type']) && $t['type'] == $type) {
  297. return true;
  298. }
  299. }
  300. return false;
  301. }
  302. function get_micropub_source(&$user, $url, $properties) {
  303. $r = micropub_get($user->micropub_endpoint, [
  304. 'q' => 'source',
  305. 'url' => $url,
  306. 'properties' => $properties
  307. ], $user->micropub_access_token);
  308. if(isset($r['data']) && isset($r['data']['properties'])) {
  309. return $r['data']['properties'];
  310. } else {
  311. return false;
  312. }
  313. }
  314. function static_map($latitude, $longitude, $height=180, $width=700, $zoom=14) {
  315. return 'https://atlas.p3k.io/map/img?marker[]=lat:' . $latitude . ';lng:' . $longitude . ';icon:small-blue-cutout&basemap=gray&width=' . $width . '&height=' . $height . '&zoom=' . $zoom;
  316. }
  317. function relative_time($date) {
  318. static $rel;
  319. if(!isset($rel)) {
  320. $config = array(
  321. 'language' => '\RelativeTime\Languages\English',
  322. 'separator' => ', ',
  323. 'suffix' => true,
  324. 'truncate' => 1,
  325. );
  326. $rel = new \RelativeTime\RelativeTime($config);
  327. }
  328. return $rel->timeAgo($date);
  329. }
  330. function validate_photo(&$file) {
  331. try {
  332. if ($_SERVER['REQUEST_METHOD'] == 'POST' && count($_POST) < 1 ) {
  333. throw new RuntimeException('File upload size exceeded.');
  334. }
  335. // Undefined | Multiple Files | $_FILES Corruption Attack
  336. // If this request falls under any of them, treat it invalid.
  337. if (
  338. !isset($file['error']) ||
  339. is_array($file['error'])
  340. ) {
  341. throw new RuntimeException('Invalid parameters.');
  342. }
  343. // Check $file['error'] value.
  344. switch ($file['error']) {
  345. case UPLOAD_ERR_OK:
  346. break;
  347. case UPLOAD_ERR_NO_FILE:
  348. throw new RuntimeException('No file sent.');
  349. case UPLOAD_ERR_INI_SIZE:
  350. case UPLOAD_ERR_FORM_SIZE:
  351. throw new RuntimeException('Exceeded filesize limit.');
  352. default:
  353. throw new RuntimeException('Unknown errors.');
  354. }
  355. // You should also check filesize here.
  356. if ($file['size'] > 4000000) {
  357. throw new RuntimeException('Exceeded filesize limit.');
  358. }
  359. // DO NOT TRUST $file['mime'] VALUE !!
  360. // Check MIME Type by yourself.
  361. $finfo = new finfo(FILEINFO_MIME_TYPE);
  362. if (false === $ext = array_search(
  363. $finfo->file($file['tmp_name']),
  364. array(
  365. 'jpg' => 'image/jpeg',
  366. 'png' => 'image/png',
  367. 'gif' => 'image/gif',
  368. ),
  369. true
  370. )) {
  371. throw new RuntimeException('Invalid file format.');
  372. }
  373. } catch (RuntimeException $e) {
  374. return $e->getMessage();
  375. }
  376. }
  377. // Reads the exif rotation data and actually rotates the photo.
  378. // Only does anything if the exif library is loaded, otherwise is a noop.
  379. function correct_photo_rotation($filename) {
  380. if(class_exists('IMagick')) {
  381. try {
  382. $image = new IMagick($filename);
  383. $orientation = $image->getImageOrientation();
  384. switch($orientation) {
  385. case IMagick::ORIENTATION_BOTTOMRIGHT:
  386. $image->rotateImage(new ImagickPixel('#00000000'), 180);
  387. break;
  388. case IMagick::ORIENTATION_RIGHTTOP:
  389. $image->rotateImage(new ImagickPixel('#00000000'), 90);
  390. break;
  391. case IMagick::ORIENTATION_LEFTBOTTOM:
  392. $image->rotateImage(new ImagickPixel('#00000000'), -90);
  393. break;
  394. }
  395. $image->setImageOrientation(IMagick::ORIENTATION_TOPLEFT);
  396. $image->writeImage($filename);
  397. } catch(Exception $e){}
  398. }
  399. }
  400. function sanitize_editor_html($html) {
  401. #error_log($html."\n");
  402. $config = HTMLPurifier_Config::createDefault();
  403. $config->autoFinalize = false;
  404. $config->set('Cache.DefinitionImpl', null);
  405. $config->set('HTML.AllowedElements', [
  406. 'a',
  407. 'abbr',
  408. 'b',
  409. 'br',
  410. 'code',
  411. 'del',
  412. 'em',
  413. 'i',
  414. 'img',
  415. 'q',
  416. 'strike',
  417. 'strong',
  418. 'blockquote',
  419. 'pre',
  420. 'p',
  421. 'h1',
  422. 'h2',
  423. 'h3',
  424. 'h4',
  425. 'h5',
  426. 'h6',
  427. 'ul',
  428. 'li',
  429. 'ol',
  430. 'figcaption',
  431. 'figure'
  432. ]);
  433. $def = $config->getHTMLDefinition(true);
  434. // http://developers.whatwg.org/grouping-content.html
  435. $def->addElement('figure', 'Block', 'Optional: (figcaption, Flow) | (Flow, figcaption) | Flow', 'Common');
  436. $def->addElement('figcaption', 'Inline', 'Flow', 'Common');
  437. // Allow data: URIs
  438. $config->set('URI.AllowedSchemes', array('data' => true, 'http' => true, 'https' => true));
  439. // Strip all classes from elements
  440. $config->set('Attr.AllowedClasses', '');
  441. // $def = $config->getHTMLDefinition(true);
  442. $purifier = new HTMLPurifier($config);
  443. $sanitized = $purifier->purify($html);
  444. $sanitized = str_replace("&#xD;","\r",$sanitized);
  445. # Remove empty paragraphs
  446. $sanitized = str_replace('<p><br /></p>','',$sanitized);
  447. $sanitized = str_replace('<p></p>','',$sanitized);
  448. $indenter = new \Gajus\Dindent\Indenter([
  449. 'indentation_character' => ' '
  450. ]);
  451. $indenter->setElementType('h1', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  452. $indenter->setElementType('h2', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  453. $indenter->setElementType('h3', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  454. $indenter->setElementType('h4', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  455. $indenter->setElementType('h5', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  456. $indenter->setElementType('h6', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  457. $sanitized = $indenter->indent($sanitized);
  458. #error_log($sanitized."\n");
  459. return $sanitized;
  460. }