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.

441 lines
13 KiB

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 get_timezone($lat, $lng) {
  54. try {
  55. $ch = curl_init();
  56. curl_setopt($ch, CURLOPT_URL, 'http://atlas.p3k.io/api/timezone?latitude='.$lat.'&longitude='.$lng);
  57. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  58. $response = curl_exec($ch);
  59. $tz = @json_decode($response);
  60. if($tz)
  61. return new DateTimeZone($tz->timezone);
  62. } catch(Exception $e) {
  63. return null;
  64. }
  65. return null;
  66. }
  67. function display_url($url) {
  68. $parts = parse_url($url);
  69. if($parts['path'] != '' && $parts['path'] != '/') {
  70. return preg_replace('/^https?:\/\//','', $url);
  71. } else {
  72. return $parts['host'];
  73. }
  74. }
  75. if(!function_exists('http_build_url')) {
  76. function http_build_url($parsed_url) {
  77. $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
  78. $host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
  79. $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
  80. $user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
  81. $pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
  82. $pass = ($user || $pass) ? "$pass@" : '';
  83. $path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
  84. $query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
  85. $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
  86. return "$scheme$user$pass$host$port$path$query$fragment";
  87. }
  88. }
  89. function micropub_post_for_user(&$user, $params, $file_path = NULL, $json = false) {
  90. // Now send to the micropub endpoint
  91. $r = micropub_post($user->micropub_endpoint, $params, $user->micropub_access_token, $file_path, $json);
  92. $user->last_micropub_response = substr(json_encode($r), 0, 1024);
  93. $user->last_micropub_response_date = date('Y-m-d H:i:s');
  94. // Check the response and look for a "Location" header containing the URL
  95. if($r['response'] && ($r['code'] == 201 || $r['code'] == 202)
  96. && isset($r['headers']['Location'])) {
  97. $r['location'] = $r['headers']['Location'][0];
  98. $user->micropub_success = 1;
  99. } else {
  100. $r['location'] = false;
  101. }
  102. $user->save();
  103. return $r;
  104. }
  105. function micropub_media_post_for_user(&$user, $file_path) {
  106. // Send to the media endpoint
  107. $r = micropub_post($user->micropub_media_endpoint, [], $user->micropub_access_token, $file_path, true, 'file');
  108. // Check the response and look for a "Location" header containing the URL
  109. if($r['response'] && preg_match('/Location: (.+)/', $r['response'], $match)) {
  110. $r['location'] = trim($match[1]);
  111. } else {
  112. $r['location'] = false;
  113. }
  114. return $r;
  115. }
  116. function micropub_post($endpoint, $params, $access_token, $file_path = NULL, $json = false, $file_prop = 'photo') {
  117. $ch = curl_init();
  118. curl_setopt($ch, CURLOPT_URL, $endpoint);
  119. curl_setopt($ch, CURLOPT_POST, true);
  120. // Send the access token in both the header and post body to support more clients
  121. // https://github.com/aaronpk/Quill/issues/4
  122. // http://indiewebcamp.com/irc/2015-02-14#t1423955287064
  123. $httpheaders = array('Authorization: Bearer ' . $access_token);
  124. if(!$json) {
  125. $params = array_merge(array(
  126. 'h' => 'entry',
  127. 'access_token' => $access_token
  128. ), $params);
  129. }
  130. if(!$file_path) {
  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, $file_path, $mimetype);
  145. $post = $multipart->data();
  146. array_push($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 static_map($latitude, $longitude, $height=180, $width=700, $zoom=14) {
  257. return 'https://atlas.p3k.io/map/img?marker[]=lat:' . $latitude . ';lng:' . $longitude . ';icon:small-blue-cutout&basemap=gray&width=' . $width . '&height=' . $height . '&zoom=' . $zoom;
  258. }
  259. function relative_time($date) {
  260. static $rel;
  261. if(!isset($rel)) {
  262. $config = array(
  263. 'language' => '\RelativeTime\Languages\English',
  264. 'separator' => ', ',
  265. 'suffix' => true,
  266. 'truncate' => 1,
  267. );
  268. $rel = new \RelativeTime\RelativeTime($config);
  269. }
  270. return $rel->timeAgo($date);
  271. }
  272. function instagram_client() {
  273. return new Andreyco\Instagram\Client(array(
  274. 'apiKey' => Config::$instagramClientID,
  275. 'apiSecret' => Config::$instagramClientSecret,
  276. 'apiCallback' => Config::$base_url . 'auth/instagram/callback',
  277. 'scope' => array('basic','likes'),
  278. ));
  279. }
  280. function validate_photo(&$file) {
  281. try {
  282. if ($_SERVER['REQUEST_METHOD'] == 'POST' && count($_POST) < 1 ) {
  283. throw new RuntimeException('File upload size exceeded.');
  284. }
  285. // Undefined | Multiple Files | $_FILES Corruption Attack
  286. // If this request falls under any of them, treat it invalid.
  287. if (
  288. !isset($file['error']) ||
  289. is_array($file['error'])
  290. ) {
  291. throw new RuntimeException('Invalid parameters.');
  292. }
  293. // Check $file['error'] value.
  294. switch ($file['error']) {
  295. case UPLOAD_ERR_OK:
  296. break;
  297. case UPLOAD_ERR_NO_FILE:
  298. throw new RuntimeException('No file sent.');
  299. case UPLOAD_ERR_INI_SIZE:
  300. case UPLOAD_ERR_FORM_SIZE:
  301. throw new RuntimeException('Exceeded filesize limit.');
  302. default:
  303. throw new RuntimeException('Unknown errors.');
  304. }
  305. // You should also check filesize here.
  306. if ($file['size'] > 4000000) {
  307. throw new RuntimeException('Exceeded filesize limit.');
  308. }
  309. // DO NOT TRUST $file['mime'] VALUE !!
  310. // Check MIME Type by yourself.
  311. $finfo = new finfo(FILEINFO_MIME_TYPE);
  312. if (false === $ext = array_search(
  313. $finfo->file($file['tmp_name']),
  314. array(
  315. 'jpg' => 'image/jpeg',
  316. 'png' => 'image/png',
  317. 'gif' => 'image/gif',
  318. ),
  319. true
  320. )) {
  321. throw new RuntimeException('Invalid file format.');
  322. }
  323. } catch (RuntimeException $e) {
  324. return $e->getMessage();
  325. }
  326. }
  327. // Reads the exif rotation data and actually rotates the photo.
  328. // Only does anything if the exif library is loaded, otherwise is a noop.
  329. function correct_photo_rotation($filename) {
  330. if(class_exists('IMagick')) {
  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. }
  347. }
  348. function tweet_to_h_entry($tweet) {
  349. // Converts to XRay's h-entry format
  350. $entry = [
  351. 'type' => 'entry',
  352. 'url' => 'https://twitter.com/'.$tweet->user->screen_name.'/status/'.$tweet->id_str,
  353. ];
  354. $published = strtotime($tweet->created_at);
  355. $entry['published'] = date('c', $published);
  356. $entry['content'] = [
  357. 'text' => $tweet->text
  358. ];
  359. if($tweet->entities->urls) {
  360. foreach($tweet->entities->urls as $url) {
  361. $entry['content']['text'] = str_replace($url->url, $url->expanded_url, $entry['content']['text']);
  362. }
  363. }
  364. $entry['author'] = [
  365. 'type' => 'card',
  366. 'url' => 'https://twitter.com/'.$tweet->user->screen_name,
  367. 'name' => $tweet->user->name,
  368. 'nickname' => $tweet->user->screen_name,
  369. 'photo' => $tweet->user->profile_image_url_https
  370. ];
  371. if($tweet->user->url) {
  372. $entry['author']['url'] = $tweet->user->entities->url->urls[0]->expanded_url;
  373. }
  374. if($tweet->entities->hashtags) {
  375. $entry['category'] = [];
  376. foreach($tweet->entities->hashtags as $tag) {
  377. $entry['category'][] = $tag->text;
  378. }
  379. }
  380. return $entry;
  381. }