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.

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