4 * @file include/network.php
8 use Friendica\Core\System;
9 use Friendica\Core\Config;
10 use Friendica\Network\Probe;
12 require_once("include/xml.php");
17 * If binary flag is true, return binary results.
18 * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
19 * to preserve cookies from one request to the next.
21 * @param string $url URL to fetch
22 * @param boolean $binary default false
23 * TRUE if asked to return binary results (file download)
24 * @param integer $redirects The recursion counter for internal use - default 0
25 * @param integer $timeout Timeout in seconds, default system config value or 60 seconds
26 * @param string $accept_content supply Accept: header with 'accept_content' as the value
27 * @param string $cookiejar Path to cookie jar file
29 * @return string The fetched content
31 function fetch_url($url,$binary = false, &$redirects = 0, $timeout = 0, $accept_content=Null, $cookiejar = 0) {
37 array('timeout'=>$timeout,
38 'accept_content'=>$accept_content,
39 'cookiejar'=>$cookiejar
46 * @brief fetches an URL.
48 * @param string $url URL to fetch
49 * @param boolean $binary default false
50 * TRUE if asked to return binary results (file download)
51 * @param int $redirects The recursion counter for internal use - default 0
52 * @param array $opts (optional parameters) assoziative array with:
53 * 'accept_content' => supply Accept: header with 'accept_content' as the value
54 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
55 * 'http_auth' => username:password
56 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
57 * 'nobody' => only return the header
58 * 'cookiejar' => path to cookie jar file
60 * @return array an assoziative array with:
61 * int 'return_code' => HTTP return code or 0 if timeout or failure
62 * boolean 'success' => boolean true (if HTTP 2xx result) or false
63 * string 'redirect_url' => in case of redirect, content was finally retrieved from this URL
64 * string 'header' => HTTP headers
65 * string 'body' => fetched content
67 function z_fetch_url($url, $binary = false, &$redirects = 0, $opts = array()) {
68 $ret = array('return_code' => 0, 'success' => false, 'header' => '', 'body' => '');
70 $stamp1 = microtime(true);
74 if (blocked_url($url)) {
75 logger('z_fetch_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
79 $ch = @curl_init($url);
81 if (($redirects > 8) || (!$ch)) {
85 @curl_setopt($ch, CURLOPT_HEADER, true);
87 if (x($opts, "cookiejar")) {
88 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
89 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
92 // These settings aren't needed. We're following the location already.
93 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
94 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
96 if (x($opts, 'accept_content')) {
97 curl_setopt($ch, CURLOPT_HTTPHEADER, array(
98 'Accept: ' . $opts['accept_content']
102 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
103 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
105 $range = intval(Config::get('system', 'curl_range_bytes', 0));
108 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
111 // Without this setting it seems as if some webservers send compressed content
112 // This seems to confuse curl so that it shows this uncompressed.
113 /// @todo We could possibly set this value to "gzip" or something similar
114 curl_setopt($ch, CURLOPT_ENCODING, '');
116 if (x($opts, 'headers')) {
117 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
120 if (x($opts, 'nobody')) {
121 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
124 if (x($opts, 'timeout')) {
125 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
127 $curl_time = intval(get_config('system', 'curl_timeout'));
128 @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
131 // by default we will allow self-signed certs
132 // but you can override this
134 $check_cert = get_config('system', 'verifyssl');
135 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
138 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
141 $proxy = get_config('system', 'proxy');
143 if (strlen($proxy)) {
144 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
145 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
146 $proxyuser = @get_config('system', 'proxyuser');
148 if (strlen($proxyuser)) {
149 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
153 if (Config::get('system', 'ipv4_resolve', false)) {
154 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
158 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
161 $a->set_curl_code(0);
163 // don't let curl abort the entire application
164 // if it throws any errors.
166 $s = @curl_exec($ch);
168 if (curl_errno($ch) !== CURLE_OK) {
169 logger('fetch_url error fetching ' . $url . ': ' . curl_error($ch), LOGGER_NORMAL);
172 $ret['errno'] = curl_errno($ch);
175 $curl_info = @curl_getinfo($ch);
177 $http_code = $curl_info['http_code'];
178 logger('fetch_url ' . $url . ': ' . $http_code . " " . $s, LOGGER_DATA);
181 // Pull out multiple headers, e.g. proxy and continuation headers
182 // allow for HTTP/2.x without fixing code
184 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
185 $chunk = substr($base, 0, strpos($base,"\r\n\r\n") + 4);
187 $base = substr($base, strlen($chunk));
190 $a->set_curl_code($http_code);
191 $a->set_curl_content_type($curl_info['content_type']);
192 $a->set_curl_headers($header);
194 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
195 $new_location_info = @parse_url($curl_info['redirect_url']);
196 $old_location_info = @parse_url($curl_info['url']);
198 $newurl = $curl_info['redirect_url'];
200 if (($new_location_info['path'] == '') && ( $new_location_info['host'] != '')) {
201 $newurl = $new_location_info['scheme'] . '://' . $new_location_info['host'] . $old_location_info['path'];
206 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
207 $newurl = trim(array_pop($matches));
209 if (strpos($newurl,'/') === 0) {
210 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
213 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
216 return z_fetch_url($newurl, $binary, $redirects, $opts);
220 $a->set_curl_code($http_code);
221 $a->set_curl_content_type($curl_info['content_type']);
223 $body = substr($s, strlen($header));
225 $rc = intval($http_code);
226 $ret['return_code'] = $rc;
227 $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
228 $ret['redirect_url'] = $url;
230 if (!$ret['success']) {
231 $ret['error'] = curl_error($ch);
232 $ret['debug'] = $curl_info;
233 logger('z_fetch_url: error: '.$url.': '.$ret['return_code'].' - '.$ret['error'], LOGGER_DEBUG);
234 logger('z_fetch_url: debug: '.print_r($curl_info, true), LOGGER_DATA);
237 $ret['body'] = substr($s, strlen($header));
238 $ret['header'] = $header;
240 if (x($opts, 'debug')) {
241 $ret['debug'] = $curl_info;
246 $a->save_timestamp($stamp1, 'network');
252 * @brief Send POST request to $url
254 * @param string $url URL to post
255 * @param mixed $params array of POST variables
256 * @param string $headers HTTP headers
257 * @param integer $redirects Recursion counter for internal use - default = 0
258 * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
260 * @return string The content
262 function post_url($url, $params, $headers = null, &$redirects = 0, $timeout = 0) {
263 $stamp1 = microtime(true);
265 if (blocked_url($url)) {
266 logger('post_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
271 $ch = curl_init($url);
273 if (($redirects > 8) || (!$ch)) {
277 logger('post_url: start ' . $url, LOGGER_DATA);
279 curl_setopt($ch, CURLOPT_HEADER, true);
280 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
281 curl_setopt($ch, CURLOPT_POST, 1);
282 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
283 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
285 if (Config::get('system', 'ipv4_resolve', false)) {
286 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
289 if (intval($timeout)) {
290 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
292 $curl_time = intval(get_config('system', 'curl_timeout'));
293 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
296 if (defined('LIGHTTPD')) {
297 if (!is_array($headers)) {
298 $headers = array('Expect:');
300 if (!in_array('Expect:', $headers)) {
301 array_push($headers, 'Expect:');
307 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
310 $check_cert = get_config('system', 'verifyssl');
311 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
314 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
317 $proxy = get_config('system', 'proxy');
319 if (strlen($proxy)) {
320 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
321 curl_setopt($ch, CURLOPT_PROXY, $proxy);
322 $proxyuser = get_config('system', 'proxyuser');
323 if (strlen($proxyuser)) {
324 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
328 $a->set_curl_code(0);
330 // don't let curl abort the entire application
331 // if it throws any errors.
333 $s = @curl_exec($ch);
336 $curl_info = curl_getinfo($ch);
337 $http_code = $curl_info['http_code'];
339 logger('post_url: result ' . $http_code . ' - ' . $url, LOGGER_DATA);
343 // Pull out multiple headers, e.g. proxy and continuation headers
344 // allow for HTTP/2.x without fixing code
346 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
347 $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
349 $base = substr($base, strlen($chunk));
352 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
354 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
355 $newurl = trim(array_pop($matches));
357 if (strpos($newurl, '/') === 0) {
358 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
361 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
363 logger('post_url: redirect ' . $url . ' to ' . $newurl);
364 return post_url($newurl, $params, $headers, $redirects, $timeout);
368 $a->set_curl_code($http_code);
370 $body = substr($s, strlen($header));
372 $a->set_curl_headers($header);
376 $a->save_timestamp($stamp1, 'network');
378 logger('post_url: end ' . $url, LOGGER_DATA);
383 // Generic XML return
384 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
385 // of $st and an optional text <message> of $message and terminates the current process.
387 function xml_status($st, $message = '') {
389 $result = array('status' => $st);
391 if ($message != '') {
392 $result['message'] = $message;
396 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
399 header("Content-type: text/xml");
401 $xmldata = array("result" => $result);
403 echo xml::from_array($xmldata, $xml);
409 * @brief Send HTTP status header and exit.
411 * @param integer $val HTTP status result value
412 * @param array $description optional message
413 * 'title' => header title
414 * 'description' => optional message
418 * @brief Send HTTP status header and exit.
420 * @param integer $val HTTP status result value
421 * @param array $description optional message
422 * 'title' => header title
423 * 'description' => optional message
425 function http_status_exit($val, $description = array()) {
429 if (!isset($description["title"]))
430 $description["title"] = $err." ".$val;
432 if ($val >= 200 && $val < 300)
435 logger('http_status_exit ' . $val);
436 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
438 if (isset($description["title"])) {
439 $tpl = get_markup_template('http_status.tpl');
440 echo replace_macros($tpl, array('$title' => $description["title"],
441 '$description' => $description["description"]));
449 * @brief Check URL to se if ts's real
451 * Take a URL from the wild, prepend http:// if necessary
452 * and check DNS to see if it's real (or check if is a valid IP address)
454 * @param string $url The URL to be validated
455 * @return boolean True if it's a valid URL, fals if something wrong with it
457 function validate_url(&$url) {
458 if (get_config('system','disable_url_validation'))
461 // no naked subdomains (allow localhost for tests)
462 if (strpos($url,'.') === false && strpos($url,'/localhost/') === false)
465 if (substr($url,0,4) != 'http')
466 $url = 'http://' . $url;
468 /// @TODO Really supress function outcomes? Why not find them + debug them?
469 $h = @parse_url($url);
471 if ((is_array($h)) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
479 * @brief Checks that email is an actual resolvable internet address
481 * @param string $addr The email address
482 * @return boolean True if it's a valid email address, false if it's not
484 function validate_email($addr) {
486 if (get_config('system','disable_email_validation'))
489 if (! strpos($addr,'@'))
491 $h = substr($addr,strpos($addr,'@') + 1);
493 if (($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
500 * @brief Check if URL is allowed
502 * Check $url against our list of allowed sites,
503 * wildcards allowed. If allowed_sites is unset return true;
505 * @param string $url URL which get tested
506 * @return boolean True if url is allowed otherwise return false
508 function allowed_url($url) {
510 $h = @parse_url($url);
516 $str_allowed = Config::get('system', 'allowed_sites');
517 if (! $str_allowed) {
523 $host = strtolower($h['host']);
525 // always allow our own site
526 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
530 $fnmatch = function_exists('fnmatch');
531 $allowed = explode(',', $str_allowed);
533 if (count($allowed)) {
534 foreach ($allowed as $a) {
535 $pat = strtolower(trim($a));
536 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
546 * Checks if the provided url domain is on the domain blocklist.
547 * Returns true if it is or malformed URL, false if not.
549 * @param string $url The url to check the domain from
552 function blocked_url($url) {
553 $h = @parse_url($url);
559 $domain_blocklist = Config::get('system', 'blocklist', array());
560 if (! $domain_blocklist) {
564 $host = strtolower($h['host']);
566 foreach ($domain_blocklist as $domain_block) {
567 if (strtolower($domain_block['domain']) == $host) {
576 * @brief Check if email address is allowed to register here.
578 * Compare against our list (wildcards allowed).
581 * @return boolean False if not allowed, true if allowed
582 * or if allowed list is not configured
584 function allowed_email($email) {
586 $domain = strtolower(substr($email,strpos($email,'@') + 1));
591 $str_allowed = get_config('system','allowed_email');
592 if (! $str_allowed) {
598 $fnmatch = function_exists('fnmatch');
599 $allowed = explode(',',$str_allowed);
601 if (count($allowed)) {
602 foreach ($allowed as $a) {
603 $pat = strtolower(trim($a));
604 if (($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
613 function avatar_img($email) {
615 $avatar['size'] = 175;
616 $avatar['email'] = $email;
618 $avatar['success'] = false;
620 call_hooks('avatar_lookup', $avatar);
622 if (! $avatar['success']) {
623 $avatar['url'] = System::baseUrl() . '/images/person-175.jpg';
626 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
627 return $avatar['url'];
631 function parse_xml_string($s, $strict = true) {
632 // the "strict" parameter is deactivated
634 /// @todo Move this function to the xml class
635 libxml_use_internal_errors(true);
637 $x = @simplexml_load_string($s);
639 logger('libxml: parse: error: ' . $s, LOGGER_DATA);
640 foreach (libxml_get_errors() as $err) {
641 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
643 libxml_clear_errors();
648 function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
650 // Suppress "view full size"
651 if (intval(get_config('system','no_view_full_size'))) {
652 $include_link = false;
657 // Picture addresses can contain special characters
658 $s = htmlspecialchars_decode($srctext);
661 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
663 require_once('include/Photo.php');
664 foreach ($matches as $mtch) {
665 logger('scale_external_image: ' . $mtch[1]);
667 $hostname = str_replace('www.','',substr(System::baseUrl(),strpos(System::baseUrl(),'://')+3));
668 if (stristr($mtch[1],$hostname)) {
672 // $scale_replace, if passed, is an array of two elements. The
673 // first is the name of the full-size image. The second is the
674 // name of a remote, scaled-down version of the full size image.
675 // This allows Friendica to display the smaller remote image if
676 // one exists, while still linking to the full-size image
677 if ($scale_replace) {
678 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
682 $i = fetch_url($scaled);
687 // guess mimetype from headers or filename
688 $type = guess_image_type($mtch[1],true);
691 $ph = new Photo($i, $type);
692 if ($ph->is_valid()) {
693 $orig_width = $ph->getWidth();
694 $orig_height = $ph->getHeight();
696 if ($orig_width > 640 || $orig_height > 640) {
698 $ph->scaleImage(640);
699 $new_width = $ph->getWidth();
700 $new_height = $ph->getHeight();
701 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
702 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
703 . "\n" . (($include_link)
704 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
706 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
713 // replace the special char encoding
714 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
719 function fix_contact_ssl_policy(&$contact,$new_policy) {
721 $ssl_changed = false;
722 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
724 $contact['url'] = str_replace('https:','http:',$contact['url']);
725 $contact['request'] = str_replace('https:','http:',$contact['request']);
726 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
727 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
728 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
729 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
732 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
734 $contact['url'] = str_replace('http:','https:',$contact['url']);
735 $contact['request'] = str_replace('http:','https:',$contact['request']);
736 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
737 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
738 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
739 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
743 dba::update('contact', $contact, array('id' => $contact['id']));
748 * @brief Remove Google Analytics and other tracking platforms params from URL
750 * @param string $url Any user-submitted URL that may contain tracking params
751 * @return string The same URL stripped of tracking parameters
753 function strip_tracking_query_params($url)
755 $urldata = parse_url($url);
756 if (is_string($urldata["query"])) {
757 $query = $urldata["query"];
758 parse_str($query, $querydata);
760 if (is_array($querydata)) {
761 foreach ($querydata AS $param => $value) {
762 if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
763 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
764 "fb_action_ids", "fb_action_types", "fb_ref",
766 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) {
768 $pair = $param . "=" . urlencode($value);
769 $url = str_replace($pair, "", $url);
771 // Second try: if the url isn't encoded completely
772 $pair = $param . "=" . str_replace(" ", "+", $value);
773 $url = str_replace($pair, "", $url);
775 // Third try: Maybey the url isn't encoded at all
776 $pair = $param . "=" . $value;
777 $url = str_replace($pair, "", $url);
779 $url = str_replace(array("?&", "&&"), array("?", ""), $url);
784 if (substr($url, -1, 1) == "?") {
785 $url = substr($url, 0, -1);
793 * @brief Returns the original URL of the provided URL
795 * This function strips tracking query params and follows redirections, either
796 * through HTTP code or meta refresh tags. Stops after 10 redirections.
798 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
800 * @see ParseUrl::getSiteinfo
802 * @param string $url A user-submitted URL
803 * @param int $depth The current redirection recursion level (internal)
804 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
805 * @return string A canonical URL
807 function original_url($url, $depth = 1, $fetchbody = false) {
810 $url = strip_tracking_query_params($url);
815 $url = trim($url, "'");
817 $stamp1 = microtime(true);
821 curl_setopt($ch, CURLOPT_URL, $url);
822 curl_setopt($ch, CURLOPT_HEADER, 1);
823 curl_setopt($ch, CURLOPT_NOBODY, 1);
824 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
825 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
826 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
828 $header = curl_exec($ch);
829 $curl_info = @curl_getinfo($ch);
830 $http_code = $curl_info['http_code'];
833 $a->save_timestamp($stamp1, "network");
838 if ((($curl_info['http_code'] == "301") || ($curl_info['http_code'] == "302"))
839 && (($curl_info['redirect_url'] != "") || ($curl_info['location'] != ""))) {
840 if ($curl_info['redirect_url'] != "")
841 return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
843 return(original_url($curl_info['location'], ++$depth, $fetchbody));
846 // Check for redirects in the meta elements of the body if there are no redirects in the header.
848 return(original_url($url, ++$depth, true));
850 // if the file is too large then exit
851 if ($curl_info["download_content_length"] > 1000000)
854 // if it isn't a HTML file then exit
855 if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]),"html"))
858 $stamp1 = microtime(true);
861 curl_setopt($ch, CURLOPT_URL, $url);
862 curl_setopt($ch, CURLOPT_HEADER, 0);
863 curl_setopt($ch, CURLOPT_NOBODY, 0);
864 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
865 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
866 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
868 $body = curl_exec($ch);
871 $a->save_timestamp($stamp1, "network");
873 if (trim($body) == "")
876 // Check for redirect in meta elements
877 $doc = new DOMDocument();
878 @$doc->loadHTML($body);
880 $xpath = new DomXPath($doc);
882 $list = $xpath->query("//meta[@content]");
883 foreach ($list as $node) {
885 if ($node->attributes->length)
886 foreach ($node->attributes as $attribute)
887 $attr[$attribute->name] = $attribute->value;
889 if (@$attr["http-equiv"] == 'refresh') {
890 $path = $attr["content"];
891 $pathinfo = explode(";", $path);
893 foreach ($pathinfo AS $value)
894 if (substr(strtolower($value), 0, 4) == "url=")
895 return(original_url(substr($value, 4), ++$depth));
902 function short_link($url) {
903 require_once('library/slinky.php');
904 $slinky = new Slinky($url);
905 $yourls_url = get_config('yourls','url1');
907 $yourls_username = get_config('yourls','username1');
908 $yourls_password = get_config('yourls', 'password1');
909 $yourls_ssl = get_config('yourls', 'ssl1');
910 $yourls = new Slinky_YourLS();
911 $yourls->set('username', $yourls_username);
912 $yourls->set('password', $yourls_password);
913 $yourls->set('ssl', $yourls_ssl);
914 $yourls->set('yourls-url', $yourls_url);
915 $slinky->set_cascade(array($yourls, new Slinky_Ur1ca(), new Slinky_TinyURL()));
917 // setup a cascade of shortening services
918 // try to get a short link from these services
919 // in the order ur1.ca, tinyurl
920 $slinky->set_cascade(array(new Slinky_Ur1ca(), new Slinky_TinyURL()));
922 return $slinky->short();
926 * @brief Encodes content to json
928 * This function encodes an array to json format
929 * and adds an application/json HTTP header to the output.
930 * After finishing the process is getting killed.
932 * @param array $x The input content
934 function json_return_and_die($x) {
935 header("content-type: application/json");
936 echo json_encode($x);
941 * @brief Find the matching part between two url
943 * @param string $url1
944 * @param string $url2
945 * @return string The matching part
947 function matching_url($url1, $url2) {
949 if (($url1 == "") || ($url2 == ""))
952 $url1 = normalise_link($url1);
953 $url2 = normalise_link($url2);
955 $parts1 = parse_url($url1);
956 $parts2 = parse_url($url2);
958 if (!isset($parts1["host"]) || !isset($parts2["host"]))
961 if ($parts1["scheme"] != $parts2["scheme"])
964 if ($parts1["host"] != $parts2["host"])
967 if ($parts1["port"] != $parts2["port"])
970 $match = $parts1["scheme"]."://".$parts1["host"];
973 $match .= ":".$parts1["port"];
975 $pathparts1 = explode("/", $parts1["path"]);
976 $pathparts2 = explode("/", $parts2["path"]);
981 $path1 = $pathparts1[$i];
982 $path2 = $pathparts2[$i];
984 if ($path1 == $path2)
987 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
991 return normalise_link($match);