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.

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