当前位置: 首页>>代码示例>>PHP>>正文


PHP FileNameFilter类代码示例

本文整理汇总了PHP中FileNameFilter的典型用法代码示例。如果您正苦于以下问题:PHP FileNameFilter类的具体用法?PHP FileNameFilter怎么用?PHP FileNameFilter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了FileNameFilter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: onBeforeWrite

 public function onBeforeWrite()
 {
     parent::onBeforeWrite();
     // Create the base folder
     if (!$this->owner->BaseFolder && $this->owner->Title) {
         $filter = new FileNameFilter();
         $this->owner->BaseFolder = $filter->filter($this->owner->getTitle());
         $this->owner->BaseFolder = str_replace(' ', '', ucwords(str_replace('-', ' ', $this->owner->BaseFolder)));
     }
     // If name has changed, rename existing groups
     $changes = $this->owner->getChangedFields();
     if (isset($changes['Title']) && !empty($changes['Title']['before'])) {
         $filter = new URLSegmentFilter();
         $groupName = $this->getAdministratorGroupName($changes['Title']['before']);
         $group = self::getGroupByName($groupName);
         if ($group) {
             $group->Title = $this->getAdministratorGroupName($changes['Title']['after']);
             $group->Code = $filter->filter($group->Title);
             $group->write();
         }
         $membersGroupName = $this->getMembersGroupName($changes['Title']['before']);
         $membersGroup = self::getGroupByName($membersGroupName);
         if ($membersGroup) {
             $membersGroup->Title = $this->getMembersGroupName($changes['Title']['after']);
             $membersGroup->Code = $filter->filter($membersGroup->Title);
             $membersGroup->write();
         }
     }
 }
开发者ID:lekoala,项目名称:silverstripe-subsites-extras,代码行数:29,代码来源:SubsiteExtension.php

示例2: run

 public function run($request)
 {
     $filesWithSpaces = File::get()->where('"Filename" LIKE \'% %\'');
     $filter = new FileNameFilter();
     foreach ($filesWithSpaces as $file) {
         DB::alteration_message("Updating file #" . $file->ID . " with filename " . $file->Filename);
         $parts = explode('/', $file->Filename);
         $filtered = array_map(function ($item) use($filter) {
             return $filter->filter($item);
         }, $parts);
         $file->Filename = implode('/', $filtered);
         $file->write();
     }
     DB::alteration_message("All done!");
 }
开发者ID:helpfulrobot,项目名称:lekoala-silverstripe-devtoolkit,代码行数:15,代码来源:RemoveSpacesFromFilenames.php

示例3: determineFolderName

 /**
  * Description
  * @return string
  */
 protected function determineFolderName()
 {
     // Grab paths
     $paths = Config::inst()->get(__CLASS__, 'upload_paths');
     // Grab ancestry from top-down
     $className = get_class($this->record);
     $classes = array_reverse(ClassInfo::ancestry($className));
     $path = $className;
     // Loop over ancestry and break out if we have a match
     foreach ($classes as $class) {
         if (array_key_exists($class, $paths)) {
             $path = $paths[$class];
             break;
         }
     }
     // If there are any parameters which require matching, search for them
     $matches = array();
     preg_match_all('/\\$[a-zA-Z0-9]+?/U', $path, $matches);
     // Replace with field values
     foreach ($matches[0] as $match) {
         $field = str_replace("\$", "", $match);
         $value = FileNameFilter::create()->filter($this->record->getField($field));
         $path = str_replace($match, $value, $path);
     }
     $this->folderName = $path;
     return $path;
 }
开发者ID:Marketo,项目名称:SilverStripe-ContextAwareUploadField,代码行数:31,代码来源:ContextAwareUploadField.php

