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)) {
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));
123 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
126 $prx = get_config('system','proxy');
128 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
129 @curl_setopt($ch, CURLOPT_PROXY, $prx);
130 $prxusr = @get_config('system','proxyuser');
132 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
135 @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
137 $a->set_curl_code(0);
139 // don't let curl abort the entire application
140 // if it throws any errors.
142 $s = @curl_exec($ch);
143 if (curl_errno($ch) !== CURLE_OK) {
144 logger('fetch_url error fetching '.$url.': '.curl_error($ch), LOGGER_NORMAL);
147 $ret['errno'] = curl_errno($ch);
150 $curl_info = @curl_getinfo($ch);
152 $http_code = $curl_info['http_code'];
153 logger('fetch_url '.$url.': '.$http_code." ".$s, LOGGER_DATA);
156 // Pull out multiple headers, e.g. proxy and continuation headers
157 // allow for HTTP/2.x without fixing code
159 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
160 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
162 $base = substr($base,strlen($chunk));
165 $a->set_curl_code($http_code);
166 $a->set_curl_content_type($curl_info['content_type']);
167 $a->set_curl_headers($header);
169 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
170 $new_location_info = @parse_url($curl_info["redirect_url"]);
171 $old_location_info = @parse_url($curl_info["url"]);
173 $newurl = $curl_info["redirect_url"];
175 if (($new_location_info["path"] == "") AND ($new_location_info["host"] != ""))
176 $newurl = $new_location_info["scheme"]."://".$new_location_info["host"].$old_location_info["path"];
179 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
180 $newurl = trim(array_pop($matches));
182 if(strpos($newurl,'/') === 0)
183 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
184 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
187 return z_fetch_url($newurl,$binary, $redirects, $opts);
192 $a->set_curl_code($http_code);
193 $a->set_curl_content_type($curl_info['content_type']);
195 $body = substr($s,strlen($header));
199 $rc = intval($http_code);
200 $ret['return_code'] = $rc;
201 $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
202 $ret['redirect_url'] = $url;
203 if(! $ret['success']) {
204 $ret['error'] = curl_error($ch);
205 $ret['debug'] = $curl_info;
206 logger('z_fetch_url: error: ' . $url . ': ' . $ret['error'], LOGGER_DEBUG);
207 logger('z_fetch_url: debug: ' . print_r($curl_info,true), LOGGER_DATA);
209 $ret['body'] = substr($s,strlen($header));
210 $ret['header'] = $header;
211 if(x($opts,'debug')) {
212 $ret['debug'] = $curl_info;
216 $a->save_timestamp($stamp1, "network");
222 // post request to $url. $params is an array of post variables.
225 * @brief Post request to $url
227 * @param string $url URL to post
228 * @param mixed $params
229 * @param string $headers HTTP headers
230 * @param integer $redirects Recursion counter for internal use - default = 0
231 * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
233 * @return string The content
235 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
236 $stamp1 = microtime(true);
239 $ch = curl_init($url);
240 if(($redirects > 8) || (! $ch))
243 logger("post_url: start ".$url, LOGGER_DATA);
245 curl_setopt($ch, CURLOPT_HEADER, true);
246 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
247 curl_setopt($ch, CURLOPT_POST,1);
248 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
249 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
251 if(intval($timeout)) {
252 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
255 $curl_time = intval(get_config('system','curl_timeout'));
256 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
259 if(defined('LIGHTTPD')) {
260 if(!is_array($headers)) {
261 $headers = array('Expect:');
263 if(!in_array('Expect:', $headers)) {
264 array_push($headers, 'Expect:');
269 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
271 $check_cert = get_config('system','verifyssl');
272 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
274 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
276 $prx = get_config('system','proxy');
278 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
279 curl_setopt($ch, CURLOPT_PROXY, $prx);
280 $prxusr = get_config('system','proxyuser');
282 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
285 $a->set_curl_code(0);
287 // don't let curl abort the entire application
288 // if it throws any errors.
290 $s = @curl_exec($ch);
293 $curl_info = curl_getinfo($ch);
294 $http_code = $curl_info['http_code'];
296 logger("post_url: result ".$http_code." - ".$url, LOGGER_DATA);
300 // Pull out multiple headers, e.g. proxy and continuation headers
301 // allow for HTTP/2.x without fixing code
303 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
304 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
306 $base = substr($base,strlen($chunk));
309 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
311 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
312 $newurl = trim(array_pop($matches));
313 if(strpos($newurl,'/') === 0)
314 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
315 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
317 logger("post_url: redirect ".$url." to ".$newurl);
318 return post_url($newurl,$params, $headers, $redirects, $timeout);
319 //return fetch_url($newurl,false,$redirects,$timeout);
322 $a->set_curl_code($http_code);
323 $body = substr($s,strlen($header));
325 $a->set_curl_headers($header);
329 $a->save_timestamp($stamp1, "network");
331 logger("post_url: end ".$url, LOGGER_DATA);
336 // Generic XML return
337 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
338 // of $st and an optional text <message> of $message and terminates the current process.
340 function xml_status($st, $message = '') {
342 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
345 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
347 header( "Content-type: text/xml" );
348 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
349 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
354 * @brief Send HTTP status header and exit.
356 * @param integer $val HTTP status result value
357 * @param array $description optional message
358 * 'title' => header title
359 * 'description' => optional message
363 * @brief Send HTTP status header and exit.
365 * @param integer $val HTTP status result value
366 * @param array $description optional message
367 * 'title' => header title
368 * 'description' => optional message
370 function http_status_exit($val, $description = array()) {
374 if (!isset($description["title"]))
375 $description["title"] = $err." ".$val;
377 if($val >= 200 && $val < 300)
380 logger('http_status_exit ' . $val);
381 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
383 if (isset($description["title"])) {
384 $tpl = get_markup_template('http_status.tpl');
385 echo replace_macros($tpl, array('$title' => $description["title"],
386 '$description' => $description["description"]));
394 * @brief Check URL to se if ts's real
396 * Take a URL from the wild, prepend http:// if necessary
397 * and check DNS to see if it's real (or check if is a valid IP address)
399 * @param string $url The URL to be validated
400 * @return boolean True if it's a valid URL, fals if something wrong with it
402 function validate_url(&$url) {
403 if(get_config('system','disable_url_validation'))
406 // no naked subdomains (allow localhost for tests)
407 if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
410 if(substr($url,0,4) != 'http')
411 $url = 'http://' . $url;
413 /// @TODO Really supress function outcomes? Why not find them + debug them?
414 $h = @parse_url($url);
416 if((is_array($h)) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
424 * @brief Checks that email is an actual resolvable internet address
426 * @param string $addr The email address
427 * @return boolean True if it's a valid email address, false if it's not
429 function validate_email($addr) {
431 if(get_config('system','disable_email_validation'))
434 if(! strpos($addr,'@'))
436 $h = substr($addr,strpos($addr,'@') + 1);
438 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
445 * @brief Check if URL is allowed
447 * Check $url against our list of allowed sites,
448 * wildcards allowed. If allowed_sites is unset return true;
450 * @param string $url URL which get tested
451 * @return boolean True if url is allowed otherwise return false
453 function allowed_url($url) {
455 $h = @parse_url($url);
461 $str_allowed = get_config('system','allowed_sites');
467 $host = strtolower($h['host']);
469 // always allow our own site
471 if($host == strtolower($_SERVER['SERVER_NAME']))
474 $fnmatch = function_exists('fnmatch');
475 $allowed = explode(',',$str_allowed);
477 if(count($allowed)) {
478 foreach($allowed as $a) {
479 $pat = strtolower(trim($a));
480 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
490 * @brief Check if email address is allowed to register here.
492 * Compare against our list (wildcards allowed).
495 * @return boolean False if not allowed, true if allowed
496 * or if allowed list is not configured
498 function allowed_email($email) {
501 $domain = strtolower(substr($email,strpos($email,'@') + 1));
505 $str_allowed = get_config('system','allowed_email');
511 $fnmatch = function_exists('fnmatch');
512 $allowed = explode(',',$str_allowed);
514 if(count($allowed)) {
515 foreach($allowed as $a) {
516 $pat = strtolower(trim($a));
517 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
526 function avatar_img($email) {
528 $avatar['size'] = 175;
529 $avatar['email'] = $email;
531 $avatar['success'] = false;
533 call_hooks('avatar_lookup', $avatar);
535 if (! $avatar['success']) {
536 $avatar['url'] = App::get_baseurl() . '/images/person-175.jpg';
539 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
540 return $avatar['url'];
544 function parse_xml_string($s,$strict = true) {
545 /// @todo Move this function to the xml class
547 if(! strstr($s,'<?xml'))
549 $s2 = substr($s,strpos($s,'<?xml'));
553 libxml_use_internal_errors(true);
555 $x = @simplexml_load_string($s2);
557 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
558 foreach (libxml_get_errors() as $err) {
559 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
561 libxml_clear_errors();
566 function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
568 // Suppress "view full size"
569 if (intval(get_config('system','no_view_full_size'))) {
570 $include_link = false;
575 // Picture addresses can contain special characters
576 $s = htmlspecialchars_decode($srctext);
579 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
581 require_once('include/Photo.php');
582 foreach ($matches as $mtch) {
583 logger('scale_external_image: ' . $mtch[1]);
585 $hostname = str_replace('www.','',substr(App::get_baseurl(),strpos(App::get_baseurl(),'://')+3));
586 if (stristr($mtch[1],$hostname)) {
590 // $scale_replace, if passed, is an array of two elements. The
591 // first is the name of the full-size image. The second is the
592 // name of a remote, scaled-down version of the full size image.
593 // This allows Friendica to display the smaller remote image if
594 // one exists, while still linking to the full-size image
595 if ($scale_replace) {
596 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
600 $i = fetch_url($scaled);
605 // guess mimetype from headers or filename
606 $type = guess_image_type($mtch[1],true);
609 $ph = new Photo($i, $type);
610 if ($ph->is_valid()) {
611 $orig_width = $ph->getWidth();
612 $orig_height = $ph->getHeight();
614 if ($orig_width > 640 || $orig_height > 640) {
616 $ph->scaleImage(640);
617 $new_width = $ph->getWidth();
618 $new_height = $ph->getHeight();
619 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
620 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
621 . "\n" . (($include_link)
622 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
624 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
631 // replace the special char encoding
632 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
637 function fix_contact_ssl_policy(&$contact,$new_policy) {
639 $ssl_changed = false;
640 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
642 $contact['url'] = str_replace('https:','http:',$contact['url']);
643 $contact['request'] = str_replace('https:','http:',$contact['request']);
644 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
645 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
646 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
647 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
650 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
652 $contact['url'] = str_replace('http:','https:',$contact['url']);
653 $contact['request'] = str_replace('http:','https:',$contact['request']);
654 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
655 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
656 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
657 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
661 q("UPDATE `contact` SET
668 WHERE `id` = %d LIMIT 1",
669 dbesc($contact['url']),
670 dbesc($contact['request']),
671 dbesc($contact['notify']),
672 dbesc($contact['poll']),
673 dbesc($contact['confirm']),
674 dbesc($contact['poco']),
675 intval($contact['id'])
681 * @brief Remove Google Analytics and other tracking platforms params from URL
683 * @param string $url Any user-submitted URL that may contain tracking params
684 * @return string The same URL stripped of tracking parameters
686 function strip_tracking_query_params($url)
688 $urldata = parse_url($url);
689 if (is_string($urldata["query"])) {
690 $query = $urldata["query"];
691 parse_str($query, $querydata);
693 if (is_array($querydata)) {
694 foreach ($querydata AS $param => $value) {
695 if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
696 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
697 "fb_action_ids", "fb_action_types", "fb_ref",
699 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) {
701 $pair = $param . "=" . urlencode($value);
702 $url = str_replace($pair, "", $url);
704 // Second try: if the url isn't encoded completely
705 $pair = $param . "=" . str_replace(" ", "+", $value);
706 $url = str_replace($pair, "", $url);
708 // Third try: Maybey the url isn't encoded at all
709 $pair = $param . "=" . $value;
710 $url = str_replace($pair, "", $url);
712 $url = str_replace(array("?&", "&&"), array("?", ""), $url);
717 if (substr($url, -1, 1) == "?") {
718 $url = substr($url, 0, -1);
726 * @brief Returns the original URL of the provided URL
728 * This function strips tracking query params and follows redirections, either
729 * through HTTP code or meta refresh tags. Stops after 10 redirections.
731 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
733 * @see ParseUrl::getSiteinfo
735 * @param string $url A user-submitted URL
736 * @param int $depth The current redirection recursion level (internal)
737 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
738 * @return string A canonical URL
740 function original_url($url, $depth = 1, $fetchbody = false) {
743 $url = strip_tracking_query_params($url);
748 $url = trim($url, "'");
750 $stamp1 = microtime(true);
754 curl_setopt($ch, CURLOPT_URL, $url);
755 curl_setopt($ch, CURLOPT_HEADER, 1);
756 curl_setopt($ch, CURLOPT_NOBODY, 1);
757 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
758 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
759 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
761 $header = curl_exec($ch);
762 $curl_info = @curl_getinfo($ch);
763 $http_code = $curl_info['http_code'];
766 $a->save_timestamp($stamp1, "network");
771 if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
772 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
773 if ($curl_info['redirect_url'] != "")
774 return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
776 return(original_url($curl_info['location'], ++$depth, $fetchbody));
779 // Check for redirects in the meta elements of the body if there are no redirects in the header.
781 return(original_url($url, ++$depth, true));
783 // if the file is too large then exit
784 if ($curl_info["download_content_length"] > 1000000)
787 // if it isn't a HTML file then exit
788 if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
791 $stamp1 = microtime(true);
794 curl_setopt($ch, CURLOPT_URL, $url);
795 curl_setopt($ch, CURLOPT_HEADER, 0);
796 curl_setopt($ch, CURLOPT_NOBODY, 0);
797 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
798 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
799 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
801 $body = curl_exec($ch);
804 $a->save_timestamp($stamp1, "network");
806 if (trim($body) == "")
809 // Check for redirect in meta elements
810 $doc = new DOMDocument();
811 @$doc->loadHTML($body);
813 $xpath = new DomXPath($doc);
815 $list = $xpath->query("//meta[@content]");
816 foreach ($list as $node) {
818 if ($node->attributes->length)
819 foreach ($node->attributes as $attribute)
820 $attr[$attribute->name] = $attribute->value;
822 if (@$attr["http-equiv"] == 'refresh') {
823 $path = $attr["content"];
824 $pathinfo = explode(";", $path);
826 foreach ($pathinfo AS $value)
827 if (substr(strtolower($value), 0, 4) == "url=")
828 return(original_url(substr($value, 4), ++$depth));
835 function short_link($url) {
836 require_once('library/slinky.php');
837 $slinky = new Slinky($url);
838 $yourls_url = get_config('yourls','url1');
840 $yourls_username = get_config('yourls','username1');
841 $yourls_password = get_config('yourls', 'password1');
842 $yourls_ssl = get_config('yourls', 'ssl1');
843 $yourls = new Slinky_YourLS();
844 $yourls->set('username', $yourls_username);
845 $yourls->set('password', $yourls_password);
846 $yourls->set('ssl', $yourls_ssl);
847 $yourls->set('yourls-url', $yourls_url);
848 $slinky->set_cascade(array($yourls, new Slinky_Ur1ca(), new Slinky_TinyURL()));
850 // setup a cascade of shortening services
851 // try to get a short link from these services
852 // in the order ur1.ca, tinyurl
853 $slinky->set_cascade(array(new Slinky_Ur1ca(), new Slinky_TinyURL()));
855 return $slinky->short();
859 * @brief Encodes content to json
861 * This function encodes an array to json format
862 * and adds an application/json HTTP header to the output.
863 * After finishing the process is getting killed.
865 * @param array $x The input content
867 function json_return_and_die($x) {
868 header("content-type: application/json");
869 echo json_encode($x);
874 * @brief Find the matching part between two url
876 * @param string $url1
877 * @param string $url2
878 * @return string The matching part
880 function matching_url($url1, $url2) {
882 if (($url1 == "") OR ($url2 == ""))
885 $url1 = normalise_link($url1);
886 $url2 = normalise_link($url2);
888 $parts1 = parse_url($url1);
889 $parts2 = parse_url($url2);
891 if (!isset($parts1["host"]) OR !isset($parts2["host"]))
894 if ($parts1["scheme"] != $parts2["scheme"])
897 if ($parts1["host"] != $parts2["host"])
900 if ($parts1["port"] != $parts2["port"])
903 $match = $parts1["scheme"]."://".$parts1["host"];
906 $match .= ":".$parts1["port"];
908 $pathparts1 = explode("/", $parts1["path"]);
909 $pathparts2 = explode("/", $parts2["path"]);
914 $path1 = $pathparts1[$i];
915 $path2 = $pathparts2[$i];
917 if ($path1 == $path2)
920 } while (($path1 == $path2) AND ($i++ <= count($pathparts1)));
924 return normalise_link($match);