public function execute($request)
 {
     $logger = $this->getWebServiceLogger();
     $wsHelper = new WSHelper();
     $wsManager = new WSManager();
     $result = '';
     $status = 'INITIAL';
     $contentType = 'text/plain';
     $httpStatus = 200;
     $httpStatusText = null;
     try {
         $paramObj = $wsHelper->extractParameters($request);
         $isMethodAvailable = $wsManager->isMethodAvailable($paramObj->getMethod(), $paramObj->getRequestMethod());
         $logger->debug(print_r($paramObj, true));
         $logger->debug("MethodAvailable:" . $isMethodAvailable);
         if ($isMethodAvailable) {
             $isAuthenticated = $wsManager->isAuthenticated($paramObj);
             $isAuthorized = $wsManager->isAuthorized($paramObj);
             if ($isAuthenticated && $isAuthorized) {
                 $result = $wsManager->callMethod($paramObj);
                 $logger->debug(print_r($result, true));
                 $result = $wsHelper->formatResult($result, WSHelper::FORMAT_JSON);
                 $logger->debug(print_r($result, true));
                 $status = 'SUCCESS';
                 $contentType = 'text/json';
             } else {
                 $result = 'NOT ALLOWED';
                 $status = 'ERROR';
                 $httpStatus = 401;
             }
         } else {
             $result = 'INVALID REQUEST';
             $status = 'ERROR';
             $httpStatus = 404;
             $httpStatusText = 'Webservice Method Not Found (' . $paramObj->getMethod() . ')';
         }
     } catch (WebServiceException $e) {
         $result = $e->getCode() . ': ' . $e->getMessage();
         $status = 'ERROR';
         $httpStatus = $e->getCode();
         $httpStatusText = $e->getMessage();
     } catch (Exception $e) {
         $logger = $this->getWebServiceLogger();
         $logger->info('Uncaught Exception: ' . $e->getMessage());
         $result = $e->getMessage() . ' ' . $e->getCode();
         $status = 'ERROR';
     }
     $response = $this->getResponse();
     $response->setContent($result);
     $response->setHttpHeader('Content-type', $contentType);
     $response->setHttpHeader('ohrm_ws_call_status', $status);
     $response->setStatusCode($httpStatus, $httpStatusText);
     return sfView::NONE;
 }
Example #2
0
 public function execute($request)
 {
     $wsHelper = new WSHelper();
     $wsManager = new WSManager();
     $result = '';
     $status = 'INITIAL';
     $contentType = 'text/plain';
     try {
         $paramObj = $wsHelper->extractParamerts($request);
         $isMethodAvailable = $wsManager->isMethodAvailable($paramObj->getMethod());
         if ($isMethodAvailable) {
             $isAuthenticated = $wsManager->isAuthenticated($paramObj);
             $isAuthorized = $wsManager->isAuthorized($paramObj);
             if ($isAuthenticated && $isAuthorized) {
                 try {
                     $result = $wsManager->callMethod($paramObj);
                     $result = $wsHelper->formatResult($result, WSHelper::FORMAT_JSON);
                     $status = 'SUCCESS';
                     $contentType = 'text/json';
                 } catch (Exception $e) {
                     $logger = $this->getWebServiceLogger();
                     $logger->info('Uncaught Exception: ' . $e->getMessage());
                     $result = 'INTERNAL ERROR';
                     $status = 'ERROR';
                 }
             } else {
                 $result = 'NOT ALLOWED';
                 $status = 'ERROR';
             }
         } else {
             $result = 'INVALID REQUEST';
             $status = 'ERROR';
         }
     } catch (WebServiceException $e) {
         $result = $e->getCode() . ': ' . $e->getMessage();
         $status = 'ERROR';
     }
     $this->getResponse()->setContent($result);
     $this->getResponse()->setHttpHeader('Content-type', $contentType);
     $this->getResponse()->setHttpHeader('ohrm_ws_call_status', $status);
     return sfView::NONE;
 }
