/**
  * Update FileTree fields
  */
 public function updateFileTreeFields()
 {
     $objDatabase = \Database::getInstance();
     $arrFields = array('singleSRC', 'imgSRC');
     // Check the column type
     $objDesc = $objDatabase->query("DESC tl_downloadarchiveitems singleSRC");
     // Change the column type
     if ($objDesc->Type != 'binary(16)') {
         foreach ($arrFields as $field) {
             $objFiles = $objDatabase->execute("SELECT id,{$field} FROM tl_downloadarchiveitems");
             $objDatabase->query("ALTER TABLE tl_downloadarchiveitems CHANGE {$field} {$field} binary(16) NULL");
             #$objDatabase->query("UPDATE tl_downloadarchiveitems SET $field=NULL WHERE $field='' OR $field=0");
             while ($objFiles->next()) {
                 $objHelper = $this->generateHelperObject($this->changePath($objFiles->{$field}));
                 // UUID already
                 if ($objHelper->isUuid) {
                     continue;
                 }
                 // Numeric ID to UUID
                 if ($objHelper->isNumeric) {
                     $objFile = \FilesModel::findByPk($objHelper->value);
                     $objDatabase->prepare("UPDATE tl_downloadarchiveitems SET {$field}=? WHERE id=?")->execute($objFile->uuid, $objFiles->id);
                 } else {
                     $objFile = \FilesModel::findByPath($objHelper->value);
                     $objDatabase->prepare("UPDATE tl_downloadarchiveitems SET {$field}=? WHERE id=?")->execute($objFile->uuid, $objFiles->id);
                 }
             }
         }
     }
 }
 /**
  * Transforms a value from the transformed representation to its original
  * representation.
  * An example might be transforming a human readable date format to a unix timestamp.
  *
  * @param mixed $value The value in the transformed representation
  *
  * @return mixed The value in the original representation
  *
  * @throws TransformationFailedException When the transformation fails.
  */
 public function reverseTransform($value)
 {
     $filesModel = \FilesModel::findByPath($value);
     if (null === $filesModel) {
         return $value;
     }
     return $filesModel->uuid;
 }
Esempio n. 3
0
 /**
  * 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();
     }
     // Add the resource (see #6880)
     if (($objModel = FilesModel::findByPath($this->strFile)) === null) {
         $objModel = Dbafs::addResource($this->strFile);
     }
     $this->Template = new BackendTemplate('be_popup');
     $this->Template->uuid = String::binToUuid($objModel->uuid);
     // see #5211
     // Add the file info
     if (is_dir(TL_ROOT . '/' . $this->strFile)) {
         $objFile = new Folder($this->strFile, true);
     } else {
         $objFile = new File($this->strFile, true);
         // Image
         if ($objFile->isGdImage) {
             $this->Template->isImage = true;
             $this->Template->width = $objFile->width;
             $this->Template->height = $objFile->height;
             $this->Template->src = $this->urlEncode($this->strFile);
         }
         $this->Template->href = ampersand(Environment::get('request'), true) . '&download=1';
         $this->Template->filesize = $this->getReadableSize($objFile->filesize) . ' (' . number_format($objFile->filesize, 0, $GLOBALS['TL_LANG']['MSC']['decimalSeparator'], $GLOBALS['TL_LANG']['MSC']['thousandsSeparator']) . ' Byte)';
     }
     $this->Template->icon = $objFile->icon;
     $this->Template->mime = $objFile->mime;
     $this->Template->ctime = Date::parse(Config::get('datimFormat'), $objFile->ctime);
     $this->Template->mtime = Date::parse(Config::get('datimFormat'), $objFile->mtime);
     $this->Template->atime = Date::parse(Config::get('datimFormat'), $objFile->atime);
     $this->Template->path = $this->strFile;
     $this->output();
 }
 public function executeResizeHook($objImage)
 {
     if (TL_MODE == 'BE') {
         return false;
     }
     // do not return a string to not interrupt Image::executeResize
     $objFile = \FilesModel::findByPath($objImage->getOriginalPath());
     if ($objFile !== null) {
         FileCreditIndex::indexFile($objFile);
     }
     return false;
     // do not return a string to not interrupt Image::executeResize
 }
 /**
  * Renames the given files
  *
  * @param array $arrFiles
  *
  * @return none
  */
 public function renameFiles($arrFiles)
 {
     if (!$GLOBALS['TL_CONFIG']['checkFilenames']) {
         return null;
     }
     $this->Import('Files');
     $this->Import('FilesModel');
     if (!empty($arrFiles)) {
         foreach ($arrFiles as $file) {
             // rename physical file
             $newFile = $this->replaceForbiddenCharacters($file);
             // because the \Files renaming function is doing
             $this->Files->rename($file, $newFile . '.tmp');
             $this->Files->rename($newFile . '.tmp', $newFile);
             // rename file in database
             $objFile = \FilesModel::findByPath($file);
             $objFile->path = $newFile;
             $objFile->hash = md5_file(TL_ROOT . '/' . $newFile);
             $objFile->save();
         }
     }
 }
Esempio n. 6
0
File: Theme.php Progetto: Jobu/core
 /**
  * Recursively add a folder to the archive
  *
  * @param \ZipWriter           $objArchive
  * @param string               $strFolder
  * @param \DOMDocument         $xml
  * @param \DOMNode|\DOMElement $table
  * @param array                $arrOrder
  *
  * @throws \Exception If the folder path is insecure
  */
 protected function addFolderToArchive(\ZipWriter $objArchive, $strFolder, \DOMDocument $xml, \DOMElement $table, array $arrOrder = array())
 {
     // Strip the custom upload folder name
     $strFolder = preg_replace('@^' . preg_quote(\Config::get('uploadPath'), '@') . '/@', '', $strFolder);
     // Add the default upload folder name
     if ($strFolder == '') {
         $strTarget = 'files';
         $strFolder = \Config::get('uploadPath');
     } else {
         $strTarget = 'files/' . $strFolder;
         $strFolder = \Config::get('uploadPath') . '/' . $strFolder;
     }
     if (\Validator::isInsecurePath($strFolder)) {
         throw new \RuntimeException('Insecure path ' . $strFolder);
     }
     // Return if the folder does not exist
     if (!is_dir(TL_ROOT . '/' . $strFolder)) {
         return;
     }
     // Recursively add the files and subfolders
     foreach (scan(TL_ROOT . '/' . $strFolder) as $strFile) {
         // Skip hidden resources
         if (strncmp($strFile, '.', 1) === 0) {
             continue;
         }
         if (is_dir(TL_ROOT . '/' . $strFolder . '/' . $strFile)) {
             $this->addFolderToArchive($objArchive, $strFolder . '/' . $strFile, $xml, $table, $arrOrder);
         } else {
             // Always store files in files and convert the directory upon import
             $objArchive->addFile($strFolder . '/' . $strFile, $strTarget . '/' . $strFile);
             $arrRow = array();
             $objFile = new \File($strFolder . '/' . $strFile, true);
             $objModel = \FilesModel::findByPath($strFolder . '/' . $strFile);
             if ($objModel !== null) {
                 $arrRow = $objModel->row();
                 foreach (array('id', 'pid', 'tstamp', 'uuid', 'type', 'extension', 'found', 'name') as $key) {
                     unset($arrRow[$key]);
                 }
             }
             // Always use files as directory and convert it upon import
             $arrRow['path'] = $strTarget . '/' . $strFile;
             $arrRow['hash'] = $objFile->hash;
             // Add the row
             $this->addDataRow($xml, $table, $arrRow, $arrOrder);
         }
     }
 }
 /**
  * Create a new user based on the given data
  * @param array
  * @return boolean
  */
 protected function createNewUser($arrProfile)
 {
     \System::loadLanguageFile('tl_member');
     $this->loadDataContainer('tl_member');
     // Call onload_callback (e.g. to check permissions)
     if (is_array($GLOBALS['TL_DCA']['tl_member']['config']['onload_callback'])) {
         foreach ($GLOBALS['TL_DCA']['tl_member']['config']['onload_callback'] as $callback) {
             if (is_array($callback)) {
                 $this->import($callback[0]);
                 $this->{$callback}[0]->{$callback}[1]();
             }
         }
     }
     $time = time();
     $arrData = array('tstamp' => $time, 'dateAdded' => $time, 'firstname' => $arrProfile['first_name'], 'lastname' => $arrProfile['last_name'], 'gender' => $arrProfile['gender'], 'email' => $arrProfile['email'], 'login' => 1, 'username' => 'fb_' . $arrProfile['id'], 'fblogin' => $arrProfile['id'], 'groups' => $this->reg_groups);
     $blnHasError = false;
     // Check the data
     foreach ($arrData as $k => $v) {
         if (!isset($GLOBALS['TL_DCA']['tl_member']['fields'][$k])) {
             unset($arrData[$k]);
             continue;
         }
         $arrField = $GLOBALS['TL_DCA']['tl_member']['fields'][$k];
         // Make sure that unique fields are unique
         if ($arrField['eval']['unique'] && $v != '' && !$this->Database->isUniqueValue('tl_member', $k, $v)) {
             $blnHasError = true;
             \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['unique'], $arrField['label'][0] ?: $k));
             continue;
         }
         // Save callback
         if (is_array($arrField['save_callback'])) {
             foreach ($arrField['save_callback'] as $callback) {
                 $this->import($callback[0]);
                 try {
                     $v = $this->{$callback}[0]->{$callback}[1]($v, null);
                 } catch (\Exception $e) {
                     $blnHasError = true;
                     \Message::addError($e->getMessage());
                 }
             }
             $arrData[$k] = $v;
         }
     }
     // HOOK: parse data before it is saved
     if (isset($GLOBALS['TL_HOOKS']['validateFacebookLogin']) && is_array($GLOBALS['TL_HOOKS']['validateFacebookLogin'])) {
         foreach ($GLOBALS['TL_HOOKS']['validateFacebookLogin'] as $callback) {
             $this->import($callback[0]);
             try {
                 $arrData = $this->{$callback}[0]->{$callback}[1]($arrData, $arrProfile);
             } catch (\Exception $e) {
                 $blnHasError = true;
                 \Message::addError($e->getMessage());
             }
         }
     }
     // Return false if there is an error
     if ($blnHasError) {
         return false;
     }
     $objNewUser = new \MemberModel();
     $objNewUser->setRow($arrData);
     $objNewUser->save();
     // Assign home directory
     if ($this->reg_assignDir) {
         $objHomeDir = \FilesModel::findByUuid($this->reg_homeDir);
         if ($objHomeDir !== null) {
             $this->import('Files');
             $strUserDir = standardize($arrData['username']) ?: 'user_' . $objNewUser->id;
             // Add the user ID if the directory exists
             while (is_dir(TL_ROOT . '/' . $objHomeDir->path . '/' . $strUserDir)) {
                 $strUserDir .= '_' . $objNewUser->id;
             }
             // Create the user folder
             new \Folder($objHomeDir->path . '/' . $strUserDir);
             $objUserDir = \FilesModel::findByPath($objHomeDir->path . '/' . $strUserDir);
             // Save the folder ID
             $objNewUser->assignDir = 1;
             $objNewUser->homeDir = $objUserDir->uuid;
             $objNewUser->save();
         }
     }
     $insertId = $objNewUser->id;
     // HOOK: send insert ID and user data
     if (isset($GLOBALS['TL_HOOKS']['createNewUser']) && is_array($GLOBALS['TL_HOOKS']['createNewUser'])) {
         foreach ($GLOBALS['TL_HOOKS']['createNewUser'] as $callback) {
             $this->import($callback[0]);
             $this->{$callback}[0]->{$callback}[1]($insertId, $arrData, $this, $arrProfile);
         }
     }
     return true;
 }
