4 * @file include/network.php
7 use \Friendica\Core\Config;
8 use \Friendica\Core\PConfig;
10 require_once("include/xml.php");
11 require_once('include/Probe.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()) {
68 $ret = array('return_code' => 0, 'success' => false, 'header' => "", 'body' => "");
71 $stamp1 = microtime(true);
75 $ch = @curl_init($url);
76 if(($redirects > 8) || (! $ch))
79 @curl_setopt($ch, CURLOPT_HEADER, true);
81 if(x($opts,"cookiejar")) {
82 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
83 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
86 // These settings aren't needed. We're following the location already.
87 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
88 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
90 if (x($opts,'accept_content')){
91 curl_setopt($ch,CURLOPT_HTTPHEADER, array (
92 "Accept: " . $opts['accept_content']
96 @curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
97 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
99 $range = intval(Config::get('system', 'curl_range_bytes', 0));
101 @curl_setopt($ch, CURLOPT_RANGE, '0-'.$range);
104 if(x($opts,'headers')){
105 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
107 if(x($opts,'nobody')){
108 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
110 if(x($opts,'timeout')){
111 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
113 $curl_time = intval(get_config('system','curl_timeout'));
114 @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
117 // by default we will allow self-signed certs
118 // but you can override this
120 $check_cert = get_config('system','verifyssl');
121 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
122 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
124 $prx = get_config('system','proxy');
126 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
127 @curl_setopt($ch, CURLOPT_PROXY, $prx);
128 $prxusr = @get_config('system','proxyuser');
130 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
133 @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
135 $a->set_curl_code(0);
137 // don't let curl abort the entire application
138 // if it throws any errors.
140 $s = @curl_exec($ch);
141 if (curl_errno($ch) !== CURLE_OK) {
142 logger('fetch_url error fetching '.$url.': '.curl_error($ch), LOGGER_NORMAL);
146 $curl_info = @curl_getinfo($ch);
148 $http_code = $curl_info['http_code'];
149 logger('fetch_url '.$url.': '.$http_code." ".$s, LOGGER_DATA);
152 // Pull out multiple headers, e.g. proxy and continuation headers
153 // allow for HTTP/2.x without fixing code
155 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
156 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
158 $base = substr($base,strlen($chunk));
161 $a->set_curl_code($http_code);
162 $a->set_curl_content_type($curl_info['content_type']);
163 $a->set_curl_headers($header);
165 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
166 $new_location_info = @parse_url($curl_info["redirect_url"]);
167 $old_location_info = @parse_url($curl_info["url"]);
169 $newurl = $curl_info["redirect_url"];
171 if (($new_location_info["path"] == "") AND ($new_location_info["host"] != ""))
172 $newurl = $new_location_info["scheme"]."://".$new_location_info["host"].$old_location_info["path"];
175 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
176 $newurl = trim(array_pop($matches));
178 if(strpos($newurl,'/') === 0)
179 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
180 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
183 return z_fetch_url($newurl,$binary, $redirects, $opts);
188 $a->set_curl_code($http_code);
189 $a->set_curl_content_type($curl_info['content_type']);
191 $body = substr($s,strlen($header));
195 $rc = intval($http_code);
196 $ret['return_code'] = $rc;
197 $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
198 $ret['redirect_url'] = $url;
199 if(! $ret['success']) {
200 $ret['error'] = curl_error($ch);
201 $ret['debug'] = $curl_info;
202 logger('z_fetch_url: error: ' . $url . ': ' . $ret['error'], LOGGER_DEBUG);
203 logger('z_fetch_url: debug: ' . print_r($curl_info,true), LOGGER_DATA);
205 $ret['body'] = substr($s,strlen($header));
206 $ret['header'] = $header;
207 if(x($opts,'debug')) {
208 $ret['debug'] = $curl_info;
212 $a->save_timestamp($stamp1, "network");
218 // post request to $url. $params is an array of post variables.
221 * @brief Post request to $url
223 * @param string $url URL to post
224 * @param mixed $params
225 * @param string $headers HTTP headers
226 * @param integer $redirects Recursion counter for internal use - default = 0
227 * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
229 * @return string The content
231 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
232 $stamp1 = microtime(true);
235 $ch = curl_init($url);
236 if(($redirects > 8) || (! $ch))
239 logger("post_url: start ".$url, LOGGER_DATA);
241 curl_setopt($ch, CURLOPT_HEADER, true);
242 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
243 curl_setopt($ch, CURLOPT_POST,1);
244 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
245 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
247 if(intval($timeout)) {
248 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
251 $curl_time = intval(get_config('system','curl_timeout'));
252 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
255 if(defined('LIGHTTPD')) {
256 if(!is_array($headers)) {
257 $headers = array('Expect:');
259 if(!in_array('Expect:', $headers)) {
260 array_push($headers, 'Expect:');
265 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
267 $check_cert = get_config('system','verifyssl');
268 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
269 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
270 $prx = get_config('system','proxy');
272 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
273 curl_setopt($ch, CURLOPT_PROXY, $prx);
274 $prxusr = get_config('system','proxyuser');
276 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
279 $a->set_curl_code(0);
281 // don't let curl abort the entire application
282 // if it throws any errors.
284 $s = @curl_exec($ch);
287 $curl_info = curl_getinfo($ch);
288 $http_code = $curl_info['http_code'];
290 logger("post_url: result ".$http_code." - ".$url, LOGGER_DATA);
294 // Pull out multiple headers, e.g. proxy and continuation headers
295 // allow for HTTP/2.x without fixing code
297 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
298 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
300 $base = substr($base,strlen($chunk));
303 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
305 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
306 $newurl = trim(array_pop($matches));
307 if(strpos($newurl,'/') === 0)
308 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
309 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
311 logger("post_url: redirect ".$url." to ".$newurl);
312 return post_url($newurl,$params, $headers, $redirects, $timeout);
313 //return fetch_url($newurl,false,$redirects,$timeout);
316 $a->set_curl_code($http_code);
317 $body = substr($s,strlen($header));
319 $a->set_curl_headers($header);
323 $a->save_timestamp($stamp1, "network");
325 logger("post_url: end ".$url, LOGGER_DATA);
330 // Generic XML return
331 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
332 // of $st and an optional text <message> of $message and terminates the current process.
334 function xml_status($st, $message = '') {
336 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
339 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
341 header( "Content-type: text/xml" );
342 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
343 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
348 * @brief Send HTTP status header and exit.
350 * @param integer $val HTTP status result value
351 * @param array $description optional message
352 * 'title' => header title
353 * 'description' => optional message
357 * @brief Send HTTP status header and exit.
359 * @param integer $val HTTP status result value
360 * @param array $description optional message
361 * 'title' => header title
362 * 'description' => optional message
364 function http_status_exit($val, $description = array()) {
368 if (!isset($description["title"]))
369 $description["title"] = $err." ".$val;
371 if($val >= 200 && $val < 300)
374 logger('http_status_exit ' . $val);
375 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
377 if (isset($description["title"])) {
378 $tpl = get_markup_template('http_status.tpl');
379 echo replace_macros($tpl, array('$title' => $description["title"],
380 '$description' => $description["description"]));
388 * @brief Check URL to se if ts's real
390 * Take a URL from the wild, prepend http:// if necessary
391 * and check DNS to see if it's real (or check if is a valid IP address)
393 * @param string $url The URL to be validated
394 * @return boolean True if it's a valid URL, fals if something wrong with it
396 function validate_url(&$url) {
397 if(get_config('system','disable_url_validation'))
400 // no naked subdomains (allow localhost for tests)
401 if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
404 if(substr($url,0,4) != 'http')
405 $url = 'http://' . $url;
407 /// @TODO Really supress function outcomes? Why not find them + debug them?
408 $h = @parse_url($url);
410 if((is_array($h)) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
418 * @brief Checks that email is an actual resolvable internet address
420 * @param string $addr The email address
421 * @return boolean True if it's a valid email address, false if it's not
423 function validate_email($addr) {
425 if(get_config('system','disable_email_validation'))
428 if(! strpos($addr,'@'))
430 $h = substr($addr,strpos($addr,'@') + 1);
432 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
439 * @brief Check if URL is allowed
441 * Check $url against our list of allowed sites,
442 * wildcards allowed. If allowed_sites is unset return true;
444 * @param string $url URL which get tested
445 * @return boolean True if url is allowed otherwise return false
447 function allowed_url($url) {
449 $h = @parse_url($url);
455 $str_allowed = get_config('system','allowed_sites');
461 $host = strtolower($h['host']);
463 // always allow our own site
465 if($host == strtolower($_SERVER['SERVER_NAME']))
468 $fnmatch = function_exists('fnmatch');
469 $allowed = explode(',',$str_allowed);
471 if(count($allowed)) {
472 foreach($allowed as $a) {
473 $pat = strtolower(trim($a));
474 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
484 * @brief Check if email address is allowed to register here.
486 * Compare against our list (wildcards allowed).
489 * @return boolean False if not allowed, true if allowed
490 * or if allowed list is not configured
492 function allowed_email($email) {
495 $domain = strtolower(substr($email,strpos($email,'@') + 1));
499 $str_allowed = get_config('system','allowed_email');
505 $fnmatch = function_exists('fnmatch');
506 $allowed = explode(',',$str_allowed);
508 if(count($allowed)) {
509 foreach($allowed as $a) {
510 $pat = strtolower(trim($a));
511 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
520 function avatar_img($email) {
522 $avatar['size'] = 175;
523 $avatar['email'] = $email;
525 $avatar['success'] = false;
527 call_hooks('avatar_lookup', $avatar);
529 if (! $avatar['success']) {
530 $avatar['url'] = App::get_baseurl() . '/images/person-175.jpg';
533 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
534 return $avatar['url'];
538 function parse_xml_string($s,$strict = true) {
539 /// @todo Move this function to the xml class
541 if(! strstr($s,'<?xml'))
543 $s2 = substr($s,strpos($s,'<?xml'));
547 libxml_use_internal_errors(true);
549 $x = @simplexml_load_string($s2);
551 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
552 foreach (libxml_get_errors() as $err) {
553 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
555 libxml_clear_errors();
560 function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
562 // Suppress "view full size"
563 if (intval(get_config('system','no_view_full_size'))) {
564 $include_link = false;
569 // Picture addresses can contain special characters
570 $s = htmlspecialchars_decode($srctext);
573 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
575 require_once('include/Photo.php');
576 foreach ($matches as $mtch) {
577 logger('scale_external_image: ' . $mtch[1]);
579 $hostname = str_replace('www.','',substr(App::get_baseurl(),strpos(App::get_baseurl(),'://')+3));
580 if (stristr($mtch[1],$hostname)) {
584 // $scale_replace, if passed, is an array of two elements. The
585 // first is the name of the full-size image. The second is the
586 // name of a remote, scaled-down version of the full size image.
587 // This allows Friendica to display the smaller remote image if
588 // one exists, while still linking to the full-size image
589 if ($scale_replace) {
590 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
594 $i = fetch_url($scaled);
599 // guess mimetype from headers or filename
600 $type = guess_image_type($mtch[1],true);
603 $ph = new Photo($i, $type);
604 if ($ph->is_valid()) {
605 $orig_width = $ph->getWidth();
606 $orig_height = $ph->getHeight();
608 if ($orig_width > 640 || $orig_height > 640) {
610 $ph->scaleImage(640);
611 $new_width = $ph->getWidth();
612 $new_height = $ph->getHeight();
613 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
614 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
615 . "\n" . (($include_link)
616 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
618 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
625 // replace the special char encoding
626 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
631 function fix_contact_ssl_policy(&$contact,$new_policy) {
633 $ssl_changed = false;
634 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
636 $contact['url'] = str_replace('https:','http:',$contact['url']);
637 $contact['request'] = str_replace('https:','http:',$contact['request']);
638 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
639 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
640 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
641 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
644 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
646 $contact['url'] = str_replace('http:','https:',$contact['url']);
647 $contact['request'] = str_replace('http:','https:',$contact['request']);
648 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
649 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
650 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
651 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
655 q("UPDATE `contact` SET
662 WHERE `id` = %d LIMIT 1",
663 dbesc($contact['url']),
664 dbesc($contact['request']),
665 dbesc($contact['notify']),
666 dbesc($contact['poll']),
667 dbesc($contact['confirm']),
668 dbesc($contact['poco']),
669 intval($contact['id'])
674 function original_url($url, $depth=1, $fetchbody = false) {
678 // Remove Analytics Data from Google and other tracking platforms
679 $urldata = parse_url($url);
680 if (is_string($urldata["query"])) {
681 $query = $urldata["query"];
682 parse_str($query, $querydata);
684 if (is_array($querydata))
685 foreach ($querydata AS $param=>$value)
686 if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
687 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
688 "fb_action_ids", "fb_action_types", "fb_ref",
690 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) {
692 $pair = $param."=".urlencode($value);
693 $url = str_replace($pair, "", $url);
695 // Second try: if the url isn't encoded completely
696 $pair = $param."=".str_replace(" ", "+", $value);
697 $url = str_replace($pair, "", $url);
699 // Third try: Maybey the url isn't encoded at all
700 $pair = $param."=".$value;
701 $url = str_replace($pair, "", $url);
703 $url = str_replace(array("?&", "&&"), array("?", ""), $url);
706 if (substr($url, -1, 1) == "?")
707 $url = substr($url, 0, -1);
713 $url = trim($url, "'");
715 $stamp1 = microtime(true);
719 curl_setopt($ch, CURLOPT_URL, $url);
720 curl_setopt($ch, CURLOPT_HEADER, 1);
721 curl_setopt($ch, CURLOPT_NOBODY, 1);
722 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
723 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
724 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
726 $header = curl_exec($ch);
727 $curl_info = @curl_getinfo($ch);
728 $http_code = $curl_info['http_code'];
731 $a->save_timestamp($stamp1, "network");
736 if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
737 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
738 if ($curl_info['redirect_url'] != "")
739 return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
741 return(original_url($curl_info['location'], ++$depth, $fetchbody));
744 // Check for redirects in the meta elements of the body if there are no redirects in the header.
746 return(original_url($url, ++$depth, true));
748 // if the file is too large then exit
749 if ($curl_info["download_content_length"] > 1000000)
752 // if it isn't a HTML file then exit
753 if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
756 $stamp1 = microtime(true);
759 curl_setopt($ch, CURLOPT_URL, $url);
760 curl_setopt($ch, CURLOPT_HEADER, 0);
761 curl_setopt($ch, CURLOPT_NOBODY, 0);
762 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
763 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
764 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
766 $body = curl_exec($ch);
769 $a->save_timestamp($stamp1, "network");
771 if (trim($body) == "")
774 // Check for redirect in meta elements
775 $doc = new DOMDocument();
776 @$doc->loadHTML($body);
778 $xpath = new DomXPath($doc);
780 $list = $xpath->query("//meta[@content]");
781 foreach ($list as $node) {
783 if ($node->attributes->length)
784 foreach ($node->attributes as $attribute)
785 $attr[$attribute->name] = $attribute->value;
787 if (@$attr["http-equiv"] == 'refresh') {
788 $path = $attr["content"];
789 $pathinfo = explode(";", $path);
791 foreach ($pathinfo AS $value)
792 if (substr(strtolower($value), 0, 4) == "url=")
793 return(original_url(substr($value, 4), ++$depth));
800 function short_link($url) {
801 require_once('library/slinky.php');
802 $slinky = new Slinky($url);
803 $yourls_url = get_config('yourls','url1');
805 $yourls_username = get_config('yourls','username1');
806 $yourls_password = get_config('yourls', 'password1');
807 $yourls_ssl = get_config('yourls', 'ssl1');
808 $yourls = new Slinky_YourLS();
809 $yourls->set('username', $yourls_username);
810 $yourls->set('password', $yourls_password);
811 $yourls->set('ssl', $yourls_ssl);
812 $yourls->set('yourls-url', $yourls_url);
813 $slinky->set_cascade(array($yourls, new Slinky_Ur1ca(), new Slinky_TinyURL()));
815 // setup a cascade of shortening services
816 // try to get a short link from these services
817 // in the order ur1.ca, tinyurl
818 $slinky->set_cascade(array(new Slinky_Ur1ca(), new Slinky_TinyURL()));
820 return $slinky->short();
824 * @brief Encodes content to json
826 * This function encodes an array to json format
827 * and adds an application/json HTTP header to the output.
828 * After finishing the process is getting killed.
830 * @param array $x The input content
832 function json_return_and_die($x) {
833 header("content-type: application/json");
834 echo json_encode($x);
839 * @brief Find the matching part between two url
841 * @param string $url1
842 * @param string $url2
843 * @return string The matching part
845 function matching_url($url1, $url2) {
847 if (($url1 == "") OR ($url2 == ""))
850 $url1 = normalise_link($url1);
851 $url2 = normalise_link($url2);
853 $parts1 = parse_url($url1);
854 $parts2 = parse_url($url2);
856 if (!isset($parts1["host"]) OR !isset($parts2["host"]))
859 if ($parts1["scheme"] != $parts2["scheme"])
862 if ($parts1["host"] != $parts2["host"])
865 if ($parts1["port"] != $parts2["port"])
868 $match = $parts1["scheme"]."://".$parts1["host"];
871 $match .= ":".$parts1["port"];
873 $pathparts1 = explode("/", $parts1["path"]);
874 $pathparts2 = explode("/", $parts2["path"]);
879 $path1 = $pathparts1[$i];
880 $path2 = $pathparts2[$i];
882 if ($path1 == $path2)
885 } while (($path1 == $path2) AND ($i++ <= count($pathparts1)));
889 return normalise_link($match);