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