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