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.

472 lines
14 KiB

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