/** * Compress images * * @param boolean $arrFiles File array */ public function processPostUpload($arrFiles) { if (is_array($arrFiles) && $GLOBALS['TL_CONFIG']['tinypng_api_key'] != '') { $strUrl = 'https://api.tinypng.com/shrink'; $strKey = $GLOBALS['TL_CONFIG']['tinypng_api_key']; $strAuthorization = 'Basic ' . base64_encode("api:{$strKey}"); foreach ($arrFiles as $file) { $objFile = FilesModel::findByPath($file); if (in_array($objFile->extension, array('png', 'jpg', 'jpeg'))) { $strFile = TL_ROOT . '/' . $file; $objRequest = new Request(); $objRequest->method = 'post'; $objRequest->data = file_get_contents($strFile); $objRequest->setHeader('Content-type', 'image/png'); $objRequest->setHeader('Authorization', $strAuthorization); $objRequest->send($strUrl); $arrResponse = json_decode($objRequest->response); if ($objRequest->code == 201) { file_put_contents($strFile, fopen($arrResponse->output->url, "rb", false)); $objFile->tstamp = time(); $objFile->path = $file; $objFile->hash = md5_file(TL_ROOT . '/' . $file); $objFile->save(); System::log('Compression was successful. (File: ' . $file . ')', __METHOD__, TL_FILES); } else { System::log('Compression failed. (' . $arrResponse->message . ') (File: ' . $file . ')', __METHOD__, TL_FILES); } } } } }
public function getDownloadElement($strTag) { $params = preg_split('/::/', $strTag); if (is_array($params) && !empty($params)) { if (strpos($params[0], 'download') === 0) { $singleSRC = strip_tags($params[1]); // remove <span> etc, otherwise Validator::isuuid fail $objDownload = new \stdClass(); if (strpos($singleSRC, '/') !== false) { if (($objFile = FilesModel::findByPath($singleSRC)) !== null && $objFile->uuid) { $singleSRC = \StringUtil::binToUuid($objFile->uuid); } } $objDownload->singleSRC = $singleSRC; $objDownload->linkTitle = strip_tags($params[2]); // remove <span> etc $objDownload->cssID[1] = 'inserttag_download ' . strip_tags($params[3]); $objDownload->cssID[0] = strip_tags($params[4]); $objContentDownload = new \ContentDownloadInserttag($objDownload); $output = $objContentDownload->generate(); if ($params[0] == 'download') { return $output; } if ($params[0] == 'download_link') { return $objContentDownload->Template->href; } if ($params[0] == 'download_size') { return $objContentDownload->Template->filesize; } return ''; } } return false; }
/** * 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; }
/** * Ajax actions that do require a data container object * * @param DataContainer $dc * * @throws NoContentResponseException * @throws ResponseException * @throws BadRequestHttpException */ public function executePostActions(DataContainer $dc) { header('Content-Type: text/html; charset=' . \Config::get('characterSet')); // Bypass any core logic for non-core drivers (see #5957) if (!$dc instanceof DC_File && !$dc instanceof DC_Folder && !$dc instanceof DC_Table) { $this->executePostActionsHook($dc); throw new NoContentResponseException(); } switch ($this->strAction) { // Load nodes of the page structure tree case 'loadStructure': throw new ResponseException($this->convertToResponse($dc->ajaxTreeView($this->strAjaxId, intval(\Input::post('level'))))); // Load nodes of the file manager tree // Load nodes of the file manager tree case 'loadFileManager': throw new ResponseException($this->convertToResponse($dc->ajaxTreeView(\Input::post('folder', true), intval(\Input::post('level'))))); // Load nodes of the page tree // Load nodes of the page tree case 'loadPagetree': $varValue = null; $strField = $dc->field = \Input::post('name'); // Call the load_callback if (is_array($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField]['load_callback'])) { foreach ($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField]['load_callback'] as $callback) { if (is_array($callback)) { $this->import($callback[0]); $varValue = $this->{$callback[0]}->{$callback[1]}($varValue, $dc); } elseif (is_callable($callback)) { $varValue = $callback($varValue, $dc); } } } /** @var PageSelector $strClass */ $strClass = $GLOBALS['BE_FFL']['pageSelector']; /** @var PageSelector $objWidget */ $objWidget = new $strClass($strClass::getAttributesFromDca($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField], $dc->field, $varValue, $strField, $dc->table, $dc)); throw new ResponseException($this->convertToResponse($objWidget->generateAjax($this->strAjaxId, \Input::post('field'), intval(\Input::post('level'))))); // Load nodes of the file tree // Load nodes of the file tree case 'loadFiletree': $varValue = null; $strField = $dc->field = \Input::post('name'); // Call the load_callback if (is_array($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField]['load_callback'])) { foreach ($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField]['load_callback'] as $callback) { if (is_array($callback)) { $this->import($callback[0]); $varValue = $this->{$callback[0]}->{$callback[1]}($varValue, $dc); } elseif (is_callable($callback)) { $varValue = $callback($varValue, $dc); } } } /** @var FileSelector $strClass */ $strClass = $GLOBALS['BE_FFL']['fileSelector']; /** @var FileSelector $objWidget */ $objWidget = new $strClass($strClass::getAttributesFromDca($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField], $dc->field, $varValue, $strField, $dc->table, $dc)); // Load a particular node if (\Input::post('folder', true) != '') { throw new ResponseException($this->convertToResponse($objWidget->generateAjax(\Input::post('folder', true), \Input::post('field'), intval(\Input::post('level'))))); } throw new ResponseException($this->convertToResponse($objWidget->generate())); // Reload the page/file picker // Reload the page/file picker case 'reloadPagetree': case 'reloadFiletree': $intId = \Input::get('id'); $strField = $dc->inputName = \Input::post('name'); // Handle the keys in "edit multiple" mode if (\Input::get('act') == 'editAll') { $intId = preg_replace('/.*_([0-9a-zA-Z]+)$/', '$1', $strField); $strField = preg_replace('/(.*)_[0-9a-zA-Z]+$/', '$1', $strField); } $dc->field = $strField; // The field does not exist if (!isset($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField])) { $this->log('Field "' . $strField . '" does not exist in DCA "' . $dc->table . '"', __METHOD__, TL_ERROR); throw new BadRequestHttpException('Bad request'); } $objRow = null; $varValue = null; // Load the value if (\Input::get('act') != 'overrideAll') { if ($GLOBALS['TL_DCA'][$dc->table]['config']['dataContainer'] == 'File') { $varValue = \Config::get($strField); } elseif ($intId > 0 && $this->Database->tableExists($dc->table)) { $objRow = $this->Database->prepare("SELECT * FROM " . $dc->table . " WHERE id=?")->execute($intId); // The record does not exist if ($objRow->numRows < 1) { $this->log('A record with the ID "' . $intId . '" does not exist in table "' . $dc->table . '"', __METHOD__, TL_ERROR); throw new BadRequestHttpException('Bad request'); } $varValue = $objRow->{$strField}; $dc->activeRecord = $objRow; } } // Call the load_callback if (is_array($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField]['load_callback'])) { foreach ($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField]['load_callback'] as $callback) { if (is_array($callback)) { $this->import($callback[0]); $varValue = $this->{$callback[0]}->{$callback[1]}($varValue, $dc); } elseif (is_callable($callback)) { $varValue = $callback($varValue, $dc); } } } // Set the new value $varValue = \Input::post('value', true); $strKey = $this->strAction == 'reloadPagetree' ? 'pageTree' : 'fileTree'; // Convert the selected values if ($varValue != '') { $varValue = \StringUtil::trimsplit("\t", $varValue); // Automatically add resources to the DBAFS if ($strKey == 'fileTree') { foreach ($varValue as $k => $v) { if (\Dbafs::shouldBeSynchronized($v)) { $objFile = \FilesModel::findByPath($v); if ($objFile === null) { $objFile = \Dbafs::addResource($v); } $varValue[$k] = $objFile->uuid; } } } $varValue = serialize($varValue); } /** @var FileTree|PageTree $strClass */ $strClass = $GLOBALS['BE_FFL'][$strKey]; /** @var FileTree|PageTree $objWidget */ $objWidget = new $strClass($strClass::getAttributesFromDca($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField], $dc->inputName, $varValue, $strField, $dc->table, $dc)); throw new ResponseException($this->convertToResponse($objWidget->generate())); // Feature/unfeature an element // Feature/unfeature an element case 'toggleFeatured': if (class_exists($dc->table, false)) { $dca = new $dc->table(); if (method_exists($dca, 'toggleFeatured')) { $dca->toggleFeatured(\Input::post('id'), \Input::post('state') == 1 ? true : false); } } throw new NoContentResponseException(); // Toggle subpalettes // Toggle subpalettes case 'toggleSubpalette': $this->import('BackendUser', 'User'); // Check whether the field is a selector field and allowed for regular users (thanks to Fabian Mihailowitsch) (see #4427) if (!is_array($GLOBALS['TL_DCA'][$dc->table]['palettes']['__selector__']) || !in_array(\Input::post('field'), $GLOBALS['TL_DCA'][$dc->table]['palettes']['__selector__']) || $GLOBALS['TL_DCA'][$dc->table]['fields'][\Input::post('field')]['exclude'] && !$this->User->hasAccess($dc->table . '::' . \Input::post('field'), 'alexf')) { $this->log('Field "' . \Input::post('field') . '" is not an allowed selector field (possible SQL injection attempt)', __METHOD__, TL_ERROR); throw new BadRequestHttpException('Bad request'); } if ($dc instanceof DC_Table) { if (\Input::get('act') == 'editAll') { $this->strAjaxId = preg_replace('/.*_([0-9a-zA-Z]+)$/', '$1', \Input::post('id')); $this->Database->prepare("UPDATE " . $dc->table . " SET " . \Input::post('field') . "='" . (intval(\Input::post('state') == 1) ? 1 : '') . "' WHERE id=?")->execute($this->strAjaxId); if (\Input::post('load')) { echo $dc->editAll($this->strAjaxId, \Input::post('id')); } } else { $this->Database->prepare("UPDATE " . $dc->table . " SET " . \Input::post('field') . "='" . (intval(\Input::post('state') == 1) ? 1 : '') . "' WHERE id=?")->execute($dc->id); if (\Input::post('load')) { throw new ResponseException($this->convertToResponse($dc->edit(false, \Input::post('id')))); } } } elseif ($dc instanceof DC_File) { $val = intval(\Input::post('state') == 1) ? true : false; \Config::persist(\Input::post('field'), $val); if (\Input::post('load')) { \Config::set(\Input::post('field'), $val); throw new ResponseException($this->convertToResponse($dc->edit(false, \Input::post('id')))); } } throw new NoContentResponseException(); // DropZone file upload // DropZone file upload case 'fileupload': $dc->move(); throw new NoContentResponseException(); // HOOK: pass unknown actions to callback functions // HOOK: pass unknown actions to callback functions default: $this->executePostActionsHook($dc); throw new NoContentResponseException(); } }
/** * 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) { $this->sendActivationMail($arrData); } // 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 = \StringUtil::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')) instanceof PageModel) { $this->jumpToOrReload($objJumpTo->row()); } $this->reload(); }
/** * Return the files model * * @return FilesModel The files model */ public function getModel() { if ($this->objModel === null && \Dbafs::shouldBeSynchronized($this->strFile)) { $this->objModel = \FilesModel::findByPath($this->strFile); } return $this->objModel; }
/** * Load the source editor * * @return string * * @throws InternalServerErrorException */ public function source() { $this->isValid($this->intId); if (is_dir(TL_ROOT . '/' . $this->intId)) { throw new InternalServerErrorException('Folder "' . $this->intId . '" cannot be edited.'); } elseif (!file_exists(TL_ROOT . '/' . $this->intId)) { throw new InternalServerErrorException('File "' . $this->intId . '" does not exist.'); } $this->import('BackendUser', 'User'); // Check user permission if (!$this->User->hasAccess('f5', 'fop')) { throw new AccessDeniedException('Not enough permissions to edit the file source of file "' . $this->intId . '".'); } $objFile = new \File($this->intId); // Check whether file type is editable if (!in_array($objFile->extension, trimsplit(',', \Config::get('editableFiles')))) { throw new AccessDeniedException('File type "' . $objFile->extension . '" (' . $this->intId . ') is not allowed to be edited.'); } $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 (isset($_POST['saveNclose'])) { \System::setCookie('BE_PAGE_OFFSET', 0, 0); $this->redirect($this->getReferer()); } $this->reload(); } $codeEditor = ''; // Prepare the code editor if (\Config::get('useCE')) { /** @var BackendTemplate|object $objTemplate */ $objTemplate = new \BackendTemplate('be_ace'); $objTemplate->selector = 'ctrl_source'; $objTemplate->type = $objFile->extension; $codeEditor = $objTemplate->parse(); } // 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'] = '<button type="submit" name="save" id="save" class="tl_submit" accesskey="s">' . $GLOBALS['TL_LANG']['MSC']['save'] . '</button>'; $arrButtons['saveNclose'] = '<button type="submit" name="saveNclose" id="saveNclose" class="tl_submit" accesskey="c">' . $GLOBALS['TL_LANG']['MSC']['saveNclose'] . '</button>'; // 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; }
/** * 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); $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); } } }
/** * Return the files model * * @return \FilesModel The files model */ public function getModel() { if ($this->blnSyncDb && $this->objModel === null) { $this->objModel = \FilesModel::findByPath($this->strFile); } return $this->objModel; }
/** * Run the controller and parse the template * * @return Response */ 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); $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); $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); // Image if ($objFile->isImage) { $objTemplate->isImage = true; $objTemplate->width = $objFile->width; $objTemplate->height = $objFile->height; $objTemplate->src = $this->urlEncode($this->strFile); } $objTemplate->href = ampersand(\Environment::get('request'), true) . '&download=1'; $objTemplate->filesize = $this->getReadableSize($objFile->filesize) . ' (' . number_format($objFile->filesize, 0, $GLOBALS['TL_LANG']['MSC']['decimalSeparator'], $GLOBALS['TL_LANG']['MSC']['thousandsSeparator']) . ' Byte)'; } $objTemplate->icon = $objFile->icon; $objTemplate->mime = $objFile->mime; $objTemplate->ctime = \Date::parse(\Config::get('datimFormat'), $objFile->ctime); $objTemplate->mtime = \Date::parse(\Config::get('datimFormat'), $objFile->mtime); $objTemplate->atime = \Date::parse(\Config::get('datimFormat'), $objFile->atime); $objTemplate->path = specialchars($this->strFile); $objTemplate->theme = \Backend::getTheme(); $objTemplate->base = \Environment::get('base'); $objTemplate->language = $GLOBALS['TL_LANGUAGE']; $objTemplate->title = specialchars($this->strFile); $objTemplate->charset = \Config::get('characterSet'); $objTemplate->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']); return $objTemplate->getResponse(); }
/** * 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 * * @deprecated Deprecated since Contao 4.3, to be removed in Contao 5.0. * Use the contao.image.image_factory service instead. */ public static function create($image, $size = null) { @trigger_error('Using Image::create() has been deprecated and will no longer work in Contao 5.0. Use the contao.image.image_factory service instead.', E_USER_DEPRECATED); 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; }
/** * 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; }