]> git.mxchange.org Git - friendica.git/blob - include/network.php
Report errors during cURL fetch
[friendica.git] / include / network.php
1 <?php
2
3
4 // curl wrapper. If binary flag is true, return binary
5 // results.
6
7 // Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
8 // to preserve cookies from one request to the next.
9 if(! function_exists('fetch_url')) {
10 function fetch_url($url,$binary = false, &$redirects = 0, $timeout = 0, $accept_content=Null, $cookiejar = 0) {
11
12         $ret = z_fetch_url(
13                 $url,
14                 $binary,
15                 $redirects,
16                 array('timeout'=>$timeout,
17                 'accept_content'=>$accept_content,
18                 'cookiejar'=>$cookiejar
19                 ));
20
21         return($ret['body']);
22 }}
23
24 if(!function_exists('z_fetch_url')){
25 /**
26  * @brief fetches an URL.
27  *
28  * @param string $url
29  *    URL to fetch
30  * @param boolean $binary default false
31  *    TRUE if asked to return binary results (file download)
32  * @param int $redirects default 0
33  *    internal use, recursion counter
34  * @param array $opts (optional parameters) assoziative array with:
35  *  * \b accept_content => supply Accept: header with 'accept_content' as the value
36  *  * \b timeout => int seconds, default system config value or 60 seconds
37  *  * \b http_auth => username:password
38  *  * \b novalidate => do not validate SSL certs, default is to validate using our CA list
39  *  * \b nobody => only return the header
40  *      * \b cookiejar => path to cookie jar file
41  *
42  * @return array an assoziative array with:
43  *  * \e int \b return_code => HTTP return code or 0 if timeout or failure
44  *  * \e boolean \b success => boolean true (if HTTP 2xx result) or false
45  *  * \e string \b header => HTTP headers
46  *  * \e string \b body => fetched content
47  */
48 function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
49
50         $ret = array('return_code' => 0, 'success' => false, 'header' => "", 'body' => "");
51
52
53         $stamp1 = microtime(true);
54
55         $a = get_app();
56
57         $ch = @curl_init($url);
58         if(($redirects > 8) || (! $ch))
59                 return false;
60
61         @curl_setopt($ch, CURLOPT_HEADER, true);
62
63         if(x($opts,"cookiejar")) {
64                 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
65                 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
66         }
67
68 //  These settings aren't needed. We're following the location already.
69 //      @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
70 //      @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
71
72         if (x($opts,'accept_content')){
73                 curl_setopt($ch,CURLOPT_HTTPHEADER, array (
74                         "Accept: " . $opts['accept_content']
75                 ));
76         }
77
78         @curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
79         @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
80
81
82
83         if(x($opts,'headers')){
84                 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
85         }
86         if(x($opts,'nobody')){
87                 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
88         }
89         if(x($opts,'timeout')){
90                 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
91         } else {
92                 $curl_time = intval(get_config('system','curl_timeout'));
93                 @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
94         }
95         // by default we will allow self-signed certs
96         // but you can override this
97
98         $check_cert = get_config('system','verifyssl');
99         @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
100         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
101
102         $prx = get_config('system','proxy');
103         if(strlen($prx)) {
104                 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
105                 @curl_setopt($ch, CURLOPT_PROXY, $prx);
106                 $prxusr = @get_config('system','proxyuser');
107                 if(strlen($prxusr))
108                         @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
109         }
110         if($binary)
111                 @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
112
113         $a->set_curl_code(0);
114
115         // don't let curl abort the entire application
116         // if it throws any errors.
117
118         $s = @curl_exec($ch);
119         if (curl_errno($ch) !== CURLE_OK) {
120                 logger('fetch_url error fetching '.$url.': '.curl_error($ch), LOGGER_NORMAL);
121         }
122
123         $base = $s;
124         $curl_info = @curl_getinfo($ch);
125
126         $http_code = $curl_info['http_code'];
127         logger('fetch_url '.$url.': '.$http_code." ".$s, LOGGER_DATA);
128         $header = '';
129
130         // Pull out multiple headers, e.g. proxy and continuation headers
131         // allow for HTTP/2.x without fixing code
132
133         while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
134                 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
135                 $header .= $chunk;
136                 $base = substr($base,strlen($chunk));
137         }
138
139         if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
140                 $new_location_info = @parse_url($curl_info["redirect_url"]);
141                 $old_location_info = @parse_url($curl_info["url"]);
142
143                 $newurl = $curl_info["redirect_url"];
144
145                 if (($new_location_info["path"] == "") AND ($new_location_info["host"] != ""))
146                         $newurl = $new_location_info["scheme"]."://".$new_location_info["host"].$old_location_info["path"];
147
148                 $matches = array();
149                 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
150                         $newurl = trim(array_pop($matches));
151                 }
152                 if(strpos($newurl,'/') === 0)
153                         $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
154                 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
155                         $redirects++;
156                         @curl_close($ch);
157                         return z_fetch_url($newurl,$binary, $redirects, $opts);
158                 }
159         }
160
161
162         $a->set_curl_code($http_code);
163         $a->set_curl_content_type($curl_info['content_type']);
164
165         $body = substr($s,strlen($header));
166         $a->set_curl_headers($header);
167
168
169
170         $rc = intval($http_code);
171         $ret['return_code'] = $rc;
172         $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
173         if(! $ret['success']) {
174                 $ret['error'] = curl_error($ch);
175                 $ret['debug'] = $curl_info;
176                 logger('z_fetch_url: error: ' . $url . ': ' . $ret['error'], LOGGER_DEBUG);
177                 logger('z_fetch_url: debug: ' . print_r($curl_info,true), LOGGER_DATA);
178         }
179         $ret['body'] = substr($s,strlen($header));
180         $ret['header'] = $header;
181         if(x($opts,'debug')) {
182                 $ret['debug'] = $curl_info;
183         }
184         @curl_close($ch);
185
186         $a->save_timestamp($stamp1, "network");
187
188         return($ret);
189
190 }}
191
192 // post request to $url. $params is an array of post variables.
193
194 if(! function_exists('post_url')) {
195 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
196         $stamp1 = microtime(true);
197
198         $a = get_app();
199         $ch = curl_init($url);
200         if(($redirects > 8) || (! $ch))
201                 return false;
202
203         logger("post_url: start ".$url, LOGGER_DATA);
204
205         curl_setopt($ch, CURLOPT_HEADER, true);
206         curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
207         curl_setopt($ch, CURLOPT_POST,1);
208         curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
209         curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
210
211         if(intval($timeout)) {
212                 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
213         }
214         else {
215                 $curl_time = intval(get_config('system','curl_timeout'));
216                 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
217         }
218
219         if(defined('LIGHTTPD')) {
220                 if(!is_array($headers)) {
221                         $headers = array('Expect:');
222                 } else {
223                         if(!in_array('Expect:', $headers)) {
224                                 array_push($headers, 'Expect:');
225                         }
226                 }
227         }
228         if($headers)
229                 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
230
231         $check_cert = get_config('system','verifyssl');
232         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
233         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
234         $prx = get_config('system','proxy');
235         if(strlen($prx)) {
236                 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
237                 curl_setopt($ch, CURLOPT_PROXY, $prx);
238                 $prxusr = get_config('system','proxyuser');
239                 if(strlen($prxusr))
240                         curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
241         }
242
243         $a->set_curl_code(0);
244
245         // don't let curl abort the entire application
246         // if it throws any errors.
247
248         $s = @curl_exec($ch);
249
250         $base = $s;
251         $curl_info = curl_getinfo($ch);
252         $http_code = $curl_info['http_code'];
253
254         logger("post_url: result ".$http_code." - ".$url, LOGGER_DATA);
255
256         $header = '';
257
258         // Pull out multiple headers, e.g. proxy and continuation headers
259         // allow for HTTP/2.x without fixing code
260
261         while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
262                 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
263                 $header .= $chunk;
264                 $base = substr($base,strlen($chunk));
265         }
266
267         if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
268                 $matches = array();
269                 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
270                 $newurl = trim(array_pop($matches));
271                 if(strpos($newurl,'/') === 0)
272                         $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
273                 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
274                         $redirects++;
275                         logger("post_url: redirect ".$url." to ".$newurl);
276                         return post_url($newurl,$params, $headers, $redirects, $timeout);
277                         //return fetch_url($newurl,false,$redirects,$timeout);
278                 }
279         }
280         $a->set_curl_code($http_code);
281         $body = substr($s,strlen($header));
282
283         $a->set_curl_headers($header);
284
285         curl_close($ch);
286
287         $a->save_timestamp($stamp1, "network");
288
289         logger("post_url: end ".$url, LOGGER_DATA);
290
291         return($body);
292 }}
293
294 // Generic XML return
295 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
296 // of $st and an optional text <message> of $message and terminates the current process.
297
298 if(! function_exists('xml_status')) {
299 function xml_status($st, $message = '') {
300
301         $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
302
303         if($st)
304                 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
305
306         header( "Content-type: text/xml" );
307         echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
308         echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
309         killme();
310 }}
311
312
313 if(! function_exists('http_status_exit')) {
314 function http_status_exit($val, $description = array()) {
315     $err = '';
316         if($val >= 400) {
317                 $err = 'Error';
318                 if (!isset($description["title"]))
319                         $description["title"] = $err." ".$val;
320         }
321         if($val >= 200 && $val < 300)
322                 $err = 'OK';
323
324         logger('http_status_exit ' . $val);
325         header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
326
327         if (isset($description["title"])) {
328                 $tpl = get_markup_template('http_status.tpl');
329                 echo replace_macros($tpl, array('$title' => $description["title"],
330                                                 '$description' => $description["description"]));
331         }
332
333         killme();
334
335 }}
336
337
338 // convert an XML document to a normalised, case-corrected array
339 // used by webfinger
340
341 if(! function_exists('convert_xml_element_to_array')) {
342 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
343
344         // If we're getting too deep, bail out
345         if ($recursion_depth > 512) {
346                 return(null);
347         }
348
349         if (!is_string($xml_element) &&
350         !is_array($xml_element) &&
351         (get_class($xml_element) == 'SimpleXMLElement')) {
352                 $xml_element_copy = $xml_element;
353                 $xml_element = get_object_vars($xml_element);
354         }
355
356         if (is_array($xml_element)) {
357                 $result_array = array();
358                 if (count($xml_element) <= 0) {
359                         return (trim(strval($xml_element_copy)));
360                 }
361
362                 foreach($xml_element as $key=>$value) {
363
364                         $recursion_depth++;
365                         $result_array[strtolower($key)] =
366                 convert_xml_element_to_array($value, $recursion_depth);
367                         $recursion_depth--;
368                 }
369                 if ($recursion_depth == 0) {
370                         $temp_array = $result_array;
371                         $result_array = array(
372                                 strtolower($xml_element_copy->getName()) => $temp_array,
373                         );
374                 }
375
376                 return ($result_array);
377
378         } else {
379                 return (trim(strval($xml_element)));
380         }
381 }}
382
383 // Given an email style address, perform webfinger lookup and
384 // return the resulting DFRN profile URL, or if no DFRN profile URL
385 // is located, returns an OStatus subscription template (prefixed
386 // with the string 'stat:' to identify it as on OStatus template).
387 // If this isn't an email style address just return $s.
388 // Return an empty string if email-style addresses but webfinger fails,
389 // or if the resultant personal XRD doesn't contain a supported
390 // subscription/friend-request attribute.
391
392 // amended 7/9/2011 to return an hcard which could save potentially loading
393 // a lengthy content page to scrape dfrn attributes
394
395 if(! function_exists('webfinger_dfrn')) {
396 function webfinger_dfrn($s,&$hcard) {
397         if(! strstr($s,'@')) {
398                 return $s;
399         }
400         $profile_link = '';
401
402         $links = webfinger($s);
403         logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
404         if(count($links)) {
405                 foreach($links as $link) {
406                         if($link['@attributes']['rel'] === NAMESPACE_DFRN)
407                                 $profile_link = $link['@attributes']['href'];
408                         if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
409                                 $profile_link = 'stat:' . $link['@attributes']['template'];
410                         if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
411                                 $hcard = $link['@attributes']['href'];
412                 }
413         }
414         return $profile_link;
415 }}
416
417 // Given an email style address, perform webfinger lookup and
418 // return the array of link attributes from the personal XRD file.
419 // On error/failure return an empty array.
420
421
422 if(! function_exists('webfinger')) {
423 function webfinger($s, $debug = false) {
424         $host = '';
425         if(strstr($s,'@')) {
426                 $host = substr($s,strpos($s,'@') + 1);
427         }
428         if(strlen($host)) {
429                 $tpl = fetch_lrdd_template($host);
430                 logger('webfinger: lrdd template: ' . $tpl);
431                 if(strlen($tpl)) {
432                         $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
433                         logger('webfinger: pxrd: ' . $pxrd);
434                         $links = fetch_xrd_links($pxrd);
435                         if(! count($links)) {
436                                 // try with double slashes
437                                 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
438                                 logger('webfinger: pxrd: ' . $pxrd);
439                                 $links = fetch_xrd_links($pxrd);
440                         }
441                         return $links;
442                 }
443         }
444         return array();
445 }}
446
447 if(! function_exists('lrdd')) {
448 function lrdd($uri, $debug = false) {
449
450         $a = get_app();
451
452         // default priority is host priority, host-meta first
453
454         $priority = 'host';
455
456         // All we have is an email address. Resource-priority is irrelevant
457         // because our URI isn't directly resolvable.
458
459         if(strstr($uri,'@')) {
460                 return(webfinger($uri));
461         }
462
463         // get the host meta file
464
465         $host = @parse_url($uri);
466
467         if($host) {
468                 $url  = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
469                 $url .= $host['host'] . '/.well-known/host-meta' ;
470         }
471         else
472                 return array();
473
474         logger('lrdd: constructed url: ' . $url);
475
476         $xml = fetch_url($url);
477
478         $headers = $a->get_curl_headers();
479
480         if (! $xml)
481                 return array();
482
483         logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
484
485         if(! stristr($xml,'<xrd'))
486                 return array();
487
488         $h = parse_xml_string($xml);
489         if(! $h)
490                 return array();
491
492         $arr = convert_xml_element_to_array($h);
493
494         if(isset($arr['xrd']['property'])) {
495                 $property = $arr['crd']['property'];
496                 if(! isset($property[0]))
497                         $properties = array($property);
498                 else
499                         $properties = $property;
500                 foreach($properties as $prop)
501                         if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
502                                 $priority = 'resource';
503         }
504
505         // save the links in case we need them
506
507         $links = array();
508
509         if(isset($arr['xrd']['link'])) {
510                 $link = $arr['xrd']['link'];
511                 if(! isset($link[0]))
512                         $links = array($link);
513                 else
514                         $links = $link;
515         }
516
517         // do we have a template or href?
518
519         if(count($links)) {
520                 foreach($links as $link) {
521                         if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
522                                 if(x($link['@attributes'],'template'))
523                                         $tpl = $link['@attributes']['template'];
524                                 elseif(x($link['@attributes'],'href'))
525                                         $href = $link['@attributes']['href'];
526                         }
527                 }
528         }
529
530         if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
531                 $tpl = '';
532
533         if($priority === 'host') {
534                 if(strlen($tpl))
535                         $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
536                 elseif(isset($href))
537                         $pxrd = $href;
538                 if(isset($pxrd)) {
539                         logger('lrdd: (host priority) pxrd: ' . $pxrd);
540                         $links = fetch_xrd_links($pxrd);
541                         return $links;
542                 }
543
544                 $lines = explode("\n",$headers);
545                 if(count($lines)) {
546                         foreach($lines as $line) {
547                                 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
548                                         return(fetch_xrd_links($matches[1]));
549                                         break;
550                                 }
551                         }
552                 }
553         }
554
555
556         // priority 'resource'
557
558
559         $html = fetch_url($uri);
560         $headers = $a->get_curl_headers();
561         logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
562
563         // don't try and parse raw xml as html
564         if(! strstr($html,'<?xml')) {
565                 require_once('library/HTML5/Parser.php');
566
567                 try {
568                         $dom = HTML5_Parser::parse($html);
569                 } catch (DOMException $e) {
570                         logger('lrdd: parse error: ' . $e);
571                 }
572
573                 if(isset($dom) && $dom) {
574                         $items = $dom->getElementsByTagName('link');
575                         foreach($items as $item) {
576                                 $x = $item->getAttribute('rel');
577                                 if($x == "lrdd") {
578                                         $pagelink = $item->getAttribute('href');
579                                         break;
580                                 }
581                         }
582                 }
583         }
584
585         if(isset($pagelink))
586                 return(fetch_xrd_links($pagelink));
587
588         // next look in HTTP headers
589
590         $lines = explode("\n",$headers);
591         if(count($lines)) {
592                 foreach($lines as $line) {
593                         /// @TODO Alter the following regex to support multiple relations (space separated)
594                         if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
595                                 $pagelink = $matches[1];
596                                 break;
597                         }
598                         // don't try and run feeds through the html5 parser
599                         if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
600                                 return array();
601                         if(stristr($html,'<rss') || stristr($html,'<feed'))
602                                 return array();
603                 }
604         }
605
606         if(isset($pagelink))
607                 return(fetch_xrd_links($pagelink));
608
609         // If we haven't found any links, return the host xrd links (which we have already fetched)
610
611         if(isset($links))
612                 return $links;
613
614         return array();
615
616 }}
617
618
619
620 // Given a host name, locate the LRDD template from that
621 // host. Returns the LRDD template or an empty string on
622 // error/failure.
623
624 if(! function_exists('fetch_lrdd_template')) {
625 function fetch_lrdd_template($host) {
626         $tpl = '';
627
628         $url1 = 'https://' . $host . '/.well-known/host-meta' ;
629         $url2 = 'http://' . $host . '/.well-known/host-meta' ;
630         $links = fetch_xrd_links($url1);
631         logger('fetch_lrdd_template from: ' . $url1);
632         logger('template (https): ' . print_r($links,true));
633         if(! count($links)) {
634                 logger('fetch_lrdd_template from: ' . $url2);
635                 $links = fetch_xrd_links($url2);
636                 logger('template (http): ' . print_r($links,true));
637         }
638         if(count($links)) {
639                 foreach($links as $link)
640                         if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd' && (!$link['@attributes']['type'] || $link['@attributes']['type'] === 'application/xrd+xml'))
641                                 $tpl = $link['@attributes']['template'];
642         }
643         if(! strpos($tpl,'{uri}'))
644                 $tpl = '';
645         return $tpl;
646 }}
647
648 // Given a URL, retrieve the page as an XRD document.
649 // Return an array of links.
650 // on error/failure return empty array.
651
652 if(! function_exists('fetch_xrd_links')) {
653 function fetch_xrd_links($url) {
654
655         $xrd_timeout = intval(get_config('system','xrd_timeout'));
656         $redirects = 0;
657         $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20), "application/xrd+xml");
658
659         logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
660
661         if ((! $xml) || (! stristr($xml,'<xrd')))
662                 return array();
663
664         // fix diaspora's bad xml
665         $xml = str_replace(array('href=&quot;','&quot;/>'),array('href="','"/>'),$xml);
666
667         $h = parse_xml_string($xml);
668         if(! $h)
669                 return array();
670
671         $arr = convert_xml_element_to_array($h);
672
673         $links = array();
674
675         if(isset($arr['xrd']['link'])) {
676                 $link = $arr['xrd']['link'];
677                 if(! isset($link[0]))
678                         $links = array($link);
679                 else
680                         $links = $link;
681         }
682         if(isset($arr['xrd']['alias'])) {
683                 $alias = $arr['xrd']['alias'];
684                 if(! isset($alias[0]))
685                         $aliases = array($alias);
686                 else
687                         $aliases = $alias;
688                 if(is_array($aliases) && count($aliases)) {
689                         foreach($aliases as $alias) {
690                                 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
691                         }
692                 }
693         }
694
695         logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
696
697         return $links;
698
699 }}
700
701
702 // Take a URL from the wild, prepend http:// if necessary
703 // and check DNS to see if it's real (or check if is a valid IP address)
704 // return true if it's OK, false if something is wrong with it
705
706 if(! function_exists('validate_url')) {
707 function validate_url(&$url) {
708
709         if(get_config('system','disable_url_validation'))
710                 return true;
711         // no naked subdomains (allow localhost for tests)
712         if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
713                 return false;
714         if(substr($url,0,4) != 'http')
715                 $url = 'http://' . $url;
716         $h = @parse_url($url);
717
718         if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
719                 return true;
720         }
721         return false;
722 }}
723
724 // checks that email is an actual resolvable internet address
725
726 if(! function_exists('validate_email')) {
727 function validate_email($addr) {
728
729         if(get_config('system','disable_email_validation'))
730                 return true;
731
732         if(! strpos($addr,'@'))
733                 return false;
734         $h = substr($addr,strpos($addr,'@') + 1);
735
736         if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
737                 return true;
738         }
739         return false;
740 }}
741
742 // Check $url against our list of allowed sites,
743 // wildcards allowed. If allowed_sites is unset return true;
744 // If url is allowed, return true.
745 // otherwise, return false
746
747 if(! function_exists('allowed_url')) {
748 function allowed_url($url) {
749
750         $h = @parse_url($url);
751
752         if(! $h) {
753                 return false;
754         }
755
756         $str_allowed = get_config('system','allowed_sites');
757         if(! $str_allowed)
758                 return true;
759
760         $found = false;
761
762         $host = strtolower($h['host']);
763
764         // always allow our own site
765
766         if($host == strtolower($_SERVER['SERVER_NAME']))
767                 return true;
768
769         $fnmatch = function_exists('fnmatch');
770         $allowed = explode(',',$str_allowed);
771
772         if(count($allowed)) {
773                 foreach($allowed as $a) {
774                         $pat = strtolower(trim($a));
775                         if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
776                                 $found = true;
777                                 break;
778                         }
779                 }
780         }
781         return $found;
782 }}
783
784 // check if email address is allowed to register here.
785 // Compare against our list (wildcards allowed).
786 // Returns false if not allowed, true if allowed or if
787 // allowed list is not configured.
788
789 if(! function_exists('allowed_email')) {
790 function allowed_email($email) {
791
792
793         $domain = strtolower(substr($email,strpos($email,'@') + 1));
794         if(! $domain)
795                 return false;
796
797         $str_allowed = get_config('system','allowed_email');
798         if(! $str_allowed)
799                 return true;
800
801         $found = false;
802
803         $fnmatch = function_exists('fnmatch');
804         $allowed = explode(',',$str_allowed);
805
806         if(count($allowed)) {
807                 foreach($allowed as $a) {
808                         $pat = strtolower(trim($a));
809                         if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
810                                 $found = true;
811                                 break;
812                         }
813                 }
814         }
815         return $found;
816 }}
817
818
819 if(! function_exists('avatar_img')) {
820 function avatar_img($email) {
821
822         $a = get_app();
823
824         $avatar['size'] = 175;
825         $avatar['email'] = $email;
826         $avatar['url'] = '';
827         $avatar['success'] = false;
828
829         call_hooks('avatar_lookup', $avatar);
830
831         if(! $avatar['success'])
832                 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
833
834         logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
835         return $avatar['url'];
836 }}
837
838
839 if(! function_exists('parse_xml_string')) {
840 function parse_xml_string($s,$strict = true) {
841         if($strict) {
842                 if(! strstr($s,'<?xml'))
843                         return false;
844                 $s2 = substr($s,strpos($s,'<?xml'));
845         }
846         else
847                 $s2 = $s;
848         libxml_use_internal_errors(true);
849
850         $x = @simplexml_load_string($s2);
851         if(! $x) {
852                 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
853                 foreach(libxml_get_errors() as $err)
854                         logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
855                 libxml_clear_errors();
856         }
857         return $x;
858 }}
859
860 function add_fcontact($arr,$update = false) {
861
862         if($update) {
863                 $r = q("UPDATE `fcontact` SET
864                         `name` = '%s',
865                         `photo` = '%s',
866                         `request` = '%s',
867                         `nick` = '%s',
868                         `addr` = '%s',
869                         `batch` = '%s',
870                         `notify` = '%s',
871                         `poll` = '%s',
872                         `confirm` = '%s',
873                         `alias` = '%s',
874                         `pubkey` = '%s',
875                         `updated` = '%s'
876                         WHERE `url` = '%s' AND `network` = '%s'",
877                         dbesc($arr['name']),
878                         dbesc($arr['photo']),
879                         dbesc($arr['request']),
880                         dbesc($arr['nick']),
881                         dbesc($arr['addr']),
882                         dbesc($arr['batch']),
883                         dbesc($arr['notify']),
884                         dbesc($arr['poll']),
885                         dbesc($arr['confirm']),
886                         dbesc($arr['alias']),
887                         dbesc($arr['pubkey']),
888                         dbesc(datetime_convert()),
889                         dbesc($arr['url']),
890                         dbesc($arr['network'])
891                 );
892         }
893         else {
894                 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
895                         `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
896                         values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
897                         dbesc($arr['url']),
898                         dbesc($arr['name']),
899                         dbesc($arr['photo']),
900                         dbesc($arr['request']),
901                         dbesc($arr['nick']),
902                         dbesc($arr['addr']),
903                         dbesc($arr['batch']),
904                         dbesc($arr['notify']),
905                         dbesc($arr['poll']),
906                         dbesc($arr['confirm']),
907                         dbesc($arr['network']),
908                         dbesc($arr['alias']),
909                         dbesc($arr['pubkey']),
910                         dbesc(datetime_convert())
911                 );
912         }
913
914         return $r;
915 }
916
917
918 function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
919
920         // Suppress "view full size"
921         if (intval(get_config('system','no_view_full_size')))
922                 $include_link = false;
923
924         $a = get_app();
925
926         // Picture addresses can contain special characters
927         $s = htmlspecialchars_decode($srctext);
928
929         $matches = null;
930         $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
931         if($c) {
932                 require_once('include/Photo.php');
933                 foreach($matches as $mtch) {
934                         logger('scale_external_image: ' . $mtch[1]);
935
936                         $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
937                         if(stristr($mtch[1],$hostname))
938                                 continue;
939
940                         // $scale_replace, if passed, is an array of two elements. The
941                         // first is the name of the full-size image. The second is the
942                         // name of a remote, scaled-down version of the full size image.
943                         // This allows Friendica to display the smaller remote image if
944                         // one exists, while still linking to the full-size image
945                         if($scale_replace)
946                                 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
947                         else
948                                 $scaled = $mtch[1];
949                         $i = @fetch_url($scaled);
950                         if(! $i)
951                                 return $srctext;
952
953                         // guess mimetype from headers or filename
954                         $type = guess_image_type($mtch[1],true);
955
956                         if($i) {
957                                 $ph = new Photo($i, $type);
958                                 if($ph->is_valid()) {
959                                         $orig_width = $ph->getWidth();
960                                         $orig_height = $ph->getHeight();
961
962                                         if($orig_width > 640 || $orig_height > 640) {
963
964                                                 $ph->scaleImage(640);
965                                                 $new_width = $ph->getWidth();
966                                                 $new_height = $ph->getHeight();
967                                                 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
968                                                 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
969                                                         . "\n" . (($include_link)
970                                                                 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
971                                                                 : ''),$s);
972                                                 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
973                                         }
974                                 }
975                         }
976                 }
977         }
978
979         // replace the special char encoding
980         $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
981         return $s;
982 }
983
984
985 function fix_contact_ssl_policy(&$contact,$new_policy) {
986
987         $ssl_changed = false;
988         if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
989                 $ssl_changed = true;
990                 $contact['url']     =   str_replace('https:','http:',$contact['url']);
991                 $contact['request'] =   str_replace('https:','http:',$contact['request']);
992                 $contact['notify']  =   str_replace('https:','http:',$contact['notify']);
993                 $contact['poll']    =   str_replace('https:','http:',$contact['poll']);
994                 $contact['confirm'] =   str_replace('https:','http:',$contact['confirm']);
995                 $contact['poco']    =   str_replace('https:','http:',$contact['poco']);
996         }
997
998         if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
999                 $ssl_changed = true;
1000                 $contact['url']     =   str_replace('http:','https:',$contact['url']);
1001                 $contact['request'] =   str_replace('http:','https:',$contact['request']);
1002                 $contact['notify']  =   str_replace('http:','https:',$contact['notify']);
1003                 $contact['poll']    =   str_replace('http:','https:',$contact['poll']);
1004                 $contact['confirm'] =   str_replace('http:','https:',$contact['confirm']);
1005                 $contact['poco']    =   str_replace('http:','https:',$contact['poco']);
1006         }
1007
1008         if($ssl_changed) {
1009                 q("update contact set
1010                         url = '%s',
1011                         request = '%s',
1012                         notify = '%s',
1013                         poll = '%s',
1014                         confirm = '%s',
1015                         poco = '%s'
1016                         where id = %d limit 1",
1017                         dbesc($contact['url']),
1018                         dbesc($contact['request']),
1019                         dbesc($contact['notify']),
1020                         dbesc($contact['poll']),
1021                         dbesc($contact['confirm']),
1022                         dbesc($contact['poco']),
1023                         intval($contact['id'])
1024                 );
1025         }
1026 }
1027
1028
1029
1030 /**
1031  * xml2array() will convert the given XML text to an array in the XML structure.
1032  * Link: http://www.bin-co.com/php/scripts/xml2array/
1033  * Portions significantly re-written by mike@macgirvin.com for Friendica (namespaces, lowercase tags, get_attribute default changed, more...)
1034  * Arguments : $contents - The XML text
1035  *                $namespaces - true or false include namespace information in the returned array as array elements.
1036  *                $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value.
1037  *                $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
1038  * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
1039  * Examples: $array =  xml2array(file_get_contents('feed.xml'));
1040  *              $array =  xml2array(file_get_contents('feed.xml', true, 1, 'attribute'));
1041  */
1042
1043 function xml2array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
1044     if(!$contents) return array();
1045
1046     if(!function_exists('xml_parser_create')) {
1047         logger('xml2array: parser function missing');
1048         return array();
1049     }
1050
1051
1052         libxml_use_internal_errors(true);
1053         libxml_clear_errors();
1054
1055         if($namespaces)
1056             $parser = @xml_parser_create_ns("UTF-8",':');
1057         else
1058             $parser = @xml_parser_create();
1059
1060         if(! $parser) {
1061                 logger('xml2array: xml_parser_create: no resource');
1062                 return array();
1063         }
1064
1065     xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
1066         // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
1067     xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
1068     xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
1069     @xml_parse_into_struct($parser, trim($contents), $xml_values);
1070     @xml_parser_free($parser);
1071
1072     if(! $xml_values) {
1073                 logger('xml2array: libxml: parse error: ' . $contents, LOGGER_DATA);
1074                 foreach(libxml_get_errors() as $err)
1075                         logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
1076                 libxml_clear_errors();
1077                 return;
1078         }
1079
1080     //Initializations
1081     $xml_array = array();
1082     $parents = array();
1083     $opened_tags = array();
1084     $arr = array();
1085
1086     $current = &$xml_array; // Reference
1087
1088     // Go through the tags.
1089     $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
1090     foreach($xml_values as $data) {
1091         unset($attributes,$value); // Remove existing values, or there will be trouble
1092
1093         // This command will extract these variables into the foreach scope
1094         // tag(string), type(string), level(int), attributes(array).
1095         extract($data); // We could use the array by itself, but this cooler.
1096
1097         $result = array();
1098         $attributes_data = array();
1099
1100         if(isset($value)) {
1101             if($priority == 'tag') $result = $value;
1102             else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
1103         }
1104
1105         //Set the attributes too.
1106         if(isset($attributes) and $get_attributes) {
1107             foreach($attributes as $attr => $val) {
1108                 if($priority == 'tag') $attributes_data[$attr] = $val;
1109                 else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
1110             }
1111         }
1112
1113         // See tag status and do the needed.
1114                 if($namespaces && strpos($tag,':')) {
1115                         $namespc = substr($tag,0,strrpos($tag,':'));
1116                         $tag = strtolower(substr($tag,strlen($namespc)+1));
1117                         $result['@namespace'] = $namespc;
1118                 }
1119                 $tag = strtolower($tag);
1120
1121                 if($type == "open") {   // The starting of the tag '<tag>'
1122             $parent[$level-1] = &$current;
1123             if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
1124                 $current[$tag] = $result;
1125                 if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
1126                 $repeated_tag_index[$tag.'_'.$level] = 1;
1127
1128                 $current = &$current[$tag];
1129
1130             } else { // There was another element with the same tag name
1131
1132                 if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
1133                     $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1134                     $repeated_tag_index[$tag.'_'.$level]++;
1135                 } else { // This section will make the value an array if multiple tags with the same name appear together
1136                     $current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
1137                     $repeated_tag_index[$tag.'_'.$level] = 2;
1138
1139                     if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1140                         $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1141                         unset($current[$tag.'_attr']);
1142                     }
1143
1144                 }
1145                 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
1146                 $current = &$current[$tag][$last_item_index];
1147             }
1148
1149         } elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
1150             //See if the key is already taken.
1151             if(!isset($current[$tag])) { //New Key
1152                 $current[$tag] = $result;
1153                 $repeated_tag_index[$tag.'_'.$level] = 1;
1154                 if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
1155
1156             } else { // If taken, put all things inside a list(array)
1157                 if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
1158
1159                     // ...push the new element into that array.
1160                     $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1161
1162                     if($priority == 'tag' and $get_attributes and $attributes_data) {
1163                         $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1164                     }
1165                     $repeated_tag_index[$tag.'_'.$level]++;
1166
1167                 } else { // If it is not an array...
1168                     $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
1169                     $repeated_tag_index[$tag.'_'.$level] = 1;
1170                     if($priority == 'tag' and $get_attributes) {
1171                         if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1172
1173                             $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1174                             unset($current[$tag.'_attr']);
1175                         }
1176
1177                         if($attributes_data) {
1178                             $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1179                         }
1180                     }
1181                     $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
1182                 }
1183             }
1184
1185         } elseif($type == 'close') { // End of tag '</tag>'
1186             $current = &$parent[$level-1];
1187         }
1188     }
1189
1190     return($xml_array);
1191 }
1192
1193 function original_url($url, $depth=1, $fetchbody = false) {
1194
1195         $a = get_app();
1196
1197         // Remove Analytics Data from Google and other tracking platforms
1198         $urldata = parse_url($url);
1199         if (is_string($urldata["query"])) {
1200                 $query = $urldata["query"];
1201                 parse_str($query, $querydata);
1202
1203                 if (is_array($querydata))
1204                         foreach ($querydata AS $param=>$value)
1205                                 if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
1206                                                         "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
1207                                                         "fb_action_ids", "fb_action_types", "fb_ref",
1208                                                         "awesm", "wtrid",
1209                                                         "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) {
1210
1211                                         $pair = $param."=".urlencode($value);
1212                                         $url = str_replace($pair, "", $url);
1213
1214                                         // Second try: if the url isn't encoded completely
1215                                         $pair = $param."=".str_replace(" ", "+", $value);
1216                                         $url = str_replace($pair, "", $url);
1217
1218                                         // Third try: Maybey the url isn't encoded at all
1219                                         $pair = $param."=".$value;
1220                                         $url = str_replace($pair, "", $url);
1221
1222                                         $url = str_replace(array("?&", "&&"), array("?", ""), $url);
1223                                 }
1224
1225                 if (substr($url, -1, 1) == "?")
1226                         $url = substr($url, 0, -1);
1227         }
1228
1229         if ($depth > 10)
1230                 return($url);
1231
1232         $url = trim($url, "'");
1233
1234         $stamp1 = microtime(true);
1235
1236         $siteinfo = array();
1237         $ch = curl_init();
1238         curl_setopt($ch, CURLOPT_URL, $url);
1239         curl_setopt($ch, CURLOPT_HEADER, 1);
1240         curl_setopt($ch, CURLOPT_NOBODY, 1);
1241         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
1242         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1243         curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
1244
1245         $header = curl_exec($ch);
1246         $curl_info = @curl_getinfo($ch);
1247         $http_code = $curl_info['http_code'];
1248         curl_close($ch);
1249
1250         $a->save_timestamp($stamp1, "network");
1251
1252         if ($http_code == 0)
1253                 return($url);
1254
1255         if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
1256                 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
1257                 if ($curl_info['redirect_url'] != "")
1258                         return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
1259                 else
1260                         return(original_url($curl_info['location'], ++$depth, $fetchbody));
1261         }
1262
1263         // Check for redirects in the meta elements of the body if there are no redirects in the header.
1264         if (!$fetchbody)
1265                 return(original_url($url, ++$depth, true));
1266
1267         // if the file is too large then exit
1268         if ($curl_info["download_content_length"] > 1000000)
1269                 return($url);
1270
1271         // if it isn't a HTML file then exit
1272         if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
1273                 return($url);
1274
1275         $stamp1 = microtime(true);
1276
1277         $ch = curl_init();
1278         curl_setopt($ch, CURLOPT_URL, $url);
1279         curl_setopt($ch, CURLOPT_HEADER, 0);
1280         curl_setopt($ch, CURLOPT_NOBODY, 0);
1281         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
1282         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1283         curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
1284
1285         $body = curl_exec($ch);
1286         curl_close($ch);
1287
1288         $a->save_timestamp($stamp1, "network");
1289
1290         if (trim($body) == "")
1291                 return($url);
1292
1293         // Check for redirect in meta elements
1294         $doc = new DOMDocument();
1295         @$doc->loadHTML($body);
1296
1297         $xpath = new DomXPath($doc);
1298
1299         $list = $xpath->query("//meta[@content]");
1300         foreach ($list as $node) {
1301                 $attr = array();
1302                 if ($node->attributes->length)
1303                         foreach ($node->attributes as $attribute)
1304                                 $attr[$attribute->name] = $attribute->value;
1305
1306                 if (@$attr["http-equiv"] == 'refresh') {
1307                         $path = $attr["content"];
1308                         $pathinfo = explode(";", $path);
1309                         $content = "";
1310                         foreach ($pathinfo AS $value)
1311                                 if (substr(strtolower($value), 0, 4) == "url=")
1312                                         return(original_url(substr($value, 4), ++$depth));
1313                 }
1314         }
1315
1316         return($url);
1317 }
1318
1319 if (!function_exists('short_link')) {
1320 function short_link($url) {
1321         require_once('library/slinky.php');
1322         $slinky = new Slinky($url);
1323         $yourls_url = get_config('yourls','url1');
1324         if ($yourls_url) {
1325                 $yourls_username = get_config('yourls','username1');
1326                 $yourls_password = get_config('yourls', 'password1');
1327                 $yourls_ssl = get_config('yourls', 'ssl1');
1328                 $yourls = new Slinky_YourLS();
1329                 $yourls->set('username', $yourls_username);
1330                 $yourls->set('password', $yourls_password);
1331                 $yourls->set('ssl', $yourls_ssl);
1332                 $yourls->set('yourls-url', $yourls_url);
1333                 $slinky->set_cascade( array($yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1334         } else {
1335                 // setup a cascade of shortening services
1336                 // try to get a short link from these services
1337                 // in the order ur1.ca, trim, id.gd, tinyurl
1338                 $slinky->set_cascade(array(new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1339         }
1340         return $slinky->short();
1341 }};