Пример #1
0
 /**
  * Builds the Meta object
  *
  * @param mixed  $metaOrName Can be a string or an array or a Meta object that will be used to define this object.
  *                            If a string, then it's assumed to be the Name for the meta.
  *                            If an array, the keys expected should match the {@link $fields}
  *                            If a Meta object, then it will be cloned.
  * @param string $value      (optional) The value for this meta
  * @param string $sectionID  (optional) The section ID for this meta
  */
 public function __construct($metaOrName, $value = '')
 {
     if ($metaOrName instanceof Meta) {
         $this->fields = $metaOrName->toArray();
     } else {
         if (is_array($metaOrName)) {
             foreach ($metaOrName as $key => $val) {
                 $this->fields[$key] = $val;
                 unset($key);
                 unset($val);
             }
         } else {
             if (is_string($metaOrName)) {
                 // assume first param is element
                 if (strpos($metaOrName, '=') === false || !empty($value)) {
                     $this->fields['MetaName'] = $metaOrName;
                     $this->fields['MetaValue'] = $value;
                 } else {
                     throw new MetaException('Creating meta using strings is deprecated, please use array or parameters');
                 }
             }
         }
     }
     if (isset($this->fields['NoValidation'])) {
         return;
     }
     if (empty($this->fields['MetaName'])) {
         throw new MetaException('Invalid meta: No MetaName was specified');
     }
     $this->fields['MetaName'] = strtolower($this->fields['MetaName']);
     if (!SlugUtils::isSlug($this->fields['MetaName'])) {
         throw new MetaException('Invalid meta: "' . $this->fields['MetaName'] . '" must be valid slug');
     }
 }
Пример #2
0
 public function getTitle()
 {
     $name = (string) $this->getRequiredParameter('name');
     if (!$this->nameExists()) {
         return SlugUtils::unsluggify($name);
     }
     $image = $this->_imageNames[$name];
     if (!array_key_exists('Title', $image)) {
         return SlugUtils::unsluggify($name);
     }
     return $image['Title'];
 }
 public function storeMedia($originalFilePath, Node $mediaNode, $desiredFilename = null, StorageFacilityFile $preconfiguredFile = null)
 {
     //CREATE DATE STAMP DIRECTORY PREFIX
     $dateStamp = '/';
     if ($this->mediaOrganizeByDate) {
         $dateStamp = $this->getDateStamp($mediaNode);
     }
     if (is_null($desiredFilename)) {
         $uploadName = basename($originalFilePath);
         $path = pathinfo($uploadName);
         $ext = !empty($path['extension']) ? strtolower($path['extension']) : $this->getDefaultExtension();
         $path['filename'] = substr($path['filename'], 0, 128);
         $mediaNode->Title = str_replace('.' . $ext, '', $mediaNode->Title);
         $desiredFileWithoutExtension = SlugUtils::createSlug($mediaNode->Title, $this->mediaAllowCustomSubdirectories);
         $desiredFilename = $desiredFileWithoutExtension . '.' . $ext;
         //ENSURE FILENAME IS 128 OR LESS
         $len = strlen($desiredFilename) + ($this->mediaOrganizeByDate ? 11 : 0) + 1;
         if ($len > 128) {
             $desiredFilename = substr($desiredFileWithoutExtension, 0, 128 - (strlen('.' . $ext) + ($this->mediaOrganizeByDate ? 11 : 0) + 1)) . '.' . $ext;
         }
     } else {
         $path = pathinfo($desiredFilename);
         if (!empty($path['extension'])) {
             $ext = strtolower($path['extension']);
             $desiredFileWithoutExtension = substr($desiredFilename, 0, strripos($desiredFilename, '.' . $ext));
         } else {
             $ext = $this->getDefaultExtension();
             $desiredFileWithoutExtension = $desiredFilename;
             $desiredFilename .= '.' . $ext;
         }
     }
     if (empty($path['extension'])) {
         $oldOriginalFilePath = $originalFilePath;
         $originalFilePath = dirname($originalFilePath) . '/' . $desiredFileWithoutExtension . '.' . $ext;
         if (!@rename($oldOriginalFilePath, $originalFilePath)) {
             throw new Exception('Cannot rename file [' . $oldOriginalFilePath . '] to [' . $originalFilePath . ']');
         }
     }
     if (in_array(strtolower($ext), array_map("strtolower", $this->mediaRestrictedExtensions))) {
         throw new Exception('Cannot add media with restricted extension [' . $ext . ']');
     }
     $desiredFilename = $dateStamp . $desiredFilename;
     $desiredFileWithoutExtension = $dateStamp . $desiredFileWithoutExtension;
     $this->processSpecificMedia($mediaNode, $originalFilePath, $desiredFilename, $desiredFileWithoutExtension, $preconfiguredFile);
     return $mediaNode;
 }
