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);
154 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
157 $a->set_curl_code(0);
159 // don't let curl abort the entire application
160 // if it throws any errors.
162 $s = @curl_exec($ch);
164 if (curl_errno($ch) !== CURLE_OK) {
165 logger('fetch_url error fetching ' . $url . ': ' . curl_error($ch), LOGGER_NORMAL);
168 $ret['errno'] = curl_errno($ch);
171 $curl_info = @curl_getinfo($ch);
173 $http_code = $curl_info['http_code'];
174 logger('fetch_url ' . $url . ': ' . $http_code . " " . $s, LOGGER_DATA);
177 // Pull out multiple headers, e.g. proxy and continuation headers
178 // allow for HTTP/2.x without fixing code
180 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
181 $chunk = substr($base, 0, strpos($base,"\r\n\r\n") + 4);
183 $base = substr($base, strlen($chunk));
186 $a->set_curl_code($http_code);
187 $a->set_curl_content_type($curl_info['content_type']);
188 $a->set_curl_headers($header);
190 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
191 $new_location_info = @parse_url($curl_info['redirect_url']);
192 $old_location_info = @parse_url($curl_info['url']);
194 $newurl = $curl_info['redirect_url'];
196 if (($new_location_info['path'] == '') && ( $new_location_info['host'] != '')) {
197 $newurl = $new_location_info['scheme'] . '://' . $new_location_info['host'] . $old_location_info['path'];
202 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
203 $newurl = trim(array_pop($matches));
205 if (strpos($newurl,'/') === 0) {
206 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
209 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
212 return z_fetch_url($newurl, $binary, $redirects, $opts);
216 $a->set_curl_code($http_code);
217 $a->set_curl_content_type($curl_info['content_type']);
219 $body = substr($s, strlen($header));
221 $rc = intval($http_code);
222 $ret['return_code'] = $rc;
223 $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
224 $ret['redirect_url'] = $url;
226 if (!$ret['success']) {
227 $ret['error'] = curl_error($ch);
228 $ret['debug'] = $curl_info;
229 logger('z_fetch_url: error: '.$url.': '.$ret['return_code'].' - '.$ret['error'], LOGGER_DEBUG);
230 logger('z_fetch_url: debug: '.print_r($curl_info, true), LOGGER_DATA);
233 $ret['body'] = substr($s, strlen($header));
234 $ret['header'] = $header;
236 if (x($opts, 'debug')) {
237 $ret['debug'] = $curl_info;
242 $a->save_timestamp($stamp1, 'network');
248 * @brief Send POST request to $url
250 * @param string $url URL to post
251 * @param mixed $params array of POST variables
252 * @param string $headers HTTP headers
253 * @param integer $redirects Recursion counter for internal use - default = 0
254 * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
256 * @return string The content
258 function post_url($url, $params, $headers = null, &$redirects = 0, $timeout = 0) {
259 $stamp1 = microtime(true);
261 if (blocked_url($url)) {
262 logger('post_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
267 $ch = curl_init($url);
269 if (($redirects > 8) || (!$ch)) {
273 logger('post_url: start ' . $url, LOGGER_DATA);
275 curl_setopt($ch, CURLOPT_HEADER, true);
276 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
277 curl_setopt($ch, CURLOPT_POST, 1);
278 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
279 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
281 if (intval($timeout)) {
282 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
284 $curl_time = intval(get_config('system', 'curl_timeout'));
285 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
288 if (defined('LIGHTTPD')) {
289 if (!is_array($headers)) {
290 $headers = array('Expect:');
292 if (!in_array('Expect:', $headers)) {
293 array_push($headers, 'Expect:');
299 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
302 $check_cert = get_config('system', 'verifyssl');
303 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
306 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
309 $proxy = get_config('system', 'proxy');
311 if (strlen($proxy)) {
312 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
313 curl_setopt($ch, CURLOPT_PROXY, $proxy);
314 $proxyuser = get_config('system', 'proxyuser');
315 if (strlen($proxyuser)) {
316 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
320 $a->set_curl_code(0);
322 // don't let curl abort the entire application
323 // if it throws any errors.
325 $s = @curl_exec($ch);
328 $curl_info = curl_getinfo($ch);
329 $http_code = $curl_info['http_code'];
331 logger('post_url: result ' . $http_code . ' - ' . $url, LOGGER_DATA);
335 // Pull out multiple headers, e.g. proxy and continuation headers
336 // allow for HTTP/2.x without fixing code
338 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
339 $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
341 $base = substr($base, strlen($chunk));
344 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
346 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
347 $newurl = trim(array_pop($matches));
349 if (strpos($newurl, '/') === 0) {
350 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
353 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
355 logger('post_url: redirect ' . $url . ' to ' . $newurl);
356 return post_url($newurl, $params, $headers, $redirects, $timeout);
360 $a->set_curl_code($http_code);
362 $body = substr($s, strlen($header));
364 $a->set_curl_headers($header);
368 $a->save_timestamp($stamp1, 'network');
370 logger('post_url: end ' . $url, LOGGER_DATA);
375 // Generic XML return
376 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
377 // of $st and an optional text <message> of $message and terminates the current process.
379 function xml_status($st, $message = '') {
381 $result = array('status' => $st);
383 if ($message != '') {
384 $result['message'] = $message;
388 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
391 header("Content-type: text/xml");
393 $xmldata = array("result" => $result);
395 echo xml::from_array($xmldata, $xml);
401 * @brief Send HTTP status header and exit.
403 * @param integer $val HTTP status result value
404 * @param array $description optional message
405 * 'title' => header title
406 * 'description' => optional message
410 * @brief Send HTTP status header and exit.
412 * @param integer $val HTTP status result value
413 * @param array $description optional message
414 * 'title' => header title
415 * 'description' => optional message
417 function http_status_exit($val, $description = array()) {
421 if (!isset($description["title"]))
422 $description["title"] = $err." ".$val;
424 if ($val >= 200 && $val < 300)
427 logger('http_status_exit ' . $val);
428 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
430 if (isset($description["title"])) {
431 $tpl = get_markup_template('http_status.tpl');
432 echo replace_macros($tpl, array('$title' => $description["title"],
433 '$description' => $description["description"]));
441 * @brief Check URL to se if ts's real
443 * Take a URL from the wild, prepend http:// if necessary
444 * and check DNS to see if it's real (or check if is a valid IP address)
446 * @param string $url The URL to be validated
447 * @return boolean True if it's a valid URL, fals if something wrong with it
449 function validate_url(&$url) {
450 if (get_config('system','disable_url_validation'))
453 // no naked subdomains (allow localhost for tests)
454 if (strpos($url,'.') === false && strpos($url,'/localhost/') === false)
457 if (substr($url,0,4) != 'http')
458 $url = 'http://' . $url;
460 /// @TODO Really supress function outcomes? Why not find them + debug them?
461 $h = @parse_url($url);
463 if ((is_array($h)) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
471 * @brief Checks that email is an actual resolvable internet address
473 * @param string $addr The email address
474 * @return boolean True if it's a valid email address, false if it's not
476 function validate_email($addr) {
478 if (get_config('system','disable_email_validation'))
481 if (! strpos($addr,'@'))
483 $h = substr($addr,strpos($addr,'@') + 1);
485 if (($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
492 * @brief Check if URL is allowed
494 * Check $url against our list of allowed sites,
495 * wildcards allowed. If allowed_sites is unset return true;
497 * @param string $url URL which get tested
498 * @return boolean True if url is allowed otherwise return false
500 function allowed_url($url) {
502 $h = @parse_url($url);
508 $str_allowed = Config::get('system', 'allowed_sites');
509 if (! $str_allowed) {
515 $host = strtolower($h['host']);
517 // always allow our own site
518 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
522 $fnmatch = function_exists('fnmatch');
523 $allowed = explode(',', $str_allowed);
525 if (count($allowed)) {
526 foreach ($allowed as $a) {
527 $pat = strtolower(trim($a));
528 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
538 * Checks if the provided url domain is on the domain blocklist.
539 * Returns true if it is or malformed URL, false if not.
541 * @param string $url The url to check the domain from
544 function blocked_url($url) {
545 $h = @parse_url($url);
551 $domain_blocklist = Config::get('system', 'blocklist', array());
552 if (! $domain_blocklist) {
556 $host = strtolower($h['host']);
558 foreach ($domain_blocklist as $domain_block) {
559 if (strtolower($domain_block['domain']) == $host) {
568 * @brief Check if email address is allowed to register here.
570 * Compare against our list (wildcards allowed).
573 * @return boolean False if not allowed, true if allowed
574 * or if allowed list is not configured
576 function allowed_email($email) {
578 $domain = strtolower(substr($email,strpos($email,'@') + 1));
583 $str_allowed = get_config('system','allowed_email');
584 if (! $str_allowed) {
590 $fnmatch = function_exists('fnmatch');
591 $allowed = explode(',',$str_allowed);
593 if (count($allowed)) {
594 foreach ($allowed as $a) {
595 $pat = strtolower(trim($a));
596 if (($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
605 function avatar_img($email) {
607 $avatar['size'] = 175;
608 $avatar['email'] = $email;
610 $avatar['success'] = false;
612 call_hooks('avatar_lookup', $avatar);
614 if (! $avatar['success']) {
615 $avatar['url'] = System::baseUrl() . '/images/person-175.jpg';
618 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
619 return $avatar['url'];
623 function parse_xml_string($s, $strict = true) {
624 // the "strict" parameter is deactivated
626 /// @todo Move this function to the xml class
627 libxml_use_internal_errors(true);
629 $x = @simplexml_load_string($s);
631 logger('libxml: parse: error: ' . $s, LOGGER_DATA);
632 foreach (libxml_get_errors() as $err) {
633 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
635 libxml_clear_errors();
640 function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
642 // Suppress "view full size"
643 if (intval(get_config('system','no_view_full_size'))) {
644 $include_link = false;
649 // Picture addresses can contain special characters
650 $s = htmlspecialchars_decode($srctext);
653 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
655 require_once('include/Photo.php');
656 foreach ($matches as $mtch) {
657 logger('scale_external_image: ' . $mtch[1]);
659 $hostname = str_replace('www.','',substr(System::baseUrl(),strpos(System::baseUrl(),'://')+3));
660 if (stristr($mtch[1],$hostname)) {
664 // $scale_replace, if passed, is an array of two elements. The
665 // first is the name of the full-size image. The second is the
666 // name of a remote, scaled-down version of the full size image.
667 // This allows Friendica to display the smaller remote image if
668 // one exists, while still linking to the full-size image
669 if ($scale_replace) {
670 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
674 $i = fetch_url($scaled);
679 // guess mimetype from headers or filename
680 $type = guess_image_type($mtch[1],true);
683 $ph = new Photo($i, $type);
684 if ($ph->is_valid()) {
685 $orig_width = $ph->getWidth();
686 $orig_height = $ph->getHeight();
688 if ($orig_width > 640 || $orig_height > 640) {
690 $ph->scaleImage(640);
691 $new_width = $ph->getWidth();
692 $new_height = $ph->getHeight();
693 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
694 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
695 . "\n" . (($include_link)
696 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
698 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
705 // replace the special char encoding
706 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
711 function fix_contact_ssl_policy(&$contact,$new_policy) {
713 $ssl_changed = false;
714 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
716 $contact['url'] = str_replace('https:','http:',$contact['url']);
717 $contact['request'] = str_replace('https:','http:',$contact['request']);
718 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
719 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
720 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
721 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
724 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
726 $contact['url'] = str_replace('http:','https:',$contact['url']);
727 $contact['request'] = str_replace('http:','https:',$contact['request']);
728 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
729 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
730 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
731 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
735 dba::update('contact', $contact, array('id' => $contact['id']));
740 * @brief Remove Google Analytics and other tracking platforms params from URL
742 * @param string $url Any user-submitted URL that may contain tracking params
743 * @return string The same URL stripped of tracking parameters
745 function strip_tracking_query_params($url)
747 $urldata = parse_url($url);
748 if (is_string($urldata["query"])) {
749 $query = $urldata["query"];
750 parse_str($query, $querydata);
752 if (is_array($querydata)) {
753 foreach ($querydata AS $param => $value) {
754 if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
755 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
756 "fb_action_ids", "fb_action_types", "fb_ref",
758 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) {
760 $pair = $param . "=" . urlencode($value);
761 $url = str_replace($pair, "", $url);
763 // Second try: if the url isn't encoded completely
764 $pair = $param . "=" . str_replace(" ", "+", $value);
765 $url = str_replace($pair, "", $url);
767 // Third try: Maybey the url isn't encoded at all
768 $pair = $param . "=" . $value;
769 $url = str_replace($pair, "", $url);
771 $url = str_replace(array("?&", "&&"), array("?", ""), $url);
776 if (substr($url, -1, 1) == "?") {
777 $url = substr($url, 0, -1);
785 * @brief Returns the original URL of the provided URL
787 * This function strips tracking query params and follows redirections, either
788 * through HTTP code or meta refresh tags. Stops after 10 redirections.
790 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
792 * @see ParseUrl::getSiteinfo
794 * @param string $url A user-submitted URL
795 * @param int $depth The current redirection recursion level (internal)
796 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
797 * @return string A canonical URL
799 function original_url($url, $depth = 1, $fetchbody = false) {
802 $url = strip_tracking_query_params($url);
807 $url = trim($url, "'");
809 $stamp1 = microtime(true);
813 curl_setopt($ch, CURLOPT_URL, $url);
814 curl_setopt($ch, CURLOPT_HEADER, 1);
815 curl_setopt($ch, CURLOPT_NOBODY, 1);
816 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
817 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
818 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
820 $header = curl_exec($ch);
821 $curl_info = @curl_getinfo($ch);
822 $http_code = $curl_info['http_code'];
825 $a->save_timestamp($stamp1, "network");
830 if ((($curl_info['http_code'] == "301") || ($curl_info['http_code'] == "302"))
831 && (($curl_info['redirect_url'] != "") || ($curl_info['location'] != ""))) {
832 if ($curl_info['redirect_url'] != "")
833 return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
835 return(original_url($curl_info['location'], ++$depth, $fetchbody));
838 // Check for redirects in the meta elements of the body if there are no redirects in the header.
840 return(original_url($url, ++$depth, true));
842 // if the file is too large then exit
843 if ($curl_info["download_content_length"] > 1000000)
846 // if it isn't a HTML file then exit
847 if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]),"html"))
850 $stamp1 = microtime(true);
853 curl_setopt($ch, CURLOPT_URL, $url);
854 curl_setopt($ch, CURLOPT_HEADER, 0);
855 curl_setopt($ch, CURLOPT_NOBODY, 0);
856 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
857 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
858 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
860 $body = curl_exec($ch);
863 $a->save_timestamp($stamp1, "network");
865 if (trim($body) == "")
868 // Check for redirect in meta elements
869 $doc = new DOMDocument();
870 @$doc->loadHTML($body);
872 $xpath = new DomXPath($doc);
874 $list = $xpath->query("//meta[@content]");
875 foreach ($list as $node) {
877 if ($node->attributes->length)
878 foreach ($node->attributes as $attribute)
879 $attr[$attribute->name] = $attribute->value;
881 if (@$attr["http-equiv"] == 'refresh') {
882 $path = $attr["content"];
883 $pathinfo = explode(";", $path);
885 foreach ($pathinfo AS $value)
886 if (substr(strtolower($value), 0, 4) == "url=")
887 return(original_url(substr($value, 4), ++$depth));
894 function short_link($url) {
895 require_once('library/slinky.php');
896 $slinky = new Slinky($url);
897 $yourls_url = get_config('yourls','url1');
899 $yourls_username = get_config('yourls','username1');
900 $yourls_password = get_config('yourls', 'password1');
901 $yourls_ssl = get_config('yourls', 'ssl1');
902 $yourls = new Slinky_YourLS();
903 $yourls->set('username', $yourls_username);
904 $yourls->set('password', $yourls_password);
905 $yourls->set('ssl', $yourls_ssl);
906 $yourls->set('yourls-url', $yourls_url);
907 $slinky->set_cascade(array($yourls, new Slinky_Ur1ca(), new Slinky_TinyURL()));
909 // setup a cascade of shortening services
910 // try to get a short link from these services
911 // in the order ur1.ca, tinyurl
912 $slinky->set_cascade(array(new Slinky_Ur1ca(), new Slinky_TinyURL()));
914 return $slinky->short();
918 * @brief Encodes content to json
920 * This function encodes an array to json format
921 * and adds an application/json HTTP header to the output.
922 * After finishing the process is getting killed.
924 * @param array $x The input content
926 function json_return_and_die($x) {
927 header("content-type: application/json");
928 echo json_encode($x);
933 * @brief Find the matching part between two url
935 * @param string $url1
936 * @param string $url2
937 * @return string The matching part
939 function matching_url($url1, $url2) {
941 if (($url1 == "") || ($url2 == ""))
944 $url1 = normalise_link($url1);
945 $url2 = normalise_link($url2);
947 $parts1 = parse_url($url1);
948 $parts2 = parse_url($url2);
950 if (!isset($parts1["host"]) || !isset($parts2["host"]))
953 if ($parts1["scheme"] != $parts2["scheme"])
956 if ($parts1["host"] != $parts2["host"])
959 if ($parts1["port"] != $parts2["port"])
962 $match = $parts1["scheme"]."://".$parts1["host"];
965 $match .= ":".$parts1["port"];
967 $pathparts1 = explode("/", $parts1["path"]);
968 $pathparts2 = explode("/", $parts2["path"]);
973 $path1 = $pathparts1[$i];
974 $path2 = $pathparts2[$i];
976 if ($path1 == $path2)
979 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
983 return normalise_link($match);