]> git.mxchange.org Git - friendica.git/blob - include/network.php
Opps, this has vanished by accident, thanks to @annando
[friendica.git] / include / network.php
1 <?php
2
3 /**
4  * @file include/network.php
5  */
6
7 require_once("include/xml.php");
8 require_once('include/Probe.php');
9
10 /**
11  * @brief Curl wrapper
12  * 
13  * If binary flag is true, return binary results.
14  * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
15  * to preserve cookies from one request to the next.
16  * 
17  * @param string $url URL to fetch
18  * @param boolean $binary default false
19  *    TRUE if asked to return binary results (file download)
20  * @param integer $redirects The recursion counter for internal use - default 0
21  * @param integer $timeout Timeout in seconds, default system config value or 60 seconds
22  * @param string $accept_content supply Accept: header with 'accept_content' as the value
23  * @param string $cookiejar Path to cookie jar file
24  * 
25  * @return string The fetched content
26  */
27 function fetch_url($url,$binary = false, &$redirects = 0, $timeout = 0, $accept_content=Null, $cookiejar = 0) {
28
29         $ret = z_fetch_url(
30                 $url,
31                 $binary,
32                 $redirects,
33                 array('timeout'=>$timeout,
34                 'accept_content'=>$accept_content,
35                 'cookiejar'=>$cookiejar
36                 ));
37
38         return($ret['body']);
39 }
40
41 /**
42  * @brief fetches an URL.
43  *
44  * @param string $url URL to fetch
45  * @param boolean $binary default false
46  *    TRUE if asked to return binary results (file download)
47  * @param int $redirects The recursion counter for internal use - default 0
48  * @param array $opts (optional parameters) assoziative array with:
49  *    'accept_content' => supply Accept: header with 'accept_content' as the value
50  *    'timeout' => int Timeout in seconds, default system config value or 60 seconds
51  *    'http_auth' => username:password
52  *    'novalidate' => do not validate SSL certs, default is to validate using our CA list
53  *    'nobody' => only return the header
54  *    'cookiejar' => path to cookie jar file
55  *
56  * @return array an assoziative array with:
57  *    int 'return_code' => HTTP return code or 0 if timeout or failure
58  *    boolean 'success' => boolean true (if HTTP 2xx result) or false
59  *    string 'redirect_url' => in case of redirect, content was finally retrieved from this URL
60  *    string 'header' => HTTP headers
61  *    string 'body' => fetched content
62  */
63 function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
64
65         $ret = array('return_code' => 0, 'success' => false, 'header' => "", 'body' => "");
66
67
68         $stamp1 = microtime(true);
69
70         $a = get_app();
71
72         $ch = @curl_init($url);
73         if(($redirects > 8) || (! $ch))
74                 return false;
75
76         @curl_setopt($ch, CURLOPT_HEADER, true);
77
78         if(x($opts,"cookiejar")) {
79                 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
80                 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
81         }
82
83 // These settings aren't needed. We're following the location already.
84 //      @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
85 //      @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
86
87         if (x($opts,'accept_content')){
88                 curl_setopt($ch,CURLOPT_HTTPHEADER, array (
89                         "Accept: " . $opts['accept_content']
90                 ));
91         }
92
93         @curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
94         @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
95
96
97
98         if(x($opts,'headers')){
99                 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
100         }
101         if(x($opts,'nobody')){
102                 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
103         }
104         if(x($opts,'timeout')){
105                 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
106         } else {
107                 $curl_time = intval(get_config('system','curl_timeout'));
108                 @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
109         }
110
111         // by default we will allow self-signed certs
112         // but you can override this
113
114         $check_cert = get_config('system','verifyssl');
115         @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
116         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
117
118         $prx = get_config('system','proxy');
119         if(strlen($prx)) {
120                 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
121                 @curl_setopt($ch, CURLOPT_PROXY, $prx);
122                 $prxusr = @get_config('system','proxyuser');
123                 if(strlen($prxusr))
124                         @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
125         }
126         if($binary)
127                 @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
128
129         $a->set_curl_code(0);
130
131         // don't let curl abort the entire application
132         // if it throws any errors.
133
134         $s = @curl_exec($ch);
135         if (curl_errno($ch) !== CURLE_OK) {
136                 logger('fetch_url error fetching '.$url.': '.curl_error($ch), LOGGER_NORMAL);
137         }
138
139         $base = $s;
140         $curl_info = @curl_getinfo($ch);
141
142         $http_code = $curl_info['http_code'];
143         logger('fetch_url '.$url.': '.$http_code." ".$s, LOGGER_DATA);
144         $header = '';
145
146         // Pull out multiple headers, e.g. proxy and continuation headers
147         // allow for HTTP/2.x without fixing code
148
149         while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
150                 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
151                 $header .= $chunk;
152                 $base = substr($base,strlen($chunk));
153         }
154
155         $a->set_curl_code($http_code);
156         $a->set_curl_content_type($curl_info['content_type']);
157         $a->set_curl_headers($header);
158
159         if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
160                 $new_location_info = @parse_url($curl_info["redirect_url"]);
161                 $old_location_info = @parse_url($curl_info["url"]);
162
163                 $newurl = $curl_info["redirect_url"];
164
165                 if (($new_location_info["path"] == "") AND ($new_location_info["host"] != ""))
166                         $newurl = $new_location_info["scheme"]."://".$new_location_info["host"].$old_location_info["path"];
167
168                 $matches = array();
169                 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
170                         $newurl = trim(array_pop($matches));
171                 }
172                 if(strpos($newurl,'/') === 0)
173                         $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
174                 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
175                         $redirects++;
176                         @curl_close($ch);
177                         return z_fetch_url($newurl,$binary, $redirects, $opts);
178                 }
179         }
180
181
182         $a->set_curl_code($http_code);
183         $a->set_curl_content_type($curl_info['content_type']);
184
185         $body = substr($s,strlen($header));
186
187
188
189         $rc = intval($http_code);
190         $ret['return_code'] = $rc;
191         $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
192         $ret['redirect_url'] = $url;
193         if(! $ret['success']) {
194                 $ret['error'] = curl_error($ch);
195                 $ret['debug'] = $curl_info;
196                 logger('z_fetch_url: error: ' . $url . ': ' . $ret['error'], LOGGER_DEBUG);
197                 logger('z_fetch_url: debug: ' . print_r($curl_info,true), LOGGER_DATA);
198         }
199         $ret['body'] = substr($s,strlen($header));
200         $ret['header'] = $header;
201         if(x($opts,'debug')) {
202                 $ret['debug'] = $curl_info;
203         }
204         @curl_close($ch);
205
206         $a->save_timestamp($stamp1, "network");
207
208         return($ret);
209
210 }
211
212 // post request to $url. $params is an array of post variables.
213
214 /**
215  * @brief Post request to $url
216  * 
217  * @param string $url URL to post
218  * @param mixed $params
219  * @param string $headers HTTP headers
220  * @param integer $redirects Recursion counter for internal use - default = 0
221  * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
222  * 
223  * @return string The content
224  */
225 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
226         $stamp1 = microtime(true);
227
228         $a = get_app();
229         $ch = curl_init($url);
230         if(($redirects > 8) || (! $ch))
231                 return false;
232
233         logger("post_url: start ".$url, LOGGER_DATA);
234
235         curl_setopt($ch, CURLOPT_HEADER, true);
236         curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
237         curl_setopt($ch, CURLOPT_POST,1);
238         curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
239         curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
240
241         if(intval($timeout)) {
242                 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
243         }
244         else {
245                 $curl_time = intval(get_config('system','curl_timeout'));
246                 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
247         }
248
249         if(defined('LIGHTTPD')) {
250                 if(!is_array($headers)) {
251                         $headers = array('Expect:');
252                 } else {
253                         if(!in_array('Expect:', $headers)) {
254                                 array_push($headers, 'Expect:');
255                         }
256                 }
257         }
258         if($headers)
259                 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
260
261         $check_cert = get_config('system','verifyssl');
262         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
263         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
264         $prx = get_config('system','proxy');
265         if(strlen($prx)) {
266                 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
267                 curl_setopt($ch, CURLOPT_PROXY, $prx);
268                 $prxusr = get_config('system','proxyuser');
269                 if(strlen($prxusr))
270                         curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
271         }
272
273         $a->set_curl_code(0);
274
275         // don't let curl abort the entire application
276         // if it throws any errors.
277
278         $s = @curl_exec($ch);
279
280         $base = $s;
281         $curl_info = curl_getinfo($ch);
282         $http_code = $curl_info['http_code'];
283
284         logger("post_url: result ".$http_code." - ".$url, LOGGER_DATA);
285
286         $header = '';
287
288         // Pull out multiple headers, e.g. proxy and continuation headers
289         // allow for HTTP/2.x without fixing code
290
291         while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
292                 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
293                 $header .= $chunk;
294                 $base = substr($base,strlen($chunk));
295         }
296
297         if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
298                 $matches = array();
299                 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
300                 $newurl = trim(array_pop($matches));
301                 if(strpos($newurl,'/') === 0)
302                         $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
303                 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
304                         $redirects++;
305                         logger("post_url: redirect ".$url." to ".$newurl);
306                         return post_url($newurl,$params, $headers, $redirects, $timeout);
307                         //return fetch_url($newurl,false,$redirects,$timeout);
308                 }
309         }
310         $a->set_curl_code($http_code);
311         $body = substr($s,strlen($header));
312
313         $a->set_curl_headers($header);
314
315         curl_close($ch);
316
317         $a->save_timestamp($stamp1, "network");
318
319         logger("post_url: end ".$url, LOGGER_DATA);
320
321         return($body);
322 }
323
324 // Generic XML return
325 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
326 // of $st and an optional text <message> of $message and terminates the current process.
327
328 function xml_status($st, $message = '') {
329
330         $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
331
332         if($st)
333                 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
334
335         header( "Content-type: text/xml" );
336         echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
337         echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
338         killme();
339 }
340
341 /**
342  * @brief Send HTTP status header and exit.
343  *
344  * @param integer $val HTTP status result value
345  * @param array $description optional message
346  *    'title' => header title
347  *    'description' => optional message
348  */
349
350 /**
351  * @brief Send HTTP status header and exit.
352  *
353  * @param integer $val HTTP status result value
354  * @param array $description optional message
355  *    'title' => header title
356  *    'description' => optional message
357  */
358 function http_status_exit($val, $description = array()) {
359         $err = '';
360         if($val >= 400) {
361                 $err = 'Error';
362                 if (!isset($description["title"]))
363                         $description["title"] = $err." ".$val;
364         }
365         if($val >= 200 && $val < 300)
366                 $err = 'OK';
367
368         logger('http_status_exit ' . $val);
369         header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
370
371         if (isset($description["title"])) {
372                 $tpl = get_markup_template('http_status.tpl');
373                 echo replace_macros($tpl, array('$title' => $description["title"],
374                                                 '$description' => $description["description"]));
375         }
376
377         killme();
378
379 }
380
381 /**
382  * @brief Check URL to se if ts's real
383  * 
384  * Take a URL from the wild, prepend http:// if necessary
385  * and check DNS to see if it's real (or check if is a valid IP address)
386  * 
387  * @param string $url The URL to be validated
388  * @return boolean True if it's a valid URL, fals if something wrong with it
389  */
390 function validate_url(&$url) {
391         logger(sprintf('[%s:%d]: url=%s - CALLED!', __FUNCTION__, __LINE__, $url), LOGGER_TRACE);
392
393         if(get_config('system','disable_url_validation'))
394                 logger(sprintf('[%s:%d]: URL validation disabled, returning TRUE - EXIT!', __FUNCTION__, __LINE__), LOGGER_TRACE);
395                 return true;
396
397         // no naked subdomains (allow localhost for tests)
398         if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
399                 logger(sprintf('[%s:%d]: URL is not complete, returning FALSE - EXIT!', __FUNCTION__, __LINE__), LOGGER_TRACE);
400                 return false;
401
402         if(substr($url,0,4) != 'http' && substr($url,0,5) != 'https')
403                 $url = 'http://' . $url;
404
405         logger(sprintf('[%s:%d]: url=%s - before parse_url() ...', __FUNCTION__, __LINE__, $url), LOGGER_DEBUG);
406
407         $h = @parse_url($url);
408
409         logger(sprintf('[%s:%d]: h[]=%s', __FUNCTION__, __LINE__, gettype($h)), LOGGER_DEBUG);
410
411         if((is_array($h)) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
412                 logger(sprintf('[%s:%d]: URL %s validated. - EXIT!', __FUNCTION__, __LINE__, $url), LOGGER_TRACE);
413                 return true;
414         }
415
416         logger(sprintf('[%s:%d]: URL %s maybe not valid - EXIT!', __FUNCTION__, __LINE__, $url), LOGGER_TRACE);
417         return false;
418 }
419
420 /**
421  * @brief Checks that email is an actual resolvable internet address
422  * 
423  * @param string $addr The email address
424  * @return boolean True if it's a valid email address, false if it's not
425  */
426 function validate_email($addr) {
427
428         if(get_config('system','disable_email_validation'))
429                 return true;
430
431         if(! strpos($addr,'@'))
432                 return false;
433         $h = substr($addr,strpos($addr,'@') + 1);
434
435         if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
436                 return true;
437         }
438         return false;
439 }
440
441 /**
442  * @brief Check if URL is allowed
443  * 
444  * Check $url against our list of allowed sites,
445  * wildcards allowed. If allowed_sites is unset return true;
446  * 
447  * @param string $url URL which get tested
448  * @return boolean True if url is allowed otherwise return false
449  */
450 function allowed_url($url) {
451
452         $h = @parse_url($url);
453
454         if(! $h) {
455                 return false;
456         }
457
458         $str_allowed = get_config('system','allowed_sites');
459         if(! $str_allowed)
460                 return true;
461
462         $found = false;
463
464         $host = strtolower($h['host']);
465
466         // always allow our own site
467
468         if($host == strtolower($_SERVER['SERVER_NAME']))
469                 return true;
470
471         $fnmatch = function_exists('fnmatch');
472         $allowed = explode(',',$str_allowed);
473
474         if(count($allowed)) {
475                 foreach($allowed as $a) {
476                         $pat = strtolower(trim($a));
477                         if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
478                                 $found = true;
479                                 break;
480                         }
481                 }
482         }
483         return $found;
484 }
485
486 /**
487  * @brief Check if email address is allowed to register here.
488  * 
489  * Compare against our list (wildcards allowed).
490  * 
491  * @param type $email
492  * @return boolean False if not allowed, true if allowed
493  *    or if allowed list is not configured
494  */
495 function allowed_email($email) {
496
497
498         $domain = strtolower(substr($email,strpos($email,'@') + 1));
499         if(! $domain)
500                 return false;
501
502         $str_allowed = get_config('system','allowed_email');
503         if(! $str_allowed)
504                 return true;
505
506         $found = false;
507
508         $fnmatch = function_exists('fnmatch');
509         $allowed = explode(',',$str_allowed);
510
511         if(count($allowed)) {
512                 foreach($allowed as $a) {
513                         $pat = strtolower(trim($a));
514                         if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
515                                 $found = true;
516                                 break;
517                         }
518                 }
519         }
520         return $found;
521 }
522
523 function avatar_img($email) {
524
525         $a = get_app();
526
527         $avatar['size'] = 175;
528         $avatar['email'] = $email;
529         $avatar['url'] = '';
530         $avatar['success'] = false;
531
532         call_hooks('avatar_lookup', $avatar);
533
534         if(! $avatar['success'])
535                 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
536
537         logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
538         return $avatar['url'];
539 }
540
541
542 function parse_xml_string($s,$strict = true) {
543         /// @todo Move this function to the xml class
544         if($strict) {
545                 if(! strstr($s,'<?xml'))
546                         return false;
547                 $s2 = substr($s,strpos($s,'<?xml'));
548         }
549         else
550                 $s2 = $s;
551         libxml_use_internal_errors(true);
552
553         $x = @simplexml_load_string($s2);
554         if(! $x) {
555                 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
556                 foreach(libxml_get_errors() as $err)
557                         logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
558                 libxml_clear_errors();
559         }
560         return $x;
561 }
562
563 function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
564
565         // Suppress "view full size"
566         if (intval(get_config('system','no_view_full_size')))
567                 $include_link = false;
568
569         $a = get_app();
570
571         // Picture addresses can contain special characters
572         $s = htmlspecialchars_decode($srctext);
573
574         $matches = null;
575         $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
576         if($c) {
577                 require_once('include/Photo.php');
578                 foreach($matches as $mtch) {
579                         logger('scale_external_image: ' . $mtch[1]);
580
581                         $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
582                         if(stristr($mtch[1],$hostname))
583                                 continue;
584
585                         // $scale_replace, if passed, is an array of two elements. The
586                         // first is the name of the full-size image. The second is the
587                         // name of a remote, scaled-down version of the full size image.
588                         // This allows Friendica to display the smaller remote image if
589                         // one exists, while still linking to the full-size image
590                         if($scale_replace)
591                                 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
592                         else
593                                 $scaled = $mtch[1];
594                         $i = @fetch_url($scaled);
595                         if(! $i)
596                                 return $srctext;
597
598                         // guess mimetype from headers or filename
599                         $type = guess_image_type($mtch[1],true);
600
601                         if($i) {
602                                 $ph = new Photo($i, $type);
603                                 if($ph->is_valid()) {
604                                         $orig_width = $ph->getWidth();
605                                         $orig_height = $ph->getHeight();
606
607                                         if($orig_width > 640 || $orig_height > 640) {
608
609                                                 $ph->scaleImage(640);
610                                                 $new_width = $ph->getWidth();
611                                                 $new_height = $ph->getHeight();
612                                                 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
613                                                 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
614                                                         . "\n" . (($include_link)
615                                                                 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
616                                                                 : ''),$s);
617                                                 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
618                                         }
619                                 }
620                         }
621                 }
622         }
623
624         // replace the special char encoding
625         $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
626         return $s;
627 }
628
629
630 function fix_contact_ssl_policy(&$contact,$new_policy) {
631
632         $ssl_changed = false;
633         if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
634                 $ssl_changed = true;
635                 $contact['url']     =   str_replace('https:','http:',$contact['url']);
636                 $contact['request'] =   str_replace('https:','http:',$contact['request']);
637                 $contact['notify']  =   str_replace('https:','http:',$contact['notify']);
638                 $contact['poll']    =   str_replace('https:','http:',$contact['poll']);
639                 $contact['confirm'] =   str_replace('https:','http:',$contact['confirm']);
640                 $contact['poco']    =   str_replace('https:','http:',$contact['poco']);
641         }
642
643         if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
644                 $ssl_changed = true;
645                 $contact['url']     =   str_replace('http:','https:',$contact['url']);
646                 $contact['request'] =   str_replace('http:','https:',$contact['request']);
647                 $contact['notify']  =   str_replace('http:','https:',$contact['notify']);
648                 $contact['poll']    =   str_replace('http:','https:',$contact['poll']);
649                 $contact['confirm'] =   str_replace('http:','https:',$contact['confirm']);
650                 $contact['poco']    =   str_replace('http:','https:',$contact['poco']);
651         }
652
653         if($ssl_changed) {
654                 q("update contact set
655                         url = '%s',
656                         request = '%s',
657                         notify = '%s',
658                         poll = '%s',
659                         confirm = '%s',
660                         poco = '%s'
661                         where id = %d limit 1",
662                         dbesc($contact['url']),
663                         dbesc($contact['request']),
664                         dbesc($contact['notify']),
665                         dbesc($contact['poll']),
666                         dbesc($contact['confirm']),
667                         dbesc($contact['poco']),
668                         intval($contact['id'])
669                 );
670         }
671 }
672
673 function original_url($url, $depth=1, $fetchbody = false) {
674
675         $a = get_app();
676
677         // Remove Analytics Data from Google and other tracking platforms
678         $urldata = parse_url($url);
679         if (is_string($urldata["query"])) {
680                 $query = $urldata["query"];
681                 parse_str($query, $querydata);
682
683                 if (is_array($querydata))
684                         foreach ($querydata AS $param=>$value)
685                                 if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
686                                                         "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
687                                                         "fb_action_ids", "fb_action_types", "fb_ref",
688                                                         "awesm", "wtrid",
689                                                         "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) {
690
691                                         $pair = $param."=".urlencode($value);
692                                         $url = str_replace($pair, "", $url);
693
694                                         // Second try: if the url isn't encoded completely
695                                         $pair = $param."=".str_replace(" ", "+", $value);
696                                         $url = str_replace($pair, "", $url);
697
698                                         // Third try: Maybey the url isn't encoded at all
699                                         $pair = $param."=".$value;
700                                         $url = str_replace($pair, "", $url);
701
702                                         $url = str_replace(array("?&", "&&"), array("?", ""), $url);
703                                 }
704
705                 if (substr($url, -1, 1) == "?")
706                         $url = substr($url, 0, -1);
707         }
708
709         if ($depth > 10)
710                 return($url);
711
712         $url = trim($url, "'");
713
714         $stamp1 = microtime(true);
715
716         $siteinfo = array();
717         $ch = curl_init();
718         curl_setopt($ch, CURLOPT_URL, $url);
719         curl_setopt($ch, CURLOPT_HEADER, 1);
720         curl_setopt($ch, CURLOPT_NOBODY, 1);
721         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
722         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
723         curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
724
725         $header = curl_exec($ch);
726         $curl_info = @curl_getinfo($ch);
727         $http_code = $curl_info['http_code'];
728         curl_close($ch);
729
730         $a->save_timestamp($stamp1, "network");
731
732         if ($http_code == 0)
733                 return($url);
734
735         if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
736                 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
737                 if ($curl_info['redirect_url'] != "")
738                         return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
739                 else
740                         return(original_url($curl_info['location'], ++$depth, $fetchbody));
741         }
742
743         // Check for redirects in the meta elements of the body if there are no redirects in the header.
744         if (!$fetchbody)
745                 return(original_url($url, ++$depth, true));
746
747         // if the file is too large then exit
748         if ($curl_info["download_content_length"] > 1000000)
749                 return($url);
750
751         // if it isn't a HTML file then exit
752         if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
753                 return($url);
754
755         $stamp1 = microtime(true);
756
757         $ch = curl_init();
758         curl_setopt($ch, CURLOPT_URL, $url);
759         curl_setopt($ch, CURLOPT_HEADER, 0);
760         curl_setopt($ch, CURLOPT_NOBODY, 0);
761         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
762         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
763         curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
764
765         $body = curl_exec($ch);
766         curl_close($ch);
767
768         $a->save_timestamp($stamp1, "network");
769
770         if (trim($body) == "")
771                 return($url);
772
773         // Check for redirect in meta elements
774         $doc = new DOMDocument();
775         @$doc->loadHTML($body);
776
777         $xpath = new DomXPath($doc);
778
779         $list = $xpath->query("//meta[@content]");
780         foreach ($list as $node) {
781                 $attr = array();
782                 if ($node->attributes->length)
783                         foreach ($node->attributes as $attribute)
784                                 $attr[$attribute->name] = $attribute->value;
785
786                 if (@$attr["http-equiv"] == 'refresh') {
787                         $path = $attr["content"];
788                         $pathinfo = explode(";", $path);
789                         $content = "";
790                         foreach ($pathinfo AS $value)
791                                 if (substr(strtolower($value), 0, 4) == "url=")
792                                         return(original_url(substr($value, 4), ++$depth));
793                 }
794         }
795
796         return($url);
797 }
798
799 function short_link($url) {
800         require_once('library/slinky.php');
801         $slinky = new Slinky($url);
802         $yourls_url = get_config('yourls','url1');
803         if ($yourls_url) {
804                 $yourls_username = get_config('yourls','username1');
805                 $yourls_password = get_config('yourls', 'password1');
806                 $yourls_ssl = get_config('yourls', 'ssl1');
807                 $yourls = new Slinky_YourLS();
808                 $yourls->set('username', $yourls_username);
809                 $yourls->set('password', $yourls_password);
810                 $yourls->set('ssl', $yourls_ssl);
811                 $yourls->set('yourls-url', $yourls_url);
812                 $slinky->set_cascade(array($yourls, new Slinky_Ur1ca(), new Slinky_TinyURL()));
813         } else {
814                 // setup a cascade of shortening services
815                 // try to get a short link from these services
816                 // in the order ur1.ca, tinyurl
817                 $slinky->set_cascade(array(new Slinky_Ur1ca(), new Slinky_TinyURL()));
818         }
819         return $slinky->short();
820 }
821
822 /**
823  * @brief Encodes content to json
824  * 
825  * This function encodes an array to json format
826  * and adds an application/json HTTP header to the output.
827  * After finishing the process is getting killed.
828  *
829  * @param array $x The input content
830  */
831 function json_return_and_die($x) {
832         header("content-type: application/json");
833         echo json_encode($x);
834         killme();
835 }
836
837 /**
838  * @brief Find the matching part between two url
839  *
840  * @param string $url1
841  * @param string $url2
842  * @return string The matching part
843  */
844 function matching_url($url1, $url2) {
845
846         if (($url1 == "") OR ($url2 == ""))
847                 return "";
848
849         $url1 = normalise_link($url1);
850         $url2 = normalise_link($url2);
851
852         $parts1 = parse_url($url1);
853         $parts2 = parse_url($url2);
854
855         if (!isset($parts1["host"]) OR !isset($parts2["host"]))
856                 return "";
857
858         if ($parts1["scheme"] != $parts2["scheme"])
859                 return "";
860
861         if ($parts1["host"] != $parts2["host"])
862                 return "";
863
864         if ($parts1["port"] != $parts2["port"])
865                 return "";
866
867         $match = $parts1["scheme"]."://".$parts1["host"];
868
869         if ($parts1["port"])
870                 $match .= ":".$parts1["port"];
871
872         $pathparts1 = explode("/", $parts1["path"]);
873         $pathparts2 = explode("/", $parts2["path"]);
874
875         $i = 0;
876         $path = "";
877         do {
878                 $path1 = $pathparts1[$i];
879                 $path2 = $pathparts2[$i];
880
881                 if ($path1 == $path2)
882                         $path .= $path1."/";
883
884         } while (($path1 == $path2) AND ($i++ <= count($pathparts1)));
885
886         $match .= $path;
887
888         return normalise_link($match);
889 }