/** * Echoes a list of members for a given slug in json. */ public function getMembersAction() { $this->getLock($slug = $this->Request->getParameter('slug')); $members = $this->updateMembersToCache($slug, $this->loadMembersFromCache($slug)); $this->releaseLock($slug); echo \JSONUtils::encode($members); }
public function showThumbnails() { $json = $this->getParameter('value'); if (empty($json)) { return ''; } $json = JSONUtils::decode($json); $thumbs = $this->getParameter('thumbnails'); $tlist = array(); if (!empty($thumbs)) { $tlist = explode(',', $thumbs); } $xmod = StringUtils::strToBool($this->getParameter('xmod')); $markup = ''; if ($xmod) { foreach ($json as $thumb) { if (!empty($list) && in_array($thumb->value, $tlist) || empty($tlist)) { $markup .= '<image id="' . $thumb->url . '" width="full"/>'; } } } else { $markup .= '<ul class="thumbnail-list">'; foreach ($json as $thumb) { if (!empty($tlist) && in_array($thumb->value, $tlist) || empty($tlist)) { $markup .= '<li><p><img src="' . $thumb->url . '" alt="' . $this->getLocal('Title') . '" /></p><p><strong>Size:</strong> ' . $thumb->value . '</p></li>'; } } $markup .= '</ul>'; } return $markup; }
public function encodeFlat() { if ($this->getParameter('value') == null) { return '""'; } $values = $this->getParameter('value'); return JSONUtils::encodeFlat($values); }
protected function _failureBulkaction($msg, $element, $slug) { $json = array('Message' => $msg, 'Element' => $element, 'Slug' => $slug); $json = JSONUtils::encode($json); $s = "<script type=\"text/javascript\" language=\"JavaScript\">parent.BulkActionToolbar.updateProgress(false," . $json . ");</script>\n"; echo $s; flush(); usleep(10000); }
/** * Indents a flat JSON string to make it more human-readable * * @return string */ public function format() { $json = (string) $this->getParameter('value'); if (empty($json)) { return '""'; } $html = (bool) $this->getParameter('html'); return JSONUtils::format($json, $html); }
public function removeTag(NodeRef $imageNodeRef, NodeRef $thumbnailFileNodeRef, Tag $tag) { $image = $this->NodeService->getByNodeRef($imageNodeRef, new NodePartials('#thumbnails-json')); $json = $image->getMetaValue('#thumbnails-json'); if ($json == null) { return; } $json = JSONUtils::decode($json); foreach ($json as $i => $thumb) { if ($thumb->value == $tag->TagValue) { array_splice($json, $i, 1); break; } } $this->NodeService->updateMeta($imageNodeRef, '#thumbnails-json', JSONUtils::encode($json)); }
public function apiJson() { $errors = $this->getGlobal('Errors'); //array of FieldValidationError or ValidationError $s = array(); if (empty($errors)) { $s[] = array('Code' => '-1', 'Message' => 'no data'); } else { foreach ($errors as $error) { if ($error instanceof FieldValidationError) { $s[] = array('Code' => $error->getFailureCode(), 'Resolved' => $error->getFieldResolved(), 'Type' => $error->getFieldType(), 'Title' => $error->getFieldTitle(), 'Value' => $error->getValue(), 'Message' => $this->errorCodeResolver->resolveMessageCode($error->getFailureCode(), $error->getFieldResolved(), $error->getFieldType(), array($error->getFieldTitle(), $error->getValue(), $error->getFieldType()), $error->getDefaultErrorMessage())); } else { if ($error instanceof ValidationError) { $s[] = array('Code' => $error->getErrorCode(), 'Message' => $this->errorCodeResolver->resolveMessageCode($error->getErrorCode(), null, null, null, $error->getDefaultErrorMessage())); } } } } return JSONUtils::encode($s); }
protected function getDeploymentCache($aggregatePath) { return JSONUtils::decode(file_get_contents($aggregatePath), true); }
/** * Returns TRUE if the given value passes validation. * * @param string $value A value to test * * @return boolean */ public function isValid($value) { if ($this->skipValidation) { return true; } $datatype = $this->validation['datatype']; //NULL check, empty strings are considered null if (in_array($datatype, array('string', 'url', 'email', 'slug', 'slugwithslash', 'html', 'binary', 'json')) && strlen(trim($value)) == 0) { $value = null; } if ($this->validation['nullable'] === false && $value === null && $datatype != 'boolean') { $this->failureCode = 'nullable'; $this->failureMessage = 'cannot be empty'; return false; } //Nothing more to validate if the value is null... if ($value === null) { return true; } //Check date makes sense if ($datatype === 'date') { //todo: not sure how to check validity of date... it's already a DateTime instance. if (false) { $this->failureCode = 'invalid'; $this->failureMessage = 'is an invalid date'; return false; } } //Validate MIN $min = $this->validation['min']; if ($min != null) { if ($datatype === 'float') { if ($value < floatval($min)) { $this->failureCode = 'min'; $this->failureMessage = 'is less than the minimum value'; return false; } } else { if ($datatype === 'int') { if ($value < intval($min)) { $this->failureCode = 'min'; $this->failureMessage = 'is less than the minimum value'; return false; } } else { if (is_string($value) && strlen($value) < intval($min)) { $this->failureCode = 'minlength'; $this->failureMessage = 'must be at least ' . $min . ' characters'; return false; } } } } //Validate MAX $max = $this->validation['max']; if ($max != null) { if ($datatype === 'float') { if ($value > floatval($max)) { $this->failureCode = 'max'; $this->failureMessage = 'is more than the maximum value'; return false; } } else { if ($datatype === 'int') { if ($value > intval($max)) { $this->failureCode = 'max'; $this->failureMessage = 'is more than the maximum value'; return false; } } else { $maxbytes = intval($max); if (intval($max) < 255) { // count characters if (is_string($value) && StringUtils::charCount($value) > intval($max)) { $this->failureCode = 'maxlength'; $this->failureMessage = 'must be a maximum of ' . $max . ' characters'; return false; } $maxbytes = 255; } // count bytes if (is_string($value) && StringUtils::byteCount($value) > intval($maxbytes)) { $this->failureCode = 'maxlength'; $this->failureMessage = 'must be a maximum of ' . $maxbytes . ' bytes'; return false; } } } } if ($datatype === 'slug') { if (!SlugUtils::isSlug($value, false)) { $this->failureCode = 'invalid'; $this->failureMessage = 'is not a valid slug, cannot contain slashes'; return false; } } if ($datatype === 'slugwithslash') { if (!SlugUtils::isSlug($value, true)) { $this->failureCode = 'invalid'; $this->failureMessage = 'is not a valid slug'; return false; } } if ($datatype === 'url') { if (!URLUtils::isUrl($value)) { $this->failureCode = 'invalid'; $this->failureMessage = 'is not a valid URL'; return false; } } if ($datatype === 'email') { if (!EmailUtils::isEmailAddress($value)) { $this->failureCode = 'invalid'; $this->failureMessage = 'is not a valid email address'; return false; } } if ($datatype === 'json') { if (!JSONUtils::isValid($value)) { $this->failureCode = 'invalid'; $this->failureMessage = 'is not a valid json string'; return false; } } //Validate MATCH expression $match = $this->validation['match']; if ($match != null) { // Automatically escape unescaped slashes in the match before running it $match = preg_replace('/([^\\\\])\\//', '$1\\/', $match); if (preg_match('/' . $match . '/s', $value) === 0) { $this->failureCode = 'invalid'; //$this->failureMessage = 'is invalid (' . substr($value, 0, 255) . ')'; $this->failureMessage = 'is invalid'; return false; } } // Validate all custom functions foreach ($this->validation['callback'] as $callback) { if (!empty($callback) && call_user_func($callback, $value) === false) { $this->failureCode = $callback; $this->failureMessage = 'is invalid'; return false; } } return true; }
public static function encodeFlat($obj, $pretty = false, $html = false) { return JSONUtils::encode(ArrayUtils::flattenObjects($obj), $pretty, $html); }
/** @see http://swfupload.org/forum/generaldiscussion/1717 */ public function postHandleQuickAdd(Transport $transport) { if (!$this->triggered) { return; } $controls = $this->RequestContext->getControls(); if ((stripos($this->Request->getUserAgent(), 'Flash') !== FALSE || stripos($this->Request->getServerAttribute('HTTP_X_REQUESTED_WITH'), 'XMLHttpRequest') !== FALSE) && $controls->getControl('action') == 'node-quick-add') { $arr = JSONUtils::decode($transport->Content, true); if (!isset($arr['Cheaters'])) { return; } $newarr = array(); //COPY NON-TAG FIELDS foreach (array('Slug', 'Title', 'Status', 'Element', 'RecordLink') as $key) { $newarr[$key] = $arr[$key]; } //COPY ORIGINAL FILE TAG DATA $newarr['#original'] = array('url' => $arr['Cheaters']['#original']['TagLinkNode']['Metas']['url']['MetaValue'], 'width' => $arr['Cheaters']['#original']['TagLinkNode']['Metas']['width']['MetaValue'], 'height' => $arr['Cheaters']['#original']['TagLinkNode']['Metas']['height']['MetaValue']); //COPY THUMBNAIL FILE TAG DATA $newarr['#thumbnails'] = array(); $thumbs = $arr['Cheaters']['#thumbnails']; if (isset($thumbs['TagDirection'])) { $thumbs = array($thumbs); } foreach ($thumbs as $thumb) { $newarr['#thumbnails'][] = array('value' => $thumb['TagValue'], 'url' => $thumb['TagLinkNode']['Metas']['url']['MetaValue'], 'width' => $thumb['TagLinkNode']['Metas']['width']['MetaValue'], 'height' => $thumb['TagLinkNode']['Metas']['height']['MetaValue']); } //ADD FORMAT SO TAG WIDGET CLASS CAN INTERPRET $newarr['Format'] = 'media/compact'; $transport->Content = JSONUtils::encode($newarr); } }
/** * Fetch the contents of a URL as a JSON array * * @param string $url Fully-qualified URL to request * @param bool $followRedirects If true, follow redirects to default max of 5 * @param string $username Username to use in http authentication header * @param string $password Password to use in http authentication header * @param array $headers Array of http headers to append to the existing headers list * * @return array PHP array version of JSON contents * @throws HttpRequestException If contents cannot be fetched */ public function fetchJSON($url, $followRedirects = true, $username = null, $password = null, $headers = array()) { $contents = $this->fetchURL($url, $followRedirects, $username, $password, $headers); return JSONUtils::decode($contents, true); }
/** * Build Node JSON structure with thumbnail information. */ protected function _buildNodeJSON(Node $node, $includeOriginal = false, $includeThumbnails = false) { $data = new stdClass(); $data->slug = $node->Slug; $data->element = $node->Element->Slug; $data->title = $node->Title; $data->status = $node->Status; $data->activeDate = $node->ActiveDate; $data->recordLink = $node->RecordLink; $data->sortOrder = $node->SortOrder; if ($includeOriginal) { $nodeRef = $node->getNodeRef(); if ($nodeRef->getElement()->hasAspect('images') || $nodeRef->getElement()->hasAspect('temporary-zipped-media')) { // Build the original and thumbnail info as well foreach (array('url', 'size', 'width', 'height') as $f) { $data->{$f} = $node->jump("#original.#{$f}"); if (is_numeric($data->{$f})) { $data->{$f} = intval($data->{$f}); } } } else { // Include the URL for non image media $data->url = $node->jump("#original.#url"); } } $json = $node->getMetaValue('#thumbnails-json'); if ($json != null) { $thumbnails = JSONUtils::decode($json); if ($includeThumbnails) { $data->thumbnails = $thumbnails; $data->thumbnailsPending = (array) $this->_getPendingThumbnails($node->getElement()->getSlug(), $thumbnails); } foreach ($thumbnails as $thmb) { if ($thmb->value == $this->imagesThumbnailCmsSize) { $data->thumbnailUrl = $thmb->url; break; } } } return $data; }
protected function _importPhotosFromJson($file) { try { $contents = file_get_contents($file); $json = JSONUtils::decode($contents); foreach ($json as $v) { echo "importing {$v->title}..."; $url = $v->src; $parts = parse_url($url); $slug = SlugUtils::createSlug(basename($parts['path'])); preg_match('/(\\.\\w*)$/', $parts['path'], $ext); $nodeRef = $this->NodeRefService->oneFromAspect('@images'); $nodeRef = $this->NodeRefService->generateNodeRef($nodeRef, $slug); $node = $nodeRef->generateNode(); if (!$this->NodeService->refExists($node->getNodeRef())) { // go fetch file from url $data = $this->HttpRequest->fetchURL($url); // create a unique output file name $sourceFile = FileSystemUtils::secureTmpname($this->workDir, 'urlfetch', !empty($ext[1]) ? strtolower($ext[1]) : null); file_put_contents($sourceFile, $data); $node->Title = rtrim($v->title); $node->Status = "published"; $node->ActiveDate = $this->DateFactory->newStorageDate(); $node = $this->ImageService->storeMedia($sourceFile, $node, basename($parts['path'])); $this->NodeService->add($node); echo "done\n"; } else { echo "exists\n"; } unset($nodeRef); unset($node); } } catch (Exception $e) { echo "Exception: " . $e->getMessage() . "\n"; } }
/** * Encodes the current records (from the locals array) into a JSON object. * * Expected Params: * keys string A single string or a list of comma-separated strings representing the keys to encode * from the locals array. If this param is not provided a default list of well-known keys is used. * * @return string */ public function jsonEncode() { $keys = $this->getEncodeKeys(); return JSONUtils::encode(ArrayUtils::flattenObjectsUsingKeys($this->locals, $keys)); }
/** * populates #thumbnails-json for the node * * @param NodeRef $nodeRef * @return void */ public function syncJsonThumbnails(NodeRef $nodeRef) { $node = $this->NodeService->getByNodeRef($nodeRef, new NodePartials(null, '#thumbnails.fields', null)); /* @var Node $node */ $tags = $node->getOutTags('#thumbnails'); $thumbs = array(); foreach ($tags as $tag) { /* @var Tag $tag */ $thumb = new stdClass(); $thumb->value = $tag->TagValue; $thumb->url = $tag->TagLinkNode->jump('#url'); $thumb->size = intval($tag->TagLinkNode->jump('#size')); $thumb->height = intval($tag->TagLinkNode->jump('#height')); $thumb->width = intval($tag->TagLinkNode->jump('#width')); $thumbs[] = $thumb; } $this->NodeService->updateMeta($node->NodeRef, '#thumbnails-json', JSONUtils::encode($thumbs)); }
/** * Returns debugging information about all passed parameters * * @return string */ public function debug() { return '<pre>' . JSONUtils::encode($this->getParameters(), true, false) . '</pre>'; }
protected function noresultsResponse() { $handler = $this->RequestContext->getControls()->getControl('view_handler'); switch ($handler) { case 'xml': $s .= '<?xml version="1.0"?> <API> <TotalRecords>0</TotalRecords> <Nodes /> </API>'; return $s; case 'json': default: $s = array('TotalRecords' => 0, 'Nodes' => array()); return JSONUtils::encode($s); } }
protected function datewidget() { extract($attributes = array_merge(array('id' => '', 'width' => 'quarter', 'edit_perms' => null, 'view_perms' => null, 'node_edit_perms' => null, 'node_view_perms' => null), $this->_attributes())); $this->attributes = $attributes; if (empty($id)) { throw new Exception('Missing id attribute on datewidget'); } if (substr($id, 0, 1) != '#') { throw new Exception('The id attribute must be a valid role beginning with #'); } if (!$this->__hasPermission($view_perms) || !$this->__hasNodePermission($node_view_perms)) { return; } $id = ltrim($id, '#'); $schemafield = $this->schema->getMetaDef($id); $vArray = $schemafield->Validation->getValidationArray(); if (!empty($vArray['dateonly']) && $vArray['dateonly'] == 'true') { $attributes['dateOnly'] = true; } $uid = $this->_generateUniqueID($id); $fullid = "#{$id}"; $fulluid = "#{$uid}"; $this->xhtml[] = " <li class=\"input-{$width}-width field {$this->_fieldClasses($schemafield)}\">"; $this->xhtml[] = " <label for=\"{$uid}\">{$schemafield->Title}</label>"; if ($this->__hasPermission($edit_perms) && $this->__hasNodePermission($node_edit_perms)) { $this->xhtml[] = " <div id=\"{$uid}-holder\">"; $this->xhtml[] = " <input id=\"{$uid}\" type=\"text\" value=\"{% filter date?value=Data:{$fullid}&format=Y-m-d H:i:s %}\" name=\"{$fulluid}\" class=\"datewidget\"/>"; $this->xhtml[] = " </div>"; $this->xhtml[] = " <script type=\"text/javascript\">"; $this->xhtml[] = " new DateWidget('{$uid}', '{% filter date?value=Data:{$fullid}&format=Y-m-d %}', '{% filter date?value=Data:{$fullid}&format=g:i A %}', " . JSONUtils::encode($attributes) . ");"; $this->xhtml[] = " </script>"; } else { $this->xhtml[] = " <div><p class=\"read-only\">{% filter date?value=Data:{$fullid}&format=Y-m-d %}</p></div>"; } }
public function tagWidgetScript() { /* * Assemble chunks of js for each tag */ $widgetInstantiations = ''; $tagUpdateEvents = ''; $domChangeEvents = array('Out' => '', 'In' => ''); foreach ($this->tagWidgets as $tagArr) { extract($tagArr); $optionsJson = JSONUtils::encode($options); $directionLc = strtolower($direction); // // $widgetInstantiations .= <<<EOT document.{$id}FilterPartial = new TagPartial('{$partial}'); new NodeTagWidget( document.tempRecord, document.{$id}FilterPartial, '#{$id}-filter', {$optionsJson} ); EOT; // // $tagUpdateEvents .= <<<EOT if ( typeof this.get{$direction}Tags( document.{$id}FilterPartial )[0] != 'undefined') { tags.{$direction}.push(this.get{$direction}Tags( document.{$id}FilterPartial)[0].toString()); } EOT; // // $domChangeEvents[$direction] .= <<<EOT document.tempRecord.removeTags('{$directionLc}', document.{$id}FilterPartial); EOT; } /* * Assemble chunks of js for each tag direction */ $tagsInitializeArray = array(); $fireFilter = ''; $domChangeFunctions = ''; $onloadTriggers = ''; foreach ($this->directions as $direction) { $tagsInitializeArray[] = "'{$direction}' : []"; $directionLc = strtolower($direction); // // $fireFilter .= <<<EOT List.filter(\$('#{$direction}TagsFilter'), '{$direction}Tags.exist', tags.{$direction}.join(',')); EOT; // // $domChangeFunctions .= <<<EOT \$('#{$direction}TagsFilter').bind('init', function() { document.tempRecord.init{$direction}Mode = true; var tags = \$(this).val(); {$domChangeEvents[$direction]} if(tags != '') { tags = tags.split(','); \$(tags).each(function(i,tag){ document.tempRecord.add{$direction}Tag( new Tag(new TagPartial(tag)) ); }); } document.tempRecord.init{$direction}Mode = false; }); EOT; // // $onloadTriggers .= <<<EOT \$('#{$direction}TagsFilter').trigger('init'); EOT; } // each direction $tagsInitialize = implode(',', $tagsInitializeArray); /* * Return script tag */ return <<<EOT <script language="JavaScript" type="text/javascript"> document.tempRecord = new NodeObject({}); {$widgetInstantiations} document.tempRecord.bind(Taggable.EVENTS.TAGS_UPDATED,function(){ if(document.tempRecord.init{$direction}Mode) return; var tags = { {$tagsInitialize} }; {$tagUpdateEvents} {$fireFilter} }); {$domChangeFunctions} \$(document).ready(function() { document.tempRecord.init{$direction}Mode = true; // this need to be tur to persist intags document.tempRecord.init(); {$onloadTriggers} }); </script> EOT; }
/** * @dataProvider getTestTypes * * @param array $phpArray * @param string $json * @param string $pretty */ public function testCompareTypes(array $phpArray, $json, $pretty) { $this->assertJsonStringEqualsJsonString(\JSONUtils::encode($phpArray), $json); $this->assertJsonStringEqualsJsonString(\JSONUtils::encode($phpArray, true), $pretty); $this->assertJsonStringEqualsJsonString(\JSONUtils::format($json), $pretty); }