4 * @file include/network.php
7 require_once("include/xml.php");
8 require_once('include/Probe.php');
13 * If binary flag is true, return binary results.
14 * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
15 * to preserve cookies from one request to the next.
17 * @param string $url URL to fetch
18 * @param boolean $binary default false
19 * TRUE if asked to return binary results (file download)
20 * @param integer $redirects The recursion counter for internal use - default 0
21 * @param integer $timeout Timeout in seconds, default system config value or 60 seconds
22 * @param string $accept_content supply Accept: header with 'accept_content' as the value
23 * @param string $cookiejar Path to cookie jar file
25 * @return string The fetched content
27 function fetch_url($url,$binary = false, &$redirects = 0, $timeout = 0, $accept_content=Null, $cookiejar = 0) {
33 array('timeout'=>$timeout,
34 'accept_content'=>$accept_content,
35 'cookiejar'=>$cookiejar
42 * @brief fetches an URL.
44 * @param string $url URL to fetch
45 * @param boolean $binary default false
46 * TRUE if asked to return binary results (file download)
47 * @param int $redirects The recursion counter for internal use - default 0
48 * @param array $opts (optional parameters) assoziative array with:
49 * 'accept_content' => supply Accept: header with 'accept_content' as the value
50 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
51 * 'http_auth' => username:password
52 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
53 * 'nobody' => only return the header
54 * 'cookiejar' => path to cookie jar file
56 * @return array an assoziative array with:
57 * int 'return_code' => HTTP return code or 0 if timeout or failure
58 * boolean 'success' => boolean true (if HTTP 2xx result) or false
59 * string 'redirect_url' => in case of redirect, content was finally retrieved from this URL
60 * string 'header' => HTTP headers
61 * string 'body' => fetched content
63 function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
65 $ret = array('return_code' => 0, 'success' => false, 'header' => "", 'body' => "");
68 $stamp1 = microtime(true);
72 $ch = @curl_init($url);
73 if(($redirects > 8) || (! $ch))
76 @curl_setopt($ch, CURLOPT_HEADER, true);
78 if(x($opts,"cookiejar")) {
79 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
80 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
83 // These settings aren't needed. We're following the location already.
84 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
85 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
87 if (x($opts,'accept_content')){
88 curl_setopt($ch,CURLOPT_HTTPHEADER, array (
89 "Accept: " . $opts['accept_content']
93 @curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
94 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
98 if(x($opts,'headers')){
99 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
101 if(x($opts,'nobody')){
102 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
104 if(x($opts,'timeout')){
105 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
107 $curl_time = intval(get_config('system','curl_timeout'));
108 @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
111 // by default we will allow self-signed certs
112 // but you can override this
114 $check_cert = get_config('system','verifyssl');
115 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
116 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
118 $prx = get_config('system','proxy');
120 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
121 @curl_setopt($ch, CURLOPT_PROXY, $prx);
122 $prxusr = @get_config('system','proxyuser');
124 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
127 @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
129 $a->set_curl_code(0);
131 // don't let curl abort the entire application
132 // if it throws any errors.
134 $s = @curl_exec($ch);
135 if (curl_errno($ch) !== CURLE_OK) {
136 logger('fetch_url error fetching '.$url.': '.curl_error($ch), LOGGER_NORMAL);
140 $curl_info = @curl_getinfo($ch);
142 $http_code = $curl_info['http_code'];
143 logger('fetch_url '.$url.': '.$http_code." ".$s, LOGGER_DATA);
146 // Pull out multiple headers, e.g. proxy and continuation headers
147 // allow for HTTP/2.x without fixing code
149 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
150 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
152 $base = substr($base,strlen($chunk));
155 $a->set_curl_code($http_code);
156 $a->set_curl_content_type($curl_info['content_type']);
157 $a->set_curl_headers($header);
159 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
160 $new_location_info = @parse_url($curl_info["redirect_url"]);
161 $old_location_info = @parse_url($curl_info["url"]);
163 $newurl = $curl_info["redirect_url"];
165 if (($new_location_info["path"] == "") AND ($new_location_info["host"] != ""))
166 $newurl = $new_location_info["scheme"]."://".$new_location_info["host"].$old_location_info["path"];
169 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
170 $newurl = trim(array_pop($matches));
172 if(strpos($newurl,'/') === 0)
173 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
174 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
177 return z_fetch_url($newurl,$binary, $redirects, $opts);
182 $a->set_curl_code($http_code);
183 $a->set_curl_content_type($curl_info['content_type']);
185 $body = substr($s,strlen($header));
189 $rc = intval($http_code);
190 $ret['return_code'] = $rc;
191 $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
192 $ret['redirect_url'] = $url;
193 if(! $ret['success']) {
194 $ret['error'] = curl_error($ch);
195 $ret['debug'] = $curl_info;
196 logger('z_fetch_url: error: ' . $url . ': ' . $ret['error'], LOGGER_DEBUG);
197 logger('z_fetch_url: debug: ' . print_r($curl_info,true), LOGGER_DATA);
199 $ret['body'] = substr($s,strlen($header));
200 $ret['header'] = $header;
201 if(x($opts,'debug')) {
202 $ret['debug'] = $curl_info;
206 $a->save_timestamp($stamp1, "network");
212 // post request to $url. $params is an array of post variables.
215 * @brief Post request to $url
217 * @param string $url URL to post
218 * @param mixed $params
219 * @param string $headers HTTP headers
220 * @param integer $redirects Recursion counter for internal use - default = 0
221 * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
223 * @return string The content
225 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
226 $stamp1 = microtime(true);
229 $ch = curl_init($url);
230 if(($redirects > 8) || (! $ch))
233 logger("post_url: start ".$url, LOGGER_DATA);
235 curl_setopt($ch, CURLOPT_HEADER, true);
236 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
237 curl_setopt($ch, CURLOPT_POST,1);
238 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
239 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
241 if(intval($timeout)) {
242 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
245 $curl_time = intval(get_config('system','curl_timeout'));
246 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
249 if(defined('LIGHTTPD')) {
250 if(!is_array($headers)) {
251 $headers = array('Expect:');
253 if(!in_array('Expect:', $headers)) {
254 array_push($headers, 'Expect:');
259 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
261 $check_cert = get_config('system','verifyssl');
262 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
263 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
264 $prx = get_config('system','proxy');
266 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
267 curl_setopt($ch, CURLOPT_PROXY, $prx);
268 $prxusr = get_config('system','proxyuser');
270 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
273 $a->set_curl_code(0);
275 // don't let curl abort the entire application
276 // if it throws any errors.
278 $s = @curl_exec($ch);
281 $curl_info = curl_getinfo($ch);
282 $http_code = $curl_info['http_code'];
284 logger("post_url: result ".$http_code." - ".$url, LOGGER_DATA);
288 // Pull out multiple headers, e.g. proxy and continuation headers
289 // allow for HTTP/2.x without fixing code
291 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
292 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
294 $base = substr($base,strlen($chunk));
297 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
299 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
300 $newurl = trim(array_pop($matches));
301 if(strpos($newurl,'/') === 0)
302 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
303 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
305 logger("post_url: redirect ".$url." to ".$newurl);
306 return post_url($newurl,$params, $headers, $redirects, $timeout);
307 //return fetch_url($newurl,false,$redirects,$timeout);
310 $a->set_curl_code($http_code);
311 $body = substr($s,strlen($header));
313 $a->set_curl_headers($header);
317 $a->save_timestamp($stamp1, "network");
319 logger("post_url: end ".$url, LOGGER_DATA);
324 // Generic XML return
325 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
326 // of $st and an optional text <message> of $message and terminates the current process.
328 function xml_status($st, $message = '') {
330 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
333 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
335 header( "Content-type: text/xml" );
336 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
337 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
342 * @brief Send HTTP status header and exit.
344 * @param integer $val HTTP status result value
345 * @param array $description optional message
346 * 'title' => header title
347 * 'description' => optional message
351 * @brief Send HTTP status header and exit.
353 * @param integer $val HTTP status result value
354 * @param array $description optional message
355 * 'title' => header title
356 * 'description' => optional message
358 function http_status_exit($val, $description = array()) {
362 if (!isset($description["title"]))
363 $description["title"] = $err." ".$val;
365 if($val >= 200 && $val < 300)
368 logger('http_status_exit ' . $val);
369 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
371 if (isset($description["title"])) {
372 $tpl = get_markup_template('http_status.tpl');
373 echo replace_macros($tpl, array('$title' => $description["title"],
374 '$description' => $description["description"]));
382 * @brief Check URL to se if ts's real
384 * Take a URL from the wild, prepend http:// if necessary
385 * and check DNS to see if it's real (or check if is a valid IP address)
387 * @param string $url The URL to be validated
388 * @return boolean True if it's a valid URL, fals if something wrong with it
390 function validate_url(&$url) {
391 if(get_config('system','disable_url_validation'))
394 // no naked subdomains (allow localhost for tests)
395 if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
398 if(substr($url,0,4) != 'http')
399 $url = 'http://' . $url;
401 /// @TODO Really supress function outcomes? Why not find them + debug them?
402 $h = @parse_url($url);
404 if((is_array($h)) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
412 * @brief Checks that email is an actual resolvable internet address
414 * @param string $addr The email address
415 * @return boolean True if it's a valid email address, false if it's not
417 function validate_email($addr) {
419 if(get_config('system','disable_email_validation'))
422 if(! strpos($addr,'@'))
424 $h = substr($addr,strpos($addr,'@') + 1);
426 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
433 * @brief Check if URL is allowed
435 * Check $url against our list of allowed sites,
436 * wildcards allowed. If allowed_sites is unset return true;
438 * @param string $url URL which get tested
439 * @return boolean True if url is allowed otherwise return false
441 function allowed_url($url) {
443 $h = @parse_url($url);
449 $str_allowed = get_config('system','allowed_sites');
455 $host = strtolower($h['host']);
457 // always allow our own site
459 if($host == strtolower($_SERVER['SERVER_NAME']))
462 $fnmatch = function_exists('fnmatch');
463 $allowed = explode(',',$str_allowed);
465 if(count($allowed)) {
466 foreach($allowed as $a) {
467 $pat = strtolower(trim($a));
468 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
478 * @brief Check if email address is allowed to register here.
480 * Compare against our list (wildcards allowed).
483 * @return boolean False if not allowed, true if allowed
484 * or if allowed list is not configured
486 function allowed_email($email) {
489 $domain = strtolower(substr($email,strpos($email,'@') + 1));
493 $str_allowed = get_config('system','allowed_email');
499 $fnmatch = function_exists('fnmatch');
500 $allowed = explode(',',$str_allowed);
502 if(count($allowed)) {
503 foreach($allowed as $a) {
504 $pat = strtolower(trim($a));
505 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
514 function avatar_img($email) {
516 $avatar['size'] = 175;
517 $avatar['email'] = $email;
519 $avatar['success'] = false;
521 call_hooks('avatar_lookup', $avatar);
523 if (! $avatar['success']) {
524 $avatar['url'] = App::get_baseurl() . '/images/person-175.jpg';
527 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
528 return $avatar['url'];
532 function parse_xml_string($s,$strict = true) {
533 /// @todo Move this function to the xml class
535 if(! strstr($s,'<?xml'))
537 $s2 = substr($s,strpos($s,'<?xml'));
541 libxml_use_internal_errors(true);
543 $x = @simplexml_load_string($s2);
545 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
546 foreach (libxml_get_errors() as $err) {
547 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
549 libxml_clear_errors();
554 function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
556 // Suppress "view full size"
557 if (intval(get_config('system','no_view_full_size'))) {
558 $include_link = false;
563 // Picture addresses can contain special characters
564 $s = htmlspecialchars_decode($srctext);
567 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
569 require_once('include/Photo.php');
570 foreach ($matches as $mtch) {
571 logger('scale_external_image: ' . $mtch[1]);
573 $hostname = str_replace('www.','',substr(App::get_baseurl(),strpos(App::get_baseurl(),'://')+3));
574 if (stristr($mtch[1],$hostname)) {
578 // $scale_replace, if passed, is an array of two elements. The
579 // first is the name of the full-size image. The second is the
580 // name of a remote, scaled-down version of the full size image.
581 // This allows Friendica to display the smaller remote image if
582 // one exists, while still linking to the full-size image
583 if ($scale_replace) {
584 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
588 $i = fetch_url($scaled);
593 // guess mimetype from headers or filename
594 $type = guess_image_type($mtch[1],true);
597 $ph = new Photo($i, $type);
598 if ($ph->is_valid()) {
599 $orig_width = $ph->getWidth();
600 $orig_height = $ph->getHeight();
602 if ($orig_width > 640 || $orig_height > 640) {
604 $ph->scaleImage(640);
605 $new_width = $ph->getWidth();
606 $new_height = $ph->getHeight();
607 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
608 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
609 . "\n" . (($include_link)
610 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
612 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
619 // replace the special char encoding
620 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
625 function fix_contact_ssl_policy(&$contact,$new_policy) {
627 $ssl_changed = false;
628 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
630 $contact['url'] = str_replace('https:','http:',$contact['url']);
631 $contact['request'] = str_replace('https:','http:',$contact['request']);
632 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
633 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
634 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
635 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
638 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
640 $contact['url'] = str_replace('http:','https:',$contact['url']);
641 $contact['request'] = str_replace('http:','https:',$contact['request']);
642 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
643 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
644 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
645 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
649 q("UPDATE `contact` SET
656 WHERE `id` = %d LIMIT 1",
657 dbesc($contact['url']),
658 dbesc($contact['request']),
659 dbesc($contact['notify']),
660 dbesc($contact['poll']),
661 dbesc($contact['confirm']),
662 dbesc($contact['poco']),
663 intval($contact['id'])
668 function original_url($url, $depth=1, $fetchbody = false) {
672 // Remove Analytics Data from Google and other tracking platforms
673 $urldata = parse_url($url);
674 if (is_string($urldata["query"])) {
675 $query = $urldata["query"];
676 parse_str($query, $querydata);
678 if (is_array($querydata))
679 foreach ($querydata AS $param=>$value)
680 if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
681 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
682 "fb_action_ids", "fb_action_types", "fb_ref",
684 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) {
686 $pair = $param."=".urlencode($value);
687 $url = str_replace($pair, "", $url);
689 // Second try: if the url isn't encoded completely
690 $pair = $param."=".str_replace(" ", "+", $value);
691 $url = str_replace($pair, "", $url);
693 // Third try: Maybey the url isn't encoded at all
694 $pair = $param."=".$value;
695 $url = str_replace($pair, "", $url);
697 $url = str_replace(array("?&", "&&"), array("?", ""), $url);
700 if (substr($url, -1, 1) == "?")
701 $url = substr($url, 0, -1);
707 $url = trim($url, "'");
709 $stamp1 = microtime(true);
713 curl_setopt($ch, CURLOPT_URL, $url);
714 curl_setopt($ch, CURLOPT_HEADER, 1);
715 curl_setopt($ch, CURLOPT_NOBODY, 1);
716 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
717 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
718 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
720 $header = curl_exec($ch);
721 $curl_info = @curl_getinfo($ch);
722 $http_code = $curl_info['http_code'];
725 $a->save_timestamp($stamp1, "network");
730 if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
731 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
732 if ($curl_info['redirect_url'] != "")
733 return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
735 return(original_url($curl_info['location'], ++$depth, $fetchbody));
738 // Check for redirects in the meta elements of the body if there are no redirects in the header.
740 return(original_url($url, ++$depth, true));
742 // if the file is too large then exit
743 if ($curl_info["download_content_length"] > 1000000)
746 // if it isn't a HTML file then exit
747 if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
750 $stamp1 = microtime(true);
753 curl_setopt($ch, CURLOPT_URL, $url);
754 curl_setopt($ch, CURLOPT_HEADER, 0);
755 curl_setopt($ch, CURLOPT_NOBODY, 0);
756 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
757 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
758 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
760 $body = curl_exec($ch);
763 $a->save_timestamp($stamp1, "network");
765 if (trim($body) == "")
768 // Check for redirect in meta elements
769 $doc = new DOMDocument();
770 @$doc->loadHTML($body);
772 $xpath = new DomXPath($doc);
774 $list = $xpath->query("//meta[@content]");
775 foreach ($list as $node) {
777 if ($node->attributes->length)
778 foreach ($node->attributes as $attribute)
779 $attr[$attribute->name] = $attribute->value;
781 if (@$attr["http-equiv"] == 'refresh') {
782 $path = $attr["content"];
783 $pathinfo = explode(";", $path);
785 foreach ($pathinfo AS $value)
786 if (substr(strtolower($value), 0, 4) == "url=")
787 return(original_url(substr($value, 4), ++$depth));
794 function short_link($url) {
795 require_once('library/slinky.php');
796 $slinky = new Slinky($url);
797 $yourls_url = get_config('yourls','url1');
799 $yourls_username = get_config('yourls','username1');
800 $yourls_password = get_config('yourls', 'password1');
801 $yourls_ssl = get_config('yourls', 'ssl1');
802 $yourls = new Slinky_YourLS();
803 $yourls->set('username', $yourls_username);
804 $yourls->set('password', $yourls_password);
805 $yourls->set('ssl', $yourls_ssl);
806 $yourls->set('yourls-url', $yourls_url);
807 $slinky->set_cascade(array($yourls, new Slinky_Ur1ca(), new Slinky_TinyURL()));
809 // setup a cascade of shortening services
810 // try to get a short link from these services
811 // in the order ur1.ca, tinyurl
812 $slinky->set_cascade(array(new Slinky_Ur1ca(), new Slinky_TinyURL()));
814 return $slinky->short();
818 * @brief Encodes content to json
820 * This function encodes an array to json format
821 * and adds an application/json HTTP header to the output.
822 * After finishing the process is getting killed.
824 * @param array $x The input content
826 function json_return_and_die($x) {
827 header("content-type: application/json");
828 echo json_encode($x);
833 * @brief Find the matching part between two url
835 * @param string $url1
836 * @param string $url2
837 * @return string The matching part
839 function matching_url($url1, $url2) {
841 if (($url1 == "") OR ($url2 == ""))
844 $url1 = normalise_link($url1);
845 $url2 = normalise_link($url2);
847 $parts1 = parse_url($url1);
848 $parts2 = parse_url($url2);
850 if (!isset($parts1["host"]) OR !isset($parts2["host"]))
853 if ($parts1["scheme"] != $parts2["scheme"])
856 if ($parts1["host"] != $parts2["host"])
859 if ($parts1["port"] != $parts2["port"])
862 $match = $parts1["scheme"]."://".$parts1["host"];
865 $match .= ":".$parts1["port"];
867 $pathparts1 = explode("/", $parts1["path"]);
868 $pathparts2 = explode("/", $parts2["path"]);
873 $path1 = $pathparts1[$i];
874 $path2 = $pathparts2[$i];
876 if ($path1 == $path2)
879 } while (($path1 == $path2) AND ($i++ <= count($pathparts1)));
883 return normalise_link($match);