Example #3
0
 /**
  * @covers WSHelper::formatResult
  */
 public function testFormatResult()
 {
     $result = new stdClass();
     $result->name = 'Test';
     $result->score = 100;
     $expcetedString = json_encode($result);
     $wsUtilityServiceMock = $this->getMock('WSUtilityService', array('format'));
     $wsUtilityServiceMock->expects($this->once())->method('format')->will($this->returnValue(json_encode($result)));
     $this->helper->setWSUtilityService($wsUtilityServiceMock);
     $this->assertEquals($expcetedString, $this->helper->formatResult($result, WSHelper::FORMAT_JSON));
 }
    /**
     * @param eZContentObjectTreeNode $node
     * @return string
     */
    public function getNodeUrl( &$node = null )
    {
        $merckIni = ExternalLinkHandlerBase::iniMerck();
        $user = MMUsers::getCurrentUserObject();

        if ( !$user )
        {
            self::redirectToErrorPage();
        }

        $esbParams = $merckIni->variable( 'EsbSettings', 'AvailableParams' );
        if ( !in_array( 'Validation_status', $esbParams ) )
        {
            $esbParams[] = 'Validation_status';
        }

        // esb part of url generating
        $parameters = array(
            'Data' => array(
                'Username' => $user->attribute( 'uuid' ),
                'Params' => $esbParams
            ),
            'cr' => $user->attribute( 'country' )
        );
        $esbResponse = WSHelper::call( 'read', $parameters );
        if ( !isset( $esbResponse['Data']['Params']['Email_address'] ) )
        {
            self::redirectToErrorPage();
        }

        $validStatuses = array(
            'VP',
            '30'
        );
        $isProperStatus = isset( $esbResponse['Data']['Params']['Validation_status'] ) && in_array( $esbResponse['Data']['Params']['Validation_status'], $validStatuses );

        // test if proper ESB response - mainly status = Success
        if ( !$isProperStatus )
        {
            self::redirectToErrorPage();
        }
        $soapUser = $esbResponse['Data']['Params']['Email_address'];
        $soapPassword = $merckIni->variable( 'MdConsultSettings', 'SoapPassword' );
        $applicationId = $merckIni->variable( 'MdConsultSettings', 'ApplicationId' );
        $apiKey = $merckIni->variable( 'MdConsultSettings', 'ApiKey' );
        $headerNamespace = $merckIni->variable( 'MdConsultSettings', 'HeaderNamespace' );
        //$soapUrl = $merckIni->variable( 'MdConsultSettings', 'SoapUrl' );
        // @dirty fix => we use a local version of the WSDL because of some type declaration duplicates
        $soapUrl = __DIR__.'/externallinkhandlerbrmdconsult.xml';
        
        $headerbody = array(
            'UsernameToken' => array(
                'Username' => $apiKey,
                'Password' => $soapPassword
            )
        );

        // soap part of url generating
        $soap = new SoapClient( $soapUrl );

        $header = new SOAPHeader( $headerNamespace, 'Security', $headerbody, false );
        $soap->__setSoapHeaders( $header );

        $params = array(
            array(
                'SiteID' => 'MSDBRZL',
                'UserName' => $soapUser,
                'ApplicationId' => $applicationId
            )
        );

        $user = '';
        $password = '';
        try
        {
            $result = $soap->__soapCall( 'GetThirdPartyCredencials', $params );

            if ( isset( $result->GetThirdPartyCredencialsResult ) && isset( $result->GetThirdPartyCredencialsResult->LOVValue ) )
            {
                $credentials = $result->GetThirdPartyCredencialsResult->LOVValue;

                if ( isset( $credentials->lovIDField ) )
                {
                    $user = $credentials->lovIDField;
                }
                else
                {
                    self::redirectToErrorPage();
                }
                if ( isset( $credentials->valueField ) )
                {
                    $password = $credentials->valueField;
                }
                else
                {
                    self::redirectToErrorPage();
                }
            }
            else
            {
                self::redirectToErrorPage();
            }
        }
        catch ( SoapFault $f )
        {
            self::redirectToErrorPage();
        }

        $url = $merckIni->variable( 'MdConsultSettings', 'MdUrl' );

        $searches = array(
            '<$md_user>',
            '<$md_password>'
        );
        $replacements = array(
            $user,
            $password
        );

        $url = str_replace( $searches, $replacements, $url );
        return $url;
    }