Esempio n. 8
0
 /**
  * Recursively synchronize the file system
  * @param string
  * @param integer
  */
 protected function execSync($strPath, $intPid = 0)
 {
     if (!$this->blnIsDbAssisted) {
         return;
     }
     $arrFiles = array();
     $arrFolders = array();
     $arrScan = scan(TL_ROOT . '/' . $strPath);
     // Separate files from folders
     foreach ($arrScan as $strFile) {
         if ($strFile == '.svn' || $strFile == '.DS_Store') {
             continue;
         }
         if (is_dir(TL_ROOT . '/' . $strPath . '/' . $strFile)) {
             $arrFolders[] = $strPath . '/' . $strFile;
         } else {
             $arrFiles[] = $strPath . '/' . $strFile;
         }
     }
     // Folders
     foreach ($arrFolders as $strFolder) {
         $objFolder = new \Folder($strFolder);
         $objModel = \FilesModel::findByPath($strFolder);
         // Create the entry if it does not yet exist
         if ($objModel === null) {
             $objModel = new \FilesModel();
             $objModel->pid = $intPid;
             $objModel->tstamp = time();
             $objModel->name = basename($strFolder);
             $objModel->type = 'folder';
             $objModel->path = $strFolder;
             $objModel->hash = $objFolder->hash;
             $objModel->found = 1;
             $objModel->save();
             $this->arrMessages[] = '<p class="tl_new">' . sprintf($GLOBALS['TL_LANG']['tl_files']['syncFolderC'], $strFolder) . '</p>';
         } else {
             // Update the hash if the folder has changed
             if ($objModel->hash != $objFolder->hash) {
                 $objModel->hash = $objFolder->hash;
                 $this->arrMessages[] = '<p class="tl_info">' . sprintf($GLOBALS['TL_LANG']['tl_files']['syncHash'], $strFolder) . '</p>';
             }
             $objModel->found = 1;
             $objModel->save();
             $this->arrMessages[] = '<p class="tl_confirm">' . sprintf($GLOBALS['TL_LANG']['tl_files']['syncFolderF'], $strFolder) . '</p>';
         }
         $this->execSync($strFolder, $objModel->id);
     }
     // Files
     foreach ($arrFiles as $strFile) {
         $objFile = new \File($strFile);
         $objModel = \FilesModel::findByPath($strFile);
         // Create the entry if it does not yet exist
         if ($objModel === null) {
             $objModel = new \FilesModel();
             $objModel->pid = $intPid;
             $objModel->tstamp = time();
             $objModel->name = basename($strFile);
             $objModel->type = 'file';
             $objModel->path = $strFile;
             $objModel->extension = $objFile->extension;
             $objModel->hash = $objFile->hash;
             $objModel->found = 1;
             $objModel->save();
             $this->arrMessages[] = '<p class="tl_new">' . sprintf($GLOBALS['TL_LANG']['tl_files']['syncFileC'], $strFile) . '</p>';
         } else {
             // Update the hash if the file has changed
             if ($objModel->hash != $objFile->hash) {
                 $objModel->hash = $objFile->hash;
                 $this->arrMessages[] = '<p class="tl_info">' . sprintf($GLOBALS['TL_LANG']['tl_files']['syncHash'], $strFile) . '</p>';
             }
             $objModel->found = 1;
             $objModel->save();
             $this->arrMessages[] = '<p class="tl_confirm">' . sprintf($GLOBALS['TL_LANG']['tl_files']['syncFileF'], $strFile) . '</p>';
         }
     }
 }
Esempio n. 9
0
 /**
  * @param $strTable
  * @param array $options
  */
 public static function exportTable($strTable, array $options = array())
 {
     // Defaults
     $preDefinedOptions = array('strSorting' => 'id ASC', 'exportType' => 'csv', 'strSeperator' => ';', 'strEnclosure' => '"', 'arrFilter' => array(), 'strDestinationCharset' => '', 'strDestination' => '', 'arrSelectedFields' => null);
     $options = array_merge($preDefinedOptions, $options);
     $strSorting = $options['strSorting'];
     $exportType = $options['exportType'];
     $strSeperator = $options['strSeperator'];
     $strEnclosure = $options['strEnclosure'];
     $arrFilter = $options['arrFilter'];
     $strDestinationCharset = $options['strDestinationCharset'];
     $strDestination = $options['strDestination'];
     $arrSelectedFields = $options['arrSelectedFields'];
     $arrData = array();
     // Load Datacontainer
     if (!is_array($GLOBALS['TL_DCA'][$strTable])) {
         \Controller::loadDataContainer($strTable, true);
     }
     $dca = array();
     if (is_array($GLOBALS['TL_DCA'][$strTable])) {
         $dca = $GLOBALS['TL_DCA'][$strTable];
     }
     // If no fields are selected, then list the whole table
     if ($arrSelectedFields === null || empty($arrSelectedFields)) {
         $arrSelectedFields = \Database::getInstance()->getFieldNames($strTable);
     }
     // create headline
     $arrHeadline = array();
     foreach ($arrSelectedFields as $fieldname) {
         $arrHeadline[] = $fieldname;
     }
     $arrData[] = $arrHeadline;
     // add rows to $arrData
     if (empty($arrFilter) || !is_array($arrFilter)) {
         $arrFilter = array();
     }
     $arrProcedures = [];
     $arrValues = [];
     foreach ($arrFilter as $filter) {
         $arrProcedures[] = $filter[0];
         $arrValues[] = $filter[1];
     }
     $arrProcedures[] = "id>=?";
     $arrValues[] = 0;
     $arrFieldInfo = self::listFields($strTable);
     $objDb = \Database::getInstance()->prepare("SELECT * FROM  " . $strTable . " WHERE " . implode(' AND ', $arrProcedures) . " ORDER BY " . $strSorting)->execute($arrValues);
     while ($dataRecord = $objDb->fetchAssoc()) {
         $arrRow = array();
         foreach ($arrSelectedFields as $field) {
             $value = $dataRecord[$field];
             // Handle binaries
             if ($value != '') {
                 switch (strtolower($arrFieldInfo[$field]['type'])) {
                     case 'binary':
                     case 'varbinary':
                     case 'blob':
                     case 'tinyblob':
                     case 'mediumblob':
                     case 'longblob':
                         $value = "0x" . bin2hex($value);
                         break;
                     default:
                         //
                         break;
                 }
             }
             // HOOK: add custom value
             if (isset($GLOBALS['TL_HOOKS']['exportTable']) && is_array($GLOBALS['TL_HOOKS']['exportTable'])) {
                 foreach ($GLOBALS['TL_HOOKS']['exportTable'] as $callback) {
                     $objCallback = \System::importStatic($callback[0]);
                     $value = $objCallback->{$callback}[1]($field, $value, $strTable, $dataRecord, $dca);
                 }
             }
             $arrRow[] = $value;
         }
         $arrData[] = $arrRow;
     }
     // xml-output
     if ($exportType == 'xml') {
         $objXml = new \XMLWriter();
         $objXml->openMemory();
         $objXml->setIndent(true);
         $objXml->setIndentString("\t");
         $objXml->startDocument('1.0', $strDestinationCharset != '' ? $strDestinationCharset : 'UTF-8');
         $objXml->startElement($strTable);
         foreach ($arrData as $row => $arrRow) {
             // Headline
             if ($row == 0) {
                 continue;
             }
             // New row
             $objXml->startElement('datarecord');
             //$objXml->writeAttribute('index', $row);
             foreach ($arrRow as $i => $fieldvalue) {
                 // New field
                 $objXml->startElement($arrHeadline[$i]);
                 // Write Attributes
                 //$objXml->writeAttribute('name', $arrHeadline[$i]);
                 //$objXml->writeAttribute('type', gettype($fieldvalue));
                 //$objXml->writeAttribute('origtype', $arrFieldInfo[$arrHeadline[$i]]['type']);
                 // Convert to charset
                 if ($strDestinationCharset != '') {
                     $fieldvalue = iconv("UTF-8", $strDestinationCharset, $fieldvalue);
                 }
                 if (is_numeric($fieldvalue) || is_null($fieldvalue) || $fieldvalue == '') {
                     $objXml->text($fieldvalue);
                 } else {
                     // Write CDATA
                     $objXml->writeCdata($fieldvalue);
                 }
                 $objXml->endElement();
                 //end field-tag
             }
             $objXml->endElement();
             // End row-tag
         }
         $objXml->endElement();
         // End table-tag
         $objXml->endDocument();
         $xml = $objXml->outputMemory();
         // Write output to file system
         if ($strDestination != '') {
             new \Folder($strDestination);
             $objFolder = \FilesModel::findByPath($strDestination);
             if ($objFolder !== null) {
                 if ($objFolder->type == 'folder' && is_dir(TL_ROOT . '/' . $objFolder->path)) {
                     $objFile = new \File($objFolder->path . '/' . $strTable . '_' . \Date::parse('Y-m-d_H-i-s') . '.csv');
                     $objFile->write($xml);
                     $objFile->close();
                     return;
                 }
             }
         }
         // Send file to browser
         header('Content-type: text/xml');
         header('Content-Disposition: attachment; filename="' . $strTable . '.xml"');
         echo $xml;
         exit;
     }
     // csv-output
     if ($exportType == 'csv') {
         // Write output to file system
         if ($strDestination != '') {
             new \Folder($strDestination);
             $objFolder = \FilesModel::findByPath($strDestination);
             if ($objFolder !== null) {
                 if ($objFolder->type == 'folder' && is_dir(TL_ROOT . '/' . $objFolder->path)) {
                     $objFile = new \File($objFolder->path . '/' . $strTable . '_' . \Date::parse('Y-m-d_H-i-s') . '.csv');
                     foreach ($arrData as $arrRow) {
                         $arrLine = array_map(function ($v) use($strDestinationCharset) {
                             if ($strDestinationCharset != '') {
                                 $v = iconv("UTF-8", $strDestinationCharset, $v);
                             }
                             return html_entity_decode($v);
                         }, $arrRow);
                         self::fputcsv($objFile->handle, $arrLine, $strSeperator, $strEnclosure);
                     }
                     $objFile->close();
                 }
             }
             return;
         }
         // Send file to browser
         header("Content-type: text/csv");
         header("Content-Disposition: attachment; filename=" . $strTable . ".csv");
         header("Content-Description: csv File");
         header("Pragma: no-cache");
         header("Expires: 0");
         $fh = fopen("php://output", 'w');
         foreach ($arrData as $arrRow) {
             $arrLine = array_map(function ($v) use($strDestinationCharset) {
                 if ($strDestinationCharset != '') {
                     $v = iconv("UTF-8", $strDestinationCharset, $v);
                 }
                 return html_entity_decode($v);
             }, $arrRow);
             self::fputcsv($fh, $arrLine, $strSeperator, $strEnclosure);
         }
         fclose($fh);
         exit;
     }
 }
