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.

337 lines
10 KiB

  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. 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. 'Accept: application/json'
  157. ));
  158. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  159. $response = curl_exec($ch);
  160. $data = array();
  161. if($response) {
  162. $data = json_decode($response, true);
  163. }
  164. $error = curl_error($ch);
  165. return array(
  166. 'response' => $response,
  167. 'data' => $data,
  168. 'error' => $error,
  169. 'curlinfo' => curl_getinfo($ch)
  170. );
  171. }
  172. function get_syndication_targets(&$user) {
  173. $targets = array();
  174. $r = micropub_get($user->micropub_endpoint, array('q'=>'syndicate-to'), $user->micropub_access_token);
  175. if($r['data'] && array_key_exists('syndicate-to', $r['data'])) {
  176. if(is_array($r['data']['syndicate-to'])) {
  177. $data = $r['data']['syndicate-to'];
  178. } else {
  179. $data = array();
  180. }
  181. foreach($data as $t) {
  182. if(array_key_exists('service', $t) && array_key_exists('photo', $t['service'])) {
  183. $icon = $t['service']['photo'];
  184. } else {
  185. $icon = false;
  186. }
  187. if(array_key_exists('uid', $t) && array_key_exists('name', $t)) {
  188. $targets[] = array(
  189. 'target' => $t['name'],
  190. 'uid' => $t['uid'],
  191. 'favicon' => $icon
  192. );
  193. }
  194. }
  195. }
  196. if(count($targets)) {
  197. $user->syndication_targets = json_encode($targets);
  198. $user->save();
  199. }
  200. return array(
  201. 'targets' => $targets,
  202. 'response' => $r
  203. );
  204. }
  205. function static_map($latitude, $longitude, $height=180, $width=700, $zoom=14) {
  206. return 'https://atlas.p3k.io/map/img?marker[]=lat:' . $latitude . ';lng:' . $longitude . ';icon:small-blue-cutout&basemap=gray&width=' . $width . '&height=' . $height . '&zoom=' . $zoom;
  207. }
  208. function relative_time($date) {
  209. static $rel;
  210. if(!isset($rel)) {
  211. $config = array(
  212. 'language' => '\RelativeTime\Languages\English',
  213. 'separator' => ', ',
  214. 'suffix' => true,
  215. 'truncate' => 1,
  216. );
  217. $rel = new \RelativeTime\RelativeTime($config);
  218. }
  219. return $rel->timeAgo($date);
  220. }
  221. function instagram_client() {
  222. return new Andreyco\Instagram\Client(array(
  223. 'apiKey' => Config::$instagramClientID,
  224. 'apiSecret' => Config::$instagramClientSecret,
  225. 'apiCallback' => Config::$base_url . 'auth/instagram/callback',
  226. 'scope' => array('basic','likes'),
  227. ));
  228. }
  229. function validate_photo(&$file) {
  230. try {
  231. if ($_SERVER['REQUEST_METHOD'] == 'POST' && count($_POST) < 1 ) {
  232. throw new RuntimeException('File upload size exceeded.');
  233. }
  234. // Undefined | Multiple Files | $_FILES Corruption Attack
  235. // If this request falls under any of them, treat it invalid.
  236. if (
  237. !isset($file['error']) ||
  238. is_array($file['error'])
  239. ) {
  240. throw new RuntimeException('Invalid parameters.');
  241. }
  242. // Check $file['error'] value.
  243. switch ($file['error']) {
  244. case UPLOAD_ERR_OK:
  245. break;
  246. case UPLOAD_ERR_NO_FILE:
  247. throw new RuntimeException('No file sent.');
  248. case UPLOAD_ERR_INI_SIZE:
  249. case UPLOAD_ERR_FORM_SIZE:
  250. throw new RuntimeException('Exceeded filesize limit.');
  251. default:
  252. throw new RuntimeException('Unknown errors.');
  253. }
  254. // You should also check filesize here.
  255. if ($file['size'] > 4000000) {
  256. throw new RuntimeException('Exceeded filesize limit.');
  257. }
  258. // DO NOT TRUST $file['mime'] VALUE !!
  259. // Check MIME Type by yourself.
  260. $finfo = new finfo(FILEINFO_MIME_TYPE);
  261. if (false === $ext = array_search(
  262. $finfo->file($file['tmp_name']),
  263. array(
  264. 'jpg' => 'image/jpeg',
  265. 'png' => 'image/png',
  266. 'gif' => 'image/gif',
  267. ),
  268. true
  269. )) {
  270. throw new RuntimeException('Invalid file format.');
  271. }
  272. } catch (RuntimeException $e) {
  273. return $e->getMessage();
  274. }
  275. }
  276. // Reads the exif rotation data and actually rotates the photo.
  277. // Only does anything if the exif library is loaded, otherwise is a noop.
  278. function correct_photo_rotation($filename) {
  279. if(class_exists('IMagick')) {
  280. $image = new IMagick($filename);
  281. $orientation = $image->getImageOrientation();
  282. switch($orientation) {
  283. case IMagick::ORIENTATION_BOTTOMRIGHT:
  284. $image->rotateImage(new ImagickPixel('#00000000'), 180);
  285. break;
  286. case IMagick::ORIENTATION_RIGHTTOP:
  287. $image->rotateImage(new ImagickPixel('#00000000'), 90);
  288. break;
  289. case IMagick::ORIENTATION_LEFTBOTTOM:
  290. $image->rotateImage(new ImagickPixel('#00000000'), -90);
  291. break;
  292. }
  293. $image->setImageOrientation(IMagick::ORIENTATION_TOPLEFT);
  294. $image->writeImage($filename);
  295. }
  296. }