Example #5
0
 public function getUserByUsername($apikey, $secret)
 {
     if (!JOM_SOCIAL) {
         return $this->getBaseUserByUsername($apikey, $secret);
     }
     $auth = new Auth($apikey, $secret);
     if ($auth->isAuthenticate()) {
         if (isset($_GET['username'])) {
             $username = $_GET['username'];
         } else {
             if (isset($_POST['username'])) {
                 $username = $_POST['username'];
             }
         }
     } else {
         $result = WSHelper::constructResult(500, 'APIKey and secret key does not match', "getUserByName");
         return $result->asXML();
     }
     if (!isset($username)) {
         $result = WebserviceHelper::constructResult(500, 'One of the required fields is not set', "getBaseUserById");
         return $result->asXML();
     }
     $db =& JFactory::getDBO();
     $sql = "SELECT `id` , `name` , `username` , `email` , `usertype` ,\r\n\t\t\t\t\tSTATUS , points, avatar, thumb, friendcount\r\n\t\t\t\t\tFROM jos_users, jos_community_users\r\n\t\t\t\t\tWHERE jos_users.id = jos_community_users.userid and jos_users.username='******'";
     $db->setQuery($sql);
     $user = $db->loadObject();
     //$user->thumb = 'http://'.$_SERVER["SERVER_NAME"].'/'.$user->thumb;
     //$user->avatar = 'http://'.$_SERVER["SERVER_NAME"].'/'.$user->avatar;
     //$user->fields = $this->_getUserFields($username, 'username') ;
     if ($db->getErrorNum()) {
         $result = WebserviceHelper::constructResult(500, $db->stderr(), "getUserByName");
         return $result->asXML();
     } else {
         $user->thumb = 'http://' . $_SERVER["SERVER_NAME"] . '/' . $user->thumb;
         $user->avatar = 'http://' . $_SERVER["SERVER_NAME"] . '/' . $user->avatar;
         $fields = $this->_getUserFields($username, 'username');
         $this->_renderFields($fields, $user);
         //print_r($user);
         //die();
         $string = XMLSerializer::generateValidXmlFromObj($user, 'user_data');
         $result = WebserviceHelper::constructResultData(200, 'User Object Loaded', $string, "getUserByName");
         return $result->asXML();
     }
 }
