/** * Create Service * * @param ServiceLocatorInterface $serviceLocator Zend View Helper Mgr * * @return Site */ public function createService(ServiceLocatorInterface $serviceLocator) { // //Uncomment to turn on sql query logging. They echo in the browser // $serviceLocator->get('Doctrine\ORM\EntityManager') // ->getConnection() // ->getConfiguration() // ->setSQLLogger(new DoctrineQueryLoggerWithTime()); /** @var \Zend\Http\PhpEnvironment\Request $request */ $request = $serviceLocator->get('request'); if ($request instanceof \Zend\Console\Request) { // Fake Site for console return new Site(); } $serverParam = $request->getServer(); $hostParts = explode(':', $serverParam->get('HTTP_HOST')); $currentDomain = $hostParts[0]; //Use the default site if the requested domain name is an IP address $ipValidator = new Ip(); if ($ipValidator->isValid($currentDomain)) { $config = $serviceLocator->get('Config'); $currentDomain = $config['Rcm']['defaultDomain']; } /** @var \Doctrine\ORM\EntityManagerInterface $entityManager */ $entityManager = $serviceLocator->get('Doctrine\\ORM\\EntityManager'); /** @var \Rcm\Repository\Site $siteRepo */ $siteRepo = $entityManager->getRepository('\\Rcm\\Entity\\Site'); $currentSite = $siteRepo->getSiteByDomain($currentDomain); if (empty($currentSite)) { $currentSite = new Site(); } return $currentSite; }
/** * @param $ipString * @return IdentityInformation * @throws \Zend\Validator\Exception\InvalidArgumentException */ public function getIpInfo($ipString) { $ipValidator = new Ip(); if (!$ipValidator->isValid($ipString)) { throw new InvalidArgumentException(); } // creating request object $request = new Request(); $request->setUri($this->endPoint . $ipString . '/json'); $client = new Client(); $adapter = new Client\Adapter\Curl(); $adapter->setCurlOption(CURLOPT_TIMEOUT_MS, 500); $client->setAdapter($adapter); $response = $client->send($request); $data = $response->getBody(); $dataArray = json_decode($data); $identityInformation = new IdentityInformation(); $identityInformation->setCountry(isset($dataArray->country) ? $dataArray->country : ''); $identityInformation->setRegion(isset($dataArray->region) ? $dataArray->region : ''); $identityInformation->setCity(isset($dataArray->city) ? $dataArray->city : ''); $identityInformation->setLocation(isset($dataArray->loc) ? $dataArray->loc : ''); $identityInformation->setProvider(isset($dataArray->org) ? $dataArray->org : ''); $identityInformation->setHostName(isset($dataArray->hostname) ? $dataArray->hostname : ''); return $identityInformation; }
/** * @param string $ipAddress * @return array|\ArrayObject|null * @throws \Zend\Validator\Exception\InvalidArgumentException */ public function getCountryDataByIp($ipAddress = '127.0.0.1') { $ipValidator = new Ip(); if ($ipValidator->isValid($ipAddress)) { /** * @var \DDD\Dao\GeoliteCountry\GeoliteCountry $geoliteCountryDao */ $geoliteCountryDao = $this->getServiceLocator()->get('dao_geolite_country_geolite_country'); $return = $geoliteCountryDao->getCountryDataByIp(ip2long($ipAddress)); return $return; } else { throw new InvalidArgumentException(); } }
/** * getPrimaryRedirectUrl * If the IP is not a domain and is not the primary, return redirect for primary * * @param Site $site * * @return null|string */ public function getPrimaryRedirectUrl(Site $site) { $currentDomain = $site->getDomain()->getDomainName(); $ipValidator = new Ip(); $isIp = $ipValidator->isValid($currentDomain); if ($isIp) { return null; } $primaryDomain = $site->getDomain()->getPrimary(); if (empty($primaryDomain)) { return null; } if ($primaryDomain->getDomainName() == $currentDomain) { return null; } return $primaryDomain->getDomainName(); }
/** * Check the domain is a known domain for the CMS. If not the primary, it will * redirect the user to the primary domain. Useful for multiple domain sites. * * @param MvcEvent $event Zend MVC Event * * @return null|Response */ public function checkDomain(MvcEvent $event) { /** @var \Zend\Http\PhpEnvironment\Request $request */ $request = $event->getRequest(); $serverParam = $request->getServer(); $currentDomain = $serverParam->get('HTTP_HOST'); if (empty($currentDomain)) { // We are on CLI return null; } if (!$this->currentSite->getSiteId() || $this->currentSite->getStatus() != 'A') { if (empty($this->config['Rcm']['defaultDomain']) || $this->config['Rcm']['defaultDomain'] == $this->currentSite->getDomain()->getDomainName()) { $response = new Response(); $response->setStatusCode(404); $event->stopPropagation(true); return $response; } $response = new Response(); $response->setStatusCode(302); $response->getHeaders()->addHeaderLine('Location', '//' . $this->config['Rcm']['defaultDomain']); $event->stopPropagation(true); return $response; } $primaryCheck = $this->currentSite->getDomain()->getPrimary(); /** * If the IP is not a domain and is not the primary, redirect to primary */ if (!$this->ipValidator->isValid($currentDomain) && !empty($primaryCheck) && $primaryCheck->getDomainName() != $currentDomain) { $response = new Response(); $response->setStatusCode(302); $response->getHeaders()->addHeaderLine('Location', '//' . $primaryCheck->getDomainName()); $event->stopPropagation(true); return $response; } return null; }
/** * Check if a host name is a valid IP address, depending on allowed IP address types * * @param string $host * @param integer $allowed allowed address types * @return boolean */ protected static function isValidIpAddress($host, $allowed) { $validatorParams = array('allowipv4' => (bool) ($allowed & self::HOST_IPV4), 'allowipv6' => false, 'allowipvfuture' => false, 'allowliteral' => false); // Test only IPv4 $validator = new Validator\Ip($validatorParams); $return = $validator->isValid($host); if ($return) { return true; } // IPv6 & IPvLiteral must be in literal format $validatorParams = array('allowipv4' => false, 'allowipv6' => (bool) ($allowed & self::HOST_IPV6), 'allowipvfuture' => (bool) ($allowed & self::HOST_IPVFUTURE), 'allowliteral' => true); static $regex = '/^\\[.*\\]$/'; $validator->setOptions($validatorParams); return preg_match($regex, $host) && $validator->isValid($host); }
/** * Ensures that getMessages() returns expected default value * * @return void */ public function testGetMessages() { $this->assertEquals(array(), $this->validator->getMessages()); }
/** * getCurrentDomain * * @param null $default * * @return null|string */ public function getCurrentDomain($default = null) { $currentDomain = PhpServer::getRequestDomain(); //Use the default site if the requested domain name is an IP address $ipValidator = new Ip(); if ($ipValidator->isValid($currentDomain)) { $currentDomain = $default; } return $currentDomain; }
/** * Check if string is a valid ip address * * @param string $ipAddr * @param boolean $allowipv6 * @return boolean */ public static function isValidIP($ipAddr, $allowipv6 = false) { $validator = new ZendIp(array('allowipv6' => $allowipv6)); return $validator->isValid($ipAddr); }
/** * Unshare IP address for a server ($id) * * @param string $id * @param string $ip * @return boolean */ public function unshareIpAddress($id, $ip) { if (empty($id)) { throw new Exception\InvalidArgumentException('You didn\'t specified the ID of the server'); } if (empty($ip)) { throw new Exception\InvalidArgumentException('You didn\'t specified the IP address to share'); } $validator = new IpValidator(); if (!$validator->isValid($ip)) { throw new Exception\InvalidArgumentException("The parameter {$ip} specified is not a valid IP address"); } $result = $this->httpCall($this->getManagementUrl() . '/servers/' . rawurlencode($id) . '/ips/public/' . rawurlencode($ip), HttpClient::DELETE); $status = $result->getStatus(); switch ($status) { case '202': // break intentionally omitted return true; case '503': $this->errorMsg = self::ERROR_SERVICE_UNAVAILABLE; break; case '401': $this->errorMsg = self::ERROR_UNAUTHORIZED; break; case '404': $this->errorMsg = self::ERROR_ITEM_NOT_FOUND; break; case '413': $this->errorMsg = self::ERROR_OVERLIMIT; break; default: $this->errorMsg = $result->getBody(); break; } $this->errorCode = $status; return false; }
/** * Check if a host name is a valid IP address, depending on allowed IP address types * * @param string $host * @param integer $allowed allowed address types * @return boolean */ protected static function isValidIpAddress($host, $allowed) { $validatorParams = array('allowipv4' => (bool) ($allowed & self::HOST_IPV4), 'allowipv6' => (bool) ($allowed & self::HOST_IPV6)); if ($allowed & (self::HOST_IPV6 | self::HOST_IPVF)) { if (preg_match('/^\\[(.+)\\]$/', $host, $match)) { $host = $match[1]; $validatorParams['allowipv4'] = false; } } if ($allowed & (self::HOST_IPV4 | self::HOST_IPV6)) { $validator = new Validator\Ip($validatorParams); if ($validator->isValid($host)) { return true; } } if ($allowed & self::HOST_IPVF) { $regex = '/^v\\.[[:xdigit:]]+[' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . ':]+$/'; return (bool) preg_match($regex, $host); } return false; }
/** * Does a bunch of additional validation on the email address parts contained in $emailAddress * Then adds it to $emailAdddresses. * @param $emailAddresses * @param $emailAddress * @param $encoding * @param $i * @return mixed */ private function _addAddress(&$emailAddresses, &$emailAddress, $encoding, $i) { if (!$emailAddress['invalid']) { if ($emailAddress['address_temp'] || $emailAddress['quote_temp']) { $emailAddress['invalid'] = true; $emailAddress['invalid_reason'] = "Incomplete address"; $this->log('error', "Email\\Parse->_addAddress - corruption during parsing - leftovers:\n\$i: {$i}\n\$emailAddress['address_temp'] : {$emailAddress['address_temp']}\n\$emailAddress['quote_temp']: {$emailAddress['quote_temp']}\n"); } elseif ($emailAddress['ip'] && $emailAddress['domain']) { // Error - this should never occur $emailAddress['invalid'] = true; $emailAddress['invalid_reason'] = "Confusion during parsing"; $this->log('error', "Email\\Parse->_addAddress - both an IP address '{$emailAddress['ip']}' and a domain '{$emailAddress['domain']}' found for the email address '{$emailAddress['original_address']}'\n"); } elseif ($emailAddress['ip'] || $emailAddress['domain'] && preg_match('/\\d+\\.\\d+\\.\\d+\\.\\d+/', $emailAddress['domain'])) { // also test if the current domain looks like an IP address if ($emailAddress['domain']) { // Likely an IP address if we get here $emailAddress['ip'] = $emailAddress['domain']; $emailAddress['domain'] = null; } if (!$this->ipValidator) { $this->ipValidator = new Ip(); } try { if (!$this->ipValidator->isValid($emailAddress['ip'])) { $emailAddress['invalid'] = true; $emailAddress['invalid_reason'] = 'IP address invalid: \'' . $emailAddress['ip'] . '\' does not appear to be a valid IP address'; } elseif (preg_match('/192\\.168\\.\\d+\\.\\d+/', $emailAddress['ip']) || preg_match('/172\\.(1[6-9]|2[0-9]|3[0-2])\\.\\d+\\.\\d+/', $emailAddress['ip']) || preg_match('/10\\.\\d+\\.\\d+\\.\\d+/', $emailAddress['ip'])) { $emailAddress['invalid'] = true; $emailAddress['invalid_reason'] = 'IP address invalid (private): ' . $emailAddress['ip']; } elseif (preg_match('/169\\.254\\.\\d+\\.\\d+/', $emailAddress['ip'])) { $emailAddress['invalid'] = true; $emailAddress['invalid_reason'] = 'IP address invalid (APIPA): ' . $emailAddress['ip']; } } catch (\Exception $e) { $emailAddress['invalid'] = true; $emailAddress['invalid_reason'] = 'IP address invalid: ' . $emailAddress['ip']; } } elseif ($emailAddress['domain']) { // Check for IDNA if (max(array_keys(count_chars($emailAddress['domain'], 1))) > 127) { try { $emailAddress['domain'] = $this->getPunycode()->encode($emailAddress['domain']); } catch (\Exception $e) { $emailAddress['invalid'] = true; $emailAddress['invalid_reason'] = "Can't convert domain {$emailAddress['domain']} to punycode"; } } $result = $this->validateDomainName($emailAddress['domain']); if (!$result['valid']) { $emailAddress['invalid'] = true; $emailAddress['invalid_reason'] = isset($result['reason']) ? 'Domain invalid: ' . $result['reason'] : 'Domain invalid for some unknown reason'; } } } // Prepare some of the fields needed $emailAddress['name_parsed'] = rtrim($emailAddress['name_parsed']); $emailAddress['original_address'] = rtrim($emailAddress['original_address']); $name = $emailAddress['name_quoted'] ? "\"{$emailAddress['name_parsed']}\"" : $emailAddress['name_parsed']; $localPart = $emailAddress['local_part_quoted'] ? "\"{$emailAddress['local_part_parsed']}\"" : $emailAddress['local_part_parsed']; $domainPart = $emailAddress['ip'] ? '[' . $emailAddress['ip'] . ']' : $emailAddress['domain']; if (!$emailAddress['invalid']) { if (mb_strlen($domainPart, $encoding) == 0) { $emailAddress['invalid'] = true; $emailAddress['invalid_reason'] = 'Email address needs a domain after the \'@\''; } elseif (mb_strlen($localPart, $encoding) > 63) { $emailAddress['invalid'] = true; $emailAddress['invalid_reason'] = 'Email address before the \'@\' can not be greater than 63 characters'; } elseif (mb_strlen($localPart, $encoding) + mb_strlen($domainPart, $encoding) + 1 > 254) { $emailAddress['invalid'] = true; $emailAddress['invalid_reason'] = 'Email addresses can not be greater than 254 characters'; } } // Build the email address hash $emailAddrDef = array('address' => '', 'simple_address' => '', 'original_address' => rtrim($emailAddress['original_address']), 'name' => $name, 'name_parsed' => $emailAddress['name_parsed'], 'local_part' => $localPart, 'local_part_parsed' => $emailAddress['local_part_parsed'], 'domain_part' => $domainPart, 'domain' => $emailAddress['domain'], 'ip' => $emailAddress['ip'], 'invalid' => $emailAddress['invalid'], 'invalid_reason' => $emailAddress['invalid_reason']); // Build the proper address by hand (has comments stripped out and should have quotes in the proper places) if (!$emailAddrDef['invalid']) { $emailAddrDef['simple_address'] = "{$emailAddrDef['local_part']}@{$emailAddrDef['domain_part']}"; $properAddress = $emailAddrDef['name'] ? "{$emailAddrDef['name']} <{$emailAddrDef['local_part']}@{$emailAddrDef['domain_part']}>" : $emailAddrDef['simple_address']; $emailAddrDef['address'] = $properAddress; } $emailAddresses[] = $emailAddrDef; return $emailAddrDef['invalid']; }
/** * Retrieve remote address * * @return integer|null */ protected function getRemoteAddr() { $remoteAddr = empty($_SERVER['REMOTE_ADDR']) ? null : $_SERVER['REMOTE_ADDR']; $validator = new ValidateIp(); return $validator->isValid($remoteAddr) ? ip2long($remoteAddr) : null; }