Contao\Dbafs::addResource PHP Метод

addResource() публичный статический Метод

Adds a file or folder with its parent folders
public static addResource ( string $strResource, boolean $blnUpdateFolders = true ) : FilesModel
$strResource string The path to the file or folder
$blnUpdateFolders boolean If true, the parent folders will be updated
Результат FilesModel The files model
    public static function addResource($strResource, $blnUpdateFolders = true)
    {
        $strUploadPath = \Config::get('uploadPath') . '/';
        // Remove trailing slashes (see #5707)
        if (substr($strResource, -1) == '/') {
            $strResource = substr($strResource, 0, -1);
        }
        // Normalize the path (see #6034)
        $strResource = str_replace(array('\\', '//'), '/', $strResource);
        // The resource does not exist or lies outside the upload directory
        if ($strResource == '' || strncmp($strResource, $strUploadPath, strlen($strUploadPath)) !== 0 || !file_exists(TL_ROOT . '/' . $strResource)) {
            throw new \InvalidArgumentException("Invalid resource {$strResource}");
        }
        $objModel = \FilesModel::findByPath($strResource);
        // Return the model if it exists already
        if ($objModel !== null) {
            $objFile = $objModel->type == 'folder' ? new \Folder($objModel->path) : new \File($objModel->path);
            // Update the timestamp and file hash (see #4818, #7828)
            if ($objModel->hash != $objFile->hash) {
                $objModel->tstamp = time();
                $objModel->hash = $objFile->hash;
                $objModel->save();
            }
            return $objModel;
        }
        $arrPaths = array();
        $arrChunks = explode('/', $strResource);
        $strPath = array_shift($arrChunks);
        $arrPids = array($strPath => null);
        $arrUpdate = array($strResource);
        $objDatabase = \Database::getInstance();
        // Build the paths
        while (count($arrChunks)) {
            $strPath .= '/' . array_shift($arrChunks);
            $arrPaths[] = $strPath;
        }
        unset($arrChunks);
        $objModels = \FilesModel::findMultipleByPaths($arrPaths);
        // Unset the entries in $arrPaths if the DB entry exists
        if ($objModels !== null) {
            while ($objModels->next()) {
                if (($i = array_search($objModels->path, $arrPaths)) !== false) {
                    unset($arrPaths[$i]);
                    $arrPids[$objModels->path] = $objModels->uuid;
                }
            }
        }
        $arrPaths = array_values($arrPaths);
        // If the resource is a folder, also add its contents
        if (is_dir(TL_ROOT . '/' . $strResource)) {
            /** @var \SplFileInfo[] $objFiles */
            $objFiles = new \RecursiveIteratorIterator(new \Filter\SyncExclude(new \RecursiveDirectoryIterator(TL_ROOT . '/' . $strResource, \FilesystemIterator::UNIX_PATHS | \FilesystemIterator::FOLLOW_SYMLINKS | \FilesystemIterator::SKIP_DOTS)), \RecursiveIteratorIterator::SELF_FIRST);
            // Add the relative path
            foreach ($objFiles as $objFile) {
                $strRelpath = str_replace(TL_ROOT . '/', '', $objFile->getPathname());
                if ($objFile->isDir()) {
                    $arrUpdate[] = $strRelpath;
                }
                $arrPaths[] = $strRelpath;
            }
        }
        $objReturn = null;
        // Create the new resources
        foreach ($arrPaths as $strPath) {
            if (basename($strPath) == '.public') {
                continue;
            }
            $strParent = dirname($strPath);
            // The parent ID should be in $arrPids
            // Do not use isset() here, because the PID can be null
            if (array_key_exists($strParent, $arrPids)) {
                $strPid = $arrPids[$strParent];
            } else {
                throw new \Exception("No parent entry for {$strParent}");
            }
            // Create the file or folder
            if (is_file(TL_ROOT . '/' . $strPath)) {
                $objFile = new \File($strPath);
                $objModel = new \FilesModel();
                $objModel->pid = $strPid;
                $objModel->tstamp = time();
                $objModel->name = $objFile->name;
                $objModel->type = 'file';
                $objModel->path = $objFile->path;
                $objModel->extension = $objFile->extension;
                $objModel->hash = $objFile->hash;
                $objModel->uuid = $objDatabase->getUuid();
                $objModel->save();
                $arrPids[$objFile->path] = $objModel->uuid;
            } else {
                $objFolder = new \Folder($strPath);
                $objModel = new \FilesModel();
                $objModel->pid = $strPid;
                $objModel->tstamp = time();
                $objModel->name = $objFolder->name;
                $objModel->type = 'folder';
                $objModel->path = $objFolder->path;
                $objModel->extension = '';
                $objModel->hash = $objFolder->hash;
                $objModel->uuid = $objDatabase->getUuid();
                $objModel->save();
                $arrPids[$objFolder->path] = $objModel->uuid;
            }
            // Store the model to be returned (see #5979)
            if ($objModel->path == $strResource) {
                $objReturn = $objModel;
            }
        }
        // Update the folder hashes
        if ($blnUpdateFolders) {
            static::updateFolderHashes($arrUpdate);
        }
        return $objReturn;
    }

