Example #1
0
 /**
  * Use the JSON encoding scheme for the value specified
  *
  * @param mixed $value  value the object to be encoded
  * @return string  The encoded value
  */
 public static function encode($value)
 {
     if (empty($value)) {
         return 'null';
     }
     $encoder = new Zend_Json_Encoder();
     return $encoder->_encodeValue($value);
 }
Example #2
0
 /**
  * Metoda logująca zmiany wprowadzane w poszczególnych tabelach.
  * W celu skorzystania należy w pliku Row modelu ustawić
  * pole $_logEnable na true
  * @param type $array
  * @throws Zend_Db_Table_Row_Exception
  */
 public function setFromArray(array $array)
 {
     $row = parent::setFromArray($array);
     if ($this->getLogEnable()) {
         try {
             $logger = Zend_Registry::get('log_app');
         } catch (Exception $e) {
             throw new Zend_Db_Table_Row_Exception('The logger "log_app" for row changes log is not set!', 0, $e);
         }
         $changeData = $this->getAllModified();
         if ($changeData['old'] != null && $changeData['new'] != null) {
             $old = Zend_Json_Encoder::encode($changeData['old']);
             $new = Zend_Json_Encoder::encode($changeData['new']);
             $id = $this->_getPrimaryKey();
             $logger->setEventItem('table_name', $this->getTable()->getName());
             $logger->setEventItem('schema_name', $this->getTable()->info('schema'));
             $logger->setEventItem('new', $new);
             if ($id[$this->getIterator()->key()] != null) {
                 $logger->setEventItem('row_id', $id[$this->getIterator()->key()]);
                 $logger->setEventItem('old', $old);
                 $logger->info('update');
             } else {
                 $logger->setEventItem('row_id', $this->save());
                 $logger->info('insert');
             }
         }
     }
     return $row;
 }
Example #3
0
 /**
  * Default error action.
  *
  * On Phprojekt_PublishedException, return an error string in JSON format.
  * <pre>
  *  - type    => 'error'.
  *  - message => Error message.
  *  - code    => Error code.
  * </pre>
  *
  * On wrong controller name or action, terminates script execution.
  *
  * In all cases, the error is logged.
  *
  * @return void
  */
 public function errorAction()
 {
     $error = $this->_getParam('error_handler');
     $this->getResponse()->clearBody();
     switch ($error->type) {
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
             // 404 error -- controller or action not found
             $this->getResponse()->setRawHeader('HTTP/1.1 404 Not Found');
             $message = "The url " . Cleaner::sanitize('xss', urldecode($error->request->getRequestUri())) . " do not exists";
             Phprojekt::getInstance()->getLog()->err($message);
             die($message);
             break;
         default:
             $exception = $error->exception;
             // We only forward exception with type PublishedException
             if ($exception instanceof Phprojekt_PublishedException) {
                 $error = array('type' => 'error', 'message' => $exception->getMessage(), 'code' => $exception->getCode());
                 echo '{}&&(' . Zend_Json_Encoder::encode($error) . ')';
             } else {
                 $logger = Phprojekt::getInstance()->getLog();
                 $logger->err($exception->getMessage() . "\n" . $exception->getTraceAsString());
             }
             break;
     }
 }
Example #4
0
 /**
  * JSON post processing
  *
  * JSON serialize view variables to response body
  *
  * @return void
  */
 public function postJsonContext()
 {
     if (!$this->_actionController->getHelper('contextSwitch')->getAutoJsonSerialization()) {
         return;
     }
     $viewRenderer = \Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
     $view = $viewRenderer->view;
     if ($view instanceof \Zend_View_Interface) {
         /**
          * @see \Zend_Json
          */
         if (method_exists($view, 'getVars')) {
             $response = null;
             $exceptionMessage = null;
             if ($this->getResponse()->isException()) {
                 $exceptionMessage = $view->message . ' : ' . $view->exception->getMessage();
             } else {
                 $response = $view->getVars();
             }
             $body = array('error' => $exceptionMessage, 'result' => $response);
             $this->getResponse()->setBody(\Zend_Json_Encoder::encode($body));
         } else {
             require_once 'Zend/Controller/Action/Exception.php';
             throw new \Zend_Controller_Action_Exception('View does not implement the getVars() method needed to encode the view into JSON');
         }
     }
 }
 /**
  * Function putAction for for putting the file from client to server.
  */
 public function putAction()
 {
     $asResponse = array('status' => 'Ok', 'massage' => 'successfull execution of put method');
     $ssResponse = Zend_Json_Encoder::encode($asResponse);
     echo $ssResponse;
     exit;
 }