Example #6
0
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* KnowledgeTree" logo and retain the original copyright notice. If the display of the
* logo is not reasonably feasible for technical reasons, the Appropriate Legal Notices
* must display the words "Powered by KnowledgeTree" and retain the original
* copyright notice.
*
* @copyright 2008-2009, KnowledgeTree Inc.
* @license GNU General Public License version 3
* @author KnowledgeTree Team
* @package Webservice
* @version Version 0.1
*/
require_once "classes/soap/common.php";
if ($_GET['class'] && (in_array($_GET['class'], $WSClasses) || in_array($_GET['class'], $WSStructures))) {
    $WSHelper = new WSHelper("http://www.knowledgetree.com", $_GET['class']);
    $WSHelper->actor = "http://www.knowledgetree.com";
    $WSHelper->use = SOAP_ENCODED;
    $WSHelper->classNameArr = $WSClasses;
    $WSHelper->structureMap = $WSStructures;
    $WSHelper->setPersistence(SOAP_PERSISTENCE_REQUEST);
    $WSHelper->setWSDLCacheFolder('wsdl/');
    //trailing slash mandatory. Default is 'wsdl/'
    try {
        $WSHelper->handle();
        //possible db transaction commit
    } catch (Exception $e) {
        //possible db transaction rollback
        $WSHelper->fault("SERVER", $e->getMessage(), "", $e->__toString());
    }
} else {
Example #7
0
<?php

require_once __DIR__ . '/common.php';
if (isset($_GET['class']) && (in_array($_GET['class'], $WSClasses) || in_array($_GET['class'], $WSStructures))) {
    $WSHelper = new WSHelper('http://schema.example.com', $_GET['class']);
    $WSHelper->actor = 'http://schema.example.com';
    $WSHelper->use = SOAP_ENCODED;
    $WSHelper->classNameArr = $WSClasses;
    $WSHelper->structureMap = $WSStructures;
    $WSHelper->setPersistence(SOAP_PERSISTENCE_REQUEST);
    $WSHelper->setWSDLCacheFolder(__DIR__ . '/wsdl/');
    //trailing slash mandatory. Default is 'wsdl/'
    $WSHelper->docTemplate = __DIR__ . '/../doc/templates/docclass.xsl';
    try {
        $WSHelper->handle();
        //possible db transaction commit
    } catch (Exception $e) {
        //possible db transaction rollback
        $WSHelper->fault('SERVER', $e->getMessage(), '', $e->__toString());
    }
} else {
    die('No valid class selected');
}
    /**
     * @param string $username
     * @param ESBResult $esbResult
     * @return array
     */
    public static function readCall( $username, $esbResult )
    {
        $countryOfRegistration = self::getCountryOfRegistration();
        $params = eZINI::instance('merck.ini')->variable( 'EsbSettings', 'AvailableParams' );

        if ( !isset( $params ) || !is_array( $params ) )
        {
            MMUserLogin::logError( $username, null, $esbResult->toTicket(), 'Missing esb login parameters. Check merck.ini configuration.' );
            return;
        }

        if( !in_array( 'Registration_date', $params ) && SolrSafeOperatorHelper::featureIsActive( 'GoogleAnalytics' ) )
        {
            $params[] = 'Registration_date';
        }
        
        // List of needed profile information
        $readParameters = array(
            'Data' => array(
                'Username' => $username,
                'Params' => $params
            ),
            'cr' => $countryOfRegistration
        );

        // Fires a request to get user profile data
        return WSHelper::call( "read", $readParameters );
    }
    /**
     * call the WS and log if an error occured
     *
     * @param string $commandName
     * @param array $params
     * @throws Exception
     * @throws ezcLogWriterException
     * @return array
     */
    public static function call($commandName, $params)
    {
        // $params = DbTool::escapeRecursiveArray($params);
        $result = '';
        
        WSHelper::instance()->logger->log(var_export($params, true), ezcLog::INFO );

        WSHelper::instance()->logger->log( str_pad('', 77, '*'), ezcLog::INFO);
        try
        {
            $command = WSHelper::instance()->client->getCommand($commandName, $params);
            $command->prepare();
            $httpRequest = $command->getRequest();
            $httpRequest->setHeader('Content-Type','application/json');
            $httpRequest->setHeader('Pragma', 'no-cache');
            $httpRequest->setHeader('Content-cache', 'no-cache');
            WSHelper::instance()->logger->log("[Guzzle - Request] ".$httpRequest, ezcLog::INFO);
            eZDB::instance()->close();                              // explicitely close the db connection to let it free in case of timeout
            MMDB::resetInstance();
            $httpResponse = $command->getResponse();
            $forceDBOpen = eZDB::instance(false, false, true);      // force connection reopen
            eZDB::setInstance( $forceDBOpen );
            WSHelper::instance()->logger->log("[Guzzle - Response] ".$httpResponse, ezcLog::INFO);
            $result = $httpResponse->json();

            // log error (header != 200 OK AND login fail)
            if ( $httpResponse->isError()
                    || ( (isset($result['Login']) && $result['Login'] == "no" ) ))
            {
                $logMessage = !empty($result['Msg']) ? $result['Msg'] : "Unkwown";
                $logLevel = ezcLog::WARNING;
            }
            else
            {
                $logLevel = ezcLog::INFO;
                if ( isset($result['Login']) && $result['Login'] == "yes") $logMessage = "Login success";
                else $logMessage = $commandName . ' successful';
            }
            WSHelper::instance()->logger->log($logMessage, $logLevel );
            return $result;

        }
        catch( Guzzle\Http\Exception\CurlException $e )
        {
            $curlError = self::getCurlError( $e->getMessage() );
            $logMessage = "[Guzzle] CurlException #{$curlError['code']}: {$curlError['message']}";
            WSHelper::instance()->logger->log($logMessage, ezcLog::ERROR);
            self::logError($commandName, $params, $result, $logMessage);

            return array(
                'Data' => array(
                    'Status' => 'Error',
                    'ErrorCode' => 10,
                    'Msg' => "#{$curlError['code']}: {$curlError['message']}"
                )
            );
        }
        catch(Guzzle\Common\Exception\BadMethodCallException $e)
        {
            $logMessage = '[Guzzle] BadMethodCallException #'.$e->getCode().':'.$e->getMessage();
            WSHelper::instance()->logger->log($logMessage, ezcLog::ERROR);
            self::logError($commandName, $params, $result, $logMessage);
        }
        catch(Guzzle\Common\Exception\InvalidArgumentException $e)
        {
            $logMessage = '[Guzzle] InvalidArgumentException #'.$e->getCode().':'.$e->getMessage();
            WSHelper::instance()->logger->log($logMessage, ezcLog::ERROR);
            self::logError($commandName, $params, $result, $logMessage);
        }
        catch(Guzzle\Common\Exception\RuntimeException $e)
        {
            $logMessage = '[Guzzle] RuntimeException #'.$e->getCode().':'.$e->getMessage();
            WSHelper::instance()->logger->log($logMessage, ezcLog::ERROR);
            self::logError($commandName, $params, $result, $logMessage);
        }
        catch(Guzzle\Common\Exception\UnexpectedValueException $e)
        {
            $logMessage = '[Guzzle] UnexpectedValueException #'.$e->getCode().':'.$e->getMessage();
            WSHelper::instance()->logger->log($logMessage, ezcLog::ERROR);
            self::logError($commandName, $params, $result, $logMessage);
        }
        catch(Exception $e)
        {
            $logMessage = "[Exception] #".$e->getCode().':'.$e->getMessage();
            WSHelper::instance()->logger->log($logMessage, ezcLog::ERROR);
            self::logError($commandName, $params, $result, $logMessage);
        }

        return null;
    }