4 * @file include/network.php
7 use \Friendica\Core\Config;
9 require_once("include/xml.php");
10 require_once('include/Probe.php');
15 * If binary flag is true, return binary results.
16 * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
17 * to preserve cookies from one request to the next.
19 * @param string $url URL to fetch
20 * @param boolean $binary default false
21 * TRUE if asked to return binary results (file download)
22 * @param integer $redirects The recursion counter for internal use - default 0
23 * @param integer $timeout Timeout in seconds, default system config value or 60 seconds
24 * @param string $accept_content supply Accept: header with 'accept_content' as the value
25 * @param string $cookiejar Path to cookie jar file
27 * @return string The fetched content
29 function fetch_url($url,$binary = false, &$redirects = 0, $timeout = 0, $accept_content=Null, $cookiejar = 0) {
35 array('timeout'=>$timeout,
36 'accept_content'=>$accept_content,
37 'cookiejar'=>$cookiejar
44 * @brief fetches an URL.
46 * @param string $url URL to fetch
47 * @param boolean $binary default false
48 * TRUE if asked to return binary results (file download)
49 * @param int $redirects The recursion counter for internal use - default 0
50 * @param array $opts (optional parameters) assoziative array with:
51 * 'accept_content' => supply Accept: header with 'accept_content' as the value
52 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
53 * 'http_auth' => username:password
54 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
55 * 'nobody' => only return the header
56 * 'cookiejar' => path to cookie jar file
58 * @return array an assoziative array with:
59 * int 'return_code' => HTTP return code or 0 if timeout or failure
60 * boolean 'success' => boolean true (if HTTP 2xx result) or false
61 * string 'redirect_url' => in case of redirect, content was finally retrieved from this URL
62 * string 'header' => HTTP headers
63 * string 'body' => fetched content
65 function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
67 $ret = array('return_code' => 0, 'success' => false, 'header' => "", 'body' => "");
70 $stamp1 = microtime(true);
74 $ch = @curl_init($url);
75 if(($redirects > 8) || (! $ch))
78 @curl_setopt($ch, CURLOPT_HEADER, true);
80 if(x($opts,"cookiejar")) {
81 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
82 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
85 // These settings aren't needed. We're following the location already.
86 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
87 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
89 if (x($opts,'accept_content')){
90 curl_setopt($ch,CURLOPT_HTTPHEADER, array (
91 "Accept: " . $opts['accept_content']
95 @curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
96 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
98 $range = intval(Config::get('system', 'curl_range_bytes', 0));
100 @curl_setopt($ch, CURLOPT_RANGE, '0-'.$range);
103 if(x($opts,'headers')){
104 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
106 if(x($opts,'nobody')){
107 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
109 if(x($opts,'timeout')){
110 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
112 $curl_time = intval(get_config('system','curl_timeout'));
113 @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
116 // by default we will allow self-signed certs
117 // but you can override this
119 $check_cert = get_config('system','verifyssl');
120 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
122 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
125 $prx = get_config('system','proxy');
127 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
128 @curl_setopt($ch, CURLOPT_PROXY, $prx);
129 $prxusr = @get_config('system','proxyuser');
131 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
134 @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
136 $a->set_curl_code(0);
138 // don't let curl abort the entire application
139 // if it throws any errors.
141 $s = @curl_exec($ch);
142 if (curl_errno($ch) !== CURLE_OK) {
143 logger('fetch_url error fetching '.$url.': '.curl_error($ch), LOGGER_NORMAL);
147 $curl_info = @curl_getinfo($ch);
149 $http_code = $curl_info['http_code'];
150 logger('fetch_url '.$url.': '.$http_code." ".$s, LOGGER_DATA);
153 // Pull out multiple headers, e.g. proxy and continuation headers
154 // allow for HTTP/2.x without fixing code
156 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
157 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
159 $base = substr($base,strlen($chunk));
162 $a->set_curl_code($http_code);
163 $a->set_curl_content_type($curl_info['content_type']);
164 $a->set_curl_headers($header);
166 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
167 $new_location_info = @parse_url($curl_info["redirect_url"]);
168 $old_location_info = @parse_url($curl_info["url"]);
170 $newurl = $curl_info["redirect_url"];
172 if (($new_location_info["path"] == "") AND ($new_location_info["host"] != ""))
173 $newurl = $new_location_info["scheme"]."://".$new_location_info["host"].$old_location_info["path"];
176 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
177 $newurl = trim(array_pop($matches));
179 if(strpos($newurl,'/') === 0)
180 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
181 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
184 return z_fetch_url($newurl,$binary, $redirects, $opts);
189 $a->set_curl_code($http_code);
190 $a->set_curl_content_type($curl_info['content_type']);
192 $body = substr($s,strlen($header));
196 $rc = intval($http_code);
197 $ret['return_code'] = $rc;
198 $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
199 $ret['redirect_url'] = $url;
200 if(! $ret['success']) {
201 $ret['error'] = curl_error($ch);
202 $ret['debug'] = $curl_info;
203 logger('z_fetch_url: error: ' . $url . ': ' . $ret['error'], LOGGER_DEBUG);
204 logger('z_fetch_url: debug: ' . print_r($curl_info,true), LOGGER_DATA);
206 $ret['body'] = substr($s,strlen($header));
207 $ret['header'] = $header;
208 if(x($opts,'debug')) {
209 $ret['debug'] = $curl_info;
213 $a->save_timestamp($stamp1, "network");
219 // post request to $url. $params is an array of post variables.
222 * @brief Post request to $url
224 * @param string $url URL to post
225 * @param mixed $params
226 * @param string $headers HTTP headers
227 * @param integer $redirects Recursion counter for internal use - default = 0
228 * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
230 * @return string The content
232 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
233 $stamp1 = microtime(true);
236 $ch = curl_init($url);
237 if(($redirects > 8) || (! $ch))
240 logger("post_url: start ".$url, LOGGER_DATA);
242 curl_setopt($ch, CURLOPT_HEADER, true);
243 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
244 curl_setopt($ch, CURLOPT_POST,1);
245 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
246 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
248 if(intval($timeout)) {
249 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
252 $curl_time = intval(get_config('system','curl_timeout'));
253 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
256 if(defined('LIGHTTPD')) {
257 if(!is_array($headers)) {
258 $headers = array('Expect:');
260 if(!in_array('Expect:', $headers)) {
261 array_push($headers, 'Expect:');
266 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
268 $check_cert = get_config('system','verifyssl');
269 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
271 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
273 $prx = get_config('system','proxy');
275 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
276 curl_setopt($ch, CURLOPT_PROXY, $prx);
277 $prxusr = get_config('system','proxyuser');
279 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
282 $a->set_curl_code(0);
284 // don't let curl abort the entire application
285 // if it throws any errors.
287 $s = @curl_exec($ch);
290 $curl_info = curl_getinfo($ch);
291 $http_code = $curl_info['http_code'];
293 logger("post_url: result ".$http_code." - ".$url, LOGGER_DATA);
297 // Pull out multiple headers, e.g. proxy and continuation headers
298 // allow for HTTP/2.x without fixing code
300 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
301 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
303 $base = substr($base,strlen($chunk));
306 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
308 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
309 $newurl = trim(array_pop($matches));
310 if(strpos($newurl,'/') === 0)
311 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
312 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
314 logger("post_url: redirect ".$url." to ".$newurl);
315 return post_url($newurl,$params, $headers, $redirects, $timeout);
316 //return fetch_url($newurl,false,$redirects,$timeout);
319 $a->set_curl_code($http_code);
320 $body = substr($s,strlen($header));
322 $a->set_curl_headers($header);
326 $a->save_timestamp($stamp1, "network");
328 logger("post_url: end ".$url, LOGGER_DATA);
333 // Generic XML return
334 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
335 // of $st and an optional text <message> of $message and terminates the current process.
337 function xml_status($st, $message = '') {
339 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
342 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
344 header( "Content-type: text/xml" );
345 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
346 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
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
360 * @brief Send HTTP status header and exit.
362 * @param integer $val HTTP status result value
363 * @param array $description optional message
364 * 'title' => header title
365 * 'description' => optional message
367 function http_status_exit($val, $description = array()) {
371 if (!isset($description["title"]))
372 $description["title"] = $err." ".$val;
374 if($val >= 200 && $val < 300)
377 logger('http_status_exit ' . $val);
378 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
380 if (isset($description["title"])) {
381 $tpl = get_markup_template('http_status.tpl');
382 echo replace_macros($tpl, array('$title' => $description["title"],
383 '$description' => $description["description"]));
391 * @brief Check URL to se if ts's real
393 * Take a URL from the wild, prepend http:// if necessary
394 * and check DNS to see if it's real (or check if is a valid IP address)
396 * @param string $url The URL to be validated
397 * @return boolean True if it's a valid URL, fals if something wrong with it
399 function validate_url(&$url) {
400 if(get_config('system','disable_url_validation'))
403 // no naked subdomains (allow localhost for tests)
404 if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
407 if(substr($url,0,4) != 'http')
408 $url = 'http://' . $url;
410 /// @TODO Really supress function outcomes? Why not find them + debug them?
411 $h = @parse_url($url);
413 if((is_array($h)) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
421 * @brief Checks that email is an actual resolvable internet address
423 * @param string $addr The email address
424 * @return boolean True if it's a valid email address, false if it's not
426 function validate_email($addr) {
428 if(get_config('system','disable_email_validation'))
431 if(! strpos($addr,'@'))
433 $h = substr($addr,strpos($addr,'@') + 1);
435 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
442 * @brief Check if URL is allowed
444 * Check $url against our list of allowed sites,
445 * wildcards allowed. If allowed_sites is unset return true;
447 * @param string $url URL which get tested
448 * @return boolean True if url is allowed otherwise return false
450 function allowed_url($url) {
452 $h = @parse_url($url);
458 $str_allowed = get_config('system','allowed_sites');
464 $host = strtolower($h['host']);
466 // always allow our own site
468 if($host == strtolower($_SERVER['SERVER_NAME']))
471 $fnmatch = function_exists('fnmatch');
472 $allowed = explode(',',$str_allowed);
474 if(count($allowed)) {
475 foreach($allowed as $a) {
476 $pat = strtolower(trim($a));
477 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
487 * @brief Check if email address is allowed to register here.
489 * Compare against our list (wildcards allowed).
492 * @return boolean False if not allowed, true if allowed
493 * or if allowed list is not configured
495 function allowed_email($email) {
498 $domain = strtolower(substr($email,strpos($email,'@') + 1));
502 $str_allowed = get_config('system','allowed_email');
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,$domain)) || ($pat == $domain)) {
523 function avatar_img($email) {
525 $avatar['size'] = 175;
526 $avatar['email'] = $email;
528 $avatar['success'] = false;
530 call_hooks('avatar_lookup', $avatar);
532 if (! $avatar['success']) {
533 $avatar['url'] = App::get_baseurl() . '/images/person-175.jpg';
536 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
537 return $avatar['url'];
541 function parse_xml_string($s,$strict = true) {
542 /// @todo Move this function to the xml class
544 if(! strstr($s,'<?xml'))
546 $s2 = substr($s,strpos($s,'<?xml'));
550 libxml_use_internal_errors(true);
552 $x = @simplexml_load_string($s2);
554 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
555 foreach (libxml_get_errors() as $err) {
556 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
558 libxml_clear_errors();
563 function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
565 // Suppress "view full size"
566 if (intval(get_config('system','no_view_full_size'))) {
567 $include_link = false;
572 // Picture addresses can contain special characters
573 $s = htmlspecialchars_decode($srctext);
576 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
578 require_once('include/Photo.php');
579 foreach ($matches as $mtch) {
580 logger('scale_external_image: ' . $mtch[1]);
582 $hostname = str_replace('www.','',substr(App::get_baseurl(),strpos(App::get_baseurl(),'://')+3));
583 if (stristr($mtch[1],$hostname)) {
587 // $scale_replace, if passed, is an array of two elements. The
588 // first is the name of the full-size image. The second is the
589 // name of a remote, scaled-down version of the full size image.
590 // This allows Friendica to display the smaller remote image if
591 // one exists, while still linking to the full-size image
592 if ($scale_replace) {
593 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
597 $i = fetch_url($scaled);
602 // guess mimetype from headers or filename
603 $type = guess_image_type($mtch[1],true);
606 $ph = new Photo($i, $type);
607 if ($ph->is_valid()) {
608 $orig_width = $ph->getWidth();
609 $orig_height = $ph->getHeight();
611 if ($orig_width > 640 || $orig_height > 640) {
613 $ph->scaleImage(640);
614 $new_width = $ph->getWidth();
615 $new_height = $ph->getHeight();
616 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
617 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
618 . "\n" . (($include_link)
619 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
621 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
628 // replace the special char encoding
629 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
634 function fix_contact_ssl_policy(&$contact,$new_policy) {
636 $ssl_changed = false;
637 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
639 $contact['url'] = str_replace('https:','http:',$contact['url']);
640 $contact['request'] = str_replace('https:','http:',$contact['request']);
641 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
642 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
643 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
644 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
647 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
649 $contact['url'] = str_replace('http:','https:',$contact['url']);
650 $contact['request'] = str_replace('http:','https:',$contact['request']);
651 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
652 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
653 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
654 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
658 q("UPDATE `contact` SET
665 WHERE `id` = %d LIMIT 1",
666 dbesc($contact['url']),
667 dbesc($contact['request']),
668 dbesc($contact['notify']),
669 dbesc($contact['poll']),
670 dbesc($contact['confirm']),
671 dbesc($contact['poco']),
672 intval($contact['id'])
678 * @brief Remove Google Analytics and other tracking platforms params from URL
680 * @param string $url Any user-submitted URL that may contain tracking params
681 * @return string The same URL stripped of tracking parameters
683 function strip_tracking_query_params($url)
685 $urldata = parse_url($url);
686 if (is_string($urldata["query"])) {
687 $query = $urldata["query"];
688 parse_str($query, $querydata);
690 if (is_array($querydata)) {
691 foreach ($querydata AS $param => $value) {
692 if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
693 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
694 "fb_action_ids", "fb_action_types", "fb_ref",
696 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) {
698 $pair = $param . "=" . urlencode($value);
699 $url = str_replace($pair, "", $url);
701 // Second try: if the url isn't encoded completely
702 $pair = $param . "=" . str_replace(" ", "+", $value);
703 $url = str_replace($pair, "", $url);
705 // Third try: Maybey the url isn't encoded at all
706 $pair = $param . "=" . $value;
707 $url = str_replace($pair, "", $url);
709 $url = str_replace(array("?&", "&&"), array("?", ""), $url);
714 if (substr($url, -1, 1) == "?") {
715 $url = substr($url, 0, -1);
723 * @brief Returns the original URL of the provided URL
725 * This function strips tracking query params and follows redirections, either
726 * through HTTP code or meta refresh tags. Stops after 10 redirections.
728 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
730 * @see ParseUrl::getSiteinfo
732 * @param string $url A user-submitted URL
733 * @param int $depth The current redirection recursion level (internal)
734 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
735 * @return string A canonical URL
737 function original_url($url, $depth = 1, $fetchbody = false) {
740 $url = strip_tracking_query_params($url);
745 $url = trim($url, "'");
747 $stamp1 = microtime(true);
751 curl_setopt($ch, CURLOPT_URL, $url);
752 curl_setopt($ch, CURLOPT_HEADER, 1);
753 curl_setopt($ch, CURLOPT_NOBODY, 1);
754 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
755 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
756 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
758 $header = curl_exec($ch);
759 $curl_info = @curl_getinfo($ch);
760 $http_code = $curl_info['http_code'];
763 $a->save_timestamp($stamp1, "network");
768 if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
769 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
770 if ($curl_info['redirect_url'] != "")
771 return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
773 return(original_url($curl_info['location'], ++$depth, $fetchbody));
776 // Check for redirects in the meta elements of the body if there are no redirects in the header.
778 return(original_url($url, ++$depth, true));
780 // if the file is too large then exit
781 if ($curl_info["download_content_length"] > 1000000)
784 // if it isn't a HTML file then exit
785 if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
788 $stamp1 = microtime(true);
791 curl_setopt($ch, CURLOPT_URL, $url);
792 curl_setopt($ch, CURLOPT_HEADER, 0);
793 curl_setopt($ch, CURLOPT_NOBODY, 0);
794 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
795 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
796 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
798 $body = curl_exec($ch);
801 $a->save_timestamp($stamp1, "network");
803 if (trim($body) == "")
806 // Check for redirect in meta elements
807 $doc = new DOMDocument();
808 @$doc->loadHTML($body);
810 $xpath = new DomXPath($doc);
812 $list = $xpath->query("//meta[@content]");
813 foreach ($list as $node) {
815 if ($node->attributes->length)
816 foreach ($node->attributes as $attribute)
817 $attr[$attribute->name] = $attribute->value;
819 if (@$attr["http-equiv"] == 'refresh') {
820 $path = $attr["content"];
821 $pathinfo = explode(";", $path);
823 foreach ($pathinfo AS $value)
824 if (substr(strtolower($value), 0, 4) == "url=")
825 return(original_url(substr($value, 4), ++$depth));
832 function short_link($url) {
833 require_once('library/slinky.php');
834 $slinky = new Slinky($url);
835 $yourls_url = get_config('yourls','url1');
837 $yourls_username = get_config('yourls','username1');
838 $yourls_password = get_config('yourls', 'password1');
839 $yourls_ssl = get_config('yourls', 'ssl1');
840 $yourls = new Slinky_YourLS();
841 $yourls->set('username', $yourls_username);
842 $yourls->set('password', $yourls_password);
843 $yourls->set('ssl', $yourls_ssl);
844 $yourls->set('yourls-url', $yourls_url);
845 $slinky->set_cascade(array($yourls, new Slinky_Ur1ca(), new Slinky_TinyURL()));
847 // setup a cascade of shortening services
848 // try to get a short link from these services
849 // in the order ur1.ca, tinyurl
850 $slinky->set_cascade(array(new Slinky_Ur1ca(), new Slinky_TinyURL()));
852 return $slinky->short();
856 * @brief Encodes content to json
858 * This function encodes an array to json format
859 * and adds an application/json HTTP header to the output.
860 * After finishing the process is getting killed.
862 * @param array $x The input content
864 function json_return_and_die($x) {
865 header("content-type: application/json");
866 echo json_encode($x);
871 * @brief Find the matching part between two url
873 * @param string $url1
874 * @param string $url2
875 * @return string The matching part
877 function matching_url($url1, $url2) {
879 if (($url1 == "") OR ($url2 == ""))
882 $url1 = normalise_link($url1);
883 $url2 = normalise_link($url2);
885 $parts1 = parse_url($url1);
886 $parts2 = parse_url($url2);
888 if (!isset($parts1["host"]) OR !isset($parts2["host"]))
891 if ($parts1["scheme"] != $parts2["scheme"])
894 if ($parts1["host"] != $parts2["host"])
897 if ($parts1["port"] != $parts2["port"])
900 $match = $parts1["scheme"]."://".$parts1["host"];
903 $match .= ":".$parts1["port"];
905 $pathparts1 = explode("/", $parts1["path"]);
906 $pathparts2 = explode("/", $parts2["path"]);
911 $path1 = $pathparts1[$i];
912 $path2 = $pathparts2[$i];
914 if ($path1 == $path2)
917 } while (($path1 == $path2) AND ($i++ <= count($pathparts1)));
921 return normalise_link($match);