Example #6
0
 function execute($task)
 {
     if (!isset($task)) {
         $this->display();
     }
     if ($task) {
         switch ($task) {
             case "wsCity":
                 $regionId = JRequest::getVar('regionId', '0', 'GET', 'string');
                 $countryId = JRequest::getVar('countryId', '0', 'GET', 'string');
                 $productName = JRequest::getVar('productName', '0', 'GET', 'string');
                 $objectXML = $this->getXMLCities($regionId, $countryId, $productName);
                 $retval = $this->callService($objectXML);
                 $valueReturn = array();
                 if (isset($retval["city"]["item"])) {
                     if (!isset($retval["city"]["item"][0])) {
                         $valueReturn["item"][0] = $retval["city"]["item"];
                     } else {
                         $valueReturn["item"] = $retval["city"]["item"];
                     }
                 }
                 die(Zend_Json_Encoder::encode($valueReturn));
                 break;
             case "wsCountryName":
                 $geographic = JRequest::getVar('Geographic', '', 'GET', 'string');
                 $resultsGetGeographic = $this->getCountryName($geographic);
                 die($resultsGetGeographic);
                 break;
         }
     }
 }
 public function servicoAction()
 {
     $this->_helper->layout->disableLayout();
     $this->_helper->viewRenderer->setNoRender();
     $servicos = $this->getServicos();
     echo Zend_Json_Encoder::encode($servicos);
 }
 /**
  * 
  */
 public function json_region()
 {
     header('Content-type: application/json');
     $id = $this->input->post('id');
     $region = $this->_region_model->getById($id);
     echo Zend_Json_Encoder::encode(array("id" => $region->reg_ia_id, "nombre" => $region->reg_c_nombre, "lat" => $region->lat, "lon" => $region->lon));
 }
 /**
  * Function addeditAction for add and edit the user's information.
  */
 public function addeditAction()
 {
     $oForm = new Application_Form_AddUsers();
     $oForm->submit->setLabel('Save');
     if ($this->getRequest()->getParam('id') != '' && is_numeric($this->getRequest()->getParam('id'))) {
         unset($oForm->password);
     }
     if ($this->getRequest()->isPost()) {
         if ($oForm->isValid($this->getRequest()->getPost())) {
             $asUserDetail = $oForm->getValues();
             $ssUserDetail = Zend_Json_Encoder::encode($asUserDetail);
             $client = new Zend_Http_Client($this->ssUri . '/addedit');
             $client->setConfig(array('timeout' => 30));
             $client->setParameterPost(array('ssUserDetail' => $ssUserDetail, 'bIsRest' => true));
             $ssResponse = $client->request('POST');
             if ($ssResponse->isSuccessful()) {
                 $ssResponseBody = $ssResponse->getBody();
                 $asResponse = Zend_Json_Decoder::decode($ssResponseBody, Zend_Json::TYPE_ARRAY);
                 if ($asResponse['status'] == 'success') {
                     $this->_redirect('/restclient/list');
                 }
             }
         }
     } elseif ($this->getRequest()->getParam('id') != '') {
         $oUser = Model_UsersTable::findUser($this->getRequest()->getParam('id'));
         $oForm->populate($oUser[0]);
     }
     $this->view->snIdUser = $this->getRequest()->getParam('id') ? $this->getRequest()->getParam('id') : '';
     $this->view->form = $oForm;
 }