示例4: find_or_make

 /**
  * Find the given folder or create it as a database record
  *
  * @param string $folderPath Directory path relative to assets root
  * @return Folder|null
  */
 public static function find_or_make($folderPath)
 {
     // replace leading and trailing slashes
     $folderPath = preg_replace('/^\\/?(.*)\\/?$/', '$1', trim($folderPath));
     $parts = explode("/", $folderPath);
     $parentID = 0;
     $item = null;
     $filter = FileNameFilter::create();
     foreach ($parts as $part) {
         if (!$part) {
             continue;
             // happens for paths with a trailing slash
         }
         // Ensure search includes folders with illegal characters removed, but
         // err in favour of matching existing folders if $folderPath
         // includes illegal characters itself.
         $partSafe = $filter->filter($part);
         $item = Folder::get()->filter(array('ParentID' => $parentID, 'Name' => array($partSafe, $part)))->first();
         if (!$item) {
             $item = new Folder();
             $item->ParentID = $parentID;
             $item->Name = $partSafe;
             $item->Title = $part;
             $item->write();
         }
         $parentID = $item->ID;
     }
     return $item;
 }
开发者ID:ivoba,项目名称:silverstripe-framework,代码行数:35,代码来源:Folder.php

示例5: onBeforeWrite

 public function onBeforeWrite()
 {
     parent::onBeforeWrite();
     $this->Title = FileNameFilter::create()->filter($this->Title);
     if (strlen($this->ContentFile)) {
         $templates = $this->fileBasedTemplates();
         if (!isset($templates[$this->ContentFile])) {
             $this->ContentFile = '';
         }
     }
 }
开发者ID:nyeholt,项目名称:silverstripe-usertemplates,代码行数:11,代码来源:UserTemplate.php

示例6: checkFolder

 function checkFolder()
 {
     if (!$this->exists()) {
         return;
     }
     if (!$this->URLSegment) {
         return;
     }
     $baseFolder = '';
     if (class_exists('Subsite') && self::config()->use_subsite_integration) {
         if ($this->SubsiteID) {
             $subsite = $this->Subsite();
             if ($subsite->hasField('BaseFolder')) {
                 $baseFolder = $subsite->BaseFolder;
             } else {
                 $filter = new FileNameFilter();
                 $baseFolder = $filter->filter($subsite->getTitle());
                 $baseFolder = str_replace(' ', '', ucwords(str_replace('-', ' ', $baseFolder)));
             }
             $baseFolder .= '/';
         }
     }
     $folderPath = $baseFolder . "galleries/{$this->URLSegment}";
     $folder = Folder::find_or_make($folderPath);
     if ($this->RootFolderID && $folder->ID != $this->RootFolderID) {
         if ($this->RootFolder()->exists()) {
             // We need to rename current folder
             $this->RootFolder()->setFilename($folder->Filename);
             $this->RootFolder()->write();
             $folder->deleteDatabaseOnly();
             //Otherwise we keep a stupid clone that will be used as the parent
         } else {
             $this->RootFolderID = $folder->ID;
         }
     } else {
         $this->RootFolderID = $folder->ID;
     }
 }
开发者ID:helpfulrobot,项目名称:lekoala-silverstripe-magnific-gallery,代码行数:38,代码来源:MagnificGalleryPage.php

