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.

558 lines
16 KiB

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