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