示例7: load

 /**
  * Save an file passed from a form post into this object.
  * 
  * @param $tmpFile array Indexed array that PHP generated for every file it uploads.
  * @param $folderPath string Folder path relative to /assets
  * @return Boolean|string Either success or error-message.
  */
 public function load($tmpFile, $folderPath = false)
 {
     if (!$folderPath) {
         $folderPath = Config::inst()->get('Upload', 'uploads_folder');
     }
     // @TODO This puts a HUGE limitation on files especially when lots
     // have been uploaded.
     $base = Director::baseFolder();
     $parentFolder = Folder::find_or_make($folderPath);
     // Generate default filename
     $fileArray = explode('/', $tmpFile);
     $fileName = $fileArray[count($fileArray) - 1];
     $nameFilter = FileNameFilter::create();
     $file = $nameFilter->filter($fileName);
     $fileName = basename($file);
     $relativeFilePath = ASSETS_DIR . "/" . $folderPath . "/{$fileName}";
     // if filename already exists, version the filename (e.g. test.gif to test1.gif)
     while (file_exists("{$base}/{$relativeFilePath}")) {
         $i = isset($i) ? $i + 1 : 2;
         $oldFilePath = $relativeFilePath;
         // make sure archives retain valid extensions
         if (substr($relativeFilePath, strlen($relativeFilePath) - strlen('.tar.gz')) == '.tar.gz' || substr($relativeFilePath, strlen($relativeFilePath) - strlen('.tar.bz2')) == '.tar.bz2') {
             $relativeFilePath = preg_replace('/[0-9]*(\\.tar\\.[^.]+$)/', $i . '\\1', $relativeFilePath);
         } else {
             if (strpos($relativeFilePath, '.') !== false) {
                 $relativeFilePath = preg_replace('/[0-9]*(\\.[^.]+$)/', $i . '\\1', $relativeFilePath);
             } else {
                 if (strpos($relativeFilePath, '_') !== false) {
                     $relativeFilePath = preg_replace('/_([^_]+$)/', '_' . $i, $relativeFilePath);
                 } else {
                     $relativeFilePath .= '_' . $i;
                 }
             }
         }
         if ($oldFilePath == $relativeFilePath && $i > 2) {
             user_error("Couldn't fix {$relativeFilePath} with {$i} tries", E_USER_ERROR);
         }
     }
     if (file_exists($tmpFile) && copy($tmpFile, $base . "/" . $relativeFilePath)) {
         $this->owner->ParentID = $parentFolder->ID;
         // This is to prevent it from trying to rename the file
         $this->owner->Name = basename($relativeFilePath);
         $this->owner->write();
         return true;
     } else {
         return false;
     }
 }
开发者ID:helpfulrobot,项目名称:andrelohmann-silverstripe-extended-file,代码行数:55,代码来源:ExtendedFile.php

示例8: getPdfPreviewImage

 public function getPdfPreviewImage()
 {
     $pdfFile = Director::getAbsFile($this->owner->getFileName());
     $pathInfo = pathinfo($pdfFile);
     if (strtolower($pathInfo['extension']) != 'pdf') {
         //@Todo if dev then exception? else fail silently
         return null;
     }
     $fileName = $pathInfo['filename'];
     $savePath = __DIR__ . '/../../';
     $saveImage = $this->imagePrefix . '-' . $fileName . '.jpg';
     // Fix illegal characters
     $filter = FileNameFilter::create();
     $saveImage = $filter->filter($saveImage);
     $saveTo = $savePath . $this->folderToSave . $saveImage;
     $image = DataObject::get_one('Image', "`Name` = '{$saveImage}'");
     if (!$image) {
         $folderObject = DataObject::get_one("Folder", "`Filename` = '{$this->folderToSave}'");
         if ($folderObject) {
             if ($this->generator->generatePreviewImage($pdfFile, $saveTo)) {
                 $image = new Image();
                 $image->ParentID = $folderObject->ID;
                 $image->setName($saveImage);
                 $image->write();
             }
         }
     } else {
         //check LastEdited to update
         $cacheInValid = false;
         if (strtotime($image->LastEdited) < strtotime($this->owner->LastEdited)) {
             $cacheInValid = true;
         }
         if ($cacheInValid) {
             $this->generator->generatePreviewImage($pdfFile, $saveTo);
             $image->setName($saveImage);
             $image->write(false, false, true);
         }
     }
     return $image;
 }
开发者ID:helpfulrobot,项目名称:ivoba-silverstripe-simple-pdf-preview,代码行数:40,代码来源:SimplePdfPreviewImageExtension.php

示例9: createPdf

 public function createPdf()
 {
     $storeIn = $this->getStorageFolder();
     $name = FileNameFilter::create()->filter($this->Title);
     $name .= '.pdf';
     if (!$name) {
         throw new Exception("Must have a name!");
     }
     if (!$this->Template) {
         throw new Exception("Please specify a template before rendering.");
     }
     $file = new ComposedPdfFile();
     $file->ParentID = $storeIn->ID;
     $file->SourceID = $this->ID;
     $file->Title = $this->Title;
     $file->setName($name);
     $file->write();
     $content = $this->renderPdf();
     $filename = singleton('PdfRenditionService')->render($content);
     if (file_exists($filename)) {
         copy($filename, $file->getFullPath());
         unlink($filename);
     }
 }