Пример #4
0
 /**
  * Builds the MetaPartial object
  *
  * @param mixed  $metaOrName Can be a string or an array or a Meta/MetaPartial object that will be used to define this object.
  *                            If a string, then it's assumed to be the Name for the meta.
  *                            If an array, the keys expected should match the {@link $fields}
  *                            If a Meta or MetaPartial object, then it will be used to build the MetaPartial
  * @param string $value      (optional) The value for this meta
  * @param string $sectionID  (optional) The section ID for this meta
  */
 public function __construct($metaOrName, $value = '')
 {
     $this->fields = array('MetaName' => '');
     if ($metaOrName instanceof MetaPartial || $metaOrName instanceof Meta) {
         $this->fields = $metaOrName->toArray();
     } else {
         if (is_array($metaOrName)) {
             $this->fields = array_merge($this->fields, $metaOrName);
         } else {
             if (is_string($metaOrName)) {
                 if (strpos($metaOrName, '#') === false) {
                     // assume first param is element
                     $this->fields['MetaName'] = $metaOrName;
                     if ($value != '') {
                         $this->fields['MetaValue'] = $value;
                     }
                 } else {
                     // assume first param is tag string
                     if (preg_match("/(meta)?#([a-z0-9-]+)?(=((\")?([^\"]*)(\")?))?\$/", $metaOrName, $valuematch)) {
                         $this->fields['MetaName'] = $valuematch[2];
                         if (isset($valuematch[6])) {
                             $this->fields['MetaValue'] = $valuematch[6];
                         }
                     }
                 }
             }
         }
     }
     if (empty($this->fields['MetaName'])) {
         throw new MetaException('Invalid MetaPartial: No name was specified');
     }
     $this->fields['MetaName'] = strtolower($this->fields['MetaName']);
     if (!SlugUtils::isSlug($this->fields['MetaName'])) {
         throw new MetaException('Invalid MetaPartial: "' . $this->fields['MetaName'] . '" must be valid slug');
     }
     if (!empty($this->fields['MetaValue'])) {
         $this->fields['MetaValue'] = preg_replace("/\\s+/s", ' ', $this->fields['MetaValue']);
     }
 }
