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.

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