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.

348 lines
10 KiB

  1. <?php
  2. if(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. if(!function_exists('http_build_url')) {
  68. function http_build_url($parsed_url) {
  69. $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
  70. $host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
  71. $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
  72. $user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
  73. $pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
  74. $pass = ($user || $pass) ? "$pass@" : '';
  75. $path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
  76. $query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
  77. $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
  78. return "$scheme$user$pass$host$port$path$query$fragment";
  79. }
  80. }
  81. function micropub_post_for_user(&$user, $params, $file_path = NULL, $json = false) {
  82. // Now send to the micropub endpoint
  83. $r = micropub_post($user->micropub_endpoint, $params, $user->micropub_access_token, $file_path, $json);
  84. $user->last_micropub_response = substr(json_encode($r), 0, 1024);
  85. $user->last_micropub_response_date = date('Y-m-d H:i:s');
  86. // Check the response and look for a "Location" header containing the URL
  87. if($r['response'] && preg_match('/Location: (.+)/', $r['response'], $match)) {
  88. $r['location'] = trim($match[1]);
  89. $user->micropub_success = 1;
  90. } else {
  91. $r['location'] = false;
  92. }
  93. $user->save();
  94. return $r;
  95. }
  96. function micropub_post($endpoint, $params, $access_token, $file_path = NULL, $json = false) {
  97. $ch = curl_init();
  98. curl_setopt($ch, CURLOPT_URL, $endpoint);
  99. curl_setopt($ch, CURLOPT_POST, true);
  100. // Send the access token in both the header and post body to support more clients
  101. // https://github.com/aaronpk/Quill/issues/4
  102. // http://indiewebcamp.com/irc/2015-02-14#t1423955287064
  103. $httpheaders = array('Authorization: Bearer ' . $access_token);
  104. if(!$json) {
  105. $params = array_merge(array(
  106. 'h' => 'entry',
  107. 'access_token' => $access_token
  108. ), $params);
  109. }
  110. if(!$file_path) {
  111. if($json) {
  112. $params['access_token'] = $access_token;
  113. $httpheaders[] = 'Content-type: application/json';
  114. $post = json_encode($params);
  115. } else {
  116. $post = http_build_query($params);
  117. $post = preg_replace('/%5B[0-9]+%5D/', '%5B%5D', $post); // change [0] to []
  118. }
  119. } else {
  120. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  121. $mimetype = finfo_file($finfo, $file_path);
  122. $multipart = new p3k\Multipart();
  123. $multipart->addArray($params);
  124. $multipart->addFile('photo', $file_path, $mimetype);
  125. $post = $multipart->data();
  126. array_push($httpheaders, 'Content-Type: ' . $multipart->contentType());
  127. }
  128. curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheaders);
  129. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  130. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  131. curl_setopt($ch, CURLOPT_HEADER, true);
  132. curl_setopt($ch, CURLINFO_HEADER_OUT, true);
  133. $response = curl_exec($ch);
  134. $error = curl_error($ch);
  135. $sent_headers = curl_getinfo($ch, CURLINFO_HEADER_OUT);
  136. $request = $sent_headers . $post;
  137. return array(
  138. 'request' => $request,
  139. 'response' => $response,
  140. 'error' => $error,
  141. 'curlinfo' => curl_getinfo($ch)
  142. );
  143. }
  144. function micropub_get($endpoint, $params, $access_token) {
  145. $url = parse_url($endpoint);
  146. if(!k($url, 'query')) {
  147. $url['query'] = http_build_query($params);
  148. } else {
  149. $url['query'] .= '&' . http_build_query($params);
  150. }
  151. $endpoint = http_build_url($url);
  152. $ch = curl_init();
  153. curl_setopt($ch, CURLOPT_URL, $endpoint);
  154. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  155. 'Authorization: Bearer ' . $access_token
  156. ));
  157. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  158. $response = curl_exec($ch);
  159. $data = array();
  160. if($response) {
  161. parse_str($response, $data);
  162. }
  163. $error = curl_error($ch);
  164. return array(
  165. 'response' => $response,
  166. 'data' => $data,
  167. 'error' => $error,
  168. 'curlinfo' => curl_getinfo($ch)
  169. );
  170. }
  171. function get_syndication_targets(&$user) {
  172. $targets = array();
  173. $r = micropub_get($user->micropub_endpoint, array('q'=>'syndicate-to'), $user->micropub_access_token);
  174. if($r['data'] && array_key_exists('syndicate-to', $r['data'])) {
  175. if(is_array($r['data']['syndicate-to'])) {
  176. $targetURLs = $r['data']['syndicate-to'];
  177. } elseif(is_string($r['data']['syndicate-to'])) {
  178. // support comma separated as a fallback
  179. $targetURLs = preg_split('/, ?/', $r['data']['syndicate-to']);
  180. } else {
  181. $targetURLs = array();
  182. }
  183. foreach($targetURLs as $t) {
  184. // If the syndication target doesn't have a scheme, add http
  185. if(!preg_match('/^http/', $t))
  186. $t2 = 'http://' . $t;
  187. else
  188. $t2 = $t;
  189. // Parse the target expecting it to be a URL
  190. $url = parse_url($t2);
  191. // If there's a host, and the host contains a . then we can assume there's a favicon
  192. // parse_url will parse strings like http://twitter into an array with a host of twitter, which is not resolvable
  193. if($url && array_key_exists('host', $url) && strpos($url['host'], '.') !== false) {
  194. $targets[] = array(
  195. 'target' => $t,
  196. 'favicon' => 'http://' . $url['host'] . '/favicon.ico'
  197. );
  198. } else {
  199. $targets[] = array(
  200. 'target' => $t,
  201. 'favicon' => false
  202. );
  203. }
  204. }
  205. }
  206. if(count($targets)) {
  207. $user->syndication_targets = json_encode($targets);
  208. $user->save();
  209. }
  210. return array(
  211. 'targets' => $targets,
  212. 'response' => $r
  213. );
  214. }
  215. function static_map($latitude, $longitude, $height=180, $width=700, $zoom=14) {
  216. return 'https://atlas.p3k.io/map/img?marker[]=lat:' . $latitude . ';lng:' . $longitude . ';icon:small-blue-cutout&basemap=gray&width=' . $width . '&height=' . $height . '&zoom=' . $zoom;
  217. }
  218. function relative_time($date) {
  219. static $rel;
  220. if(!isset($rel)) {
  221. $config = array(
  222. 'language' => '\RelativeTime\Languages\English',
  223. 'separator' => ', ',
  224. 'suffix' => true,
  225. 'truncate' => 1,
  226. );
  227. $rel = new \RelativeTime\RelativeTime($config);
  228. }
  229. return $rel->timeAgo($date);
  230. }
  231. function instagram_client() {
  232. return new Andreyco\Instagram\Client(array(
  233. 'apiKey' => Config::$instagramClientID,
  234. 'apiSecret' => Config::$instagramClientSecret,
  235. 'apiCallback' => Config::$base_url . 'auth/instagram/callback',
  236. 'scope' => array('basic','likes'),
  237. ));
  238. }
  239. function validate_photo(&$file) {
  240. try {
  241. if ($_SERVER['REQUEST_METHOD'] == 'POST' && count($_POST) < 1 ) {
  242. throw new RuntimeException('File upload size exceeded.');
  243. }
  244. // Undefined | Multiple Files | $_FILES Corruption Attack
  245. // If this request falls under any of them, treat it invalid.
  246. if (
  247. !isset($file['error']) ||
  248. is_array($file['error'])
  249. ) {
  250. throw new RuntimeException('Invalid parameters.');
  251. }
  252. // Check $file['error'] value.
  253. switch ($file['error']) {
  254. case UPLOAD_ERR_OK:
  255. break;
  256. case UPLOAD_ERR_NO_FILE:
  257. throw new RuntimeException('No file sent.');
  258. case UPLOAD_ERR_INI_SIZE:
  259. case UPLOAD_ERR_FORM_SIZE:
  260. throw new RuntimeException('Exceeded filesize limit.');
  261. default:
  262. throw new RuntimeException('Unknown errors.');
  263. }
  264. // You should also check filesize here.
  265. if ($file['size'] > 4000000) {
  266. throw new RuntimeException('Exceeded filesize limit.');
  267. }
  268. // DO NOT TRUST $file['mime'] VALUE !!
  269. // Check MIME Type by yourself.
  270. $finfo = new finfo(FILEINFO_MIME_TYPE);
  271. if (false === $ext = array_search(
  272. $finfo->file($file['tmp_name']),
  273. array(
  274. 'jpg' => 'image/jpeg',
  275. 'png' => 'image/png',
  276. 'gif' => 'image/gif',
  277. ),
  278. true
  279. )) {
  280. throw new RuntimeException('Invalid file format.');
  281. }
  282. } catch (RuntimeException $e) {
  283. return $e->getMessage();
  284. }
  285. }
  286. // Reads the exif rotation data and actually rotates the photo.
  287. // Only does anything if the exif library is loaded, otherwise is a noop.
  288. function correct_photo_rotation($filename) {
  289. if(class_exists('IMagick')) {
  290. $image = new IMagick($filename);
  291. $orientation = $image->getImageOrientation();
  292. switch($orientation) {
  293. case IMagick::ORIENTATION_BOTTOMRIGHT:
  294. $image->rotateImage(new ImagickPixel('#00000000'), 180);
  295. break;
  296. case IMagick::ORIENTATION_RIGHTTOP:
  297. $image->rotateImage(new ImagickPixel('#00000000'), 90);
  298. break;
  299. case IMagick::ORIENTATION_LEFTBOTTOM:
  300. $image->rotateImage(new ImagickPixel('#00000000'), -90);
  301. break;
  302. }
  303. $image->setImageOrientation(IMagick::ORIENTATION_TOPLEFT);
  304. $image->writeImage($filename);
  305. }
  306. }