Пример #5
0
 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;
 }
 /**
  * Returns TRUE if the given value passes validation.
  *
  * @param string $value A value to test
  *
  * @return boolean
  */
 public function isValid($value)
 {
     if ($this->skipValidation) {
         return true;
     }
     $datatype = $this->validation['datatype'];
     //NULL check, empty strings are considered null
     if (in_array($datatype, array('string', 'url', 'email', 'slug', 'slugwithslash', 'html', 'binary', 'json')) && strlen(trim($value)) == 0) {
         $value = null;
     }
     if ($this->validation['nullable'] === false && $value === null && $datatype != 'boolean') {
         $this->failureCode = 'nullable';
         $this->failureMessage = 'cannot be empty';
         return false;
     }
     //Nothing more to validate if the value is null...
     if ($value === null) {
         return true;
     }
     //Check date makes sense
     if ($datatype === 'date') {
         //todo: not sure how to check validity of date... it's already a DateTime instance.
         if (false) {
             $this->failureCode = 'invalid';
             $this->failureMessage = 'is an invalid date';
             return false;
         }
     }
     //Validate MIN
     $min = $this->validation['min'];
     if ($min != null) {
         if ($datatype === 'float') {
             if ($value < floatval($min)) {
                 $this->failureCode = 'min';
                 $this->failureMessage = 'is less than the minimum value';
                 return false;
             }
         } else {
             if ($datatype === 'int') {
                 if ($value < intval($min)) {
                     $this->failureCode = 'min';
                     $this->failureMessage = 'is less than the minimum value';
                     return false;
                 }
             } else {
                 if (is_string($value) && strlen($value) < intval($min)) {
                     $this->failureCode = 'minlength';
                     $this->failureMessage = 'must be at least ' . $min . ' characters';
                     return false;
                 }
             }
         }
     }
     //Validate MAX
     $max = $this->validation['max'];
     if ($max != null) {
         if ($datatype === 'float') {
             if ($value > floatval($max)) {
                 $this->failureCode = 'max';
                 $this->failureMessage = 'is more than the maximum value';
                 return false;
             }
         } else {
             if ($datatype === 'int') {
                 if ($value > intval($max)) {
                     $this->failureCode = 'max';
                     $this->failureMessage = 'is more than the maximum value';
                     return false;
                 }
             } else {
                 $maxbytes = intval($max);
                 if (intval($max) < 255) {
                     // count characters
                     if (is_string($value) && StringUtils::charCount($value) > intval($max)) {
                         $this->failureCode = 'maxlength';
                         $this->failureMessage = 'must be a maximum of ' . $max . ' characters';
                         return false;
                     }
                     $maxbytes = 255;
                 }
                 // count bytes
                 if (is_string($value) && StringUtils::byteCount($value) > intval($maxbytes)) {
                     $this->failureCode = 'maxlength';
                     $this->failureMessage = 'must be a maximum of ' . $maxbytes . ' bytes';
                     return false;
                 }
             }
         }
     }
     if ($datatype === 'slug') {
         if (!SlugUtils::isSlug($value, false)) {
             $this->failureCode = 'invalid';
             $this->failureMessage = 'is not a valid slug, cannot contain slashes';
             return false;
         }
     }
     if ($datatype === 'slugwithslash') {
         if (!SlugUtils::isSlug($value, true)) {
             $this->failureCode = 'invalid';
             $this->failureMessage = 'is not a valid slug';
             return false;
         }
     }
     if ($datatype === 'url') {
         if (!URLUtils::isUrl($value)) {
             $this->failureCode = 'invalid';
             $this->failureMessage = 'is not a valid URL';
             return false;
         }
     }
     if ($datatype === 'email') {
         if (!EmailUtils::isEmailAddress($value)) {
             $this->failureCode = 'invalid';
             $this->failureMessage = 'is not a valid email address';
             return false;
         }
     }
     if ($datatype === 'json') {
         if (!JSONUtils::isValid($value)) {
             $this->failureCode = 'invalid';
             $this->failureMessage = 'is not a valid json string';
             return false;
         }
     }
     //Validate MATCH expression
     $match = $this->validation['match'];
     if ($match != null) {
         // Automatically escape unescaped slashes in the match before running it
         $match = preg_replace('/([^\\\\])\\//', '$1\\/', $match);
         if (preg_match('/' . $match . '/s', $value) === 0) {
             $this->failureCode = 'invalid';
             //$this->failureMessage = 'is invalid (' . substr($value, 0, 255) . ')';
             $this->failureMessage = 'is invalid';
             return false;
         }
     }
     // Validate all custom functions
     foreach ($this->validation['callback'] as $callback) {
         if (!empty($callback) && call_user_func($callback, $value) === false) {
             $this->failureCode = $callback;
             $this->failureMessage = 'is invalid';
             return false;
         }
     }
     return true;
 }
Пример #7
0
 /**
  * Creates a slug from the camel case text given. Adds space in between words starting with capital letters and acronyms.
  *
  * @param string  $string       A bit of camel case text that we will generate our slug from.
  * @param boolean $allowSlashes If set to false, any slashes will be removed from the slug.
  *                                 Default: false
  *
  * @return string Our sluggified version of the {@link $string} param
  **/
 public static function createSlugFromCamelCase($string, $allowSlashes = false)
 {
     $string = trim(preg_replace('/(([A-Z]|[0-9])[^A-Z])/', ' $1', $string));
     return SlugUtils::createSlug($string, $allowSlashes);
 }
