/** * Parses the widget and returns either the uuid of the file or false if moving the file failed * * @param $widget * @return mixed * @throws \Exception */ public function parseWidget($widget) { /** * Check if file in session exists */ if (!isset($_SESSION['FILES'][$this->field->getColName()])) { return false; } /** * Rename the file (move) to the new location with the new name */ $ext = pathinfo($_SESSION['FILES'][$this->field->getColName()]['name'], PATHINFO_EXTENSION); $name = $this->field->uploadPath . '/' . $this->item->get('id') . '_' . $this->field->getColName() . '.' . $ext; if (move_uploaded_file($_SESSION['FILES'][$this->field->getColName()]['tmp_name'], TL_ROOT . '/' . $name)) { /** * Add File to the DBAFS */ $dbafsFile = \Dbafs::addResource($name); /** * Remove file from session */ unset($_SESSION['FILES'][$this->field->getColName()]); /** * Return UUID */ return $dbafsFile->uuid; } return false; }
/** * add uuids to tl_gallery_creator_pictures version added in 4.8.0 */ public static function addUuids() { // add field if (!\Database::getInstance()->fieldExists('uuid', 'tl_gallery_creator_pictures')) { \Database::getInstance()->query("ALTER TABLE `tl_gallery_creator_pictures` ADD `uuid` BINARY(16) NULL"); } $objDB = \Database::getInstance()->execute("SELECT * FROM tl_gallery_creator_pictures WHERE uuid IS NULL"); while ($objDB->next()) { if ($objDB->path == '') { continue; } if (is_file(TL_ROOT . '/' . $objDB->path)) { \Dbafs::addResource($objDB->path); } else { continue; } $oFile = new \File($objDB->path); $oFile->close(); $fileModel = $oFile->getModel(); if (\Validator::isUuid($fileModel->uuid)) { \Database::getInstance()->prepare("UPDATE tl_gallery_creator_pictures SET uuid=? WHERE id=?")->execute($fileModel->uuid, $objDB->id); $_SESSION["TL_CONFIRM"][] = "Added a valid file-uuid into tl_gallery_creator_pictures.uuid ID " . $objDB->id . ". Please check if all the galleries are running properly."; } } }
public function __construct() { parent::__construct(); $this->import('BackendUser', 'User'); $this->import('Files'); //relativer Pfad zum Upload-Dir fuer safe-mode-hack $this->uploadPath = GALLERY_CREATOR_UPLOAD_PATH; //parse Backend Template Hook registrieren $GLOBALS['TL_HOOKS']['parseBackendTemplate'][] = array('tl_gallery_creator_pictures', 'myParseBackendTemplate'); // set the referer when redirecting from import files from the filesystem if (\Input::get('filesImported')) { $this->import('Session'); $session = $this->Session->get('referer'); $session[TL_REFERER_ID]['current'] = 'contao/main.php?do=gallery_creator'; $this->Session->set('referer', $session); } switch (Input::get('mode')) { case 'imagerotate': $objPic = GalleryCreatorPicturesModel::findById(Input::get('imgId')); $objFile = FilesModel::findByUuid($objPic->uuid); if ($objFile !== null) { // Rotate image anticlockwise $angle = 270; GalleryCreator\GcHelpers::imageRotate($objFile->path, $angle); Dbafs::addResource($objFile->path, true); $this->redirect('contao/main.php?do=gallery_creator&table=tl_gallery_creator_pictures&id=' . Input::get('id')); } break; default: break; } //end switch switch (Input::get('act')) { case 'create': //Neue Bilder können ausschliesslich über einen Bildupload realisiert werden $this->Redirect('contao/main.php?do=gallery_creator&table=tl_gallery_creator_pictures&id=' . Input::get('pid')); break; case 'select': if (!$this->User->isAdmin) { // only list pictures where user is owner if (!$GLOBALS['TL_CONFIG']['gc_disable_backend_edit_protection']) { $GLOBALS['TL_DCA']['tl_gallery_creator_pictures']['list']['sorting']['filter'] = array(array('owner=?', $this->User->id)); } } break; default: break; } //end switch // get the source album when cuting pictures from one album to an other if (Input::get('act') == 'paste' && Input::get('mode') == 'cut') { $objPicture = GalleryCreatorPicturesModel::findByPk(Input::get('id')); if ($objPicture !== null) { $_SESSION['gallery_creator']['SOURCE_ALBUM_ID'] = $objPicture->pid; } } }
/** * Searches through the DCA and converts a file path to an UUID * if the DCA field is a single fileTree input */ public function storeFormData($arrSet, \Form $objForm) { // get table $table = $objForm->targetTable; // load DCA $this->loadDataContainer($table); // check if DCA exists for target table if (!is_array($GLOBALS['TL_DCA'][$table])) { return $arrSet; } // go through each field foreach ($arrSet as $field => $value) { // check if field exists in DCA if (!isset($GLOBALS['TL_DCA'][$table]['fields'][$field])) { continue; } // get DCA for field $dcaField = $GLOBALS['TL_DCA'][$table]['fields'][$field]; // check for single fileTree inputType if ($dcaField['inputType'] != 'fileTree') { continue; } // check if value is array if (is_array($value)) { // DCA field must be enabled for multiple selection if (!$dcaField['eval']['multiple']) { continue; } // prepare UUID array $uuids = array(); // go through each file foreach ($value as $file) { // check if file exists if (file_exists(TL_ROOT . '/' . $file)) { // get the file object to retrieve UUID $uuids[] = \Dbafs::addResource($file)->uuid; } } // set the UUID array $arrSet[$field] = serialize($uuids); } elseif (file_exists(TL_ROOT . '/' . $value)) { // get the file object to retrieve UUID $objFile = \Dbafs::addResource($value); // set the UUID $arrSet[$field] = $dcaField['eval']['multiple'] ? serialize(array($objFile->uuid)) : $objFile->uuid; } } // return result return $arrSet; }
/** * Run the controller and parse the template */ public function run() { if ($this->strFile == '') { die('No file given'); } // Make sure there are no attempts to hack the file system if (preg_match('@^\\.+@i', $this->strFile) || preg_match('@\\.+/@i', $this->strFile) || preg_match('@(://)+@i', $this->strFile)) { die('Invalid file name'); } // Limit preview to the files directory if (!preg_match('@^' . preg_quote(\Config::get('uploadPath'), '@') . '@i', $this->strFile)) { die('Invalid path'); } // Check whether the file exists if (!file_exists(TL_ROOT . '/' . $this->strFile)) { die('File not found'); } // Check whether the file is mounted (thanks to Marko Cupic) if (!$this->User->hasAccess($this->strFile, 'filemounts')) { die('Permission denied'); } // Open the download dialogue if (\Input::get('download')) { $objFile = new \File($this->strFile, true); $objFile->sendToBrowser(); } /** @var \BackendTemplate|object $objTemplate */ $objTemplate = new \BackendTemplate('be_popup'); // Add the resource (see #6880) if (($objModel = \FilesModel::findByPath($this->strFile)) === null) { if (\Dbafs::shouldBeSynchronized($this->strFile)) { $objModel = \Dbafs::addResource($this->strFile); } } if ($objModel !== null) { $objTemplate->uuid = \StringUtil::binToUuid($objModel->uuid); // see #5211 } // Add the file info if (is_dir(TL_ROOT . '/' . $this->strFile)) { $objFile = new \Folder($this->strFile, true); $objTemplate->filesize = $this->getReadableSize($objFile->size) . ' (' . number_format($objFile->size, 0, $GLOBALS['TL_LANG']['MSC']['decimalSeparator'], $GLOBALS['TL_LANG']['MSC']['thousandsSeparator']) . ' Byte)'; } else { $objFile = new \File($this->strFile, true); // Image if ($objFile->isImage) { $objTemplate->isImage = true; $objTemplate->width = $objFile->width; $objTemplate->height = $objFile->height; $objTemplate->src = $this->urlEncode($this->strFile); } $objTemplate->href = ampersand(\Environment::get('request'), true) . '&download=1'; $objTemplate->filesize = $this->getReadableSize($objFile->filesize) . ' (' . number_format($objFile->filesize, 0, $GLOBALS['TL_LANG']['MSC']['decimalSeparator'], $GLOBALS['TL_LANG']['MSC']['thousandsSeparator']) . ' Byte)'; } $objTemplate->icon = $objFile->icon; $objTemplate->mime = $objFile->mime; $objTemplate->ctime = \Date::parse(\Config::get('datimFormat'), $objFile->ctime); $objTemplate->mtime = \Date::parse(\Config::get('datimFormat'), $objFile->mtime); $objTemplate->atime = \Date::parse(\Config::get('datimFormat'), $objFile->atime); $objTemplate->path = specialchars($this->strFile); $objTemplate->theme = \Backend::getTheme(); $objTemplate->base = \Environment::get('base'); $objTemplate->language = $GLOBALS['TL_LANGUAGE']; $objTemplate->title = specialchars($this->strFile); $objTemplate->charset = \Config::get('characterSet'); $objTemplate->headline = basename(utf8_convert_encoding($this->strFile, \Config::get('characterSet'))); $objTemplate->label_uuid = $GLOBALS['TL_LANG']['MSC']['fileUuid']; $objTemplate->label_imagesize = $GLOBALS['TL_LANG']['MSC']['fileImageSize']; $objTemplate->label_filesize = $GLOBALS['TL_LANG']['MSC']['fileSize']; $objTemplate->label_ctime = $GLOBALS['TL_LANG']['MSC']['fileCreated']; $objTemplate->label_mtime = $GLOBALS['TL_LANG']['MSC']['fileModified']; $objTemplate->label_atime = $GLOBALS['TL_LANG']['MSC']['fileAccessed']; $objTemplate->label_path = $GLOBALS['TL_LANG']['MSC']['filePath']; $objTemplate->download = specialchars($GLOBALS['TL_LANG']['MSC']['fileDownload']); \Config::set('debugMode', false); $objTemplate->output(); }
/** * Synchronize the file system with the database * * @return string */ public function sync() { if (!$this->blnIsDbAssisted) { return ''; } $this->import('BackendUser', 'User'); $this->loadLanguageFile('tl_files'); // Check the permission to synchronize if (!$this->User->hasAccess('f6', 'fop')) { $this->log('Not enough permissions to synchronize the file system', __METHOD__, TL_ERROR); $this->redirect('contao/main.php?act=error'); } // Synchronize $strLog = \Dbafs::syncFiles(); // Show the results $arrMessages = array(); $arrCounts = array('Added' => 0, 'Changed' => 0, 'Unchanged' => 0, 'Moved' => 0, 'Deleted' => 0); // Read the log file $fh = fopen(TL_ROOT . '/' . $strLog, 'rb'); while (($buffer = fgets($fh)) !== false) { list($type, $file) = explode('] ', trim(substr($buffer, 1)), 2); // Add a message depending on the type switch ($type) { case 'Added': $arrMessages[] = '<p class="tl_new">' . sprintf($GLOBALS['TL_LANG']['tl_files']['syncAdded'], specialchars($file)) . '</p>'; break; case 'Changed': $arrMessages[] = '<p class="tl_info">' . sprintf($GLOBALS['TL_LANG']['tl_files']['syncChanged'], specialchars($file)) . '</p>'; break; case 'Unchanged': $arrMessages[] = '<p class="tl_confirm hidden">' . sprintf($GLOBALS['TL_LANG']['tl_files']['syncUnchanged'], specialchars($file)) . '</p>'; break; case 'Moved': list($source, $target) = explode(' to ', $file, 2); $arrMessages[] = '<p class="tl_info">' . sprintf($GLOBALS['TL_LANG']['tl_files']['syncMoved'], specialchars($source), specialchars($target)) . '</p>'; break; case 'Deleted': $arrMessages[] = '<p class="tl_error">' . sprintf($GLOBALS['TL_LANG']['tl_files']['syncDeleted'], specialchars($file)) . '</p>'; break; } ++$arrCounts[$type]; } // Close the log file unset($buffer); fclose($fh); // Confirm \Message::addConfirmation($GLOBALS['TL_LANG']['tl_files']['syncComplete']); $return = ' <div id="tl_buttons"> <a href="' . $this->getReferer(true) . '" class="header_back" title="' . specialchars($GLOBALS['TL_LANG']['MSC']['backBTTitle']) . '" accesskey="b" onclick="Backend.getScrollOffset()">' . $GLOBALS['TL_LANG']['MSC']['backBT'] . '</a> </div> ' . \Message::generate() . ' <div id="sync-results"> <p class="left">' . sprintf($GLOBALS['TL_LANG']['tl_files']['syncResult'], \System::getFormattedNumber($arrCounts['Added'], 0), \System::getFormattedNumber($arrCounts['Changed'], 0), \System::getFormattedNumber($arrCounts['Unchanged'], 0), \System::getFormattedNumber($arrCounts['Moved'], 0), \System::getFormattedNumber($arrCounts['Deleted'], 0)) . '</p> <p class="right"><input type="checkbox" id="show-hidden" class="tl_checkbox" onclick="Backend.toggleUnchanged()"> <label for="show-hidden">' . $GLOBALS['TL_LANG']['tl_files']['syncShowUnchanged'] . '</label></p> <div class="clear"></div> </div> <div class="tl_message nobg" id="result-list" style="margin-bottom:2em">'; // Add the messages foreach ($arrMessages as $strMessage) { $return .= "\n " . $strMessage; } $return .= ' </div> <div class="tl_submit_container"> <a href="' . $this->getReferer(true) . '" class="tl_submit" style="display:inline-block">' . $GLOBALS['TL_LANG']['MSC']['continue'] . '</a> </div> '; return $return; }
/** * Extract the theme files and write the data to the database * * @param array $arrFiles * @param array $arrDbFields */ protected function extractThemeFiles($arrFiles, $arrDbFields) { foreach ($arrFiles as $strZipFile) { $xml = null; // Open the archive $objArchive = new \ZipReader($strZipFile); // Extract all files while ($objArchive->next()) { // Load the XML file if ($objArchive->file_name == 'theme.xml') { $xml = new \DOMDocument(); $xml->preserveWhiteSpace = false; $xml->loadXML($objArchive->unzip()); continue; } // Limit file operations to files and the templates directory if (strncmp($objArchive->file_name, 'files/', 6) !== 0 && strncmp($objArchive->file_name, 'tl_files/', 9) !== 0 && strncmp($objArchive->file_name, 'templates/', 10) !== 0) { \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['invalidFile'], $objArchive->file_name)); continue; } // Extract the files try { \File::putContent($this->customizeUploadPath($objArchive->file_name), $objArchive->unzip()); } catch (\Exception $e) { \Message::addError($e->getMessage()); } } // Continue if there is no XML file if (!$xml instanceof \DOMDocument) { \Message::addError(sprintf($GLOBALS['TL_LANG']['tl_theme']['missing_xml'], basename($strZipFile))); continue; } $arrMapper = array(); $tables = $xml->getElementsByTagName('table'); $arrNewFolders = array(); // Extract the folder names from the XML file for ($i = 0; $i < $tables->length; $i++) { if ($tables->item($i)->getAttribute('name') == 'tl_theme') { $fields = $tables->item($i)->childNodes->item(0)->childNodes; for ($k = 0; $k < $fields->length; $k++) { if ($fields->item($k)->getAttribute('name') == 'folders') { $arrNewFolders = deserialize($fields->item($k)->nodeValue); break; } } break; } } // Sync the new folder(s) if (!empty($arrNewFolders) && is_array($arrNewFolders)) { foreach ($arrNewFolders as $strFolder) { \Dbafs::addResource($this->customizeUploadPath($strFolder)); } } // Lock the tables $arrLocks = array('tl_files' => 'WRITE', 'tl_theme' => 'WRITE', 'tl_style_sheet' => 'WRITE', 'tl_style' => 'WRITE', 'tl_module' => 'WRITE', 'tl_layout' => 'WRITE', 'tl_image_size' => 'WRITE', 'tl_image_size_item' => 'WRITE'); // Load the DCAs of the locked tables (see #7345) foreach (array_keys($arrLocks) as $table) { $this->loadDataContainer($table); } $this->Database->lockTables($arrLocks); // Get the current auto_increment values $tl_files = $this->Database->getNextId('tl_files'); $tl_theme = $this->Database->getNextId('tl_theme'); $tl_style_sheet = $this->Database->getNextId('tl_style_sheet'); $tl_style = $this->Database->getNextId('tl_style'); $tl_module = $this->Database->getNextId('tl_module'); $tl_layout = $this->Database->getNextId('tl_layout'); $tl_image_size = $this->Database->getNextId('tl_image_size'); $tl_image_size_item = $this->Database->getNextId('tl_image_size_item'); // Loop through the tables for ($i = 0; $i < $tables->length; $i++) { $rows = $tables->item($i)->childNodes; $table = $tables->item($i)->getAttribute('name'); // Skip invalid tables if (!in_array($table, array_keys($arrLocks))) { continue; } // Get the order fields $objDcaExtractor = \DcaExtractor::getInstance($table); $arrOrder = $objDcaExtractor->getOrderFields(); // Loop through the rows for ($j = 0; $j < $rows->length; $j++) { $set = array(); $fields = $rows->item($j)->childNodes; // Loop through the fields for ($k = 0; $k < $fields->length; $k++) { $value = $fields->item($k)->nodeValue; $name = $fields->item($k)->getAttribute('name'); // Skip NULL values if ($value == 'NULL') { continue; } elseif ($name == 'id') { $id = ${$table}++; $arrMapper[$table][$value] = $id; $value = $id; } elseif ($name == 'pid') { if ($table == 'tl_style') { $value = $arrMapper['tl_style_sheet'][$value]; } elseif ($table == 'tl_image_size_item') { $value = $arrMapper['tl_image_size'][$value]; } else { $value = $arrMapper['tl_theme'][$value]; } } elseif ($name == 'fallback') { $value = ''; } elseif ($table == 'tl_layout' && $name == 'stylesheet') { $stylesheets = deserialize($value); if (is_array($stylesheets)) { foreach (array_keys($stylesheets) as $key) { $stylesheets[$key] = $arrMapper['tl_style_sheet'][$stylesheets[$key]]; } $value = serialize($stylesheets); } } elseif ($table == 'tl_layout' && $name == 'modules') { $modules = deserialize($value); if (is_array($modules)) { foreach ($modules as $key => $mod) { if ($mod['mod'] > 0) { $modules[$key]['mod'] = $arrMapper['tl_module'][$mod['mod']]; } } $value = serialize($modules); } } elseif (($table == 'tl_theme' || $table == 'tl_style_sheet') && $name == 'name') { $objCount = $this->Database->prepare("SELECT COUNT(*) AS count FROM " . $table . " WHERE name=?")->execute($value); if ($objCount->count > 0) { $value = preg_replace('/( |\\-)[0-9]+$/', '', $value); $value .= ($table == 'tl_style_sheet' ? '-' : ' ') . ${$table}; } } elseif (($table == 'tl_style_sheet' || $table == 'tl_style' || $table == 'tl_files' && $name == 'path') && strpos($value, 'files') !== false) { $tmp = deserialize($value); if (is_array($tmp)) { foreach ($tmp as $kk => $vv) { $tmp[$kk] = $this->customizeUploadPath($vv); } $value = serialize($tmp); } else { $value = $this->customizeUploadPath($value); } } elseif ($GLOBALS['TL_DCA'][$table]['fields'][$name]['inputType'] == 'fileTree' && !$GLOBALS['TL_DCA'][$table]['fields'][$name]['eval']['multiple']) { if (!$value) { $value = null; // Contao >= 3.2 } else { // Do not use the FilesModel here – tables are locked! $objFile = $this->Database->prepare("SELECT uuid FROM tl_files WHERE path=?")->limit(1)->execute($this->customizeUploadPath($value)); $value = $objFile->uuid; } } elseif ($GLOBALS['TL_DCA'][$table]['fields'][$name]['inputType'] == 'fileTree' || in_array($name, $arrOrder)) { $tmp = deserialize($value); if (is_array($tmp)) { foreach ($tmp as $kk => $vv) { // Do not use the FilesModel here – tables are locked! $objFile = $this->Database->prepare("SELECT uuid FROM tl_files WHERE path=?")->limit(1)->execute($this->customizeUploadPath($vv)); $tmp[$kk] = $objFile->uuid; } $value = serialize($tmp); } } elseif ($GLOBALS['TL_DCA'][$table]['fields'][$name]['inputType'] == 'imageSize') { $imageSizes = deserialize($value, true); if (!empty($imageSizes)) { if (is_numeric($imageSizes[2])) { $imageSizes[2] = $arrMapper['tl_image_size'][$imageSizes[2]]; } } $value = serialize($imageSizes); } $set[$name] = $value; } // Skip fields that are not in the database (e.g. because of missing extensions) foreach ($set as $k => $v) { if (!in_array($k, $arrDbFields[$table])) { unset($set[$k]); } } // Create the templates folder even if it is empty (see #4793) if ($table == 'tl_theme' && isset($set['templates']) && strncmp($set['templates'], 'templates/', 10) === 0 && !is_dir(TL_ROOT . '/' . $set['templates'])) { new \Folder($set['templates']); } // Update tl_files (entries have been created by the Dbafs class) if ($table == 'tl_files') { $this->Database->prepare("UPDATE {$table} %s WHERE path=?")->set($set)->execute($set['path']); } else { $this->Database->prepare("INSERT INTO {$table} %s")->set($set)->execute(); } } } // Unlock the tables $this->Database->unlockTables(); // Update the style sheets $this->import('StyleSheets'); $this->StyleSheets->updateStyleSheets(); // Notify the user \Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['tl_theme']['theme_imported'], basename($strZipFile))); // HOOK: add custom logic if (isset($GLOBALS['TL_HOOKS']['extractThemeFiles']) && is_array($GLOBALS['TL_HOOKS']['extractThemeFiles'])) { $intThemeId = empty($arrMapper['tl_theme']) ? null : reset($arrMapper['tl_theme']); foreach ($GLOBALS['TL_HOOKS']['extractThemeFiles'] as $callback) { \System::importStatic($callback[0])->{$callback}[1]($xml, $objArchive, $intThemeId, $arrMapper); } } unset($tl_files, $tl_theme, $tl_style_sheet, $tl_style, $tl_module, $tl_layout, $tl_image_size, $tl_image_size_item); } \System::setCookie('BE_PAGE_OFFSET', 0, 0); $this->Session->remove('uploaded_themes'); // Redirect $this->redirect(str_replace('&key=importTheme', '', \Environment::get('request'))); }
echo json_encode(array('status' => 'error', 'value' => 'size')); // Datei zu gross die; } $tempFile = $files['file']['tmp_name']; //3 if ($rename != '') { $targetPathAbs = $targetPathAbs . '/' . $rename; //5 } else { $targetPathAbs = $targetPathAbs . '/' . $files['file']['name']; //5 } $tmp = move_uploaded_file($tempFile, $targetPathAbs); //6 \Dbafs::addResource($targetPath . '/' . $files['file']['name']); file_exists($targetPathAbs) == true ? $retVal = json_encode(array('status' => 'ok')) : ($retVal = json_encode(array('status' => 'error', 'value' => 'nofile'))); // die Datei ist nicht vorhanden echo $retVal; // alte Ordner loeschen $delFiles = @scandir($delPathAbs); //1 if (false !== $delFiles) { foreach ($delFiles as $file) { if ('.' != $file && '..' != $file && '.DS_Store' != $file) { if (filemtime($delPathAbs . '/' . $file) <= time() - 60 * 60 * 3) { echo filemtime($delPathAbs . '/' . $file) . ' - ' . (time() - 60 * 60 * 3) . "\n"; $allFiles = array_diff(scandir($delPathAbs . '/' . $file), array('.', '..')); foreach ($allFiles as $allFile) { unlink("{$delPathAbs}/{$file}/{$allFile}"); }
/** * Validate the input and set the value */ public function validate() { $this->maxlength = $GLOBALS['TL_CONFIG']['avatar_maxsize']; $this->extensions = $GLOBALS['TL_CONFIG']['avatar_filetype']; $this->uploadFolder = $GLOBALS['TL_CONFIG']['avatar_dir']; $this->storeFile = $this->uploadFolder != '' ? true : false; $arrImage = deserialize($GLOBALS['TL_CONFIG']['avatar_maxdims']); $this->import('FrontendUser', 'User'); // No file specified if (!isset($_FILES[$this->strName]) || empty($_FILES[$this->strName]['name'])) { if ($this->mandatory) { if ($this->strLabel == '') { $this->addError($GLOBALS['TL_LANG']['ERR']['mdtryNoLabel']); } else { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['mandatory'], $this->strLabel)); } } return; } $file = $_FILES[$this->strName]; $maxlength_kb = $this->getReadableSize($this->maxlength); // Romanize the filename $file['name'] = utf8_romanize($file['name']); // File was not uploaded if (!is_uploaded_file($file['tmp_name'])) { if (in_array($file['error'], array(1, 2))) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filesize'], $maxlength_kb)); $this->log('File "' . $file['name'] . '" exceeds the maximum file size of ' . $maxlength_kb, 'FormFileUpload validate()', TL_ERROR); } if ($file['error'] == 3) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filepartial'], $file['name'])); $this->log('File "' . $file['name'] . '" was only partially uploaded', 'FormFileUpload validate()', TL_ERROR); } unset($_FILES[$this->strName]); return; } // File is too big if ($this->maxlength > 0 && $file['size'] > $this->maxlength) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filesize'], $maxlength_kb)); $this->log('File "' . $file['name'] . '" exceeds the maximum file size of ' . $maxlength_kb, 'FormFileUpload validate()', TL_ERROR); unset($_FILES[$this->strName]); return; } $strExtension = pathinfo($file['name'], PATHINFO_EXTENSION); $uploadTypes = trimsplit(',', $this->extensions); // File type is not allowed if (!in_array(strtolower($strExtension), $uploadTypes)) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filetype'], $strExtension)); $this->log('File type "' . $strExtension . '" is not allowed to be uploaded (' . $file['name'] . ')', 'FormFileUpload validate()', TL_ERROR); unset($_FILES[$this->strName]); return; } $blnResize = false; if (($arrImageSize = @getimagesize($file['tmp_name'])) != false) { // Image exceeds maximum image width if ($arrImageSize[0] > $arrImage[0]) { if ($GLOBALS['TL_CONFIG']['avatar_resize']) { $blnResize = true; } else { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filewidth'], $file['name'], $arrImage[0])); $this->log('File "' . $file['name'] . '" exceeds the maximum image width of ' . $GLOBALS['TL_CONFIG']['imageWidth'] . ' pixels', 'FormFileUpload validate()', TL_ERROR); unset($_FILES[$this->strName]); return; } } // Image exceeds maximum image height if ($arrImageSize[1] > $arrImage[1]) { if ($GLOBALS['TL_CONFIG']['avatar_resize']) { $blnResize = true; } else { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['fileheight'], $file['name'], $arrImage[1])); $this->log('File "' . $file['name'] . '" exceeds the maximum image height of ' . $GLOBALS['TL_CONFIG']['imageHeight'] . ' pixels', 'FormFileUpload validate()', TL_ERROR); unset($_FILES[$this->strName]); return; } } } // Store file in the session and optionally on the server if (!$this->hasErrors()) { $_SESSION['FILES'][$this->strName] = $_FILES[$this->strName]; $this->log('File "' . $file['name'] . '" uploaded successfully', 'FormFileUpload validate()', TL_FILES); if ($this->storeFile) { $intUploadFolder = $this->uploadFolder; if ($this->User->assignDir && $this->User->homeDir) { $intUploadFolder = $this->User->homeDir; } $objUploadFolder = \FilesModel::findByUuid($intUploadFolder); // The upload folder could not be found if ($objUploadFolder === null) { throw new \Exception("Invalid upload folder ID {$intUploadFolder}"); } $strUploadFolder = $objUploadFolder->path; // Store the file if the upload folder exists if ($strUploadFolder != '' && is_dir(TL_ROOT . '/' . $strUploadFolder)) { $this->import('Files'); if ($GLOBALS['TL_CONFIG']['avatar_rename']) { $pathinfo = pathinfo($file['name']); $user = \MemberModel::findByPk($this->User->id); $targetName = standardize(\String::parseSimpleTokens($GLOBALS['TL_CONFIG']['avatar_name'], $user->row())) . '.' . $pathinfo['extension']; } else { $targetName = $file['name']; } // Do not overwrite existing files if ($this->doNotOverwrite && file_exists(TL_ROOT . '/' . $strUploadFolder . '/' . $targetName)) { $offset = 1; $pathinfo = pathinfo($targetName); $name = $pathinfo['filename']; $arrAll = scan(TL_ROOT . '/' . $strUploadFolder); $arrFiles = preg_grep('/^' . preg_quote($name, '/') . '.*\\.' . preg_quote($pathinfo['extension'], '/') . '/', $arrAll); foreach ($arrFiles as $strFile) { if (preg_match('/__[0-9]+\\.' . preg_quote($pathinfo['extension'], '/') . '$/', $strFile)) { $strFile = str_replace('.' . $pathinfo['extension'], '', $strFile); $intValue = intval(substr($strFile, strrpos($strFile, '_') + 1)); $offset = max($offset, $intValue); } } $targetName = str_replace($name, $name . '__' . ++$offset, $targetName); } $this->Files->move_uploaded_file($file['tmp_name'], $strUploadFolder . '/' . $targetName); $this->Files->chmod($strUploadFolder . '/' . $targetName, $GLOBALS['TL_CONFIG']['defaultFileChmod']); if ($blnResize) { \Image::resize($strUploadFolder . '/' . $targetName, $arrImageSize[0], $arrImageSize[1], $arrImageSize[2]); } $_SESSION['FILES'][$this->strName] = array('name' => $targetName, 'type' => $file['type'], 'tmp_name' => TL_ROOT . '/' . $strUploadFolder . '/' . $file['name'], 'error' => $file['error'], 'size' => $file['size'], 'uploaded' => true); $strFile = $strUploadFolder . '/' . $targetName; $objModel = \Dbafs::addResource($strFile, true); // new Avatar for Member $objMember = \MemberModel::findByPk($this->User->id); $objMember->avatar = $objModel->uuid; $objMember->save(); $this->varValue = $objModel->uuid; $this->log('File "' . $targetName . '" has been moved to "' . $strUploadFolder . '"', __METHOD__, TL_FILES); } } } unset($_FILES[$this->strName]); }
/** * Delete files based on a file list. * * @CtoCommunication Enable * * @param array $arrFileList List with files for deleting. * * @param boolean $blnIsDbafs Flag if we have to change the dbafs system. * * @return array The list with some more information about the deleted file. */ public function deleteFiles($arrFileList, $blnIsDbafs) { if (count($arrFileList) != 0) { // Run each entry in the list.. foreach ($arrFileList as $key => $value) { // Clean up the path. $strPath = $this->objSyncCtoHelper->standardizePath($value['path']); $strFullPath = $this->objSyncCtoHelper->getFullPath($strPath); try { if (!file_exists($strFullPath)) { $arrFileList[$key]['transmission'] = SyncCtoEnum::FILETRANS_SEND; // Remove from dbafs. if ($blnIsDbafs) { \Dbafs::deleteResource($strPath); } } elseif (is_file($strFullPath)) { // Delete the file. if ($this->objFiles->delete($strPath)) { $arrFileList[$key]['transmission'] = SyncCtoEnum::FILETRANS_SEND; // Remove from dbafs. if ($blnIsDbafs) { \Dbafs::deleteResource($strPath); } } else { $arrFileList[$key]['transmission'] = SyncCtoEnum::FILETRANS_SKIPPED; $arrFileList[$key]['error'] = $GLOBALS['TL_LANG']['ERR']['cant_delete_file']; $arrFileList[$key]['skipreason'] = $GLOBALS['TL_LANG']['ERR']['cant_delete_file']; } } elseif (is_dir($strFullPath)) { $this->objFiles->rrdir($strPath); $arrFileList[$key]['transmission'] = SyncCtoEnum::FILETRANS_SEND; // Remove from dbafs. if ($blnIsDbafs) { \Dbafs::deleteResource($strPath); } } } catch (Exception $exc) { $arrFileList[$key]['transmission'] = SyncCtoEnum::FILETRANS_SKIPPED; $arrFileList[$key]['error'] = sprintf('Can not delete file - %s. Exception message: %s', $strPath, $exc->getMessage()); $arrFileList[$key]['skipreason'] = $GLOBALS['TL_LANG']['ERR']['cant_delete_file']; } } } return $arrFileList; }
/** * Check if the folder should be synchronized with the database * * @return bool True if the folder needs to be synchronized with the database * * @deprecated Use Dbafs::shouldBeSynchronized() instead */ public function shouldBeSynchronized() { return \Dbafs::shouldBeSynchronized($this->strFolder); }
/** * generate an albumalias based on the albumname and create a directory of the same name * and register the directory in tl files * @param $strAlias * @param \Contao\DataContainer $dc * @return mixed|string */ public function saveCbGenerateAlias($strAlias, \Contao\DataContainer $dc) { $blnDoNotCreateDir = false; // get current row $objAlbum = GalleryCreatorAlbumsModel::findByPk($dc->id); if ($objAlbum === null) { return; } // Save assigned Dir if it was defined. if ($this->Input->post('FORM_SUBMIT') && strlen($this->Input->post('assignedDir'))) { $objAlbum->assignedDir = $this->Input->post('assignedDir'); $objAlbum->save(); $blnDoNotCreateDir = true; } $strAlias = standardize($strAlias); // if there isn't an existing albumalias generate one from the albumname if (!strlen($strAlias)) { $strAlias = standardize($dc->activeRecord->name); } // limit alias to 50 characters $strAlias = substr($strAlias, 0, 43); // remove invalid characters $strAlias = preg_replace("/[^a-z0-9\\_\\-]/", "", $strAlias); // if alias already exists add the album-id to the alias $objAlb = $this->Database->prepare('SELECT * FROM tl_gallery_creator_albums WHERE id!=? AND alias=?')->execute($dc->activeRecord->id, $strAlias); if ($objAlb->numRows) { $strAlias = 'id-' . $dc->id . '-' . $strAlias; } // Create default upload folder if ($blnDoNotCreateDir === false) { // create the new folder and register it in tl_files $objFolder = new Folder($this->uploadPath . '/' . $strAlias); $oFolder = Dbafs::addResource($objFolder->path, true); $objAlbum->assignedDir = $oFolder->uuid; $objAlbum->save(); // Important Input::setPost('assignedDir', String::binToUuid($objAlbum->assignedDir)); } return $strAlias; }
/** * Convert an uuid or path to a value to be handled by MetaModels. * * The output array will have the following layout: * array( * 'bin' => array() // the binary id. * 'value' => array() // the uuid. * 'path' => array() // the path. * ) * * @param array $values The binary uuids or paths to convert. * * @return array * * @throws \InvalidArgumentException When any of the input is not a valid uuid or an non existent file. */ public static function convertUuidsOrPathsToMetaModels($values) { $values = array_filter((array) $values); if (empty($values)) { return array('bin' => array(), 'value' => array(), 'path' => array()); } foreach ($values as $key => $value) { if (!\Validator::isUuid($value)) { $file = \FilesModel::findByPath($value) ?: \Dbafs::addResource($value); if (!$file) { throw new \InvalidArgumentException('Invalid value.'); } $values[$key] = $file->uuid; } } return self::convertValuesToMetaModels($values); }
/** * Retrieve the value as serialized array. * * If the type is "file", the file names will automatically be added to the Dbafs and converted to file id. * * @param string $strType Either "page" or "file". * * @param string $varValue The value as comma separated list. * * @return string The values as serialized array. */ protected function getTreeValue($strType, $varValue) { // Convert the selected values. if ($varValue != '') { $varValue = trimsplit("\t", $varValue); // Automatically add resources to the DBAFS. if ($strType == 'file') { foreach ($varValue as $k => $v) { if (version_compare(VERSION, '3.2', '<')) { $varValue[$k] = \Dbafs::addResource($v)->id; } else { $varValue[$k] = \Dbafs::addResource($v)->uuid; } } } $varValue = serialize($varValue); } return $varValue; }
/** * Copy the file * * @param string $strNewName The target path * * @return boolean True if the operation was successful */ public function copyTo($strNewName) { $strParent = dirname($strNewName); // Create the parent folder if it does not exist if (!is_dir(TL_ROOT . '/' . $strParent)) { new \Folder($strParent); } $this->Files->copy($this->strFile, $strNewName); // Update the database AFTER the file has been renamed $syncSource = \Dbafs::shouldBeSynchronized($this->strFile); $syncTarget = \Dbafs::shouldBeSynchronized($strNewName); // Synchronize the database if ($syncSource && $syncTarget) { \Dbafs::copyResource($this->strFile, $strNewName); } elseif ($syncTarget) { \Dbafs::addResource($strNewName); } return true; }
/** * Retrieve the value as serialized array. * * If the type is "file", the file names will automatically be added to the Dbafs and converted to file id. * * @param string $strType Either "page" or "file". * * @param string $varValue The value as comma separated list. * * @return string The value array. */ protected function getTreeValue($strType, $varValue) { // Convert the selected values. if ($varValue != '') { $varValue = trimsplit("\t", $varValue); // Automatically add resources to the DBAFS. if ($strType == 'file') { foreach ($varValue as $k => $v) { $varValue[$k] = \String::binToUuid(\Dbafs::addResource($v)->uuid); } } } return $varValue; }
/** * Get the meta file * * @return \File|null * * @throws \Exception */ public function getMetaFile() { $folder = $this->getAlbumFolder(); if ($folder === null) { return null; } $file = new \File($folder->path . '/' . $this->metaFileName . '.json'); // Synchronize the file with database if ($file->getModel() === null) { \Dbafs::addResource($file->path); } return $file; }
/** * Return a form to choose an existing sermon and import it * @return string * @throws \Exception */ public function importSermon() { if (\Input::get('key') != 'import') { return ''; } $this->import('BackendUser', 'User'); $class = $this->User->uploader; // See #4086 if (!class_exists($class)) { $class = 'FileUpload'; } $objUploader = new $class(); // Import Sermon if (\Input::post('FORM_SUBMIT') == 'tl_sermoner_items_import') { $uploadPath = \FilesModel::findByUuid(SermonArchiveModel::findByPk(\Input::get('id'))->directUploadDestination)->path; $arrUploaded = $objUploader->uploadTo($uploadPath); if (empty($arrUploaded)) { \Message::addError($GLOBALS['TL_LANG']['ERR']['all_fields']); $this->reload(); } foreach ($arrUploaded as $strAudioFile) { // Folders cannot be imported if (is_dir(TL_ROOT . '/' . $strAudioFile)) { \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['importFolder'], basename($strAudioFile))); continue; } $objFile = \Dbafs::addResource($strAudioFile); // Check the file extension if ($objFile->extension != 'mp3') { \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['filetype'], $objFile->extension)); continue; } $this->import('getid3'); $getID3 = new \getID3(); $ThisFileInfo = $getID3->analyze(TL_ROOT . '/' . $objFile->path); $metadata = $ThisFileInfo['tags']['id3v2']; //prepare date out of comment field $comment = array_pop($metadata['comment']); preg_match("/[0-9]{2}\\.{1}[0-9]{2}\\.[0-9]{4}/", $comment, $date); $date = new \Date($date[0]); $objSermon = $this->Database->prepare("INSERT INTO tl_sermoner_items (pid, tstamp, title, speaker, date, audioSingleSRC) VALUES (?,?,?,?,?,?)")->execute(\Input::get('id'), time(), $metadata['title'][0], $metadata['artist'][0], $date->timestamp, $objFile->uuid); $insertId = $objSermon->insertId; if (!is_numeric($insertId) || $insertId < 0) { throw new \Exception('Invalid insert ID'); } } // Redirect \System::setCookie('BE_PAGE_OFFSET', 0, 0); $this->redirect(str_replace('&key=import', '&act=edit&id=' . $insertId, \Environment::get('request'))); } // Return form return ' <div id="tl_buttons"> <a href="' . ampersand(str_replace('&key=import', '', \Environment::get('request'))) . '" class="header_back" title="' . specialchars($GLOBALS['TL_LANG']['MSC']['backBTTitle']) . '" accesskey="b">' . $GLOBALS['TL_LANG']['MSC']['backBT'] . '</a> </div> <h2 class="sub_headline">' . $GLOBALS['TL_LANG']['tl_sermoner_items']['import'][1] . '</h2> ' . \Message::generate() . ' <form action="' . ampersand(\Environment::get('request'), true) . '" id="tl_sermoner_items_import" class="tl_form" method="post" enctype="multipart/form-data"> <div class="tl_formbody_edit"> <input type="hidden" name="FORM_SUBMIT" value="tl_sermoner_items_import"> <input type="hidden" name="REQUEST_TOKEN" value="' . REQUEST_TOKEN . '"> <input type="hidden" name="MAX_FILE_SIZE" value="' . $GLOBALS['TL_CONFIG']['maxFileSize'] . '"> <div class="tl_tbox"> <h3>' . $GLOBALS['TL_LANG']['tl_sermoner_items']['source'][0] . '</h3>' . $objUploader->generateMarkup() . (isset($GLOBALS['TL_LANG']['tl_sermoner_items']['source'][1]) ? ' <p class="tl_help tl_tip">' . $GLOBALS['TL_LANG']['tl_sermoner_items']['source'][1] . '</p>' : '') . ' </div> </div> <div class="tl_formbody_submit"> <div class="tl_submit_container"> <input type="submit" name="save" id="save" class="tl_submit" accesskey="s" value="' . specialchars($GLOBALS['TL_LANG']['tl_sermoner_items']['import'][0]) . '"> </div> </div> </form>'; }
/** * Copy the folder * * @param string $strNewName The target path * * @return boolean True if the operation was successful */ public function copyTo($strNewName) { $strParent = dirname($strNewName); // Create the parent folder if it does not exist if (!is_dir(TL_ROOT . '/' . $strParent)) { new \Folder($strParent); } $this->Files->rcopy($this->strFolder, $strNewName); // Update the database AFTER the folder has been renamed if ($this->blnSyncDb) { $this->objModel = \Dbafs::copyResource($this->strFolder, $strNewName); } return true; }
/** * revise tables * @param $albumId * @param bool $blnCleanDb */ public static function reviseTables($albumId, $blnCleanDb = false) { $_SESSION['GC_ERROR'] = array(); //Upload-Verzeichnis erstellen, falls nicht mehr vorhanden new \Folder(GALLERY_CREATOR_UPLOAD_PATH); // Get album model $objAlbum = \MCupic\GalleryCreatorAlbumsModel::findByPk($albumId); if ($objAlbum === null) { return; } // Check for valid album owner $objUser = \UserModel::findByPk($objAlbum->owner); if ($objUser !== null) { $owner = $objUser->name; } else { $owner = "no-name"; } $objAlbum->owners_name = $owner; $objAlbum->save(); // Check for valid pid if ($objAlbum->pid > 0) { $objParentAlb = $objAlbum->getRelated('pid'); if ($objParentAlb === null) { $objAlbum->pid = null; $objAlbum->save(); } } if (\Database::getInstance()->fieldExists('path', 'tl_gallery_creator_pictures')) { // Datensaetzen ohne gültige uuid über den Feldinhalt path versuchen zu "retten" $objPictures = \GalleryCreatorPicturesModel::findByPid($albumId); if ($objPictures !== null) { while ($objPictures->next()) { // Get parent album $objFile = \FilesModel::findByUuid($objPictures->uuid); if ($objFile === null) { if ($objPictures->path != '') { if (is_file(TL_ROOT . '/' . $objPictures->path)) { $objModel = \Dbafs::addResource($objPictures->path); if (\Validator::isUuid($objModel->uuid)) { $objPictures->uuid = $objModel->uuid; $objPictures->save(); continue; } } } if ($blnCleanDb !== false) { $msg = ' Deleted Datarecord with ID ' . $objPictures->id . '.'; $_SESSION['GC_ERROR'][] = $msg; $objPictures->delete(); } else { //show the error-message $path = $objPictures->path != '' ? $objPictures->path : 'unknown path'; $_SESSION['GC_ERROR'][] = sprintf($GLOBALS['TL_LANG']['ERR']['link_to_not_existing_file_1'], $objPictures->id, $path, $objAlbum->alias); } } elseif (!is_file(TL_ROOT . '/' . $objFile->path)) { // If file has an entry in Dbafs, but doesn't exist on the server anymore if ($blnCleanDb !== false) { $msg = 'Deleted Datarecord with ID ' . $objPictures->id . '.'; $_SESSION['GC_ERROR'][] = $msg; $objPictures->delete(); } else { $_SESSION['GC_ERROR'][] = sprintf($GLOBALS['TL_LANG']['ERR']['link_to_not_existing_file_1'], $objPictures->id, $objFile->path, $objAlbum->alias); } } else { // Pfadangaben mit tl_files.path abgleichen (Redundanz) if ($objPictures->path != $objFile->path) { $objPictures->path = $objFile->path; $objPictures->save(); } } } } } /** * Sorgt dafuer, dass in tl_content im Feld gc_publish_albums keine verwaisten AlbumId's vorhanden sind * Prueft, ob die im Inhaltselement definiertern Alben auch noch existieren. * Wenn nein, werden diese aus dem Array entfernt. */ $objCont = \Database::getInstance()->prepare('SELECT id, gc_publish_albums FROM tl_content WHERE type=?')->execute('gallery_creator'); while ($objCont->next()) { $newArr = array(); $arrAlbums = unserialize($objCont->gc_publish_albums); if (is_array($arrAlbums)) { foreach ($arrAlbums as $AlbumID) { $objAlb = \Database::getInstance()->prepare('SELECT id FROM tl_gallery_creator_albums WHERE id=?')->limit('1')->execute($AlbumID); if ($objAlb->next()) { $newArr[] = $AlbumID; } } } \Database::getInstance()->prepare('UPDATE tl_content SET gc_publish_albums=? WHERE id=?')->execute(serialize($newArr), $objCont->id); } }
/** * Ajax actions that do require a data container object * * @param \DataContainer $dc */ 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); exit; } switch ($this->strAction) { // Load nodes of the page structure tree case 'loadStructure': echo $dc->ajaxTreeView($this->strAjaxId, intval(\Input::post('level'))); exit; break; // Load nodes of the file manager tree // Load nodes of the file manager tree case 'loadFileManager': echo $dc->ajaxTreeView(\Input::post('folder', true), intval(\Input::post('level'))); exit; break; // Load nodes of the page tree // Load nodes of the page tree case 'loadPagetree': $strField = $dc->field = \Input::post('name'); /** @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, null, $strField, $dc->table, $dc)); echo $objWidget->generateAjax($this->strAjaxId, \Input::post('field'), intval(\Input::post('level'))); exit; break; // Load nodes of the file tree // Load nodes of the file tree case 'loadFiletree': $strField = $dc->field = \Input::post('name'); /** @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, null, $strField, $dc->table, $dc)); // Load a particular node if (\Input::post('folder', true) != '') { echo $objWidget->generateAjax(\Input::post('folder', true), \Input::post('field'), intval(\Input::post('level'))); } else { echo $objWidget->generate(); } exit; break; // Reload the page/file picker // Reload the page/file picker case 'reloadPagetree': case 'reloadFiletree': $intId = \Input::get('id'); $strField = $dc->field = \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); } // 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); header('HTTP/1.1 400 Bad Request'); die('Bad Request'); } $objRow = null; $varValue = null; // Load the value 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); header('HTTP/1.1 400 Bad Request'); die('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 = trimsplit("\t", $varValue); // Automatically add resources to the DBAFS if ($strKey == 'fileTree') { foreach ($varValue as $k => $v) { if (\Dbafs::shouldBeSynchronized($v)) { $varValue[$k] = \Dbafs::addResource($v)->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->field, $varValue, $strField, $dc->table, $dc)); echo $objWidget->generate(); exit; break; // 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); } } exit; break; // 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); header('HTTP/1.1 400 Bad Request'); die('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')) { echo $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); echo $dc->edit(false, \Input::post('id')); } } exit; break; // DropZone file upload // DropZone file upload case 'fileupload': $dc->move(); exit; break; // HOOK: pass unknown actions to callback functions // HOOK: pass unknown actions to callback functions default: $this->executePostActionsHook($dc); exit; break; } }
/** * Move the temporary file to its destination * @param string * @param string * @return string */ protected function moveTemporaryFile($strFile, $strDestination) { if (!is_file(TL_ROOT . '/' . $strFile)) { return ''; } // Do not store the file if (!$this->arrConfiguration['storeFile']) { return $strFile; } // The file is not temporary if (stripos($strFile, $this->strTemporaryPath) === false) { return $strFile; } $strNew = $strDestination . '/' . basename($strFile); // Do not overwrite existing files if ($this->arrConfiguration['doNotOverwrite']) { $strNew = $strDestination . '/' . $this->getFileName(basename($strFile), $strDestination); } $blnRename = \Files::getInstance()->rename($strFile, $strNew); // Add the file to Dbafs if ($this->arrConfiguration['addToDbafs'] && $blnRename) { $objModel = \Dbafs::addResource($strNew); if ($objModel !== null) { $strNew = $objModel->uuid; } } return $strNew; }
public function moveAppend(&$arrSubmittedArray, $arrLabelsArray, $objForm, $arrFields = array()) { file_put_contents('uploadlog.txt', 'Die Funktion wurde aufgerufen'); $this->import('Database'); $_POST[myid] = ''; $_GET[myid] = ''; $files = $this->Input->get('attachfiles'); if ($files == "") { $files = $this->Input->post('attachfiles'); } // get JSON-data if ($files != "") { foreach ($files as $file) { $tmp = split('"elemID"', $file); $file = '{"elemID"' . $tmp[1]; //file_put_contents('check.txt',$file."\n", FILE_APPEND ); if ($obj = json_decode($file)) { $myElem = $obj->elemID; $addToFile = $obj->addToFile; // get uploadFolder $myElemData = $this->Database->prepare("SELECT * FROM tl_form_field WHERE id = " . $myElem)->execute(); $uploadFolder = ''; if ($myElemData->next()) { $tmpFolder = $myElemData->multiuploadFolder; $objUploadFolder = \FilesModel::findByUuid($tmpFolder); $uploadFolder = $objUploadFolder->path; } $uploaded = $obj->files; // Array foreach ($uploaded as $curFile) { if (file_exists(TL_ROOT . '/' . $uploadFolder . '/tmp/' . $addToFile . '/' . $curFile)) { // move files if (!file_exists(TL_ROOT . '/' . $uploadFolder . '/' . $addToFile) && $myElemData->storecase != 'file') { new \Folder($uploadFolder . '/' . $addToFile); \Dbafs::addResource($uploadFolder . '/' . $addToFile); } // use ID as folder or file prename if ($myElemData->storecase == 'file') { $storeFolderPreFile = $addToFile . '_'; } else { $storeFolderPreFile = $addToFile . '/'; } if (copy(TL_ROOT . '/' . $uploadFolder . '/tmp/' . $addToFile . '/' . $curFile, TL_ROOT . '/' . $uploadFolder . '/' . $storeFolderPreFile . $curFile)) { \Dbafs::addResource($uploadFolder . '/' . $storeFolderPreFile . $curFile); @unlink(TL_ROOT . '/' . $uploadFolder . '/tmp/' . $addToFile . '/' . $curFile); \Dbafs::deleteResource($uploadFolder . '/tmp/' . $addToFile . '/' . $curFile); if (in_array($myElemData->sendcase, array('attach', 'all'))) { // Dateien der Mail anhaengen $_SESSION['FILES'][$curFile] = array('name' => $curFile, 'type' => 'file', 'tmp_name' => TL_ROOT . '/' . $uploadFolder . '/' . $storeFolderPreFile . $curFile, 'uploaded' => false); } if (in_array($myElemData->sendcase, array('link', 'all'))) { // Dateien per Link einbinden if (file_exists(TL_ROOT . '/' . $uploadFolder . '/' . $storeFolderPreFile . $curFile)) { $subfolder = str_replace(array('/', '\\'), '', $GLOBALS['TL_CONFIG']['websitePath']); if ($subfolder != '') { $subfolder .= '/'; } $arrSubmittedArray[$myElemData->name] .= "\nhttp://" . $_SERVER['SERVER_NAME'] . '/' . $subfolder . $uploadFolder . '/' . $storeFolderPreFile . $curFile; } } if ($myElemData->sendcase == 'attach') { // Datei-Verlinkung loeschen unset($arrSubmittedArray[$myElemData->name]); unset($arrLabelsArray[$myElemData->name]); } } } } } } //\Dbafs::syncFiles(); } }
/** * Validate the input and set the value */ public function validate() { // No file specified if (!isset($_FILES[$this->strName]) || empty($_FILES[$this->strName]['name'])) { if ($this->mandatory) { if ($this->strLabel == '') { $this->addError($GLOBALS['TL_LANG']['ERR']['mdtryNoLabel']); } else { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['mandatory'], $this->strLabel)); } } return; } $file = $_FILES[$this->strName]; $maxlength_kb = $this->getReadableSize($this->maxlength); // Romanize the filename $file['name'] = utf8_romanize($file['name']); // File was not uploaded if (!is_uploaded_file($file['tmp_name'])) { if ($file['error'] == 1 || $file['error'] == 2) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filesize'], $maxlength_kb)); $this->log('File "' . $file['name'] . '" exceeds the maximum file size of ' . $maxlength_kb, __METHOD__, TL_ERROR); } elseif ($file['error'] == 3) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filepartial'], $file['name'])); $this->log('File "' . $file['name'] . '" was only partially uploaded', __METHOD__, TL_ERROR); } elseif ($file['error'] > 0) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['fileerror'], $file['error'], $file['name'])); $this->log('File "' . $file['name'] . '" could not be uploaded (error ' . $file['error'] . ')', __METHOD__, TL_ERROR); } unset($_FILES[$this->strName]); return; } // File is too big if ($this->maxlength > 0 && $file['size'] > $this->maxlength) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filesize'], $maxlength_kb)); $this->log('File "' . $file['name'] . '" exceeds the maximum file size of ' . $maxlength_kb, __METHOD__, TL_ERROR); unset($_FILES[$this->strName]); return; } $strExtension = pathinfo($file['name'], PATHINFO_EXTENSION); $uploadTypes = trimsplit(',', $this->extensions); // File type is not allowed if (!in_array(strtolower($strExtension), $uploadTypes)) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filetype'], $strExtension)); $this->log('File type "' . $strExtension . '" is not allowed to be uploaded (' . $file['name'] . ')', __METHOD__, TL_ERROR); unset($_FILES[$this->strName]); return; } if (($arrImageSize = @getimagesize($file['tmp_name'])) != false) { // Image exceeds maximum image width if ($arrImageSize[0] > \Config::get('imageWidth')) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filewidth'], $file['name'], \Config::get('imageWidth'))); $this->log('File "' . $file['name'] . '" exceeds the maximum image width of ' . \Config::get('imageWidth') . ' pixels', __METHOD__, TL_ERROR); unset($_FILES[$this->strName]); return; } // Image exceeds maximum image height if ($arrImageSize[1] > \Config::get('imageHeight')) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['fileheight'], $file['name'], \Config::get('imageHeight'))); $this->log('File "' . $file['name'] . '" exceeds the maximum image height of ' . \Config::get('imageHeight') . ' pixels', __METHOD__, TL_ERROR); unset($_FILES[$this->strName]); return; } } // Store file in the session and optionally on the server if (!$this->hasErrors()) { $_SESSION['FILES'][$this->strName] = $_FILES[$this->strName]; $this->log('File "' . $file['name'] . '" uploaded successfully', __METHOD__, TL_FILES); if ($this->storeFile) { $intUploadFolder = $this->uploadFolder; // Overwrite the upload folder with user's home directory if ($this->useHomeDir && FE_USER_LOGGED_IN) { $this->import('FrontendUser', 'User'); if ($this->User->assignDir && $this->User->homeDir) { $intUploadFolder = $this->User->homeDir; } } $objUploadFolder = \FilesModel::findByUuid($intUploadFolder); // The upload folder could not be found if ($objUploadFolder === null) { throw new \Exception("Invalid upload folder ID {$intUploadFolder}"); } $strUploadFolder = $objUploadFolder->path; // Store the file if the upload folder exists if ($strUploadFolder != '' && is_dir(TL_ROOT . '/' . $strUploadFolder)) { $this->import('Files'); // Do not overwrite existing files if ($this->doNotOverwrite && file_exists(TL_ROOT . '/' . $strUploadFolder . '/' . $file['name'])) { $offset = 1; $pathinfo = pathinfo($file['name']); $name = $pathinfo['filename']; $arrAll = scan(TL_ROOT . '/' . $strUploadFolder); $arrFiles = preg_grep('/^' . preg_quote($name, '/') . '.*\\.' . preg_quote($pathinfo['extension'], '/') . '/', $arrAll); foreach ($arrFiles as $strFile) { if (preg_match('/__[0-9]+\\.' . preg_quote($pathinfo['extension'], '/') . '$/', $strFile)) { $strFile = str_replace('.' . $pathinfo['extension'], '', $strFile); $intValue = intval(substr($strFile, strrpos($strFile, '_') + 1)); $offset = max($offset, $intValue); } } $file['name'] = str_replace($name, $name . '__' . ++$offset, $file['name']); } $this->Files->move_uploaded_file($file['tmp_name'], $strUploadFolder . '/' . $file['name']); $this->Files->chmod($strUploadFolder . '/' . $file['name'], \Config::get('defaultFileChmod')); // Generate the DB entries $strFile = $strUploadFolder . '/' . $file['name']; $objFile = \FilesModel::findByPath($strFile); // Existing file is being replaced (see #4818) if ($objFile !== null) { $objFile->tstamp = time(); $objFile->path = $strFile; $objFile->hash = md5_file(TL_ROOT . '/' . $strFile); $objFile->save(); } else { $objFile = \Dbafs::addResource($strFile); } // Update the hash of the target folder \Dbafs::updateFolderHashes($strUploadFolder); // Add the session entry (see #6986) $_SESSION['FILES'][$this->strName] = array('name' => $file['name'], 'type' => $file['type'], 'tmp_name' => TL_ROOT . '/' . $strFile, 'error' => $file['error'], 'size' => $file['size'], 'uploaded' => true, 'uuid' => \String::binToUuid($objFile->uuid)); // Add a log entry $this->log('File "' . $file['name'] . '" has been moved to "' . $strUploadFolder . '"', __METHOD__, TL_FILES); } } } unset($_FILES[$this->strName]); }
/** * Handle ajax post actions * @param $strAction * @param $dc */ public function executePostActions($strAction, $dc) { switch ($strAction) { case 'toggleEfgSubpalette': if ($dc instanceof DC_Formdata) { if (\Input::get('act') == 'editAll') { $this->strAjaxId = preg_replace('/.*_([0-9a-zA-Z]+)$/', '$1', \Input::post('id')); if (in_array(\Input::post('field'), $this->arrBaseFields)) { \Database::getInstance()->prepare("UPDATE tl_formdata SET " . \Input::post('field') . "='" . (intval(\Input::post('state')) == 1 ? 1 : '') . "' WHERE id=?")->execute($this->strAjaxId); } else { $strValue = ''; if (intval(\Input::post('state')) == 1) { $option = array_pop($GLOBALS['TL_DCA']['tl_formdata']['fields'][\Input::post('field')]['options']); if (!empty($option)) { $strValue = $option; } } $objResult = \Database::getInstance()->prepare("SELECT * FROM tl_formdata_details WHERE pid=? AND ff_name=?")->execute($this->strAjaxId, \Input::post('field')); if ($objResult->numRows < 1) { $arrFieldSet = array('pid' => $this->strAjaxId, 'tstamp' => time(), 'ff_id' => $GLOBALS['TL_DCA']['tl_formdata']['fields'][\Input::post('field')]['f_id'], 'ff_name' => \Input::post('field'), 'value' => $strValue); \Database::getInstance()->prepare("INSERT INTO tl_formdata_details %s")->set($arrFieldSet)->execute(); } else { \Database::getInstance()->prepare("UPDATE tl_formdata_details SET `value`='" . $strValue . "' WHERE pid=? AND ff_name=?")->execute($this->strAjaxId, \Input::post('field')); } } if (\Input::post('load')) { echo $dc->editAll($this->strAjaxId, \Input::post('id')); } } else { if (in_array(\Input::post('field'), $this->arrBaseFields)) { \Database::getInstance()->prepare("UPDATE tl_formdata SET " . \Input::post('field') . "='" . (intval(\Input::post('state')) == 1 ? 1 : '') . "' WHERE id=?")->execute($dc->id); } else { $strValue = ''; if (intval(\Input::post('state')) == 1) { $option = array_pop($GLOBALS['TL_DCA']['tl_formdata']['fields'][\Input::post('field')]['options']); if (!empty($option)) { $strValue = $option; } } $objResult = \Database::getInstance()->prepare("SELECT * FROM tl_formdata_details WHERE pid=? AND ff_name=?")->execute($dc->id, \Input::post('field')); if ($objResult->numRows < 1) { $arrFieldSet = array('pid' => $dc->id, 'tstamp' => time(), 'ff_id' => $GLOBALS['TL_DCA']['tl_formdata']['fields'][\Input::post('field')]['f_id'], 'ff_name' => \Input::post('field'), 'value' => $strValue); \Database::getInstance()->prepare("INSERT INTO tl_formdata_details %s")->set($arrFieldSet)->execute(); } else { \Database::getInstance()->prepare("UPDATE tl_formdata_details SET `value`='" . $strValue . "' WHERE pid=? AND ff_name=?")->execute($dc->id, \Input::post('field')); } } if (\Input::post('load')) { echo $dc->edit(false, \Input::post('id')); } } } break; // Load nodes of the file tree // Load nodes of the file tree // Load nodes of the file tree // Load nodes of the file tree case 'loadFiletree': $arrData['strTable'] = $dc->table; $arrData['id'] = $this->strAjaxName ?: $dc->id; $arrData['name'] = \Input::post('name'); $objWidget = new $GLOBALS['BE_FFL']['fileSelector']($arrData, $dc); // Load a particular node if (\Input::post('folder', true) != '') { echo $objWidget->generateAjax(\Input::post('folder', true), \Input::post('field'), intval(\Input::post('level'))); } else { echo $objWidget->generate(); } exit; break; case 'reloadEfgFiletree': $intId = \Input::get('id'); $strField = $strFieldName = \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); } // Validate the request data if (\Database::getInstance()->tableExists($dc->table)) { // The field does not exist if (!in_array($strField, $dc->arrBaseFields) && !in_array($strField, $dc->arrDetailFields)) { $this->log('Field "' . $strField . '" does not belong to form data table', 'Formdata executePostActions()', TL_ERROR); header('HTTP/1.1 400 Bad Request'); die('Bad Request'); } $objRow = \Database::getInstance()->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 . '"', 'Ajax executePostActions()', TL_ERROR); header('HTTP/1.1 400 Bad Request'); die('Bad Request'); } } $varValue = \Input::post('value'); $strKey = 'fileTree'; // Convert the selected values if ($varValue != '') { $varValue = trimsplit("\t", $varValue); // Automatically add resources to the DBAFS if ($strKey == 'fileTree') { foreach ($varValue as $k => $v) { $varValue[$k] = \Dbafs::addResource($v)->uuid; } } $varValue = serialize($varValue); } // Set the new value if (in_array($strField, $dc->arrBaseFields) || in_array($strField, $dc->arrDetailFields)) { $objRow->{$strField} = $varValue; $arrAttribs['activeRecord'] = $objRow; } $arrAttribs['id'] = $strFieldName; $arrAttribs['name'] = $strFieldName; $arrAttribs['value'] = $varValue; $arrAttribs['strTable'] = $dc->table; $arrAttribs['strField'] = $strField; $objWidget = new $GLOBALS['BE_FFL'][$strKey]($arrAttribs); echo $objWidget->generate() . '<script>handleEfgFileselectorButton();</script>'; break; exit; case 'reloadEfgImportSource': $intId = \Input::get('id'); $strField = $strFieldName = \Input::post('name'); $varValue = \Input::post('value'); $strKey = 'fileTree'; // Convert the selected values if ($varValue != '') { $varValue = trimsplit("\t", $varValue); // Automatically add resources to the DBAFS if ($strKey == 'fileTree') { foreach ($varValue as $k => $v) { $varValue[$k] = \Dbafs::addResource($v)->uuid; } } $varValue = serialize($varValue); } $arrAttribs['id'] = $strFieldName; $arrAttribs['name'] = $strFieldName; $arrAttribs['value'] = $varValue; $arrAttribs['strTable'] = $dc->table; $arrAttribs['strField'] = $strField; $objWidget = new $GLOBALS['BE_FFL'][$strKey]($arrAttribs); echo $objWidget->generate() . '<script>handleEfgFileselectorButton();</script>'; break; exit; } }
/** * Generate module * * @return void */ protected function compile() { global $objPage; $this->maxlength = $GLOBALS['TL_CONFIG']['avatar_maxsize']; $this->extensions = $GLOBALS['TL_CONFIG']['avatar_filetype']; $this->uploadFolder = $GLOBALS['TL_CONFIG']['avatar_dir']; $this->storeFile = $this->uploadFolder != '' ? true : false; $arrImage = deserialize($GLOBALS['TL_CONFIG']['avatar_maxdims']); $this->import('FrontendUser', 'User'); $strAvatar = $this->User->avatar; $strAlt = $this->User->firstname . " " . $this->User->lastname; $objFile = \FilesModel::findByUuid($strAvatar); if ($objFile === null && $GLOBALS['TL_CONFIG']['avatar_fallback_image']) { $objFile = \FilesModel::findByUuid($GLOBALS['TL_CONFIG']['avatar_fallback_image']); } if ($objFile !== null) { $this->Template->avatar = '<img src="' . TL_FILES_URL . \Image::get($objFile->path, $arrImage[0], $arrImage[1], $arrImage[2]) . '" width="' . $arrImage[0] . '" height="' . $arrImage[1] . '" alt="' . $strAlt . '" class="avatar">'; } elseif ($this->User->gender != '') { $this->Template->avatar = '<img src="' . TL_FILES_URL . \Image::get("system/modules/avatar/assets/" . $this->User->gender . ".png", $arrImage[0], $arrImage[1], $arrImage[2]) . '" width="' . $arrImage[0] . '" height="' . $arrImage[1] . '" alt="Avatar" class="avatar">'; } else { $this->Template->avatar = '<img src="' . TL_FILES_URL . \Image::get("system/modules/avatar/assets/male.png", $arrImage[0], $arrImage[1], $arrImage[2]) . '" width="' . $arrImage[0] . '" height="' . $arrImage[1] . '" alt="Avatar" class="avatar">'; } $this->Template->action = ampersand(\Environment::get('request')); $this->Template->formId = 'avatar_' . $this->id; $this->Template->method = 'post'; $this->Template->enctype = 'multipart/form-data'; $this->Template->attributes = ''; $this->Template->avatar_reset_label = $GLOBALS['TL_LANG']['AVATAR']['reset']; $this->Template->avatar_submit_value = $GLOBALS['TL_LANG']['AVATAR']['save']; $this->Template->avatar_file_label = sprintf($GLOBALS['TL_LANG']['AVATAR']['file']['1'], $this->extensions, $this->maxlength, $arrImage[0], $arrImage[1]); // Confirm or remove a subscription if (\Input::get('token')) { static::changeSubscriptionStatus($objTemplate); return; } // Remove the avatar if (\Input::postRaw('avatar_reset')) { \Database::getInstance()->prepare("UPDATE `tl_member` SET avatar='' WHERE `id`=?")->execute($this->User->id); $this->reload(); } $file = $_FILES[$this->strName]; $maxlength_kb = $this->getReadableSize($this->maxlength); // Romanize the filename $file['name'] = utf8_romanize($file['name']); // File was not uploaded if (!is_uploaded_file($file['tmp_name'])) { if (in_array($file['error'], array(1, 2))) { $this->Template->error = sprintf($GLOBALS['TL_LANG']['ERR']['filesize'], $maxlength_kb); $this->log('File "' . $file['name'] . '" exceeds the maximum file size of ' . $maxlength_kb, 'FormFileUpload validate()', TL_ERROR); } if ($file['error'] == 3) { $this->Template->error = sprintf($GLOBALS['TL_LANG']['ERR']['filepartial'], $file['name']); $this->log('File "' . $file['name'] . '" was only partially uploaded', 'FormFileUpload validate()', TL_ERROR); } unset($_FILES[$this->strName]); return; } // File is too big if ($this->maxlength > 0 && $file['size'] > $this->maxlength) { $this->Template->error = sprintf($GLOBALS['TL_LANG']['ERR']['filesize'], $maxlength_kb); $this->log('File "' . $file['name'] . '" exceeds the maximum file size of ' . $maxlength_kb, 'FormFileUpload validate()', TL_ERROR); unset($_FILES[$this->strName]); return; } $strExtension = pathinfo($file['name'], PATHINFO_EXTENSION); $uploadTypes = trimsplit(',', $this->extensions); // File type is not allowed if (!in_array(strtolower($strExtension), $uploadTypes)) { $this->Template->error = sprintf($GLOBALS['TL_LANG']['ERR']['filetype'], $strExtension); $this->log('File type "' . $strExtension . '" is not allowed to be uploaded (' . $file['name'] . ')', 'FormFileUpload validate()', TL_ERROR); unset($_FILES[$this->strName]); return; } $blnResize = false; if (($arrImageSize = @getimagesize($file['tmp_name'])) != false) { // Image exceeds maximum image width if ($arrImageSize[0] > $arrImage[0]) { if ($GLOBALS['TL_CONFIG']['avatar_resize']) { $blnResize = true; } else { $this->Template->error = sprintf($GLOBALS['TL_LANG']['ERR']['filewidth'], $file['name'], $arrImage[0]); $this->log('File "' . $file['name'] . '" exceeds the maximum image width of ' . $arrImage[0] . ' pixels', 'FormFileUpload validate()', TL_ERROR); unset($_FILES[$this->strName]); return; } } // Image exceeds maximum image height if ($arrImageSize[1] > $arrImage[1]) { if ($GLOBALS['TL_CONFIG']['avatar_resize']) { $blnResize = true; } else { $this->Template->error = sprintf($GLOBALS['TL_LANG']['ERR']['fileheight'], $file['name'], $arrImage[1]); $this->log('File "' . $file['name'] . '" exceeds the maximum image height of ' . $arrImage[1] . ' pixels', 'FormFileUpload validate()', TL_ERROR); unset($_FILES[$this->strName]); return; } } } $_SESSION['FILES'][$this->strName] = $_FILES[$this->strName]; $this->log('File "' . $file['name'] . '" uploaded successfully', 'FormFileUpload validate()', TL_FILES); if ($this->storeFile) { $intUploadFolder = $this->uploadFolder; if ($this->User->assignDir && $this->User->homeDir) { $intUploadFolder = $this->User->homeDir; } $objUploadFolder = \FilesModel::findByUuid($intUploadFolder); // The upload folder could not be found if ($objUploadFolder === null) { throw new \Exception("Invalid upload folder ID {$intUploadFolder}"); } $strUploadFolder = $objUploadFolder->path; // Store the file if the upload folder exists if ($strUploadFolder != '' && is_dir(TL_ROOT . '/' . $strUploadFolder)) { $this->import('Files'); // Do not overwrite existing files if ($this->doNotOverwrite && file_exists(TL_ROOT . '/' . $strUploadFolder . '/' . $file['name'])) { $offset = 1; $pathinfo = pathinfo($file['name']); $name = $pathinfo['filename']; $arrAll = scan(TL_ROOT . '/' . $strUploadFolder); $arrFiles = preg_grep('/^' . preg_quote($name, '/') . '.*\\.' . preg_quote($pathinfo['extension'], '/') . '/', $arrAll); foreach ($arrFiles as $strFile) { if (preg_match('/__[0-9]+\\.' . preg_quote($pathinfo['extension'], '/') . '$/', $strFile)) { $strFile = str_replace('.' . $pathinfo['extension'], '', $strFile); $intValue = intval(substr($strFile, strrpos($strFile, '_') + 1)); $offset = max($offset, $intValue); } } $file['name'] = str_replace($name, $name . '__' . ++$offset, $file['name']); } $this->Files->move_uploaded_file($file['tmp_name'], $strUploadFolder . '/' . $file['name']); $this->Files->chmod($strUploadFolder . '/' . $file['name'], $GLOBALS['TL_CONFIG']['defaultFileChmod']); if ($blnResize) { \Image::resize($strUploadFolder . '/' . $file['name'], $arrImage[0], $arrImage[1], $arrImage[2]); } $_SESSION['FILES'][$this->strName] = array('name' => $file['name'], 'type' => $file['type'], 'tmp_name' => TL_ROOT . '/' . $strUploadFolder . '/' . $file['name'], 'error' => $file['error'], 'size' => $file['size'], 'uploaded' => true); $this->loadDataContainer('tl_files'); // Generate the DB entries if ($GLOBALS['TL_DCA']['tl_files']['config']['databaseAssisted']) { $strFile = $strUploadFolder . '/' . $file['name']; $objFile = \FilesModel::findByPath($strFile); // Existing file is being replaced (see #4818) if ($objFile !== null) { $objFile->tstamp = time(); $objFile->path = $strFile; $objFile->hash = md5_file(TL_ROOT . '/' . $strFile); $objFile->save(); } else { \Dbafs::addResource($strFile); } // Update the hash of the target folder \Dbafs::updateFolderHashes($strUploadFolder); } // Update Userdata $strFile = $strUploadFolder . '/' . $file['name']; $objFile = \FilesModel::findByPath($strFile); // new Avatar for Member \Database::getInstance()->prepare("UPDATE tl_member SET avatar=? WHERE id=?")->execute($objFile->uuid, $this->User->id); $this->log('File "' . $file['name'] . '" has been moved to "' . $strUploadFolder . '"', 'FormFileUpload validate()', TL_FILES); } } unset($_FILES[$this->strName]); $this->reload(); }
/** * Validate the input and set the value */ public function validate() { // No file specified if (!isset($_FILES[$this->strName]) || empty($_FILES[$this->strName]['name'])) { if ($this->mandatory) { if ($this->strLabel == '') { $this->addError($GLOBALS['TL_LANG']['ERR']['mdtryNoLabel']); } else { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['mandatory'], $this->strLabel)); } } return; } $file = $_FILES[$this->strName]; $maxlength_kb = $this->getMaximumUploadSize(); $maxlength_kb_readable = $this->getReadableSize($maxlength_kb); // Sanitize the filename try { $file['name'] = \StringUtil::sanitizeFileName($file['name']); } catch (\InvalidArgumentException $e) { $this->addError($GLOBALS['TL_LANG']['ERR']['filename']); return; } // Invalid file name if (!\Validator::isValidFileName($file['name'])) { $this->addError($GLOBALS['TL_LANG']['ERR']['filename']); return; } // File was not uploaded if (!is_uploaded_file($file['tmp_name'])) { if ($file['error'] == 1 || $file['error'] == 2) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filesize'], $maxlength_kb_readable)); } elseif ($file['error'] == 3) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filepartial'], $file['name'])); } elseif ($file['error'] > 0) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['fileerror'], $file['error'], $file['name'])); } unset($_FILES[$this->strName]); return; } // File is too big if ($file['size'] > $maxlength_kb) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filesize'], $maxlength_kb_readable)); unset($_FILES[$this->strName]); return; } $objFile = new \File($file['name']); $uploadTypes = \StringUtil::trimsplit(',', strtolower($this->extensions)); // File type is not allowed if (!in_array($objFile->extension, $uploadTypes)) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filetype'], $objFile->extension)); unset($_FILES[$this->strName]); return; } if (($arrImageSize = @getimagesize($file['tmp_name'])) != false) { // Image exceeds maximum image width if ($arrImageSize[0] > \Config::get('imageWidth')) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filewidth'], $file['name'], \Config::get('imageWidth'))); unset($_FILES[$this->strName]); return; } // Image exceeds maximum image height if ($arrImageSize[1] > \Config::get('imageHeight')) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['fileheight'], $file['name'], \Config::get('imageHeight'))); unset($_FILES[$this->strName]); return; } } // Store file in the session and optionally on the server if (!$this->hasErrors()) { $_SESSION['FILES'][$this->strName] = $_FILES[$this->strName]; if ($this->storeFile) { $intUploadFolder = $this->uploadFolder; // Overwrite the upload folder with user's home directory if ($this->useHomeDir && FE_USER_LOGGED_IN) { $this->import('FrontendUser', 'User'); if ($this->User->assignDir && $this->User->homeDir) { $intUploadFolder = $this->User->homeDir; } } $objUploadFolder = \FilesModel::findByUuid($intUploadFolder); // The upload folder could not be found if ($objUploadFolder === null) { throw new \Exception("Invalid upload folder ID {$intUploadFolder}"); } $strUploadFolder = $objUploadFolder->path; // Store the file if the upload folder exists if ($strUploadFolder != '' && is_dir(TL_ROOT . '/' . $strUploadFolder)) { $this->import('Files'); // Do not overwrite existing files if ($this->doNotOverwrite && file_exists(TL_ROOT . '/' . $strUploadFolder . '/' . $file['name'])) { $offset = 1; $arrAll = scan(TL_ROOT . '/' . $strUploadFolder); $arrFiles = preg_grep('/^' . preg_quote($objFile->filename, '/') . '.*\\.' . preg_quote($objFile->extension, '/') . '/', $arrAll); foreach ($arrFiles as $strFile) { if (preg_match('/__[0-9]+\\.' . preg_quote($objFile->extension, '/') . '$/', $strFile)) { $strFile = str_replace('.' . $objFile->extension, '', $strFile); $intValue = intval(substr($strFile, strrpos($strFile, '_') + 1)); $offset = max($offset, $intValue); } } $file['name'] = str_replace($objFile->filename, $objFile->filename . '__' . ++$offset, $file['name']); } // Move the file to its destination $this->Files->move_uploaded_file($file['tmp_name'], $strUploadFolder . '/' . $file['name']); $this->Files->chmod($strUploadFolder . '/' . $file['name'], \Config::get('defaultFileChmod')); $strUuid = null; $strFile = $strUploadFolder . '/' . $file['name']; // Generate the DB entries if (\Dbafs::shouldBeSynchronized($strFile)) { $objModel = \FilesModel::findByPath($strFile); if ($objModel === null) { $objModel = \Dbafs::addResource($strFile); } $strUuid = \StringUtil::binToUuid($objModel->uuid); // Update the hash of the target folder \Dbafs::updateFolderHashes($strUploadFolder); } // Add the session entry (see #6986) $_SESSION['FILES'][$this->strName] = array('name' => $file['name'], 'type' => $file['type'], 'tmp_name' => TL_ROOT . '/' . $strFile, 'error' => $file['error'], 'size' => $file['size'], 'uploaded' => true, 'uuid' => $strUuid); // Add a log entry $this->log('File "' . $strUploadFolder . '/' . $file['name'] . '" has been uploaded', __METHOD__, TL_FILES); } } } unset($_FILES[$this->strName]); }
/** * * @param type $action * @param type $dc */ public function executePostActions($action, $dc) { if ($action == 'reloadFiletree_mcw' || $action == 'reloadPagetree_mcw') { //get the fieldname $strRef = $this->Session->get('filePickerRef'); $strRef = substr($strRef, stripos($strRef, 'field=') + 6); $arrRef = explode('&', $strRef); $strField = $arrRef[0]; //get value and fieldName $strFieldName = \Input::post('name'); $varValue = \Input::post('value'); //get the fieldname parts $arrfieldParts = preg_split('/_row[0-9]*_/i', $strFieldName); preg_match('/_row[0-9]*_/i', $strFieldName, $arrRow); $intRow = substr(substr($arrRow[0], 4), 0, -1); //build fieldname $strFieldName = $arrfieldParts[0] . '[' . $intRow . '][' . $arrfieldParts[1] . ']'; $strKey = $action == 'reloadPagetree_mcw' ? 'pageTree' : 'fileTree'; // Convert the selected values if ($varValue != '') { $varValue = trimsplit("\t", $varValue); // Automatically add resources to the DBAFS if ($strKey == 'fileTree') { if (version_compare(VERSION, '3.1', '>=') && version_compare(VERSION, '3.2', '<')) { $fileId = 'id'; } if (version_compare(VERSION, '3.2', '>=')) { $fileId = 'uuid'; } foreach ($varValue as $k => $v) { $varValue[$k] = \Dbafs::addResource($v)->{$fileId}; } } $varValue = serialize($varValue); } $arrAttribs['id'] = \Input::post('name'); $arrAttribs['name'] = $strFieldName; $arrAttribs['value'] = $varValue; $arrAttribs['strTable'] = $dc->table; $arrAttribs['strField'] = $strField; $objWidget = new $GLOBALS['BE_FFL'][$strKey]($arrAttribs); echo $objWidget->generate(); exit; break; } }
/** * Last Steps for all functions */ private function pageSyncToShowStep6() { /* --------------------------------------------------------------------- * Init */ if ($this->objStepPool->step == null) { $this->objStepPool->step = 1; } // Set content back to normale mode $this->booError = false; $this->strError = ""; $this->objData->setState(SyncCtoEnum::WORK_WORK); // Get the file list. $fileList = new \SyncCto\Sync\FileList\Base($this->arrListCompare); /* --------------------------------------------------------------------- * Run page */ try { switch ($this->objStepPool->step) { /** * Init */ case 1: $this->objData->setState(SyncCtoEnum::WORK_WORK); $this->objData->setDescription($GLOBALS['TL_LANG']['tl_syncCto_sync']["step_5"]['description_2']); $this->objData->setTitle($GLOBALS['TL_LANG']['MSC']['step'] . " %s"); $this->objStepPool->step++; break; case 2: $this->objSyncCtoCommunicationClient->purgeCache(); $this->objStepPool->step++; break; /** * Import files */ /** * Import files */ case 3: // Reset the msg. $this->objData->setDescription($GLOBALS['TL_LANG']['tl_syncCto_sync']["step_5"]['description_2']); $this->setErrorMsg(''); try { // Get the file list. $itCore = $fileList->getTransferCore(true, false); $itPrivate = $fileList->getTransferPrivate(true, false); $itDbafs = $fileList->getDbafs(true, false); $itOverall = $fileList->getTransferFiles(true, true); // Count some values. $waitingFiles = iterator_count($itCore) + iterator_count($itPrivate) + iterator_count($itDbafs); $overallFiles = iterator_count($itOverall); // Add the status. $this->objData->setDescription(sprintf($GLOBALS['TL_LANG']['tl_syncCto_sync']["step_3"]['description_2'], $overallFiles - $waitingFiles, $overallFiles)); // Check if we have some files. if ($waitingFiles == 0) { $this->objData->setHtml(''); $this->objStepPool->step++; break; } // Check for endless run. if ($waitingFiles == $this->arrSyncSettings['last_transfer']) { $this->objData->setHtml(''); $this->objData->setDescription($GLOBALS['TL_LANG']['tl_syncCto_sync']["step_5"]['description_1']); $this->setError(true); $this->setErrorMsg('Error on moving files. Some files could not be moved.'); break; } // Add the current count to the config. $this->arrSyncSettings['last_transfer'] = $waitingFiles; // Run core if we have files. if (iterator_count($itCore) != 0) { $arrTransmission = $this->objSyncCtoCommunicationClient->runFileImport(iterator_to_array($itCore), false); foreach ($arrTransmission as $key => $value) { $this->arrListCompare['core'][$key] = $value; } } else { if (iterator_count($itPrivate) != 0) { // Get only 100 files. $itSupSet = new LimitIterator($itPrivate, 0, 100); $itSupSet = iterator_to_array($itSupSet); // Get the dbafs information. foreach ($itSupSet as $key => $value) { // Get the information from the tl_files. $objModel = \FilesModel::findByPath($value['path']); // Okay we have the file ... if ($objModel != null) { $arrModelData = $objModel->row(); // PHP 7 compatibility // See #309 (https://github.com/contao/core-bundle/issues/309) if (version_compare(VERSION . '.' . BUILD, '3.5.5', '>=')) { $arrModelData['pid'] = strlen($arrModelData['pid']) ? \StringUtil::binToUuid($arrModelData['pid']) : $arrModelData['pid']; $arrModelData['uuid'] = \StringUtil::binToUuid($arrModelData['uuid']); } else { $arrModelData['pid'] = strlen($arrModelData['pid']) ? \String::binToUuid($arrModelData['pid']) : $arrModelData['pid']; $arrModelData['uuid'] = \String::binToUuid($arrModelData['uuid']); } } else { $objModel = \Dbafs::addResource($value['path']); $arrModelData = $objModel->row(); // PHP 7 compatibility // See #309 (https://github.com/contao/core-bundle/issues/309) if (version_compare(VERSION . '.' . BUILD, '3.5.5', '>=')) { $arrModelData['pid'] = strlen($arrModelData['pid']) ? \StringUtil::binToUuid($arrModelData['pid']) : $arrModelData['pid']; $arrModelData['uuid'] = \StringUtil::binToUuid($arrModelData['uuid']); } else { $arrModelData['pid'] = strlen($arrModelData['pid']) ? \String::binToUuid($arrModelData['pid']) : $arrModelData['pid']; $arrModelData['uuid'] = \String::binToUuid($arrModelData['uuid']); } } $itSupSet[$key]['tl_files'] = $arrModelData; } // Send the data to the client. $arrTransmission = $this->objSyncCtoCommunicationClient->runFileImport($itSupSet, true); // Add the information to the current list. foreach ($arrTransmission as $key => $value) { $this->arrListCompare['files'][$key] = $value; } } else { if (iterator_count($itDbafs) != 0) { // Get only 100 files. $itSupSet = new LimitIterator($itDbafs, 0, 100); // Send it to the client. $arrTransmission = $this->objSyncCtoCommunicationClient->updateDbafs(iterator_to_array($itSupSet)); // Update the current list. foreach ($arrTransmission as $key => $value) { // Set the state. if ($value['saved']) { $value["transmission"] = SyncCtoEnum::FILETRANS_SEND; } else { $value["transmission"] = SyncCtoEnum::FILETRANS_SKIPPED; } $this->arrListCompare['files'][$key] = $value; } } } } } catch (Exception $e) { $this->objData->setHtml(''); $this->objData->setDescription($e->getMessage()); $this->setError(true); $this->setErrorMsg('Error on moving files. Some files could not be moved.'); } break; /** * Delete Files */ /** * Delete Files */ case 4: // Reset the msg. $this->objData->setDescription($GLOBALS['TL_LANG']['tl_syncCto_sync']["step_5"]['description_2']); $this->setErrorMsg(''); try { // Get the file list. $itCore = $fileList->getDeletedCore(true); $itPrivate = $fileList->getDeletedPrivate(true); $itOverall = $fileList->getDeletedFiles(false); // Count some values. $waitingFiles = iterator_count($itCore) + iterator_count($itPrivate); $overallFiles = iterator_count($itOverall); // Add the status. $this->objData->setDescription(sprintf($GLOBALS['TL_LANG']['tl_syncCto_sync']["step_3"]['description_2'], $overallFiles - $waitingFiles, $overallFiles)); // Check if we have some files. if ($waitingFiles == 0) { $this->objData->setHtml(''); $this->objData->setDescription($GLOBALS['TL_LANG']['tl_syncCto_sync']["step_5"]['description_1']); $this->objStepPool->step++; break; } // Check for endless run. if ($waitingFiles == $this->arrSyncSettings['last_delete']) { $this->objData->setHtml(''); $this->objData->setDescription($GLOBALS['TL_LANG']['tl_syncCto_sync']["step_5"]['description_1']); $this->setError(true); $this->setErrorMsg('Error on deleting files. Some files could not be deleted.'); break; } // Add the current count to the config. $this->arrSyncSettings['last_delete'] = $waitingFiles; // Run core if we have files. if (iterator_count($itCore) != 0) { // Get only 100 files. $itSupSet = new LimitIterator($itCore, 0, 100); // Send them to the client. $arrTransmission = $this->objSyncCtoCommunicationClient->deleteFiles(iterator_to_array($itSupSet), false); // Add all information to the file list. foreach ($arrTransmission as $key => $value) { $this->arrListCompare['core'][$key] = $value; } } else { if (iterator_count($itPrivate) != 0) { // Get only 100 files. $itSupSet = new LimitIterator($itPrivate, 0, 100); // Send them to the client. $arrTransmission = $this->objSyncCtoCommunicationClient->deleteFiles(iterator_to_array($itSupSet), false); // Add all information to the file list. foreach ($arrTransmission as $key => $value) { $this->arrListCompare['files'][$key] = $value; } } } } catch (Exception $e) { // If there was an error just go on. The endless protection will // handle any problem. } break; case 5: $this->objSyncCtoCommunicationClient->createCache(); $this->objStepPool->step++; break; /** * Import Config */ /** * Import Config */ case 6: if ($this->arrSyncSettings["syncCto_Type"] == 'all' || in_array("localconfig_update", $this->arrSyncSettings["syncCto_Type"])) { $this->objSyncCtoCommunicationClient->runLocalConfigImport(); $this->objStepPool->step++; break; } $this->objStepPool->step++; /** * Import Config / Set show error */ /** * Import Config / Set show error */ case 7: $this->objSyncCtoCommunicationClient->setDisplayErrors($this->arrSyncSettings["syncCto_ShowError"]); $this->objStepPool->step++; break; /** * Import Config / Set referrer check */ /** * Import Config / Set referrer check */ case 8: if (is_array($this->arrSyncSettings["syncCto_Systemoperations_Maintenance"]) && count($this->arrSyncSettings["syncCto_Systemoperations_Maintenance"]) != 0) { $this->objSyncCtoCommunicationClient->runMaintenance($this->arrSyncSettings["syncCto_Systemoperations_Maintenance"]); } $this->objStepPool->step++; break; case 9: if ($this->arrSyncSettings["syncCto_AttentionFlag"] == true) { $this->objSyncCtoCommunicationClient->setAttentionFlag(false); } $this->log(vsprintf("Successfully finishing of synchronization client ID %s.", array(\Input::get("id"))), __CLASS__ . " " . __FUNCTION__, "INFO"); /** * Cleanup */ /** * Cleanup */ case 10: if (in_array("temp_folders", $this->arrSyncSettings["syncCto_Systemoperations_Maintenance"])) { $this->objSyncCtoCommunicationClient->purgeTempFolder(); $this->objSyncCtoFiles->purgeTemp(); } $this->objStepPool->step++; $this->objData->setState(SyncCtoEnum::WORK_OK); $this->objData->setHtml(""); $this->booRefresh = true; $this->intStep++; break; default: $this->objData->setState(SyncCtoEnum::WORK_OK); $this->objData->setHtml(""); $this->booRefresh = true; $this->intStep++; break; } } catch (Exception $exc) { $this->objStepPool->step++; $this->log(vsprintf("Error on synchronization client ID %s with msg: %s", array(\Input::get("id"), $exc->getMessage())), __CLASS__ . " " . __FUNCTION__, "ERROR"); } }
/** * Backup filesystem */ protected function pageFileBackupPage() { // Init | Set Step to 1 if ($this->intStep == 0) { // Init content $this->booError = false; $this->booAbort = false; $this->booFinished = false; $this->strError = ""; $this->booRefresh = true; $this->strUrl = "contao/main.php?do=syncCto_backups&table=tl_syncCto_backup_file&act=start"; $this->strGoBack = \Environment::get('base') . "contao/main.php?do=syncCto_backups&table=tl_syncCto_backup_file"; $this->strHeadline = $GLOBALS['TL_LANG']['tl_syncCto_backup_file']['edit']; $this->strInformation = ""; $this->intStep = 1; $this->floStart = microtime(true); $this->objData = new ContentData(array(), $this->intStep); // Reset some Sessions $this->resetStepPool(); } // Load step pool $this->loadStepPool(); // Set content back to normale mode $this->booRefresh = true; $this->objData->setStep(1); $this->objData->setState(SyncCtoEnum::WORK_WORK); $this->objData->setHtml(""); try { switch ($this->intStep) { case 1: $this->objData->setTitle($GLOBALS['TL_LANG']['MSC']['step'] . " %s"); $this->objData->setDescription($GLOBALS['TL_LANG']['tl_syncCto_backup_file']['step1']); $this->objData->setState(SyncCtoEnum::WORK_WORK); $this->objStepPool->zipname = ""; $this->objStepPool->skippedfiles = array(); $this->intStep++; break; case 2: if (!file_exists(TL_ROOT . '/' . SyncCtoHelper::getInstance()->standardizePath($GLOBALS['SYC_PATH']['file']))) { throw new Exception(sprintf($GLOBALS['TL_LANG']['ERR']['missing_file_folder'], SyncCtoHelper::getInstance()->standardizePath($GLOBALS['SYC_PATH']['file']))); } $arrResult = $this->objSyncCtoFiles->runDump($this->arrBackupSettings['backup_name'], $this->arrBackupSettings['core_files'], $this->arrBackupSettings['filelist']); $this->objStepPool->zipname = $arrResult["name"]; $this->objStepPool->skippedfiles = $arrResult["skipped"]; \Dbafs::addResource(SyncCtoHelper::getInstance()->standardizePath($GLOBALS['SYC_PATH']['file'], $this->objStepPool->zipname)); $this->intStep++; break; case 3: $this->booFinished = true; $this->booRefresh = false; $this->objData->setStep(1); $this->objData->setState(SyncCtoEnum::WORK_OK); $strHTML = "<p class='tl_help'><br />"; $strHTML .= "<a onclick=\"Backend.openModalIframe({'width':600,'title':'" . $this->objStepPool->zipname . "','url':this.href,'height':216});return false\" href='contao/popup.php?src=" . base64_encode($GLOBALS['TL_CONFIG']['uploadPath'] . "/syncCto_backups/files/" . $this->objStepPool->zipname) . "'>" . $GLOBALS['TL_LANG']['MSC']['fileDownload'] . "</a>"; $strHTML .= "</p>"; if (count($this->objStepPool->skippedfiles) != 0) { $strHTML = '<br /><p class="tl_help">' . count($this->objStepPool->skippedfiles) . $GLOBALS['TL_LANG']['MSC']['skipped_files'] . '</p>'; $strHTML .= '<ul class="fileinfo">'; foreach ($this->objStepPool->skippedfiles as $value) { $strHTML .= "<li>" . $value . "</li>"; } $strHTML .= "</ul>"; } $this->objData->setStep(2); $this->objData->setTitle($GLOBALS['TL_LANG']['MSC']['complete']); $this->objData->setDescription($GLOBALS['TL_LANG']['tl_syncCto_backup_file']['complete'] . " " . $this->objStepPool->zipname); $this->objData->setHtml($strHTML); $this->objData->setState(SyncCtoEnum::WORK_OK); break; } } catch (Exception $exc) { $objErrTemplate = new BackendTemplate('be_syncCto_error'); $objErrTemplate->strErrorMsg = $exc->getMessage(); $this->booRefresh = false; $this->objData->setState(SyncCtoEnum::WORK_ERROR); $this->objData->setHtml($objErrTemplate->parse()); } }