]> git.mxchange.org Git - friendica.git/blobdiff - include/network.php
Merge pull request #4283 from MrPetovan/bug/2487-fix-autolink-regex
[friendica.git] / include / network.php
index 7e388112367b562aa1c7accb58e3cf9a27c4cd4b..de7069a6d964b250bd00a2677c0ca301e4693408 100644 (file)
@@ -1,14 +1,13 @@
 <?php
-
 /**
  * @file include/network.php
  */
-
 use Friendica\App;
 use Friendica\Core\System;
 use Friendica\Core\Config;
 use Friendica\Network\Probe;
-use Friendica\Util\Xml;
+use Friendica\Object\Image;
+use Friendica\Util\XML;
 
 /**
  * @brief Curl wrapper
@@ -33,10 +32,10 @@ function fetch_url($url, $binary = false, &$redirects = 0, $timeout = 0, $accept
                $url,
                $binary,
                $redirects,
-               array('timeout'=>$timeout,
+               ['timeout'=>$timeout,
                'accept_content'=>$accept_content,
                'cookiejar'=>$cookiejar
-               )
+               ]
        );
 
        return($ret['body']);
@@ -64,9 +63,9 @@ function fetch_url($url, $binary = false, &$redirects = 0, $timeout = 0, $accept
  *    string 'header' => HTTP headers
  *    string 'body' => fetched content
  */
-function z_fetch_url($url, $binary = false, &$redirects = 0, $opts = array())
+function z_fetch_url($url, $binary = false, &$redirects = 0, $opts = [])
 {
-       $ret = array('return_code' => 0, 'success' => false, 'header' => '', 'info' => '', 'body' => '');
+       $ret = ['return_code' => 0, 'success' => false, 'header' => '', 'info' => '', 'body' => ''];
 
        $stamp1 = microtime(true);
 
@@ -98,7 +97,7 @@ function z_fetch_url($url, $binary = false, &$redirects = 0, $opts = array())
                curl_setopt(
                        $ch,
                        CURLOPT_HTTPHEADER,
-                       array('Accept: ' . $opts['accept_content'])
+                       ['Accept: ' . $opts['accept_content']]
                );
        }
 
@@ -127,8 +126,8 @@ function z_fetch_url($url, $binary = false, &$redirects = 0, $opts = array())
        if (x($opts, 'timeout')) {
                @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
        } else {
-               $curl_time = intval(Config::get('system', 'curl_timeout'));
-               @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
+               $curl_time = Config::get('system', 'curl_timeout', 60);
+               @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
        }
 
        // by default we will allow self-signed certs
@@ -214,7 +213,7 @@ function z_fetch_url($url, $binary = false, &$redirects = 0, $opts = array())
                        $newurl = $new_location_info['scheme'] . '://' . $new_location_info['host'] . $old_location_info['path'];
                }
 
-               $matches = array();
+               $matches = [];
 
                if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
                        $newurl = trim(array_pop($matches));
@@ -233,8 +232,6 @@ function z_fetch_url($url, $binary = false, &$redirects = 0, $opts = array())
        $a->set_curl_code($http_code);
        $a->set_curl_content_type($curl_info['content_type']);
 
-       $body = substr($s, strlen($header));
-
        $rc = intval($http_code);
        $ret['return_code'] = $rc;
        $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
