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 items()
 {
     $feedURL = (string) $this->getRequiredTemplateVariable('FeedURL');
     $nativeOrder = StringUtils::strToBool((string) $this->getTemplateVariable('NativeOrder'));
     $includeImage = StringUtils::strToBool((string) $this->getTemplateVariable('IncludeImage'));
     $maxRows = intval((string) $this->getRequiredTemplateVariable('MaxRows'));
     $items = array();
     if (!URLUtils::isUrl($feedURL)) {
         return $items;
     }
     try {
         $feed = $this->FeedParser->parseFeed($feedURL, $nativeOrder);
         $i = 0;
         foreach ($feed->get_items() as $item) {
             if ($i >= $maxRows) {
                 break;
             }
             if (trim($item->get_title()) == '') {
                 continue;
             }
             $itemDate = null;
             if ($item->get_date() != '') {
                 $itemDate = $this->DateFactory->newStorageDate($item->get_date());
             }
             $img = null;
             if ($includeImage) {
                 // first try to get it from the enclosure node itself
                 $tags = $item->get_item_tags('', 'enclosure');
                 if (is_array($tags)) {
                     foreach ($tags as $tag) {
                         if (!isset($tag['attribs']['']['type'])) {
                             continue;
                         }
                         if (strpos($tag['attribs']['']['type'], 'image') !== false) {
                             $img = isset($tag['attribs']['']['url']) ? $tag['attribs']['']['url'] : null;
                             break;
                         }
                     }
                 }
                 if (empty($img)) {
                     $enclosure = $item->get_enclosure();
                     if ($enclosure) {
                         $img = $enclosure->get_thumbnail();
                         if (empty($img)) {
                             $img = $enclosure->get_link();
                         }
                     }
                 }
             }
             $items[] = array('Permalink' => $item->get_permalink(), 'Title' => $item->get_title(), 'Description' => $item->get_description(), 'PublishDate' => $itemDate, 'Image' => $img);
             $i++;
         }
     } catch (FeedParserException $fpe) {
         $this->Logger->debug($fpe->getMessage());
     }
     return $items;
 }
 public function isDeprecated()
 {
     $name = (string) $this->getRequiredParameter('name');
     if (!$this->nameExists()) {
         return true;
     }
     $image = $this->_imageNames[$name];
     if (array_key_exists('Deprecated', $image)) {
         return StringUtils::strToBool($image['Deprecated']);
     }
     return false;
 }
 public function findAll(DTO $dto)
 {
     $sd = __CLASS__ . (string) serialize($dto);
     $slugs = $this->SystemCache->get($sd);
     if ($slugs === false) {
         $this->loadSource();
         $slugs = array();
         $sort_array = array();
         $dir = 'ASC';
         $orderbys = $dto->getOrderBys();
         if (!empty($orderbys)) {
             foreach ($orderbys as $col => $dir) {
             }
         } else {
             $col = 'Slug';
         }
         foreach ($this->objectsBySlug as $slug => $obj) {
             if ($dto->hasParameter('Enabled') && $obj->Enabled != $dto->getParameter('Enabled')) {
                 continue;
             }
             if (!$dto->hasParameter('FlattenChildren') || StringUtils::strToBool($dto->getParameter('FlattenChildren')) == false) {
                 if ($obj->hasParentSlug()) {
                     continue;
                 }
             }
             if (($val = $dto->getParameter('Slug')) != null) {
                 if ($obj->Slug != $val) {
                     continue;
                 }
             }
             if (($val = $dto->getParameter('PluginID')) != null) {
                 if ($obj->PluginID != $val) {
                     continue;
                 }
             }
             $slugs[] = $slug;
             $sort_array[] = $obj[$col];
         }
         array_multisort($sort_array, strtolower($dir) == 'asc' ? SORT_ASC : SORT_DESC, SORT_REGULAR, $slugs);
         $this->SystemCache->put($sd, $slugs, 0);
     }
     // retrieve objects
     $rows = $this->multiGetBySlug($slugs);
     $results = array();
     foreach ($slugs as $slug) {
         if (isset($rows[$slug])) {
             $results[] = $rows[$slug];
         }
     }
     return $dto->setResults($results);
 }
 /**
  * Rotates an image by specified degrees.
  *
  * Options:
  * degrees => value between -180 and +180 (default is 90)
  * autoCrop => if true, image is auto-cropped to remove empty corners (only valid in 'rotate' mode - default scale = 1.3)
  * backgroundColor => color to fill empty corners with e.g. 'blue' or 'rgb(255,255,255)' or '#FFFFFF'(default)
  * mode => 'rotate'(default) or 'distort' - if 'distort' empty corners are blurred rather than filled with background color
  * scale => for distort mode scales image to reduce empty corners - useful values are between about 1.1 to 1.5
  *
  * @param $sourceFile The source file to operate on
  * @param $options An array of otions as described above
  *
  * @see AbstractImageFilter::applyFilter()
  */
 public function applyFilter($sourceFile, $options = null)
 {
     if (!empty($options['angle']) && !is_numeric($options['angle'])) {
         throw new ImageFilterException("Degrees parameter must be a valid integer value");
     }
     $this->degrees = sprintf("%+d", !empty($options['angle']) ? intval($options['angle']) : 0);
     if ($this->degrees < -180 || $this->degrees > 180) {
         throw new ImageFilterException("Degrees parameter must be between -180 and +180");
     }
     $this->autoCrop = StringUtils::strToBool($options['autoCrop']);
     $this->mode = !empty($options['mode']) ? $options['mode'] : 'rotate';
     $this->scale = !empty($options['scale']) ? $options['scale'] : '0';
     // default to white if no background color specified
     $this->backgroundColor = !empty($options['backgroundColor']) ? $options['backgroundColor'] : '#ffffff';
     return parent::applyFilter($sourceFile, $options);
 }
 /**
  * Rebuilds thumbnails for a single node ref or array of node refs.
  */
 public function rebuildThumbnails()
 {
     $data = $this->getData();
     $forceRebuildExisting = isset($data['forceRebuildExisting']) ? StringUtils::strToBool($data['forceRebuildExisting']) : false;
     if (isset($data['nodeRef'])) {
         $this->rebuildThumbnailsOnNodeRef($data['nodeRef'], $forceRebuildExisting);
         return;
     }
     if (!isset($data['nodeRefs']) || !is_array($data['nodeRefs'])) {
         return;
     }
     foreach ($data['nodeRefs'] as $nodeRef) {
         $this->rebuildThumbnailsOnNodeRef($nodeRef, $forceRebuildExisting);
         $this->TransactionManager->commit()->begin();
         usleep(100000);
     }
 }
 protected function filter()
 {
     $eventName = $this->getParameter('name');
     if (StringUtils::strToBool($this->getParameter('allowTemplateCode')) == true) {
         $this->allowTemplateCode();
     }
     $params = $this->getParameters();
     $output = new Transport();
     foreach ($params as $k => $v) {
         $output->{$k} = $v;
     }
     if (!isset($output->Node)) {
         $output->Node = $this->getLocal('Node');
     }
     $this->Events->trigger($eventName, $output);
     return $output->value;
 }
 public function getDuration()
 {
     $name = trim((string) $this->getParameter('name'));
     $fullPage = StringUtils::strToBool((string) $this->getParameter('FullPage'));
     if (empty($name)) {
         $name = 'default';
     }
     if (in_array($name, explode(',', 'none,never,off,0,zero,no'))) {
         return 0;
     }
     if (!array_key_exists($name, $this->durations)) {
         $name = 'default';
     }
     $duration = abs((int) $this->durations[$name]);
     if (!$fullPage || $duration < 1) {
         return $duration;
     }
     // full page cache duration should be half the cache time
     return ceil($duration / 2);
 }
 protected function handle()
 {
     $qsa = StringUtils::strToBool((string) $this->getTemplateVariable('QSA'));
     $destination = $this->getRequiredTemplateVariable('Destination');
     $isPermanent = StringUtils::strToBool((string) $this->getTemplateVariable('IsPermanent'));
     $sc = $isPermanent ? Response::SC_MOVED_PERMANENTLY : Response::SC_OK;
     if ($qsa) {
         $qs = $this->Request->getQueryString();
         if (!empty($qs)) {
             if (strpos($destination, '?') === false) {
                 $destination .= '?' . $qs;
             } else {
                 $destination .= '&' . $qs;
             }
         }
     }
     $this->Response->addHeader('Cache-Control', 'no-cache, must-revalidate, post-check=0, pre-check=0');
     $this->Response->addHeader('Expires', $this->DateFactory->newLocalDate()->toRFCDate());
     $this->Response->sendStatus($sc)->sendRedirect($destination);
 }
 /**
  * Creates an underlay of color or an image to the source image.
  *
  * image => a base64 encoded data string to use as background matte
  * repeat => if the image should be repeated
  * color => a color to use if an image is not set
  * width => the width of the canvas to place the source image on
  * height => the height of the canvas to place the source image on
  * anchor => may be one of 'northwest', 'north', 'northeast', 'west', 'center', 'east', 'southwest', 'south' or 'southeast'
  * offsetX => the X offset from relative to the anchor position (default is 0)
  * offsetY => the Y offset from relative to the anchor position (default is 0)
  *
  * @param $sourceFile The source file to operate on
  * @param $options An array of options as described above
  *
  * @see AbstractImageFilter::applyFilter()
  */
 public function applyFilter($sourceFile, $options = null)
 {
     if (!empty($options['image']) && $options['image'] != 'null') {
         $this->image = $this->prepareImageData($options['image']);
         $this->repeat = StringUtils::strToBool($options['repeat']);
     }
     $this->color = !empty($options['color']) ? '#' . preg_replace('/[^a-f0-9]/i', '', $options['color']) : "#ffffff";
     if (!empty($this->color) && !preg_match('/^#[a-f0-9]{6}$/i', $this->color)) {
         throw new ImageFilterException("Color must be a valid hex value " . $this->color);
     }
     if (!empty($options['width']) && !is_numeric($options['width'])) {
         throw new ImageFilterException("Canvas width must be a valid integer value");
     }
     $this->width = !empty($options['width']) ? intval($options['width']) : 0;
     if (!empty($options['height']) && !is_numeric($options['height'])) {
         throw new ImageFilterException("Canvas height must be a valid integer value");
     }
     $this->height = !empty($options['height']) ? intval($options['height']) : 0;
     $this->populateAnchorFields($options);
     return parent::applyFilter($sourceFile, $options);
 }
 protected function primaryImageEmbedOptions()
 {
     if (!count($this->_primaryImageEmbedOptions)) {
         foreach ($this->_imageNames as $key => $image) {
             if (array_key_exists('Title', $image)) {
                 $title = $image['Title'];
             } else {
                 $title = SlugUtils::unsluggify($key);
             }
             $deprecated = false;
             if (array_key_exists('Deprecated', $image)) {
                 $deprecated = StringUtils::strToBool($image['Deprecated']);
             }
             $size = '';
             if (array_key_exists('Size', $image)) {
                 $size = (string) $image['Size'];
             }
             $this->_primaryImageEmbedOptions[] = array('EmbedOptionSlug' => $key, 'EmbedOptionTitle' => $title, 'EmbedOptionDeprecated' => $deprecated, 'EmbedOptionSize' => $size);
         }
         $this->_primaryImageEmbedOptions[] = array('EmbedOptionSlug' => 'off', 'EmbedOptionTitle' => 'DO NOT Auto Embed', 'EmbedOptionDeprecated' => false, 'EmbedOptionSize' => '');
     }
     return $this->_primaryImageEmbedOptions;
 }
 public function findAll()
 {
     $dto = new NodeQuery();
     $this->buildLimitOffset($dto);
     $this->buildSorts($dto);
     $this->buildFilters($dto);
     $this->passthruParameter($dto, 'Elements.in');
     $this->passthruParameter($dto, 'Sites.in');
     //$this->passthruParameter($dto, 'SiteIDs.in');
     $this->passthruParameter($dto, 'Slugs.in');
     $this->passthruParameter($dto, 'Meta.select');
     $this->passthruParameter($dto, 'OutTags.select');
     $this->passthruParameter($dto, 'InTags.select');
     $this->passthruParameter($dto, 'Sections.select');
     $this->passthruParameter($dto, 'OrderByInTag');
     $this->passthruParameter($dto, 'OrderByOutTag');
     $this->passthruParameter($dto, 'Title.like');
     $this->passthruParameter($dto, 'Title.ieq');
     $this->passthruParameter($dto, 'Title.eq');
     $this->passthruParameter($dto, 'Title.firstChar');
     $this->passthruParameter($dto, 'Status.isActive');
     $this->passthruParameter($dto, 'Status.all');
     $this->passthruParameter($dto, 'Status.eq');
     $this->passthruParameter($dto, 'TreeID.childOf');
     $this->passthruParameter($dto, 'TreeID.eq');
     $this->passthruParameter($dto, 'ActiveDate.before');
     $this->passthruParameter($dto, 'ActiveDate.after');
     $this->passthruParameter($dto, 'ActiveDate.start');
     $this->passthruParameter($dto, 'ActiveDate.end');
     $this->passthruParameter($dto, 'CreationDate.before');
     $this->passthruParameter($dto, 'CreationDate.after');
     $this->passthruParameter($dto, 'CreationDate.start');
     $this->passthruParameter($dto, 'CreationDate.end');
     $this->passthruParameter($dto, 'OutTags.exist');
     $this->passthruParameter($dto, 'InTags.exist');
     $this->passthruParameter($dto, 'Meta.exist');
     $this->passthruParameter($dto, 'Sections.exist');
     foreach ($this->Request->getParameters() as $name => $value) {
         if (strpos($name, '#') === 0) {
             $dto->setParameter(str_replace('_', '.', $name), $value);
         }
     }
     $dto->isRetrieveTotalRecords(true);
     if ($this->Request->getParameter('OrderBy') != null) {
         $dto->setOrderBys(array());
         $dto->setOrderBy($this->Request->getParameter('OrderBy'));
     }
     $this->Events->trigger('NodeApiController.findAll', $dto);
     $dto = $this->RegulatedNodeService->findAll($dto, $this->Request->getParameter('ForceReadWrite') != null ? StringUtils::strToBool($this->Request->getParameter('ForceReadWrite')) : false);
     echo $this->readDTO($dto);
     return null;
 }
 /**
  * @see TemplateEngineInterface::loadTemplateExtended
  */
 public function loadTemplateExtended(Template $template, &$globals)
 {
     $params = $template->getLocals();
     if (!empty($params['Presenter'])) {
         $template->setPresenter($params['Presenter']);
     }
     if (!empty($params['CacheTime'])) {
         $template->setCacheTime((int) $params['CacheTime']);
     } else {
         $template->setCacheTime(300);
     }
     if ($template->getCacheTime() > 0 && (empty($params['NoCache']) || StringUtils::strToBool($params['NoCache']) == false)) {
         $template->setCacheable(true);
     }
     return $template;
 }
 public function setAudiencescienceEnabled()
 {
     $this->audiencescienceEnabled = StringUtils::strToBool((string) $this->getRequiredParameter('value'));
 }
 /**
  * Returns false if the node fails to match the parameters
  *
  * @throws NodeException
  * @param  $node
  * @param  $filterParams
  * @param  $metaParams
  * @return bool
  */
 protected function filterNode($node, $filterParams, $metaParams)
 {
     if (!empty($filterParams)) {
         if (is_null($this->now)) {
             $this->now = $this->DateFactory->newStorageDate();
         }
         foreach ($filterParams as $key => $value) {
             if (strpos($key, '#') === 0) {
                 continue;
             }
             switch ($key) {
                 case 'Title.firstChar':
                     $firstChar = strtolower(substr($node['Title'], 0, 1));
                     if ($value == '#') {
                         $ord = ord($firstChar);
                         if ($ord >= 97 && $ord <= 122) {
                             return false;
                         }
                     } else {
                         if (strcmp($firstChar, $value) !== 0) {
                             return false;
                         }
                     }
                     break;
                 case 'Title.eq':
                     if (strcmp($value, $node['Title']) !== 0) {
                         return false;
                     }
                     break;
                 case 'Title.ieq':
                     if (strcasecmp($value, $node['Title']) !== 0) {
                         return false;
                     }
                     break;
                 case 'Title.like':
                     if (is_null($value)) {
                         break;
                     }
                     if (stripos($node['Title'], $value) === FALSE) {
                         return false;
                     }
                     break;
                 case 'TreeID.childOf':
                     if (stripos($node['TreeID'], $value) !== 0) {
                         return false;
                     }
                     break;
                 case 'TreeID.eq':
                     if (strcmp($value, $node['TreeID']) !== 0) {
                         return false;
                     }
                     break;
                 case 'TreeID.depth':
                     if (strlen($node['TreeID']) / 4 != $value) {
                         return false;
                     }
                     break;
                 case 'ActiveDate.after':
                     if ($node['ActiveDate']->toUnix() < $value->toUnix()) {
                         return false;
                     }
                     break;
                 case 'ActiveDate.before':
                     if ($node['ActiveDate']->toUnix() >= $value->toUnix()) {
                         return false;
                     }
                     break;
                 case 'ActiveDate.start':
                     if ($node['ActiveDate']->toUnix() <= $value->toUnix()) {
                         return false;
                     }
                     break;
                 case 'ActiveDate.end':
                     if ($node['ActiveDate']->toUnix() >= $value->toUnix()) {
                         return false;
                     }
                     break;
                 case 'CreationDate.after':
                     if ($node['CreationDate']->toUnix() < $value->toUnix()) {
                         return false;
                     }
                     break;
                 case 'CreationDate.before':
                     if ($node['CreationDate']->toUnix() >= $value->toUnix()) {
                         return false;
                     }
                     break;
                 case 'CreationDate.start':
                     if ($node['CreationDate']->toUnix() <= $value->toUnix()) {
                         return false;
                     }
                     break;
                 case 'CreationDate.end':
                     if ($node['CreationDate']->toUnix() >= $value->toUnix()) {
                         return false;
                     }
                     break;
                 case 'Status.eq':
                     switch (strtolower($value)) {
                         case 'published':
                             if (strtolower($node['Status']) != 'published') {
                                 return false;
                             }
                             break;
                         case 'draft':
                             if (strtolower($node['Status']) != 'draft') {
                                 return false;
                             }
                             break;
                         case 'deleted':
                             if (strtolower($node['Status']) != 'deleted') {
                                 return false;
                             }
                             break;
                         default:
                             if (strtolower($node['Status']) == 'deleted') {
                                 return false;
                             }
                             break;
                     }
                     break;
                 case 'Status.isActive':
                     if (StringUtils::strToBool($value) == true && (strcmp('published', $node['Status']) !== 0 || $node['ActiveDate']->toUnix() >= $this->now->toUnix())) {
                         return false;
                     }
                     break;
                 case 'Status.all':
                     if (StringUtils::strToBool($value) == false && strcmp('deleted', $node['Status']) === 0) {
                         return false;
                     }
                     break;
                     //                case 'IncludesMeta':
                     //                    $found = false;
                     //                    foreach($value as $partial) {
                     //                        $meta = MetaUtils::filterMeta($node['Metas'],$partial->getMetaName());
                     //                        if($partial->match($meta))
                     //                            $found = true;
                     //                    }
                     //                    if(!$found)
                     //                        return false;
                     //                    break;
                 //                case 'IncludesMeta':
                 //                    $found = false;
                 //                    foreach($value as $partial) {
                 //                        $meta = MetaUtils::filterMeta($node['Metas'],$partial->getMetaName());
                 //                        if($partial->match($meta))
                 //                            $found = true;
                 //                    }
                 //                    if(!$found)
                 //                        return false;
                 //                    break;
                 case 'Meta.exist':
                     foreach ($value as $partial) {
                         $meta = $node->getMeta($partial->getMetaName());
                         if (empty($meta) || !$partial->match($meta)) {
                             return false;
                         }
                     }
                     break;
                     //                case 'IncludesOutTags':
                     //                    $found = false;
                     //                    foreach($value as $partial) {
                     //                        foreach($node['OutTags'] as $tag)
                     //                        {
                     //                            if($this->TagsHelper->matchPartial($partial, $tag)) {
                     //                                $found = true;
                     //                                break 2;
                     //                            }
                     //                        }
                     //                    }
                     //                    if(!$found)
                     //                        return false;
                     //
                     //                    break;
                 //                case 'IncludesOutTags':
                 //                    $found = false;
                 //                    foreach($value as $partial) {
                 //                        foreach($node['OutTags'] as $tag)
                 //                        {
                 //                            if($this->TagsHelper->matchPartial($partial, $tag)) {
                 //                                $found = true;
                 //                                break 2;
                 //                            }
                 //                        }
                 //                    }
                 //                    if(!$found)
                 //                        return false;
                 //
                 //                    break;
                 case 'OutTags.exist':
                     $found = 0;
                     foreach ($value as $partial) {
                         foreach ($node['OutTags'] as $tag) {
                             if ($this->TagsHelper->matchPartial($partial, $tag)) {
                                 ++$found;
                                 break;
                             }
                         }
                     }
                     if ($found != count($value)) {
                         return false;
                     }
                     break;
                     //                case 'IncludesInTags':
                     //                    $found = false;
                     //                    foreach($value as $partial) {
                     //                        foreach($node['InTags'] as $tag)
                     //                        {
                     //                            if($this->TagsHelper->matchPartial($partial, $tag)) {
                     //                                $found = true;
                     //                                break 2;
                     //                            }
                     //                        }
                     //                    }
                     //                    if(!$found)
                     //                        return false;
                     //
                     //                    break;
                 //                case 'IncludesInTags':
                 //                    $found = false;
                 //                    foreach($value as $partial) {
                 //                        foreach($node['InTags'] as $tag)
                 //                        {
                 //                            if($this->TagsHelper->matchPartial($partial, $tag)) {
                 //                                $found = true;
                 //                                break 2;
                 //                            }
                 //                        }
                 //                    }
                 //                    if(!$found)
                 //                        return false;
                 //
                 //                    break;
                 case 'InTags.exist':
                     $found = 0;
                     foreach ($value as $partial) {
                         foreach ($node['InTags'] as $tag) {
                             if ($this->TagsHelper->matchPartial($partial, $tag)) {
                                 ++$found;
                                 break;
                             }
                         }
                     }
                     if ($found != count($value)) {
                         return false;
                     }
                     break;
             }
         }
     }
     if (!empty($metaParams)) {
         $schema = $node['NodeRef']->getElement()->getSchema();
         foreach ($metaParams as $mArgs) {
             list($full, $name, $operator, $compareValue) = $mArgs;
             $def = $schema->getMetaDef($name);
             $datatype = $def->Datatype;
             if (is_object($node)) {
                 $realValue = $node->getMetaValue($name);
             } else {
                 $meta = MetaUtils::filterMeta($node['Metas'], $name);
                 $realValue = $meta->getMetaValue();
             }
             if ($datatype == 'flag') {
                 throw new NodeException('Unable to run meta clause on flag datatype');
             }
             switch ($operator) {
                 case 'eq':
                     if (in_array($datatype, array('text', 'varchar'))) {
                         if (strcmp($compareValue, $realValue) !== 0) {
                             return false;
                         } else {
                             if ($compareValue !== $realValue) {
                                 return false;
                             }
                         }
                     }
                     break;
                 case 'ieq':
                     if (strcasecmp($compareValue, $realValue) !== 0) {
                         return false;
                     }
                     break;
                 case 'like':
                     if (is_null($compareValue)) {
                         break;
                     }
                     if (stripos($compareValue, $realValue) === FALSE) {
                         return false;
                     }
                     break;
                 case 'before':
                     $d = $this->DateFactory->newLocalDate($value);
                     if ($realValue->toUnix() <= $d->toUnix()) {
                         return false;
                     }
                     break;
                 case 'after':
                     $d = $this->DateFactory->newLocalDate($compareValue);
                     if ($realValue->toUnix() > $d->toUnix()) {
                         return false;
                     }
                     break;
                 case 'start':
                     $d = $this->DateFactory->newLocalDate($compareValue);
                     $d->setTime(0, 0, 0);
                     if ($realValue->toUnix() >= $d->toUnix()) {
                         return false;
                     }
                     break;
                 case 'end':
                     $d = $this->DateFactory->newLocalDate($compareValue);
                     $d->setTime(23, 59, 59);
                     if ($realValue->toUnix() <= $d->toUnix()) {
                         return false;
                     }
                     break;
                 case 'notEq':
                     if (in_array($datatype, array('text', 'varchar'))) {
                         if (strcmp($compareValue, $realValue) === 0) {
                             return false;
                         } else {
                             if ($compareValue === $realValue) {
                                 return false;
                             }
                         }
                     }
                     break;
                 case 'lessThan':
                     if ($compareValue >= $realValue) {
                         return false;
                     }
                     break;
                 case 'lessThanEq':
                     if ($compareValue > $realValue) {
                         return false;
                     }
                     break;
                 case 'greaterThan':
                     if ($compareValue <= $realValue) {
                         return false;
                     }
                     break;
                 case 'greaterThanEq':
                     if ($compareValue < $realValue) {
                         return false;
                     }
                     break;
                     /*
                      * case insensitive comparison for #meta.in filtering.
                      * works exactly like the SQL SomeValue IN ('item1', 'item2')
                      */
                 /*
                  * case insensitive comparison for #meta.in filtering.
                  * works exactly like the SQL SomeValue IN ('item1', 'item2')
                  */
                 case 'in':
                     $inValues = explode(',', $compareValue);
                     $foundValue = false;
                     if (in_array($datatype, array('text', 'varchar'))) {
                         foreach ($inValues as $val) {
                             if (strcasecmp($val, $realValue) === 0) {
                                 $foundValue = true;
                                 break;
                             }
                         }
                     } else {
                         foreach ($inValues as $val) {
                             if ($val === $realValue) {
                                 $foundValue = true;
                                 break;
                             }
                         }
                     }
                     if (!$foundValue) {
                         return false;
                     }
                     break;
             }
         }
     }
     return true;
 }
 public function setResolveLinks($resolve)
 {
     $this->fields['ResolveLinks'] = StringUtils::strToBool($resolve);
 }
 protected function _buildWidgetOptions($schemafield, $attributes)
 {
     // Non-file related tag widget defaults to media-quick-add
     if (isset($attributes['class'])) {
         switch ($attributes['class']) {
             case 'MediaGalleryTagWidget':
             case 'MediaTagWidget':
             case 'PrimaryMediaTagWidget':
             case 'MediaLibraryTagWidget':
                 if (empty($attributes['quick-add-action'])) {
                     $attributes['quick-add-action'] = 'media-quick-add';
                 }
                 break;
         }
     }
     $opt = parent::_buildWidgetOptions($schemafield, $attributes);
     // Add/edit control action detection
     $opt[] = "\t\t\tIsNewControlAction: {% if Data:CONTROL_ACTION_METHOD eq 'edit' %}false{% else %}true{% endif %}";
     // set remove and update nonces for non-fieldlike schemas, and always for media galleries
     if (!$schemafield->isFieldlike() || $attributes['class'] == 'MediaGalleryTagWidget') {
         $opt[] = "\t\t\tRemoveTagNonce: '{% filter nonce?action=node-remove-tag %}'";
         $opt[] = "\t\t\tUpdateTagsNonce: '{% filter nonce?action=node-update-tags %}'";
     }
     if ($schemafield['Fieldlike']) {
         $opt[] = "          IsFieldLike: " . $schemafield['Fieldlike'];
     }
     if (!empty($attributes['default-quick-add-element'])) {
         $opt[] = "          DefaultQuickAddElement: '" . $attributes['default-quick-add-element'] . "'";
     }
     //@deprecated
     if (!empty($attributes['default-quickadd-element'])) {
         $opt[] = "          DefaultQuickAddElement: '" . $attributes['default-quickadd-element'] . "'";
     }
     if (!empty($attributes['file-mask'])) {
         $opt[] = "\t\t\tFileMask: '" . $attributes['file-mask'] . "'";
     }
     if (isset($attributes['class'])) {
         switch ($attributes['class']) {
             case 'MediaGalleryTagWidget':
             case 'MediaTagWidget':
             case 'PrimaryMediaTagWidget':
             case 'MediaLibraryTagWidget':
                 $opt[] = "              QuickAddURL: '{% filter contexts-get-by-slug?Slug=api&Property=BaseURL %}/media/quick-add.json/'";
                 break;
             case 'FileTagWidget':
                 $opt[] = "              QuickAddURL: '{% filter contexts-get-by-slug?Slug=api&Property=BaseURL %}/files/quick-add.json/'";
                 break;
         }
     }
     if (isset($attributes['allow-quick-add'])) {
         if (StringUtils::strToBool($attributes['allow-quick-add'])) {
             $opt[] = "              AllowQuickAdd: true";
         } else {
             $opt[] = "              AllowQuickAdd: false";
         }
     }
     if ($this->dropImageToMarkdownTemplate) {
         $opt[] = sprintf("              DropImageToMarkdownTemplate: '%s'", $this->dropImageToMarkdownTemplate);
     }
     return $opt;
 }
 protected function parse()
 {
     if ($this->changed) {
         return;
     }
     if ($this->parsed != true) {
         $this->cmsNavItems = array();
         $this->plugins = array();
         $this->aspects = array();
         $this->elements = array();
         $this->site = null;
         $xml = $this->SimpleXMLParser->parseXMLFile($this->environmentsXMLFile);
         foreach ($xml as $ename => $enode) {
             switch ((string) $ename) {
                 case 'environment':
                     foreach ($enode->attributes() as $name => $value) {
                         $environment[$name] = (string) $value;
                     }
                     if (!empty($environment['slug']) && strtolower($environment['slug']) != strtolower($_SERVER['ENVIRONMENT'])) {
                         continue;
                     }
                     $this->rewriteBase = strval($enode->rewrite_base);
                     $this->publicFilesBaseURI = strval($enode->public_files_base_uri);
                     foreach ($enode as $name => $node) {
                         switch ((string) $name) {
                             case 'context':
                                 $context = array('sites' => array());
                                 foreach ($node->attributes() as $name => $value) {
                                     $context[$name] = (string) $value;
                                 }
                                 foreach ($node as $childNode) {
                                     if ($childNode->getName() == 'sites') {
                                         foreach ($childNode as $siteNode) {
                                             $site = array();
                                             foreach ($siteNode->attributes() as $name => $value) {
                                                 $site[$name] = (string) $value;
                                             }
                                             // By default if a site is not specified as enabled, it is enabled.
                                             if (!array_key_exists('enabled', $site)) {
                                                 $site['enabled'] = true;
                                             }
                                             // If the context that contains the site is disabled
                                             // The site within it should always be disabled.
                                             if (!StringUtils::strToBool($context['enabled'])) {
                                                 $site['enabled'] = false;
                                             }
                                             foreach ($siteNode as $siteChildNode) {
                                                 if ((string) $siteChildNode->getName() == 'storage_facility') {
                                                     $sf = array();
                                                     foreach ($siteChildNode->attributes() as $name => $value) {
                                                         $sf[$name] = (string) $value;
                                                     }
                                                     foreach ($siteChildNode as $sfChildNode) {
                                                         $sf[(string) $sfChildNode->getName()] = (string) $sfChildNode;
                                                     }
                                                     if (isset($sf['for'])) {
                                                         $site['storagefacilities'][$sf['for']] = $sf;
                                                     }
                                                 } else {
                                                     $site[(string) $siteChildNode->getName()] = (string) $siteChildNode;
                                                 }
                                             }
                                             $this->siteContext = $context;
                                             $this->site = $site;
                                             break;
                                         }
                                     } else {
                                         if ($childNode->getName() == 'storage_facility') {
                                             $sf = array();
                                             foreach ($childNode->attributes() as $name => $value) {
                                                 $sf[$name] = (string) $value;
                                             }
                                             foreach ($childNode as $sfChildNode) {
                                                 $sf[(string) $sfChildNode->getName()] = (string) $sfChildNode;
                                             }
                                             if (isset($sf['for'])) {
                                                 $context['storagefacilities'][$sf['for']] = $sf;
                                             }
                                         } else {
                                             $context[(string) $childNode->getName()] = (string) $childNode;
                                         }
                                     }
                                 }
                                 if (empty($context['sites'])) {
                                     unset($context['sites']);
                                 }
                                 $contextObject = URLUtils::resolveContextFromArray($context, $this->isAliasDomain);
                                 $contextObject->ContextID = count($this->contexts) + 1;
                                 $this->contexts[] = $contextObject;
                                 break;
                         }
                     }
                     break;
             }
         }
         $xml = $this->SimpleXMLParser->parseXMLFile($this->systemXMLFile);
         foreach ($xml as $name => $node) {
             $array = array();
             $sort_array = array();
             $sort_array2 = array();
             switch ((string) $name) {
                 case 'plugins':
                     foreach ($node as $pluginNode) {
                         if ($pluginNode->getName() == 'plugin') {
                             $item = $this->SystemXMLConverter->xmlToPlugin(new Plugin(), $pluginNode);
                             $sort_array[] = $item->Slug;
                             $array[] = $item;
                         }
                     }
                     array_multisort($sort_array, SORT_ASC, $array);
                     $this->plugins = $array;
                     break;
                 case 'elements':
                     foreach ($node as $elementNode) {
                         if ($elementNode->getName() == 'element') {
                             $item = $this->SystemXMLConverter->xmlToElement(new Element(), $elementNode);
                             $sort_array[] = $item->Slug;
                             $array[] = $item;
                         }
                     }
                     array_multisort($sort_array, SORT_ASC, $array);
                     $this->elements = $array;
                     break;
                 case 'aspects':
                     foreach ($node as $aspectNode) {
                         if ($aspectNode->getName() == 'aspect') {
                             $item = $this->SystemXMLConverter->xmlToAspect(new Aspect(), $aspectNode);
                             $sort_array[] = $item->Slug;
                             $array[] = $item;
                         }
                     }
                     array_multisort($sort_array, SORT_ASC, $array);
                     $this->aspects = $array;
                     break;
                 case 'cmsnavitems':
                     foreach ($node as $cmsNavNode) {
                         if ($cmsNavNode->getName() == 'item') {
                             $item = $this->SystemXMLConverter->xmlToCMSNavItem(new CMSNavItem(), $cmsNavNode);
                             $sort_array[] = $item->SortOrder;
                             $sort_array2[] = $item->Slug;
                             $array[] = $item;
                         }
                     }
                     array_multisort($sort_array, SORT_ASC, $sort_array2, SORT_ASC, $array);
                     $this->cmsNavItems = $array;
                     break;
             }
         }
         $contextArray = $this->siteContext;
         $site2 = array_merge($contextArray, $this->site);
         if (isset($contextArray['storagefacilities'])) {
             foreach ($contextArray['storagefacilities'] as $key => $sf) {
                 $site2['storagefacilities'][$key] = $sf;
             }
         }
         if (isset($site['storagefacilities'])) {
             foreach ($site['storagefacilities'] as $key => $sf) {
                 $site2['storagefacilities'][$key] = $sf;
             }
         }
         $site2['context'] = $contextArray['slug'];
         unset($site2['sites']);
         $siteArray = $site2;
         $site = URLUtils::resolveSiteFromArray($siteArray, $this->isAliasDomain);
         $site->SiteID = 1;
         $this->sites[$site->Slug] = $site;
         $this->parsed = true;
     }
 }
 protected function items()
 {
     $dto = new NodeQuery();
     $this->buildLimitOffset($dto);
     if ($this->getTemplateVariable('Site.all') == null) {
         if ($this->getTemplateVariable('Sites.in') == null) {
             $site = $this->RequestContext->getSite();
             $dto->setParameter('Sites.in', $site->getSlug());
         }
         $this->passthruTemplateVariable($dto, 'Sites.in');
         //$this->passthruTemplateVariable($dto, 'SiteIDs.in');
     }
     $this->passthruTemplateVariable($dto, 'NodeRefs.in');
     $this->passthruTemplateVariable($dto, 'Elements.in');
     $this->passthruTemplateVariable($dto, 'Slugs.in');
     $this->passthruTemplateVariable($dto, 'Meta.select');
     $this->passthruTemplateVariable($dto, 'OutTags.select');
     $this->passthruTemplateVariable($dto, 'InTags.select');
     //$this->passthruTemplateVariable($dto, 'Sections.select');
     $this->passthruTemplateVariable($dto, 'OrderByInTag');
     $this->passthruTemplateVariable($dto, 'OrderByOutTag');
     $this->passthruTemplateVariable($dto, 'Title.like');
     $this->passthruTemplateVariable($dto, 'Title.ieq');
     $this->passthruTemplateVariable($dto, 'Title.eq');
     $this->passthruTemplateVariable($dto, 'Title.firstChar');
     $this->passthruTemplateVariable($dto, 'Status.isActive');
     $this->passthruTemplateVariable($dto, 'Status.all');
     $this->passthruTemplateVariable($dto, 'Status.eq');
     if ($this->getTemplateVariable('Status.isActive') === null && $this->getTemplateVariable('Status.all') === null && $this->getTemplateVariable('Status.eq') === null) {
         $dto->setParameter('Status.isActive', true);
     }
     $this->passthruTemplateVariable($dto, 'ActiveDate.before');
     $this->passthruTemplateVariable($dto, 'ActiveDate.after');
     $this->passthruTemplateVariable($dto, 'ActiveDate.start');
     $this->passthruTemplateVariable($dto, 'ActiveDate.end');
     $this->passthruTemplateVariable($dto, 'CreationDate.before');
     $this->passthruTemplateVariable($dto, 'CreationDate.after');
     $this->passthruTemplateVariable($dto, 'CreationDate.start');
     $this->passthruTemplateVariable($dto, 'CreationDate.end');
     $this->passthruTemplateVariable($dto, 'OutTags.exist');
     $this->passthruTemplateVariable($dto, 'InTags.exist');
     $this->passthruTemplateVariable($dto, 'Meta.exist');
     //$this->passthruTemplateVariable($dto, 'Sections.exist');
     $this->passthruTemplateVariable($dto, 'TreeID.childOf');
     $this->passthruTemplateVariable($dto, 'TreeID.depth');
     foreach ($this->templateVars as $name => $value) {
         if (strpos($name, '#') === 0) {
             $dto->setParameter($name, $value);
         }
     }
     $dto->setOrderBy($this->getTemplateVariable('OrderBy'));
     $this->Events->trigger('NodeWebController.items', $dto);
     $dto = $this->RegulatedNodeService->findAll($dto, $this->getTemplateVariable('ForceReadWrite') != null ? StringUtils::strToBool($this->getTemplateVariable('ForceReadWrite')) : false);
     return $this->readNodeQuery($dto);
 }
 /**
  * Fills the {@link &$model} with values from the {@link $fields}
  *
  * @param array       $fields    An array with field names as keys and the values to store.
  * @param array       $rawFields An array with field names as keys and the raw value as the value.
  *                                  Used for 'html' typed fields, for raw access to the field value.
  * @param ModelObject &$model    The ModelObject we're filling
  * @param Errors      $errors    The Errors object to update if there are any field errors
  *
  * @return ModelObject Returns &$model after modifications
  */
 public function inputArrayToModel(array $fields, array $rawFields, ModelObject &$model, Errors $errors)
 {
     $fields = array_intersect_key($fields, array_flip($model->getPersistentFields()));
     foreach ($fields as $key => $value) {
         $datatype = $model->getDatatype($key);
         // Clean HTML
         if ($datatype === 'html') {
             $validation = $model->getValidation($key);
             $fields[$key] = $this->InputClean->clean($rawFields[$key], array_key_exists('allowedtags', $validation) ? $validation['allowedtags'] : null);
         }
         // Convert INT
         if ($datatype === 'int' && !empty($value)) {
             if (is_numeric($value) === false) {
                 $errors->addFieldError('invalid', get_class($model) . '.' . $key, 'field', $model->getFieldTitle($key), $value, "Cannot convert string [{$value}] to integer.");
             } else {
                 $fields[$key] = intval($value);
             }
         }
         // Convert FLOAT
         if ($datatype === 'float' && !empty($value)) {
             if (is_numeric($value) === false) {
                 $errors->addFieldError('invalid', get_class($model) . '.' . $key, 'field', $model->getFieldTitle($key), $value, "Cannot convert string [{$value}] to float.");
             } else {
                 $fields[$key] = floatval($value);
             }
         }
         // Convert BOOLEAN
         if ($datatype === 'boolean') {
             $fields[$key] = StringUtils::strToBool($value);
         }
         // Convert DATE
         if ($datatype === 'date' && strlen(trim($value)) > 0) {
             try {
                 $fields[$key] = $this->DateFactory->newLocalDate(trim($value));
             } catch (DateException $e) {
                 $errors->addFieldError('invalid', get_class($model) . '.' . $key, 'field', $model->getFieldTitle($key), $value, "Cannot convert string [{$value}] to date.");
             }
         }
     }
     $model->setFromArray($fields);
     return $model;
 }
 public function loadTemplateExtended(Template $template, &$globals)
 {
     if ($this->benchmarkRendering) {
         $this->Benchmark->start('load-template-extended-' . $template->getName());
     }
     //        if(!($templateFileCached = $this->TemplateCache->get('t:'.$template->getName())))
     //        {
     if (!$this->TemplateService->fileExists($template->getName())) {
         throw new TemplateEngineException("Template file not found for template name: " . $template->getName());
     }
     $file = $this->TemplateService->resolveFile($template->getName());
     $template->setFile($file->getLocalPath());
     $this->Logger->debug("Loading template file: " . $template->getFile());
     $this->loadTemplateContents($template, $globals);
     $this->Logger->debug('Parsing set blocks: ' . $template->getName());
     if (preg_match_all("/\\{\\%\\s+(set|setGlobal|appendGlobal)\\s+([^\\%]+?)\\s+\\%\\}[\n\r\t]*(.*?)[\n\r\t]*\\{\\%\\s+end\\s+\\%\\}/s", $template->getContents(), $setMatches, PREG_SET_ORDER)) {
         $template->setSetMatches($setMatches);
     } else {
         $template->setSetMatches(array());
     }
     //            $this->TemplateCache->put('t:'.$template->getName(), $template, 0);
     //        } else {
     //
     //            $template->setFile($templateFileCached->getFile());
     //            $template->setSetMatches($templateFileCached->getSetMatches());
     //            $template->setContents($templateFileCached->getContents());
     //
     //        }
     $params = $template->getLocals();
     $templateSetGlobals = array();
     foreach ($template->getSetMatches() as $m) {
         $m[3] = $this->parseFormatVariables($m[3], $this->getConstants());
         switch ($m[1]) {
             case 'set':
                 if (array_key_exists($m[2], $params)) {
                     continue;
                 }
                 $val = $this->parseFormatVariablesAndFilters($m[3], $params);
                 $params[$m[2]] = $val;
                 break;
             case 'setGlobal':
                 $templateSetGlobals[$m[2]] = $m[3];
                 break;
             case 'appendGlobal':
                 $val = $this->parseFormatVariablesAndFilters($m[3], $params);
                 if (!array_key_exists($m[2], $globals)) {
                     $templateSetGlobals[$m[2]] = $val;
                 } else {
                     $templateSetGlobals[$m[2]] = $globals[$m[2]];
                     $templateSetGlobals[$m[2]] .= $val;
                 }
                 break;
         }
     }
     //        $this->Logger->debug(__CLASS__,$params);
     $template->setLocals($params);
     $template->setTemplateSetGlobals($templateSetGlobals);
     if (!empty($params['CacheTime'])) {
         $template->setCacheTime($params['CacheTime']);
     }
     if ($template->getCacheTime() > 0 && (empty($params['NoCache']) || StringUtils::strToBool($params['NoCache']) == false)) {
         // if this module is not marked as NoCache
         $template->setCacheable(true);
     }
     if ($this->benchmarkRendering) {
         $this->Benchmark->end('load-template-extended-' . $template->getName());
     }
     return $template;
 }
 public function buildMySQLQuery(DatabaseInterface $db, $tableNodeRef, $table, $tableid, NodeQuery $nodeQuery, $orderObjects, $slugs, $ids = null)
 {
     $table = $db->quoteIdentifier($table);
     $element = $tableNodeRef->getElement();
     $schema = $element->getSchema();
     $q = new Query();
     $q->SELECT('DISTINCT ' . $table . '.' . $tableid . ' as ID', true);
     $q->SELECT($table . '.Slug');
     $mTableC = 1;
     if ($nodeQuery->hasParameter('OrderByInTag')) {
         $inParts = explode(' ', $nodeQuery->getParameter('OrderByInTag'), 2);
         $partials = PartialUtils::unserializeInPartials($inParts[0]);
         foreach ($partials as $partial) {
             if ($partial->getTagElement() && $partial->getTagSlug() && $partial->getTagRole()) {
                 $tTable = $db->quoteIdentifier($this->NodeDBMeta->getInTagsTable($tableNodeRef));
                 $tClause = $this->NodeTagsDAO->getOutTagPartialClause($partial, $db, $tTable);
                 $q->SELECT("OCondTable" . $mTableC . ".SortOrder as OSortOrder{$mTableC}");
                 $q->JOIN("INNER JOIN {$tTable} as OCondTable{$mTableC} " . str_replace($tTable, 'OCondTable' . $mTableC, " ON {$table}.{$tableid} = {$tTable}.{$tableid} AND {$tClause}"));
                 $direction = array_key_exists(1, $inParts) ? $inParts[1] : 'ASC';
                 $q->ORDERBY('OCondTable' . $mTableC . '.SortOrder ' . $direction);
                 $mTableC++;
             } else {
                 throw new NodeException('Invalid OrderByInTag parameter, must be fully qualified TagPartial with element:slug#role');
             }
         }
     }
     if ($nodeQuery->hasParameter('OrderByOutTag')) {
         $outParts = explode(' ', $nodeQuery->getParameter('OrderByOutTag'), 2);
         $partials = PartialUtils::unserializeOutPartials($outParts[0]);
         foreach ($partials as $partial) {
             if ($partial->getTagElement() && $partial->getTagSlug() && $partial->getTagRole()) {
                 $tTable = $db->quoteIdentifier($this->NodeDBMeta->getOutTagsTable($tableNodeRef));
                 $tClause = $this->NodeTagsDAO->getOutTagPartialClause($partial, $db, $tTable);
                 $q->SELECT("OCondTable" . $mTableC . ".SortOrder as OSortOrder{$mTableC}");
                 $q->JOIN("INNER JOIN {$tTable} as OCondTable{$mTableC} " . str_replace($tTable, 'OCondTable' . $mTableC, " ON {$table}.{$tableid} = {$tTable}.{$tableid} AND {$tClause}"));
                 $direction = array_key_exists(1, $outParts) ? $outParts[1] : 'ASC';
                 $q->ORDERBY('OCondTable' . $mTableC . '.SortOrder ' . $direction);
                 $mTableC++;
             } else {
                 throw new NodeException('Invalid OrderByOutTag parameter, must be fully qualified TagPartial with element:slug#role');
             }
         }
     }
     $mTableC = 1;
     foreach ($orderObjects as $orderObject) {
         $column = $orderObject->getColumn();
         $direction = $orderObject->getDirection();
         //if(!in_array($column, array('ID', 'Slug')))
         //{
         if ($orderObject->isMeta()) {
             $partial = $orderObject->getOrderByMetaPartial();
             $datatype = $orderObject->getOrderByMetaDataType();
             $mTable = $this->NodeDBMeta->getMetaTable($tableNodeRef, $datatype);
             $mTableAlias = $db->quoteIdentifier($mTable . $mTableC++);
             $mTable = $db->quoteIdentifier($mTable);
             $mClause = $this->NodeMetaDAO->getMetaPartialClause(new MetaPartial($partial), $datatype, $db, $mTableAlias);
             $q->SELECT($mTableAlias . '.' . $datatype . 'Value as ' . $column);
             $q->JOIN('LEFT JOIN ' . $mTable . ' as ' . $mTableAlias . ' ON ' . $table . '.' . $tableid . ' = ' . $mTableAlias . '.' . $tableid . ' AND ' . $mClause);
             $q->ORDERBY("{$column} {$direction}");
         } else {
             if ($orderObject->isDirectional()) {
                 if (!in_array($orderObject->getColumn(), array('Title', 'Slug', 'SortOrder', 'ActiveDate', 'CreationDate', 'ModifiedDate', 'TreeID'))) {
                     throw new NodeException('Invalid ordering column [' . $orderObject->getColumn() . '], must be Title, Slug, SortOrder, ActiveDate, CreationDate, ModifiedDate, TreeID, or #meta-id');
                 }
                 if ($orderObject->getColumn() != 'Slug') {
                     $q->SELECT($table . '.' . $orderObject->getColumn());
                 }
                 $q->ORDERBY("{$table}.{$column} {$direction}");
             }
         }
         //}
     }
     // Add if clause 2/1/2010 by Craig .. Mysql seems to be doing it's job without this secondary sort.
     if (empty($orderObjects)) {
         $q->ORDERBY('ID DESC');
     }
     $q->FROM($table);
     // ID
     if (!empty($ids)) {
         if (count($ids) > 1) {
             $q->WHERE("{$table}.{$tableid} IN (" . $db->joinQuote($ids) . ")");
         } else {
             if (isset($ids[0])) {
                 $q->WHERE("{$table}.{$tableid} = {$db->quote($ids[0])}");
             }
         }
     }
     // Slug
     if (!empty($slugs)) {
         if (count($slugs) > 1) {
             $q->WHERE("{$table}.Slug IN (" . $db->joinQuote($slugs) . ")");
         } else {
             if (isset($slugs[0])) {
                 $q->WHERE("{$table}.Slug = {$db->quote($slugs[0])}");
             }
         }
     }
     // AlphaIndex
     if (($alpha = $nodeQuery->getParameter('Title.firstChar')) != null) {
         if (strtolower($alpha) == '#') {
             $q->WHERE("(ASCII(LOWER(LEFT({$table}.Title, 1))) < 65) OR (ASCII(LOWER(LEFT({$table}.Title, 1))) BETWEEN 90 AND 97) OR (ASCII(LOWER(LEFT({$table}.Title, 1))) > 122)");
         } else {
             $q->WHERE("LOWER(LEFT({$table}.Title, 1)) = {$db->quote(strtolower($alpha))}");
         }
     }
     // Title
     $this->DTOHelper->buildEqualsFilter($db, $q, $nodeQuery, 'Title.ieq', "{$table}.Title");
     $this->DTOHelper->buildReplaceFilter($db, $q, $nodeQuery, 'Title.eq', "BINARY {$table}.Title = ?");
     // TitleSearch
     $this->DTOHelper->buildReplaceFilter($db, $q, $nodeQuery, 'Title.like', "{$table}.Title LIKE ?", '%#s%');
     // ParentTreeID
     $this->DTOHelper->buildReplaceFilter($db, $q, $nodeQuery, 'TreeID.childOf', "{$table}.TreeID LIKE ?", "#s%");
     // TreeID
     $this->DTOHelper->buildEqualsFilter($db, $q, $nodeQuery, 'TreeID.eq', "{$table}.TreeID");
     // select node by Tree depth (or limit existing selection)
     if (($treeDepth = $nodeQuery->getParameter('TreeID.depth')) !== null) {
         $actualDepth = $treeDepth * 4;
         $q->orWhere("LENGTH({$table}.TreeID) = {$db->quote($actualDepth)}");
     }
     if (($treeid = $nodeQuery->getParameter('TreeID.parentOf')) != null) {
         $depth = strlen($treeid) / 4;
         if ($depth == 1) {
             $q->WHERE('1 = 0');
         } else {
             for ($i = 1; $i < $depth; ++$i) {
                 $ptreeid = substr($treeid, 0, $i * 4);
                 $q->ORWHERE("{$table}.TreeID = {$db->quote($ptreeid)}");
             }
         }
     }
     // ActiveAfter
     // ActiveBefore
     $this->DTOHelper->buildDateReplaceFilter($db, $q, $nodeQuery, 'ActiveDate.after', "{$table}.ActiveDate > ?");
     $this->DTOHelper->buildDateReplaceFilter($db, $q, $nodeQuery, 'ActiveDate.before', "{$table}.ActiveDate <= ?");
     $this->DTOHelper->buildDateReplaceFilter($db, $q, $nodeQuery, 'ActiveDate.start', "{$table}.ActiveDate >= ?", 0, 0, 0);
     $this->DTOHelper->buildDateReplaceFilter($db, $q, $nodeQuery, 'ActiveDate.end', "{$table}.ActiveDate <= ?", 23, 59, 59);
     // CreatedAfter
     // CreatedBefore
     $this->DTOHelper->buildDateReplaceFilter($db, $q, $nodeQuery, 'CreationDate.after', "{$table}.CreationDate > ?");
     $this->DTOHelper->buildDateReplaceFilter($db, $q, $nodeQuery, 'CreationDate.before', "{$table}.CreationDate <= ?");
     $this->DTOHelper->buildDateReplaceFilter($db, $q, $nodeQuery, 'CreationDate.start', "{$table}.CreationDate >= ?", 0, 0, 0);
     $this->DTOHelper->buildDateReplaceFilter($db, $q, $nodeQuery, 'CreationDate.end', "{$table}.CreationDate <= ?", 23, 59, 59);
     // Status
     if (($status = $nodeQuery->getParameter('Status.eq')) != null) {
         switch ($status) {
             case 'published':
                 $q->WHERE("{$table}.Status = 'published'");
                 break;
             case 'draft':
                 $q->WHERE("{$table}.Status = 'draft'");
                 break;
             case 'deleted':
                 $q->WHERE("{$table}.Status = 'deleted'");
                 break;
             default:
                 $q->WHERE("{$table}.Status != 'deleted'");
                 break;
         }
     } else {
         if ($nodeQuery->getParameter('Status.isActive') !== null && StringUtils::strToBool($nodeQuery->getParameter('Status.isActive')) == true) {
             $now = $this->DateFactory->newStorageDate();
             $q->WHERE("{$table}.Status = 'published' AND {$table}.ActiveDate < {$db->quote($now)}");
         } else {
             if ($nodeQuery->getParameter('Status.all') == null || StringUtils::strToBool($nodeQuery->getParameter('Status.all')) == false) {
                 $q->WHERE("{$table}.Status != 'deleted'");
             }
         }
     }
     $metaParams = $this->NodesHelper->getMetaFilters($nodeQuery);
     $tablect = 0;
     foreach ($metaParams as $mArgs) {
         list($full, $name, $operator, $value) = $mArgs;
         $def = $schema->getMetaDef($name);
         $datatype = $def->Datatype;
         $mTable = $db->quoteIdentifier($this->NodeDBMeta->getMetaTable($tableNodeRef, $datatype));
         $clause = ' ' . $db->quoteIdentifier($mTable) . '.Name = ' . $db->quote($name) . " AND ";
         if ($datatype == 'flag') {
             throw new NodeException('Unable to run meta clause on flag datatype');
         }
         if (in_array($datatype, array('text', 'blob', 'mediumtext', 'mediumblob'))) {
             throw new NodeException('Query arguments with #' . $name . ' are not supported');
         }
         switch ($operator) {
             case 'eq':
                 if ($datatype == 'varchar') {
                     $clause .= " BINARY {$db->quoteIdentifier($mTable)}.{$datatype}Value = {$db->quote($value)}";
                 } else {
                     $clause .= " {$db->quoteIdentifier($mTable)}.{$datatype}Value = {$db->quote($value)}";
                 }
                 break;
             case 'ieq':
                 $clause .= " {$db->quoteIdentifier($mTable)}.{$datatype}Value = {$db->quote($value)}";
                 break;
             case 'like':
                 $clause .= " {$db->quoteIdentifier($mTable)}.{$datatype}Value LIKE " . $db->quote('%' . $value . '%');
                 break;
             case 'before':
                 $d = $this->DateFactory->newLocalDate($value);
                 $clause .= " {$db->quoteIdentifier($mTable)}.{$datatype}Value <= {$db->quote($d)}";
                 break;
             case 'after':
                 $d = $this->DateFactory->newLocalDate($value);
                 $clause .= " {$db->quoteIdentifier($mTable)}.{$datatype}Value > {$db->quote($d)}";
                 break;
             case 'start':
                 $d = $this->DateFactory->newLocalDate($value);
                 $d->setTime(0, 0, 0);
                 $clause .= " {$db->quoteIdentifier($mTable)}.{$datatype}Value >= {$db->quote($d)}";
                 break;
             case 'end':
                 $d = $this->DateFactory->newLocalDate($value);
                 $d->setTime(23, 59, 59);
                 $clause .= " {$db->quoteIdentifier($mTable)}.{$datatype}Value <= {$db->quote($d)}";
                 break;
             case 'notEq':
                 if ($datatype == 'varchar') {
                     $clause .= " BINARY {$db->quoteIdentifier($mTable)}.{$datatype}Value != {$db->quote($value)}";
                 } else {
                     $clause .= " {$db->quoteIdentifier($mTable)}.{$datatype}Value != {$db->quote($value)}";
                 }
                 break;
             case 'lessThan':
                 $clause .= " {$db->quoteIdentifier($mTable)}.{$datatype}Value < {$db->quote($value)}";
                 break;
             case 'lessThanEq':
                 $clause .= " {$db->quoteIdentifier($mTable)}.{$datatype}Value <= {$db->quote($value)}";
                 break;
             case 'greaterThan':
                 $clause .= " {$db->quoteIdentifier($mTable)}.{$datatype}Value > {$db->quote($value)}";
                 break;
             case 'greaterThanEq':
                 $clause .= " {$db->quoteIdentifier($mTable)}.{$datatype}Value >= {$db->quote($value)}";
                 break;
                 /*
                  * case insensitive comparison for #meta.in filtering.
                  */
             /*
              * case insensitive comparison for #meta.in filtering.
              */
             case 'in':
                 $inValues = explode(',', $value);
                 if (count($inValues) > 1) {
                     $clause .= " {$db->quoteIdentifier($mTable)}.{$datatype}Value IN ({$db->joinQuote($inValues)})";
                 } else {
                     if ($datatype == 'varchar') {
                         $clause .= " BINARY {$db->quoteIdentifier($mTable)}.{$datatype}Value = {$db->quote($value)}";
                     } else {
                         $clause .= " {$db->quoteIdentifier($mTable)}.{$datatype}Value = {$db->quote($value)}";
                     }
                 }
                 break;
         }
         $tablect++;
         $q->JOIN("INNER JOIN {$mTable} as CondTable{$tablect} " . str_replace($mTable, 'CondTable' . $tablect, " ON {$table}.{$tableid} = {$mTable}.{$tableid} AND {$clause}"));
     }
     // IncludesMeta
     //        if(($im = $nodeQuery->getParameter('Meta.exist')) != NULL ) {
     //            $metas       = PartialUtils::unserializeMetaPartials($im);
     //            $conditions = array();
     //            foreach($metas as $partial) {
     //                $s = $schema->getMetaDef($partial->getMetaName());
     //
     //                $datatype = $s->Datatype;
     //
     //                $mTable = $db->quoteIdentifier($this->NodeDBMeta->getMetaTable($tableNodeRef, $datatype));
     //                $mClause = $this->NodeMetaDAO->getMetaPartialClause($partial, $datatype, $db, $mTable);
     //
     //                $conditions[] = "{$table}.{$tableid} IN
     //                    (SELECT {$mTable}.{$tableid}
     //                    FROM {$mTable}
     //                    WHERE ".$mClause.")";
     ////                  $conditions[] = "EXISTS (SELECT 1 FROM {$this->model->getMetaTable()}
     ////                      WHERE {$this->model->getMetaTable()}.{$this->model->getTableID()} = {$table}.{$this->model->getTableID()}
     ////                      AND ".$partial->getTagClause($this->model->getMetaTable()).")";
     //            }
     //            if (!empty($conditions)) {
     //                $q->WHERE(join(' OR ', $conditions));
     //            }
     //
     //        }
     // IncludesAllMeta
     if (($iam = $nodeQuery->getParameter('Meta.exist')) != NULL) {
         $metas = PartialUtils::unserializeMetaPartials($iam);
         foreach ($metas as $partial) {
             $s = $schema->getMetaDef($partial->getMetaName());
             $datatype = $s->Datatype;
             $mTable = $db->quoteIdentifier($this->NodeDBMeta->getMetaTable($tableNodeRef, $datatype));
             $mClause = $this->NodeMetaDAO->getMetaPartialClause($partial, $datatype, $db, $mTable);
             $tablect++;
             $q->JOIN("INNER JOIN {$mTable} as CondTable{$tablect} " . str_replace($mTable, 'CondTable' . $tablect, " ON {$table}.{$tableid} = {$mTable}.{$tableid} AND {$mClause}"));
             //                $q->WHERE("{$table}.{$tableid} IN
             //                    (SELECT {$mTable}.{$tableid}
             //                    FROM {$mTable}
             //                    WHERE ".$mClause.")");
             //                  $this->db->WHERE("EXISTS (SELECT 1 FROM {$this->model->getMetaTable()}
             //                      WHERE {$this->model->getMetaTable()}.{$this->model->getTableID()} = {$table}.{$this->model->getTableID()}
             //                      AND ".$partial->getTagClause($this->model->getMetaTable()).")");
         }
     }
     // IncludesOutTags
     //        if(($iot = $nodeQuery->getParameter('IncludesOutTags')) != NULL ) {
     //            $tags       = PartialUtils::unserializeOutPartials($iot);
     //            $conditions = array();
     //            foreach($tags as $partial) {
     //                $tTable = $db->quoteIdentifier($this->NodeDBMeta->getOutTagsTable($tableNodeRef));
     //
     //                // TODO: need to support aspects
     //                // TODO: convert OR clauses into multiple unions
     //
     //                $tClause = $this->NodeTagsDAO->getOutTagPartialClause($partial, $tableNodeRef->getSite(), $db, $tTable);
     //
     //                $conditions[] = "{$table}.{$tableid} IN
     //                    (SELECT {$tTable}.{$tableid}
     //                    FROM {$tTable}
     //                    WHERE {$tClause})";
     ////                  $conditions[] = "EXISTS (SELECT 1 FROM {$this->model->getTagsTable()} t2
     ////                      INNER JOIN tags2 ON t2.tagid = tags2.tagid
     ////                      WHERE {$table}.{$this->model->getTableID()} = t2.{$this->model->getTableID()} AND
     ////                      ".$partial->getTagClause("tags2").")";
     //            }
     //            if (!empty($conditions)) {
     //                $q->WHERE(join(' OR ', $conditions));
     //            }
     //
     //        }
     // IncludesAllOutTags
     if (($iaot = $nodeQuery->getParameter('OutTags.exist')) != NULL) {
         $tags = PartialUtils::unserializeOutPartials($iaot);
         foreach ($tags as $partial) {
             $tTable = $db->quoteIdentifier($this->NodeDBMeta->getOutTagsTable($tableNodeRef));
             $tClause = $this->NodeTagsDAO->getOutTagPartialClause($partial, $db, $tTable);
             $tablect++;
             $q->JOIN("INNER JOIN {$tTable} as CondTable{$tablect} " . str_replace($tTable, 'CondTable' . $tablect, " ON {$table}.{$tableid} = {$tTable}.{$tableid} AND {$tClause}"));
             //                $q->WHERE( "{$table}.{$tableid} IN
             //                    (SELECT {$tTable}.{$tableid}
             //                    FROM {$tTable}
             //                    WHERE {$tClause})" );
             //                  $this->db->WHERE("EXISTS (SELECT 1 FROM {$this->model->getTagsTable()} t2
             //                      INNER JOIN tags2 ON t2.tagid = tags2.tagid
             //                      WHERE {$table}.{$this->model->getTableID()} = t2.{$this->model->getTableID()} AND
             //                      ".$partial->getTagClause("tags2").")");
         }
     }
     // IncludesInTags
     //        if(($iit = $nodeQuery->getParameter('IncludesInTags')) != NULL ) {
     //            $tags       = PartialUtils::unserializeInPartials($iit);
     //            $conditions = array();
     //            foreach($tags as $partial) {
     //                $tTable = $db->quoteIdentifier($this->NodeDBMeta->getInTagsTable($tableNodeRef));
     //                $tClause = $this->NodeTagsDAO->getInTagPartialClause($partial, $tableNodeRef->getElement(), $tableNodeRef->getSite(), $db, $tTable);
     //
     //                $conditions[] = "{$table}.{$tableid} IN
     //                    (SELECT {$tTable}.{$tableid}
     //                    FROM {$tTable}
     //                    WHERE {$tClause})";
     ////                  $conditions[] = "EXISTS (SELECT 1 FROM {$this->model->getTagsTable()} t2
     ////                      INNER JOIN tags2 ON t2.tagid = tags2.tagid
     ////                      WHERE {$table}.{$this->model->getTableID()} = t2.{$this->model->getTableID()} AND
     ////                      ".$partial->getTagClause("tags2").")";
     //            }
     //            if (!empty($conditions)) {
     //                $q->WHERE(join(' OR ', $conditions));
     //            }
     //
     //        }
     // IncludesAllInTags
     if (($iait = $nodeQuery->getParameter('InTags.exist')) != NULL) {
         $tags = PartialUtils::unserializeInPartials($iait);
         foreach ($tags as $partial) {
             $tTable = $db->quoteIdentifier($this->NodeDBMeta->getInTagsTable($tableNodeRef));
             $tClause = $this->NodeTagsDAO->getInTagPartialClause($partial, $tableNodeRef->getElement(), $db, $tTable);
             $tablect++;
             $q->JOIN("INNER JOIN {$tTable} as CondTable{$tablect} " . str_replace($tTable, 'CondTable' . $tablect, " ON {$table}.{$tableid} = {$tTable}.{$tableid} AND {$tClause}"));
             //
             //                $q->WHERE( "{$table}.{$tableid} IN
             //                    (SELECT {$tTable}.{$tableid}
             //                    FROM {$tTable}
             //                    WHERE {$tClause})" );
             //                  $this->db->WHERE("EXISTS (SELECT 1 FROM {$this->model->getTagsTable()} t2
             //                      INNER JOIN tags2 ON t2.tagid = tags2.tagid
             //                      WHERE {$table}.{$this->model->getTableID()} = t2.{$this->model->getTableID()} AND
             //                      ".$partial->getTagClause("tags2").")");
         }
     }
     return $q;
 }
 /**
  * Fetches a specific media node.
  *
  * @param ElementSlug  _required_  e.g. image
  * @param NodeSlug  _required_  the Slug of the node to retrieve
  * @param Thumbnails _optional_  comma delimited list of thumbnail sizes to return e.g. "150,100x100" or "all"
  * @param Meta.select  _optional_  list of Meta fields to return as per NodeApiController
  * @param OutTags.select  _optional_  list of OutTags to retrieve as per NodeApiController
  * @param Depth _optional_ whether to include original/thumbnail tags (TBD)
  */
 public function get()
 {
     $noderef = $this->getNodeRef();
     $hasJsonThumbnails = $noderef->getElement()->hasAspect('mixin-json-thumbnails');
     $nodePartials = new NodePartials($this->Request->getParameter('Meta_select'), $this->Request->getParameter('OutTags_select'), $this->Request->getParameter('InTags_select'));
     $nodePartials->increaseOutPartials('#original.fields');
     if ($hasJsonThumbnails && StringUtils::strToBool($this->Request->getParameter('retrieveThumbnails'))) {
         $nodePartials->increaseMetaPartials('#thumbnails-json');
     }
     $node = $this->RegulatedNodeService->getByNodeRef($noderef, $nodePartials);
     $c = $this->_buildNodeJSON($node, true, StringUtils::strToBool($this->Request->getParameter('retrieveThumbnails')));
     //todo: include metas
     //todo: include tags
     $this->sendJSON($c);
 }
 protected function _buildWidgetOptions($schemafield, $attributes)
 {
     $partial = $schemafield->Partial;
     $filter = $schemafield->Filter;
     $is_multiple = $schemafield->isMultiple();
     $is_quickadd = $schemafield->isQuickadd();
     $is_sortable = $schemafield->isSortable();
     $tag_direction = $schemafield->Direction;
     if (empty($tag_direction)) {
         $tag_direction = 'out';
     }
     if (!empty($attributes['title'])) {
         $title = $attributes['title'];
     } else {
         $title = $schemafield->Title;
     }
     $value_opts = $schemafield->ValueOptions;
     $value_is_multiple = false;
     $pre_values = array();
     $values_name = 'role';
     if (!empty($value_opts)) {
         $value_mode = $value_opts->Mode;
         $values_name = $value_opts->Name;
         $value_is_multiple = $value_opts->isMultiple();
         if ($value_mode != 'none') {
             $pre_values = $value_opts->Values;
         }
     } else {
         $value_mode = 'none';
     }
     $title = StringUtils::jsEscape($title);
     $title_plural = $title;
     //StringUtils::pluralize($title);
     $opt[] = "\t\t\tLabel: '{$title}'";
     $opt[] = "\t\t\tLabelPlural: '{$title_plural}'";
     $opt[] = "\t\t\tActivateButtonLabel: '{$title}'";
     $element = $partial->getTagElement();
     if (empty($element)) {
         $element = '@' . $partial->getTagAspect();
     }
     $quickaddelement = $element;
     if (!empty($attributes['quick-add-element'])) {
         $quickaddelement = $attributes['quick-add-element'];
     }
     $quickaddaction = 'node-quick-add';
     if (!empty($attributes['quick-add-action'])) {
         $quickaddaction = $attributes['quick-add-action'];
     }
     if (!empty($attributes['search-parameters'])) {
         $str = array();
         $params = explode('&', urldecode($attributes['search-parameters']));
         foreach ($params as $param) {
             list($k, $v) = explode('=', $param, 2);
             $str[] = "'" . $k . "' : '" . $v . "'";
         }
         $opt[] = "\t\t\tSearchParameters: {" . implode(',', $str) . "}";
     } else {
         $opt[] = "\t\t\tSearchParameters: {'Elements.in' : '{$element}'}";
         //Title keyword is auto-added by widget
     }
     if (!empty($attributes['search-url'])) {
         $opt[] = "\t\t\tSearchURL: '{$attributes['search-url']}'";
     }
     if (!empty($attributes['show-element'])) {
         $opt[] = "\t\t\tShowElementInChosenList: true";
         $opt[] = "\t\t\tShowElementInSearchResults: true";
     }
     if ($tag_direction != 'out') {
         $opt[] = "\t\tTagDirection: '{$tag_direction}'";
     }
     if (!empty($filter)) {
         $opt[] = "\t\tTagFilter: '" . $filter . "'";
     }
     if ($is_quickadd) {
         $opt[] = "\t\t\tAllowQuickAdd: true";
         $opt[] = "\t\t\tQuickAddNonce: '{% filter nonce?action={$quickaddaction} %}'";
         $opt[] = "\t\t\tAddTagNonce: '{% filter nonce?action=node-add-tag %}'";
         $opt[] = "\t\t\tReplaceNonce: '{% filter nonce?action=node-replace %}'";
         $opt[] = "\t\t\tQuickAddElement : '{$quickaddelement}'";
         $opt[] = "\t\t\tEditNonce: '{% filter nonce?action=node-edit %}'";
     }
     if ($is_multiple) {
         $opt[] = "\t\t\tAllowMultiple: " . ($is_multiple ? 'true' : 'false') . "";
     }
     if ($is_sortable) {
         $opt[] = "\t\t\tAllowReorderChosenList: " . ($is_sortable ? 'true' : 'false') . "";
     }
     if ($value_mode != 'none') {
         $opt[] = "\t\tValueMode: '{$value_mode}'";
         $opt[] = "\t\tAllowMultipleValues: " . ($value_is_multiple ? 'true' : 'false') . "";
         if (!empty($pre_values)) {
             foreach ((array) $pre_values as $dname => $dvalue) {
                 $array[] = array('value' => $dname, 'display' => $dvalue);
             }
             $opt[] = "\t\tValues: " . json_encode($array) . "";
         }
         if (count($pre_values) == 1) {
             $opt[] = "\t\tShowExistingValues: false";
         } else {
             if ($value_mode == 'typein') {
                 $opt[] = "\t\tShowExistingValues: true";
             }
         }
     }
     if (!empty($attributes['hide-tag-values'])) {
         $opt[] = "\t\t\tHideTagValues: true";
     }
     if (!empty($attributes['tag-prepend'])) {
         if (StringUtils::strToBool($attributes['tag-prepend'])) {
             $opt[] = "\t\t\tTagPrepend: true";
         } else {
             $opt[] = "\t\t\tTagPrepend: false";
         }
     }
     return $opt;
 }
 public function xmlToCMSNavItem(ModelObject $CMSNavItem, SimpleXMLExtended $xml)
 {
     if (($id = $xml->attribute('id')) !== null) {
         $CMSNavItem->CMSNavItemID = intval($id);
     }
     if (($id = $xml->attribute('slug')) !== null) {
         $CMSNavItem->Slug = strval($id);
     }
     if (($id = $xml->attribute('pluginid')) !== null) {
         $CMSNavItem->PluginID = strval($id);
     }
     if (($id = $xml->attribute('uri')) !== null) {
         $CMSNavItem->URI = strval($id);
     }
     if (($id = $xml->attribute('create_add_menu')) !== null) {
         $CMSNavItem->DoAddLinksFor = strval($id);
     }
     if (($id = $xml->attribute('enabled')) !== null) {
         $CMSNavItem->Enabled = StringUtils::strToBool($id);
     } else {
         $CMSNavItem->Enabled = true;
     }
     foreach (array('label', 'sort_order', 'permissions', 'parent_slug') as $key) {
         $camel = StringUtils::camelize($key);
         $CMSNavItem->{$camel} = trim($xml->attribute($key));
     }
     if ($CMSNavItem->Slug == '') {
         $CMSNavItem->Slug = SlugUtils::createSlug($CMSNavItem->Label);
     }
     if (empty($CMSNavItem->SortOrder)) {
         $CMSNavItem->SortOrder = PHP_INT_MAX;
     }
     $children = array();
     foreach ($xml as $childNode) {
         if ($childNode->getName() == 'item') {
             $child = $this->xmlToCMSNavItem(new CMSNavItem(), $childNode);
             $child->ParentSlug = $CMSNavItem->Slug;
             $children[] = $child;
             $sort_array[] = $child->SortOrder;
             $sort_array2[] = $child->Slug;
         }
     }
     if (!empty($children)) {
         array_multisort($sort_array, SORT_ASC, $sort_array2, SORT_ASC, $children);
     }
     $CMSNavItem->Children = $children;
     //        if($xml->creation_date)
     //            $CMSNavItem->CreationDate = $this->DateFactory->newStorageDate(strval($xml->creation_date));
     //        if($xml->modified_date)
     //            $CMSNavItem->ModifiedDate = $this->DateFactory->newStorageDate(strval($xml->modified_date));
     return $CMSNavItem;
 }
