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.

468 lines
14 KiB

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