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.

477 lines
14 KiB

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