Usage Example

Пример #1
0
 /**
  * Ajax actions that do require a data container object
  *
  * @param DataContainer $dc
  *
  * @throws NoContentResponseException
  * @throws ResponseException
  * @throws BadRequestHttpException
  */
 public function executePostActions(DataContainer $dc)
 {
     header('Content-Type: text/html; charset=' . \Config::get('characterSet'));
     // Bypass any core logic for non-core drivers (see #5957)
     if (!$dc instanceof DC_File && !$dc instanceof DC_Folder && !$dc instanceof DC_Table) {
         $this->executePostActionsHook($dc);
         throw new NoContentResponseException();
     }
     switch ($this->strAction) {
         // Load nodes of the page structure tree
         case 'loadStructure':
             throw new ResponseException($this->convertToResponse($dc->ajaxTreeView($this->strAjaxId, intval(\Input::post('level')))));
             // Load nodes of the file manager tree
         // Load nodes of the file manager tree
         case 'loadFileManager':
             throw new ResponseException($this->convertToResponse($dc->ajaxTreeView(\Input::post('folder', true), intval(\Input::post('level')))));
             // Load nodes of the page tree
         // Load nodes of the page tree
         case 'loadPagetree':
             $varValue = null;
             $strField = $dc->field = \Input::post('name');
             // Call the load_callback
             if (is_array($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField]['load_callback'])) {
                 foreach ($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField]['load_callback'] as $callback) {
                     if (is_array($callback)) {
                         $this->import($callback[0]);
                         $varValue = $this->{$callback[0]}->{$callback[1]}($varValue, $dc);
                     } elseif (is_callable($callback)) {
                         $varValue = $callback($varValue, $dc);
                     }
                 }
             }
             /** @var PageSelector $strClass */
             $strClass = $GLOBALS['BE_FFL']['pageSelector'];
             /** @var PageSelector $objWidget */
             $objWidget = new $strClass($strClass::getAttributesFromDca($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField], $dc->field, $varValue, $strField, $dc->table, $dc));
             throw new ResponseException($this->convertToResponse($objWidget->generateAjax($this->strAjaxId, \Input::post('field'), intval(\Input::post('level')))));
             // Load nodes of the file tree
         // Load nodes of the file tree
         case 'loadFiletree':
             $varValue = null;
             $strField = $dc->field = \Input::post('name');
             // Call the load_callback
             if (is_array($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField]['load_callback'])) {
                 foreach ($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField]['load_callback'] as $callback) {
                     if (is_array($callback)) {
                         $this->import($callback[0]);
                         $varValue = $this->{$callback[0]}->{$callback[1]}($varValue, $dc);
                     } elseif (is_callable($callback)) {
                         $varValue = $callback($varValue, $dc);
                     }
                 }
             }
             /** @var FileSelector $strClass */
             $strClass = $GLOBALS['BE_FFL']['fileSelector'];
             /** @var FileSelector $objWidget */
             $objWidget = new $strClass($strClass::getAttributesFromDca($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField], $dc->field, $varValue, $strField, $dc->table, $dc));
             // Load a particular node
             if (\Input::post('folder', true) != '') {
                 throw new ResponseException($this->convertToResponse($objWidget->generateAjax(\Input::post('folder', true), \Input::post('field'), intval(\Input::post('level')))));
             }
             throw new ResponseException($this->convertToResponse($objWidget->generate()));
             // Reload the page/file picker
         // Reload the page/file picker
         case 'reloadPagetree':
         case 'reloadFiletree':
             $intId = \Input::get('id');
             $strField = $dc->inputName = \Input::post('name');
             // Handle the keys in "edit multiple" mode
             if (\Input::get('act') == 'editAll') {
                 $intId = preg_replace('/.*_([0-9a-zA-Z]+)$/', '$1', $strField);
                 $strField = preg_replace('/(.*)_[0-9a-zA-Z]+$/', '$1', $strField);
             }
             $dc->field = $strField;
             // The field does not exist
             if (!isset($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField])) {
                 $this->log('Field "' . $strField . '" does not exist in DCA "' . $dc->table . '"', __METHOD__, TL_ERROR);
                 throw new BadRequestHttpException('Bad request');
             }
             $objRow = null;
             $varValue = null;
             // Load the value
             if (\Input::get('act') != 'overrideAll') {
                 if ($GLOBALS['TL_DCA'][$dc->table]['config']['dataContainer'] == 'File') {
                     $varValue = \Config::get($strField);
                 } elseif ($intId > 0 && $this->Database->tableExists($dc->table)) {
                     $objRow = $this->Database->prepare("SELECT * FROM " . $dc->table . " WHERE id=?")->execute($intId);
                     // The record does not exist
                     if ($objRow->numRows < 1) {
                         $this->log('A record with the ID "' . $intId . '" does not exist in table "' . $dc->table . '"', __METHOD__, TL_ERROR);
                         throw new BadRequestHttpException('Bad request');
                     }
                     $varValue = $objRow->{$strField};
                     $dc->activeRecord = $objRow;
                 }
             }
             // Call the load_callback
             if (is_array($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField]['load_callback'])) {
                 foreach ($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField]['load_callback'] as $callback) {
                     if (is_array($callback)) {
                         $this->import($callback[0]);
                         $varValue = $this->{$callback[0]}->{$callback[1]}($varValue, $dc);
                     } elseif (is_callable($callback)) {
                         $varValue = $callback($varValue, $dc);
                     }
                 }
             }
             // Set the new value
             $varValue = \Input::post('value', true);
             $strKey = $this->strAction == 'reloadPagetree' ? 'pageTree' : 'fileTree';
             // Convert the selected values
             if ($varValue != '') {
                 $varValue = \StringUtil::trimsplit("\t", $varValue);
                 // Automatically add resources to the DBAFS
                 if ($strKey == 'fileTree') {
                     foreach ($varValue as $k => $v) {
                         if (\Dbafs::shouldBeSynchronized($v)) {
                             $objFile = \FilesModel::findByPath($v);
                             if ($objFile === null) {
                                 $objFile = \Dbafs::addResource($v);
                             }
                             $varValue[$k] = $objFile->uuid;
                         }
                     }
                 }
                 $varValue = serialize($varValue);
             }
             /** @var FileTree|PageTree $strClass */
             $strClass = $GLOBALS['BE_FFL'][$strKey];
             /** @var FileTree|PageTree $objWidget */
             $objWidget = new $strClass($strClass::getAttributesFromDca($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField], $dc->inputName, $varValue, $strField, $dc->table, $dc));
             throw new ResponseException($this->convertToResponse($objWidget->generate()));
             // Feature/unfeature an element
         // Feature/unfeature an element
         case 'toggleFeatured':
             if (class_exists($dc->table, false)) {
                 $dca = new $dc->table();
                 if (method_exists($dca, 'toggleFeatured')) {
                     $dca->toggleFeatured(\Input::post('id'), \Input::post('state') == 1 ? true : false);
                 }
             }
             throw new NoContentResponseException();
             // Toggle subpalettes
         // Toggle subpalettes
         case 'toggleSubpalette':
             $this->import('BackendUser', 'User');
             // Check whether the field is a selector field and allowed for regular users (thanks to Fabian Mihailowitsch) (see #4427)
             if (!is_array($GLOBALS['TL_DCA'][$dc->table]['palettes']['__selector__']) || !in_array(\Input::post('field'), $GLOBALS['TL_DCA'][$dc->table]['palettes']['__selector__']) || $GLOBALS['TL_DCA'][$dc->table]['fields'][\Input::post('field')]['exclude'] && !$this->User->hasAccess($dc->table . '::' . \Input::post('field'), 'alexf')) {
                 $this->log('Field "' . \Input::post('field') . '" is not an allowed selector field (possible SQL injection attempt)', __METHOD__, TL_ERROR);
                 throw new BadRequestHttpException('Bad request');
             }
             if ($dc instanceof DC_Table) {
                 if (\Input::get('act') == 'editAll') {
                     $this->strAjaxId = preg_replace('/.*_([0-9a-zA-Z]+)$/', '$1', \Input::post('id'));
                     $this->Database->prepare("UPDATE " . $dc->table . " SET " . \Input::post('field') . "='" . (intval(\Input::post('state') == 1) ? 1 : '') . "' WHERE id=?")->execute($this->strAjaxId);
                     if (\Input::post('load')) {
                         echo $dc->editAll($this->strAjaxId, \Input::post('id'));
                     }
                 } else {
                     $this->Database->prepare("UPDATE " . $dc->table . " SET " . \Input::post('field') . "='" . (intval(\Input::post('state') == 1) ? 1 : '') . "' WHERE id=?")->execute($dc->id);
                     if (\Input::post('load')) {
                         throw new ResponseException($this->convertToResponse($dc->edit(false, \Input::post('id'))));
                     }
                 }
             } elseif ($dc instanceof DC_File) {
                 $val = intval(\Input::post('state') == 1) ? true : false;
                 \Config::persist(\Input::post('field'), $val);
                 if (\Input::post('load')) {
                     \Config::set(\Input::post('field'), $val);
                     throw new ResponseException($this->convertToResponse($dc->edit(false, \Input::post('id'))));
                 }
             }
             throw new NoContentResponseException();
             // DropZone file upload
         // DropZone file upload
         case 'fileupload':
             $dc->move();
             throw new NoContentResponseException();
             // HOOK: pass unknown actions to callback functions
         // HOOK: pass unknown actions to callback functions
         default:
             $this->executePostActionsHook($dc);
             throw new NoContentResponseException();
     }
 }
All Usage Examples Of Contao\Dbafs::addResource