public static function generateHandle($sourceVal)
 {
     // Remove HTML tags
     $handle = preg_replace('/<(.*?)>/', '', $sourceVal);
     // Remove inner-word punctuation
     $handle = preg_replace('/[\'"‘’“”\\[\\]\\(\\)\\{\\}:]/', '', $handle);
     // Make it lowercase
     $handle = strtolower($handle);
     // Convert extended ASCII characters to basic ASCII
     $handle = StringHelper::asciiString($handle);
     // Handle must start with a letter
     $handle = preg_replace('/^[^a-z]+/', '', $handle);
     // Get the "words"
     $words = array_filter(preg_split('/[^a-z0-9]+/', $handle));
     $handle = '';
     // Make it camelCase
     for ($i = 0; $i < count($words); $i++) {
         if ($i == 0) {
             $handle .= $words[$i];
         } else {
             $handle .= strtoupper($words[$i][0]) . substr($words[$i], 1);
         }
     }
     return $handle;
 }
 /**
  * Make handle from source name.
  *
  * @param $name
  *
  * @return string
  */
 private function _makeHandle($name, $sourceId)
 {
     // Remove HTML tags
     $handle = preg_replace('/<(.*?)>/', '', $name);
     $handle = preg_replace('/<[\'"‘’“”\\[\\]\\(\\)\\{\\}:]>/', '', $handle);
     $handle = StringHelper::toLowerCase($handle);
     $handle = StringHelper::asciiString($handle);
     $handle = preg_replace('/^[^a-z]+/', '', $handle);
     // In case it was an all non-ASCII handle, have a default.
     if (!$handle) {
         $handle = 'source' . $sourceId;
     }
     $handleParts = preg_split('/[^a-z0-9]+/', $handle);
     $handle = '';
     foreach ($handleParts as $index => &$part) {
         if ($index) {
             $part = ucfirst($part);
         }
         $handle .= $part;
     }
     $appendix = '';
     while (true) {
         $taken = craft()->db->createCommand()->select('handle')->from('assetsources')->where('handle = :handle', array(':handle' => $handle . $appendix))->queryScalar();
         if ($taken) {
             $appendix = (int) $appendix + 1;
         } else {
             break;
         }
     }
     return $handle . $appendix;
 }
Beispiel #3
0
 /**
  * Sets a valid slug on a given element.
  *
  * @param BaseElementModel $element
  *
  * @return null
  */
 public static function setValidSlug(BaseElementModel $element)
 {
     $slug = $element->slug;
     if (!$slug) {
         // Create a slug for them, based on the element's title.
         // Replace periods, underscores, and hyphens with spaces so they get separated with the slugWordSeparator
         // to mimic the default JavaScript-based slug generation.
         $slug = str_replace(array('.', '_', '-'), ' ', $element->title);
         // Enforce the limitAutoSlugsToAscii config setting
         if (craft()->config->get('limitAutoSlugsToAscii')) {
             $slug = StringHelper::asciiString($slug);
         }
     }
     $element->slug = static::createSlug($slug);
 }
 /**
  * Backup All Forms
  */
 public function backupAllForms()
 {
     $forms = FormBuilder2_FormRecord::model()->ordered()->findAll();
     $table = 'craft_formbuilder2_forms';
     if ($forms) {
         $this->_currentVersion = 'v' . craft()->getVersion() . '.' . craft()->getBuild();
         $siteName = IOHelper::cleanFilename(StringHelper::asciiString(craft()->getSiteName()));
         $fileName = ($siteName ? $siteName . '_' : '') . gmdate('ymd_His') . '_' . $this->_currentVersion . '.sql';
         $this->_filePath = craft()->path->getDbBackupPath() . StringHelper::toLowerCase($fileName);
         $this->_processHeader();
         $results = $this->_processResult($table);
         $this->_processConstraints();
         $this->_processFooter();
         $filepath = $this->_filePath;
         $this->_processFile($fileName, $filepath);
     } else {
         return false;
     }
 }
 /**
  * Triggers the database backup including all DML and DDL and writes it out to a file.
  *
  * @return string The path to the database backup file.
  */
 public function run()
 {
     // Normalize the ignored table names if there is a table prefix set.
     if (($tablePrefix = craft()->config->get('tablePrefix', ConfigFile::Db)) !== '') {
         foreach ($this->_ignoreDataTables as $key => $tableName) {
             $this->_ignoreDataTables[$key] = $tablePrefix . '_' . $tableName;
         }
     }
     $this->_currentVersion = 'v' . craft()->getVersion() . '.' . craft()->getBuild();
     $siteName = IOHelper::cleanFilename(StringHelper::asciiString(craft()->getSiteName()));
     $fileName = ($siteName ? $siteName . '_' : '') . gmdate('ymd_His') . '_' . $this->_currentVersion . '.sql';
     $this->_filePath = craft()->path->getDbBackupPath() . StringHelper::toLowerCase($fileName);
     $this->_processHeader();
     foreach (craft()->db->getSchema()->getTables() as $resultName => $val) {
         $this->_processResult($resultName);
     }
     $this->_processConstraints();
     $this->_processFooter();
     return $this->_filePath;
 }
 /**
  * Generates an entry slug based on its title.
  *
  * @access private
  * @param EntryModel $entry
  */
 private function _generateEntrySlug(EntryModel $entry)
 {
     $slug = $entry->slug ? $entry->slug : $entry->getTitle();
     // Remove HTML tags
     $slug = preg_replace('/<(.*?)>/', '', $slug);
     // Remove apostrophes
     $slug = str_replace(array('\'', '’'), array('', ''), $slug);
     // Make it lowercase
     $slug = strtolower($slug);
     // Convert extended ASCII characters to basic ASCII
     $slug = StringHelper::asciiString($slug);
     // Slug must start and end with alphanumeric characters
     $slug = preg_replace('/^[^a-z0-9]+/', '', $slug);
     $slug = preg_replace('/[^a-z0-9]+$/', '', $slug);
     // Get the "words"
     $words = preg_split('/[^a-z0-9]+/', $slug);
     $words = ArrayHelper::filterEmptyStringsFromArray($words);
     $slug = implode('-', $words);
     if ($slug) {
         // Make it unique
         $conditions = array('and', 'sectionId = :sectionId', 'locale = :locale', 'slug = :slug');
         $params = array(':sectionId' => $entry->sectionId, ':locale' => $entry->locale);
         if ($entry->id) {
             $conditions[] = 'id != :entryId';
             $params[':entryId'] = $entry->id;
         }
         for ($i = 0; true; $i++) {
             $testSlug = $slug . ($i != 0 ? "-{$i}" : '');
             $params[':slug'] = $testSlug;
             $totalEntries = craft()->db->createCommand()->select('count(id)')->from('entries_i18n')->where($conditions, $params)->queryScalar();
             if ($totalEntries == 0) {
                 break;
             }
         }
         $entry->slug = $testSlug;
     } else {
         $entry->slug = '';
     }
 }
