예제 #1
0
//
//   iTop is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU Affero General Public License for more details.
//
//   You should have received a copy of the GNU Affero General Public License
//   along with iTop. If not, see <http://www.gnu.org/licenses/>
/**
 * Shows a usage of the SOAP queries 
 *
 * @copyright   Copyright (C) 2010-2012 Combodo SARL
 * @license     http://opensource.org/licenses/AGPL-3.0
 */
require_once 'itopsoaptypes.class.inc.php';
$sItopRoot = 'http' . (utils::IsConnectionSecure() ? 's' : '') . '://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . dirname($_SERVER['SCRIPT_NAME']) . '/..';
$sWsdlUri = $sItopRoot . '/webservices/itop.wsdl.php';
//$sWsdlUri .= '?service_category=';
$aSOAPMapping = SOAPMapping::GetMapping();
ini_set("soap.wsdl_cache_enabled", "0");
$oSoapClient = new SoapClient($sWsdlUri, array('trace' => 1, 'classmap' => $aSOAPMapping));
try {
    // The most simple service, returning a string
    //
    $sServerVersion = $oSoapClient->GetVersion();
    echo "<p>GetVersion() returned <em>{$sServerVersion}</em></p>";
    // More complex ones, returning a SOAPResult structure
    // (run the page to know more about the returned data)
    //
    $oRes = $oSoapClient->CreateIncidentTicket('admin', 'admin', 'Email server down', 'HW found shutdown', null, new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'NW Management'))), new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Troubleshooting'))), '', new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'NW support'))), array(new SOAPLinkCreationSpec('Device', array(new SOAPSearchCondition('name', 'switch01')), array()), new SOAPLinkCreationSpec('Server', array(new SOAPSearchCondition('name', 'dbserver1.demo.com')), array())), '1', '1');
    echo "<p>CreateIncidentTicket() returned:\n";