Example #10
0
 /**
  * Query the ACL if the user is allowed to be dispatched to the resource
  *
  * @param Zend_Controller_Request_Abstract $request
  * @throws Zend_Exception if user is not allowed (handled by error controller)
  */
 public function preDispatch(Zend_Controller_Request_Abstract $request)
 {
     $module = $request->getModuleName();
     $controller = $request->getControllerName();
     $action = $request->getActionName();
     $resource = $module . '/' . $controller;
     $auth = Zend_Auth::getInstance();
     if ($auth->hasIdentity() === TRUE) {
         $user = $auth->getIdentity();
     } else {
         $user = new App_User();
         $user->setRole(Zend_Registry::get('acl_default_role_name'), Zend_Registry::get('acl_default_role_id'));
     }
     $auth->getStorage()->write($user);
     /**
      * load acl stuff from cache.
      * the acl is created, that it doesnot grab the data from the database again
      * so, we should have a little bit of performance here
      */
     /*
             //FIXME: ACL Caching seems be faulty or its the development process
             //       After changing rules, ACL doesn't match anymore
             //       Fix: After Changing roles/rules refresh the ACL Cache Object
             $cache = Zend_Registry::get('Cache_Acl');
             $acl   = $cache->load('acl_object');
             IF(!$acl) {
        $acl = new App_Acl;
             }
     */
     $acl = new App_Acl();
     // FIXME: remove after above is fixed
     $acl->buildResourceRules($module, $controller, $action, $user);
     // $cache->save($acl, 'acl_object'); // FIXME: enabled again after above problem is fixed
     foreach ($user->getRoles() as $roleId => $roleName) {
         if ($acl->isAllowed($roleId, $resource, $action)) {
             return TRUE;
         }
         foreach ($acl->getRole($roleId)->getParentRole() as $roleId => $roleName) {
             if ($acl->isAllowed($roleId, $resource, $action)) {
                 return TRUE;
             }
         }
     }
     /**
      * This part is critical (see todo in class docs)
      *
      * 1. On XML Requests:
      *      The setbody just adds information to the body. If an php error occure, the
      *      setBody just prepend the this error to the php error => the return is an Json/html mixed response, unreadable for Ajax Client
      * 2. normal HTTP resposen:
      *      anonymouse rerouting to login page, no reason or any notification to the user
      */
     if ($this->getRequest()->isXmlHttpRequest()) {
         $this->getResponse()->setBody(Zend_Json_Encoder::encode(array('success' => FALSE, 'error_message' => 'No Right to execute this action')));
     } elseif ($controller !== 'error') {
         $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
         $redirector->gotoSimple('login', 'auth', 'noc');
     }
 }
 public function testProcessInputData()
 {
     $response = new Zend_Http_Response(200, array(), Zend_Json_Encoder::encode($this->testArgs));
     $args = $this->proc->processInputData($response);
     $this->assertEquals($args, $this->testArgs, 'Received JSON data should be decoded');
     $args = $this->proc->processInputData();
     $this->assertEquals($args, array(), 'When a response is not provided we should return an empty array');
 }
 /**
  * @param string $string
  * @param bool   $jsonEncode
  *
  * @return $this
  */
 protected function _setReturn($string = '', $jsonEncode = FALSE)
 {
     if (TRUE === $jsonEncode) {
         $this->getResponse()->setHeader('Content-type', 'application/json', TRUE);
     }
     $this->getResponse()->setBody($jsonEncode ? Zend_Json_Encoder::encode($string) : $string);
     return $this;
 }
Example #13
0
 /**
  * Encode the mixed $valueToEncode into the JSON format
  *
  * Encodes using ext/json's json_encode() if available.
  *
  * NOTE: Object should not contain cycles; the JSON format
  * does not allow object reference.
  *
  * NOTE: Only public variables will be encoded
  *
  * @param mixed $valueToEncode
  * @param boolean $cycleCheck Optional; whether or not to check for object recursion; off by default
  * @return string JSON encoded object
  */
 public static function encode($valueToEncode, $cycleCheck = false)
 {
     if (function_exists('json_encode') && self::$useBuiltinEncoderDecoder !== true) {
         return json_encode($valueToEncode);
     }
     require_once 'vtwsclib/third-party/Zend/Json/Encoder.php';
     return Zend_Json_Encoder::encode($valueToEncode, $cycleCheck);
 }