Esempio n. 10
0
 /**
  * Return the files model
  *
  * @return FilesModel The files model
  */
 public function getModel()
 {
     if ($this->objModel === null && \Dbafs::shouldBeSynchronized($this->strFolder)) {
         $this->objModel = \FilesModel::findByPath($this->strFolder);
     }
     return $this->objModel;
 }
Esempio n. 11
0
 /**
  * Synchronize the file system with the database
  *
  * @return string The path to the synchronization log file
  *
  * @throws \Exception If a parent ID entry is missing
  */
 public static function syncFiles()
 {
     // Try to raise the limits (see #7035)
     @ini_set('memory_limit', -1);
     @ini_set('max_execution_time', 0);
     $objDatabase = \Database::getInstance();
     // Lock the files table
     $objDatabase->lockTables(array('tl_files'));
     // Reset the "found" flag
     $objDatabase->query("UPDATE tl_files SET found=''");
     // Get a filtered list of all files
     $objFiles = new \RecursiveIteratorIterator(new \Dbafs\Filter(new \RecursiveDirectoryIterator(TL_ROOT . '/' . \Config::get('uploadPath'), \FilesystemIterator::UNIX_PATHS | \FilesystemIterator::FOLLOW_SYMLINKS | \FilesystemIterator::SKIP_DOTS)), \RecursiveIteratorIterator::SELF_FIRST);
     $strLog = 'system/tmp/' . md5(uniqid(mt_rand(), true));
     // Open the log file
     $objLog = new \File($strLog, true);
     $objLog->truncate();
     $arrModels = array();
     // Create or update the database entries
     foreach ($objFiles as $objFile) {
         $strRelpath = str_replace(TL_ROOT . '/', '', $objFile->getPathname());
         // Get all subfiles in a single query
         if ($objFile->isDir()) {
             $objSubfiles = \FilesModel::findMultipleFilesByFolder($strRelpath);
             if ($objSubfiles !== null) {
                 while ($objSubfiles->next()) {
                     $arrModels[$objSubfiles->path] = $objSubfiles->current();
                 }
             }
         }
         // Get the model
         if (isset($arrModels[$strRelpath])) {
             $objModel = $arrModels[$strRelpath];
         } else {
             $objModel = \FilesModel::findByPath($strRelpath);
         }
         if ($objModel === null) {
             // Add a log entry
             $objLog->append("[Added] {$strRelpath}");
             // Get the parent folder
             $strParent = dirname($strRelpath);
             // Get the parent ID
             if ($strParent == \Config::get('uploadPath')) {
                 $strPid = null;
             } else {
                 $objParent = \FilesModel::findByPath($strParent);
                 if ($objParent === null) {
                     throw new \Exception("No parent entry for {$strParent}");
                 }
                 $strPid = $objParent->uuid;
             }
             // Create the file or folder
             if (is_file(TL_ROOT . '/' . $strRelpath)) {
                 $objFile = new \File($strRelpath, true);
                 $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->found = 2;
                 $objModel->hash = $objFile->hash;
                 $objModel->uuid = $objDatabase->getUuid();
                 $objModel->save();
             } else {
                 $objFolder = new \Folder($strRelpath);
                 $objModel = new \FilesModel();
                 $objModel->pid = $strPid;
                 $objModel->tstamp = time();
                 $objModel->name = $objFolder->name;
                 $objModel->type = 'folder';
                 $objModel->path = $objFolder->path;
                 $objModel->extension = '';
                 $objModel->found = 2;
                 $objModel->hash = $objFolder->hash;
                 $objModel->uuid = $objDatabase->getUuid();
                 $objModel->save();
             }
         } else {
             // Check whether the MD5 hash has changed
             $objResource = $objFile->isDir() ? new \Folder($strRelpath) : new \File($strRelpath);
             $strType = $objModel->hash != $objResource->hash ? 'Changed' : 'Unchanged';
             // Add a log entry
             $objLog->append("[{$strType}] {$strRelpath}");
             // Update the record
             $objModel->found = 1;
             $objModel->hash = $objResource->hash;
             $objModel->save();
         }
     }
     // Check for left-over entries in the DB
     $objFiles = \FilesModel::findByFound('');
     if ($objFiles !== null) {
         $arrMapped = array();
         $arrPidUpdate = array();
         while ($objFiles->next()) {
             $objFound = \FilesModel::findBy(array('hash=?', 'found=2'), $objFiles->hash);
             if ($objFound !== null) {
                 // Check for matching file names if the result is ambiguous (see #5644)
                 if ($objFound->count() > 1) {
                     while ($objFound->next()) {
                         if ($objFound->name == $objFiles->name) {
                             $objFound = $objFound->current();
                             break;
                         }
                     }
                 }
                 // If another file has been mapped already, delete the entry (see #6008)
                 if (in_array($objFound->path, $arrMapped)) {
                     $objLog->append("[Deleted] {$objFiles->path}");
                     $objFiles->delete();
                     continue;
                 }
                 $arrMapped[] = $objFound->path;
                 // Store the PID change
                 if ($objFiles->type == 'folder') {
                     $arrPidUpdate[$objFound->uuid] = $objFiles->uuid;
                 }
                 // Add a log entry BEFORE changing the object
                 $objLog->append("[Moved] {$objFiles->path} to {$objFound->path}");
                 // Update the original entry
                 $objFiles->pid = $objFound->pid;
                 $objFiles->tstamp = $objFound->tstamp;
                 $objFiles->name = $objFound->name;
                 $objFiles->type = $objFound->type;
                 $objFiles->path = $objFound->path;
                 $objFiles->found = 1;
                 // Delete the newer (duplicate) entry
                 $objFound->delete();
                 // Then save the modified original entry (prevents duplicate key errors)
                 $objFiles->save();
             } else {
                 // Add a log entry BEFORE changing the object
                 $objLog->append("[Deleted] {$objFiles->path}");
                 // Delete the entry if the resource has gone
                 $objFiles->delete();
             }
         }
         // Update the PID of the child records
         if (!empty($arrPidUpdate)) {
             foreach ($arrPidUpdate as $from => $to) {
                 $objChildren = \FilesModel::findByPid($from);
                 if ($objChildren !== null) {
                     while ($objChildren->next()) {
                         $objChildren->pid = $to;
                         $objChildren->save();
                     }
                 }
             }
         }
     }
     // Close the log file
     $objLog->close();
     // Reset the found flag
     $objDatabase->query("UPDATE tl_files SET found=1 WHERE found=2");
     // Unlock the tables
     $objDatabase->unlockTables();
     // Return the path to the log file
     return $strLog;
 }
