public function guardarAction() { $values = \Zend\Json\Json::decode($this->getRequest()->getContent()); $content = array(); foreach ($values as $key) { $content[] = $key; } $nombre = $content[0]; $session = $content[1]; $messaggio = $content[2]; $color = 'yellow'; $xposition = rand(2, 1000); $yposition = rand(3, 650); $zposition = rand(1, 100); $posiciones = $xposition . 'x' . $yposition . 'x' . $zposition; $posterlab = $this->getSessioniDao()->tuttiPerId($session)->getPosterlab(); $tipo = 1; $patron = 'Y-m-d H:i'; $fecha = new DateTime(); $fechactual = $fecha->format($patron); $stato = 1; $productos = array('nome' => $nombre, 'messaggio' => $messaggio, 'color' => $color, 'xyz' => $posiciones, 'posterlab_id' => $posterlab, 'tipo' => $tipo, 'sessione' => $session, 'data' => $fechactual, 'stato' => $stato); $producto = new Interattivo(); $producto->exchangeArray($productos); $nuevoid = $this->getInterattivoDao()->salvare($producto); //$salvado = $this->getInterattivoDao()->salvare($producto); if (!$nuevoid) { $json = new JsonModel(array('data' => 'error')); return $json; } else { $json = new JsonModel(array('data' => 'success', 'messaggio' => $messaggio)); return $json; } }
/** * @return array */ public function getResults($offset, $itemCountPerPage) { $query = $this->createSearchQuery($offset, $itemCountPerPage); $adapter = new Http\Client\Adapter\Curl(); $adapter->setOptions(array('curloptions' => array(CURLOPT_SSL_VERIFYPEER => false))); $client = new Http\Client(); $client->setAdapter($adapter); $client->setMethod('GET'); $client->setUri($this->getOptions()->getSearchEndpoint() . $query); $response = $client->send(); if (!$response->isSuccess()) { throw new Exception\RuntimeException("Invalid response received from CloudSearch.\n" . $response->getContent()); } $results = Json::decode($response->getContent(), Json::TYPE_ARRAY); $this->count = $results['hits']['found']; if (0 == $this->count) { return array(); } if ($this->getOptions()->getReturnIdResults()) { $results = $this->extractResultsToIdArray($results); } foreach ($this->getConverters() as $converter) { $results = $converter->convert($results); } return $results; }
/** * @param UploaderModelInterface $model * @param null $values * @return string * @throws InvalidArgumentException */ public function render($model, $values = null) { if (!$model instanceof UploaderModelInterface) { throw new InvalidArgumentException("Unsupportable type of model, required type UploaderModelInterface"); } $textArea = new Textarea(); $textArea->setName('response'); $textAreaViewHelper = new FormTextarea(); $jsonEncoder = new Json(); $value = $jsonEncoder->encode($model->getVariables()); $textArea->setValue($value); return $textAreaViewHelper->render($textArea); }
public function onBootstrap(MvcEvent $event) { Json::$useBuiltinEncoderDecoder = true; $eventManager = $event->getApplication()->getEventManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); }
/** * 更新安全密码 * * @author young * @name 更新安全密码 * @version 2014.01.02 young * @return JsonModel */ public function updateAction() { $oldPassword = trim($this->params()->fromPost('oldPassword', '')); $password = trim($this->params()->fromPost('password', '')); $repeatPassword = trim($this->params()->fromPost('repeatPassword', '')); $active = filter_var($this->params()->fromPost('active', ''), FILTER_VALIDATE_BOOLEAN); $criteria = array('project_id' => $this->_project_id, 'collection_id' => $this->_collection_id); $lockInfo = $this->_lock->findOne($criteria); if ($lockInfo != null) { if (empty($oldPassword)) { return $this->msg(true, '请输入原密码'); } if (sha1($oldPassword) !== $lockInfo['password']) { return $this->msg(true, '身份验证未通过'); } } if (empty($password) || empty($repeatPassword)) { return $this->msg(true, '请输入新密码或者确认密码'); } if ($password !== $repeatPassword) { return $this->msg(true, '两次密码输入不一致'); } $datas = array('password' => sha1($password), 'active' => $active); if ($active) { $rst = $this->_lock->update($criteria, array('$set' => $datas), array('upsert' => true)); if ($rst['ok']) { return $this->msg(true, '设定集合访问密钥成功'); } else { return $this->msg(false, Json::encode($rst)); } } else { $this->_lock->remove($criteria); return $this->msg(true, '清除安全密钥成功'); } }
private function getStorages() { $director = $this->getServiceLocator()->get('director'); $result = $director->send_command("list storages", 2, null); $storages = \Zend\Json\Json::decode($result, \Zend\Json\Json::TYPE_ARRAY); return $storages['result']['storages']; }
/** * Encode data as JSON, disable layouts, and set response header * * If $keepLayouts is true, does not disable layouts. * * @param mixed $data * @param bool $keepLayouts * NOTE: if boolean, establish $keepLayouts to true|false * if array, admit params for Zend_Json::encode as enableJsonExprFinder=>true|false * this array can contains a 'keepLayout'=>true|false * that will not be passed to Zend_Json::encode method but will be used here * @return string|void */ public function direct($data = null, $keepLayouts = false) { if ($data == null) { throw new \InvalidArgumentException('JSON: missing argument. $data is required in json($data, $keepLayouts = false)'); } $options = array(); if (is_array($keepLayouts)) { $options = $keepLayouts; $keepLayouts = (array_key_exists('keepLayouts', $keepLayouts)) ? $keepLayouts['keepLayouts'] : false; unset($options['keepLayouts']); } $data = \Zend\Json\Json::encode($data, null, $options); if (!$keepLayouts) { $layout = LayoutManager::getMvcInstance(); if ($layout instanceof LayoutManager) { $layout->disableLayout(); } } $response = \Zend\Controller\Front::getInstance()->getResponse(); $response->setHeader('Content-Type', 'application/json'); return $data; }
public function testCanSerializeWithJsonpCallback() { $array = array('foo' => 'bar'); $model = new JsonModel($array); $model->setJsonpCallback('callback'); $this->assertEquals('callback(' . Json::encode($array) . ');', $model->serialize()); }
/** * Converts an associative array to a string of tag attributes. * * @access public * * @param array $attribs From this array, each key-value pair is * converted to an attribute name and value. * * @return string The XHTML for the attributes. */ protected function htmlAttribs($attribs) { $xhtml = ''; $escaper = $this->getView()->plugin('escapehtml'); foreach ((array) $attribs as $key => $val) { $key = $escaper($key); if ('on' == substr($key, 0, 2) || 'constraints' == $key) { // Don't escape event attributes; _do_ substitute double quotes with singles if (!is_scalar($val)) { // non-scalar data should be cast to JSON first $val = \Zend\Json\Json::encode($val); } // Escape single quotes inside event attribute values. // This will create html, where the attribute value has // single quotes around it, and escaped single quotes or // non-escaped double quotes inside of it $val = str_replace('\'', ''', $val); } else { if (is_array($val)) { $val = implode(' ', $val); } $val = $escaper($val); } if ('id' == $key) { $val = $this->normalizeId($val); } if (strpos($val, '"') !== false) { $xhtml .= " {$key}='{$val}'"; } else { $xhtml .= " {$key}=\"{$val}\""; } } return $xhtml; }
protected function _parseParameters(HTTPResponse $response) { $params = array(); $body = $response->getBody(); if (empty($body)) { return; } $tokenFormat = $this->getTokenFormat(); switch ($tokenFormat) { case 'json': $params = \Zend\Json\Json::decode($body); break; case 'jsonp': break; case 'pair': $parts = explode('&', $body); foreach ($parts as $kvpair) { $pair = explode('=', $kvpair); $params[rawurldecode($pair[0])] = rawurldecode($pair[1]); } break; default: throw new Exception\InvalidArgumentException(sprintf('Unable to handle access token response by undefined format %', $tokenFormat)); } return (array) $params; }
/** * Fetches the version of the latest stable release. * * By Default, this uses the GitHub API (v3) and only returns refs that begin with * 'tags/release-'. Because GitHub returns the refs in alphabetical order, * we need to reduce the array to a single value, comparing the version * numbers with version_compare(). * * If $service is set to VERSION_SERVICE_ZEND this will fall back to calling the * classic style of version retreival. * * * @see http://developer.github.com/v3/git/refs/#get-all-references * @link https://api.github.com/repos/zendframework/zf2/git/refs/tags/release- * @link http://framework.zend.com/api/zf-version?v=2 * @param string $service Version Service with which to retrieve the version * @return string */ public static function getLatest($service = self::VERSION_SERVICE_ZEND) { if (null === static::$latestVersion) { static::$latestVersion = 'not available'; if ($service == self::VERSION_SERVICE_GITHUB) { $url = 'https://api.github.com/repos/zendframework/zf2/git/refs/tags/release-'; $apiResponse = Json::decode(file_get_contents($url), Json::TYPE_ARRAY); // Simplify the API response into a simple array of version numbers $tags = array_map(function ($tag) { return substr($tag['ref'], 18); // Reliable because we're filtering on 'refs/tags/release-' }, $apiResponse); // Fetch the latest version number from the array static::$latestVersion = array_reduce($tags, function ($a, $b) { return version_compare($a, $b, '>') ? $a : $b; }); } elseif ($service == self::VERSION_SERVICE_ZEND) { $handle = fopen('http://framework.zend.com/api/zf-version?v=2', 'r'); if (false !== $handle) { static::$latestVersion = stream_get_contents($handle); fclose($handle); } } } return static::$latestVersion; }
/** * @todo whats wrong with SSL? * @return array */ public function doRequest() { $url = 'https://www.mvg.de/.rest/betriebsaenderungen/api/interruptions'; $client = new Client($url, array('adapter' => 'Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => array(CURLOPT_FOLLOWLOCATION => TRUE, CURLOPT_SSL_VERIFYPEER => FALSE))); $client->setMethod(\Zend\Http\Request::METHOD_GET); return ZendJson::decode($client->send()->getBody()); }
public function listOrdersAction() { $params = Json::decode($this->getRequest()->getContent(), Json::TYPE_ARRAY); $order = $this->getServiceLocator()->get('TocatCore\\Model\\OrderTableGateway'); if (empty($params)) { return new ViewModel(iterator_to_array($order->select())); } if (isset($params['ticket_id'])) { $rowset = $order->select(function (Select $select) use($params) { $select->join('order_ticket', 'order_ticket.order_uid = order.uid', array()); $select->join('ticket', 'order_ticket.ticket_uid = ticket.uid', array()); $select->where(array('ticket.ticket_id' => $params['ticket_id'])); $select->quantifier('DISTINCT'); }); return new ViewModel(iterator_to_array($rowset)); } if (isset($params['project_id'])) { $rowset = $order->select(function (Select $select) use($params) { $select->join('order_project', 'order_project.order_uid = order.uid', array()); $select->join('project', 'order_project.project_uid = project.uid'); $select->where(array('project.project_id' => $params['project_id'])); $select->quantifier('DISTINCT'); }); return new ViewModel(iterator_to_array($rowset)); } }
/** * {@inheritDoc} */ public function render($model, $values = null) { $apiResponse = $model->getApiResponse(); if ($apiResponse->isError()) { $errors = $apiResponse->getErrors(); if ($e = $model->getException()) { $errors[$apiResponse->getStatus()] = $e->getMessage(); } $payload = ['errors' => $errors]; } else { $payload = $apiResponse->getContent(); } if (null === $payload) { return null; } $jsonpCallback = $model->getOption('callback'); if (null !== $jsonpCallback) { // Wrap the JSON in a JSONP callback. $this->setJsonpCallback($jsonpCallback); } $output = parent::render($payload); if (null !== $model->getOption('pretty_print')) { // Pretty print the JSON. $output = Json::prettyPrint($output); } return $output; }
/** * Converts an associative array to a string of tag attributes. * * @access public * * @param array $attribs From this array, each key-value pair is * converted to an attribute name and value. * * @return string The XHTML for the attributes. */ protected function htmlAttribs($attribs) { $xhtml = ''; $escaper = $this->getView()->plugin('escapehtml'); $escapeHtmlAttr = $this->getView()->plugin('escapehtmlattr'); foreach ((array) $attribs as $key => $val) { $key = $escaper($key); if ('on' == substr($key, 0, 2) || 'constraints' == $key) { // Don't escape event attributes; _do_ substitute double quotes with singles if (!is_scalar($val)) { // non-scalar data should be cast to JSON first $val = \Zend\Json\Json::encode($val); } } else { if (is_array($val)) { $val = implode(' ', $val); } } $val = $escapeHtmlAttr($val); if ('id' == $key) { $val = $this->normalizeId($val); } if (strpos($val, '"') !== false) { $xhtml .= " {$key}='{$val}'"; } else { $xhtml .= " {$key}=\"{$val}\""; } } return $xhtml; }
public static function getLatLng($address) { $latLng = []; try { $url = sprintf('http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false', $address); $client = new Client($url); $client->setAdapter(new Curl()); $client->setMethod('GET'); $client->setOptions(['curloptions' => [CURLOPT_HEADER => false]]); $response = $client->send(); $body = $response->getBody(); $result = Json\Json::decode($body, 1); $latLng = ['lat' => $result['results'][0]['geometry']['location']['lat'], 'lng' => $result['results'][0]['geometry']['location']['lng']]; $isException = false; } catch (\Zend\Http\Exception\RuntimeException $e) { $isException = true; } catch (\Zend\Http\Client\Adapter\Exception\RuntimeException $e) { $isException = true; } catch (Json\Exception\RuntimeException $e) { $isException = true; } catch (Json\Exception\RecursionException $e2) { $isException = true; } catch (Json\Exception\InvalidArgumentException $e3) { $isException = true; } catch (Json\Exception\BadMethodCallException $e4) { $isException = true; } if ($isException === true) { //código em caso de problemas no decode } return $latLng; }
/** * Returns data from string * * @param string $string * @return array */ public function fromString($string) { if (empty($string)) { return array(); } return \Zend\Json\Json::decode($string, \Zend\Json\Json::TYPE_ARRAY); }
public function validatepostajaxAction() { $form = $this->getForm(); $request = $this->getRequest(); $response = $this->getResponse(); $messages = array(); if ($request->isPost()) { $form->setData($request->getPost()); $formValidador = new ValidaFormulario(); $form->setInputFilter($formValidador->getInputFilter()); echo "es valido2: " . "<pre>" . print_r($form->isValid(), true) . "</pre>"; if (!$form->isValid()) { $errors = $form->getMessages(); foreach ($errors as $key => $row) { if (!empty($row) && $key != 'enviar') { foreach ($row as $keyer => $rower) { //save error(s) per-element that //needed by Javascript $messages[$key][] = $rower; } } } } if (!empty($messages)) { $response->setContent(\Zend\Json\Json::encode($messages)); } else { //save to db <span class="wp-smiley wp-emoji wp-emoji-wink" title=";)">;)</span> echo "son válidos los datos"; //$this->savetodb($form->getData()); $response->setContent(\Zend\Json\Json::encode(array('success' => 1))); } } return $response; }
protected function getContactsFromResponse() { if (!$this->response) { return false; } $data = $this->response->getBody(); if (!$data) { return false; } $data = Json::decode($data, 1); if (!isset($data['feed']['entry'])) { return false; } $users = $data['feed']['entry']; foreach ($users as $key => $user) { if (!isset($user['gd$email'])) { continue; } $email = null; foreach ($user['gd$email'] as $address) { if ($email) { continue; } $email = $address['address']; } if (!$email) { continue; } $contacts[] = array('name' => isset($user['title']['$t']) ? $user['title']['$t'] : null, 'email' => $email); } return $contacts; }
/** * Override serialize() * * Tests for the special top-level variable "payload", set by ZF\Rest\RestController. * * If discovered, the value is pulled and used as the variables to serialize. * * A further check is done to see if we have a ZF\Hal\Entity or * ZF\Hal\Collection, and, if so, we pull the top-level entity or * collection and serialize that. * * @return string */ public function serialize() { $variables = $this->getVariables(); // 'payload' == payload for HAL representations if (isset($variables['payload'])) { $variables = $variables['payload']; } // Use ZF\Hal\Entity's composed entity if ($variables instanceof HalEntity) { $variables = method_exists($variables, 'getEntity') ? $variables->getEntity() : $variables->entity; // v1.0-1.1.* } // Use ZF\Hal\Collection's composed collection if ($variables instanceof HalCollection) { $variables = $variables->getCollection(); } if (null !== $this->jsonpCallback) { return $this->jsonpCallback . '(' . Json::encode($variables) . ');'; } $serialized = Json::encode($variables); if (false === $serialized) { $this->raiseError(json_last_error()); } return $serialized; }
/** * Defined by Zend\ProgressBar\Adapter\AbstractAdapter * * @param float $current Current progress value * @param float $max Max progress value * @param float $percent Current percent value * @param int $timeTaken Taken time in seconds * @param int $timeRemaining Remaining time in seconds * @param string $text Status text * @return void */ public function notify($current, $max, $percent, $timeTaken, $timeRemaining, $text) { $arguments = ['current' => $current, 'max' => $max, 'percent' => $percent * 100, 'timeTaken' => $timeTaken, 'timeRemaining' => $timeRemaining, 'text' => $text]; $data = '<script type="text/javascript">' . 'parent.' . $this->updateMethodName . '(' . Json::encode($arguments) . ');' . '</script>'; // Output the data $this->_outputData($data); }
/** * return geojson representation of test points given either * * - neighborhood name and region name */ public function showAction() { $neighborhood_name = $this->getRequestParameter('neighborhood'); $region_name = $this->getRequestParameter('region'); $grid_resolution = $this->getRequestParameter('grid-res'); if (empty($neighborhood_name) or empty($region_name) or empty($grid_resolution)) { die("neighborhood_name,region_name and grid_res must all be defined"); } $neighborhood = $this->m()->neighborhoodMapper()->byName($neighborhood_name, $region_name); if (empty($neighborhood)) { die("no neighborhood found"); } $user_polygons = $this->m()->userPolygonMapper()->byNeighborhood($neighborhood); if (empty($user_polygons)) { die("no user polygons found for neighborhood"); } $timer = \Whathood\Timer::start('api'); $points = $this->m()->testPointMapper()->createByUserPolygons($user_polygons, $grid_resolution); $test_point_ms = $timer->elapsed_milliseconds(); $test_point_count = count($points); $this->logger()->info(sprintf("generated %s test points in %sms; %sms per 1000 points", $test_point_count, $test_point_ms, round($test_point_ms / $test_point_count * 1000, 1))); if (empty($points)) { die("no points returned with grid_resolution {$grid_resolution}"); } $timer = \Whathood\Timer::start('election'); $consensus_col = $this->m()->electionMapper()->buildElectionPointCollection($points); $consensus_seconds = $timer->elapsed_seconds(); $this->logger()->info(sprintf("got consensus in %s seconds; %sms per point", $consensus_seconds, round($consensus_seconds / count($points) * 1000, 2))); $timer = \Whathood\Timer::start('election'); $consensus_col = $this->m()->electionMapper()->buildElectionPointCollection($points); $points = $consensus_col->pointsByNeighborhoodId($neighborhood->getId()); \Zend\Debug\Debug::dump(get_class($points[0])); print Json::encode(\Whathood\Spatial\Util::multiPointToGeoJsonArray(new WhMultiPoint($points))); }
public function deleteAction() { foreach (Json::decode($this->getRequest()->getContent(), Json::TYPE_ARRAY) as $item) { $this->service->deleteRow($item); } return new JsonModel([]); }
/** * Defined by Zend\ProgressBar\Adapter\AbstractAdapter * * @param float $current Current progress value * @param float $max Max progress value * @param float $percent Current percent value * @param int $timeTaken Taken time in seconds * @param int $timeRemaining Remaining time in seconds * @param string $text Status text * @return void */ public function notify($current, $max, $percent, $timeTaken, $timeRemaining, $text) { $arguments = array('current' => $current, 'max' => $max, 'percent' => $percent * 100, 'timeTaken' => $timeTaken, 'timeRemaining' => $timeRemaining, 'text' => $text); $data = 'parent.' . $this->updateMethodName . '(' . Json::encode($arguments) . ');'; // Output the data $this->_outputData($data); }
public function getList() { $config = $this->getServiceLocator()->get('config'); $file = $config['php.ug.event']['cachefile']; $content = Json::decode(file_get_contents($file), Json::TYPE_ARRAY); return new JsonModel($content); }
public function setBudgetAction() { $params = Json::decode($this->getRequest()->getContent(), Json::TYPE_ARRAY); switch ($params['type']) { case 'project': return new ApiProblemResponse(new ApiProblem(406, 'Not Implemented')); break; case 'ticket': default: $ticket = $this->getServiceLocator()->get('TocatCore\\Model\\TicketTableGateway'); $rowset = $ticket->select(array('ticket_id' => $params['id'])); if (count($rowset) < 1) { return new ApiProblemResponse(new ApiProblem(404, 'Not Found')); } $order = $this->getServiceLocator()->get('TocatCore\\Model\\OrderTableGateway'); $orderList = $order->select(function (Select $select) use($rowset) { $select->columns(array('totalBudget' => new Expression('SUM(order.budget)'))); $select->join('order_ticket', 'order_ticket.order_uid = order.uid', array()); $select->where(array('order_ticket.uid' => $rowset->current()->uid)); $select->group('order_ticket.uid'); }); if ($params['budget'] > $orderList->current()->totalBudget) { return new ApiProblemResponse(new ApiProblem(406, 'Budget value bigger then total budget')); } $ticket->update(array('budget' => $params['budget']), array('uid' => $rowset->current()->uid)); $rowset = $ticket->select(array('ticket_id' => $params['id'])); return new ViewModel((array) $rowset->current() + (array) $orderList->current()); break; } }
private function getFilesets() { $director = $this->getServiceLocator()->get('director'); $result = $director->send_command("list filesets", 2, null); $filesets = \Zend\Json\Json::decode($result, \Zend\Json\Json::TYPE_ARRAY); return $filesets['result']['filesets']; }
/** * {@inheritdoc} */ public function decode(Response $response) { $headers = $response->getHeaders(); if (!$headers->has('Content-Type')) { $exception = new Exception\InvalidResponseException('Content-Type missing'); $exception->setResponse($response); throw $exception; } /* @var $contentType \Zend\Http\Header\ContentType */ $contentType = $headers->get('Content-Type'); switch (true) { case $contentType->match('*/json'): $payload = Json::decode($response->getBody(), Json::TYPE_ARRAY); break; //TODO: xml // case $contentType->match('*/xml'): // $xml = Security::scan($response->getBody()); // $payload = Json::decode(Json::encode((array) $xml), Json::TYPE_ARRAY); // break; //TODO: xml // case $contentType->match('*/xml'): // $xml = Security::scan($response->getBody()); // $payload = Json::decode(Json::encode((array) $xml), Json::TYPE_ARRAY); // break; default: throw new Exception\InvalidFormatException(sprintf('The "%s" media type is invalid or not supported', $contentType->getMediaType())); break; } $this->lastPayload = $payload; if ($contentType->match('*/hal+*')) { return $this->extractResourceFromHal($payload, $this->getPromoteTopCollection()); } //else return (array) $payload; }
private function getVolume($volume) { $director = $this->getServiceLocator()->get('director'); $result = $director->send_command('llist volume="' . $volume . '"', 2, null); $pools = \Zend\Json\Json::decode($result, \Zend\Json\Json::TYPE_ARRAY); return $pools['result']['volume']; }
public function validatepostajaxAction() { $form = $this->getForm(); $request = $this->getRequest(); $response = $this->getResponse(); $messages = array(); if ($request->isPost()) { $form->setData($request->getPost()); if (!$form->isValid()) { $errors = $form->getMessages(); foreach ($errors as $key => $row) { if (!empty($row) && $key != 'submit') { foreach ($row as $keyer => $rower) { $messages[$key][] = $rower; } } } } if (!empty($messages)) { $response->setContent(\Zend\Json\Json::encode($messages)); } else { //save to db ;) $this->savetodb($form->getData()); $response->setContent(\Zend\Json\Json::encode(array('success' => 1))); } } return $response; }