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.

282 lines
8.2 KiB

  1. <?php
  2. ORM::configure('mysql:host=' . Config::$dbHost . ';dbname=' . Config::$dbName);
  3. ORM::configure('username', Config::$dbUsername);
  4. ORM::configure('password', Config::$dbPassword);
  5. function render($page, $data) {
  6. global $app;
  7. return $app->render('layout.php', array_merge($data, array('page' => $page)));
  8. };
  9. function partial($template, $data=array(), $debug=false) {
  10. global $app;
  11. if($debug) {
  12. $tpl = new Savant3(\Slim\Extras\Views\Savant::$savantOptions);
  13. echo '<pre>' . $tpl->fetch($template . '.php') . '</pre>';
  14. return '';
  15. }
  16. ob_start();
  17. $tpl = new Savant3(\Slim\Extras\Views\Savant::$savantOptions);
  18. foreach($data as $k=>$v) {
  19. $tpl->{$k} = $v;
  20. }
  21. $tpl->display($template . '.php');
  22. return ob_get_clean();
  23. }
  24. function js_bookmarklet($partial, $context) {
  25. return str_replace('+','%20',urlencode(str_replace(array("\n"),array(''),partial($partial, $context))));
  26. }
  27. function session($key) {
  28. if(array_key_exists($key, $_SESSION))
  29. return $_SESSION[$key];
  30. else
  31. return null;
  32. }
  33. function k($a, $k, $default=null) {
  34. if(is_array($k)) {
  35. $result = true;
  36. foreach($k as $key) {
  37. $result = $result && array_key_exists($key, $a);
  38. }
  39. return $result;
  40. } else {
  41. if(is_array($a) && array_key_exists($k, $a) && $a[$k])
  42. return $a[$k];
  43. elseif(is_object($a) && property_exists($a, $k) && $a->$k)
  44. return $a->$k;
  45. else
  46. return $default;
  47. }
  48. }
  49. function get_timezone($lat, $lng) {
  50. try {
  51. $ch = curl_init();
  52. curl_setopt($ch, CURLOPT_URL, 'http://timezone-api.geoloqi.com/timezone/'.$lat.'/'.$lng);
  53. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  54. $response = curl_exec($ch);
  55. $tz = @json_decode($response);
  56. if($tz)
  57. return new DateTimeZone($tz->timezone);
  58. } catch(Exception $e) {
  59. return null;
  60. }
  61. return null;
  62. }
  63. function micropub_post_for_user(&$user, $params, $file_path = NULL) {
  64. // Now send to the micropub endpoint
  65. $r = micropub_post($user->micropub_endpoint, $params, $user->micropub_access_token, $file_path);
  66. $user->last_micropub_response = substr(json_encode($r), 0, 1024);
  67. $user->last_micropub_response_date = date('Y-m-d H:i:s');
  68. // Check the response and look for a "Location" header containing the URL
  69. if($r['response'] && preg_match('/Location: (.+)/', $r['response'], $match)) {
  70. $r['location'] = trim($match[1]);
  71. $user->micropub_success = 1;
  72. } else {
  73. $r['location'] = false;
  74. }
  75. $user->save();
  76. return $r;
  77. }
  78. function micropub_post($endpoint, $params, $access_token, $file_path = NULL) {
  79. $ch = curl_init();
  80. curl_setopt($ch, CURLOPT_URL, $endpoint);
  81. curl_setopt($ch, CURLOPT_POST, true);
  82. $httpheaders = array('Authorization: Bearer ' . $access_token);
  83. $params = array_merge(array('h' => 'entry'), $params);
  84. if(!$file_path) {
  85. $post = http_build_query($params);
  86. $post = preg_replace('/%5B[0-9]+%5D/', '%5B%5D', $post); // change [0] to []
  87. } else {
  88. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  89. $mimetype = finfo_file($finfo, $file_path);
  90. $multipart = new p3k\Multipart();
  91. $multipart->addArray($params);
  92. $multipart->addFile('photo', $file_path, $mimetype);
  93. $post = $multipart->data();
  94. array_push($httpheaders, 'Content-Type: ' . $multipart->contentType());
  95. }
  96. curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheaders);
  97. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  98. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  99. curl_setopt($ch, CURLOPT_HEADER, true);
  100. curl_setopt($ch, CURLINFO_HEADER_OUT, true);
  101. $response = curl_exec($ch);
  102. $error = curl_error($ch);
  103. $sent_headers = curl_getinfo($ch, CURLINFO_HEADER_OUT);
  104. $request = $sent_headers . $post;
  105. return array(
  106. 'request' => $request,
  107. 'response' => $response,
  108. 'error' => $error,
  109. 'curlinfo' => curl_getinfo($ch)
  110. );
  111. }
  112. function micropub_get($endpoint, $params, $access_token) {
  113. $ch = curl_init();
  114. curl_setopt($ch, CURLOPT_URL, $endpoint . '?' . http_build_query($params));
  115. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  116. 'Authorization: Bearer ' . $access_token
  117. ));
  118. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  119. $response = curl_exec($ch);
  120. $data = array();
  121. if($response) {
  122. parse_str($response, $data);
  123. }
  124. $error = curl_error($ch);
  125. return array(
  126. 'response' => $response,
  127. 'data' => $data,
  128. 'error' => $error,
  129. 'curlinfo' => curl_getinfo($ch)
  130. );
  131. }
  132. function get_syndication_targets(&$user) {
  133. $targets = array();
  134. $r = micropub_get($user->micropub_endpoint, array('q'=>'syndicate-to'), $user->micropub_access_token);
  135. if($r['data'] && array_key_exists('syndicate-to', $r['data'])) {
  136. if(is_array($r['data']['syndicate-to'])) {
  137. $targetURLs = $r['data']['syndicate-to'];
  138. } elseif(is_string($r['data']['syndicate-to'])) {
  139. // support comma separated as a fallback
  140. $targetURLs = preg_split('/, ?/', $r['data']['syndicate-to']);
  141. } else {
  142. $targetURLs = array();
  143. }
  144. foreach($targetURLs as $t) {
  145. // If the syndication target doesn't have a scheme, add http
  146. if(!preg_match('/^http/', $t))
  147. $t2 = 'http://' . $t;
  148. else
  149. $t2 = $t;
  150. // Parse the target expecting it to be a URL
  151. $url = parse_url($t2);
  152. // If there's a host, and the host contains a . then we can assume there's a favicon
  153. // parse_url will parse strings like http://twitter into an array with a host of twitter, which is not resolvable
  154. if(array_key_exists('host', $url) && strpos($url['host'], '.') !== false) {
  155. $targets[] = array(
  156. 'target' => $t,
  157. 'favicon' => 'http://' . $url['host'] . '/favicon.ico'
  158. );
  159. } else {
  160. $targets[] = array(
  161. 'target' => $t,
  162. 'favicon' => false
  163. );
  164. }
  165. }
  166. }
  167. if(count($targets)) {
  168. $user->syndication_targets = json_encode($targets);
  169. $user->save();
  170. }
  171. return array(
  172. 'targets' => $targets,
  173. 'response' => $r
  174. );
  175. }
  176. function static_map($latitude, $longitude, $height=180, $width=700, $zoom=14) {
  177. 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;
  178. }
  179. function relative_time($date) {
  180. static $rel;
  181. if(!isset($rel)) {
  182. $config = array(
  183. 'language' => '\RelativeTime\Languages\English',
  184. 'separator' => ', ',
  185. 'suffix' => true,
  186. 'truncate' => 1,
  187. );
  188. $rel = new \RelativeTime\RelativeTime($config);
  189. }
  190. return $rel->timeAgo($date);
  191. }
  192. function instagram_client() {
  193. return new Andreyco\Instagram\Client(array(
  194. 'apiKey' => Config::$instagramClientID,
  195. 'apiSecret' => Config::$instagramClientSecret,
  196. 'apiCallback' => Config::$base_url . 'auth/instagram/callback',
  197. 'scope' => array('basic','likes'),
  198. ));
  199. }
  200. function validate_photo(&$file) {
  201. try {
  202. if ($_SERVER['REQUEST_METHOD'] == 'POST' && count($_POST) < 1 ) {
  203. throw new RuntimeException('File upload size exceeded.');
  204. }
  205. // Undefined | Multiple Files | $_FILES Corruption Attack
  206. // If this request falls under any of them, treat it invalid.
  207. if (
  208. !isset($file['error']) ||
  209. is_array($file['error'])
  210. ) {
  211. throw new RuntimeException('Invalid parameters.');
  212. }
  213. // Check $file['error'] value.
  214. switch ($file['error']) {
  215. case UPLOAD_ERR_OK:
  216. break;
  217. case UPLOAD_ERR_NO_FILE:
  218. throw new RuntimeException('No file sent.');
  219. case UPLOAD_ERR_INI_SIZE:
  220. case UPLOAD_ERR_FORM_SIZE:
  221. throw new RuntimeException('Exceeded filesize limit.');
  222. default:
  223. throw new RuntimeException('Unknown errors.');
  224. }
  225. // You should also check filesize here.
  226. if ($file['size'] > 1000000) {
  227. throw new RuntimeException('Exceeded filesize limit.');
  228. }
  229. // DO NOT TRUST $file['mime'] VALUE !!
  230. // Check MIME Type by yourself.
  231. $finfo = new finfo(FILEINFO_MIME_TYPE);
  232. if (false === $ext = array_search(
  233. $finfo->file($file['tmp_name']),
  234. array(
  235. 'jpg' => 'image/jpeg',
  236. 'png' => 'image/png',
  237. 'gif' => 'image/gif',
  238. ),
  239. true
  240. )) {
  241. throw new RuntimeException('Invalid file format.');
  242. }
  243. } catch (RuntimeException $e) {
  244. return $e->getMessage();
  245. }
  246. }