Esempio n. 12
0
    /**
     * Load the source editor
     *
     * @return string
     */
    public function source()
    {
        $this->isValid($this->intId);
        if (is_dir(TL_ROOT . '/' . $this->intId)) {
            $this->log('Folder "' . $this->intId . '" cannot be edited', __METHOD__, TL_ERROR);
            $this->redirect('contao/main.php?act=error');
        } elseif (!file_exists(TL_ROOT . '/' . $this->intId)) {
            $this->log('File "' . $this->intId . '" does not exist', __METHOD__, TL_ERROR);
            $this->redirect('contao/main.php?act=error');
        }
        $this->import('BackendUser', 'User');
        // Check user permission
        if (!$this->User->hasAccess('f5', 'fop')) {
            $this->log('Not enough permissions to edit the file source of file "' . $this->intId . '"', __METHOD__, TL_ERROR);
            $this->redirect('contao/main.php?act=error');
        }
        $objFile = new \File($this->intId, true);
        // Check whether file type is editable
        if (!in_array($objFile->extension, trimsplit(',', strtolower(\Config::get('editableFiles'))))) {
            $this->log('File type "' . $objFile->extension . '" (' . $this->intId . ') is not allowed to be edited', __METHOD__, TL_ERROR);
            $this->redirect('contao/main.php?act=error');
        }
        $objMeta = null;
        $objVersions = null;
        // Add the versioning routines
        if ($this->blnIsDbAssisted && \Dbafs::shouldBeSynchronized($this->intId)) {
            $objMeta = \FilesModel::findByPath($objFile->value);
            if ($objMeta === null) {
                $objMeta = \Dbafs::addResource($objFile->value);
            }
            $objVersions = new \Versions($this->strTable, $objMeta->id);
            if (!$GLOBALS['TL_DCA'][$this->strTable]['config']['hideVersionMenu']) {
                // Compare versions
                if (\Input::get('versions')) {
                    $objVersions->compare();
                }
                // Restore a version
                if (\Input::post('FORM_SUBMIT') == 'tl_version' && \Input::post('version') != '') {
                    $objVersions->restore(\Input::post('version'));
                    // Purge the script cache (see #7005)
                    if ($objFile->extension == 'css' || $objFile->extension == 'scss' || $objFile->extension == 'less') {
                        $this->import('Automator');
                        $this->Automator->purgeScriptCache();
                    }
                    $this->reload();
                }
            }
            $objVersions->initialize();
        }
        $strContent = $objFile->getContent();
        if ($objFile->extension == 'svgz') {
            $strContent = gzdecode($strContent);
        }
        // Process the request
        if (\Input::post('FORM_SUBMIT') == 'tl_files') {
            // Restore the basic entities (see #7170)
            $strSource = \StringUtil::restoreBasicEntities(\Input::postRaw('source'));
            // Save the file
            if (md5($strContent) != md5($strSource)) {
                if ($objFile->extension == 'svgz') {
                    $strSource = gzencode($strSource);
                }
                // Write the file
                $objFile->write($strSource);
                $objFile->close();
                // Update the database
                if ($this->blnIsDbAssisted && $objMeta !== null) {
                    /** @var \FilesModel $objMeta */
                    $objMeta->hash = $objFile->hash;
                    $objMeta->save();
                    $objVersions->create();
                }
                // Purge the script cache (see #7005)
                if ($objFile->extension == 'css' || $objFile->extension == 'scss' || $objFile->extension == 'less') {
                    $this->import('Automator');
                    $this->Automator->purgeScriptCache();
                }
            }
            if (\Input::post('saveNclose')) {
                \System::setCookie('BE_PAGE_OFFSET', 0, 0);
                $this->redirect($this->getReferer());
            }
            $this->reload();
        }
        $codeEditor = '';
        // Prepare the code editor
        if (\Config::get('useCE')) {
            $selector = 'ctrl_source';
            $type = $objFile->extension;
            // Load the code editor configuration
            ob_start();
            include TL_ROOT . '/system/config/ace.php';
            $codeEditor = ob_get_contents();
            ob_end_clean();
            unset($selector, $type);
        }
        // Versions overview
        if ($GLOBALS['TL_DCA'][$this->strTable]['config']['enableVersioning'] && !$GLOBALS['TL_DCA'][$this->strTable]['config']['hideVersionMenu'] && $this->blnIsDbAssisted && $objVersions !== null) {
            $version = $objVersions->renderDropdown();
        } else {
            $version = '';
        }
        // Submit buttons
        $arrButtons = array();
        $arrButtons['save'] = '<input type="submit" name="save" id="save" class="tl_submit" accesskey="s" value="' . specialchars($GLOBALS['TL_LANG']['MSC']['save']) . '">';
        $arrButtons['saveNclose'] = '<input type="submit" name="saveNclose" id="saveNclose" class="tl_submit" accesskey="c" value="' . specialchars($GLOBALS['TL_LANG']['MSC']['saveNclose']) . '">';
        // Call the buttons_callback (see #4691)
        if (is_array($GLOBALS['TL_DCA'][$this->strTable]['edit']['buttons_callback'])) {
            foreach ($GLOBALS['TL_DCA'][$this->strTable]['edit']['buttons_callback'] as $callback) {
                if (is_array($callback)) {
                    $this->import($callback[0]);
                    $arrButtons = $this->{$callback[0]}->{$callback[1]}($arrButtons, $this);
                } elseif (is_callable($callback)) {
                    $arrButtons = $callback($arrButtons, $this);
                }
            }
        }
        // Add the form
        return $version . '
<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() . '
<form action="' . ampersand(\Environment::get('request'), true) . '" id="tl_files" class="tl_form" method="post">
<div class="tl_formbody_edit">
<input type="hidden" name="FORM_SUBMIT" value="tl_files">
<input type="hidden" name="REQUEST_TOKEN" value="' . REQUEST_TOKEN . '">
<div class="tl_tbox">
  <h3><label for="ctrl_source">' . $GLOBALS['TL_LANG']['tl_files']['editor'][0] . '</label></h3>
  <textarea name="source" id="ctrl_source" class="tl_textarea monospace" rows="12" cols="80" style="height:400px" onfocus="Backend.getScrollOffset()">' . "\n" . htmlspecialchars($strContent) . '</textarea>' . (\Config::get('showHelp') && strlen($GLOBALS['TL_LANG']['tl_files']['editor'][1]) ? '
  <p class="tl_help tl_tip">' . $GLOBALS['TL_LANG']['tl_files']['editor'][1] . '</p>' : '') . '
</div>
</div>

<div class="tl_formbody_submit">

<div class="tl_submit_container">
  ' . implode(' ', $arrButtons) . '
</div>

</div>
</form>' . "\n\n" . $codeEditor;
    }
Esempio n. 13
0
   /**
    * Generate the widget and return it as string
    * @return string
    */
   public function generate()
   {
       $this->import('BackendUser', 'User');
       // Store the keyword
       if (\Input::post('FORM_SUBMIT') == 'item_selector') {
           $this->Session->set('file_selector_search', \Input::post('keyword'));
           $this->reload();
       }
       // Extension filter
       if ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField]['eval']['extensions'] != '') {
           $this->strExtensions = " AND (type='folder' OR extension IN('" . implode("','", trimsplit(',', $GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField]['eval']['extensions'])) . "'))";
       }
       // Sort descending
       if (isset($GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField]['flag']) && $GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField]['flag'] % 2 == 0) {
           $this->strSortFlag = ' DESC';
       }
       $tree = '';
       $this->getPathNodes();
       $for = $this->Session->get('file_selector_search');
       $arrIds = array();
       // Search for a specific file
       if ($for != '') {
           // The keyword must not start with a wildcard (see #4910)
           if (strncmp($for, '*', 1) === 0) {
               $for = substr($for, 1);
           }
           $objRoot = $this->Database->prepare("SELECT id FROM tl_files WHERE CAST(name AS CHAR) REGEXP ?{$this->strExtensions} ORDER BY type='file', name{$this->strSortFlag}")->execute($for);
           if ($objRoot->numRows > 0) {
               // Respect existing limitations
               if ($this->User->isAdmin) {
                   $arrIds = $objRoot->fetchEach('id');
               } else {
                   $arrRoot = array();
                   while ($objRoot->next()) {
                       if (count(array_intersect($this->User->filemounts, $this->Database->getParentRecords($objRoot->id, 'tl_files'))) > 0) {
                           $arrRoot[] = $objRoot->id;
                       }
                   }
                   $arrIds = $arrRoot;
               }
           }
           // Build the tree
           foreach ($arrIds as $id) {
               $tree .= $this->renderFiletree($id, -20, false, true);
           }
       } else {
           // Show a custom path (see #4926)
           if ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField]['eval']['path'] != '') {
               $objFolder = \FilesModel::findByPath($GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField]['eval']['path']);
               if ($objFolder !== null) {
                   $tree .= $this->renderFiletree($objFolder->id, -20);
               }
           } elseif ($this->User->isAdmin) {
               $objFile = $this->Database->prepare("SELECT id FROM tl_files WHERE pid=?{$this->strExtensions} ORDER BY type='file', name{$this->strSortFlag}")->execute(0);
               while ($objFile->next()) {
                   $tree .= $this->renderFiletree($objFile->id, -20);
               }
           } else {
               foreach ($this->eliminateNestedPages($this->User->filemountIds, 'tl_files') as $node) {
                   $tree .= $this->renderFiletree($node, -20);
               }
           }
       }
       // Select all checkboxes
       if ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField]['eval']['fieldType'] == 'checkbox') {
           $strReset = "\n" . '    <li class="tl_folder"><div class="tl_left">&nbsp;</div> <div class="tl_right"><label for="check_all_' . $this->strId . '" class="tl_change_selected">' . $GLOBALS['TL_LANG']['MSC']['selectAll'] . '</label> <input type="checkbox" id="check_all_' . $this->strId . '" class="tl_tree_checkbox" value="" onclick="Backend.toggleCheckboxGroup(this,\'' . $this->strName . '\')"></div><div style="clear:both"></div></li>';
       } else {
           $strReset = "\n" . '    <li class="tl_folder"><div class="tl_left">&nbsp;</div> <div class="tl_right"><label for="reset_' . $this->strId . '" class="tl_change_selected">' . $GLOBALS['TL_LANG']['MSC']['resetSelected'] . '</label> <input type="radio" name="' . $this->strName . '" id="reset_' . $this->strName . '" class="tl_tree_radio" value="" onfocus="Backend.getScrollOffset()"></div><div style="clear:both"></div></li>';
       }
       // Return the tree
       return '<ul class="tl_listing tree_view' . ($this->strClass != '' ? ' ' . $this->strClass : '') . '" id="' . $this->strId . '">
   <li class="tl_folder_top"><div class="tl_left">' . $this->generateImage($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['icon'] != '' ? $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['icon'] : 'filemounts.gif') . ' ' . ($GLOBALS['TL_CONFIG']['websiteTitle'] ?: 'Contao Open Source CMS') . '</div> <div class="tl_right">&nbsp;</div><div style="clear:both"></div></li><li class="parent" id="' . $this->strId . '_parent"><ul>' . $tree . $strReset . '
 </ul></li></ul>';
   }