Example #14
0
 /**
  * Encode the mixed $valueToEncode into the JSON format
  *
  * Encodes using ext/json's json_encode() if available.
  *
  * NOTE: Object should not contain cycles; the JSON format
  * does not allow object reference.
  *
  * NOTE: Only public variables will be encoded
  *
  * @param mixed $valueToEncode
  * @param boolean $cycleCheck Optional; whether or not to check for object recursion; off by default
  * @return string JSON encoded object
  */
 public static function encode($valueToEncode, $cycleCheck = false)
 {
     if (function_exists('json_encode') && self::$useBuiltinEncoderDecoder !== true) {
         return json_encode($valueToEncode);
     }
     import('lib.Json.Encoder');
     return Zend_Json_Encoder::encode($valueToEncode, $cycleCheck);
 }
Example #15
0
 /**
  * Encode the mixed $valueToEncode into the JSON format
  *
  * Encodes using ext/json's json_encode() if available.
  *
  * NOTE: Object should not contain cycles; the JSON format
  * does not allow object reference.
  *
  * NOTE: Only public variables will be encoded
  *
  * @param mixed $valueToEncode
  * @param boolean $cycleCheck Optional; whether or not to check for object recursion; off by default
  * @return string JSON encoded object
  */
 public static function encode($valueToEncode, $cycleCheck = false)
 {
     if (function_exists('json_encode')) {
         return json_encode($valueToEncode);
     }
     include_once 'Zend/Json/Encoder.php';
     return Zend_Json_Encoder::encode($valueToEncode, $cycleCheck);
 }
Example #16
0
 /**
  * Encode the mixed $valueToEncode into the JSON format
  *
  * Encodes using ext/json's json_encode() if available.
  *
  * NOTE: Object should not contain cycles; the JSON format
  * does not allow object reference.
  *
  * NOTE: Only public variables will be encoded
  *
  * @param mixed $valueToEncode
  * @param boolean $cycleCheck Optional; whether or not to check for object recursion; off by default
  * @return string JSON encoded object
  */
 public static function encode($valueToEncode, $cycleCheck = false)
 {
     if (function_exists('json_encode')) {
         return json_encode($valueToEncode);
     }
     include_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Json' . DIRECTORY_SEPARATOR . 'Encoder.php';
     return Zend_Json_Encoder::encode($valueToEncode, $cycleCheck);
 }
Example #17
0
 public function getOptionProductsJSON($option)
 {
     $data = $option->getLinkCollection()->toArray();
     if (sizeof($data) == 0) {
         return '{}';
     }
     return Zend_Json_Encoder::encode($data);
 }
Example #18
0
 public function indexAction()
 {
     $objGenre = new Default_Model_Genre();
     $genre = $objGenre->listJson();
     $this->addYosonVar('genre', Zend_Json_Encoder::encode($genre), false);
     $objUbigeo = new Default_Model_Ubigeo();
     $ubigeo = $objUbigeo->listCountryJson();
     $this->addYosonVar('ubigeo', Zend_Json_Encoder::encode($ubigeo), false);
 }
Example #19
0
 public function indexAction()
 {
     $objCompany = new Default_Model_Company();
     $company = $objCompany->listCompanyJson();
     $this->addYosonVar('company', Zend_Json_Encoder::encode($company), false);
     $objUbigeo = new Default_Model_Ubigeo();
     $ubigeo = $objUbigeo->listStateJson();
     $this->addYosonVar('ubigeo', Zend_Json_Encoder::encode($ubigeo), false);
 }
 public function getProductsJSON()
 {
     $result = array();
     if ($this->getProducts()) {
         foreach ($this->getProducts() as $iProductId) {
             $result[$iProductId] = array('qty' => null, 'position' => 0);
         }
     }
     return $result ? Zend_Json_Encoder::encode($result) : '{}';
 }