Пример #8
0
 public function generateNodeRef(NodeRef $nodeRef, $title = null, $useTime = false)
 {
     if (is_null($nodeRef)) {
         throw new NodeException('Cannot generate NodeRef, $nodeRef is null');
     }
     $slug = $nodeRef->getSlug();
     if (empty($slug)) {
         if (empty($title)) {
             throw new NodeException('Cannot generate NodeRef without title');
         }
         if ($useTime) {
             $slug = SlugUtils::createSlug(substr($title, 0, 237) . '-' . floor(microtime(true) * 100), $nodeRef->getElement()->isAllowSlugSlashes());
         } else {
             $slug = SlugUtils::createSlug(substr($title, 0, 255), $nodeRef->getElement()->isAllowSlugSlashes());
         }
         $nodeRef = new NodeRef($nodeRef->getElement(), $slug);
     } else {
         if ($useTime) {
             $title = substr($slug, 0, 237) . '-' . floor(microtime(true) * 100);
         } else {
             $title = substr($slug, 0, 255);
         }
         $nodeRef = new NodeRef($nodeRef->getElement(), SlugUtils::createSlug($title, $nodeRef->getElement()->isAllowSlugSlashes()));
     }
     return $nodeRef;
 }
Пример #9
0
 public function __construct($tagOrElement, $slug = '', $role = '', $value = '', $valuedisplay = '')
 {
     $this->fields = array('TagDirection' => 'out', 'TagElement' => '', 'TagSlug' => '', 'TagRole' => '', 'TagRoleDisplay' => '', 'TagValue' => '', 'TagValueDisplay' => '', 'TagSortOrder' => 0, 'TagSectionID' => 0);
     if ($tagOrElement instanceof Tag || $tagOrElement instanceof TagPartial) {
         $this->fields = array_merge($this->fields, $tagOrElement->toArray());
     } else {
         if (is_array($tagOrElement)) {
             foreach ($tagOrElement as $key => $val) {
                 $this->fields[$key] = $val;
                 unset($key);
                 unset($val);
             }
         } else {
             if (is_string($tagOrElement) || $tagOrElement instanceof NodeRef) {
                 if ($tagOrElement instanceof NodeRef) {
                     $slug = $tagOrElement->getSlug();
                     $tagOrElement = $tagOrElement->getElement()->getSlug();
                 }
                 // assume first param is element
                 if (!empty($slug) || !empty($role) || !empty($value) || !empty($valuedisplay)) {
                     $this->fields['TagElement'] = $tagOrElement;
                     $this->fields['TagSlug'] = $slug;
                     $this->fields['TagRole'] = $role;
                     //                    $this->fields['TagRoleDisplay'] = $roledisplay;
                     $this->fields['TagValue'] = $value;
                     $this->fields['TagValueDisplay'] = $valuedisplay;
                 } else {
                     if (($pos = strpos($tagOrElement, '"')) !== FALSE) {
                         $parseTag = substr($tagOrElement, 0, $pos);
                         if (substr($tagOrElement, -1) != '"') {
                             throw new TagException('Invalid tag: TagValueDisplay must end in "');
                         }
                         $this->fields['TagValueDisplay'] = substr($tagOrElement, $pos + 1, -1);
                     } else {
                         $parseTag = $tagOrElement;
                     }
                     if (preg_match("/^(?P<el>[a-z0-9-]+):(?P<s>[a-z0-9\\/\\-]+)#(?P<r>[a-z0-9-]+)(=(?P<v>.+?)?)?\$/", $parseTag, $m)) {
                         $this->fields['TagElement'] = !empty($m['el']) ? $m['el'] : '';
                         $this->fields['TagSlug'] = !empty($m['s']) ? $m['s'] : '';
                         $this->fields['TagRole'] = !empty($m['r']) ? $m['r'] : '';
                         $this->fields['TagValue'] = !empty($m['v']) ? $m['v'] : '';
                     }
                 }
             }
         }
     }
     if (isset($this->fields['NoValidation'])) {
         return;
     }
     if (empty($this->fields['TagElement'])) {
         throw new TagException('Invalid tag: No TagElement was specified');
     }
     if (strtolower($this->fields['TagElement']) !== $this->fields['TagElement']) {
         $this->fields['TagElement'] = strtolower($this->fields['TagElement']);
     }
     //      $elementObj = AppContext::Element($this->fields['TagElement']);
     //      if(empty($elementObj))
     //          throw new TagException('Invalid tag: "'.$this->fields['TagElement'].'" is not a valid element');
     if (!isset($this->fields['TagSlug'])) {
         throw new TagException('Invalid tag: No TagSlug was specified');
     }
     if (strtolower($this->fields['TagSlug']) !== $this->fields['TagSlug']) {
         $this->fields['TagSlug'] = strtolower($this->fields['TagSlug']);
     }
     if (!preg_match("/^[a-z0-9-\\/]+\$/", $this->fields['TagSlug'])) {
         throw new TagException('Invalid tag: "' . $this->fields['TagSlug'] . '" must be valid slug');
     }
     if (empty($this->fields['TagRole'])) {
         throw new Exception('Invalid tag: No TagRole was specified');
     }
     if (!preg_match("/^[a-z0-9-\\/]+\$/", $this->fields['TagRole'])) {
         $this->fields['TagRole'] = SlugUtils::createSlug($this->fields['TagRole']);
     }
     // TagRoleDisplay inherits TagRole if empty
     //        if(empty($this->fields['TagRoleDisplay'])) {
     //            $this->fields['TagRoleDisplay'] = SlugUtils::unsluggify($this->fields['TagRole']);
     //        }
     //        if(!empty($this->tag['TagRoleDisplay']))
     //            $this->tag['TagRoleDisplay'] = preg_replace("/\s+/s",' ',$this->tag['TagRoleDisplay']);
     if (!empty($this->fields['TagValue'])) {
         if (!preg_match("/^[a-z0-9-\\/]+\$/", $this->fields['TagValue'])) {
             $this->fields['TagValue'] = SlugUtils::createSlug($this->fields['TagValue']);
         }
         // TagValueDisplay inherits TagValue if empty
         if (empty($this->fields['TagValueDisplay'])) {
             $this->fields['TagValueDisplay'] = $this->fields['TagValue'];
         }
     } else {
         if (!empty($this->fields['TagValueDisplay'])) {
             $this->fields['TagValue'] = SlugUtils::createSlug($this->fields['TagValueDisplay']);
         }
     }
     if (!empty($this->fields['TagValueDisplay'])) {
         $this->fields['TagValueDisplay'] = preg_replace("/\\s+/s", ' ', $this->fields['TagValueDisplay']);
     }
     // lowercase all parts
     foreach (array('TagElement', 'TagSlug', 'TagRole', 'TagValue') as $name) {
         $this->fields[$name] = strtolower($this->fields[$name]);
     }
     if (!empty($this->fields['MatchPartial'])) {
         $this->setMatchPartial(new TagPartial($this->fields['MatchPartial']));
     }
     // set TagString to empty so toString forces rebuild
     //      $this->fields['TagString'] = '';
     //      $this->toString();
 }
 /**
  * Generates key.
  *
  * @param string $slug
  * @param string $prefix
  *
  * @return string
  */
 protected function generateKey($slug, $prefix = 'active-edits')
 {
     return sprintf('%s-%s', $prefix, \SlugUtils::createSlug($slug));
 }
 public function replace()
 {
     $this->checkNonce();
     if (empty($this->params['Title'])) {
         throw new Exception('Title parameter is required', 210);
     }
     if (empty($this->params['ElementSlug'])) {
         throw new Exception('ElementSlug parameter is required', 220);
     }
     $title = $this->params['Title'];
     $slug = SlugUtils::createSlug($title);
     $noderef = new NodeRef($this->ElementService->getBySlug($this->Request->getParameter('ElementSlug')), $slug);
     // create node
     $node = $noderef->generateNode();
     $this->NodeMapper->defaultsOnNode($node);
     $node->Title = $title;
     $node->Slug = $slug;
     $this->getErrors()->throwOnError();
     // edit existing record
     if ($this->RegulatedNodeService->refExists($noderef)) {
         $existing = $this->RegulatedNodeService->getByNodeRef($noderef);
         $existing->setNodePartials($node->getNodePartials());
         $existing->setMetas($node->getMetas());
         $existing->setOutTags($node->getOutTags());
         $node = $this->RegulatedNodeService->edit($node);
         //create new record
     } else {
         $node = $this->RegulatedNodeService->quickAdd($node);
     }
     $node = $this->RegulatedNodeService->getByNodeRef($node->getNodeRef(), new NodePartials());
     $this->bindToActionDatasource(array($node));
     return new View($this->successView());
 }
 /**
  * Creates a filename from title, prefixed with date if required.
  *
  * @param string The title to use e.g. IMG-1234.jpg
  * @return string The filename
  */
 protected function buildFilename($title)
 {
     $ext = pathinfo($title, PATHINFO_EXTENSION);
     $filename = str_replace('.' . $ext, '', $title);
     $datePrefix = '/';
     if ($this->mediaOrganizeByDate) {
         $now = $this->DateFactory->newStorageDate();
         $datePrefix = $now->format('/Y/m/d/');
     }
     return $datePrefix . SlugUtils::createSlug($filename) . '.' . strtolower($ext);
 }
 protected function validateMetas(array $metas)
 {
     foreach ($metas as $meta) {
         $role = 'unknown id';
         try {
             // Required attributes
             foreach (array('id') as $attr) {
                 if ($meta->attribute($attr) == null) {
                     throw new SchemaException("Required attribute '{$attr}' not found for meta: " . htmlentities($meta->asPrettyXML()));
                 }
             }
             $role = ltrim($meta->attribute('id'), '#');
             if (!SlugUtils::isSlug($role)) {
                 throw new SchemaException("Meta ID is in an invalid format. Must be in valid slug format. Meta: " . $meta->attribute('id'));
             }
             if (in_array($role, $this->allRoles)) {
                 throw new SchemaException("Meta id [" . $role . "] already used in schema");
             }
             $this->allRoles[] = $role;
             // Required children
             foreach (array('title', 'validation') as $required_child) {
                 if (!$meta->{$required_child}) {
                     throw new SchemaException("Required child element '{$required_child}' not found for meta: " . $meta->attribute('id'));
                 }
             }
             // Validate we have some text for the title
             if (strlen((string) $meta->title) == 0) {
                 throw new SchemaException("Meta title must have a value. Meta: " . $meta->attribute('id'));
             }
             // Check that the <validation> tag is sane, if it exists
             $this->validationCheck($meta->validation);
             if ($meta->validation->attribute('datatype') == 'boolean' && empty($meta->default)) {
                 throw new SchemaException('Meta boolean datatype must specify a default value: ' . $meta->attribute('id'));
             }
         } catch (SchemaException $e) {
             throw new SchemaException("Unable to parse meta definition [{$role}]:\n" . $e->getMessage());
         }
     }
 }
