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.

494 lines
15 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 revoke_micropub_token($access_token, $token_endpoint) {
  197. $ch = curl_init();
  198. curl_setopt($ch, CURLOPT_URL, $token_endpoint);
  199. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  200. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
  201. 'action' => 'revoke',
  202. 'token' => $access_token,
  203. ]));
  204. curl_exec($ch);
  205. }
  206. function parse_headers($headers) {
  207. $retVal = array();
  208. $fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $headers));
  209. foreach($fields as $field) {
  210. if(preg_match('/([^:]+): (.+)/m', $field, $match)) {
  211. $match[1] = preg_replace_callback('/(?<=^|[\x09\x20\x2D])./', function($m) {
  212. return strtoupper($m[0]);
  213. }, strtolower(trim($match[1])));
  214. // If there's already a value set for the header name being returned, turn it into an array and add the new value
  215. $match[1] = preg_replace_callback('/(?<=^|[\x09\x20\x2D])./', function($m) {
  216. return strtoupper($m[0]);
  217. }, strtolower(trim($match[1])));
  218. if(isset($retVal[$match[1]])) {
  219. $retVal[$match[1]][] = trim($match[2]);
  220. } else {
  221. $retVal[$match[1]] = [trim($match[2])];
  222. }
  223. }
  224. }
  225. return $retVal;
  226. }
  227. function get_micropub_config(&$user, $query=[]) {
  228. $targets = [];
  229. $r = micropub_get($user->micropub_endpoint, $query, $user->micropub_access_token);
  230. if($r['data'] && is_array($r['data']) && array_key_exists('syndicate-to', $r['data'])) {
  231. if(is_array($r['data']['syndicate-to'])) {
  232. $data = $r['data']['syndicate-to'];
  233. } else {
  234. $data = [];
  235. }
  236. foreach($data as $t) {
  237. if(is_array($t) && array_key_exists('service', $t) && array_key_exists('photo', $t['service'])) {
  238. $icon = $t['service']['photo'];
  239. } else {
  240. $icon = false;
  241. }
  242. if(is_array($t) && array_key_exists('uid', $t) && array_key_exists('name', $t)) {
  243. $targets[] = [
  244. 'target' => $t['name'],
  245. 'uid' => $t['uid'],
  246. 'favicon' => $icon
  247. ];
  248. }
  249. }
  250. }
  251. if(count($targets))
  252. $user->syndication_targets = json_encode($targets);
  253. $media_endpoint = false;
  254. if($r['data'] && is_array($r['data']) && array_key_exists('media-endpoint', $r['data'])) {
  255. $media_endpoint = $r['data']['media-endpoint'];
  256. $user->micropub_media_endpoint = $media_endpoint;
  257. }
  258. if(count($targets) || $media_endpoint) {
  259. $user->save();
  260. }
  261. return [
  262. 'targets' => $targets,
  263. 'response' => $r
  264. ];
  265. }
  266. function get_micropub_source(&$user, $url, $properties) {
  267. $r = micropub_get($user->micropub_endpoint, [
  268. 'q' => 'source',
  269. 'url' => $url,
  270. 'properties' => $properties
  271. ], $user->micropub_access_token);
  272. if(isset($r['data']) && isset($r['data']['properties'])) {
  273. return $r['data']['properties'];
  274. } else {
  275. return false;
  276. }
  277. }
  278. function static_map($latitude, $longitude, $height=180, $width=700, $zoom=14) {
  279. return 'https://atlas.p3k.io/map/img?marker[]=lat:' . $latitude . ';lng:' . $longitude . ';icon:small-blue-cutout&basemap=gray&width=' . $width . '&height=' . $height . '&zoom=' . $zoom;
  280. }
  281. function relative_time($date) {
  282. static $rel;
  283. if(!isset($rel)) {
  284. $config = array(
  285. 'language' => '\RelativeTime\Languages\English',
  286. 'separator' => ', ',
  287. 'suffix' => true,
  288. 'truncate' => 1,
  289. );
  290. $rel = new \RelativeTime\RelativeTime($config);
  291. }
  292. return $rel->timeAgo($date);
  293. }
  294. function instagram_client() {
  295. return new Andreyco\Instagram\Client(array(
  296. 'apiKey' => Config::$instagramClientID,
  297. 'apiSecret' => Config::$instagramClientSecret,
  298. 'apiCallback' => Config::$base_url . 'auth/instagram/callback',
  299. 'scope' => array('basic','likes'),
  300. ));
  301. }
  302. function validate_photo(&$file) {
  303. try {
  304. if ($_SERVER['REQUEST_METHOD'] == 'POST' && count($_POST) < 1 ) {
  305. throw new RuntimeException('File upload size exceeded.');
  306. }
  307. // Undefined | Multiple Files | $_FILES Corruption Attack
  308. // If this request falls under any of them, treat it invalid.
  309. if (
  310. !isset($file['error']) ||
  311. is_array($file['error'])
  312. ) {
  313. throw new RuntimeException('Invalid parameters.');
  314. }
  315. // Check $file['error'] value.
  316. switch ($file['error']) {
  317. case UPLOAD_ERR_OK:
  318. break;
  319. case UPLOAD_ERR_NO_FILE:
  320. throw new RuntimeException('No file sent.');
  321. case UPLOAD_ERR_INI_SIZE:
  322. case UPLOAD_ERR_FORM_SIZE:
  323. throw new RuntimeException('Exceeded filesize limit.');
  324. default:
  325. throw new RuntimeException('Unknown errors.');
  326. }
  327. // You should also check filesize here.
  328. if ($file['size'] > 4000000) {
  329. throw new RuntimeException('Exceeded filesize limit.');
  330. }
  331. // DO NOT TRUST $file['mime'] VALUE !!
  332. // Check MIME Type by yourself.
  333. $finfo = new finfo(FILEINFO_MIME_TYPE);
  334. if (false === $ext = array_search(
  335. $finfo->file($file['tmp_name']),
  336. array(
  337. 'jpg' => 'image/jpeg',
  338. 'png' => 'image/png',
  339. 'gif' => 'image/gif',
  340. ),
  341. true
  342. )) {
  343. throw new RuntimeException('Invalid file format.');
  344. }
  345. } catch (RuntimeException $e) {
  346. return $e->getMessage();
  347. }
  348. }
  349. // Reads the exif rotation data and actually rotates the photo.
  350. // Only does anything if the exif library is loaded, otherwise is a noop.
  351. function correct_photo_rotation($filename) {
  352. if(class_exists('IMagick')) {
  353. try {
  354. $image = new IMagick($filename);
  355. $orientation = $image->getImageOrientation();
  356. switch($orientation) {
  357. case IMagick::ORIENTATION_BOTTOMRIGHT:
  358. $image->rotateImage(new ImagickPixel('#00000000'), 180);
  359. break;
  360. case IMagick::ORIENTATION_RIGHTTOP:
  361. $image->rotateImage(new ImagickPixel('#00000000'), 90);
  362. break;
  363. case IMagick::ORIENTATION_LEFTBOTTOM:
  364. $image->rotateImage(new ImagickPixel('#00000000'), -90);
  365. break;
  366. }
  367. $image->setImageOrientation(IMagick::ORIENTATION_TOPLEFT);
  368. $image->writeImage($filename);
  369. } catch(Exception $e){}
  370. }
  371. }
  372. function sanitize_editor_html($html) {
  373. #error_log($html."\n");
  374. $config = HTMLPurifier_Config::createDefault();
  375. $config->autoFinalize = false;
  376. $config->set('Cache.DefinitionImpl', null);
  377. $config->set('HTML.AllowedElements', [
  378. 'a',
  379. 'abbr',
  380. 'b',
  381. 'br',
  382. 'code',
  383. 'del',
  384. 'em',
  385. 'i',
  386. 'img',
  387. 'q',
  388. 'strike',
  389. 'strong',
  390. 'blockquote',
  391. 'pre',
  392. 'p',
  393. 'h1',
  394. 'h2',
  395. 'h3',
  396. 'h4',
  397. 'h5',
  398. 'h6',
  399. 'ul',
  400. 'li',
  401. 'ol',
  402. 'figcaption',
  403. 'figure'
  404. ]);
  405. $def = $config->getHTMLDefinition(true);
  406. // http://developers.whatwg.org/grouping-content.html
  407. $def->addElement('figure', 'Block', 'Optional: (figcaption, Flow) | (Flow, figcaption) | Flow', 'Common');
  408. $def->addElement('figcaption', 'Inline', 'Flow', 'Common');
  409. // Allow data: URIs
  410. $config->set('URI.AllowedSchemes', array('data' => true, 'http' => true, 'https' => true));
  411. // Strip all classes from elements
  412. $config->set('Attr.AllowedClasses', '');
  413. // $def = $config->getHTMLDefinition(true);
  414. $purifier = new HTMLPurifier($config);
  415. $sanitized = $purifier->purify($html);
  416. $sanitized = str_replace("&#xD;","\r",$sanitized);
  417. # Remove empty paragraphs
  418. $sanitized = str_replace('<p><br /></p>','',$sanitized);
  419. $sanitized = str_replace('<p></p>','',$sanitized);
  420. $indenter = new \Gajus\Dindent\Indenter([
  421. 'indentation_character' => ' '
  422. ]);
  423. $indenter->setElementType('h1', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  424. $indenter->setElementType('h2', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  425. $indenter->setElementType('h3', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  426. $indenter->setElementType('h4', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  427. $indenter->setElementType('h5', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  428. $indenter->setElementType('h6', \Gajus\Dindent\Indenter::ELEMENT_TYPE_INLINE);
  429. $sanitized = $indenter->indent($sanitized);
  430. #error_log($sanitized."\n");
  431. return $sanitized;
  432. }