Esempio n. 14
0
 /**
  * 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]);
 }
Esempio n. 15
0
 /**
  *
  */
 protected function compile()
 {
     global $objPage;
     // needed for options
     \Input::setGet('id', $this->f_select_wrapper);
     $GLOBALS['TL_LANGUAGE'] = $objPage->language;
     // get fields
     $this->strTableName = $this->f_select_module;
     $this->strTableData = $this->strTableName . '_data';
     $this->strPid = $this->f_select_wrapper;
     $moduleDCA = DCACreator::getInstance();
     $arrModule = $moduleDCA->getModuleByTableName($this->strTableName);
     $dcaData = DCAModuleData::getInstance();
     $this->dcaFields = $dcaData->setFields($arrModule, $this->strPid);
     // set tpl
     if ($this->fm_sign_template != '') {
         /** @var \FrontendTemplate|object $objTemplate */
         $objTemplate = new \FrontendTemplate($this->fm_sign_template);
         $this->Template = $objTemplate;
         $this->Template->setData($this->arrData);
     }
     //
     $this->Template->tableless = $this->tableless;
     $this->Template->fields = '';
     $this->Template->tableless = $this->tableless;
     $objCaptcha = null;
     $doNotSubmit = false;
     //
     $arrGroups = array('teaser' => array(), 'date' => array(), 'image' => array(), 'enclosure' => array(), 'map' => array(), 'expert' => array());
     // load language
     \System::loadLanguageFile('tl_fmodules_language_pack');
     // Captcha
     if (!$this->disableCaptcha) {
         $arrCaptcha = array('id' => 'registration', 'label' => $GLOBALS['TL_LANG']['MSC']['securityQuestion'], 'type' => 'captcha', 'mandatory' => true, 'required' => true, 'tableless' => $this->tableless);
         /** @var \FormCaptcha $strClass */
         $strClass = $GLOBALS['TL_FFL']['captcha'];
         // Fallback to default if the class is not defined
         if (!class_exists($strClass)) {
             $strClass = 'FormCaptcha';
         }
         /** @var \FormCaptcha $objCaptcha */
         $objCaptcha = new $strClass($arrCaptcha);
         if (\Input::post('FORM_SUBMIT') == 'fm_registration') {
             $objCaptcha->validate();
             if ($objCaptcha->hasErrors()) {
                 $doNotSubmit = true;
             }
         }
     }
     $arrValidData = array();
     $arrFields = array();
     $hasUpload = false;
     $i = 0;
     foreach ($this->fm_editable_fields as $field) {
         $arrData = $this->dcaFields[$field];
         $arrData = $this->convertWidgetToField($arrData);
         if (isset($arrData['eval']['fmEditable']) && $arrData['eval']['fmEditable'] === false || !isset($arrData['eval']['fmEditable'])) {
             continue;
         }
         $strClass = $this->fieldClassExist($arrData['inputType']);
         if ($strClass == false) {
             continue;
         }
         $objWidget = new $strClass($strClass::getAttributesFromDca($arrData, $field, $arrData['default'], '', '', $this));
         $objWidget->storeValues = true;
         $objWidget->rowClass = 'row_' . $i . ($i == 0 ? ' row_first' : '') . ($i % 2 == 0 ? ' even' : ' odd');
         if ($arrData['inputType'] == 'upload') {
             $objWidget->storeFile = $this->fm_storeFile;
             $objWidget->uploadFolder = $this->fm_uploadFolder;
             $objWidget->useHomeDir = $this->fm_useHomeDir;
             $objWidget->doNotOverwrite = $this->fm_doNotOverwrite;
             $objWidget->extensions = $this->fm_extensions;
             $objWidget->maxlength = $this->fm_maxlength;
         }
         // Increase the row count if its a password field
         if ($objWidget instanceof \FormPassword) {
             $objWidget->rowClassConfirm = 'row_' . ++$i . ($i % 2 == 0 ? ' even' : ' odd');
         }
         // Validate input
         if (\Input::post('FORM_SUBMIT') == 'fm_registration') {
             $objWidget->validate();
             $varValue = $objWidget->value;
             $varValue = $this->decodeValue($varValue);
             $varValue = $this->replaceInsertTags($varValue);
             $rgxp = $arrData['eval']['rgxp'];
             // Convert date formats into timestamps (check the eval setting first -> #3063)
             if ($varValue != '' && in_array($rgxp, array('date', 'time', 'datim'))) {
                 try {
                     $objDate = new \Date($varValue, \Date::getFormatFromRgxp($rgxp));
                     $varValue = $objDate->tstamp;
                 } catch (\OutOfBoundsException $e) {
                     $objWidget->addError(sprintf($GLOBALS['TL_LANG']['ERR']['invalidDate'], $varValue));
                 }
             }
             // Make sure that unique fields are unique (check the eval setting first -> #3063)
             if ($arrData['eval']['unique'] && $varValue != '' && !$this->Database->isUniqueValue($this->strTableData, $field, $varValue)) {
                 $objWidget->addError(sprintf($GLOBALS['TL_LANG']['ERR']['unique'], $arrData['label'][0] ?: $field));
             }
             // Save callback
             if ($objWidget->submitInput() && !$objWidget->hasErrors() && is_array($arrData['save_callback'])) {
                 foreach ($arrData['save_callback'] as $callback) {
                     try {
                         if (is_array($callback)) {
                             $this->import($callback[0]);
                             $varValue = $this->{$callback[0]}->{$callback[1]}($varValue, null);
                         } elseif (is_callable($callback)) {
                             $varValue = $callback($varValue, null);
                         }
                     } catch (\Exception $e) {
                         $objWidget->class = 'error';
                         $objWidget->addError($e->getMessage());
                     }
                 }
             }
             // Store the current value
             if ($objWidget->hasErrors()) {
                 $doNotSubmit = true;
             } elseif ($objWidget->submitInput()) {
                 // Set the correct empty value (see #6284, #6373)
                 if ($varValue === '') {
                     $varValue = $objWidget->getEmptyValue();
                 }
                 // Encrypt the value (see #7815)
                 if ($arrData['eval']['encrypt']) {
                     $varValue = \Encryption::encrypt($varValue);
                 }
                 // Set the new value
                 $arrValidData[$field] = $varValue;
             }
             // store file
             $Files = $_SESSION['FILES'];
             if ($Files && isset($Files[$field]) && $this->fm_storeFile) {
                 $strRoot = TL_ROOT . '/';
                 $strUuid = $Files[$field]['uuid'];
                 $strFile = substr($Files[$field]['tmp_name'], strlen($strRoot));
                 $arrFiles = \FilesModel::findByPath($strFile);
                 if ($arrFiles !== null) {
                     $strUuid = $arrFiles->uuid;
                 }
                 $arrValidData[$field] = $strUuid;
             }
             // reset session
             if ($Files && isset($Files[$field])) {
                 unset($_SESSION['FILES'][$field]);
             }
         }
         if ($objWidget instanceof \uploadable) {
             $hasUpload = true;
         }
         $temp = $objWidget->parse();
         // $objWidget->generate();
         $this->Template->fields .= $temp;
         $arrFields[$arrData['eval']['fmGroup']][$field] .= $temp;
         ++$i;
     }
     // Captcha
     if (!$this->disableCaptcha) {
         $objCaptcha->rowClass = 'row_' . $i . ($i == 0 ? ' row_first' : '') . ($i % 2 == 0 ? ' even' : ' odd');
         $strCaptcha = $objCaptcha->parse();
         $this->Template->fields .= $strCaptcha;
         $arrFields['captcha']['captcha'] .= $strCaptcha;
     }
     $this->Template->rowLast = 'row_' . ++$i . ($i % 2 == 0 ? ' even' : ' odd');
     $this->Template->enctype = $hasUpload ? 'multipart/form-data' : 'application/x-www-form-urlencoded';
     $this->Template->hasError = $doNotSubmit;
     // Create new entity if there are no errors
     if (\Input::post('FORM_SUBMIT') == 'fm_registration' && !$doNotSubmit) {
         $this->createNewEntity($arrValidData);
     }
     $this->Template->teaserDetails = $GLOBALS['TL_LANG']['tl_fmodules_language_pack']['teaserData'];
     $this->Template->dateDetails = $GLOBALS['TL_LANG']['tl_fmodules_language_pack']['dateDetails'];
     $this->Template->imageDetails = $GLOBALS['TL_LANG']['tl_fmodules_language_pack']['imageDetails'];
     $this->Template->enclosureDetails = $GLOBALS['TL_LANG']['tl_fmodules_language_pack']['enclosureDetails'];
     $this->Template->expertDetails = $GLOBALS['TL_LANG']['tl_fmodules_language_pack']['expertDetails'];
     $this->Template->mapDetails = $GLOBALS['TL_LANG']['tl_fmodules_language_pack']['mapDetails'];
     $this->Template->authorDetails = $GLOBALS['TL_LANG']['tl_fmodules_language_pack']['authorDetails'];
     $this->Template->sourceDetails = $GLOBALS['TL_LANG']['tl_fmodules_language_pack']['sourceDetails'];
     $this->Template->otherDetails = $GLOBALS['TL_LANG']['tl_fmodules_language_pack']['otherDetails'];
     $this->Template->captchaDetails = $GLOBALS['TL_LANG']['MSC']['securityQuestion'];
     // Add the groups
     foreach ($arrFields as $k => $v) {
         $this->Template->{$k} = $v;
         // backwards compatibility
         $key = $k . ($k == 'teaser' ? 'Data' : 'Details');
         $arrGroups[$GLOBALS['TL_LANG']['tl_fmodules_language_pack'][$key]] = $v;
     }
     $this->Template->categories = $arrGroups;
     $this->Template->formId = 'fm_registration';
     $this->Template->slabel = specialchars($GLOBALS['TL_LANG']['MSC']['register']);
     $this->Template->action = \Environment::get('indexFreeRequest');
     $this->Template->captcha = $arrFields['captcha']['captcha'];
     // backwards compatibility
 }