Пример #14
0
 public function unsluggify()
 {
     $slug = $this->getParameter('value');
     return SlugUtils::unsluggify($slug);
 }
 protected function filenameFromBasename($basename)
 {
     $path = pathinfo($basename);
     $ext = !empty($path['extension']) ? strtolower($path['extension']) : '';
     $path['filename'] = substr($path['filename'], 0, 128);
     $desiredFileWithoutExtension = SlugUtils::createSlug($path['filename'], $this->mediaAllowCustomSubdirectories);
     $desiredFilename = $desiredFileWithoutExtension . (!empty($ext) ? '.' . $ext : '');
     //ENSURE FILENAME IS 128 OR LESS
     $len = strlen($desiredFilename) + ($this->mediaOrganizeByDate ? 11 : 0) + 1;
     if ($len > 128) {
         $desiredFilename = substr($desiredFileWithoutExtension, 0, 128 - (strlen(!empty($ext) ? '.' . $ext : '') + ($this->mediaOrganizeByDate ? 11 : 0) + 1)) . (!empty($ext) ? '.' . $ext : '');
     }
     $dateStamp = '/';
     if ($this->mediaOrganizeByDate) {
         $now = $this->DateFactory->newStorageDate();
         $dateStamp = $now->format('/Y/m/d/');
     }
     return $dateStamp . $desiredFilename;
 }
 public function filenameForNode($node)
 {
     $ext = pathinfo($node->Title, PATHINFO_EXTENSION);
     $filename = str_replace('.' . $ext, '', $node->Title);
     $dateStamp = '/';
     if ($this->mediaOrganizeByDate) {
         $dateStamp = $this->getDateStamp($node);
     }
     return $dateStamp . SlugUtils::createSlug($filename);
 }
