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.

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