开发者ID:helpfulrobot,项目名称:silverstripe-australia-pdfrendition,代码行数:24,代码来源:ComposedPdf.php

示例10: sanitize_folder_name

 /**
  * Folder name sanitizer.
  * Checks for valid names and sanitizes
  * against directory traversal.
  * 
  * @param  string $foldername
  * @return string
  */
 public static function sanitize_folder_name($foldername)
 {
     //return $foldername;
     return FileNameFilter::create()->filter(basename($foldername));
 }
开发者ID:arillo,项目名称:silverstripe-cleanutilities,代码行数:13,代码来源:ControlledFolderDataExtension.php

示例11: loadUploadedImage

 /**
  * File names are filtered through {@link FileNameFilter}, see class documentation
  * on how to influence this behaviour.
  *
  * @deprecated 3.2
  */
 public function loadUploadedImage($tmpFile)
 {
     Deprecation::notice('3.2', 'Use the Upload::loadIntoFile()');
     if (!is_array($tmpFile)) {
         user_error("Image::loadUploadedImage() Not passed an array.  Most likely, the form hasn't got the right" . "enctype", E_USER_ERROR);
     }
     if (!$tmpFile['size']) {
         return;
     }
     $class = $this->class;
     // Create a folder
     if (!file_exists(ASSETS_PATH)) {
         mkdir(ASSETS_PATH, Config::inst()->get('Filesystem', 'folder_create_mask'));
     }
     if (!file_exists(ASSETS_PATH . "/{$class}")) {
         mkdir(ASSETS_PATH . "/{$class}", Config::inst()->get('Filesystem', 'folder_create_mask'));
     }
     // Generate default filename
     $nameFilter = FileNameFilter::create();
     $file = $nameFilter->filter($tmpFile['name']);
     if (!$file) {
         $file = "file.jpg";
     }
     $file = ASSETS_PATH . "/{$class}/{$file}";
     while (file_exists(BASE_PATH . "/{$file}")) {
         $i = $i ? $i + 1 : 2;
         $oldFile = $file;
         $file = preg_replace('/[0-9]*(\\.[^.]+$)/', $i . '\\1', $file);
         if ($oldFile == $file && $i > 2) {
             user_error("Couldn't fix {$file} with {$i}", E_USER_ERROR);
         }
     }
     if (file_exists($tmpFile['tmp_name']) && copy($tmpFile['tmp_name'], BASE_PATH . "/{$file}")) {
         // Remove the old images
         $this->deleteFormattedImages();
         return true;
     }
 }
开发者ID:nicocin,项目名称:silverstripe-framework,代码行数:44,代码来源:Image.php

示例12: addUploadToFolder

	/**
	 * Take a file uploaded via a POST form, and save it inside this folder.
	 * File names are filtered through {@link FileNameFilter}, see class documentation
	 * on how to influence this behaviour.
	 */
	function addUploadToFolder($tmpFile) {
		if(!is_array($tmpFile)) {
			user_error("Folder::addUploadToFolder() Not passed an array.  Most likely, the form hasn't got the right enctype", E_USER_ERROR);
		}
		if(!isset($tmpFile['size'])) {
			return;
		}
		
		$base = BASE_PATH;
		// $parentFolder = Folder::findOrMake("Uploads");

		// Generate default filename
		$nameFilter = FileNameFilter::create();
		$file = $nameFilter->filter($tmpFile['name']);
		while($file[0] == '_' || $file[0] == '.') {
			$file = substr($file, 1);
		}

		$file = $this->RelativePath . $file;
		Filesystem::makeFolder(dirname("$base/$file"));
		
		$doubleBarrelledExts = array('.gz', '.bz', '.bz2');
		
		$ext = "";
		if(preg_match('/^(.*)(\.[^.]+)$/', $file, $matches)) {
			$file = $matches[1];
			$ext = $matches[2];
			// Special case for double-barrelled 
			if(in_array($ext, $doubleBarrelledExts) && preg_match('/^(.*)(\.[^.]+)$/', $file, $matches)) {
				$file = $matches[1];
				$ext = $matches[2] . $ext;
			}
		}
		$origFile = $file;

		$i = 1;
		while(file_exists("$base/$file$ext")) {
			$i++;
			$oldFile = $file;
			
			if(strpos($file, '.') !== false) {
				$file = preg_replace('/[0-9]*(\.[^.]+$)/', $i . '\\1', $file);
			} elseif(strpos($file, '_') !== false) {
				$file = preg_replace('/_([^_]+$)/', '_' . $i, $file);
			} else {
				$file .= '_'.$i;
			}

			if($oldFile == $file && $i > 2) user_error("Couldn't fix $file$ext with $i", E_USER_ERROR);
		}
		
		if (move_uploaded_file($tmpFile['tmp_name'], "$base/$file$ext")) {
			// Update with the new image
			return $this->constructChild(basename($file . $ext));
		} else {
			if(!file_exists($tmpFile['tmp_name'])) user_error("Folder::addUploadToFolder: '$tmpFile[tmp_name]' doesn't exist", E_USER_ERROR);
			else user_error("Folder::addUploadToFolder: Couldn't copy '$tmpFile[tmp_name]' to '$base/$file$ext'", E_USER_ERROR);
			return false;
		}
	}
