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