예제 #1
0
 /**
  * Extract domain name and extension from FQDN
  *
  * @param string $hostname
  * @return array (name, extension)
  */
 public static function Parse($domain)
 {
     $domain = FQDN::Sanitize($domain);
     list($name, $extension) = explode(".", $domain, 2);
     // FAIL11
     if (empty($name) || empty($extension)) {
         throw new Exception(sprintf(_("Failed to parse domain name: %s"), $domain));
     }
     return array($name, $extension);
 }
예제 #2
0
 function DispatchPollUpdateDomain(PollUpdateDomainResponse $resp)
 {
     if ($resp->IsFailed()) {
         Log::Log(sprintf('DispatchPollUpdateDomain failed. Registry response: %s', $resp->ErrMsg), E_USER_ERROR);
         throw new Exception($resp->ErrMsg, $resp->Code);
     }
     if ($resp->Succeed()) {
         list($name, $extension) = FQDN::Parse($resp->HostName);
         $domain = $this->DBDomain->LoadByName($name, $extension, $this->GetManifest());
         if ($resp->Result) {
             $domain = $this->GetRemoteDomain($domain);
             $this->FireEvent('DomainOperation', $domain, self::OP_UPDATE);
             $this->FireEvent('DomainUpdated', $domain);
             $this->DBDomain->Save($domain);
         } else {
             $this->FireEvent('DomainOperation', $domain, self::OP_UPDATE, true, $resp->FailReason);
         }
         return true;
     }
 }
		/**
		 * This method request registry for information about domain
		 * 
		 * @param Domain $domain 
		 * @return GetRemoteDomainResponse
		 */
		public function GetRemoteDomain(Domain $domain)
		{			
			$params = array(
				"name"	=> $this->MakeNameIDNCompatible($domain->GetHostName()),
				'authinfo' => ''			
			);
			if ($domain->AuthCode)
				$params['authinfo'] = "<domain:authInfo><domain:pw>{$domain->AuthCode}</domain:pw></domain:authInfo>";				
				
			$this->BeforeRequest('domain-info', $params, __METHOD__, $domain);
			$response = $this->Request("domain-info", $params);
			
			$status = ($response->Succeed) ? REGISTRY_RESPONSE_STATUS::SUCCESS : REGISTRY_RESPONSE_STATUS::FAILED;
			$resp = new GetRemoteDomainResponse($status, $response->ErrMsg, $response->Code);
			$resp->RawResponse = $response->Data;
	
			if ($response->Succeed)
			{
				$info = $response->Data->response->resData->children($this->XmlNamespaces['domain']);
				$info = $info[0];
				
				$resp->CLID = (string)$info->clID[0];
				
				try
				{
					$resp->CRID = (string)$info->crID[0];
				}
				catch(Exception $e){}
				
				if ($resp->CRID)
				{
					$resp->AuthCode = ($info->authInfo[0]) ? (string)$info->authInfo[0]->pw[0] : "";
					
					$resp->CreateDate = $this->StrToTime((string)$info->crDate[0]);
					if ($info->exDate[0])
					{
						$resp->ExpireDate = $this->StrToTime((string)$info->exDate[0]);	
					}
					
					// Get contacts
					foreach ($info->contact as $k=>$v)
					{
						$attrs = $v->attributes();
						$ctype = (string)$attrs["type"];
						
						switch($ctype)
						{
							case "admin":
								$resp->AdminContact = (string)$v;
								break;
							case "tech":
								$resp->TechContact = (string)$v;
								break;
							case "billing":
								$resp->BillingContact = (string)$v;
								break;
						}
					}
					$resp->RegistrantContact = (string)$info->registrant[0];

					
					// Get nameservers
					$ns_arr = array();
					$registryOptionsConfig = $this->Manifest->GetRegistryOptions();
					if ((bool)$registryOptionsConfig->ability->hostattr)
					{
						// Iterate over hostAttr
						if ($info->ns->hostAttr)
						{
							foreach ($info->ns->hostAttr as $hostAttr)
							{
								$hostName = (string)$hostAttr->hostName;
								if ($hostAttr->hostAddr[0])
								{
									$ns = new NameserverHost($hostName, (string)$hostAttr->hostAddr[0]);
								}
								else
								{
									$ns = new Nameserver($hostName);
								}
								$ns_arr[] = $ns;
							}
						}
					}
					else
					{
						// Iterate over hostObj
						if ($info->ns->hostObj)
						{
							foreach ($info->ns->hostObj as $v)
							{
								$hostname = (string)strtolower($v);
								if (FQDN::IsSubdomain($hostname, $domain->GetHostName()))
								{
									try
									{
										$ip = $this->GetHostIpAddress($hostname);
										$ns_arr[] = new NameserverHost($hostname, $ip);
									}
									catch (Exception $e) 
									{
										$ns_arr[] = new NameserverHost($hostname, '');
									}
								}
								else
								{
									// nameserver
									$ns_arr[] = new Nameserver($hostname);			 
								}							
							}
						}
					}
					$resp->SetNameserverList($ns_arr);

					
					// Flags (Domain status)
					$flags = array();
					foreach ($info->status as $status)
					{
						$flags[] = (string)$status->attributes()->s;
					}
					
					$resp->RegistryStatus = (string)$flags[0];
					
					// Remove default 'ok' status from domain flags 
					if (($i = array_search("ok", $flags)) !== false) {
						array_splice($flags, $i, 1);
					}
					$resp->SetFlagList($flags);					
				}
			}
		
			return $resp;
		}