Exemple #26
0
 public function setErrorMultiline($multiline = false)
 {
     $this->multiline = StringUtils::strToBool($multiline);
 }
 /**
  * Returns a cacheKey for the specified Template
  *
  * @param Template $template The template to generate the cacheKey for
  * @param array    $globals  An array of globals set on this template
  *
  * @return string The cache key
  */
 public function getTemplateCacheKey(Template $template, $globals)
 {
     $locals = $template->getLocals();
     $cachekey = '';
     if ($template->isTopTemplate()) {
         $cachekey .= $this->Request->getAdjustedRequestURI();
     } else {
         $cachekey .= $template->getContentType() . $template->getName();
     }
     $cacheParams = array();
     // any locals that aren't globals
     foreach ($locals as $name => $value) {
         if (!is_array($value) && !array_key_exists($name, $globals) && !preg_match("/^[A-Z\\-\\_0-9]+\$/", $name) && !preg_match("/\\-\\d+\$/", $name)) {
             $cacheParams[$name] = $value;
         }
     }
     if (isset($cacheParams['UseQueryStringInCacheKey']) && StringUtils::strToBool($cacheParams['UseQueryStringInCacheKey']) == true) {
         foreach ($_GET as $name => $value) {
             if (!is_array($value)) {
                 $cacheParams['q_' . $name] = $value;
             }
         }
     }
     $cachekey .= '?';
     if (!empty($cacheParams)) {
         ksort($cacheParams);
         foreach ($cacheParams as $n => $v) {
             $cachekey .= $n . '=' . substr($v, 0, 255) . '&';
         }
     }
     $cachekey = rtrim($cachekey, '&');
     $this->Logger->debug('Cache Key [' . $cachekey . ']');
     return $cachekey;
 }
 public function addInTag(NodeRef $nodeRef, Tag $tag)
 {
     $this->NodeEvents->fireNodeEvents(__FUNCTION__, '', $nodeRef, $tag);
     $tagId = $tag->getTagRole();
     $schema = $nodeRef->getElement()->getSchema();
     $tagDef = $schema->getTagDef($tagId);
     $tag = TagUtils::filterTagAgainstDef($tag, $tagDef);
     // retrieve the DB connection and table from DataSourceManager
     $db = $this->getConnectionForWrite($nodeRef);
     // Make sure the node we're adding to exists
     $id = $this->getRecordIDFromNodeRef($nodeRef);
     // If the role being tagged to does not allow multiple tags, we need to get the node and ensure that
     // a tag isn't already tagged to it. If there is a tag already, the NodeValidator will throw a ValidationException.
     if (!StringUtils::strToBool($tagDef->Multiple)) {
         $existingNode = $this->NodeLookupDAO->getByNodeRef($nodeRef, new NodePartials('', '', '#' . $tagId));
         $existingNode->addInTag($tag);
         $this->NodeValidator->validateFor('edit', $existingNode)->throwOnError();
     }
     $matchPartial = $tag->getMatchPartial();
     $matchPartial->TagSlug = $tag->getTagSlug();
     // save the tags
     $this->NodeTagsDAO->saveInTags($db, $nodeRef, $id, $matchPartial->toString(), array($tag));
 }
 protected function deriveMetaDatatype(ValidationExpression $ve)
 {
     $v = $ve->getValidationArray();
     $datatype = $v['datatype'];
     switch ($datatype) {
         case 'flag':
             return 'flag';
         case 'boolean':
             return 'tiny';
         case 'date':
             if (isset($v['unix']) && !StringUtils::strToBool($v['unix'])) {
                 return 'datetime';
             }
             // If unix attribute is not specified, assume they want date (timestamp) for backward-compatibility
             return 'date';
         case 'int':
             $min = isset($v['min']) ? (int) $v['min'] : 0;
             $max = isset($v['max']) ? (int) $v['max'] : PHP_INT_MAX;
             if ($min < 0) {
                 if ($min >= -128 && $max <= 127) {
                     return 'tiny-signed';
                 } else {
                     if ($min >= -2147483648 && $max <= 2147483647) {
                         return 'int-signed';
                     }
                 }
                 return 'long-signed';
             }
             if ($max < 255) {
                 return 'tiny';
             } else {
                 if ($max <= 4294967295) {
                     return 'int';
                 }
             }
             return 'long';
         case 'float':
             return 'float';
         case 'slug':
         case 'slugwithslash':
         case 'email':
             $ve->setMax(255);
             // set max
             return 'varchar';
         case 'json':
             $ve->setMax(262144);
             //set max to 256K
             return 'mediumtext';
         case 'string':
         case 'html':
         case 'url':
             // NOTE: MySQL columns are bytes, string lengths are characters
             $max = 255;
             // default is 255
             if (isset($v['max'])) {
                 $max = (int) FileSystemUtils::iniValueInBytes($v['max']);
             }
             if ($max == 65536) {
                 $max = 65535;
             }
             if ($max > 262144) {
                 // max is 256K
                 $max = 262144;
             }
             $ve->setMax($max);
             // set max
             if ($max <= 255) {
                 // 255 or less is VARCHAR
                 return 'varchar';
             }
             if ($max <= 65535) {
                 // 64K or less is TEXT
                 return 'text';
             }
             if ($max <= 262144) {
                 // 256K or less is MEDIUMTEXT
                 return 'mediumtext';
             }
         case 'binary':
             $max = 262144;
             // default is 256K
             if (isset($v['max'])) {
                 $max = (int) FileSystemUtils::iniValueInBytes($v['max']);
             }
             if ($max == 65536) {
                 $max = 65535;
             }
             if ($max > 262144) {
                 // max is 256K
                 $max = 262144;
             }
             $ve->setMax($max);
             // set max
             if ($max <= 65535) {
                 // 64K or less, store as BLOB
                 return 'blob';
             }
             if ($max <= 262144) {
                 // 256K or less, store as MEDIUMBLOB
                 return 'mediumblob';
             }
     }
 }
 /**
  * Gets the current PDO connection object
  *
  * @return PDO MySQL PDO Connection
  */
 public function getConnection()
 {
     if (empty($this->connection)) {
         if (empty($this->connectionConfig) || !is_array($this->connectionConfig)) {
             throw new DatabaseException("Connection config is empty or not an array.");
         }
         $connCount = count($this->connectionConfig);
         for ($i = 0; $i < $connCount; ++$i) {
             $connectionInfo = $this->connectionConfig[$i];
             if (empty($connectionInfo['port'])) {
                 $connectionInfo['port'] = 3306;
             }
             $dsn = "mysql:dbname={$connectionInfo['database']};host={$connectionInfo['host']};port={$connectionInfo['port']}";
             if (!empty($connectionInfo['unix_socket'])) {
                 $dsn .= ';unix_socket=' . $connectionInfo['unix_socket'];
             }
             try {
                 $trx_attempt = 0;
                 while ($trx_attempt < $this->deadlockRetries) {
                     try {
                         $this->connection = new PDO($dsn, $connectionInfo['username'], $connectionInfo['password'], array(PDO::ATTR_PERSISTENT => !empty($connectionInfo['persistent']) ? StringUtils::strToBool($connectionInfo['persistent']) : false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_CASE => PDO::CASE_NATURAL, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true, PDO::MYSQL_ATTR_DIRECT_QUERY => true, PDO::ATTR_TIMEOUT => !empty($connectionInfo['timeout']) ? $connectionInfo['timeout'] : 30));
                         $this->connDebugString = $connectionInfo['host'] . ':' . $connectionInfo['database'];
                         $this->currentDBName = $connectionInfo['database'];
                         $this->Logger->debug(array('SQL' => 'CONNECTION - DB: ' . $this->connDebugString));
                         return $this->connection;
                     } catch (PDOException $pe) {
                         if (strpos($pe->getMessage(), 'Too many connections') !== FALSE && ++$trx_attempt < $this->deadlockRetries) {
                             usleep(pow(2, $trx_attempt) * 100000);
                             continue;
                         }
                         throw $pe;
                     }
                 }
             } catch (PDOException $pe) {
                 // if the last connection fails
                 if ($i == $connCount - 1) {
                     throw new SQLConnectionException($pe->getMessage());
                 }
             }
         }
     }
     return $this->connection;
 }