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.

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