예제 #4
0
파일: ns.php 프로젝트: rchicoria/epp-drs
				
				$okmsg = sprintf(_("Managed DNS disabled successfully for %s"), $Domain->GetHostName());
				CoreUtils::Redirect("ns.php");
			}
		}
		elseif ($post_task == "modify")
		{	
			$registryOptions = $Registry->GetManifest()->GetRegistryOptions();
			$host_as_attr = (bool)$registryOptions->ability->hostattr;
			
			$nslist = array();
			foreach ($post_ns as $k => $hostname)
			{
				if ($hostname && !in_array($hostname, (array)$post_delete))
				{
					if ($host_as_attr && FQDN::IsSubdomain($hostname, $Domain->GetHostName()))
					{
						$nslist[] = new NameserverHost($hostname, $post_ns_ip[$k]);
					}
					else
					{
						$nslist[] = new Nameserver($hostname);						
					}
				}
			}
			
			try
			{
				$Action = new UpdateDomainNameserversAction($Domain, $nslist);
				$result = $Action->Run($_SESSION['userid']);
				if ($result == UpdateDomainNameserversAction_Result::OK)
예제 #5
0
/**
 * Update all Network Organisation
 *
 * @param $ADDTODISPLAYPREF
**/
function updateNetworkFramework(&$ADDTODISPLAYPREF)
{
    global $DB, $migration;
    $ADDTODISPLAYPREF['FQDN'] = array(11);
    $ADDTODISPLAYPREF['WifiNetwork'] = array(10);
    $ADDTODISPLAYPREF['NetworkPortMigration'] = array();
    $ADDTODISPLAYPREF['IPNetwork'] = array(14, 10, 11, 12, 13);
    $ADDTODISPLAYPREF['NetworkName'] = array(12, 13);
    $optionIndex = 10;
    foreach (NetworkPortMigration::getMotives() as $key => $name) {
        $ADDTODISPLAYPREF['NetworkPortMigration'][] = $optionIndex++;
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'Network framework'));
    $originTables = array();
    foreach (array('glpi_networkports', 'glpi_networkequipments') as $table) {
        $originTables[$table] = 'origin_' . $table;
    }
    if (!TableExists('origin_glpi_networkequipments')) {
        // remove of mac field from glpi_networkequipments is done at the end of migration
        // framework process
        if (!FieldExists('glpi_networkequipments', 'mac')) {
            // Nothing to be done : migration of NetworkPort already OK !
            // But don't add display preference for NetworkPortMigration if none exists
            if (!TableExists('glpi_networkportmigrations')) {
                unset($ADDTODISPLAYPREF['NetworkPortMigration']);
            }
            $migration->displayWarning('Network Framework already migrated: nothing to be done !', false);
            return;
        }
        foreach ($originTables as $table => $originTable) {
            if (!TableExists($originTable) && TableExists($table)) {
                $migration->copyTable($table, $originTable);
                $migration->displayWarning("To be safe, we are working on {$originTable}. " . "It is a copy of {$table}", false);
            }
        }
    }
    // Remove all tables created by any previous migration
    $new_network_ports = array('glpi_fqdns', 'glpi_ipaddresses', 'glpi_ipaddresses_ipnetworks', 'glpi_ipnetworks', 'glpi_networkaliases', 'glpi_networknames', 'glpi_networkportaggregates', 'glpi_networkportdialups', 'glpi_networkportethernets', 'glpi_networkportlocals', 'glpi_networkportmigrations', 'glpi_networkportwifis', 'glpi_wifinetworks');
    foreach ($new_network_ports as $table) {
        $migration->dropTable($table);
    }
    // Create the glpi_networkportmigrations that is a copy of origin_glpi_networkports
    $query = "CREATE TABLE `glpi_networkportmigrations` LIKE `origin_glpi_networkports`";
    $DB->queryOrDie($query, "0.84 create glpi_networkportmigrations");
    // And add the error motive fields
    foreach (NetworkPortMigration::getMotives() as $key => $name) {
        $migration->addField('glpi_networkportmigrations', $key, 'bool');
    }
    $migration->migrationOneTable('glpi_networkportmigrations');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_fqdns'));
    // Adding FQDN table
    if (!TableExists('glpi_fqdns')) {
        $query = "CREATE TABLE `glpi_fqdns` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `fqdn` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `name` (`name`),\n                  KEY `fqdn` (`fqdn`),\n                  KEY `is_recursive` (`is_recursive`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_fqdns");
        $fqdn = new FQDN();
        // Then, populate it from domains (beware that "domains" can be FQDNs and Windows workgroups)
        $query = "SELECT DISTINCT LOWER(`name`) AS name, `comment`\n                FROM `glpi_domains`";
        foreach ($DB->request($query) as $domain) {
            $domainName = $domain['name'];
            // We ensure that domains have at least 1 dote to be sure it is not a Windows workgroup
            if (strpos($domainName, '.') !== false && FQDN::checkFQDN($domainName)) {
                $migration->insertInTable($fqdn->getTable(), array('entities_id' => 0, 'name' => $domainName, 'fqdn' => $domainName, 'comment' => $domain['comment']));
            }
        }
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_ipaddresses'));
    // Adding IPAddress table
    if (!TableExists('glpi_ipaddresses')) {
        $query = "CREATE TABLE `glpi_ipaddresses` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  `itemtype` varchar(100) COLLATE utf8_unicode_ci NOT NULL,\n                  `version` tinyint unsigned DEFAULT '0',\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `binary_0`  int unsigned NOT NULL DEFAULT '0',\n                  `binary_1`  int unsigned NOT NULL DEFAULT '0',\n                  `binary_2`  int unsigned NOT NULL DEFAULT '0',\n                  `binary_3`  int unsigned NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `textual` (`name`),\n                  KEY `binary` (`binary_0`, `binary_1`, `binary_2`, `binary_3`),\n                  KEY `item` (`itemtype`, `items_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_ipaddresses");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_wifinetworks'));
    // Adding WifiNetwork table
    if (!TableExists('glpi_wifinetworks')) {
        $query = "CREATE TABLE `glpi_wifinetworks` (\n                 `id` int(11) NOT NULL AUTO_INCREMENT,\n                 `entities_id` int(11) NOT NULL DEFAULT '0',\n                 `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n                 `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                 `essid` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                 `mode` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL\n                        COMMENT 'ad-hoc, access_point',\n                 `comment` text COLLATE utf8_unicode_ci,\n                 PRIMARY KEY (`id`),\n                 KEY `entities_id` (`entities_id`),\n                 KEY `essid` (`essid`),\n                 KEY `name` (`name`)\n               ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_wifinetworks");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), "glpi_ipnetworks"));
    // Adding IPNetwork table
    if (!TableExists('glpi_ipnetworks')) {
        $query = "CREATE TABLE `glpi_ipnetworks` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n                  `ipnetworks_id` int(11) NOT NULL DEFAULT '0',\n                  `completename` text COLLATE utf8_unicode_ci,\n                  `level` int(11) NOT NULL DEFAULT '0',\n                  `ancestors_cache` longtext COLLATE utf8_unicode_ci,\n                  `sons_cache` longtext COLLATE utf8_unicode_ci,\n                  `addressable` tinyint(1) NOT NULL DEFAULT '0',\n                  `version` tinyint unsigned DEFAULT '0',\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `address` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `address_0`  int unsigned NOT NULL DEFAULT '0',\n                  `address_1`  int unsigned NOT NULL DEFAULT '0',\n                  `address_2`  int unsigned NOT NULL DEFAULT '0',\n                  `address_3`  int unsigned NOT NULL DEFAULT '0',\n                  `netmask` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `netmask_0`  int unsigned NOT NULL DEFAULT '0',\n                  `netmask_1`  int unsigned NOT NULL DEFAULT '0',\n                  `netmask_2`  int unsigned NOT NULL DEFAULT '0',\n                  `netmask_3`  int unsigned NOT NULL DEFAULT '0',\n                  `gateway` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `gateway_0`  int unsigned NOT NULL DEFAULT '0',\n                  `gateway_1`  int unsigned NOT NULL DEFAULT '0',\n                  `gateway_2`  int unsigned NOT NULL DEFAULT '0',\n                  `gateway_3`  int unsigned NOT NULL DEFAULT '0',\n                  `comment` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  KEY `network_definition` (`entities_id`,`address`,`netmask`),\n                  KEY `address` (`address_0`, `address_1`, `address_2`, `address_3`),\n                  KEY `netmask` (`netmask_0`, `netmask_1`, `netmask_2`, `netmask_3`),\n                  KEY `gateway` (`gateway_0`, `gateway_1`, `gateway_2`, `gateway_3`),\n                  KEY `name` (`name`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_ipnetworks");
        // Retrieve all the networks from the current network ports and add them to the IPNetworks
        $query = "SELECT DISTINCTROW INET_NTOA(INET_ATON(`ip`)&INET_ATON(`netmask`)) AS address,\n                     `netmask`, `gateway`, `entities_id`\n                FROM `origin_glpi_networkports`\n                ORDER BY `gateway` DESC";
        $address = new IPAddress();
        $netmask = new IPNetmask();
        $gateway = new IPAddress();
        $network = new IPNetwork();
        foreach ($DB->request($query) as $entry) {
            $address = $entry['address'];
            $netmask = $entry['netmask'];
            $gateway = $entry['gateway'];
            $entities_id = $entry['entities_id'];
            if (empty($address) || $address == '0.0.0.0' || empty($netmask) || $netmask == '0.0.0.0' || $netmask == '255.255.255.255') {
                continue;
            }
            if ($gateway == '0.0.0.0') {
                $gateway = '';
            }
            $networkDefinition = "{$address}/{$netmask}";
            $networkName = $networkDefinition . (empty($gateway) ? "" : " - " . $gateway);
            $input = array('entities_id' => $entities_id, 'name' => $networkName, 'network' => $networkDefinition, 'gateway' => $gateway, 'ipnetworks_id' => 0, 'addressable' => 1, 'completename' => $networkName, 'level' => 1);
            $preparedInput = $network->prepareInput($input);
            if (is_array($preparedInput['input'])) {
                $input = $preparedInput['input'];
                if (isset($preparedInput['error'])) {
                    $query = "SELECT id, items_id, itemtype\n                         FROM origin_glpi_networkports\n                         WHERE INET_NTOA(INET_ATON(`ip`)&INET_ATON(`netmask`)) = '{$address}'\n                               AND `netmask` = '{$netmask}'\n                               AND `gateway` = '{$gateway}'\n                               AND `entities_id` = '{$entities_id}'";
                    $result = $DB->query($query);
                    foreach ($DB->request($query) as $data) {
                        addNetworkPortMigrationError($data['id'], 'invalid_gateway');
                        logNetworkPortError('network warning', $data['id'], $data['itemtype'], $data['items_id'], $preparedInput['error']);
                    }
                }
                $migration->insertInTable($network->getTable(), $input);
            } else {
                if (isset($preparedInput['error'])) {
                    $query = "SELECT id, items_id, itemtype\n                      FROM origin_glpi_networkports\n                      WHERE INET_NTOA(INET_ATON(`ip`)&INET_ATON(`netmask`)) = '" . $entry['address'] . "'\n                            AND `netmask` = '{$netmask}'\n                            AND `gateway` = '{$gateway}'\n                            AND `entities_id` = '{$entities_id}'";
                    $result = $DB->query($query);
                    foreach ($DB->request($query) as $data) {
                        addNetworkPortMigrationError($data['id'], 'invalid_network');
                        logNetworkPortError('network error', $data['id'], $data['itemtype'], $data['items_id'], $preparedInput['error']);
                    }
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), "glpi_ipnetworks_vlans"));
    // Adding IPNetwork table
    if (!TableExists('glpi_ipnetworks_vlans')) {
        $query = "CREATE TABLE `glpi_ipnetworks_vlans` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `ipnetworks_id` int(11) NOT NULL DEFAULT '0',\n                  `vlans_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `link` (`ipnetworks_id`, `vlans_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.84 create glpi_ipnetworks_vlans");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), "glpi_networknames"));
    // Adding NetworkName table
    if (!TableExists('glpi_networknames')) {
        $query = "CREATE TABLE `glpi_networknames` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  `itemtype` varchar(100) COLLATE utf8_unicode_ci NOT NULL,\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  `fqdns_id` int(11) NOT NULL DEFAULT '0',\n                  `is_deleted` tinyint(1) NOT NULL DEFAULT '0',\n                  `is_dynamic` tinyint(1) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `FQDN` (`name`,`fqdns_id`),\n                  KEY `name` (`name`),\n                  KEY `item` (`itemtype`, `items_id`),\n                  KEY `fqdns_id` (`fqdns_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_networknames");
        // Retrieve all the networks from the current network ports and add them to the IPNetworks
        $query = "SELECT `ip`, `id`, `entities_id`, `itemtype`, `items_id`\n                FROM `origin_glpi_networkports`\n                WHERE `ip` <> ''";
        foreach ($DB->request($query) as $entry) {
            if (empty($entry["ip"])) {
                continue;
            }
            createNetworkNameFromItem('NetworkPort', $entry['id'], $entry['items_id'], $entry['itemtype'], $entry['entities_id'], $entry["ip"]);
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), "glpi_networkaliases"));
    // Adding NetworkAlias table
    if (!TableExists('glpi_networkaliases')) {
        $query = "CREATE TABLE `glpi_networkaliases` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `networknames_id` int(11) NOT NULL DEFAULT '0',\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `fqdns_id` int(11) NOT NULL DEFAULT '0',\n                  `comment` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `name` (`name`),\n                  KEY `networknames_id` (`networknames_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_networkaliases");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), "glpi_ipaddresses_ipnetworks"));
    // Adding IPAddress_IPNetwork table
    if (!TableExists('glpi_ipaddresses_ipnetworks')) {
        $query = "CREATE TABLE `glpi_ipaddresses_ipnetworks` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `ipaddresses_id` int(11) NOT NULL DEFAULT '0',\n                  `ipnetworks_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`ipaddresses_id`,`ipnetworks_id`),\n                  KEY `ipnetworks_id` (`ipnetworks_id`),\n                  KEY `ipaddresses_id` (`ipaddresses_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.84 create glpi_ipaddresses_ipnetworks");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), "glpi_networkinterfaces"));
    // Update NetworkPorts
    $migration->addField('glpi_networkports', 'instantiation_type', 'string', array('after' => 'name', 'update' => "'NetworkPortEthernet'"));
    $migration->displayMessage(sprintf(__('Data migration - %s'), "glpi_networkports"));
    // Retrieve all the networks from the current network ports and add them to the IPNetwork
    $query = "SELECT *\n             FROM `glpi_networkinterfaces`";
    foreach ($DB->request($query) as $entry) {
        $instantiation_type = "";
        switch ($entry['name']) {
            case 'Local':
                $instantiation_type = "NetworkPortLocal";
                break;
            case 'Ethernet':
                $instantiation_type = "NetworkPortEthernet";
                break;
            case 'Wifi':
                $instantiation_type = "NetworkPortWifi";
                break;
            case 'Dialup':
                $instantiation_type = "NetworkPortDialup";
                break;
            default:
                if (preg_match('/TX/i', $entry['name']) || preg_match('/SX/i', $entry['name']) || preg_match('/Ethernet/i', $entry['name'])) {
                    $instantiation_type = "NetworkPortEthernet";
                }
                break;
        }
        /// In case of unknown Interface Type, we should have to set instantiation_type to ''
        /// Thus we should be able to convert it later to correct type (ethernet, wifi, loopback ...)
        if (!empty($instantiation_type)) {
            $query = "UPDATE `glpi_networkports`\n                   SET `instantiation_type` = '{$instantiation_type}'\n                   WHERE `id` IN (SELECT `id`\n                                  FROM `origin_glpi_networkports`\n                                  WHERE `networkinterfaces_id` = '" . $entry['id'] . "')";
            $DB->queryOrDie($query, "0.84 update instantiation_type field of glpi_networkports");
            // Clear $instantiation_type for next check inside the loop
            unset($instantiation_type);
        }
    }
    foreach (array('ip', 'gateway', 'netmask', 'netpoints_id', 'networkinterfaces_id', 'subnet') as $field) {
        $migration->dropField('glpi_networkports', $field);
    }
    foreach (array('ip', 'mac') as $field) {
        $migration->dropField('glpi_networkequipments', $field);
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'Index mac field and transform address mac to lower'));
    $query = "UPDATE `glpi_networkports`\n             SET `mac` = LOWER(`mac`)";
    $DB->queryOrDie($query, "0.84 transforme MAC to lower case");
    $migration->addKey('glpi_networkports', 'mac');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'Update migration of interfaces errors'));
    $query = "SELECT id\n             FROM `glpi_networkports`\n             WHERE `instantiation_type` = ''";
    foreach ($DB->request($query) as $networkPortID) {
        addNetworkPortMigrationError($networkPortID['id'], 'unknown_interface_type');
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), "glpi_networkportethernets"));
    // Adding NetworkPortEthernet table
    if (!TableExists('glpi_networkportethernets')) {
        $query = "CREATE TABLE `glpi_networkportethernets` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `networkports_id` int(11) NOT NULL DEFAULT '0',\n                  `items_devicenetworkcards_id` int(11) NOT NULL DEFAULT '0',\n                  `netpoints_id` int(11) NOT NULL DEFAULT '0',\n                  `type` varchar(10) COLLATE utf8_unicode_ci DEFAULT '' COMMENT 'T, LX, SX',\n                  `speed` int(11) NOT NULL DEFAULT '10' COMMENT 'Mbit/s: 10, 100, 1000, 10000',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `networkports_id` (`networkports_id`),\n                  KEY `card` (`items_devicenetworkcards_id`),\n                  KEY `netpoint` (`netpoints_id`),\n                  KEY `type` (`type`),\n                  KEY `speed` (`speed`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_networkportethernets");
        $port = new NetworkPortEthernet();
        updateNetworkPortInstantiation($port, array('`netpoints_id`' => 'netpoints_id'), true);
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), "glpi_networkportwifis"));
    // Adding NetworkPortWifi table
    if (!TableExists('glpi_networkportwifis')) {
        $query = "CREATE TABLE `glpi_networkportwifis` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `networkports_id` int(11) NOT NULL DEFAULT '0',\n                  `items_devicenetworkcards_id` int(11) NOT NULL DEFAULT '0',\n                  `wifinetworks_id` int(11) NOT NULL DEFAULT '0',\n                  `networkportwifis_id` int(11) NOT NULL DEFAULT '0'\n                                        COMMENT 'only usefull in case of Managed node',\n                  `version` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL\n                            COMMENT 'a, a/b, a/b/g, a/b/g/n, a/b/g/n/y',\n                  `mode` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL\n                         COMMENT 'ad-hoc, managed, master, repeater, secondary, monitor, auto',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `networkports_id` (`networkports_id`),\n                  KEY `card` (`items_devicenetworkcards_id`),\n                  KEY `essid` (`wifinetworks_id`),\n                  KEY `version` (`version`),\n                  KEY `mode` (`mode`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_networkportwifis");
        $port = new NetworkPortWifi();
        updateNetworkPortInstantiation($port, array(), true);
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), "glpi_networkportlocals"));
    // Adding NetworkPortLocal table
    if (!TableExists('glpi_networkportlocals')) {
        $query = "CREATE TABLE `glpi_networkportlocals` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `networkports_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `networkports_id` (`networkports_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_networkportlocals");
        $port = new NetworkPortLocal();
        updateNetworkPortInstantiation($port, array(), false);
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), "glpi_networkportdialups"));
    // Adding NetworkPortDialup table
    if (!TableExists('glpi_networkportdialups')) {
        $query = "CREATE TABLE `glpi_networkportdialups` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `networkports_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `networkports_id` (`networkports_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_networkportdialups");
        $port = new NetworkPortDialup();
        updateNetworkPortInstantiation($port, array(), true);
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), "glpi_networkportaggregates"));
    // Adding NetworkPortAggregate table
    if (!TableExists('glpi_networkportaggregates')) {
        $query = "CREATE TABLE `glpi_networkportaggregates` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `networkports_id` int(11) NOT NULL DEFAULT '0',\n                  `networkports_id_list` TEXT DEFAULT NULL\n                             COMMENT 'array of associated networkports_id',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `networkports_id` (`networkports_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_networkportaggregates");
        // Transform NetworkEquipment local MAC address as a networkport that aggregates all ports
        $query = "SELECT *\n                FROM `origin_glpi_networkequipments`\n                WHERE `mac` != ''\n                      OR `ip` != ''";
        $port_input = array('itemtype' => 'NetworkEquipment', 'logical_number' => '0', 'name' => 'management', 'instantiation_type' => 'NetworkPortAggregate');
        foreach ($DB->request($query) as $equipment) {
            $networkequipments_id = $equipment['id'];
            $query = "SELECT `id`, `ip`, `mac`\n                   FROM `origin_glpi_networkports`\n                   WHERE `itemtype` = 'NetworkEquipment'\n                         AND `items_id` = '{$networkequipments_id}'\n                         AND (`ip` = '" . $equipment['ip'] . "'\n                              OR `mac` = '" . $equipment['mac'] . "')";
            $both = array();
            $mac = array();
            $ip = array();
            foreach ($DB->request($query) as $ports) {
                if ($ports['ip'] == $equipment['ip']) {
                    if ($ports['mac'] == $equipment['mac']) {
                        $both[] = $ports['id'];
                    } else {
                        $ip[] = $ports['id'];
                    }
                } else {
                    $mac[] = $ports['id'];
                }
            }
            if (count($both) != 1) {
                // Only add a NetworkPort if there is 0 or more than one element !
                $port_input['items_id'] = $networkequipments_id;
                $port_input['entities_id'] = $equipment['entities_id'];
                $port_input['is_recursive'] = $equipment['is_recursive'];
                $port_input['mac'] = strtolower($equipment['mac']);
                $networkports_id = $migration->insertInTable('glpi_networkports', $port_input);
                $aggregate_input = array();
                $aggregate_input['networkports_id'] = $networkports_id;
                $aggregate_input['networkports_id_list'] = exportArrayToDB($both);
                $migration->insertInTable('glpi_networkportaggregates', $aggregate_input);
                createNetworkNameFromItem('NetworkPort', $networkports_id, $equipment['id'], 'NetworkEquipment', $equipment['entities_id'], $equipment['ip']);
                foreach ($both as $aggregated_networkports_id) {
                    $query = "DELETE\n                         FROM `glpi_networknames`\n                         WHERE `itemtype` = 'NetworkPort'\n                               AND `items_id` = '{$aggregated_networkports_id}'";
                    $DB->query($query);
                    $query = "UPDATE `glpi_networkports`\n                         SET `mac` = ''\n                         WHERE `id` = '{$aggregated_networkports_id}'";
                    $DB->query($query);
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), "glpi_networkportaliases"));
    // Adding NetworkPortAlias table
    if (!TableExists('glpi_networkportaliases')) {
        $query = "CREATE TABLE `glpi_networkportaliases` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `networkports_id` int(11) NOT NULL DEFAULT '0',\n                  `networkports_id_alias` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `networkports_id` (`networkports_id`),\n                  KEY `networkports_id_alias` (`networkports_id_alias`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_networkportaliases");
        // New element, so, we don't need to create items
    }
    $migration->addField('glpi_networkports_vlans', 'tagged', 'bool', array('value' => '0'));
    $migration->addField('glpi_vlans', 'entities_id', 'integer', array('value' => '0', 'after' => 'id'));
    $migration->addKey('glpi_vlans', 'entities_id');
    $migration->addField('glpi_vlans', 'is_recursive', 'bool', array('value' => '0', 'after' => 'entities_id', 'update' => '1'));
    $migration->addKey('glpi_vlans', 'tag');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'Update connections between IPAddress and IPNetwork'));
    // Here, we are sure that there is only IPv4 addresses. So, the SQL requests are simplified
    $query = "SELECT `id`, `address_3`, `netmask_3`\n             FROM `glpi_ipnetworks`";
    if ($network_result = $DB->query($query)) {
        unset($query);
        while ($ipnetwork_row = $DB->fetch_assoc($network_result)) {
            $ipnetworks_id = $ipnetwork_row['id'];
            $netmask = floatval($ipnetwork_row['netmask_3']);
            $address = floatval($ipnetwork_row['address_3']) & $netmask;
            $query = "SELECT `id`\n                   FROM `glpi_ipaddresses`\n                   WHERE (`glpi_ipaddresses`.`binary_3` & '{$netmask}') = {$address}\n                         AND `glpi_ipaddresses`.`version` = '4'\n                   GROUP BY `items_id`";
            if ($ipaddress_result = $DB->query($query)) {
                unset($query);
                while ($link = $DB->fetch_assoc($ipaddress_result)) {
                    $query = "INSERT INTO `glpi_ipaddresses_ipnetworks`\n                                (`ipaddresses_id`, `ipnetworks_id`)\n                         VALUES ('" . $link['id'] . "', '{$ipnetworks_id}')";
                    $DB->query($query);
                    unset($query);
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Drop table glpi_networkportmigrations if empty'));
    if (countElementsInTable("glpi_networkportmigrations") == 0) {
        $migration->dropTable("glpi_networkportmigrations");
        $migration->dropTable("glpi_networkportinterfaces");
        unset($ADDTODISPLAYPREF['NetworkPortMigration']);
    }
    // We migrate glpi_networkequipments: mac field presence is used to check if framework has
    // already been migrated
    $migration->migrationOneTable('glpi_networkequipments');
    foreach ($originTables as $table) {
        $migration->dropTable($table);
    }
}
예제 #6
0
 /**
  * This method request registry for information about domain
  * 
  * @param Domain $domain 
  * @return GetRemoteDomainResponse
  */
 public function GetRemoteDomain(Domain $domain)
 {
     $hostname = $domain->GetHostName();
     $is_idn = $this->RegistryAccessible->IsIDNHostName($hostname);
     $params = array('name' => $is_idn ? $this->RegistryAccessible->PunycodeEncode($hostname) : $hostname);
     $response = $this->Request("domain-info", $params);
     $status = $response->Succeed ? REGISTRY_RESPONSE_STATUS::SUCCESS : REGISTRY_RESPONSE_STATUS::FAILED;
     $ret = new GetRemoteDomainResponse($status, $response->ErrMsg, $response->Code);
     if ($ret->Succeed()) {
         $info = $response->Data->response->resData->children($this->XmlNamespaces['domain']);
         $info = $info[0];
         $ret->CRID = (string) $info->crID[0];
         $ret->CLID = (string) $info->clID[0];
         if ($ret->CLID) {
             // Contacts
             $ret->RegistrantContact = (string) $info->registrant[0];
             $contact = $info->xpath('domain:contact[@type="admin"]');
             $ret->AdminContact = (string) $contact[0];
             $contact = $info->xpath('domain:contact[@type="tech"]');
             $ret->TechContact = (string) $contact[0];
             $ret->CreateDate = strtotime($info->crDate[0]);
             $ret->ExpireDate = strtotime($info->exDate[0]);
             // Nameservers
             $ns_arr = array();
             foreach ($info->xpath('domain:ns/domain:hostObj') as $hostObj) {
                 $hostname = (string) $hostObj;
                 if (FQDN::IsSubdomain($hostname, $domain->GetHostName())) {
                     try {
                         $ip = $this->GetHostIpAddress($hostname);
                         $ns_arr[] = new NameserverHost($hostname, $ip);
                     } catch (Exception $e) {
                         $ns_arr[] = new NameserverHost($hostname, '');
                     }
                 } else {
                     // nameserver
                     $ns_arr[] = new Nameserver($hostname);
                 }
             }
             $ret->SetNameserverList($ns_arr);
             // Flags
             $flags = array();
             if ($nodes = $info->xpath('domain:status/@s')) {
                 foreach ($nodes as $flag) {
                     $flags[] = (string) $flag;
                 }
             }
             if ($nodes = $response->Data->xpath('//dnslu:domain/dnslu:status')) {
                 foreach ($nodes as $flag) {
                     $flags[] = (string) $flag;
                 }
             }
             $ret->RegistryStatus = (string) $flags[0];
             $flags = array_filter($flags);
             // Remove default 'ok' status from domain flags
             if (($i = array_search("ok", $flags)) !== false) {
                 array_splice($flags, $i, 1);
             }
             $ret->SetFlagList($flags);
         }
         $ret->AuthCode = '';
         $ret->Protocol = '';
     }
     return $ret;
 }
예제 #7
0
		/**
		 * Return information about domain
		 * 
		 * @access public
		 * @param Domain $domain 
		 * @return GetRemoteDomainResponse Domain info if the following format:
		 */
		public function GetRemoteDomain(Domain $domain)
		{
			$params = array(
				"name"	=> $this->MakeNameIDNCompatible($domain->GetHostName()),			
				'authinfo' => ''			
			);
			if ($domain->AuthCode)
				$params['authinfo'] = "<domain:authInfo><domain:pw>".$this->EscapeXML($domain->AuthCode)."</domain:pw></domain:authInfo>";				
			
			$response = $this->Request("domain-info", $params);
			
			$status = ($response->Succeed) ? REGISTRY_RESPONSE_STATUS::SUCCESS : REGISTRY_RESPONSE_STATUS::FAILED;
			$resp = new GetRemoteDomainResponse($status, $response->ErrMsg, $response->Code);
	
			if ($response->Succeed)
			{
				$info = $response->Data->response->resData->children("urn:ietf:params:xml:ns:domain-1.0");
				$info = $info[0];
				
				$resp->CLID = (string)$info->clID[0];
				

				$resp->AuthCode = ($info->authInfo[0]) ? (string)$info->authInfo[0]->pw[0] : "";
				
				if ($info->exDate[0])
				{
					$resp->ExpireDate = $this->StrToTime((string)$info->exDate[0]); 
					$resp->CreateDate = $resp->ExpireDate-(86400*365);
				}
				
				foreach ($info->contact as $k=>$v)
				{
					$attrs = $v->attributes();
					$ctype = (string)$attrs["type"];
					
					switch($ctype)
					{
						case "tech":
							$resp->TechContact = (string)$v;
							break;
					}
				}
				
				$resp->RegistrantContact = (string)$info->registrant[0];
				
				// Get nameservers
				$ns_arr = array();
				foreach ($info->ns->hostObj as $v)
				{
					$hostname = (string)$v;
					if (FQDN::IsSubdomain($hostname, $domain->GetHostName()))
					{
						try
						{
							$ip = $this->GetHostIpAddress($hostname);
							$ns_arr[] = new NameserverHost($hostname, $ip);
						}
						catch (Exception $e) 
						{
							$ns_arr[] = new NameserverHost($hostname, '');
						}
					}
					else
					{
						// nameserver
						$ns_arr[] = new Nameserver($hostname);						 
					}					
				}
				
				$resp->SetNameserverList($ns_arr);
				
				if ($info->status[0])
				    $attrs = $info->status[0]->attributes();
				elseif ($info->status)
				    $attrs = $info->status->attributes();
				else 
				    $attrs["s"] = false;
				    
				$resp->RegistryStatus = (string)$attrs["s"];
			}
			
			return $resp;
		}
예제 #8
0
 /**
  * This method request registry for information about domain
  * 
  * @param Domain $domain 
  * @return GetRemoteDomainResponse
  */
 public function GetRemoteDomain(Domain $domain)
 {
     $params = array("name" => $this->MakeNameIDNCompatible($domain->GetHostName()), 'authinfo' => '', 'subproduct' => 'dot' . strtoupper($this->Extension));
     if ($domain->AuthCode) {
         $params['authinfo'] = "<domain:authInfo><domain:pw>{$domain->AuthCode}</domain:pw></domain:authInfo>";
     }
     $response = $this->Request("domain-info", $params);
     $status = $response->Succeed ? REGISTRY_RESPONSE_STATUS::SUCCESS : REGISTRY_RESPONSE_STATUS::FAILED;
     $resp = new GetRemoteDomainResponse($status, $response->ErrMsg, $response->Code);
     $response->Data->registerXPathNamespace('rgp', $this->XmlNamespaces['rgp']);
     if ($response->Succeed) {
         $info = $response->Data->response->resData->children($this->XmlNamespaces['domain']);
         $info = $info[0];
         $resp->CLID = (string) $info->clID[0];
         try {
             $resp->CRID = (string) $info->crID[0];
         } catch (Exception $e) {
         }
         if ($resp->CRID) {
             $resp->AuthCode = $info->authInfo[0] ? (string) $info->authInfo[0]->pw[0] : "";
             $resp->CreateDate = $this->StrToTime((string) $info->crDate[0]);
             $resp->ExpireDate = $this->StrToTime((string) $info->exDate[0]);
             // Request whois for contacts
             $domain_whois = $this->Db->GetRow("\r\n\t\t\t\t\t\tSELECT * FROM whois_domain WHERE domain = ?", array($domain->GetHostName()));
             if ($domain_whois) {
                 $resp->RegistrantContact = $this->PersonIdToCLID($domain_whois['holder']);
                 $resp->AdminContact = $this->PersonIdToCLID($domain_whois['admin_c']);
                 $resp->TechContact = $this->PersonIdToCLID($domain_whois['tech_c']);
                 $resp->BillingContact = $this->PersonIdToCLID($domain_whois['bill_c']);
             }
             // Get nameservers
             $ns_arr = array();
             if ($info->ns) {
                 foreach ($info->ns->hostObj as $v) {
                     $hostname = (string) $v;
                     if (FQDN::IsSubdomain($hostname, $domain->GetHostName())) {
                         try {
                             $ip = $this->GetHostIpAddress($hostname);
                             $ns_arr[] = new NameserverHost($hostname, $ip);
                         } catch (Exception $e) {
                             $ns_arr[] = new NameserverHost($hostname, '');
                         }
                     } else {
                         // nameserver
                         $ns_arr[] = new Nameserver($hostname);
                     }
                 }
             }
             $resp->SetNameserverList($ns_arr);
             // Flags (Domain status)
             $flags = array();
             if ($nodes = $info->xpath('domain:status/@s')) {
                 foreach ($nodes as $flag) {
                     $flags[] = (string) $flag;
                 }
             }
             // Not works. Why ??
             //				if ($nodes = $response->Data->response->xpath('//rgp:infData/rgp:rgpStatus/@s'))
             //					foreach ($nodes as $flag)
             //						$flags[] = (string)$flag;
             // Intead of glamour XPath expression use ugly hack
             if ($response->Data->response->extension) {
                 $rgpInfo = $response->Data->response->extension->children($this->XmlNamespaces['rgp']);
                 foreach ($rgpInfo->rgpStatus as $status) {
                     $flag[] = (string) $status->attributes()->s;
                 }
             }
             $resp->SetFlagList($flags);
             $resp->RegistryStatus = $flags[0];
         }
     }
     return $resp;
 }
예제 #9
0
 private function CreateObject($row, RegistryManifest $registry_manifest = null)
 {
     /*
     if ($registry_manifest == null)
     {
     	$registry = RegistryModuleFactory::GetInstance()->GetRegistryByExtension($row['TLD']);
     	$registry_manifest = $registry->GetManifest();
     	unset($registry);
     }
     */
     // TODO
     // ���������� ���������� �� ������������ ������, ���� ������� ���� ��������
     // ��������� ������� Domain
     //
     $registry = RegistryModuleFactory::GetInstance()->GetRegistryByExtension($row['TLD']);
     if (!$registry) {
         throw new Exception(sprintf(_("Registry module not defined for '%s' domain extension"), $row['TLD']));
     }
     $domain = $registry->NewDomainInstance();
     $registry_manifest = $registry->GetManifest();
     //unset($registry);
     // Normalize DB data
     $row['start_date'] = strtotime($row['start_date']);
     $row['end_date'] = strtotime($row['end_date']);
     $row['dtTransfer'] = strtotime($row['dtTransfer']);
     $row["islocked"] = (bool) $row["islocked"];
     $row['managed_dns'] = (bool) $row['managed_dns'];
     // Normalize nameservers data
     $ns_arr = array();
     if ($row['ns1']) {
         $ns_arr[] = $row['ns1'];
     }
     if ($row['ns2']) {
         $ns_arr[] = $row['ns2'];
     }
     if ($row['ns_n']) {
         $ns_n = array_map('trim', explode(';', $row['ns_n']));
         foreach ($ns_n as $hostname) {
             $ns_arr[] = $hostname;
         }
     }
     // Load glue records
     $arr = $this->DB->GetAll('SELECT * FROM nhosts WHERE domainid = ?', array($row['id']));
     $glue_records = array();
     foreach ($arr as $tmp) {
         $glue_records["{$tmp['hostname']}.{$row['name']}.{$row['TLD']}"] = $tmp;
     }
     // Create nameservers list
     $nslist = array();
     foreach ($ns_arr as $hostname) {
         // Check that nameserver is glue record.
         if (FQDN::IsSubdomain($hostname, "{$row["name"]}.{$row["TLD"]}") && array_key_exists($hostname, $glue_records)) {
             $nshost = new NameserverHost($hostname, $glue_records[$hostname]['ipaddr']);
             $nshost->ID = $glue_records[$hostname]['id'];
             $nslist[] = $nshost;
         } else {
             $nslist[] = new Nameserver($hostname);
         }
     }
     // Map fields to properties
     foreach ($this->FieldPropertyMap as $field => $property) {
         $domain->{$property} = $row[$field];
     }
     // Set nameservers
     $domain->SetNameserverList($nslist);
     // Load extra fields
     $extra_fields = $this->DB->GetAll('SELECT `key`, `value` FROM domains_data WHERE domainid = ?', array($domain->ID));
     foreach ($extra_fields as $ext_row) {
         $domain->{$ext_row['key']} = $ext_row['value'];
         $domain->SetExtraField($ext_row['key'], $ext_row['value']);
     }
     // Load flags
     $flags_data = $this->DB->GetAll('SELECT DISTINCT flag FROM domains_flags WHERE domainid = ?', array($domain->ID));
     $flag_list = array();
     foreach ($flags_data as $flag_row) {
         $flag_list[] = $flag_row['flag'];
     }
     $domain->SetFlagList($flag_list);
     // Load contacts
     foreach ($this->ContactFieldTypeMap as $field => $contact_type) {
         $CLID = $row[$field];
         if ($CLID) {
             try {
                 $contact = $this->DBContact->LoadByCLID($CLID, $registry_manifest);
             } catch (Exception $e) {
                 $contact = $registry->NewContactInstance($contact_type);
                 $contact->CLID = $CLID;
             }
             $domain->SetContact($contact, $contact_type);
         }
     }
     // Add pending operations to domain
     $operations = $this->DB->Execute("SELECT * FROM pending_operations WHERE objecttype='DOMAIN' AND objectid=?", array($domain->ID));
     while ($op = $operations->FetchRow()) {
         if ($op) {
             $domain->AddPendingOperation($op["operation"]);
         }
     }
     // Add domain to loaded objects storage
     $this->LoadedObjects[$domain->ID] = clone $domain;
     return $domain;
 }
예제 #10
0
 /**
  * Look for "computer name" inside all databases
  *
  * @param $fqdn                     name to search (for instance : forge.indepnet.net)
  * @param $wildcard_search boolean  true if we search with wildcard (false by default)
  *
  * @return (array) each value of the array (corresponding to one NetworkPort) is an array of the
  *                 items from the master item to the NetworkPort
  **/
 static function getItemsByFQDN($fqdn, $wildcard_search = false)
 {
     $FQNDs_with_Items = array();
     if (!$wildcard_search) {
         if (!FQDN::checkFQDN($fqdn)) {
             return array();
         }
     }
     $position = strpos($fqdn, ".");
     if ($position !== false) {
         $label = strtolower(substr($fqdn, 0, $position));
         $fqdns_id = FQDN::getFQDNIDByFQDN(substr($fqdn, $position + 1), $wildcard_search);
     } else {
         $label = $fqdn;
         $fqdns_id = -1;
     }
     foreach (self::getIDsByLabelAndFQDNID($label, $fqdns_id, $wildcard_search) as $class => $IDs) {
         if ($FQDNlabel = getItemForItemtype($class)) {
             foreach ($IDs as $ID) {
                 if ($FQDNlabel->getFromDB($ID)) {
                     $FQNDs_with_Items[] = array_merge(array_reverse($FQDNlabel->recursivelyGetItems()), array(clone $FQDNlabel));
                 }
             }
         }
     }
     return $FQNDs_with_Items;
 }
예제 #11
0
 /**
  * This method request registry for information about domain
  * 
  * @param Domain $domain 
  * @return GetRemoteDomainResponse
  */
 public function GetRemoteDomain(Domain $domain)
 {
     $Resp = $this->Whois($domain);
     $status = $Resp->Succeed ? REGISTRY_RESPONSE_STATUS::SUCCESS : REGISTRY_RESPONSE_STATUS::FAILED;
     $Ret = new GetRemoteDomainResponse($status, $Resp->ErrMsg);
     if ($Ret->Succeed()) {
         $ns_arr = array();
         foreach ($Resp->Data as $k => $v) {
             if (stristr($k, "DNS SERVER")) {
                 $hostname = (string) $v;
                 if (FQDN::IsSubdomain($hostname, $domain->GetHostName())) {
                     try {
                         $ip = $this->GetHostIpAddress($hostname);
                         $ns_arr[] = new NameserverHost($hostname, $ip);
                     } catch (Exception $e) {
                         $ns_arr[] = new NameserverHost($hostname, '');
                     }
                 } else {
                     // nameserver
                     $ns_arr[] = new Nameserver($hostname);
                 }
             }
         }
         $Ret->SetNameserverList($ns_arr);
         $Ret->CRID = $this->Config->GetFieldByName('Login')->Value;
         $Ret->CLID = $this->Config->GetFieldByName('Login')->Value;
         $Ret->CreateDate = (int) $Resp->Data['REGISTRATION DATE'];
         $Ret->ExpireDate = (int) $Resp->Data['EXPIRATION DATE'];
         $Ret->RegistryStatus = 'ok';
         $Ret->RegistrantContact = $Resp->Data['RESPONSIBLE PERSON'];
         $Ret->BillingContact = $Resp->Data['BILLING CONTACT'];
         $Ret->AdminContact = $Resp->Data['ADMIN CONTACT'];
         $Ret->TechContact = $Resp->Data['TECHNICAL CONTACT'];
     }
     return $Ret;
 }
예제 #12
0
<?php

require_once 'src/prepend.inc.php';
@set_time_limit(999999);
if (Client::Load($_SESSION['userid'])->GetSettingValue('domain_preorder') != 1) {
    CoreUtils::Redirect("index.php");
}
if ($_POST) {
    $Validator = new Validator();
    $lines = explode("\n", $post_domains);
    $post_domainname = FQDN::Sanitize($post_domainname);
    list($domain_name, $extension) = FQDN::Parse($post_domainname);
    $expiredate = trim($post_dt);
    // Validate date. Sucks.
    if (!preg_match("/^[0-9]{4}-[0-9]{2}-[0-9]{2}\$/", $expiredate) || !strtotime($expiredate)) {
        throw new ApplicationException(sprintf(_("Incorrect expiration date.")));
    }
    // Validate domain name
    if (!$Validator->IsDomain($post_domainname)) {
        throw new Exception(sprintf(_("Incorrect domain name: %s"), $post_domainname));
    }
    if (!$Registries[$extension]) {
        try {
            $Registry = RegistryModuleFactory::GetInstance()->GetRegistryByExtension($extension);
        } catch (Exception $e) {
            throw new ApplicationException($e->getMessage());
        }
        $Manifest = $Registry->GetManifest();
        if ($Manifest->GetRegistryOptions()->ability->preregistration != 1) {
            throw new ApplicationException(sprintf(_("Module %s does not support domain pre-registration."), $Registry->GetModuleName()));
        }
예제 #13
0
 /**
  * Return information about domain
  * 
  * @access public
  * @param Domain $domain 
  * @return GetRemoteDomainResponse
  */
 public function GetRemoteDomain(Domain $domain)
 {
     if ($domain->AuthCode) {
         $pw = "<domain:authInfo>\r\n\t\t\t\t\t\t<domain:pw>" . $this->EscapeXML($domain->AuthCode) . "</domain:pw>\r\n\t\t\t\t\t</domain:authInfo>";
     } else {
         $pw = '';
     }
     $response = $this->Request("domain-info", array("name" => "{$domain->Name}.{$this->Extension}", "pw" => $pw));
     $status = $response->Succeed ? REGISTRY_RESPONSE_STATUS::SUCCESS : REGISTRY_RESPONSE_STATUS::FAILED;
     $resp = new GetRemoteDomainResponse($status, $response->ErrMsg, $response->Code);
     if ($response->Succeed) {
         $info = $response->Data->response->resData->children("urn:ietf:params:xml:ns:domain-1.0");
         $info = $info[0];
         $resp->CLID = (string) $info->clID[0];
         try {
             $resp->CRID = (string) $info->crID[0];
         } catch (Exception $e) {
         }
         if ($resp->CRID) {
             $resp->AuthCode = $info->authInfo[0] ? (string) $info->authInfo[0]->pw[0] : "";
             $resp->CreateDate = $this->StrToTime((string) $info->crDate[0]);
             $resp->ExpireDate = $this->StrToTime((string) $info->exDate[0]);
             $extdomain = $response->Data->response->extension->children("urn:ics-forth:params:xml:ns:extdomain-1.1");
             $resp->Protocol = (string) $extdomain->resData->protocol[0];
             foreach ($info->contact as $k => $v) {
                 $attrs = $v->attributes();
                 $ctype = (string) $attrs["type"];
                 switch ($ctype) {
                     case "admin":
                         $resp->AdminContact = (string) $v;
                         break;
                     case "tech":
                         $resp->TechContact = (string) $v;
                         break;
                     case "billing":
                         $resp->BillingContact = (string) $v;
                         break;
                 }
             }
             $resp->RegistrantContact = (string) $info->registrant[0];
             // Get nameservers
             // TODO: testit
             $ns_arr = array();
             foreach ($info->ns->hostObj as $v) {
                 $hostname = (string) $v;
                 if (FQDN::IsSubdomain($hostname, $domain->GetHostName())) {
                     try {
                         $ip = $this->GetHostIpAddress($hostname);
                         $ns_arr[] = new NameserverHost($hostname, $ip);
                     } catch (Exception $e) {
                         $ns_arr[] = new NameserverHost($hostname, '');
                     }
                 } else {
                     // nameserver
                     $ns_arr[] = new Nameserver($hostname);
                 }
             }
             $resp->SetNameserverList($ns_arr);
             if ($info->status[0]) {
                 $attrs = $info->status[0]->attributes();
             } elseif ($info->status) {
                 $attrs = $info->status->attributes();
             } else {
                 $attrs["s"] = false;
             }
             $resp->RegistryStatus = (string) $attrs["s"];
         }
     }
     return $resp;
 }
 public function Run(Domain $Domain)
 {
     Log::Log("Start domain registration action", E_USER_NOTICE);
     $ErrList = new ErrorList();
     if (!($Domain->Name && $Domain->Period && $Domain->UserID)) {
         throw new Exception("Domain must have name, period and userid filled");
     }
     if ($this->do_check) {
         // Perform a domain check
         $chk = $this->Registry->DomainCanBeRegistered($Domain);
         if (!$chk->Result) {
             throw new Exception("Domain cannot be registered" . ($chk->Reason ? ". Reason: {$chk->Reason}" : ""));
         }
     }
     if ($this->period) {
         $Domain->Period = $this->period;
     } else {
         self::ValidatePeriod($Domain->Period, $this->Registry);
     }
     /*
      * Set nameservers
      */
     if (!$this->managed_dns_enabled) {
         $domain_hostname = $Domain->GetHostName();
         foreach ($this->nameserver_list as $Nameserver) {
             if (FQDN::IsSubdomain($Nameserver->HostName, $domain_hostname)) {
                 $ErrList->AddMessage(sprintf(_("%s cannot be used as nameserver because %s is not registered yet."), $Nameserver->HostName, $domain_hostname));
             }
         }
     }
     // Break on errors
     $this->ExceptionOnErrors($ErrList);
     $Domain->IsManagedDNSEnabled = $this->managed_dns_enabled;
     $Domain->SetNameserverList($this->nameserver_list);
     /*
      * Set contacts
      */
     foreach ($this->contact_list as $ctype => $Contact) {
         try {
             $Domain->SetContact($Contact, $ctype);
         } catch (Exception $e) {
             $ErrList->AddMessage(sprintf(_("Cannot set %s contact to %s. %s"), $ctype, $clid, $e->getMessage()));
         }
     }
     // Break on errors
     $this->ExceptionOnErrors($ErrList);
     /*
      * Set additional domain data
      */
     if ($this->extra_data) {
         foreach ($this->extra_data as $field) {
             $Domain->SetExtraField($field['name'], $this->extra_data[$field['name']]);
         }
     }
     /*
      * Register domain
      */
     if ($Domain->IncompleteOrderOperation == INCOMPLETE_OPERATION::DOMAIN_CREATE) {
         Log::Log("Trying to register domain. (Postpaid)", E_USER_NOTICE);
         try {
             $this->Registry->CreateDomain($Domain, $Domain->Period, $this->extra_data);
             return $Domain->HasPendingOperation(Registry::OP_CREATE) ? RegisterDomainAction_Result::PENDING : RegisterDomainAction_Result::OK;
         } catch (Exception $e) {
             Log::Log($e->getMessage(), E_USER_ERROR);
             throw new RegisterDomainAction_Exception($e->getMessage());
         }
     } else {
         $Domain->Status = DOMAIN_STATUS::AWAITING_PAYMENT;
         try {
             DBDomain::GetInstance()->Save($Domain);
         } catch (Exception $e) {
             Log::Log($e->getMessage(), E_USER_ERROR);
             throw new RegisterDomainAction_Exception(sprintf(_('Cannot save domain. Reason: %s'), $e->getMessage()));
         }
         try {
             $Invoice = new Invoice(INVOICE_PURPOSE::DOMAIN_CREATE, $Domain->ID, $Domain->UserID);
             $Invoice->Description = sprintf(_("%s domain name registration for %s year(s)"), $Domain->GetHostName(), $Domain->Period);
             if ($this->Order) {
                 // In case of order add invoice.
                 $this->Order->AddInvoice($Invoice);
                 // Save operation must be called from order
             } else {
                 $Invoice->Save();
                 $this->Invoice = $Invoice;
             }
             return RegisterDomainAction_Result::INVOICE_GENERATED;
         } catch (Exception $e) {
             throw new RegisterDomainAction_Exception(sprintf(_("Cannot create invoice. Reason: %s"), $e->getMessage()));
         }
     }
 }
예제 #15
0
 /**
  * @param $networkPortID
  **/
 static function showFormForNetworkPort($networkPortID)
 {
     global $DB, $CFG_GLPI;
     $name = new self();
     $number_names = 0;
     if ($networkPortID > 0) {
         $query = "SELECT `id`\n                   FROM `" . $name->getTable() . "`\n                   WHERE `itemtype` = 'NetworkPort'\n                   AND `items_id` = '{$networkPortID}'\n                   AND `is_deleted` = '0'";
         $result = $DB->query($query);
         if ($DB->numrows($result) > 1) {
             echo "<tr class='tab_bg_1'><th colspan='4'>" . __("Several network names available! Go to the tab 'Network Name' to manage them.") . "</th></tr>\n";
             return;
         }
         switch ($DB->numrows($result)) {
             case 1:
                 $nameID = $DB->fetch_assoc($result);
                 $name->getFromDB($nameID['id']);
                 break;
             case 0:
                 $name->getEmpty();
                 break;
         }
     } else {
         $name->getEmpty();
     }
     echo "<tr class='tab_bg_1'><th colspan='4'>";
     // If the networkname is defined, we must be able to edit it. So we make a link
     if ($name->getID() > 0) {
         echo "<a href='" . $name->getLinkURL() . "'>" . self::getTypeName(1) . "</a>";
         echo "<input type='hidden' name='NetworkName_id' value='" . $name->getID() . "'>&nbsp;\n";
         Html::showSimpleForm($name->getFormURL(), 'unaffect', _sx('button', 'Dissociate'), array('id' => $name->getID()), $CFG_GLPI["root_doc"] . '/pics/sub_dropdown.png');
     } else {
         echo self::getTypeName(1);
     }
     echo "</th>\n";
     echo "</tr><tr class='tab_bg_1'>";
     echo "<td>" . self::getTypeName(1) . "</td><td>\n";
     Html::autocompletionTextField($name, "name", array('name' => 'NetworkName_name'));
     echo "</td>\n";
     echo "<td>" . FQDN::getTypeName(1) . "</td><td>";
     Dropdown::show(getItemTypeForTable(getTableNameForForeignKeyField("fqdns_id")), array('value' => $name->fields["fqdns_id"], 'name' => 'NetworkName_fqdns_id', 'entity' => $name->getEntityID(), 'displaywith' => array('view')));
     echo "</td>\n";
     echo "</tr><tr class='tab_bg_1'>\n";
     echo "<td>" . IPAddress::getTypeName(Session::getPluralNumber());
     IPAddress::showAddChildButtonForItemForm($name, 'NetworkName__ipaddresses');
     echo "</td>";
     echo "<td>";
     IPAddress::showChildsForItemForm($name, 'NetworkName__ipaddresses');
     echo "</td>";
     // MoYo : really need to display it here ?
     // make confure because not updatable
     //       echo "<td>".IPNetwork::getTypeName(Session::getPluralNumber())."&nbsp;";
     //       Html::showToolTip(__('IP network is not included in the database. However, you can see current available networks.'));
     //       echo "</td><td>";
     //       IPNetwork::showIPNetworkProperties($name->getEntityID());
     //       echo "</td>\n";
     echo "<td colspan='2'>&nbsp;</td>";
     echo "</tr>\n";
 }
예제 #16
0
 function getSearchOptions()
 {
     $tab = parent::getSearchOptions();
     $tab[12]['table'] = 'glpi_fqdns';
     $tab[12]['field'] = 'fqdn';
     $tab[12]['name'] = FQDN::getTypeName(1);
     $tab[12]['datatype'] = 'string';
     $tab[20]['table'] = 'glpi_networknames';
     $tab[20]['field'] = 'name';
     $tab[20]['name'] = NetworkName::getTypeName(1);
     $tab[20]['massiveaction'] = false;
     $tab[20]['datatype'] = 'dropdown';
     return $tab;
 }
예제 #17
0
			$full_dmn_name = "{$_SESSION["domaininfo"]["name"]}.{$_SESSION["domaininfo"]["extension"]}";
				
	        if ($_POST["enable_managed_dns"])
			{
				$_POST["ns1"] = CONFIG::$NS1;
				$_POST["ns2"] = CONFIG::$NS2;
			}
			else 
			{
				foreach (array("ns1", "ns2") as $k)
				{
					if (!$Validator->IsDomain($_POST[$k]))
						$exception->AddMessage(sprintf(_("%s is not a valid host"), $_POST[$k]));
					else
					{
						$isglue = FQDN::IsSubdomain($_POST[$k], $full_dmn_name);
						if ($isglue)
							$exception->AddMessage(sprintf(_("%s cannot be used as nameserver because %s is not registered yet."), $_POST[$k], $full_dmn_name));
					}
				}				
					
				if ($_POST["ns1"] == $_POST["ns2"])
					$exception->AddMessage(_("You cannot use the same nameserver twice."));
			}
			
			if ($exception->hasMessages())
				throw $exception;

			if ($_SESSION["domaininfo"]["id"])
				$Domain = DBDomain::GetInstance()->LoadByName($_SESSION["domaininfo"]["name"], $_SESSION["domaininfo"]["extension"]);
			else