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.

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