4 * @file include/network.php
8 use Friendica\Core\Config;
9 use Friendica\Network\Probe;
11 require_once("include/xml.php");
16 * If binary flag is true, return binary results.
17 * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
18 * to preserve cookies from one request to the next.
20 * @param string $url URL to fetch
21 * @param boolean $binary default false
22 * TRUE if asked to return binary results (file download)
23 * @param integer $redirects The recursion counter for internal use - default 0
24 * @param integer $timeout Timeout in seconds, default system config value or 60 seconds
25 * @param string $accept_content supply Accept: header with 'accept_content' as the value
26 * @param string $cookiejar Path to cookie jar file
28 * @return string The fetched content
30 function fetch_url($url,$binary = false, &$redirects = 0, $timeout = 0, $accept_content=Null, $cookiejar = 0) {
36 array('timeout'=>$timeout,
37 'accept_content'=>$accept_content,
38 'cookiejar'=>$cookiejar
45 * @brief fetches an URL.
47 * @param string $url URL to fetch
48 * @param boolean $binary default false
49 * TRUE if asked to return binary results (file download)
50 * @param int $redirects The recursion counter for internal use - default 0
51 * @param array $opts (optional parameters) assoziative array with:
52 * 'accept_content' => supply Accept: header with 'accept_content' as the value
53 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
54 * 'http_auth' => username:password
55 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
56 * 'nobody' => only return the header
57 * 'cookiejar' => path to cookie jar file
59 * @return array an assoziative array with:
60 * int 'return_code' => HTTP return code or 0 if timeout or failure
61 * boolean 'success' => boolean true (if HTTP 2xx result) or false
62 * string 'redirect_url' => in case of redirect, content was finally retrieved from this URL
63 * string 'header' => HTTP headers
64 * string 'body' => fetched content
66 function z_fetch_url($url, $binary = false, &$redirects = 0, $opts = array()) {
67 $ret = array('return_code' => 0, 'success' => false, 'header' => '', 'body' => '');
69 $stamp1 = microtime(true);
73 if (blocked_url($url)) {
74 logger('z_fetch_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
78 $ch = @curl_init($url);
80 if (($redirects > 8) || (!$ch)) {
84 @curl_setopt($ch, CURLOPT_HEADER, true);
86 if (x($opts, "cookiejar")) {
87 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
88 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
91 // These settings aren't needed. We're following the location already.
92 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
93 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
95 if (x($opts, 'accept_content')) {
96 curl_setopt($ch, CURLOPT_HTTPHEADER, array(
97 'Accept: ' . $opts['accept_content']
101 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
102 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
104 $range = intval(Config::get('system', 'curl_range_bytes', 0));
107 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
110 if (x($opts, 'headers')) {
111 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
114 if (x($opts, 'nobody')) {
115 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
118 if (x($opts, 'timeout')) {
119 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
121 $curl_time = intval(get_config('system', 'curl_timeout'));
122 @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
125 // by default we will allow self-signed certs
126 // but you can override this
128 $check_cert = get_config('system', 'verifyssl');
129 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
132 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
135 $proxy = get_config('system', 'proxy');
137 if (strlen($proxy)) {
138 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
139 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
140 $proxyuser = @get_config('system', 'proxyuser');
142 if (strlen($proxyuser)) {
143 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
148 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
151 $a->set_curl_code(0);
153 // don't let curl abort the entire application
154 // if it throws any errors.
156 $s = @curl_exec($ch);
158 if (curl_errno($ch) !== CURLE_OK) {
159 logger('fetch_url error fetching ' . $url . ': ' . curl_error($ch), LOGGER_NORMAL);
162 $ret['errno'] = curl_errno($ch);
165 $curl_info = @curl_getinfo($ch);
167 $http_code = $curl_info['http_code'];
168 logger('fetch_url ' . $url . ': ' . $http_code . " " . $s, LOGGER_DATA);
171 // Pull out multiple headers, e.g. proxy and continuation headers
172 // allow for HTTP/2.x without fixing code
174 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
175 $chunk = substr($base, 0, strpos($base,"\r\n\r\n") + 4);
177 $base = substr($base, strlen($chunk));
180 $a->set_curl_code($http_code);
181 $a->set_curl_content_type($curl_info['content_type']);
182 $a->set_curl_headers($header);
184 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
185 $new_location_info = @parse_url($curl_info['redirect_url']);
186 $old_location_info = @parse_url($curl_info['url']);
188 $newurl = $curl_info['redirect_url'];
190 if (($new_location_info['path'] == '') AND ( $new_location_info['host'] != '')) {
191 $newurl = $new_location_info['scheme'] . '://' . $new_location_info['host'] . $old_location_info['path'];
196 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
197 $newurl = trim(array_pop($matches));
199 if (strpos($newurl,'/') === 0) {
200 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
203 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
206 return z_fetch_url($newurl, $binary, $redirects, $opts);
210 $a->set_curl_code($http_code);
211 $a->set_curl_content_type($curl_info['content_type']);
213 $body = substr($s, strlen($header));
215 $rc = intval($http_code);
216 $ret['return_code'] = $rc;
217 $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
218 $ret['redirect_url'] = $url;
220 if (!$ret['success']) {
221 $ret['error'] = curl_error($ch);
222 $ret['debug'] = $curl_info;
223 logger('z_fetch_url: error: ' . $url . ': ' . $ret['error'], LOGGER_DEBUG);
224 logger('z_fetch_url: debug: ' . print_r($curl_info, true), LOGGER_DATA);
227 $ret['body'] = substr($s, strlen($header));
228 $ret['header'] = $header;
230 if (x($opts, 'debug')) {
231 $ret['debug'] = $curl_info;
236 $a->save_timestamp($stamp1, 'network');
242 * @brief Send POST request to $url
244 * @param string $url URL to post
245 * @param mixed $params array of POST variables
246 * @param string $headers HTTP headers
247 * @param integer $redirects Recursion counter for internal use - default = 0
248 * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
250 * @return string The content
252 function post_url($url, $params, $headers = null, &$redirects = 0, $timeout = 0) {
253 $stamp1 = microtime(true);
255 if (blocked_url($url)) {
256 logger('post_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
261 $ch = curl_init($url);
263 if (($redirects > 8) || (!$ch)) {
267 logger('post_url: start ' . $url, LOGGER_DATA);
269 curl_setopt($ch, CURLOPT_HEADER, true);
270 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
271 curl_setopt($ch, CURLOPT_POST, 1);
272 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
273 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
275 if (intval($timeout)) {
276 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
278 $curl_time = intval(get_config('system', 'curl_timeout'));
279 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
282 if (defined('LIGHTTPD')) {
283 if (!is_array($headers)) {
284 $headers = array('Expect:');
286 if (!in_array('Expect:', $headers)) {
287 array_push($headers, 'Expect:');
293 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
296 $check_cert = get_config('system', 'verifyssl');
297 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
300 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
303 $proxy = get_config('system', 'proxy');
305 if (strlen($proxy)) {
306 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
307 curl_setopt($ch, CURLOPT_PROXY, $proxy);
308 $proxyuser = get_config('system', 'proxyuser');
309 if (strlen($proxyuser)) {
310 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
314 $a->set_curl_code(0);
316 // don't let curl abort the entire application
317 // if it throws any errors.
319 $s = @curl_exec($ch);
322 $curl_info = curl_getinfo($ch);
323 $http_code = $curl_info['http_code'];
325 logger('post_url: result ' . $http_code . ' - ' . $url, LOGGER_DATA);
329 // Pull out multiple headers, e.g. proxy and continuation headers
330 // allow for HTTP/2.x without fixing code
332 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
333 $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
335 $base = substr($base, strlen($chunk));
338 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
340 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
341 $newurl = trim(array_pop($matches));
343 if (strpos($newurl, '/') === 0) {
344 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
347 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
349 logger('post_url: redirect ' . $url . ' to ' . $newurl);
350 return post_url($newurl, $params, $headers, $redirects, $timeout);
354 $a->set_curl_code($http_code);
356 $body = substr($s, strlen($header));
358 $a->set_curl_headers($header);
362 $a->save_timestamp($stamp1, 'network');
364 logger('post_url: end ' . $url, LOGGER_DATA);
369 // Generic XML return
370 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
371 // of $st and an optional text <message> of $message and terminates the current process.
373 function xml_status($st, $message = '') {
375 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
378 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
380 header( "Content-type: text/xml" );
381 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
382 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
387 * @brief Send HTTP status header and exit.
389 * @param integer $val HTTP status result value
390 * @param array $description optional message
391 * 'title' => header title
392 * 'description' => optional message
396 * @brief Send HTTP status header and exit.
398 * @param integer $val HTTP status result value
399 * @param array $description optional message
400 * 'title' => header title
401 * 'description' => optional message
403 function http_status_exit($val, $description = array()) {
407 if (!isset($description["title"]))
408 $description["title"] = $err." ".$val;
410 if ($val >= 200 && $val < 300)
413 logger('http_status_exit ' . $val);
414 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
416 if (isset($description["title"])) {
417 $tpl = get_markup_template('http_status.tpl');
418 echo replace_macros($tpl, array('$title' => $description["title"],
419 '$description' => $description["description"]));
427 * @brief Check URL to se if ts's real
429 * Take a URL from the wild, prepend http:// if necessary
430 * and check DNS to see if it's real (or check if is a valid IP address)
432 * @param string $url The URL to be validated
433 * @return boolean True if it's a valid URL, fals if something wrong with it
435 function validate_url(&$url) {
436 if (get_config('system','disable_url_validation'))
439 // no naked subdomains (allow localhost for tests)
440 if (strpos($url,'.') === false && strpos($url,'/localhost/') === false)
443 if (substr($url,0,4) != 'http')
444 $url = 'http://' . $url;
446 /// @TODO Really supress function outcomes? Why not find them + debug them?
447 $h = @parse_url($url);
449 if ((is_array($h)) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
457 * @brief Checks that email is an actual resolvable internet address
459 * @param string $addr The email address
460 * @return boolean True if it's a valid email address, false if it's not
462 function validate_email($addr) {
464 if (get_config('system','disable_email_validation'))
467 if (! strpos($addr,'@'))
469 $h = substr($addr,strpos($addr,'@') + 1);
471 if (($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
478 * @brief Check if URL is allowed
480 * Check $url against our list of allowed sites,
481 * wildcards allowed. If allowed_sites is unset return true;
483 * @param string $url URL which get tested
484 * @return boolean True if url is allowed otherwise return false
486 function allowed_url($url) {
488 $h = @parse_url($url);
494 $str_allowed = Config::get('system', 'allowed_sites');
495 if (! $str_allowed) {
501 $host = strtolower($h['host']);
503 // always allow our own site
504 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
508 $fnmatch = function_exists('fnmatch');
509 $allowed = explode(',', $str_allowed);
511 if (count($allowed)) {
512 foreach ($allowed as $a) {
513 $pat = strtolower(trim($a));
514 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
524 * Checks if the provided url domain is on the domain blocklist.
525 * Returns true if it is or malformed URL, false if not.
527 * @param string $url The url to check the domain from
530 function blocked_url($url) {
531 $h = @parse_url($url);
537 $domain_blocklist = Config::get('system', 'blocklist', array());
538 if (! $domain_blocklist) {
542 $host = strtolower($h['host']);
544 foreach ($domain_blocklist as $domain_block) {
545 if (strtolower($domain_block['domain']) == $host) {
554 * @brief Check if email address is allowed to register here.
556 * Compare against our list (wildcards allowed).
559 * @return boolean False if not allowed, true if allowed
560 * or if allowed list is not configured
562 function allowed_email($email) {
564 $domain = strtolower(substr($email,strpos($email,'@') + 1));
569 $str_allowed = get_config('system','allowed_email');
570 if (! $str_allowed) {
576 $fnmatch = function_exists('fnmatch');
577 $allowed = explode(',',$str_allowed);
579 if (count($allowed)) {
580 foreach ($allowed as $a) {
581 $pat = strtolower(trim($a));
582 if (($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
591 function avatar_img($email) {
593 $avatar['size'] = 175;
594 $avatar['email'] = $email;
596 $avatar['success'] = false;
598 call_hooks('avatar_lookup', $avatar);
600 if (! $avatar['success']) {
601 $avatar['url'] = App::get_baseurl() . '/images/person-175.jpg';
604 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
605 return $avatar['url'];
609 function parse_xml_string($s,$strict = true) {
610 /// @todo Move this function to the xml class
612 if (! strstr($s,'<?xml'))
614 $s2 = substr($s,strpos($s,'<?xml'));
618 libxml_use_internal_errors(true);
620 $x = @simplexml_load_string($s2);
622 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
623 foreach (libxml_get_errors() as $err) {
624 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
626 libxml_clear_errors();
631 function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
633 // Suppress "view full size"
634 if (intval(get_config('system','no_view_full_size'))) {
635 $include_link = false;
640 // Picture addresses can contain special characters
641 $s = htmlspecialchars_decode($srctext);
644 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
646 require_once('include/Photo.php');
647 foreach ($matches as $mtch) {
648 logger('scale_external_image: ' . $mtch[1]);
650 $hostname = str_replace('www.','',substr(App::get_baseurl(),strpos(App::get_baseurl(),'://')+3));
651 if (stristr($mtch[1],$hostname)) {
655 // $scale_replace, if passed, is an array of two elements. The
656 // first is the name of the full-size image. The second is the
657 // name of a remote, scaled-down version of the full size image.
658 // This allows Friendica to display the smaller remote image if
659 // one exists, while still linking to the full-size image
660 if ($scale_replace) {
661 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
665 $i = fetch_url($scaled);
670 // guess mimetype from headers or filename
671 $type = guess_image_type($mtch[1],true);
674 $ph = new Photo($i, $type);
675 if ($ph->is_valid()) {
676 $orig_width = $ph->getWidth();
677 $orig_height = $ph->getHeight();
679 if ($orig_width > 640 || $orig_height > 640) {
681 $ph->scaleImage(640);
682 $new_width = $ph->getWidth();
683 $new_height = $ph->getHeight();
684 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
685 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
686 . "\n" . (($include_link)
687 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
689 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
696 // replace the special char encoding
697 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
702 function fix_contact_ssl_policy(&$contact,$new_policy) {
704 $ssl_changed = false;
705 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
707 $contact['url'] = str_replace('https:','http:',$contact['url']);
708 $contact['request'] = str_replace('https:','http:',$contact['request']);
709 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
710 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
711 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
712 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
715 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
717 $contact['url'] = str_replace('http:','https:',$contact['url']);
718 $contact['request'] = str_replace('http:','https:',$contact['request']);
719 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
720 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
721 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
722 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
726 dba::update('contact', $contact, array('id' => $contact['id']));
731 * @brief Remove Google Analytics and other tracking platforms params from URL
733 * @param string $url Any user-submitted URL that may contain tracking params
734 * @return string The same URL stripped of tracking parameters
736 function strip_tracking_query_params($url)
738 $urldata = parse_url($url);
739 if (is_string($urldata["query"])) {
740 $query = $urldata["query"];
741 parse_str($query, $querydata);
743 if (is_array($querydata)) {
744 foreach ($querydata AS $param => $value) {
745 if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
746 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
747 "fb_action_ids", "fb_action_types", "fb_ref",
749 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) {
751 $pair = $param . "=" . urlencode($value);
752 $url = str_replace($pair, "", $url);
754 // Second try: if the url isn't encoded completely
755 $pair = $param . "=" . str_replace(" ", "+", $value);
756 $url = str_replace($pair, "", $url);
758 // Third try: Maybey the url isn't encoded at all
759 $pair = $param . "=" . $value;
760 $url = str_replace($pair, "", $url);
762 $url = str_replace(array("?&", "&&"), array("?", ""), $url);
767 if (substr($url, -1, 1) == "?") {
768 $url = substr($url, 0, -1);
776 * @brief Returns the original URL of the provided URL
778 * This function strips tracking query params and follows redirections, either
779 * through HTTP code or meta refresh tags. Stops after 10 redirections.
781 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
783 * @see ParseUrl::getSiteinfo
785 * @param string $url A user-submitted URL
786 * @param int $depth The current redirection recursion level (internal)
787 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
788 * @return string A canonical URL
790 function original_url($url, $depth = 1, $fetchbody = false) {
793 $url = strip_tracking_query_params($url);
798 $url = trim($url, "'");
800 $stamp1 = microtime(true);
804 curl_setopt($ch, CURLOPT_URL, $url);
805 curl_setopt($ch, CURLOPT_HEADER, 1);
806 curl_setopt($ch, CURLOPT_NOBODY, 1);
807 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
808 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
809 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
811 $header = curl_exec($ch);
812 $curl_info = @curl_getinfo($ch);
813 $http_code = $curl_info['http_code'];
816 $a->save_timestamp($stamp1, "network");
821 if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
822 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
823 if ($curl_info['redirect_url'] != "")
824 return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
826 return(original_url($curl_info['location'], ++$depth, $fetchbody));
829 // Check for redirects in the meta elements of the body if there are no redirects in the header.
831 return(original_url($url, ++$depth, true));
833 // if the file is too large then exit
834 if ($curl_info["download_content_length"] > 1000000)
837 // if it isn't a HTML file then exit
838 if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
841 $stamp1 = microtime(true);
844 curl_setopt($ch, CURLOPT_URL, $url);
845 curl_setopt($ch, CURLOPT_HEADER, 0);
846 curl_setopt($ch, CURLOPT_NOBODY, 0);
847 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
848 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
849 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
851 $body = curl_exec($ch);
854 $a->save_timestamp($stamp1, "network");
856 if (trim($body) == "")
859 // Check for redirect in meta elements
860 $doc = new DOMDocument();
861 @$doc->loadHTML($body);
863 $xpath = new DomXPath($doc);
865 $list = $xpath->query("//meta[@content]");
866 foreach ($list as $node) {
868 if ($node->attributes->length)
869 foreach ($node->attributes as $attribute)
870 $attr[$attribute->name] = $attribute->value;
872 if (@$attr["http-equiv"] == 'refresh') {
873 $path = $attr["content"];
874 $pathinfo = explode(";", $path);
876 foreach ($pathinfo AS $value)
877 if (substr(strtolower($value), 0, 4) == "url=")
878 return(original_url(substr($value, 4), ++$depth));
885 function short_link($url) {
886 require_once('library/slinky.php');
887 $slinky = new Slinky($url);
888 $yourls_url = get_config('yourls','url1');
890 $yourls_username = get_config('yourls','username1');
891 $yourls_password = get_config('yourls', 'password1');
892 $yourls_ssl = get_config('yourls', 'ssl1');
893 $yourls = new Slinky_YourLS();
894 $yourls->set('username', $yourls_username);
895 $yourls->set('password', $yourls_password);
896 $yourls->set('ssl', $yourls_ssl);
897 $yourls->set('yourls-url', $yourls_url);
898 $slinky->set_cascade(array($yourls, new Slinky_Ur1ca(), new Slinky_TinyURL()));
900 // setup a cascade of shortening services
901 // try to get a short link from these services
902 // in the order ur1.ca, tinyurl
903 $slinky->set_cascade(array(new Slinky_Ur1ca(), new Slinky_TinyURL()));
905 return $slinky->short();
909 * @brief Encodes content to json
911 * This function encodes an array to json format
912 * and adds an application/json HTTP header to the output.
913 * After finishing the process is getting killed.
915 * @param array $x The input content
917 function json_return_and_die($x) {
918 header("content-type: application/json");
919 echo json_encode($x);
924 * @brief Find the matching part between two url
926 * @param string $url1
927 * @param string $url2
928 * @return string The matching part
930 function matching_url($url1, $url2) {
932 if (($url1 == "") OR ($url2 == ""))
935 $url1 = normalise_link($url1);
936 $url2 = normalise_link($url2);
938 $parts1 = parse_url($url1);
939 $parts2 = parse_url($url2);
941 if (!isset($parts1["host"]) OR !isset($parts2["host"]))
944 if ($parts1["scheme"] != $parts2["scheme"])
947 if ($parts1["host"] != $parts2["host"])
950 if ($parts1["port"] != $parts2["port"])
953 $match = $parts1["scheme"]."://".$parts1["host"];
956 $match .= ":".$parts1["port"];
958 $pathparts1 = explode("/", $parts1["path"]);
959 $pathparts2 = explode("/", $parts2["path"]);
964 $path1 = $pathparts1[$i];
965 $path2 = $pathparts2[$i];
967 if ($path1 == $path2)
970 } while (($path1 == $path2) AND ($i++ <= count($pathparts1)));
974 return normalise_link($match);