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