Пример #17
0
 protected function sanitizeURI($uri)
 {
     $sluggedUri = SlugUtils::createSlug($uri, true);
     if (strcmp($sluggedUri, $uri) !== 0) {
         $this->Response->sendStatus(Response::SC_MOVED_PERMANENTLY);
         $this->Response->sendRedirect($sluggedUri);
     }
     return $sluggedUri;
 }
 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;
 }
 protected function _importPhotosFromJson($file)
 {
     try {
         $contents = file_get_contents($file);
         $json = JSONUtils::decode($contents);
         foreach ($json as $v) {
             echo "importing {$v->title}...";
             $url = $v->src;
             $parts = parse_url($url);
             $slug = SlugUtils::createSlug(basename($parts['path']));
             preg_match('/(\\.\\w*)$/', $parts['path'], $ext);
             $nodeRef = $this->NodeRefService->oneFromAspect('@images');
             $nodeRef = $this->NodeRefService->generateNodeRef($nodeRef, $slug);
             $node = $nodeRef->generateNode();
             if (!$this->NodeService->refExists($node->getNodeRef())) {
                 // go fetch file from url
                 $data = $this->HttpRequest->fetchURL($url);
                 // create a unique output file name
                 $sourceFile = FileSystemUtils::secureTmpname($this->workDir, 'urlfetch', !empty($ext[1]) ? strtolower($ext[1]) : null);
                 file_put_contents($sourceFile, $data);
                 $node->Title = rtrim($v->title);
                 $node->Status = "published";
                 $node->ActiveDate = $this->DateFactory->newStorageDate();
                 $node = $this->ImageService->storeMedia($sourceFile, $node, basename($parts['path']));
                 $this->NodeService->add($node);
                 echo "done\n";
             } else {
                 echo "exists\n";
             }
             unset($nodeRef);
             unset($node);
         }
     } catch (Exception $e) {
         echo "Exception: " . $e->getMessage() . "\n";
     }
 }