Example #21
0
 public function makeCall($url, $method, $params = array(), $store = null)
 {
     // Get the authentication data
     $auth = $this->getApiAuthArray($store);
     $method = preg_replace('/^magebridge\\./', '', $method);
     // If these values are not set, we are unable to continue
     if (empty($url) || $auth == false) {
         return false;
     }
     // Add the $auth-array to the parameters
     $params['api_auth'] = $auth;
     // Construct an ID
     $id = md5($method);
     // Construct the POST-data
     $post = array('method' => $method, 'params' => $params, 'id' => $id);
     $post = Zend_Json_Encoder::encode($post);
     // Initialize a CURL-client
     $ch = curl_init($url);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
     curl_setopt($ch, CURLOPT_TIMEOUT, 30);
     curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
     // Build the CURL connection and receive feedback
     $data = curl_exec($ch);
     if (empty($data) || !preg_match('/^\\{/', $data)) {
         Mage::getSingleton('magebridge/debug')->trace('JSON-RPC: Wrong data in JSON-RPC reply', $data);
         Mage::getSingleton('magebridge/debug')->trace('JSON-RPC: CURL error', curl_error($ch));
         return 'Wrong data in JSON-RPC reply';
     }
     // Try to decode the result
     $decoded = json_decode($data, true);
     if (empty($decoded)) {
         Mage::getSingleton('magebridge/debug')->error('JSON-RPC: Empty JSON-response');
         Mage::getSingleton('magebridge/debug')->trace('JSON-RPC: Actual response', $data);
         return 'Empty JSON-response';
     }
     $data = $decoded;
     if (!is_array($data)) {
         Mage::getSingleton('magebridge/debug')->trace('JSON-RPC: JSON-response is not an array', $data);
         return 'JSON-response is not an array';
     } else {
         if (isset($data['error']) && !empty($data['error']['message'])) {
             Mage::getSingleton('magebridge/debug')->trace('JSON-RPC: JSON-error', $data['error']['message']);
             return $data['error']['message'];
         } elseif (!isset($data['result'])) {
             Mage::getSingleton('magebridge/debug')->error('JSON-RPC: No result in JSON-data');
             return 'No result in JSON-data';
         }
     }
     Mage::getSingleton('magebridge/debug')->trace('JSON-RPC: Result', $data['result']);
     return $data['result'];
 }
 /**
  * Returns a JSON encoded JavaScript function call that refreshes
  * the grid with the product's maintainers.
  *
  * @return string The JSON encoded JavaScript function call
  */
 public function getMaintainersJSON()
 {
     // initialize the array with the JSON encoded string
     $result = array();
     if ($this->getMaintainers()) {
         foreach ($this->getMaintainers() as $maintainer) {
             $result[$maintainer->getUserId()] = $maintainer->toArray(array('active'));
         }
     }
     return $result ? Zend_Json_Encoder::encode($result) : '{}';
 }
Example #23
0
 /**
  * @return void
  */
 public function tmpAction()
 {
     $this->_helper->layout->disableLayout();
     $this->_helper->viewRenderer->setNoRender(TRUE);
     try {
         $result = $this->_helper->upload->send();
         echo \Zend_Json_Encoder::encode($result);
     } catch (\Exception $exp) {
         $error = array('jsonrpc' => '2.0', 'id' => 'id', 'error' => array('code' => $exp->getCode(), 'message' => $exp->getMessage()));
         echo \Zend_Json_Encoder::encode($error);
     }
 }