Esempio n. 16
0
 /**
  * insert a new entry in tl_gallery_creator_pictures
  *
  * @param integer
  * @param string
  * $intAlbumId - albumId
  * $strFilepath - filepath -> files/gallery_creator_albums/albumalias/filename.jpg
  * @return bool
  */
 public static function createNewImage($intAlbumId, $strFilepath)
 {
     //get the file-object
     $objFile = new \File($strFilepath);
     if (!$objFile->isGdImage) {
         return false;
     }
     //get the album-object
     $objAlbum = \MCupic\GalleryCreatorAlbumsModel::findById($intAlbumId);
     // get the assigned album directory
     $objFolder = \FilesModel::findByUuid($objAlbum->assignedDir);
     $assignedDir = null;
     if ($objFolder !== null) {
         if (is_dir(TL_ROOT . '/' . $objFolder->path)) {
             $assignedDir = $objFolder->path;
         }
     }
     if ($assignedDir == null) {
         die('Aborted Script, because there is no upload directory assigned to the Album with ID ' . $intAlbumId);
     }
     //check if the file ist stored in the album-directory or if it is stored in an external directory
     $blnExternalFile = false;
     if (\Input::get('importFromFilesystem')) {
         $blnExternalFile = strstr($objFile->dirname, $assignedDir) ? false : true;
     }
     //get the album object and the alias
     $strAlbumAlias = $objAlbum->alias;
     //db insert
     $objImg = new \GalleryCreatorPicturesModel();
     $objImg->tstamp = time();
     $objImg->pid = $objAlbum->id;
     $objImg->externalFile = $blnExternalFile ? "1" : "";
     $objImg->save();
     if ($objImg->id) {
         $insertId = $objImg->id;
         // Get the next sorting index
         $objImg_2 = \Database::getInstance()->prepare('SELECT MAX(sorting)+10 AS maximum FROM tl_gallery_creator_pictures WHERE pid=?')->execute($objAlbum->id);
         $sorting = $objImg_2->maximum;
         // If filename should be generated
         if (!$objAlbum->preserve_filename && $blnExternalFile === false) {
             $newFilepath = sprintf('%s/alb%s_img%s.%s', $assignedDir, $objAlbum->id, $insertId, $objFile->extension);
             $objFile->renameTo($newFilepath);
         }
         // GalleryCreatorImagePostInsert - HOOK
         // übergibt die id des neu erstellten db-Eintrages ($lastInsertId)
         if (isset($GLOBALS['TL_HOOKS']['galleryCreatorImagePostInsert']) && is_array($GLOBALS['TL_HOOKS']['galleryCreatorImagePostInsert'])) {
             foreach ($GLOBALS['TL_HOOKS']['galleryCreatorImagePostInsert'] as $callback) {
                 $objClass = self::importStatic($callback[0]);
                 $objClass->{$callback}[1]($insertId);
             }
         }
         if (is_file(TL_ROOT . '/' . $objFile->path)) {
             //get the userId
             $userId = '0';
             if (TL_MODE == 'BE') {
                 $userId = \BackendUser::getInstance()->id;
             }
             // the album-owner is automaticaly the image owner, if the image was uploaded by a by a frontend user
             if (TL_MODE == 'FE') {
                 $userId = $objAlbum->owner;
             }
             // Get the FilesModel
             $objFileModel = \FilesModel::findByPath($objFile->path);
             //finally save the new image in tl_gallery_creator_pictures
             $objPicture = \GalleryCreatorPicturesModel::findByPk($insertId);
             $objPicture->uuid = $objFileModel->uuid;
             $objPicture->owner = $userId;
             $objPicture->date = $objAlbum->date;
             $objPicture->sorting = $sorting;
             $objPicture->save();
             \System::log('A new version of tl_gallery_creator_pictures ID ' . $insertId . ' has been created', __METHOD__, TL_GENERAL);
             //check for a valid preview-thumb for the album
             $objAlbum = \MCupic\GalleryCreatorAlbumsModel::findByAlias($strAlbumAlias);
             if ($objAlbum !== null) {
                 if ($objAlbum->thumb == "") {
                     $objAlbum->thumb = $insertId;
                     $objAlbum->save();
                 }
             }
             return true;
         } else {
             if ($blnExternalFile === true) {
                 $_SESSION['TL_ERROR'][] = sprintf($GLOBALS['TL_LANG']['ERR']['link_to_not_existing_file'], $strFilepath);
             } else {
                 $_SESSION['TL_ERROR'][] = sprintf($GLOBALS['TL_LANG']['ERR']['uploadError'], $strFilepath);
             }
             \System::log('Unable to create the new image in: ' . $strFilepath . '!', __METHOD__, TL_ERROR);
         }
     }
     return false;
 }
 /**
  * @param  bool   $import        True for import, false for export
  * @param  array  $data          Data of element or parent list item
  * @param  array  $config        Fields configuration
  * @param  array  $idMappingData ID mapping for imported database rows
  * @param  string $fieldPrefix
  * @return array                 Converted $data
  */
 protected function convertDataForImportExportParseFields($import, $data, $config, $idMappingData, $fieldPrefix = 'rsce_field_')
 {
     foreach ($data as $fieldName => $value) {
         $fieldConfig = $this->getNestedConfig($fieldPrefix . $fieldName, $config);
         if (empty($fieldConfig['inputType'])) {
             continue;
         }
         if ($fieldConfig['inputType'] === 'list') {
             for ($dataKey = 0; isset($value[$dataKey]); $dataKey++) {
                 $data[$fieldName][$dataKey] = $this->convertDataForImportExportParseFields($import, $value[$dataKey], $config, $idMappingData, $fieldPrefix . $fieldName . '__' . $dataKey . '__');
             }
         } else {
             if ($value && ($fieldConfig['inputType'] === 'fileTree' || $fieldConfig['inputType'] === 'fineUploader')) {
                 if (empty($fieldConfig['eval']['multiple'])) {
                     if ($import) {
                         $file = \FilesModel::findByPath(\Config::get('uploadPath') . '/' . preg_replace('(^files/)', '', $value));
                         if ($file) {
                             $data[$fieldName] = \String::binToUuid($file->uuid);
                         }
                     } else {
                         $file = \FilesModel::findById($value);
                         if ($file) {
                             $data[$fieldName] = 'files/' . preg_replace('(^' . preg_quote(\Config::get('uploadPath')) . '/)', '', $file->path);
                         }
                     }
                 } else {
                     $data[$fieldName] = serialize(array_map(function ($value) use($import) {
                         if ($import) {
                             $file = \FilesModel::findByPath(\Config::get('uploadPath') . '/' . preg_replace('(^files/)', '', $value));
                             if ($file) {
                                 return \String::binToUuid($file->uuid);
                             }
                         } else {
                             $file = \FilesModel::findById($value);
                             if ($file) {
                                 return 'files/' . preg_replace('(^' . preg_quote(\Config::get('uploadPath')) . '/)', '', $file->path);
                             }
                         }
                         return $value;
                     }, deserialize($value, true)));
                 }
             } else {
                 if ($fieldConfig['inputType'] === 'imageSize' && $value && $import) {
                     $value = deserialize($value, true);
                     if (!empty($value[2]) && is_numeric($value[2]) && !empty($idMappingData['tl_image_size'][$value[2]])) {
                         $value[2] = $idMappingData['tl_image_size'][$value[2]];
                         $data[$fieldName] = serialize($value);
                     }
                 }
             }
         }
     }
     return $data;
 }
Esempio n. 18
0
 /**
  * Move temp files. If DBAFS support is enabled add entries to the dbafs.
  *
  * @CtoCommunication Enable
  *
  * @param  array   $arrFileList List with files for moving.
  *
  * @param  boolean $blnIsDbafs  Flag if we have to change the dbafs system.
  *
  * @return array The list with some more information about the moving of the file.
  */
 public function moveTempFile($arrFileList, $blnIsDbafs)
 {
     foreach ($arrFileList as $key => $value) {
         try {
             $blnMovedFile = false;
             $strTempFile = $this->objSyncCtoHelper->standardizePath($GLOBALS['SYC_PATH']['tmp'], "sync", $value["path"]);
             // Check if the tmp file exists.
             if (!file_exists(TL_ROOT . DIRECTORY_SEPARATOR . $strTempFile)) {
                 $arrFileList[$key]['saved'] = false;
                 $arrFileList[$key]['error'] = sprintf($GLOBALS['TL_LANG']['ERR']['unknown_file'], $strTempFile);
                 $arrFileList[$key]['skipreasons'] = $GLOBALS['TL_LANG']['ERR']['missing_file_information'];
                 continue;
             }
             // Generate the folder if not already there.
             $strFolderPath = dirname($value["path"]);
             if ($strFolderPath != ".") {
                 $objFolder = new Folder($strFolderPath);
                 unset($objFolder);
             }
             // Build folders.
             $strFileSource = $this->objSyncCtoHelper->standardizePath($GLOBALS['SYC_PATH']['tmp'], "sync", $value["path"]);
             $strFileDestination = $this->objSyncCtoHelper->standardizePath($value["path"]);
             // DBAFS support. Check if we have the file already in the locale dbafs system.
             if ($blnIsDbafs) {
                 // Get the information from the dbafs.
                 /**  @var \Model $objLocaleData */
                 $objLocaleData = \FilesModel::findByPath($strFileDestination);
                 // If we have no entry in the dbafs just overwrite the current file and add the entry to the dbafs.
                 if ($objLocaleData == null) {
                     // Move file.
                     $blnMovedFile = $this->objFiles->copy($strFileSource, $strFileDestination);
                     // If success add file to the database.
                     if ($blnMovedFile) {
                         // First add it to the dbafs.
                         $objLocaleData = \Dbafs::addResource($strFileDestination);
                         // PHP 7 compatibility
                         // See #309 (https://github.com/contao/core-bundle/issues/309)
                         if (version_compare(VERSION . '.' . BUILD, '3.5.5', '>=')) {
                             $objLocaleData->uuid = \StringUtil::uuidToBin($value['tl_files']['uuid']);
                         } else {
                             $objLocaleData->uuid = \String::uuidToBin($value['tl_files']['uuid']);
                         }
                         $objLocaleData->meta = $value['tl_files']['meta'];
                         $objLocaleData->save();
                         // Add a status report for debugging and co.
                         $arrFileList[$key]['dbafs']['msg'] = 'Moved file and add to database.';
                         $arrFileList[$key]['dbafs']['state'] = SyncCtoEnum::DBAFS_CREATE;
                     }
                 } else {
                     // PHP 7 compatibility
                     // See #309 (https://github.com/contao/core-bundle/issues/309)
                     if (version_compare(VERSION . '.' . BUILD, '3.5.5', '>=')) {
                         // Get the readable UUID for the work.
                         $strLocaleUUID = \StringUtil::binToUuid($objLocaleData->uuid);
                     } else {
                         // Get the readable UUID for the work.
                         $strLocaleUUID = \String::binToUuid($objLocaleData->uuid);
                     }
                     // Okay it seems we have already a file with this values.
                     if ($strLocaleUUID == $value['tl_files']['uuid']) {
                         // Move file.
                         $blnMovedFile = $this->objFiles->copy($strFileSource, $strFileDestination);
                         // If success add file to the database.
                         if ($blnMovedFile) {
                             $objLocaleData->hash = $value['checksum'];
                             $objLocaleData->meta = $value['tl_files']['meta'];
                             $objLocaleData->save();
                             // Add a status report for debugging and co.
                             $arrFileList[$key]['dbafs']['msg'] = 'UUID same no problem found. Update database with new hash.';
                             $arrFileList[$key]['dbafs']['state'] = SyncCtoEnum::DBAFS_SAME;
                         }
                     } elseif ($strLocaleUUID != $value['tl_files']['uuid']) {
                         // Get information about the current file information.
                         $arrDestinationInformation = pathinfo($strFileDestination);
                         // Try to rename it to _1 or _2 and so on.
                         $strNewDestinationName = null;
                         $intFileNumber = 1;
                         for ($i = 1; $i < 100; $i++) {
                             $strNewDestinationName = sprintf('%s' . DIRECTORY_SEPARATOR . '%s_%s.%s', $arrDestinationInformation['dirname'], $arrDestinationInformation['filename'], $i, $arrDestinationInformation['extension']);
                             if (!file_exists(TL_ROOT . DIRECTORY_SEPARATOR . $strNewDestinationName)) {
                                 $intFileNumber = $i;
                                 break;
                             }
                         }
                         // Move the current file to another name, that we have space for the new one.
                         $this->objFiles->copy($strFileDestination, $strNewDestinationName);
                         $objRenamedLocaleData = \Dbafs::moveResource($strFileDestination, $strNewDestinationName);
                         // Move the tmp file.
                         $blnMovedFile = $this->objFiles->copy($strFileSource, $strFileDestination);
                         // If success add file to the database.
                         if ($blnMovedFile) {
                             // First add it to the dbafs.
                             $objLocaleData = \Dbafs::addResource($strFileDestination);
                             // PHP 7 compatibility
                             // See #309 (https://github.com/contao/core-bundle/issues/309)
                             if (version_compare(VERSION . '.' . BUILD, '3.5.5', '>=')) {
                                 $objLocaleData->uuid = \StringUtil::uuidToBin($value['tl_files']['uuid']);
                             } else {
                                 $objLocaleData->uuid = \String::uuidToBin($value['tl_files']['uuid']);
                             }
                             $objLocaleData->meta = $value['tl_files']['meta'];
                             $objLocaleData->save();
                             // Add a status report for debugging and co.
                             $arrFileList[$key]['dbafs']['msg'] = $GLOBALS['TL_LANG']['ERR']['dbafs_uuid_conflict'];
                             $arrFileList[$key]['dbafs']['error'] = sprintf($GLOBALS['TL_LANG']['ERR']['dbafs_uuid_conflict_rename'], $intFileNumber);
                             $arrFileList[$key]['dbafs']['rename'] = $strNewDestinationName;
                             $arrFileList[$key]['dbafs']['state'] = SyncCtoEnum::DBAFS_CONFLICT;
                         }
                     }
                 }
             } else {
                 $blnMovedFile = $this->objFiles->copy($strFileSource, $strFileDestination);
             }
             // Check the state at moving and add a msg to the return array.
             if ($blnMovedFile) {
                 $arrFileList[$key]['saved'] = true;
                 $arrFileList[$key]['transmission'] = SyncCtoEnum::FILETRANS_MOVED;
             } else {
                 $arrFileList[$key]['saved'] = false;
                 $arrFileList[$key]['error'] = sprintf($GLOBALS['TL_LANG']['ERR']['cant_move_file'], $strFileSource, $strFileDestination);
                 $arrFileList[$key]['transmission'] = SyncCtoEnum::FILETRANS_SKIPPED;
                 $arrFileList[$key]['skipreason'] = $GLOBALS['TL_LANG']['ERR']['cant_move_files'];
             }
         } catch (Exception $e) {
             $arrFileList[$key]['saved'] = false;
             $arrFileList[$key]['error'] = sprintf('Can not move file - %s. Exception message: %s', $value["path"], $e->getMessage());
             $arrFileList[$key]['transmission'] = SyncCtoEnum::FILETRANS_SKIPPED;
             $arrFileList[$key]['skipreason'] = $GLOBALS['TL_LANG']['ERR']['cant_move_files'];
         }
     }
     return $arrFileList;
 }