Пример #20
0
 public function __construct($tagOrElement, $slug = '', $role = '', $value = '')
 {
     if ($tagOrElement instanceof TagPartial || $tagOrElement instanceof Tag) {
         $this->fields = $tagOrElement->toArray();
         return;
     }
     $this->fields = array_merge($this->fields, array('TagElement' => '', 'TagAspect' => '', 'TagSlug' => '', 'TagRole' => '', 'TagValue' => ''));
     if (is_array($tagOrElement)) {
         $this->fields = array_merge($this->fields, $tagOrElement);
     } else {
         if (is_string($tagOrElement)) {
             // assume first param is element
             if (!empty($slug) || !empty($role) || !empty($value)) {
                 if (substr($tagOrElement, 0, 1) == '@') {
                     $this->fields['TagAspect'] = substr($tagOrElement, 1);
                 } else {
                     $this->fields['TagElement'] = $tagOrElement;
                 }
                 $this->fields['TagSlug'] = $slug;
                 $this->fields['TagRole'] = $role;
                 $this->fields['TagValue'] = $value;
                 // assume first param is tag string
             } else {
                 $expressions = StringUtils::smartSplit($tagOrElement, ".", '"', '\\"', 2);
                 if (preg_match("/^(((?P<ai>@)?(?P<el>[a-z0-9-]+))?(:(?P<s>[a-z0-9\\/\\-]+)?)?)?(#(?P<r>[a-z0-9-]+)?)?(=(?P<v>.+?))?\$/", array_shift($expressions), $m)) {
                     if (!empty($m['ai'])) {
                         $this->fields['TagAspect'] = !empty($m['el']) ? $m['el'] : '';
                     } else {
                         $this->fields['TagElement'] = !empty($m['el']) ? $m['el'] : '';
                     }
                     $this->fields['TagSlug'] = !empty($m['s']) ? $m['s'] : '';
                     $this->fields['TagRole'] = !empty($m['r']) ? $m['r'] : '';
                     $this->fields['TagValue'] = !empty($m['v']) ? $m['v'] : '';
                     if (!empty($expressions)) {
                         //                            if(count($expressions) > 1)
                         $this->fields['ChildPartials'] = current($expressions);
                         //                            else
                         //                                $this->fields['ChildPartial'] = $expressions[0];
                     }
                 }
             }
         } else {
             throw new Exception('Invalid parameter to TagPartial: ' . ClassUtils::getQualifiedType($tagOrElement));
         }
     }
     if (empty($this->fields['TagElement']) && empty($this->fields['TagAspect']) && empty($this->fields['TagRole'])) {
         throw new TagException('Invalid partial: No element, aspect, or role was specified [' . print_r($tagOrElement, true) . ']');
     }
     if (!empty($this->fields['TagAspect'])) {
         //            $this->fields['TagAspect'] = strtolower($this->fields['TagAspect']);
         if (!preg_match("/[a-z0-9-]+/", $this->fields['TagAspect'])) {
             throw new TagException('Invalid partial: Aspect "' . $this->fields['TagAspect'] . '" must contain only characters or dash');
         }
     }
     if (!empty($this->fields['TagSlug'])) {
         $this->fields['TagSlug'] = strtolower($this->fields['TagSlug']);
         if (!SlugUtils::isSlug($this->fields['TagSlug'], true)) {
             throw new TagException('Invalid tag: "' . $this->fields['TagSlug'] . '" must be valid slug');
         }
     }
     if (!empty($this->fields['TagRole']) && !SlugUtils::isSlug($this->fields['TagRole'])) {
         $this->fields['TagRole'] = SlugUtils::createSlug($this->fields['TagRole']);
     }
     if (!empty($this->fields['TagValue']) && !SlugUtils::isSlug($this->fields['TagValue'])) {
         $this->fields['TagValue'] = SlugUtils::createSlug($this->fields['TagValue']);
     }
     // lowercase all parts
     foreach (array('TagElement', 'TagAspect', 'TagSlug', 'TagRole', 'TagValue') as $name) {
         $this->fields[$name] = strtolower($this->fields[$name]);
     }
 }