Example #24
0
 public function getProductsJSON()
 {
     $result = array();
     if ($this->getProducts()) {
         $isEntityId = $this->getIsEntityId();
         foreach ($this->getProducts() as $product) {
             $id = $isEntityId ? $product->getEntityId() : $product->getId();
             $result[$id] = $product->toArray(array('qty', 'position'));
         }
     }
     return $result ? Zend_Json_Encoder::encode($result) : '{}';
 }
 public function getassignProductsJSON()
 {
     ////Mage::helper('errorlog')->insert('getassignProductsJSON()', 'madeithere');
     $result = array();
     if ($this->getAssignedProducts()) {
         ////Mage::helper('errorlog')->insert('getassignProductsJSON()', 'intoif');
         foreach ($this->getAssignedProducts() as $iProductId) {
             $result[$iProductId] = array('qty' => null, 'position' => 0);
         }
     }
     return $result ? Zend_Json_Encoder::encode($result) : '{}';
 }
 public function userAction()
 {
     $user = Rp_User::getInstance();
     $userData = array('personId' => $user->getPersonId(), 'fullname' => $user->getPerson()->fullname, 'subposts' => array(), 'viewposts' => array());
     if ($user->isCurrent()) {
         $treePost = $user->getTreePost();
         $userData['subposts'] = $treePost->findChildPosts(true)->toArray();
         $userData['viewposts'] = $treePost->findViewedPosts(true)->toArray();
     }
     $view = $this->initView();
     $view->user = Zend_Json_Encoder::encode($userData);
 }
 public function buscarAction()
 {
     $this->_helper->layout->disableLayout();
     $this->_helper->viewRenderer->setNoRender();
     $fabricante_nome = $this->getRequest()->getParam("query");
     try {
         $modelFabricante = new Model_DbTable_Fabricante();
         $where = $modelFabricante->getDefaultAdapter()->quoteInto("fabricante_nome like ?", "%" . $fabricante_nome . "%");
         $fabricantes = $modelFabricante->fetchAll($where);
         echo Zend_Json_Encoder::encode($fabricantes);
     } catch (Exception $ex) {
     }
 }
Example #28
0
 /** The function to return
  * @param string $name
  * @param string $value
  * @param array $params
  * @param array $attribs
  * @return string
  * @access public
  */
 public function formCKEditor($name, $value = null, $params = null, $attribs = null)
 {
     $hTextA = new Zend_View_Helper_FormTextarea();
     $hTextA->setView($this->view);
     $xhtml = $hTextA->formTextarea($name, $value, $attribs);
     $this->view->jQuery()->addJavascript('$(document).ready(function () {$("#' . $this->_normalizeId($name) . '").ckeditor(' . (!is_null($params) ? 'function () {},' . Zend_Json_Encoder::encode($params) : '') . ')});');
     if (self::$set == false) {
         $this->view->jQuery()->addJavascriptFile($this->view->baseUrl() . '/js/ckeditor/ckeditor.js');
         $this->view->jQuery()->addJavascriptFile($this->view->baseUrl() . '/js/ckeditor/adapters/jquery.js');
         self::$set = true;
     }
     return $xhtml;
 }
 public function testProcessOutputData()
 {
     $restVerbs = array('get', 'post', 'put', 'delete');
     $encodedVerbs = array('post', 'put');
     foreach ($restVerbs as $verb) {
         $this->proc->setRestMethod(new Zend_Config(array('method' => $verb)));
         $args = $this->proc->processOutputData($this->testArgs);
         if (in_array($verb, $encodedVerbs)) {
             $this->assertEquals($args, Zend_Json_Encoder::encode($this->testArgs), strtoupper($verb) . ' petition should send encoded arguments');
         } else {
             $this->assertEquals($args, $this->testArgs, strtoupper($verb) . ' petition should send plain arguments');
         }
     }
 }
Example #30
0
 public function indexAction()
 {
     $id = (int) $this->_getParam('id', 0);
     if (empty($id)) {
         $this->_redirect('/company');
     }
     $dataCompany = Default_Model_Company::getRow($id);
     if (!$dataCompany) {
         $this->_redirect('/company');
     }
     $this->view->name = $dataCompany['name'];
     $this->addYosonVar("idCompany", $id);
     $objUbigeo = new Default_Model_Ubigeo();
     $ubigeo = $objUbigeo->listStateJson();
     $this->addYosonVar('ubigeo', Zend_Json_Encoder::encode($ubigeo), false);
 }