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.

315 lines
9.5 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) {
  82. // Now send to the micropub endpoint
  83. $r = micropub_post($user->micropub_endpoint, $params, $user->micropub_access_token, $file_path);
  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) {
  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. $params = array_merge(array(
  105. 'h' => 'entry',
  106. 'access_token' => $access_token
  107. ), $params);
  108. if(!$file_path) {
  109. $post = http_build_query($params);
  110. $post = preg_replace('/%5B[0-9]+%5D/', '%5B%5D', $post); // change [0] to []
  111. } else {
  112. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  113. $mimetype = finfo_file($finfo, $file_path);
  114. $multipart = new p3k\Multipart();
  115. $multipart->addArray($params);
  116. $multipart->addFile('photo', $file_path, $mimetype);
  117. $post = $multipart->data();
  118. array_push($httpheaders, 'Content-Type: ' . $multipart->contentType());
  119. }
  120. curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheaders);
  121. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  122. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  123. curl_setopt($ch, CURLOPT_HEADER, true);
  124. curl_setopt($ch, CURLINFO_HEADER_OUT, true);
  125. $response = curl_exec($ch);
  126. $error = curl_error($ch);
  127. $sent_headers = curl_getinfo($ch, CURLINFO_HEADER_OUT);
  128. $request = $sent_headers . $post;
  129. return array(
  130. 'request' => $request,
  131. 'response' => $response,
  132. 'error' => $error,
  133. 'curlinfo' => curl_getinfo($ch)
  134. );
  135. }
  136. function micropub_get($endpoint, $params, $access_token) {
  137. $url = parse_url($endpoint);
  138. if(!k($url, 'query')) {
  139. $url['query'] = http_build_query($params);
  140. } else {
  141. $url['query'] .= '&' . http_build_query($params);
  142. }
  143. $endpoint = http_build_url($url);
  144. $ch = curl_init();
  145. curl_setopt($ch, CURLOPT_URL, $endpoint);
  146. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  147. 'Authorization: Bearer ' . $access_token
  148. ));
  149. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  150. $response = curl_exec($ch);
  151. $data = array();
  152. if($response) {
  153. parse_str($response, $data);
  154. }
  155. $error = curl_error($ch);
  156. return array(
  157. 'response' => $response,
  158. 'data' => $data,
  159. 'error' => $error,
  160. 'curlinfo' => curl_getinfo($ch)
  161. );
  162. }
  163. function get_syndication_targets(&$user) {
  164. $targets = array();
  165. $r = micropub_get($user->micropub_endpoint, array('q'=>'syndicate-to'), $user->micropub_access_token);
  166. if($r['data'] && array_key_exists('syndicate-to', $r['data'])) {
  167. if(is_array($r['data']['syndicate-to'])) {
  168. $targetURLs = $r['data']['syndicate-to'];
  169. } elseif(is_string($r['data']['syndicate-to'])) {
  170. // support comma separated as a fallback
  171. $targetURLs = preg_split('/, ?/', $r['data']['syndicate-to']);
  172. } else {
  173. $targetURLs = array();
  174. }
  175. foreach($targetURLs as $t) {
  176. // If the syndication target doesn't have a scheme, add http
  177. if(!preg_match('/^http/', $t))
  178. $t2 = 'http://' . $t;
  179. else
  180. $t2 = $t;
  181. // Parse the target expecting it to be a URL
  182. $url = parse_url($t2);
  183. // If there's a host, and the host contains a . then we can assume there's a favicon
  184. // parse_url will parse strings like http://twitter into an array with a host of twitter, which is not resolvable
  185. if(array_key_exists('host', $url) && strpos($url['host'], '.') !== false) {
  186. $targets[] = array(
  187. 'target' => $t,
  188. 'favicon' => 'http://' . $url['host'] . '/favicon.ico'
  189. );
  190. } else {
  191. $targets[] = array(
  192. 'target' => $t,
  193. 'favicon' => false
  194. );
  195. }
  196. }
  197. }
  198. if(count($targets)) {
  199. $user->syndication_targets = json_encode($targets);
  200. $user->save();
  201. }
  202. return array(
  203. 'targets' => $targets,
  204. 'response' => $r
  205. );
  206. }
  207. function static_map($latitude, $longitude, $height=180, $width=700, $zoom=14) {
  208. return 'http://static-maps.pdx.esri.com/img.php?marker[]=lat:' . $latitude . ';lng:' . $longitude . ';icon:small-blue-cutout&basemap=gray&width=' . $width . '&height=' . $height . '&zoom=' . $zoom;
  209. }
  210. function relative_time($date) {
  211. static $rel;
  212. if(!isset($rel)) {
  213. $config = array(
  214. 'language' => '\RelativeTime\Languages\English',
  215. 'separator' => ', ',
  216. 'suffix' => true,
  217. 'truncate' => 1,
  218. );
  219. $rel = new \RelativeTime\RelativeTime($config);
  220. }
  221. return $rel->timeAgo($date);
  222. }
  223. function instagram_client() {
  224. return new Andreyco\Instagram\Client(array(
  225. 'apiKey' => Config::$instagramClientID,
  226. 'apiSecret' => Config::$instagramClientSecret,
  227. 'apiCallback' => Config::$base_url . 'auth/instagram/callback',
  228. 'scope' => array('basic','likes'),
  229. ));
  230. }
  231. function validate_photo(&$file) {
  232. try {
  233. if ($_SERVER['REQUEST_METHOD'] == 'POST' && count($_POST) < 1 ) {
  234. throw new RuntimeException('File upload size exceeded.');
  235. }
  236. // Undefined | Multiple Files | $_FILES Corruption Attack
  237. // If this request falls under any of them, treat it invalid.
  238. if (
  239. !isset($file['error']) ||
  240. is_array($file['error'])
  241. ) {
  242. throw new RuntimeException('Invalid parameters.');
  243. }
  244. // Check $file['error'] value.
  245. switch ($file['error']) {
  246. case UPLOAD_ERR_OK:
  247. break;
  248. case UPLOAD_ERR_NO_FILE:
  249. throw new RuntimeException('No file sent.');
  250. case UPLOAD_ERR_INI_SIZE:
  251. case UPLOAD_ERR_FORM_SIZE:
  252. throw new RuntimeException('Exceeded filesize limit.');
  253. default:
  254. throw new RuntimeException('Unknown errors.');
  255. }
  256. // You should also check filesize here.
  257. if ($file['size'] > 4000000) {
  258. throw new RuntimeException('Exceeded filesize limit.');
  259. }
  260. // DO NOT TRUST $file['mime'] VALUE !!
  261. // Check MIME Type by yourself.
  262. $finfo = new finfo(FILEINFO_MIME_TYPE);
  263. if (false === $ext = array_search(
  264. $finfo->file($file['tmp_name']),
  265. array(
  266. 'jpg' => 'image/jpeg',
  267. 'png' => 'image/png',
  268. 'gif' => 'image/gif',
  269. ),
  270. true
  271. )) {
  272. throw new RuntimeException('Invalid file format.');
  273. }
  274. } catch (RuntimeException $e) {
  275. return $e->getMessage();
  276. }
  277. }