geo.php

来自「PHP 知识管理系统(基于树结构的知识管理系统), 英文原版的PHP源码。」· PHP 代码 · 共 646 行 · 第 1/2 页

PHP
646
字号
     * @access public
     */
    function getLong($latLongHashRef)
    {
        if (is_array($latLongHashRef)) {
            $long = $latLongHashRef["LONG"];
        } else {
            $long = 0;
        }

        return sprintf("%.2f", $long);
    }

    /**
     * Interface to the public functions
     *
     * @param string $methodName Lookup method
     * @param mixed  $target     Address(es) to lookup
     * @return array
     * @access private
     */
    function _execute($methodName, $input)
    {

        // if we haven't got a service set, then do it now
        if (empty($this->service)) {
            $this->setService();
        }

        // Test the target strings in the input array.  Any targets not in
        // an acceptable format will have their STATUS field set to INPUT_ERROR.
        // This method will also store the standardized target into the array
        // for use as a key in the cache table.
        $inputArray = $this->_verifyInputFormatArray($methodName, $input);
        if (PEAR::isError($inputArray)) {
            return $inputArray;
        }

        $resultArray = $this->_processArray($methodName, $inputArray);
        
        // if there is only one array, move the whole thing up one
        if (count($resultArray) == 1) {
            $resultArray = $resultArray[0];
        }

        return $resultArray;        
    }   

    
    /**
     * Verify the type of the target argument and verify types of array elements
     * Also converts the input array into the start of the output array
     *
     * @param string $methodName Lookup method
     * @param mixed  $inputArray Address(es) to lookup
     * @return array or pear error object on failure
     * @access private
     */
    function _verifyInputFormatArray($methodName, $inputArray)
    {
        // makes sure that the input is an array
        // if length is > than ARRAY_LIMIT_LENTH then bomb ou
        if (count($inputArray) > $this->array_limit) {
            // raise an error
            $error = new PEAR_Error("Too many entries. Limit is ".$this->array_limit);
            return $error;
        }

        // convert into a useable array
        $inputArray = $this->_convertInputArray($inputArray);
        return $inputArray;
    }

    /**
     * Utility function to check what the input array
     * and to convert to a correct array format for processing
     *
     * @param mixed $inputArray Address array
     * @return array
     * @access private
     */
    function _convertInputArray($inputArray)
    {
        // first check the darn thing is actually an array
        if (!is_array($inputArray)) {
            $inputArray = array($inputArray);
        }
    
        // now convert to the correct array form
        foreach ($inputArray as $entry) {
            $returnArray[]["TARGET"] = $entry;
        }
        
        return $returnArray;

    }


    /** 
     * Main function that processes addresses
     *
     * It might be a good idea to move the caching up one level?
     * 
     * @param string $methodName Lookup method
     * @param array  $inputArray Formatted address array
     * @return array
     * @access private
     */
    function _processArray($methodName, $inputArray)
    {
        $i = 0;
        foreach ($inputArray as $entry) {
            $entry = $this->_verifyInputFormat($entry);
        
            if (isset($entry["TARGET"]) && !isset($entry["INPUT_ERROR"])) {

                // set up the cache work around
                $GLOBALS[$this->netgeo_global] =& $this;
                
                if ($this->service == "localizer") {

                    $response = $this->cache->call('localizer_search', $entry["TARGET"]);

                } else {

                    // else do the HTTP request
                    $url = sprintf("%s?method=%s&target=%s", $this->default_server,
                                                             $methodName, $entry["TARGET"]
                                  );

                    $response =& $this->cache->call($this->netgeo_global.'->_executeHttpRequest', $url);
    
                }

                if (!isset($response)) {
                    $entry["STATUS"] = NETGEO_HTTP_ERROR;
                }

                // parse it all into something useful
                // at this point we should look for NETGEO_LIMIT_EXCEEDED as well
                $dataArray[$i] = $this->_processResult($response);
                
            } else {
                $dataArray[$i] = $entry;
            }

            $i++;
        }
        
        if (is_array($dataArray)) {
            return $dataArray;
        } else {
            return array("STATUS"=>NETGEO_HTTP_ERROR);
        }
    }

    /**
     * Test the input and make sure it is in an acceptable format.  The input
     * can be an AS number (with or without a leading "AS"), an IP address in
     * dotted decimal format, or a domain name.  Stores the standardized targe
     * string into the hash if input target is valid format, otherwise stores
     * undef into hash.
     * 
     * @param array  $inputArray Address(es) to lookup
     * @return array
     * @access private

     */
    function _verifyInputFormat($inputArray)
    {
        $target = trim($inputArray["TARGET"]);
        
        // look for AS|as
        if (preg_match('/^(?:AS|as)?\s?(\d{1,})$/', $target, $matches)) {
            // check the AS number. Btwn 1 and 65536
            if ($matches[1] >= 1 && $matches[1] < 65536) {
                $standardizedTarget = $matches[0];
            } else {
                $inputArray["INPUT_ERROR"] = NETGEO_INPUT_ERROR;
                // raise some error tex
                // Bad format for input. AS number must be between 1 and 65536
                return $inputArray;
            }

        // IP number
        } elseif (preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $target, $matches)) {
            if ($matches[1] <= 255 && $matches[2] <= 255 && $matches[3] <= 255 && $matches[4] <= 255) {
                $standardizedTarget = $target;
            } else {
                $inputArray["INPUT_ERROR"] = NETGEO_INPUT_ERROR;
                // raise some error tex
                // Bad format for input. each octet in IP address must be between 0 and 255
                return $inputArray;
            }

        // TLD
        } elseif (preg_match('/^(?:[\w\-]+\.)*[\w\-]+\.([A-Za-z]{2,3})$/', $target, $matches)) {
            $tld = $matches[1];
            
            // TLD length is either 2 or 3.  If length is 2 we just accept it,
            // otherwise we test the TLD against the list.
            if (strlen($tld) == 2 || preg_match('/^(com|net|org|edu|gov|mil|int)/i', $tld)) {
                $standardizedTarget = $target;
            } else {
                $inputArray["INPUT_ERROR"] = NETGEO_INPUT_ERROR;
                // raise some error tex
                // Bad TLD in domain name. 3-letter TLDs must be one of com,net,org,edu,gov,mil,in
                return $inputArray;
            }
        } else {
            $inputArray["INPUT_ERROR"] = NETGEO_INPUT_ERROR;
            // raise some error text
            // unrecognized format for input
            return $inputArray;
        }
        
        return $inputArray;
                
    }
    
    /**
     * Executes a request to the netgeo server
     *
     * @param array $inputArray Address(es) to lookup
     * @return string Response from netgeo server
     * @access private
     */
    function _executeHttpRequest($url)
    {
        $response = "";

        if (function_exists('curl_init')) {
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $response = curl_exec($ch);
            curl_close($ch);
        } else {
            // split the server url
            $urlinfo = parse_url($url);
            if (!isset($urlinfo["port"])) {
                $urlinfo["port"] = 80;
            }
        
            $sp = @fsockopen($urlinfo["host"], $urlinfo["port"], $errno, $errstr, $this->default_timeout);
            if (!$sp) {
                return false;
            }
    
            fputs($sp, "GET " . $urlinfo["path"] ."?". $urlinfo["query"] . " HTTP/1.0\r\n");
            fputs($sp, "User-Agent: " . $this->useragent . "\r\n\r\n");
            while (!feof($sp)) {
                $response .= fgets($sp,128);
            }
            fclose ($sp);
        }

        return $response;
    }
   
    /**
     * Parses the results from the server into an array
     * 
     * @param string $response Response from netgeo server
     * @return array 
     * @access private
     */
    function _processResult($response)
    {
        // process the localizer result differently
        // since we already have an array
        if ($this->service == "localizer") {

            foreach ($response as $key=>$val) {

                $retarray[strtoupper($key)] = $val;
            }

        } elseif ($this->service == "caida") {
       
            $lineArray = preg_split("/\n/", $response);
            $line = array_shift($lineArray);

            // first check for anything icky from the server
            if (preg_match("/".NETGEO_HTTP_ERROR."/", $line) || preg_match('/^\s*$/', $response)) {

                // empty empty empty
                if (preg_match('/^\s*$/', $text)) {
                    $text = "Empty content string";
                    return array("STATUS"=>$text);
                }

            } elseif (preg_match("/".NETGEO_LIMIT_EXCEEDED."/", $line)) {
                return array("STATUS"=>$text);
            }

            // now loop through. This should being us out at TARGET
            while (isset($line) && !preg_match("/^TARGET:/", $line)) {
                $line = array_shift($lineArray);
            }

            // keep going
            while (isset($line)) {
                if (preg_match("/^TARGET:\s+(.*\S)\s*<br>/", $line, $matches)) {
                    $retarray["TARGET"] = $matches[1];
                } elseif (preg_match("/^STATUS:\s+([\w\s]+\S)\s*<br>/", $line, $matches)) {
                    $retarray["STATUS"] = $matches[1];
                } elseif (preg_match("/^(\w+):\s+(.*\S)\s*<br>/", $line, $matches)) {
                    $retarray[$matches[1]] = $matches[2];
                }
                $line = array_shift($lineArray);
            }

        }

        return $retarray;   

    }

}


?>

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?