예제 #2
0
    }
} else {
    $oSoapServer->setClass('BasicServices', null);
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    CMDBObject::SetTrackOrigin('webservice-soap');
    $oSoapServer->handle();
} else {
    echo "This SOAP server can handle the following functions: ";
    $aFunctions = $oSoapServer->getFunctions();
    echo "<ul>\n";
    foreach ($aFunctions as $sFunc) {
        if ($sFunc == 'GetWSDLContents') {
            continue;
        }
        echo "<li>{$sFunc}</li>\n";
    }
    echo "</ul>\n";
    echo "<p>Here the <a href=\"{$sWsdlUri}\">WSDL file</a><p>";
    echo "You may also want to try the following service categories: ";
    echo "<ul>\n";
    foreach (get_declared_classes() as $sPHPClass) {
        if (is_subclass_of($sPHPClass, 'WebServicesBase')) {
            $sServiceCategory = $sPHPClass;
            $sSoapServerUri = 'http' . (utils::IsConnectionSecure() ? 's' : '') . '://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . dirname($_SERVER['SCRIPT_NAME']) . '/../webservices/soapserver.php';
            $sSoapServerUri .= "?service_category={$sServiceCategory}";
            echo "<li><a href=\"{$sSoapServerUri}\">{$sServiceCategory}</a></li>\n";
        }
    }
    echo "</ul>\n";
}
 /**
  * Attempt a login
  * 	 	
  * @param int iOnExit What action to take if the user is not logged on (one of the class constants EXIT_...)
  * @return int One of the class constants EXIT_CODE_...
  */
 protected static function Login($iOnExit)
 {
     if (self::SecureConnectionRequired() && !utils::IsConnectionSecure()) {
         // Non secured URL... request for a secure connection
         throw new Exception('Secure connection required!');
     }
     $aAllowedLoginTypes = MetaModel::GetConfig()->GetAllowedLoginTypes();
     if (isset($_SESSION['auth_user'])) {
         //echo "User: "******"\n";
         // Already authentified
         UserRights::Login($_SESSION['auth_user']);
         // Login & set the user's language
         return self::EXIT_CODE_OK;
     } else {
         $index = 0;
         $sLoginMode = '';
         $sAuthentication = 'internal';
         while ($sLoginMode == '' && $index < count($aAllowedLoginTypes)) {
             $sLoginType = $aAllowedLoginTypes[$index];
             switch ($sLoginType) {
                 case 'cas':
                     utils::InitCASClient();
                     // check CAS authentication
                     if (phpCAS::isAuthenticated()) {
                         $sAuthUser = phpCAS::getUser();
                         $sAuthPwd = '';
                         $sLoginMode = 'cas';
                         $sAuthentication = 'external';
                     }
                     break;
                 case 'form':
                     // iTop standard mode: form based authentication
                     $sAuthUser = utils::ReadPostedParam('auth_user', '', false, 'raw_data');
                     $sAuthPwd = utils::ReadPostedParam('auth_pwd', null, false, 'raw_data');
                     if ($sAuthUser != '' && $sAuthPwd !== null) {
                         $sLoginMode = 'form';
                     }
                     break;
                 case 'basic':
                     // Standard PHP authentication method, works with Apache...
                     // Case 1) Apache running in CGI mode + rewrite rules in .htaccess
                     if (isset($_SERVER['HTTP_AUTHORIZATION']) && !empty($_SERVER['HTTP_AUTHORIZATION'])) {
                         list($sAuthUser, $sAuthPwd) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
                         $sLoginMode = 'basic';
                     } else {
                         if (isset($_SERVER['PHP_AUTH_USER'])) {
                             $sAuthUser = $_SERVER['PHP_AUTH_USER'];
                             // Unfortunately, the RFC is not clear about the encoding...
                             // IE and FF supply the user and password encoded in ISO-8859-1 whereas Chrome provides them encoded in UTF-8
                             // So let's try to guess if it's an UTF-8 string or not... fortunately all encodings share the same ASCII base
                             if (!self::LooksLikeUTF8($sAuthUser)) {
                                 // Does not look like and UTF-8 string, try to convert it from iso-8859-1 to UTF-8
                                 // Supposed to be harmless in case of a plain ASCII string...
                                 $sAuthUser = iconv('iso-8859-1', 'utf-8', $sAuthUser);
                             }
                             $sAuthPwd = $_SERVER['PHP_AUTH_PW'];
                             if (!self::LooksLikeUTF8($sAuthPwd)) {
                                 // Does not look like and UTF-8 string, try to convert it from iso-8859-1 to UTF-8
                                 // Supposed to be harmless in case of a plain ASCII string...
                                 $sAuthPwd = iconv('iso-8859-1', 'utf-8', $sAuthPwd);
                             }
                             $sLoginMode = 'basic';
                         }
                     }
                     break;
                 case 'external':
                     // Web server supplied authentication
                     $bExternalAuth = false;
                     $sExtAuthVar = MetaModel::GetConfig()->GetExternalAuthenticationVariable();
                     // In which variable is the info passed ?
                     eval('$sAuthUser = isset(' . $sExtAuthVar . ') ? ' . $sExtAuthVar . ' : false;');
                     // Retrieve the value
                     if ($sAuthUser && strlen($sAuthUser) > 0) {
                         $sAuthPwd = '';
                         // No password in this case the web server already authentified the user...
                         $sLoginMode = 'external';
                         $sAuthentication = 'external';
                     }
                     break;
                 case 'url':
                     // Credentials passed directly in the url
                     $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
                     $sAuthPwd = utils::ReadParam('auth_pwd', null, false, 'raw_data');
                     if ($sAuthUser != '' && $sAuthPwd !== null) {
                         $sLoginMode = 'url';
                     }
                     break;
             }
             $index++;
         }
         //echo "\nsLoginMode: $sLoginMode (user: $sAuthUser / pwd: $sAuthPwd\n)";
         if ($sLoginMode == '') {
             // First connection
             $sDesiredLoginMode = utils::ReadParam('login_mode');
             if (in_array($sDesiredLoginMode, $aAllowedLoginTypes)) {
                 $sLoginMode = $sDesiredLoginMode;
             } else {
                 $sLoginMode = $aAllowedLoginTypes[0];
                 // First in the list...
             }
             if (array_key_exists('HTTP_X_COMBODO_AJAX', $_SERVER)) {
                 // X-Combodo-Ajax is a special header automatically added to all ajax requests
                 // Let's reply that we're currently logged-out
                 header('HTTP/1.0 401 Unauthorized');
                 exit;
             }
             if ($iOnExit == self::EXIT_HTTP_401 || $sLoginMode == 'basic') {
                 header('WWW-Authenticate: Basic realm="' . Dict::Format('UI:iTopVersion:Short', ITOP_VERSION));
                 header('HTTP/1.0 401 Unauthorized');
                 header('Content-type: text/html; charset=iso-8859-1');
                 exit;
             } else {
                 if ($iOnExit == self::EXIT_RETURN) {
                     if ($sAuthUser !== '' && $sAuthPwd === null) {
                         return self::EXIT_CODE_MISSINGPASSWORD;
                     } else {
                         return self::EXIT_CODE_MISSINGLOGIN;
                     }
                 } else {
                     $oPage = self::NewLoginWebPage();
                     $oPage->DisplayLoginForm($sLoginMode, false);
                     $oPage->output();
                     exit;
                 }
             }
         } else {
             if (!UserRights::CheckCredentials($sAuthUser, $sAuthPwd, $sLoginMode, $sAuthentication)) {
                 //echo "Check Credentials returned false for user $sAuthUser!";
                 self::ResetSession();
                 if ($iOnExit == self::EXIT_HTTP_401 || $sLoginMode == 'basic') {
                     header('WWW-Authenticate: Basic realm="' . Dict::Format('UI:iTopVersion:Short', ITOP_VERSION));
                     header('HTTP/1.0 401 Unauthorized');
                     header('Content-type: text/html; charset=iso-8859-1');
                     exit;
                 } else {
                     if ($iOnExit == self::EXIT_RETURN) {
                         return self::EXIT_CODE_WRONGCREDENTIALS;
                     } else {
                         $oPage = self::NewLoginWebPage();
                         $oPage->DisplayLoginForm($sLoginMode, true);
                         $oPage->output();
                         exit;
                     }
                 }
             } else {
                 // User is Ok, let's save it in the session and proceed with normal login
                 UserRights::Login($sAuthUser, $sAuthentication);
                 // Login & set the user's language
                 if (MetaModel::GetConfig()->Get('log_usage')) {
                     $oLog = new EventLoginUsage();
                     $oLog->Set('userinfo', UserRights::GetUser());
                     $oLog->Set('user_id', UserRights::GetUserObject()->GetKey());
                     $oLog->Set('message', 'Successful login');
                     $oLog->DBInsertNoReload();
                 }
                 $_SESSION['auth_user'] = $sAuthUser;
                 $_SESSION['login_mode'] = $sLoginMode;
                 UserRights::_InitSessionCache();
             }
         }
     }
     return self::EXIT_CODE_OK;
 }
