public function PanamericanaServer() { $server = new SoapServer("Oris.wsdl"); $server->setClass("Metodos"); try { $server->handle(); } catch (Exception $e) { $server->fault('Sender', $e->getMessage()); } }
/** * Handle the service request */ protected function handleRequest() { $server = new \SoapServer(null, ['uri' => $this->getServiceUri()]); /** @var object $object */ $object = GeneralUtility::makeInstance($this->serverClass); $server->setObject($object); try { $server->handle(); } catch (\Exception $ex) { $server->fault($ex->getCode(), $ex->getMessage()); } }
/** * Execução de Serviço * * Construção de Serviços para determinados elementos do sistema, utilizando * ações nesta controladora para acesso. Esta inicialização deve ser * efetuada somente uma vez por requisição. * * @param string $element Nome do Serviço para Execução * @return null */ protected function _execute($element) { // Desabilitar Layout WSL_Controller_Front::getInstance()->getConfig()->setParam('Layout.enabled', false); // Inicialização $service = new SoapServer(null, array('uri' => 'tns:' . $element . 'Service')); // Configurar Classe $service->setClass('Service_' . $element); // Tratamento de Requisição try { $service->handle(); } catch (Exception $e) { // Tratamento de Erro $service->fault('Server', $e->getMessage()); } }
public function panamericana($wsdl = false) { if (!$wsdl) { $this->loadController('metodosController'); $server = new SoapServer(ROOT . 'public' . DS . 'panamericana.wsdl'); $server->setClass('metodosController'); /* $tz = date_default_timezone_get(); $header = new SoapHeader('urn:pc_SOAP_return_time', 'get_timezone', $tz); $server->addSoapHeader($header); */ try { $server->handle(); } catch (Exception $e) { $server->fault('Sender', $e->getMessage()); } } else { $this->_view->renderizaWSDL('panamericana'); } }
// $request = "REQUEST:"; global $requestContents; $requestContents = "\n" . file_get_contents('php://input') . "\n"; LogMsg(2, $request . $requestContents); ob_start(); try { $server->handle(); } catch (Exception $e) { logMsg(0, "exception: " . $e->getMessage()); $errorId2msgId = array('Server.ServiceUnknownError' => l10n("MSG_SOAPFAULT_SERVICE_UNKNOWN_ERROR"), 'Server.ServiceUnavailable' => l10n("MSG_SOAPFAULT_SERVICE_UNAVAILABLE"), 'Client.SessionIdInvalid' => l10n("MSG_SOAPFAULT_SESSION_ID_INVALID"), 'Client.LoginInvalid' => l10n("MSG_SOAPFAULT_LOGIN_UNAUTHORIZED"), 'Client.LoginDisabled' => l10n("MSG_SOAPFAULT_LOGIN_DISABLED"), 'Client.LoginUnauthorized' => l10n("MSG_SOAPFAULT_LOGIN_UNAUTHORIZED"), 'Client.DeviceLimit' => l10n("MSG_SOAPFAULT_DEVICE_LIMIT"), 'Client.UnsupportedTerritory' => l10n("MSG_SOAPFAULT_UNSUPPORTED_TERRITORY"), 'Client.ItemNotFound' => l10n("MSG_SOAPFAULT_ITEM_NOT_FOUND")); $requestContents = "\n" . file_get_contents('php://input') . "\n"; // reset this to just the input on any fault $transittime = number_format(microtime(true) - $start, 6); logMsg(0, $request . $requestContents . "\nRESPONSE ({$transittime}): ERROR: " . $errorId2msgId[$e->getMessage()] . ' (' . $e->getCode() . ': ' . $e->getFile() . ':' . $e->getLine() . ")\n" . "---------------------------------------------------\n"); $server->fault($e->getMessage(), $errorId2msgId[$e->getMessage()] . ' (' . $e->getCode() . ': ' . $e->getFile() . ':' . $e->getLine() . ')'); // $server->fault ends processing, so this line is never reached. } $response = ob_get_contents(); $size = strlen($response); $sizemsg = "{$size} bytes"; ///////////////////////////////////////////////////////////////////////////// // // Encode long responses using GZIP // // KLUDGE: This appears to be quite broken... // if (0) { if (function_exists("gzencode") && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) { if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip') !== false) { $encoding = 'x-gzip';
$current_company = $clf->getByID($current_user->getCompany())->getCurrent(); if (is_object($current_company)) { Debug::text('Handling SOAP Call To API Factory: ' . $class_name . ' UserName: '******'Failed to get Company Object!', __FILE__, __LINE__, __METHOD__, 10); } } else { Debug::text('Failed to get User Object!', __FILE__, __LINE__, __METHOD__, 10); } } else { Debug::text('Class Factory does not exist!', __FILE__, __LINE__, __METHOD__, 10); $soap_server->fault(9800, 'Class Factory (' . $class_name . ') does not exist!'); } } else { TTi18n::chooseBestLocale(); //Make sure we set the locale as best we can when not logged in Debug::text('User not authenticated! Session likely timed out.', __FILE__, __LINE__, __METHOD__, 10); //$soap_server->fault( 9900, 'Session timed out, please login again.'); $soap_server->setClass('APIAuthentication'); //Allow checking isLoggedIn() and logging in again here. $soap_server->handle(); //PHP appears to exit in this function if there is an error. } } else { TTi18n::chooseBestLocale(); //Make sure we set the locale as best we can when not logged in Debug::text('SOAP UnAuthenticated!', __FILE__, __LINE__, __METHOD__, 10);
/** * Manipular Requisição * * Verifica se na requisição está sendo solicitada a especificação WSDL do * conteúdo do serviço que deve ser apresentado, enviando as configurações * solicitadas para o cliente. Caso contrário, executa o servidor com a * classe configurada no momento da inicialização do objeto. * * @return WSL_Soap_Server Próprio Objeto para Encadeamento */ public function handle() { // Existe parâmetro WSDL? if (array_key_exists('WSDL', $_GET)) { // Exibir Configurações if (!headers_sent()) { header('Content-Type: text/xml'); } // Conteúdo na Saída Padrão file_put_contents('php://output', $this); } else { // Capturar Conteúdo de Entrada $content = file_get_contents('php://input'); // Construção do Servidor $server = new SoapServer($this->getUri() . '?WSDL'); $server->setClass($this->getClass()); try { // Execução $server->handle($content); } catch (Exception $e) { // Apresentar Erro $server->fault($e->getCode(), $e->getMessage()); } } // Encadeamento return $this; }
include_once "moodleplugin.php"; ini_set('soap.wsdl_cache_enabled', 0); $server = new SoapServer("moodleplugin.wsdl", array('soap_version' => SOAP_1_2, 'encoding' => "UTF-8")); $server->setClass("MoodlePlugin"); session_start(); session_name('PHPMOODLEWSSESSID'); /*if (!(adminlogin($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']))) { // Check username and password authenticate(); // Send basic authentication headers because username and/or password didnot match } else {*/ if ($_SERVER["REQUEST_METHOD"] == "POST") { $server->setPersistence(SOAP_PERSISTENCE_REQUEST); try { $server->handle(); } catch (Exception $exc) { $server->fault($exc->getCode(), $exc->getMessage()); } } else { #output function list of webserver $functions = $server->getFunctions(); foreach ($functions as $func) { echo $func . "<br>"; } } //} // Call authentication display function authenticate() { Header("WWW-Authenticate: Basic"); Header("HTTP/1.0 401 Unauthorized"); echo "error";
//listSamples - required for CartWrapper //listProjects - required for CartWrapper //canListSamples - required for CartWrapper // Implemented WSDL operations $server->addFunction("getPlateInfo"); $server->addFunction("getImagingTasks"); $server->addFunction("imagingPlate"); $server->addFunction("imagedPlate"); $server->addFunction("skippedImaging"); $server->addFunction("updatedPriority"); $server->addFunction("uploadImages"); /******************************************************************* ********************** END SOAPSERVER SETUP ************************ *******************************************************************/ /******************************************************************* ********************** HANDLE SOAP REQUESTS ************************ *******************************************************************/ // Handle the SOAP request try { // ob_start(); $server->handle(); // $xml = ob_get_contents(); // ob_end_clean(); // error_log($xml); // echo $xml; } catch (Exception $e) { $server->fault('Sender', $e->getMessage()); } ?>
/** * Handles the web service request. */ public function run() { header('Content-Type: text/xml;charset=' . $this->encoding); if (YII_DEBUG) { ini_set("soap.wsdl_cache_enabled", 0); } list(, $hash) = explode(' ', \Yii::$app->getRequest()->getHeaders()->get('authorization') . ' '); $auth = $hash ? base64_decode($hash) . '@' : ''; $server = new \SoapServer(str_replace('http://', 'http://' . $auth, $this->wsdlUrl), $this->getOptions()); try { if ($this->persistence !== null) { $server->setPersistence($this->persistence); } if (is_string($this->provider)) { $provider = $this->provider; $provider = new $provider(); } else { $provider = $this->provider; } $server->setObject($provider); ob_start(); $server->handle(); $soapXml = ob_get_contents(); ob_end_clean(); return $soapXml; } catch (Exception $e) { if ($e->getCode() !== self::SOAP_ERROR) { // only log for non-PHP-error case because application's error handler already logs it // php <5.2 doesn't support string conversion auto-magically \Yii::error($e->__toString()); } $message = $e->getMessage(); if (YII_DEBUG) { $message .= ' (' . $e->getFile() . ':' . $e->getLine() . ")\n" . $e->getTraceAsString(); } // We need to end application explicitly because of // http://bugs.php.net/bug.php?id=49513 $server->fault(get_class($e), $message); exit(1); } }
/** * Run the route action and return the response. * * @param Request $request * @return mixed * @throws NotFoundHttpException * @throws \SoapFault */ protected function runController(Request $request) { list($class, $method) = explode('@', $this->action['uses']); $parameters = $this->resolveClassMethodDependencies($this->parametersWithoutNulls(), $class, $method); if (!method_exists($instance = $this->container->make($class), $method)) { throw new NotFoundHttpException(); } try { $soapServer = new \SoapServer($this->getWsdlPath()); } catch (\SoapFault $e) { throw new \SoapFault(500, 'The application encountered an unexpected error.'); } try { $soapHandler = $this->container->make('MultiRouting\\Adapters\\Soap\\Request\\Handlers\\Handler', [$instance, $method, $parameters]); $soapServer->setObject($soapHandler); $soapServer->handle(); } catch (\Exception $e) { $soapServer->fault($e->getCode(), $e->getMessage()); } }
<?php require_once 'Ahorcado.class.php'; function autoinclude($className) { $className = str_replace('\\', '/', $className) . '.php'; require_once $className; } spl_autoload_register('autoinclude'); if (isset($_GET['wsdl'])) { header('Content-Type: application/soap+xml; charset=utf-8'); echo file_get_contents('Ahorcado.wsdl'); } else { session_start(); if (!isset($_SESSION['service'])) { $_SESSION['service'] = new Ahorcado(); } $servidorSoap = new SoapServer('C:\\Users\\Iva\\Documents\\II-2015\\Apps\\TareaWebService\\TPRepo\\Ahorcado.wsdl'); //poner la ruta en tu compu //Para evitar la excepción por defecto de SOAP PHP cuando no existe HTTP_RAW_POST_DATA, //se regresa explícitamente el siguiente fallo cuando no hay solicitud (v.b. desde un navegador) if (!@$HTTP_RAW_POST_DATA) { $servidorSoap->fault('SOAP-ENV:Client', 'Invalid Request'); exit; } $servidorSoap->setObject(new Zend\Soap\Server\DocumentLiteralWrapper($_SESSION['service'])); $servidorSoap->setPersistence(SOAP_PERSISTENCE_SESSION); $servidorSoap->handle(); }
die($e->getMessage()); } } function ns1_filter($input) { $search = '/ns1/'; $replace = 'cwmp'; $output = preg_replace($search, $replace, $input); return $output; } $server = new SoapServer(NULL,array( 'location' => "http://10.0.0.1:80/wsdl/acs.php", 'uri' => "urn:dslforum-org:cwmp-1-0" )); if ($_SERVER['REQUEST_METHOD'] !== "POST") $server->fault('Sender',"ONLY POST METHOD SUPPORTED"); $server->setClass('ACS'); $server->setPersistence(SOAP_PERSISTENCE_SESSION); try { switch ($HEADERS["Content-Length"]) { case 0: $server->handle(file_get_contents('finish.xml')); break; default: $server->handle(); } } catch (Exception $e) { $server->fault('Sender',$e->getMessage()); } ob_end_flush(); ?>
EOF; $request2 = <<<EOF <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://127.0.0.1:8080/test/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><SOAP-ENV:Body><ns1:test2/></SOAP-ENV:Body></SOAP-ENV:Envelope> EOF; class SoapFaultTest { public function test1() { // Test #1 return 'Test #1 exception with some special chars: Äßö'; } public function test2() { // Test #2 //throw new SoapFault('Server', 'Test #2 exception with some special chars: Äßö'); throw new Exception('Test #2 exception with some special chars: Äßö'); } } $server = new SoapServer(null, array('uri' => "http://127.0.0.1:8080/test/", 'encoding' => 'ISO-8859-1')); $server->setClass('SoapFaultTest'); try { $server->handle($request1); } catch (Exception $e) { $server->fault("Sender", $e->getMessage()); } try { $server->handle($request2); } catch (Exception $e) { $server->fault("Sender", $e->getMessage()); }
/** * Run the route action and return the response. * * @param Request $request * @return mixed * @throws NotFoundHttpException * @throws \SoapFault */ protected function runController(Request $request) { list($class, $method) = explode('@', $this->action['uses']); $parameters = $this->resolveClassMethodDependencies($this->parameters(), $class, $method); $options = []; $optionsAlias = 'multirouting.adapters.soap.server.options'; if ($this->container->bound($optionsAlias)) { $options = $this->container->make($optionsAlias); } try { $soapServer = new \SoapServer($this->getWsdlPath(), $options); } catch (\SoapFault $e) { throw new \SoapFault('500', 'The application encountered an unexpected error.'); } if (!method_exists($instance = $this->container->make($class), $method)) { $soapServer->fault('500', 'The application encountered an unexpected error.'); } ob_start(); try { $proxyAlias = 'multirouting.adapters.soap.request.proxy'; if ($this->container->bound($proxyAlias)) { /** @var ProxyInterface $proxyInstance */ $proxyInstance = $this->container->make($proxyAlias); $proxyInstance->setMatchedInstance($instance); $proxyInstance->setMatchedMethod($method); $proxyInstance->setMatchedParameters($parameters); $instance = $proxyInstance; } $soapServer->setObject($instance); $soapServer->handle(); $statusCode = 200; } catch (\Exception $e) { $soapServer->fault($e->getCode(), $e->getMessage()); $statusCode = 500; } $responseContent = ob_get_contents(); $headers = headers_list(); ob_end_clean(); $responseHeaders = []; foreach ($headers as $header) { list($key, $value) = explode(':', $header, 2); $responseHeaders[trim($key)] = trim($value); } return new Response($responseContent, $statusCode, $responseHeaders); }
public function getServer() { function isTimestampIsoValid($timestamp) { if (preg_match('/^' . '(\\d{4})-(\\d{2})-(\\d{2})T' . '(\\d{2}):(\\d{2}):(\\d{2})' . '(Z|((-|\\+)\\d{2}:\\d{2})|((-|\\+)\\d{2}\\d{2}))' . '$/', $timestamp, $parts) == true) { try { new \DateTime($timestamp); return true; } catch (\Exception $e) { return false; } } else { return false; } } function validarUsuario($user) { if (!isset($user->now) || !isset($user->login) || !isset($user->company) || !isset($user->auth_string)) { return "is not authorized"; } $toaNow = $user->now; //$toaNow = "2011-07-07T09:25:02+00:00"; $psiNow = date("c"); $login = $user->login; $company = $user->company; $authString = $user->auth_string; /*validar now*/ if (!isTimestampIsoValid($toaNow)) { return "Parameter now is different of ISO 8601 format"; } //diferencia de hora $psiNow $toaNow $datetimePsi = new DateTime($psiNow); //$datetimePsi->add(new DateInterval('PT5H')); //considerar la diferencia de hora quellega $datetimeToa = new DateTime($toaNow); $datetimeToa->sub(new DateInterval('PT5H')); $segPsi = strtotime($datetimePsi->format('Y-m-d H:i:s')); $segToa = strtotime($datetimeToa->format('Y-m-d H:i:s')); $diferencia = abs($segPsi - $segToa); if ($diferencia > (int) \Config::get("ofsc.outbound.diferenciaSegundos")) { return "the current time on the server and this difference exceeds"; } /*validar company*/ if ($company != \Config::get("ofsc.outbound.company")) { return "cannot be found in ETAdirect"; } /*validar login acceso*/ // \Config::get("ofsc.outbound.login") if ($login != \Config::get("ofsc.outbound.login")) { return "cannot be found for this company"; } /*validar login autorizacion*/ $sendMessage = \Config::get("ofsc.outbound.authorized.send_message"); //$sendMessage=true; if ($sendMessage == false) { return "is not authorized to use send_message method"; } /*validar auth_string*/ $authStringNow = md5($toaNow . md5(\Config::get("ofsc.outbound.pass"))); //$authStringNow = md5($toaNow. md5('arg3ntinsa')); if ($authString != $authStringNow) { return "is not authorized" . $authStringNow; } return 1; } function send_message($request) { //ID de proceso function make_seed() { list($usec, $sec) = explode(' ', microtime()); return (double) $sec + (double) $usec * 100000; } mt_srand(make_seed()); $randval = md5(mt_rand()); //Guardar todo para pruebas DB::table('log_ofsc')->insert(['process' => $randval, 'type' => 'full', 'body' => serialize($request), 'created_at' => date("Y-m-d H:i:s")]); $validacion = "is not authorized"; if (isset($request->user)) { $validacion = validarUsuario($request->user); //Guardar resultado de validacion DB::table('log_ofsc')->insert(['process' => $randval, 'type' => 'validate', 'body' => serialize($validacion), 'created_at' => date("Y-m-d H:i:s")]); if ($validacion != 1) { return new SoapFault('SOAP-ENV:Client', $validacion, 'Authentication module'); } } else { return new SoapFault('SOAP-ENV:Client', $validacion, 'Authentication module'); } $return = array(); if (!isset($request->messages->message)) { return new SoapFault('SOAP-ENV:Client', $validacion, 'Authentication module'); } $message = $request->messages->message; DB::table('log_ofsc')->insert(['process' => $randval, 'type' => 'content', 'body' => serialize($message), 'created_at' => date("Y-m-d H:i:s")]); //validar si es array u objeto //cuando llega un elemento llega como objecto if (is_object($message)) { $message = array($message); } if (is_array($message)) { for ($i = 0; $i < count($message); $i++) { /* ====obligatorio===== app_host app_port app_url message_id ====opcional======== company_id address send_to subject body */ //validar json $message[$i]->company_id = ''; $body = json_decode($message[$i]->body); if ($body !== null) { $apptNumber = $body->appt_number; $name = $body->name; $phone = $body->phone; } $messageId = $message[$i]->message_id; $data = array('message_id' => $messageId, 'status' => 'sending'); array_push($return, $data); } $push = Queue::push('NotificacionController@sendMessage', $message); DB::table('log_ofsc')->insert(['process' => $randval, 'type' => 'push', 'body' => serialize($push), 'created_at' => date("Y-m-d H:i:s")]); return $return; } } function drop_message($request) { //se debe abortar el proceso (Pag 14 Outbound) $validacion = "is not authorized"; if (isset($request->user)) { $validacion = validarUsuario($request->user); if ($validacion != 1) { return new SoapFault('SOAP-ENV:Client', $validacion, 'Authentication module'); } } else { return new SoapFault('SOAP-ENV:Client', $validacion, 'Authentication module'); } $return = array(); //var_dump($messages); exit(); if (!isset($request->messages->message)) { return new SoapFault('SOAP-ENV:Client', $validacion, 'Authentication module'); } $message = $request->messages->message; if (is_object($message)) { $message = array($message); } if (is_array($message)) { for ($i = 0; $i < count($message); $i++) { $messageId = $message[$i]->message_id; //borrar los mensajes que se envian try { $respuesta = Mensaje::drop($messageId); } catch (Exception $e) { $respuesta = array('code' => "ERROR", 'desc' => ""); } $data = array('message_id' => $messageId, 'result' => $respuesta); array_push($return, $data); } return $return; } } function get_message_status($request) { // $validacion = "is not authorized"; if (isset($request->user)) { $validacion = validarUsuario($request->user); if ($validacion != 1) { return new SoapFault('SOAP-ENV:Client', $validacion, 'Authentication module'); } } else { return new SoapFault('SOAP-ENV:Client', $validacion, 'Authentication module'); } $return = array(); if (!isset($request->messages->message)) { return new SoapFault('SOAP-ENV:Client', $validacion, 'Authentication module'); } $message = $request->messages->message; if (is_object($message)) { $message = array($message); } if (is_array($message)) { for ($i = 0; $i < count($message); $i++) { $messageId = $message[$i]->message_id; //borrar los mensajes que se envian try { $respuesta = Mensaje::getStatus($messageId); } catch (Exception $e) { $respuesta = array('code' => "ERROR", 'desc' => ""); } $data = array('message_id' => $messageId, 'result' => $respuesta); array_push($return, $data); } return $return; } } try { //$server = new SoapServer(url('/').'/toa_outbound'); $server = new SoapServer('http://10.226.44.222:7020/toa_outbound'); $server->addFunction("send_message"); $server->addFunction("drop_message"); $server->addFunction("get_message_status"); $server->handle(); } catch (Exception $e) { $server->fault($e->getCode(), $e->getMessage()); } //return Response::make(null, 200, array('content-type'=>'application/xml')); }