开发者ID:redema,项目名称:sapphire,代码行数:65,代码来源:Folder.php

示例13: setName

 /**
  * Setter function for Name. Automatically sets a default title,
  * and removes characters that might be invalid on the filesystem.
  * Also adds a suffix to the name if the filename already exists
  * on the filesystem, and is associated to a different {@link File} database record
  * in the same folder. This means "myfile.jpg" might become "myfile-1.jpg".
  * 
  * Does not change the filesystem itself, please use {@link write()} for this.
  * 
  * @param String $name
  */
 function setName($name)
 {
     $oldName = $this->Name;
     // It can't be blank, default to Title
     if (!$name) {
         $name = $this->Title;
     }
     // Fix illegal characters
     $filter = FileNameFilter::create();
     $name = $filter->filter($name);
     // We might have just turned it blank, so check again.
     if (!$name) {
         $name = 'new-folder';
     }
     // If it's changed, check for duplicates
     if ($oldName && $oldName != $name) {
         $base = pathinfo($name, PATHINFO_BASENAME);
         $ext = self::get_file_extension($name);
         $suffix = 1;
         while (DataObject::get_one("File", "\"Name\" = '" . Convert::raw2sql($name) . "' AND \"ParentID\" = " . (int) $this->ParentID)) {
             $suffix++;
             $name = "{$base}-{$suffix}{$ext}";
         }
     }
     // Update title
     if (!$this->getField('Title')) {
         $this->__set('Title', str_replace(array('-', '_'), ' ', preg_replace('/\\.[^.]+$/', '', $name)));
     }
     // Update actual field value
     $this->setField('Name', $name);
     // Ensure that the filename is updated as well (only in-memory)
     // Important: Circumvent the getter to avoid infinite loops
     $this->setField('Filename', $this->getRelativePath());
     return $this->getField('Name');
 }
开发者ID:nzjoel,项目名称:sapphire,代码行数:46,代码来源:File.php

示例14: getValidFilename

 /**
  * Given a temporary file and upload path, validate the file and determine the
  * value of the 'Filename' tuple that should be used to store this asset.
  *
  * @param array $tmpFile
  * @param string $folderPath
  * @return string|false Value of filename tuple, or false if invalid
  */
 protected function getValidFilename($tmpFile, $folderPath = null)
 {
     if (!is_array($tmpFile)) {
         throw new InvalidArgumentException("Upload::load() Not passed an array.  Most likely, the form hasn't got the right enctype");
     }
     // Validate
     $this->clearErrors();
     $valid = $this->validate($tmpFile);
     if (!$valid) {
         return false;
     }
     // Clean filename
     if (!$folderPath) {
         $folderPath = $this->config()->uploads_folder;
     }
     $nameFilter = FileNameFilter::create();
     $file = $nameFilter->filter($tmpFile['name']);
     $filename = basename($file);
     if ($folderPath) {
         $filename = File::join_paths($folderPath, $filename);
     }
     return $filename;
 }
