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.

551 lines
16 KiB

5 years ago
5 years ago
7 years ago
7 years ago
1 year 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['headers'] && $r['headers']['Location']) {
  106. $r['location'] = $r['headers']['Location'];
  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. $params = [
  324. 'h' => $height,
  325. 'w' => $width,
  326. 'z' => $zoom,
  327. ];
  328. return '/map-img?lat='.$latitude.'&lng='.$longitude.'&'.http_build_query($params);
  329. }
  330. function relative_time($date) {
  331. static $rel;
  332. if(!isset($rel)) {
  333. $config = array(
  334. 'language' => '\RelativeTime\Languages\English',
  335. 'separator' => ', ',
  336. 'suffix' => true,
  337. 'truncate' => 1,
  338. );
  339. $rel = new \RelativeTime\RelativeTime($config);
  340. }
  341. return $rel->timeAgo($date);
  342. }
  343. function validate_photo(&$file) {
  344. try {
  345. if ($_SERVER['REQUEST_METHOD'] == 'POST' && count($_POST) < 1 ) {
  346. throw new RuntimeException('File upload size exceeded.');
  347. }
  348. // Undefined | Multiple Files | $_FILES Corruption Attack
  349. // If this request falls under any of them, treat it invalid.
  350. if (
  351. !isset($file['error']) ||
  352. is_array($file['error'])
  353. ) {
  354. throw new RuntimeException('Invalid parameters.');
  355. }
  356. // Check $file['error'] value.
  357. switch ($file['error']) {
  358. case UPLOAD_ERR_OK:
  359. break;
  360. case UPLOAD_ERR_NO_FILE:
  361. throw new RuntimeException('No file sent.');
  362. case UPLOAD_ERR_INI_SIZE:
  363. case UPLOAD_ERR_FORM_SIZE:
  364. throw new RuntimeException('Exceeded filesize limit.');
  365. default:
  366. throw new RuntimeException('Unknown errors.');
  367. }
  368. // You should also check filesize here.
  369. if ($file['size'] > 12000000) {
  370. throw new RuntimeException('Exceeded Quill filesize limit.');
  371. }
  372. // DO NOT TRUST $file['mime'] VALUE !!
  373. // Check MIME Type by yourself.
  374. $finfo = new finfo(FILEINFO_MIME_TYPE);
  375. if (false === $ext = array_search(
  376. $finfo->file($file['tmp_name']),
  377. array(
  378. 'jpg' => 'image/jpeg',
  379. 'png' => 'image/png',
  380. 'gif' => 'image/gif',
  381. ),
  382. true
  383. )) {
  384. throw new RuntimeException('Invalid file format.');
  385. }
  386. } catch (RuntimeException $e) {
  387. return $e->getMessage();
  388. }
  389. }
  390. // Reads the exif rotation data and actually rotates the photo.
  391. // Only does anything if the exif library is loaded, otherwise is a noop.
  392. function correct_photo_rotation($filename) {
  393. if(class_exists('IMagick')) {
  394. try {
  395. $image = new IMagick($filename);
  396. // Don't try to convert animated images
  397. if($image->getImageIterations() == 1)
  398. return;
  399. $orientation = $image->getImageOrientation();
  400. switch($orientation) {
  401. case IMagick::ORIENTATION_BOTTOMRIGHT:
  402. $image->rotateImage(new ImagickPixel('#00000000'), 180);
  403. break;
  404. case IMagick::ORIENTATION_RIGHTTOP:
  405. $image->rotateImage(new ImagickPixel('#00000000'), 90);
  406. break;
  407. case IMagick::ORIENTATION_LEFTBOTTOM:
  408. $image->rotateImage(new ImagickPixel('#00000000'), -90);
  409. break;
  410. default:
  411. // Don't overwrite if no orientation header was returned
  412. return;
  413. }
  414. $image->setImageOrientation(IMagick::ORIENTATION_TOPLEFT);
  415. $image->writeImage($filename);
  416. } catch(Exception $e){}
  417. }
  418. }
  419. function sanitize_editor_html($html) {
  420. #error_log($html."\n");
  421. $config = HTMLPurifier_Config::createDefault();
  422. $config->autoFinalize = false;
  423. $config->set('Cache.DefinitionImpl', null);
  424. $config->set('HTML.AllowedElements', [
  425. 'a',
  426. 'abbr',
  427. 'b',
  428. 'br',
  429. 'code',
  430. 'del',
  431. 'em',
  432. 'i',
  433. 'img',
  434. 'q',
  435. 'strike',
  436. 'strong',
  437. 'blockquote',
  438. 'pre',
  439. 'p',
  440. 'h1',
  441. 'h2',
  442. 'h3',
  443. 'h4',
  444. 'h5',
  445. 'h6',
  446. 'ul',
  447. 'li',
  448. 'ol',
  449. 'figcaption',
  450. 'figure'
  451. ]);
  452. $def = $config->getHTMLDefinition(true);
  453. // http://developers.whatwg.org/grouping-content.html
  454. $def->addElement('figure', 'Block', 'Optional: (figcaption, Flow) | (Flow, figcaption) | Flow', 'Common');
  455. $def->addElement('figcaption', 'Inline', 'Flow', 'Common');
  456. // Allow data: URIs
  457. $config->set('URI.AllowedSchemes', array('data' => true, 'http' => true, 'https' => true));
  458. // Strip all classes from elements
  459. $config->set('Attr.AllowedClasses', '');
  460. // $def = $config->getHTMLDefinition(true);
  461. $purifier = new HTMLPurifier($config);
  462. $sanitized = $purifier->purify($html);
  463. $sanitized = str_replace("&#xD;","\r",$sanitized);
  464. # Remove empty paragraphs
  465. $sanitized = str_replace('<p><br /></p>','',$sanitized);
  466. $sanitized = str_replace('<p></p>','',$sanitized);
  467. $indenter = new \Gajus\Dindent\Indenter([
  468. 'indentation_character' => ' '
  469. ]);
  470. $indenter->setElementType('h1', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  471. $indenter->setElementType('h2', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  472. $indenter->setElementType('h3', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  473. $indenter->setElementType('h4', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  474. $indenter->setElementType('h5', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  475. $indenter->setElementType('h6', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  476. $sanitized = $indenter->indent($sanitized);
  477. #error_log($sanitized."\n");
  478. return $sanitized;
  479. }