Esempio n. 19
0
 /**
  * Create a picture instance from the given image path and size
  *
  * @param string|File   $file The image path or File instance
  * @param array|integer $size  The image size as array (width, height, resize mode) or an tl_image_size ID
  *
  * @return static The created picture instance
  */
 public static function create($file, $size = null)
 {
     if (is_string($file)) {
         $file = new \File(rawurldecode($file));
     }
     $imageSize = null;
     $picture = new static($file);
     // tl_image_size ID as resize mode
     if (is_array($size) && !empty($size[2]) && is_numeric($size[2])) {
         $size = (int) $size[2];
     }
     $imageSize = null;
     if (!is_array($size)) {
         $imageSize = \ImageSizeModel::findByPk($size);
         if ($imageSize === null) {
             $size = array();
         }
     }
     if (is_array($size)) {
         $size = $size + array(0, 0, 'crop');
         $imageSize = new \stdClass();
         $imageSize->width = $size[0];
         $imageSize->height = $size[1];
         $imageSize->resizeMode = $size[2];
         $imageSize->zoom = 0;
     }
     $picture->setImageSize($imageSize);
     if ($imageSize !== null && !empty($imageSize->id)) {
         $picture->setImageSizeItems(\ImageSizeItemModel::findVisibleByPid($imageSize->id, array('order' => 'sorting ASC')));
     }
     $fileRecord = \FilesModel::findByPath($file->path);
     if ($fileRecord !== null && $fileRecord->importantPartWidth && $fileRecord->importantPartHeight) {
         $picture->setImportantPart(array('x' => (int) $fileRecord->importantPartX, 'y' => (int) $fileRecord->importantPartY, 'width' => (int) $fileRecord->importantPartWidth, 'height' => (int) $fileRecord->importantPartHeight));
     }
     return $picture;
 }
Esempio n. 20
0
 /**
  * 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]);
 }
 protected function createNewUser($arrData)
 {
     $arrData['tstamp'] = time();
     $arrData['login'] = $this->reg_allowLogin;
     $arrData['activation'] = md5(uniqid(mt_rand(), true));
     $arrData['dateAdded'] = $arrData['tstamp'];
     $pw = $this->getRandomPassword(6);
     $arrData['password'] = \Encryption::hash($pw["clear"]);
     $arrData['username'] = strtolower($arrData['email']);
     $arrData['email'] = strtolower($arrData['email']);
     // Set default groups
     if (!array_key_exists('groups', $arrData)) {
         $arrData['groups'] = $this->reg_groups;
     }
     //        // Disable account
     //        $arrData['disable'] = 1;
     // Send activation e-mail
     if ($this->reg_activate) {
         $arrChunks = array();
         $strConfirmation = $this->reg_text;
         preg_match_all('/##[^#]+##/', $strConfirmation, $arrChunks);
         foreach ($arrChunks[0] as $strChunk) {
             $strKey = substr($strChunk, 2, -2);
             switch ($strKey) {
                 case 'domain':
                     $strConfirmation = str_replace($strChunk, \Idna::decode(\Environment::get('host')), $strConfirmation);
                     break;
                 case 'gen_pw':
                     $strConfirmation = str_replace($strChunk, $pw["clear"], $strConfirmation);
                     break;
                 case 'link':
                     $strConfirmation = str_replace($strChunk, \Idna::decode(\Environment::get('base')) . \Environment::get('request') . (\Config::get('disableAlias') || strpos(\Environment::get('request'), '?') !== false ? '&' : '?') . 'token=' . $arrData['activation'], $strConfirmation);
                     break;
                     // HOOK: support newsletter subscriptions
                 // HOOK: support newsletter subscriptions
                 case 'channel':
                 case 'channels':
                     if (!in_array('newsletter', \ModuleLoader::getActive())) {
                         break;
                     }
                     // Make sure newsletter is an array
                     if (!is_array($arrData['newsletter'])) {
                         if ($arrData['newsletter'] != '') {
                             $arrData['newsletter'] = array($arrData['newsletter']);
                         } else {
                             $arrData['newsletter'] = array();
                         }
                     }
                     // Replace the wildcard
                     if (!empty($arrData['newsletter'])) {
                         $objChannels = \NewsletterChannelModel::findByIds($arrData['newsletter']);
                         if ($objChannels !== null) {
                             $strConfirmation = str_replace($strChunk, implode("\n", $objChannels->fetchEach('title')), $strConfirmation);
                         }
                     } else {
                         $strConfirmation = str_replace($strChunk, '', $strConfirmation);
                     }
                     break;
                 default:
                     $strConfirmation = str_replace($strChunk, $arrData[$strKey], $strConfirmation);
                     break;
             }
         }
         $objEmail = new \Email();
         $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
         $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
         $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['emailSubject'], \Idna::decode(\Environment::get('host')));
         $objEmail->text = $strConfirmation;
         $objEmail->sendTo($arrData['email']);
     }
     // Make sure newsletter is an array
     if (isset($arrData['newsletter']) && !is_array($arrData['newsletter'])) {
         $arrData['newsletter'] = array($arrData['newsletter']);
     }
     // Create the user
     $objNewUser = new \MemberModel();
     $objNewUser->setRow($arrData);
     $objNewUser->save();
     $insertId = $objNewUser->id;
     // Assign home directory
     if ($this->reg_assignDir) {
         $objHomeDir = \FilesModel::findByUuid($this->reg_homeDir);
         if ($objHomeDir !== null) {
             $this->import('Files');
             $strUserDir = standardize($arrData['username']) ?: 'user_' . $insertId;
             // Add the user ID if the directory exists
             while (is_dir(TL_ROOT . '/' . $objHomeDir->path . '/' . $strUserDir)) {
                 $strUserDir .= '_' . $insertId;
             }
             // Create the user folder
             new \Folder($objHomeDir->path . '/' . $strUserDir);
             $objUserDir = \FilesModel::findByPath($objHomeDir->path . '/' . $strUserDir);
             // Save the folder ID
             $objNewUser->assignDir = 1;
             $objNewUser->homeDir = $objUserDir->uuid;
             $objNewUser->save();
         }
     }
     // HOOK: send insert ID and user data
     if (isset($GLOBALS['TL_HOOKS']['createNewUser']) && is_array($GLOBALS['TL_HOOKS']['createNewUser'])) {
         foreach ($GLOBALS['TL_HOOKS']['createNewUser'] as $callback) {
             $this->import($callback[0]);
             $this->{$callback}[0]->{$callback}[1]($insertId, $arrData, $this);
         }
     }
     // Inform admin if no activation link is sent
     if (!$this->reg_activate) {
         $this->sendAdminNotification($insertId, $arrData);
     }
     // Check whether there is a jumpTo page
     if (($objJumpTo = $this->objModel->getRelated('jumpTo')) !== null) {
         $this->jumpToOrReload($objJumpTo->row());
     }
     $this->reload();
 }
Esempio n. 22
0
 /**
  * Convert file paths inside "src" attributes to insert tags
  *
  * @param string $data The markup string
  *
  * @return string The markup with file paths converted to insert tags
  */
 public static function srcToInsertTag($data)
 {
     $return = '';
     $paths = preg_split('/((src|href)="([^"]+)")/i', $data, -1, PREG_SPLIT_DELIM_CAPTURE);
     for ($i = 0, $c = count($paths); $i < $c; $i = $i + 4) {
         $return .= $paths[$i];
         if (!isset($paths[$i + 1])) {
             continue;
         }
         $file = \FilesModel::findByPath($paths[$i + 3]);
         if ($file !== null) {
             $return .= $paths[$i + 2] . '="{{file::' . static::binToUuid($file->uuid) . '}}"';
         } else {
             $return .= $paths[$i + 2] . '="' . $paths[$i + 3] . '"';
         }
     }
     return $return;
 }