@@ -303,13 +300,13 @@ function post_url($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
        if (intval($timeout)) {
                curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        } else {
-               $curl_time = intval(Config::get('system', 'curl_timeout'));
-               curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
+               $curl_time = Config::get('system', 'curl_timeout', 60);
+               curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
        }
 
        if (defined('LIGHTTPD')) {
                if (!is_array($headers)) {
-                       $headers = array('Expect:');
+                       $headers = ['Expect:'];
                } else {
                        if (!in_array('Expect:', $headers)) {
                                array_push($headers, 'Expect:');
@@ -364,7 +361,7 @@ function post_url($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
        }
 
        if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
-               $matches = array();
+               $matches = [];
                preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
                $newurl = trim(array_pop($matches));
 
@@ -400,7 +397,7 @@ function post_url($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
 
 function xml_status($st, $message = '')
 {
-       $result = array('status' => $st);
+       $result = ['status' => $st];
 
        if ($message != '') {
                $result['message'] = $message;
@@ -412,9 +409,9 @@ function xml_status($st, $message = '')
 
        header("Content-type: text/xml");
 
-       $xmldata = array("result" => $result);
+       $xmldata = ["result" => $result];
 
-       echo Xml::from_array($xmldata, $xml);
+       echo XML::fromArray($xmldata, $xml);
 
        killme();
 }
@@ -436,7 +433,7 @@ function xml_status($st, $message = '')
  *                             'title' => header title
  *                             'description' => optional message
  */
-function http_status_exit($val, $description = array())
+function http_status_exit($val, $description = [])
 {
        $err = '';
        if ($val >= 400) {
@@ -455,9 +452,9 @@ function http_status_exit($val, $description = array())
                $tpl = get_markup_template('http_status.tpl');
                echo replace_macros(
                        $tpl,
-                       array(
+                       [
                                '$title' => $description["title"],
-                               '$description' => $description["description"])
+                               '$description' => $description["description"]]
                );
        }
 
@@ -471,26 +468,28 @@ function http_status_exit($val, $description = array())
  * and check DNS to see if it's real (or check if is a valid IP address)
  *
  * @param string $url The URL to be validated
- * @return boolean True if it's a valid URL, fals if something wrong with it
+ * @return string|boolean The actual working URL, false else
  */
-function validate_url(&$url)
+function validate_url($url)
 {
        if (Config::get('system', 'disable_url_validation')) {
-               return true;
+               return $url;
        }
 
        // no naked subdomains (allow localhost for tests)
-       if (strpos($url, '.') === false && strpos($url, '/localhost/') === false)
+       if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
                return false;
+       }
 
-       if (substr($url, 0, 4) != 'http')
+       if (substr($url, 0, 4) != 'http') {
                $url = 'http://' . $url;
+       }
 
-       /// @TODO Really supress function outcomes? Why not find them + debug them?
+       /// @TODO Really suppress function outcomes? Why not find them + debug them?
        $h = @parse_url($url);
 
-       if ((is_array($h)) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
-               return true;
+       if ((is_array($h)) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
+               return $url;
        }
 
        return false;
@@ -570,7 +569,8 @@ function allowed_url($url)
  * Checks if the provided url domain is on the domain blocklist.
  * Returns true if it is or malformed URL, false if not.
  *
- * @param  string $url The url to check the domain from
+ * @param string $url The url to check the domain from
+ *
  * @return boolean
  */
 function blocked_url($url)
@@ -581,7 +581,7 @@ function blocked_url($url)
                return true;
        }
 
-       $domain_blocklist = Config::get('system', 'blocklist', array());
+       $domain_blocklist = Config::get('system', 'blocklist', []);
        if (! $domain_blocklist) {
                return false;
        }
@@ -609,29 +609,40 @@ function blocked_url($url)
 function allowed_email($email)
 {
        $domain = strtolower(substr($email, strpos($email, '@') + 1));
-       if (! $domain) {
+       if (!$domain) {
                return false;
        }
 
-       $str_allowed = Config::get('system', 'allowed_email');
-       if (! $str_allowed) {
+       $str_allowed = Config::get('system', 'allowed_email', '');
+       if (!x($str_allowed)) {
                return true;
        }
 
-       $found = false;
-
-       $fnmatch = function_exists('fnmatch');
        $allowed = explode(',', $str_allowed);
 
-       if (count($allowed)) {
-               foreach ($allowed as $a) {
-                       $pat = strtolower(trim($a));
-                       if (($fnmatch && fnmatch($pat, $domain)) || ($pat == $domain)) {
-                               $found = true;
-                               break;
-                       }
+       return allowed_domain($domain, $allowed);
+}
+
+/**
+ * Checks for the existence of a domain in a domain list
+ *
+ * @brief Checks for the existence of a domain in a domain list
+ * @param string $domain
+ * @param array  $domain_list
+ * @return boolean
+ */
+function allowed_domain($domain, array $domain_list)
+{
+       $found = false;
+
+       foreach ($domain_list as $item) {
+               $pat = strtolower(trim($item));
+               if (fnmatch($pat, $domain) || ($pat == $domain)) {
+                       $found = true;
+                       break;
                }
        }
+
        return $found;
 }
 
@@ -678,15 +689,12 @@ function scale_external_images($srctext, $include_link = true, $scale_replace =
                $include_link = false;
        }
 
-       $a = get_app();
-
        // Picture addresses can contain special characters
        $s = htmlspecialchars_decode($srctext);
 
        $matches = null;
        $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism', $s, $matches, PREG_SET_ORDER);
        if ($c) {
-               require_once 'include/Photo.php';
                foreach ($matches as $mtch) {
                        logger('scale_external_image: ' . $mtch[1]);
 
@@ -711,18 +719,18 @@ function scale_external_images($srctext, $include_link = true, $scale_replace =
                        }
 
                        // guess mimetype from headers or filename
-                       $type = guess_image_type($mtch[1], true);
+                       $type = Image::guessType($mtch[1], true);
 
                        if ($i) {
-                               $ph = new Photo($i, $type);
-                               if ($ph->is_valid()) {
-                                       $orig_width = $ph->getWidth();
-                                       $orig_height = $ph->getHeight();
+                               $Image = new Image($i, $type);
+                               if ($Image->isValid()) {
+                                       $orig_width = $Image->getWidth();
+                                       $orig_height = $Image->getHeight();
 
                                        if ($orig_width > 640 || $orig_height > 640) {
-                                               $ph->scaleImage(640);
-                                               $new_width = $ph->getWidth();
-                                               $new_height = $ph->getHeight();
+                                               $Image->scaleDown(640);
+                                               $new_width = $Image->getWidth();
+                                               $new_height = $Image->getHeight();
                                                logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
                                                $s = str_replace(
                                                        $mtch[0],
@@ -769,10 +777,10 @@ function fix_contact_ssl_policy(&$contact, $new_policy)
        }
 
        if ($ssl_changed) {
-               $fields = array('url' => $contact['url'], 'request' => $contact['request'],
+               $fields = ['url' => $contact['url'], 'request' => $contact['request'],
                                'notify' => $contact['notify'], 'poll' => $contact['poll'],
-                               'confirm' => $contact['confirm'], 'poco' => $contact['poco']);
-               dba::update('contact', $fields, array('id' => $contact['id']));
+                               'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
+               dba::update('contact', $fields, ['id' => $contact['id']]);
        }
 }
 
@@ -793,12 +801,12 @@ function strip_tracking_query_params($url)
                        foreach ($querydata as $param => $value) {
                                if (in_array(
                                        $param,
-                                       array(
+                                       [
                                                "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
                                                "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
                                                "fb_action_ids", "fb_action_types", "fb_ref",
                                                "awesm", "wtrid",
-                                               "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term")
+                                               "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
                                        )
                                ) {
                                        $pair = $param . "=" . urlencode($value);
@@ -812,7 +820,7 @@ function strip_tracking_query_params($url)
                                        $pair = $param . "=" . $value;
                                        $url = str_replace($pair, "", $url);
 
-                                       $url = str_replace(array("?&", "&&"), array("?", ""), $url);
+                                       $url = str_replace(["?&", "&&"], ["?", ""], $url);
                                }
                        }
                }
@@ -854,7 +862,6 @@ function original_url($url, $depth = 1, $fetchbody = false)
 
        $stamp1 = microtime(true);
 
-       $siteinfo = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 1);
@@ -863,7 +870,7 @@ function original_url($url, $depth = 1, $fetchbody = false)
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
 
-       $header = curl_exec($ch);
+       curl_exec($ch);
        $curl_info = @curl_getinfo($ch);
        $http_code = $curl_info['http_code'];
        curl_close($ch);
@@ -925,7 +932,7 @@ function original_url($url, $depth = 1, $fetchbody = false)
 
        $list = $xpath->query("//meta[@content]");
        foreach ($list as $node) {
-               $attr = array();
+               $attr = [];
                if ($node->attributes->length) {
                        foreach ($node->attributes as $attribute) {
                                $attr[$attribute->name] = $attribute->value;
@@ -935,7 +942,6 @@ function original_url($url, $depth = 1, $fetchbody = false)
                if (@$attr["http-equiv"] == 'refresh') {
                        $path = $attr["content"];
                        $pathinfo = explode(";", $path);
-                       $content = "";
                        foreach ($pathinfo as $value) {
                                if (substr(strtolower($value), 0, 4) == "url=") {
                                        return(original_url(substr($value, 4), ++$depth));
@@ -944,7 +950,7 @@ function original_url($url, $depth = 1, $fetchbody = false)
                }
        }
 
-       return($url);
+       return $url;
 }
 
 function short_link($url)
@@ -961,12 +967,12 @@ function short_link($url)
                $yourls->set('password', $yourls_password);
                $yourls->set('ssl', $yourls_ssl);
                $yourls->set('yourls-url', $yourls_url);
-               $slinky->set_cascade(array($yourls, new Slinky_Ur1ca(), new Slinky_TinyURL()));
+               $slinky->set_cascade([$yourls, new Slinky_Ur1ca(), new Slinky_TinyURL()]);
        } else {
                // setup a cascade of shortening services
                // try to get a short link from these services
                // in the order ur1.ca, tinyurl
-               $slinky->set_cascade(array(new Slinky_Ur1ca(), new Slinky_TinyURL()));
+               $slinky->set_cascade([new Slinky_Ur1ca(), new Slinky_TinyURL()]);
        }
        return $slinky->short();
 }