Beispiel #7
0
 /**
  * Cleans a filename.
  *
  * @param string $fileName  The filename to clean.
  * @param bool   $onlyAscii Whether to only allow ASCII characters in the filename.
  * @param string $separator The separator to use for any whitespace. Defaults to '-'.
  *
  * @return mixed
  */
 public static function cleanFilename($fileName, $onlyAscii = false, $separator = '-')
 {
     $disallowedChars = array('—', '–', '&#8216;', '&#8217;', '&#8220;', '&#8221;', '&#8211;', '&#8212;', '+', '%', '^', '~', '?', '[', ']', '/', '\\', '=', '<', '>', ':', ';', ',', '\'', '"', '&', '$', '#', '*', '(', ')', '|', '~', '`', '!', '{', '}');
     // Replace any control characters in the name with a space.
     $fileName = preg_replace("#\\x{00a0}#siu", ' ', $fileName);
     // Strip any characters not allowed.
     $fileName = str_replace($disallowedChars, '', strip_tags($fileName));
     if (!is_null($separator)) {
         $fileName = preg_replace('/(\\s|' . preg_quote($separator) . ')+/', $separator, $fileName);
     }
     // Nuke any trailing or leading .-_
     $fileName = trim($fileName, '.-_');
     $fileName = $onlyAscii ? StringHelper::asciiString($fileName) : $fileName;
     return $fileName;
 }
 /**
  * Get paths for an external file (really external, or on an external source type)
  *
  * @param $image
  * @throws Exception
  */
 private function _getPathsForUrl($image)
 {
     $convertedImageStr = StringHelper::asciiString(urldecode($image));
     $urlParts = parse_url($convertedImageStr);
     $pathParts = pathinfo($urlParts['path']);
     $hashRemoteUrl = craft()->imager->getSetting('hashRemoteUrl');
     $hashPath = craft()->imager->getSetting('hashPath');
     if ($hashPath) {
         $targetFolder = '/' . md5($pathParts['dirname']);
     } else {
         $targetFolder = $pathParts['dirname'];
     }
     if ($hashRemoteUrl) {
         if (is_string($hashRemoteUrl) && $hashRemoteUrl == 'host') {
             $parsedDirname = substr(md5($urlParts['host']), 0, 10) . $targetFolder;
         } else {
             $parsedDirname = md5($urlParts['host'] . $pathParts['dirname']);
         }
     } else {
         $parsedDirname = str_replace('.', '_', $urlParts['host']) . $targetFolder;
     }
     $this->sourcePath = craft()->path->getRuntimePath() . 'imager/' . $parsedDirname . '/';
     $this->targetPath = craft()->imager->getSetting('imagerSystemPath') . $parsedDirname . '/';
     $this->targetUrl = craft()->imager->getSetting('imagerUrl') . $parsedDirname . '/';
     $this->sourceFilename = $this->targetFilename = str_replace(' ', '-', $pathParts['basename']);
     // check if the temp path for remote files exists or can be created.
     if (!IOHelper::getRealPath($this->sourcePath)) {
         IOHelper::createFolder($this->sourcePath, craft()->config->get('defaultFolderPermissions'), true);
         if (!IOHelper::getRealPath($this->sourcePath)) {
             throw new Exception(Craft::t('Temp folder “{sourcePath}” does not exist and could not be created', array('sourcePath' => $this->sourcePath)));
         }
     }
     // check if the file is already downloaded
     if (!IOHelper::fileExists($this->sourcePath . $this->sourceFilename) || craft()->imager->getSetting('cacheDurationRemoteFiles') !== false && IOHelper::getLastTimeModified($this->sourcePath . $this->sourceFilename)->format('U') + craft()->imager->getSetting('cacheDurationRemoteFiles') < time()) {
         $this->_downloadFile($this->sourcePath . $this->sourceFilename, $image);
         if (!IOHelper::fileExists($this->sourcePath . $this->sourceFilename)) {
             throw new Exception(Craft::t('File could not be downloaded and saved to “{sourcePath}”', array('sourcePath' => $this->sourcePath)));
         }
     }
 }
Beispiel #9
0
 /**
  * Clean a filename.
  *
  * @param $fileName
  * @return mixed
  */
 public static function cleanFilename($fileName)
 {
     $fileName = StringHelper::asciiString(ltrim($fileName, '.'));
     return preg_replace('/[^@a-z0-9\\-_\\.]/i', '_', str_replace(chr(0), '', $fileName));
 }