Пример #21
0
 /**
  * @param NodeRef $nodeRef
  * @param null $title
  * @param bool $useTime
  * @return NodeRef
  * @throws NodeException
  * @events slugUniquing validation event with $slugTransporter as param2
  */
 public function generateUniqueNodeRef(NodeRef $nodeRef, $title = null, $useTime = false)
 {
     $slug = $nodeRef->getSlug();
     $slugTransporter = new Transport();
     $slugTransporter->Slug = $slug;
     $errors = new Errors();
     $this->NodeEvents->fireValidationEvents('slugUniquing', $errors, $nodeRef, $slugTransporter);
     $slug = $slugTransporter->Slug;
     $nodeRef = new NodeRef($nodeRef->getElement(), $slug);
     $errors->throwOnError();
     if (empty($slug)) {
         if (empty($title)) {
             throw new NodeException('Cannot generate unique NodeRef without title');
         }
         if ($useTime) {
             $slug = SlugUtils::createSlug(substr($title, 0, 237) . '-' . floor(microtime(true) * 100), $nodeRef->getElement()->isAllowSlugSlashes());
         } else {
             $slug = SlugUtils::createSlug(substr($title, 0, 255), $nodeRef->getElement()->isAllowSlugSlashes());
         }
         $nodeRef = new NodeRef($nodeRef->getElement(), $slug);
     } else {
         if ($useTime) {
             $title = substr($slug, 0, 237) . '-' . floor(microtime(true) * 100);
         } else {
             $title = substr($slug, 0, 255);
         }
         $nodeRef = new NodeRef($nodeRef->getElement(), SlugUtils::createSlug($title, $nodeRef->getElement()->isAllowSlugSlashes()));
     }
     $i = 0;
     while ($this->refExists($nodeRef)) {
         // Generate a unique slug
         $slug = SlugUtils::createSlug(substr($title, 0, 250) . " " . ++$i, $nodeRef->getElement()->isAllowSlugSlashes());
         $nodeRef = new NodeRef($nodeRef->getElement(), $slug);
     }
     return $nodeRef;
 }