The normalization does the following work:
- Convert all directory separators into DIRECTORY_SEPARATOR (e.g. "\a/b\c" becomes "/a/b/c")
- Remove trailing directory separators (e.g. "/a/b/c/" becomes "/a/b/c")
- Turn multiple consecutive slashes into a single one (e.g. "/a///b/c" becomes "/a/b/c")
- Remove ".." and "." based on their meanings (e.g. "/a/./b/../c" becomes "/a/c")
/** * Verifica si existe un directorio, si no existe lo crea * @param $directorio * @throws \yii\base\Exception */ public static function existeDirectorio($directorio) { $base = BaseFileHelper::normalizePath(Yii::getAlias('@libreria') . '/imagenes/' . $directorio); if (!file_exists($base)) { BaseFileHelper::createDirectory($base, 0750, true); } }
/** * После сохранения */ public function afterSave() { $this->path = null; //Сохраняем файл foreach ($this->fields as $field) { $isWeb = $this->_webFile[$field]; $file = null; if ($isWeb || ($file = UploadedFile::getInstance($this->owner, $field))) { //Директория для сохранения $path = $this->getPath($field); $files = BaseFileHelper::findFiles($path); foreach ($files as $cFile) { @unlink($cFile); } $fileName = self::normalize($isWeb ? $this->_names[$field] : $file->name); $filePath = BaseFileHelper::normalizePath($path . '/' . $fileName); // d($filePath); if ($this->_webFile[$field]) { $result = @copy($this->_webFile[$field], $filePath); if (!$result) { $fileName = ''; } } else { $file->saveAs($path . '/' . $fileName); chmod($filePath, 0666); } $this->owner->updateAttributes(array($field => $fileName)); } } $this->setAttach(); }
/** * generate the abosolute path for a uploaded media file where to store the file. * The folder structure is not the same as the virtual structure that is shown in the media browser. Instead for a new uploaded file a folder following the pattern '.../YYYY/MM/DD' will be created. * Uses the value of @see Frontend->getMediarepositoryBasePath() * * @param UploadedFile $file * @return string the full path to the storage folder for this file (note: the folder itself will NOT only be created automatically if the optional parameter createFolder is set to true!) */ private function getFullUploadPathForFile($file) { $currentDate = new \DateTime(); $cleanedFileName = str_replace(' ', '_', $file->name); $formatedPath = $currentDate->format('Y/m/d'); $targetFolder = BaseFileHelper::normalizePath($this->module->getMediarepositoryBasePath() . DIRECTORY_SEPARATOR . $formatedPath) . DIRECTORY_SEPARATOR; $fullFilePath = $targetFolder . $cleanedFileName; //check if folder exists, create if not if (!file_exists($targetFolder)) { if (!mkdir($targetFolder, 0755, true)) { throw new \Exception('Could not create target folder: ' . $targetFolder); } } $conflictCounter = 1; while (file_exists($fullFilePath)) { $fullFilePath = $targetFolder . str_replace(' ', '_', $file->baseName) . '_' . $conflictCounter . '.' . $file->extension; $conflictCounter++; } return $fullFilePath; }