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.

473 lines
14 KiB

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