Esempio n. 23
0
 /**
  * Convert a multi source field to UUIDs
  *
  * @param string $table The table name
  * @param string $field The field name
  */
 public static function convertMultiField($table, $field)
 {
     $objDatabase = \Database::getInstance();
     // Get the non-empty rows
     $objRow = $objDatabase->query("SELECT id, {$field} FROM {$table} WHERE {$field}!=''");
     // Check the column type
     $objDesc = $objDatabase->query("DESC {$table} {$field}");
     // Change the column type
     if ($objDesc->Type != 'blob') {
         $objDatabase->query("ALTER TABLE `{$table}` CHANGE `{$field}` `{$field}` blob NULL");
         $objDatabase->query("UPDATE `{$table}` SET `{$field}`=NULL WHERE `{$field}`=''");
     }
     while ($objRow->next()) {
         $arrValues = deserialize($objRow->{$field}, true);
         if (empty($arrValues)) {
             continue;
         }
         $objHelper = static::generateHelperObject($arrValues);
         // UUID already
         if ($objHelper->isUuid) {
             continue;
         }
         foreach ($arrValues as $k => $v) {
             // Numeric ID to UUID
             if ($objHelper->isNumeric) {
                 $objFile = \FilesModel::findByPk($objHelper->value[$k]);
                 $arrValues[$k] = $objFile->uuid;
             } else {
                 $objFile = \FilesModel::findByPath($objHelper->value[$k]);
                 $arrValues[$k] = $objFile->uuid;
             }
         }
         $objDatabase->prepare("UPDATE {$table} SET {$field}=? WHERE id=?")->execute(serialize($arrValues), $objRow->id);
     }
 }
Esempio n. 24
0
 /**
  * Create a new user and redirect
  *
  * @param array $arrData
  */
 protected function createNewUser($arrData)
 {
     $arrData['tstamp'] = time();
     $arrData['login'] = $this->reg_allowLogin;
     $arrData['activation'] = md5(uniqid(mt_rand(), true));
     $arrData['dateAdded'] = $arrData['tstamp'];
     // Set default groups
     if (!array_key_exists('groups', $arrData)) {
         $arrData['groups'] = $this->reg_groups;
     }
     // Disable account
     $arrData['disable'] = 1;
     // Send activation e-mail
     if ($this->reg_activate) {
         // Prepare the simple token data
         $arrTokenData = $arrData;
         $arrTokenData['domain'] = \Idna::decode(\Environment::get('host'));
         $arrTokenData['link'] = \Idna::decode(\Environment::get('base')) . \Environment::get('request') . (\Config::get('disableAlias') || strpos(\Environment::get('request'), '?') !== false ? '&' : '?') . 'token=' . $arrData['activation'];
         $arrTokenData['channels'] = '';
         if (in_array('newsletter', \ModuleLoader::getActive())) {
             // Make sure newsletter is an array
             if (!is_array($arrData['newsletter'])) {
                 if ($arrData['newsletter'] != '') {
                     $arrData['newsletter'] = array($arrData['newsletter']);
                 } else {
                     $arrData['newsletter'] = array();
                 }
             }
             // Replace the wildcard
             if (!empty($arrData['newsletter'])) {
                 $objChannels = \NewsletterChannelModel::findByIds($arrData['newsletter']);
                 if ($objChannels !== null) {
                     $arrTokenData['channels'] = implode("\n", $objChannels->fetchEach('title'));
                 }
             }
         }
         // Backwards compatibility
         $arrTokenData['channel'] = $arrTokenData['channels'];
         $objEmail = new \Email();
         $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
         $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
         $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['emailSubject'], \Idna::decode(\Environment::get('host')));
         $objEmail->text = \String::parseSimpleTokens($this->reg_text, $arrTokenData);
         $objEmail->sendTo($arrData['email']);
     }
     // Make sure newsletter is an array
     if (isset($arrData['newsletter']) && !is_array($arrData['newsletter'])) {
         $arrData['newsletter'] = array($arrData['newsletter']);
     }
     // Create the user
     $objNewUser = new \MemberModel();
     $objNewUser->setRow($arrData);
     $objNewUser->save();
     // Assign home directory
     if ($this->reg_assignDir) {
         $objHomeDir = \FilesModel::findByUuid($this->reg_homeDir);
         if ($objHomeDir !== null) {
             $this->import('Files');
             $strUserDir = standardize($arrData['username']) ?: 'user_' . $objNewUser->id;
             // Add the user ID if the directory exists
             while (is_dir(TL_ROOT . '/' . $objHomeDir->path . '/' . $strUserDir)) {
                 $strUserDir .= '_' . $objNewUser->id;
             }
             // Create the user folder
             new \Folder($objHomeDir->path . '/' . $strUserDir);
             $objUserDir = \FilesModel::findByPath($objHomeDir->path . '/' . $strUserDir);
             // Save the folder ID
             $objNewUser->assignDir = 1;
             $objNewUser->homeDir = $objUserDir->uuid;
             $objNewUser->save();
         }
     }
     // HOOK: send insert ID and user data
     if (isset($GLOBALS['TL_HOOKS']['createNewUser']) && is_array($GLOBALS['TL_HOOKS']['createNewUser'])) {
         foreach ($GLOBALS['TL_HOOKS']['createNewUser'] as $callback) {
             $this->import($callback[0]);
             $this->{$callback}[0]->{$callback}[1]($objNewUser->id, $arrData, $this);
         }
     }
     // Create the initial version (see #7816)
     $objVersions = new \Versions('tl_member', $objNewUser->id);
     $objVersions->setUsername($objNewUser->username);
     $objVersions->setUserId(0);
     $objVersions->setEditUrl('contao/main.php?do=member&act=edit&id=%s&rt=1');
     $objVersions->initialize();
     // Inform admin if no activation link is sent
     if (!$this->reg_activate) {
         $this->sendAdminNotification($objNewUser->id, $arrData);
     }
     // Check whether there is a jumpTo page
     if (($objJumpTo = $this->objModel->getRelated('jumpTo')) !== null) {
         $this->jumpToOrReload($objJumpTo->row());
     }
     $this->reload();
 }
Esempio n. 25
0
 /**
  * Create an image instance from the given image path and size
  *
  * @param string|File   $image The image path or File instance
  * @param array|integer $size  The image size as array (width, height, resize mode) or an tl_image_size ID
  *
  * @return static The created image instance
  */
 public static function create($image, $size = null)
 {
     if (is_string($image)) {
         $image = new \File(rawurldecode($image));
     }
     /** @var \Image $imageObj */
     $imageObj = new static($image);
     // tl_image_size ID as resize mode
     if (is_array($size) && !empty($size[2]) && is_numeric($size[2])) {
         $size = (int) $size[2];
     }
     if (is_array($size)) {
         $size = $size + array(0, 0, 'crop');
         $imageObj->setTargetWidth($size[0])->setTargetHeight($size[1])->setResizeMode($size[2]);
     } elseif (($imageSize = \ImageSizeModel::findByPk($size)) !== null) {
         $imageObj->setTargetWidth($imageSize->width)->setTargetHeight($imageSize->height)->setResizeMode($imageSize->resizeMode)->setZoomLevel($imageSize->zoom);
     }
     $fileRecord = \FilesModel::findByPath($image->path);
     // Set the important part
     if ($fileRecord !== null && $fileRecord->importantPartWidth && $fileRecord->importantPartHeight) {
         $imageObj->setImportantPart(array('x' => (int) $fileRecord->importantPartX, 'y' => (int) $fileRecord->importantPartY, 'width' => (int) $fileRecord->importantPartWidth, 'height' => (int) $fileRecord->importantPartHeight));
     }
     return $imageObj;
 }
Esempio n. 26
0
 /**
  * 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();
 }
 /**
  * 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) . '&amp;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();
 }
Esempio n. 28
0
 /**
  * Update all FileTree fields
  */
 public function updateFileTreeFields()
 {
     $arrFields = array();
     // Find all fileTree fields
     foreach (scan(TL_ROOT . '/system/cache/dca') as $strFile) {
         if ($strFile != '.htaccess') {
             $strTable = str_replace('.php', '', $strFile);
             $this->loadDataContainer($strTable);
             $arrConfig =& $GLOBALS['TL_DCA'][$strTable]['config'];
             // Skip non-database DCAs
             if ($arrConfig['dataContainer'] == 'File') {
                 continue;
             }
             if ($arrConfig['dataContainer'] == 'Folder' && !$arrConfig['databaseAssisted']) {
                 continue;
             }
             foreach ($GLOBALS['TL_DCA'][$strTable]['fields'] as $strField => $arrField) {
                 // FIXME: support other field types
                 if ($arrField['inputType'] == 'fileTree') {
                     if ($this->Database->fieldExists($strField, $strTable)) {
                         $key = $arrField['eval']['multiple'] ? 'multiple' : 'single';
                         $arrFields[$key][] = $strTable . '.' . $strField;
                     }
                 }
             }
         }
     }
     // Update the existing singleSRC entries
     foreach ($arrFields['single'] as $val) {
         list($table, $field) = explode('.', $val);
         $objRow = $this->Database->query("SELECT id, {$field} FROM {$table} WHERE {$field}!=''");
         while ($objRow->next()) {
             if (!is_numeric($objRow->{$field})) {
                 $objFile = \FilesModel::findByPath($objRow->{$field});
                 $this->Database->prepare("UPDATE {$table} SET {$field}=? WHERE id=?")->execute($objFile->id, $objRow->id);
             }
         }
     }
     // Update the existing multiSRC entries
     foreach ($arrFields['multiple'] as $val) {
         list($table, $field) = explode('.', $val);
         $objRow = $this->Database->query("SELECT id, {$field} FROM {$table} WHERE {$field}!=''");
         while ($objRow->next()) {
             $arrPaths = deserialize($objRow->{$field}, true);
             if (empty($arrPaths)) {
                 continue;
             }
             foreach ($arrPaths as $k => $v) {
                 if (!is_numeric($v)) {
                     $objFile = \FilesModel::findByPath($v);
                     $arrPaths[$k] = $objFile->id;
                 }
             }
             $this->Database->prepare("UPDATE {$table} SET {$field}=? WHERE id=?")->execute(serialize($arrPaths), $objRow->id);
         }
     }
 }
Esempio n. 29
0
 /**
  * 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");
     }
 }
Esempio n. 30
0
 /**
  * Return the files model
  *
  * @return \FilesModel The files model
  */
 public function getModel()
 {
     if ($this->blnSyncDb && $this->objModel === null) {
         $this->objModel = \FilesModel::findByPath($this->strFolder);
     }
     return $this->objModel;
 }