开发者ID:assertchris,项目名称:silverstripe-framework,代码行数:31,代码来源:Upload.php

示例15: generateExportFileData

 /**
  * Generate export fields for Excel.
  *
  * @param GridField $gridField
  * @return PHPExcel
  */
 public function generateExportFileData($gridField)
 {
     $class = $gridField->getModelClass();
     $columns = $this->exportColumns ? $this->exportColumns : ExcelImportExport::exportFieldsForClass($class);
     $fileData = '';
     $singl = singleton($class);
     $singular = $class ? $singl->i18n_singular_name() : '';
     $plural = $class ? $singl->i18n_plural_name() : '';
     $filter = new FileNameFilter();
     if ($this->exportName) {
         $this->exportName = $filter->filter($this->exportName);
     } else {
         $this->exportName = $filter->filter('export-' . $plural);
     }
     $excel = new PHPExcel();
     $excelProperties = $excel->getProperties();
     $excelProperties->setTitle($this->exportName);
     $sheet = $excel->getActiveSheet();
     if ($plural) {
         $sheet->setTitle($plural);
     }
     $row = 1;
     $col = 0;
     if ($this->hasHeader) {
         $headers = array();
         // determine the headers. If a field is callable (e.g. anonymous function) then use the
         // source name as the header instead
         foreach ($columns as $columnSource => $columnHeader) {
             $headers[] = !is_string($columnHeader) && is_callable($columnHeader) ? $columnSource : $columnHeader;
         }
         foreach ($headers as $header) {
             $sheet->setCellValueByColumnAndRow($col, $row, $header);
             $col++;
         }
         $endcol = PHPExcel_Cell::stringFromColumnIndex($col - 1);
         $sheet->setAutoFilter("A1:{$endcol}1");
         $sheet->getStyle("A1:{$endcol}1")->getFont()->setBold(true);
         $col = 0;
         $row++;
     }
     // Autosize
     $cellIterator = $sheet->getRowIterator()->current()->getCellIterator();
     try {
         $cellIterator->setIterateOnlyExistingCells(true);
     } catch (Exception $ex) {
         continue;
     }
     foreach ($cellIterator as $cell) {
         $sheet->getColumnDimension($cell->getColumn())->setAutoSize(true);
     }
     //Remove GridFieldPaginator as we're going to export the entire list.
     $gridField->getConfig()->removeComponentsByType('GridFieldPaginator');
     $items = $gridField->getManipulatedList();
     // @todo should GridFieldComponents change behaviour based on whether others are available in the config?
     foreach ($gridField->getConfig()->getComponents() as $component) {
         if ($component instanceof GridFieldFilterHeader || $component instanceof GridFieldSortableHeader) {
             $items = $component->getManipulatedData($gridField, $items);
         }
     }
     foreach ($items->limit(null) as $item) {
         if (!$item->hasMethod('canView') || $item->canView()) {
             foreach ($columns as $columnSource => $columnHeader) {
                 if (!is_string($columnHeader) && is_callable($columnHeader)) {
                     if ($item->hasMethod($columnSource)) {
                         $relObj = $item->{$columnSource}();
                     } else {
                         $relObj = $item->relObject($columnSource);
                     }
                     $value = $columnHeader($relObj);
                 } else {
                     $value = $gridField->getDataFieldValue($item, $columnSource);
                     if ($value === null) {
                         $value = $gridField->getDataFieldValue($item, $columnHeader);
                     }
                 }
                 $value = str_replace(array("\r", "\n"), "\n", $value);
                 $sheet->setCellValueByColumnAndRow($col, $row, $value);
                 $col++;
             }
         }
         if ($item->hasMethod('destroy')) {
             $item->destroy();
         }
         $col = 0;
         $row++;
     }
     return $excel;
 }
开发者ID:lekoala,项目名称:silverstripe-excel-import-export,代码行数:94,代码来源:ExcelGridFieldExportButton.php


注:本文中的FileNameFilter类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。