本文整理汇总了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();
}
}
}
示例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!");
}
示例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;
}
示例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;
}
示例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 = '';
}
}
}
示例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;
}
}
示例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;
}
}
示例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);
}
}
示例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));
}
示例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;
}
}
示例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;
}
}
示例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');
}
示例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;
}
示例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;
}