예제 #4
0
 protected function DoExecute()
 {
     echo "<p>Note: You may also want to try the sample SOAP client <a href=\"../webservices/itopsoap.examples.php\">itopsoap.examples.php</a></p>\n";
     $aSOAPMapping = SOAPMapping::GetMapping();
     // this file is generated dynamically with location = here
     $sWsdlUri = 'http' . (utils::IsConnectionSecure() ? 's' : '') . '://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . dirname($_SERVER['SCRIPT_NAME']) . '/../webservices/itop.wsdl.php';
     ini_set("soap.wsdl_cache_enabled", "0");
     foreach ($this->m_aTestSpecs as $iPos => $aWebService) {
         echo "<h2>SOAP call #{$iPos} - {$aWebService['verb']}</h2>\n";
         echo "<p>Using WSDL: {$sWsdlUriForService}</p>\n";
         echo "<p>{$aWebService['explain result']}</p>\n";
         $sWsdlUriForService = $sWsdlUri . '?service_category=' . $aWebService['service_category'];
         $this->m_SoapClient = new SoapClient($sWsdlUriForService, array('classmap' => $aSOAPMapping, 'trace' => 1));
         if (false) {
             self::DumpVariable($this->m_SoapClient->__getTypes());
         }
         try {
             $oRes = call_user_func_array(array($this->m_SoapClient, $aWebService['verb']), $aWebService['args']);
         } catch (SoapFault $e) {
             print "<pre>\n";
             print "Request: \n" . htmlspecialchars($this->m_SoapClient->__getLastRequest()) . "\n";
             print "Response: \n" . htmlspecialchars($this->m_SoapClient->__getLastResponse()) . "\n";
             print "</pre>";
             print "Response in HTML: <p>" . $this->m_SoapClient->__getLastResponse() . "</p>";
             throw $e;
         }
         self::DumpVariable($oRes);
         print "<pre>\n";
         print "Request: \n" . htmlspecialchars($this->m_SoapClient->__getLastRequest()) . "\n";
         print "Response: \n" . htmlspecialchars($this->m_SoapClient->__getLastResponse()) . "\n";
         print "</pre>";
         if ($oRes instanceof SOAPResult) {
             $res = $oRes->status;
         } elseif ($oRes instanceof SOAPSimpleResult) {
             $res = $oRes->status;
         } else {
             $res = $oRes;
         }
         if ($res != $aWebService['expected result']) {
             echo "Expecting:<br/>\n";
             var_dump($aWebService['expected result']);
             echo "Obtained:<br/>\n";
             var_dump($res);
             throw new UnitTestException("Expecting result '{$aWebService['expected result']}', but got '{$res}'");
         }
     }
 }