public function getThumbsAction() { // width of html doc $screen_width = (int) $this->params()->fromQuery('screen_width'); //width of browser viewport $width = (int) $this->params()->fromQuery('width'); $height = (int) $this->params()->fromQuery('height'); $direction = $this->params()->fromQuery('direction'); $galleryModel = $this->getVideosModel(); $limit = $galleryModel->getLimit($width, $height); //$page = (int)$this->params('page'); $page = (int) $this->params()->fromQuery('page'); $offset = 0; if ($page > 0) { $offset = $page * $limit; } $cache = $this->getVideosModel()->getThumbVideosCache(); $key = $offset . "_" . $limit; $jsonStr = $cache->getItem($key, $success); if ($this->disableCache || !$success) { $thumbArr = $this->getVideosMapper()->fetchThumbArr($offset, $limit); if ($thumbArr) { $cache->setItem($key, serialize($thumbArr)); } } else { $thumbArr = unserialize($jsonStr); } $jsonModel = new JsonModel(array("result" => $thumbArr)); $jsonModel->setTerminal(true); return $jsonModel; }
/** * Call this method from the appropriate action method * * @return ApiProblemResponse|JsonModel */ public function handleRequest() { $request = $this->getRequest(); if ($request->getMethod() != $request::METHOD_GET) { return new ApiProblemResponse(new ApiProblem(405, 'Only the GET method is allowed for this URI')); } $model = new JsonModel([$this->property => $this->model->fetchAll()]); $model->setTerminal(true); return $model; }
/** * getJsonResponse * * @param Result $result result * * @return \Zend\Stdlib\ResponseInterface */ public function getJsonResponse($result) { $view = new JsonModel(); $view->setTerminal(true); $response = $this->getResponse(); $json = json_encode($result); $response->setContent($json); $response->getHeaders()->addHeaders(['Content-Type' => 'application/json']); return $response; }
/** * @param HttpRequest $request * * @return \Zend\View\Model\ViewModel */ public function build(HttpRequest $request, SmartServiceResult $result, $action) { $viewModel = null; if ($request->isXmlHttpRequest()) { $viewModel = new JsonModel(); $viewModel->setTerminal(true); } else { $viewModel = new \Zend\View\Model\ViewModel(); $viewModel->setVariable('entity', $result->getEntity()); $viewModel->setVariable('form', $result->getForm()); $viewModel->setVariable('list', $result->getList()); $viewModel->setTemplate(sprintf($this->getTemplate(), $action)); } return $viewModel; }
/** * Method executed when the render event is triggered * * @param MvcEvent $e * @return void */ public static function onRender(MvcEvent $e) { if ($e->getRequest() instanceof \Zend\Console\Request || $e->getResponse()->isOk() || $e->getResponse()->getStatusCode() == Response::STATUS_CODE_401) { return; } $httpCode = $e->getResponse()->getStatusCode(); $sm = $e->getApplication()->getServiceManager(); $viewModel = $e->getResult(); $exception = $viewModel->getVariable('exception'); $model = new JsonModel(array('errorCode' => !empty($exception) ? $exception->getCode() : $httpCode, 'errorMsg' => !empty($exception) ? $exception->getMessage() : NULL)); $model->setTerminal(true); $e->setResult($model); $e->setViewModel($model); $e->getResponse()->setStatusCode($httpCode); }
public function getCamGirlsOnlineAction() { $cache = $this->getCache(); $key = $this->getCacheKey(); $str = $cache->getItem($key, $success); if (!$success) { $res = $this->getCamTable()->getCamGirlsOnline(); $res = $this->getCamModel()->buildCamgirlArr($res); if ($res) { $cache->setItem($key, serialize($res)); } } else { $res = unserialize($str); } $jsonModel = new JsonModel(array("result" => $res)); $jsonModel->setTerminal(true); return $jsonModel; }
public function notificarAction() { //Conectamos a BBDD $sid = new Container('base'); $db_name = $sid->offsetGet('dbNombre'); $remitente = "Comit�"; $this->dbAdapter = $this->getServiceLocator()->get($db_name); //Obtenemos datos POST $post = $this->request->getPost(); if (isset($post['destino'])) { //Validamos si es mensaje directo a Dpto if (isset($post['dpto'])) { //Consultamos datos del dpto $dptoMail = new UnidadTable($this->dbAdapter); $lista = $dptoMail->getVerResidentesActivos($this->dbAdapter, $post['id_unidad']); $htmlMarkup = \HtmlCorreo::htmlMensajeDirecto($lista[0]['nombre'], $remitente, $post['textbody']); $html = new MimePart($htmlMarkup); $html->type = "text/html"; $body = new MimeMessage(); $body->setParts(array($html)); $message = new Message(); $message->addTo($lista[0]['correo'])->addFrom('*****@*****.**', 'Notificacion becheck')->setSubject($post['asunto'])->setBody($body); $transport = new SendmailTransport(); $transport->send($message); //Retornamos a la vista $result = new JsonModel(array('status' => 'ok', 'descripcion' => 'Se ha enviado correctamente un correo')); //$result->setTerminal(true); return $result; } $result = new JsonModel(array('status' => 'ok', 'descripcion' => $post)); $result->setTerminal(true); return $result; } //Instancias $dpto = new UnidadTable($this->dbAdapter); $form = new NotificacionForm("form"); //Obtenemos combo dptos $dptos = $dpto->getDatosActivos(); //Cargamos dptos en formulario $form->get('id_unidad')->setAttribute('options', $dptos); $this->layout('layout/comite'); return new ViewModel(array('form' => $form)); }
public function handleError(MvcEvent $e) { if ($e->getError() == Application::ERROR_ROUTER_NO_MATCH) { return; } if ($e->getError() == Application::ERROR_EXCEPTION) { $translator = $e->getApplication()->getServiceManager()->get('translator'); $exception = $e->getParam('exception'); if ($exception instanceof BusinessException) { // translate $status = intval($exception->getCode()); $messsage = $translator->translate($exception->getMessage()); } else { $status = 999; if (isset($_SERVER['APPLICATION_ENV']) && $_SERVER['APPLICATION_ENV'] == 'development') { $messsage = $exception->getMessage(); } else { $messsage = '对不起, 系统出错了...'; } } /* @var $request \Zend\Http\Request */ $request = $e->getRequest(); $response = $e->getResponse(); if ($request->isXmlHttpRequest()) { // change status code from 500 to 200 $response->setStatusCode(200); $response->getHeaders()->addHeaders(array('Content-type' => 'application/json; charset=utf8')); $json = new JsonModel(); $json->setVariables(array('status' => $status, 'message' => $messsage, 'content' => array())); $json->setTerminal(false); $e->setViewModel($json); // mute other default exception handler $e->setError(false); } } }
/** * getJsonResponse * * @param $data $data * * @return \Zend\Stdlib\ResponseInterface */ public function getJsonResponse($data) { $view = new JsonModel(); $view->setTerminal(true); $response = $this->getResponse(); $response->setContent(json_encode($data)); return $response; }
/** * Render JSON response on Error * * @param MvcEvent $e */ public function onRenderError(MvcEvent $e) { // must be an error if (!$e->isError()) { return; } // if we have a JsonModel in the result, then do nothing $currentModel = $e->getResult(); if ($currentModel instanceof JsonModel) { return; } // create a new JsonModel - use application/api-problem+json fields. /** * * @var Response $response */ $response = $e->getResponse(); /** @var \Exception $exception */ $exception = $e->getParam('exception'); // Create a new ViewModel $model = new JsonModel(array("httpStatus" => $exception ? $exception->getCode() : ($response instanceof Response ? $response->getStatusCode() : 500), "title" => $e->getError())); if ($exception && $exception instanceof ValidationException) { $model->httpStatus = $exception->getCode(); if ($response instanceof Response) { $response->setStatusCode($model->httpStatus); } $model->title = 'validation-exception'; //We can have many validation errors $model->validationMessages = $exception instanceof ValidationException ? $exception->getMessages() : $exception->getMessage(); } // Add a detailed info about the error, if it exists if (isset($_SERVER['APPLICATION_ENV']) && $_SERVER['APPLICATION_ENV'] === 'development' && $e->getError()) { switch ($e->getError()) { case 'error-controller-cannot-dispatch': $model->detail = 'The requested controller was unable to dispatch the request.'; break; case 'error-controller-not-found': $model->detail = 'The requested controller could not be mapped to an existing controller class.'; break; case 'error-controller-invalid': $model->detail = 'The requested controller was not dispatchable.'; break; case 'error-router-no-match': $model->detail = 'The requested URL could not be matched by routing.'; break; default: $model->title = get_class($exception); $model->detail = ['message' => $exception instanceof ValidationException ? $exception->getMessages() : $exception->getMessage(), 'file' => $exception->getFile(), 'line' => $exception->getLine()]; break; } } // set our new view model $model->setTerminal(true); $e->setResult($model); $e->setViewModel($model); }
public function dataAction() { /* $newusername = file_get_contents('php://input'); //Получаем JSON запрос от extjs.jsonstore $newusername = json_decode($newusername); if(isset($newusername->user_name) && !empty($newusername->user_name)){} */ if (isset($_GET['act'])) { $action = $_GET['act']; $user = new User(); $user->user_id = $_GET['user_id']; $user->user_name = $_GET['user_name']; $user->user_educ = $_GET['user_educ']; $user->city_name = $_GET['city_name']; $city = new City(); $city->user_id = $_GET['user_id']; $city->city_name = $_GET['city_name']; $education = new Education(); $education->user_id = $_GET['user_id']; $education->user_educ = $_GET['user_educ']; switch ($action) { case "update": $user->user_id = $this->getUserTable()->saveUser($user); $this->getCityTable()->saveCity($city, $user->user_id); $this->getEducationTable()->saveEducation($education, $user->user_id); header('Location:http://univer/user'); exit; break; case "delete": $this->getUserTable()->deleteUser($user->user_id); $this->getCityTable()->deleteCity($user->user_id); $this->getEducationTable()->deleteEducation($user->user_id); header('Location:http://univer/user'); exit; break; } } else { //$jsonfile = array(array("user_id"=> "1","user_name"=>"ОШИБКА!"),); } //----------------------------------------------------------------------------------- //---------------Передача данных клиенту--------------------------------------------- //----------------------------------------------------------------------------------- $user_data = array('user' => $this->getUserTable()->fetchUserInfo()); //-----------переработать!!!!!------------------------ $jsonfile = "["; foreach ($user_data['user'] as $user) { $jsonfile = $jsonfile . '{"user_id": "' . $user->user_id . '", "user_name":"' . $user->user_name . '", "user_educ":"' . $user->user_educ . '", "city_name":"' . $user->city_name . '"},'; } $jsonfile = substr($jsonfile, 0, -1); //удалаем последний символ(запятую) $jsonfile = $jsonfile . ']'; $jsonfile = json_decode($jsonfile); //------------------------------------------------ $result = new JsonModel($jsonfile); //$view->setTemplate('user/index/data'); //установка шаблона $result->setTerminal(true); //don't load layout return $result; }
/** * Return json model * * @param array $data Data * * @return \Zend\View\Model\JsonModel */ public function returnJson(array $data) { $jsonModel = new JsonModel(); $jsonModel->setVariables($data); $jsonModel->setTerminal(true); return $jsonModel; }
public function nomegustareclamoAction() { //Obtenemos datos post $id = $this->params()->fromRoute("id", null); //$data = $this->request->getPost(); //Conectamos con BBDD $sid = new Container('base'); $db_name = $sid->offsetGet('dbNombre'); $this->dbAdapter = $this->getServiceLocator()->get($db_name); $id_usuario = $sid->id_usuario; //Instancias $recl = new ReclamoTable($this->dbAdapter); $recl->nomegustaReclamo($this->dbAdapter, $id, $id_usuario); //Retornamos a la vista $result = new JsonModel(array('status' => 'ok', 'desc' => 'Camnpo N°' . $id . ' fue actualizado')); $result->setTerminal(true); return $result; }
protected function myJsonModel($obj) { $view = new JsonModel($obj); $view->setTerminal(true); return $view; }
public function getMonthlyNavAction() { $arr = $this->getMonthlyNav(); $jsonModel = new JsonModel(array("result" => $arr)); $jsonModel->setTerminal(true); return $jsonModel; }
public function editaractivoAction() { //Conectamos con BBDD $sid = new Container('base'); $db_name = $sid->offsetGet('dbNombre'); $this->dbAdapter = $this->getServiceLocator()->get($db_name); //Obtenemos datos POST $data = $this->getRequest()->getPost(); //Instancias $invt = new InventarioTable($this->dbAdapter); $fond = new FondosTable($this->dbAdapter); $prov = new ProveedorTable($this->dbAdapter); $form = new ActivoForm("form"); if ($data['id_pk'] > 0) { //Guardamos en BBDD $invt->editarActivo($data['id_pk'], $data); //Retornamos a la vista $descripcion = 'Cambios guardados exitosamente'; $result = new JsonModel(array('status' => 'ok', 'descripcion' => $descripcion)); $result->setTerminal(true); return $result; } //Obtenemos activo con id $activo = $invt->getActivoId($data['id']); //Obtenemos datos de combos $fondo = $fond->getFondoId($activo[0]['id_fondo']); $combo = array($fondo[0]['id'] => $fondo[0]['nombre']); //Cargamos combo proveedor if ($activo[0]['area_responsable'] == "proveedor") { $proveedores = $prov->getProveedoresCombo($this->dbAdapter); $form->get('responsable')->setAttribute('options', $proveedores); $value = array_search($activo[0]['responsable'], $proveedores); $form->get('responsable')->setAttribute('value', $value); } //Cargamos codigo interno del inventario $activo[0]['codigo_interno'] = "10" . $activo[0]['id'] * 2; //Cargamos formulario $form->get('id_pk')->setAttribute('value', $activo[0]['id']); $form->get('nombre')->setAttribute('value', $activo[0]['nombre']); $form->get('id_fondo')->setAttribute('options', $combo); $form->get('valor')->setAttribute('value', $activo[0]['valor']); $form->get('cantidad')->setAttribute('value', $activo[0]['cantidad']); $form->get('area_responsable')->setAttribute('value', $activo[0]['area_responsable']); $form->get('estado')->setAttribute('value', $activo[0]['estado']); $form->get('factura')->setAttribute('value', $activo[0]['factura']); $form->get('fecha')->setAttribute('value', $activo[0]['fecha']); $form->get('send')->setAttribute('value', "Editar activo"); $form->get('marca')->setAttribute('value', $activo[0]['marca']); $form->get('modelo')->setAttribute('value', $activo[0]['modelo']); $form->get('nmro_serie')->setAttribute('value', $activo[0]['nmro_serie']); $form->get('ubicacion')->setAttribute('value', $activo[0]['ubicacion']); $form->get('observacion')->setAttribute('value', $activo[0]['observacion']); //Retornamos a la vista $result = new ViewModel(array('form' => $form, 'activo' => $activo)); $result->setTerminal(true); return $result; }
public function testChildrenMayInvokeDifferentRenderingStrategiesThanParents() { $this->view->addRenderingStrategy(function ($e) { $model = $e->getModel(); if (!$model instanceof ViewModel) { return; } return new TestAsset\Renderer\VarExportRenderer(); }); $this->view->addRenderingStrategy(function ($e) { $model = $e->getModel(); if (!$model instanceof JsonModel) { return; } return new Renderer\JsonRenderer(); }, 10); // higher priority, so it matches earlier $this->result = $result = new stdClass(); $this->view->addResponseStrategy(function ($e) use($result) { $result->content = $e->getResult(); }); $child1 = new ViewModel(array('foo' => 'bar')); $child1->setCaptureTo('child1'); $child2 = new JsonModel(array('bar' => 'baz')); $child2->setCaptureTo('child2'); $child2->setTerminal(false); $this->model->setVariable('parent', 'node'); $this->model->addChild($child1); $this->model->addChild($child2); $this->view->render($this->model); $expected = var_export(new ViewVariables(array('parent' => 'node', 'child1' => var_export(array('foo' => 'bar'), true), 'child2' => json_encode(array('bar' => 'baz')))), true); $this->assertEquals($expected, $this->result->content); }
public function onRenderError($e) { // must be an error if (!$e->isError()) { return; } // Check the accept headers for application/json $request = $e->getRequest(); if (!$request instanceof HttpRequest) { return; } $headers = $request->getHeaders(); if (!$headers->has('Accept')) { return; } $accept = $headers->get('Accept'); $match = $accept->match('application/json'); if (!$match || $match->getTypeString() == '*/*') { // not application/json return; } // make debugging easier if we're using xdebug! ini_set('html_errors', 0); // if we have a JsonModel in the result, then do nothing $currentModel = $e->getResult(); if ($currentModel instanceof JsonModel) { return; } //print_r($match); //exit(); // create a new JsonModel - use application/api-problem+json fields. $response = $e->getResponse(); $model = new JsonModel(array("httpStatus" => $response->getStatusCode(), "title" => $response->getReasonPhrase())); // Find out what the error is $exception = $currentModel->getVariable('exception'); if ($currentModel instanceof ModelInterface && $currentModel->reason) { switch ($currentModel->reason) { case 'error-controller-cannot-dispatch': $model->detail = 'The requested controller was unable to dispatch the request.'; break; case 'error-controller-not-found': $model->detail = 'The requested controller could not be mapped to an existing controller class.'; break; case 'error-controller-invalid': $model->detail = 'The requested controller was not dispatchable.'; break; case 'error-router-no-match': $model->detail = 'The requested URL could not be matched by routing.'; break; default: $model->detail = $currentModel->message; break; } } if ($exception) { if ($exception->getCode()) { $e->getResponse()->setStatusCode($exception->getCode()); } $model->detail = $exception->getMessage(); // find the previous exceptions $messages = array(); while ($exception = $exception->getPrevious()) { $messages[] = "* " . $exception->getMessage(); } if (count($messages)) { $exceptionString = implode("n", $messages); $model->messages = $exceptionString; } } $contentType = $headers->get('Content-Type'); if (strpos($contentType->getFieldValue(), 'application/json') !== false && strpos($response->getContent(), 'httpStatus')) { // This is (almost certainly!) an api-problem $headers->addHeaderLine('Content-Type', 'application/api-problem+json'); } // set our new view model $model->setTerminal(true); $e->setResult($model); $e->setViewModel($model); //$e->stopPropagation(); //return $model; }
public function camarasAction() { //Obtenemos datos post $lista = $this->request->getPost(); //Conectamos a BBDD $sid = new Container('base'); $db_name = $sid->offsetGet('dbNombre'); $this->dbAdapter = $this->getServiceLocator()->get($db_name); //Instancias $cam = new CamaraTable($this->dbAdapter); $form = new CamarasForm("form"); //Validamos si es POST if (isset($lista['id_pk_cam'])) { $lista['user_create'] = $sid->offsetGet('id_usuario'); //Validamos si es Update if ($lista['id_pk_cam'] > 0) { //Actualizamos nueva info de camaras $cam->editarCamara($lista['id_pk_cam'], $lista); $desc = "Cambios guardados exitosamente"; } else { //Insertamos nueva info de camaras $cam->nuevaCamara($lista); $desc = "Datos ingresados exitosamente"; } //Retornamos a la Vista $result = new JsonModel(array('status' => 'ok', 'desc' => $desc)); $result->setTerminal(true); return $result; } else { $camaras = $cam->getDatos(); //Validamos si existen datos if (isset($camaras)) { $form->get('id_pk_cam')->setAttribute('value', $camaras[0]['id']); $form->get('graban')->setAttribute('value', $camaras[0]['graban']); $form->get('camaras')->setAttribute('value', $camaras[0]['camaras']); $form->get('reglas')->setAttribute('value', $camaras[0]['reglas']); } //Retornamos a la Vista $result = new ViewModel(array('status' => 'ok', 'form' => $form)); $result->setTerminal(true); return $result; } }
public function renderError(MvcEvent $e) { // must be an error if (!$e->isError()) { return; } $request = $e->getRequest(); if (!$request instanceof HttpRequest) { return; } // We ought to check for a JSON accept header here, except that we // don't need to as we only ever send back JSON. // If we have a JsonModel in the result, then do nothing $currentModel = $e->getResult(); if ($currentModel instanceof JsonModel) { return; } // Create a new JsonModel and populate with default error information $model = new JsonModel(); // Override with information from actual ViewModel $displayExceptions = true; if ($currentModel instanceof ModelInterface) { $model->setVariables($currentModel->getVariables()); if ($model->display_exceptions) { $displayExceptions = (bool) $data['display_exceptions']; } } // Check for exception $exception = $currentModel->getVariable('exception'); if ($exception && $displayExceptions) { // If a code was set in the Exception, then assume that it's the // HTTP Status code to be sent back to the client if ($exception->getCode()) { $e->getResponse()->setStatusCode($exception->getCode()); } // Should probably only render a backtrace this if in development mode! $model->backtrace = explode("\n", $exception->getTraceAsString()); // Assign the message & any previous ones $model->message = $exception->getMessage(); $previousMessages = array(); while ($exception = $exception->getPrevious()) { $previousMessages[] = "* " . $exception->getMessage(); } if (count($previousMessages)) { $exceptionString = implode("\n", $previousMessages); $model->previous_messages = $exceptionString; } } // Set the result and view model to our new JsonModel $model->setTerminal(true); $e->setResult($model); $e->setViewModel($model); }
/** * @codeCoverageIgnore * display * * @param string $content * @param \Zend\Mvc\MvcEvent $event * * @return void */ public function display($content, \Zend\Mvc\MvcEvent $event) { $view = new JsonModel(); $view->setTerminal(true); $event->setViewModel($view); /** @var Response $response */ $response = $event->getResponse(); $response->getHeaders()->clearHeaders(); $this->setResponseHeaders(); $response->setStatusCode(Response::STATUS_CODE_500); $response->getHeaders()->addHeaders(['Content-Type' => 'application/json']); $response->setContent(''); $response->getContent(); $this->setResponseHeaders(); echo $content; exit(0); }
/** * @param MvcEvent $event * @return MvcEvent */ public function getJsonModelError(MvcEvent $event) { $view = $event->getViewModel(); if ($view instanceof JsonModel) { return; } if (!$this->isJson($event)) { return; } // || (!$event->getError() && !$event->getResponse()->isNotFound() if ($event->getViewModel()->getChildren()) { foreach ($event->getViewModel()->getChildren() as $child) { $params = $child->getVariables(); } } else { $params = $event->getViewModel()->getVariables(); } $result = array('data' => array(), 'errors' => array(), 'options' => array(), 'success' => array()); foreach ($params as $key => $param) { if (method_exists($param, 'toArray')) { $result['data'][] = $param->toArray(); } elseif ($param instanceof Form) { foreach ($param->getElements() as $formElement) { $messages = array(); if ($formElement->getMessages()) { foreach ($formElement->getMessages() as $type => $message) { $messages[] = $message; } $result['errors'][$formElement->getName()] = $messages; } } $result['data'][$key] = $param->getData(); $result['options'] = ['method' => $param->getAttribute('method')]; } else { $result['data'][$key] = $param; } } /** @var \Zend\Mvc\Controller\Plugin\FlashMessenger $flashMessenger */ $flashMessenger = $event->getApplication()->getServiceManager()->get('viewHelperManager')->get('flashMessenger'); $result['success'] = $flashMessenger->getCurrentSuccessMessages(); $flashMessenger->clearCurrentMessagesFromContainer(); $notifyErrors = array(); if ($event->getParam('exception')) { $notifyErrors[] = $event->getParam('exception')->getMessage(); } elseif ($event->getResponse()->isNotFound()) { $notifyErrors[] = isset($result['data']['message']) ? $result['data']['message'] : 'Not Found'; } $event->getResponse()->getHeaders()->addHeaderLine('Fury-Notify', Json::encode(['error' => $notifyErrors])); $model = new JsonModel($result); $model->setTerminal(true); $event->setResult($model)->setViewModel($model); return $event; }
/** * Remove event * * @return JsonModel */ public function removeEventAction() { $model = Event\Model::fromId($this->params()->fromRoute('id')); $success = false; if (!empty($model)) { $model->delete(); $success = true; } $jsonModel = new JsonModel(); $jsonModel->setVariables(array('success' => $success)); $jsonModel->setTerminal(true); return $jsonModel; }