log() public static method

Add a log entry to the database
Deprecation: Deprecated since Contao 4.2, to be removed in Contao 5. Use the logger service instead.
public static log ( string $strText, string $strFunction, string $strCategory )
$strText string The log message
$strFunction string The function name
$strCategory string The category name
 /**
  * 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);
                 }
             }
         }
     }
 }
Esempio n. 2
0
 /**
  * Purge the data
  */
 public function purge()
 {
     // Purge the data
     Database::getInstance()->query("TRUNCATE TABLE tl_vimeo_cache");
     // Purge the images
     $folder = new \Folder(static::$imagesFolder);
     $folder->purge();
     // Log the action
     System::log('Purged the Vimeo cache', __METHOD__, TL_CRON);
 }
 /**
  * Rebuild Vimeo cache
  *
  * @param DataContainer $dc
  */
 public function rebuildVimeoCache(DataContainer $dc)
 {
     $rebuilder = new Rebuilder();
     try {
         $result = $rebuilder->rebuildElementCache(ContentModel::findByPk($dc->id));
     } catch (\InvalidArgumentException $e) {
         return;
     } catch (\RuntimeException $e) {
         System::log(sprintf('Unable to rebuild Vimeo cache of element ID %s: %s', $dc->id, $e->getMessage()), __METHOD__, TL_ERROR);
         $result = false;
     }
     if ($result === true) {
         Message::addConfirmation($GLOBALS['TL_LANG']['tl_content']['vimeo_cacheConfirm']);
     } elseif ($result === false) {
         Message::addError($GLOBALS['TL_LANG']['tl_content']['vimeo_cacheError']);
     }
 }
Esempio n. 4
0
 public function checkLoginStatus($objPage, $objLayout, \PageRegular $objPageRegular)
 {
     global $objPage;
     $loggedIn = FE_USER_LOGGED_IN;
     if (\Input::get('logout')) {
         if (@$this->User->logout()) {
             $loggedIn = false;
         }
     }
     if (!$loggedIn && $objPage->type != "login" && (Config::get("globalLogin") == 1 || $objPage->type == "error_403")) {
         $loginPage = PageModel::findOneBy("type", "login");
         if (isset($loginPage) && $loginPage->published == 1) {
             $loginPage->loadDetails();
             $objPage = $loginPage;
             $handler = new LoginPage(\Environment::get("request"));
             $handler->generate($loginPage);
             exit;
         } else {
             System::log("Please create a Login-Page urgently!!", "LoginPage\\checkLoginStatus", TL_ERROR);
             if ($objPage->type == "error_403") {
                 return;
             }
             $page403_model = \PageModel::find403ByPid($objPage->rootId);
             if (isset($page403_model) && $page403_model->published == 1) {
                 $page403_model->loadDetails();
                 $objPage = $page403_model;
                 $handler = new PageError403();
                 $handler->generate($page403_model->id, $page403_model->rootId);
                 exit;
             } else {
                 System::log("Please create a 403-Error-Page urgently!!", "LoginPage\\checkLoginStatus", TL_ERROR);
                 $objPage->template = 'fe_login';
                 $objPage->templateGroup = $objLayout->templates;
                 $objPageRegular->createTemplate($objPage, $objLayout);
             }
         }
     }
 }
 /**
  * Contao ImportUser Hook Implementation
  *
  * Imports a user from phpbb if login credentials match
  *
  * @param $username
  * @param $password
  * @param $scope
  * @return bool
  */
 public function onImportUser($username, $password, $scope)
 {
     if ($scope == 'tl_member') {
         // Before we try to import a user, we must check is username is maybe = username_clean
         // We already now that the user could not be found by username column
         if (($real_username = $this->findByCleanUsername($username)) != '') {
             // So we found the user by it's clean username, then we overwrite the POST Value
             // because contao will recheck it.
             Input::setPost('username', $real_username);
             return true;
         }
         $loginResult = System::getContainer()->get('phpbb_bridge.connector')->validateLogin($username, $password);
         // Only import user if login to forum succeeded
         if ($loginResult === true) {
             System::log("Trying to import User: " . $username, __METHOD__, TL_ACCESS);
             // Try to import the user to contao (tl_member / frontend)
             $importResult = System::getContainer()->get('phpbb_bridge.connector')->importUser($username, $password);
             return $importResult;
             // Should usually be true
         }
     }
     return false;
 }
Esempio n. 6
0
 /**
  * Make an API request to Vimeo.
  *
  * @param string $url    A Vimeo API Endpoint. Should not include the host
  * @param array  $params An array of parameters to send to the endpoint. If the HTTP method is GET, they will be added to the url, otherwise they will be written to the body
  * @param string $method The HTTP Method of the request
  * @param bool   $json_body
  *
  * @return array|null
  */
 public function request($url, $params = array(), $method = 'GET', $json_body = true)
 {
     if (Config::get('debugMode')) {
         static $requestCount = 0;
         if (++$requestCount > $this->requestLimit) {
             System::log(sprintf('The request limit of %s has been reached. Please check your script for possible optimizations.', $this->requestLimit), __METHOD__, 'VIMEO');
             return null;
         }
         System::log('Vimeo request to: ' . $url, __METHOD__, 'VIMEO');
     }
     try {
         $response = parent::request($url, $params, $method, $json_body);
     } catch (\Exception $e) {
         System::log(sprintf('Vimeo request (%s) failed with exception: %s', $url, $e->getMessage()), __METHOD__, TL_ERROR);
         return null;
     }
     $this->updateStats($response['headers']);
     if ($response['status'] !== 200) {
         System::log(sprintf('Vimeo request (%s) failed (code %s): %s', $url, $response['status'], print_r($response, true)), __METHOD__, TL_ERROR);
         return null;
     }
     return $response;
 }
 /**
  * Fetch the video image
  *
  * @param int $videoId
  * @param int $index
  *
  * @return null|string
  *
  * @throws \InvalidArgumentException
  */
 protected function fetchVideoImage($videoId, $index)
 {
     if ($index < 1) {
         throw new \InvalidArgumentException('The image index cannot be smaller than 1');
     }
     $videoId = (int) $videoId;
     // Return if the video could not be found
     if (($videoData = $this->getVideo($videoId)) === null) {
         return null;
     }
     $index = (int) $index - 1;
     // If the first image was requested then it should already be there
     if ($index === 0 && isset($videoData['pictures']['sizes'])) {
         $sizes = $videoData['pictures']['sizes'];
     } else {
         // Return if there are no video images
         if (($images = $this->getVideoImages($videoId)) === null) {
             return null;
         }
         $sizes = isset($images['data'][$index]['sizes']) ? $images['data'][$index]['sizes'] : $images['data'][0]['sizes'];
     }
     $picture = array_pop($sizes);
     $request = new Request();
     $request->send($picture['link']);
     if ($request->hasError()) {
         System::log(sprintf('Unable to download Vimeo video image "%s"', $picture['link']), __METHOD__, TL_ERROR);
         return null;
     }
     return $request->response;
 }
Esempio n. 8
0
 /**
  * Try to find a root page based on language and URL
  *
  * @return PageModel
  */
 public static function getRootPageFromUrl()
 {
     // HOOK: add custom logic
     if (isset($GLOBALS['TL_HOOKS']['getRootPageFromUrl']) && is_array($GLOBALS['TL_HOOKS']['getRootPageFromUrl'])) {
         foreach ($GLOBALS['TL_HOOKS']['getRootPageFromUrl'] as $callback) {
             /** @var PageModel $objRootPage */
             if (is_object($objRootPage = static::importStatic($callback[0])->{$callback[1]}())) {
                 return $objRootPage;
             }
         }
     }
     $host = \Environment::get('host');
     // The language is set in the URL
     if (\Config::get('addLanguageToUrl') && !empty($_GET['language'])) {
         $objRootPage = \PageModel::findFirstPublishedRootByHostAndLanguage($host, \Input::get('language'));
         // No matching root page found
         if ($objRootPage === null) {
             \System::log('No root page found (host "' . $host . '", language "' . \Input::get('language') . '")', __METHOD__, TL_ERROR);
             throw new NoRootPageFoundException('No root page found');
         }
     } else {
         $accept_language = \Environment::get('httpAcceptLanguage');
         // Find the matching root pages (thanks to Andreas Schempp)
         $objRootPage = \PageModel::findFirstPublishedRootByHostAndLanguage($host, $accept_language);
         // No matching root page found
         if ($objRootPage === null) {
             \System::log('No root page found (host "' . \Environment::get('host') . '", languages "' . implode(', ', \Environment::get('httpAcceptLanguage')) . '")', __METHOD__, TL_ERROR);
             throw new NoRootPageFoundException('No root page found');
         }
         // Redirect to the language root (e.g. en/)
         if (\Config::get('addLanguageToUrl') && !\Config::get('doNotRedirectEmpty') && \Environment::get('relativeRequest') == '') {
             $arrParams = array('_locale' => $objRootPage->language);
             $strUrl = \System::getContainer()->get('router')->generate('contao_index', $arrParams);
             $strUrl = substr($strUrl, strlen(\Environment::get('path')) + 1);
             static::redirect($strUrl, 301);
         }
     }
     return $objRootPage;
 }
 /**
  * @return Browser
  */
 protected function initForumRequest($force = false)
 {
     // Init Request
     $client = new Curl();
     $client->setMaxRedirects(0);
     $browser = new Browser();
     $browser->setClient($client);
     $cookieListener = new CookieListener();
     $browser->addListener($cookieListener);
     // We need to make sure that the if the original Request is already coming from the forum, we then are not
     // allowed to send a request to the forum so we create a login loop for example.
     if ($force === false && System::getContainer()->get('request_stack')->getCurrentRequest() && System::getContainer()->get('request_stack')->getCurrentRequest()->headers->get('x-requested-with') == 'ContaoPhpbbBridge') {
         System::log('Bridge Request Recursion detected', __METHOD__, TL_ERROR);
         throw new TooManyRequestsHttpException(null, 'Internal recursion Bridge requests detected');
     }
     return $browser;
 }
 /**
  * Handle a log event.
  *
  * @param LogEvent $event The event.
  *
  * @return void
  */
 public function handleLog(LogEvent $event)
 {
     System::log($event->getText(), $event->getFunction(), $event->getCategory());
 }
Esempio n. 11
0
 /**
  * Resize an image and store the resized version in the image target folder
  *
  * @param string  $image        The image path
  * @param integer $width        The target width
  * @param integer $height       The target height
  * @param string  $mode         The resize mode
  * @param string  $target       An optional target path
  * @param boolean $force        Override existing target images
  *
  * @return string|null The path of the resized image or null
  *
  * @deprecated Deprecated since Contao 4.3, to be removed in Contao 5.0.
  *             Use the contao.image.image_factory service instead.
  */
 public static function get($image, $width, $height, $mode = '', $target = null, $force = false)
 {
     @trigger_error('Using Image::get() has been deprecated and will no longer work in Contao 5.0. Use the contao.image.image_factory service instead.', E_USER_DEPRECATED);
     if ($image == '') {
         return null;
     }
     try {
         $imageObj = static::create($image, array($width, $height, $mode));
         $imageObj->setTargetPath($target);
         $imageObj->setForceOverride($force);
         if (($path = $imageObj->executeResize()->getResizedPath()) != '') {
             return $path;
         }
     } catch (\Exception $e) {
         \System::log('Image "' . $image . '" could not be processed: ' . $e->getMessage(), __METHOD__, TL_ERROR);
     }
     return null;
 }
 /**
  * @Route("/autologin")
  * @return Response
  */
 public function autologinAction()
 {
     $this->validateRequest();
     $isLoggedIn = false;
     $userId = 0;
     if (FE_USER_LOGGED_IN === true) {
         $username = $this->container->get('security.token_storage')->getToken()->getUsername();
         $phpBBuser = $this->container->get('phpbb_bridge.connector')->getUser($username);
         if ($phpBBuser !== null) {
             $isLoggedIn = true;
             $userId = $phpBBuser->user_id;
         } else {
             System::log('Request from phpbb to autologin a user which was found in Contao but not in phpbb: ' . $username, __METHOD__, TL_ERROR);
         }
     }
     $response = new JsonResponse();
     $response->setData(array('is_logged_in' => $isLoggedIn, 'user_id' => (int) $userId));
     return $response;
 }
Esempio n. 13
0
    /**
     * Add a breadcrumb menu to the file tree
     *
     * @param string $strKey
     *
     * @throws \RuntimeException
     */
    public static function addFilesBreadcrumb($strKey = 'tl_files_node')
    {
        /** @var AttributeBagInterface $objSession */
        $objSession = \System::getContainer()->get('session')->getBag('contao_backend');
        // Set a new node
        if (isset($_GET['node'])) {
            // Check the path (thanks to Arnaud Buchoux)
            if (\Validator::isInsecurePath(\Input::get('node', true))) {
                throw new \RuntimeException('Insecure path ' . \Input::get('node', true));
            }
            $objSession->set($strKey, \Input::get('node', true));
            \Controller::redirect(preg_replace('/(&|\\?)node=[^&]*/', '', \Environment::get('request')));
        }
        $strNode = $objSession->get($strKey);
        if ($strNode == '') {
            return;
        }
        // Check the path (thanks to Arnaud Buchoux)
        if (\Validator::isInsecurePath($strNode)) {
            throw new \RuntimeException('Insecure path ' . $strNode);
        }
        // Currently selected folder does not exist
        if (!is_dir(TL_ROOT . '/' . $strNode)) {
            $objSession->set($strKey, '');
            return;
        }
        $objUser = \BackendUser::getInstance();
        $strPath = \Config::get('uploadPath');
        $arrNodes = explode('/', preg_replace('/^' . preg_quote(\Config::get('uploadPath'), '/') . '\\//', '', $strNode));
        $arrLinks = array();
        // Add root link
        $arrLinks[] = '<img src="' . TL_FILES_URL . 'system/themes/' . \Backend::getTheme() . '/images/filemounts.gif" width="18" height="18" alt=""> <a href="' . \Controller::addToUrl('node=') . '" title="' . specialchars($GLOBALS['TL_LANG']['MSC']['selectAllNodes']) . '">' . $GLOBALS['TL_LANG']['MSC']['filterAll'] . '</a>';
        // Generate breadcrumb trail
        foreach ($arrNodes as $strFolder) {
            $strPath .= '/' . $strFolder;
            // Do not show pages which are not mounted
            if (!$objUser->hasAccess($strPath, 'filemounts')) {
                continue;
            }
            // No link for the active folder
            if ($strFolder == basename($strNode)) {
                $arrLinks[] = '<img src="' . TL_FILES_URL . 'system/themes/' . \Backend::getTheme() . '/images/folderC.gif" width="18" height="18" alt=""> ' . $strFolder;
            } else {
                $arrLinks[] = '<img src="' . TL_FILES_URL . 'system/themes/' . \Backend::getTheme() . '/images/folderC.gif" width="18" height="18" alt=""> <a href="' . \Controller::addToUrl('node=' . $strPath) . '" title="' . specialchars($GLOBALS['TL_LANG']['MSC']['selectNode']) . '">' . $strFolder . '</a>';
            }
        }
        // Check whether the node is mounted
        if (!$objUser->hasAccess($strNode, 'filemounts')) {
            $objSession->set($strKey, '');
            \System::log('Folder ID ' . $strNode . ' was not mounted', __METHOD__, TL_ERROR);
            \Controller::redirect('contao/main.php?act=error');
        }
        // Limit tree
        $GLOBALS['TL_DCA']['tl_files']['list']['sorting']['root'] = array($strNode);
        // Insert breadcrumb menu
        $GLOBALS['TL_DCA']['tl_files']['list']['sorting']['breadcrumb'] .= '

<ul id="tl_breadcrumb">
  <li>' . implode(' &gt; </li><li>', $arrLinks) . '</li>
</ul>';
    }
Esempio n. 14
0
 /**
  * Handle the element AJAX action
  *
  * @throws \InvalidArgumentException
  * @throws \RuntimeException
  */
 protected function handleElementAction()
 {
     // Throw an error if content element could not be found
     if (($contentElement = ContentModel::findByPk(Input::post('id'))) === null) {
         System::log(sprintf('Unable to find the content element ID %s', Input::post('id')), __METHOD__, TL_ERROR);
         header('HTTP/1.1 400 Bad Request');
         die('Bad Request');
     }
     $dataProvider = $this->getBatchProvider();
     $callback = static::getCallbackInstance($contentElement->type);
     if (!$callback->rebuild($dataProvider, $contentElement)) {
         header('HTTP/1.1 400 Bad Request');
         die('Bad Request');
     }
     header('HTTP/1.1 200 OK');
     die('OK');
 }
Esempio n. 15
0
 /**
  * Handle "runonce" files
  *
  * @throws \Exception
  */
 public static function handleRunOnce()
 {
     try {
         $files = \System::getContainer()->get('contao.resource_locator')->locate('config/runonce.php', null, false);
     } catch (\InvalidArgumentException $e) {
         return;
     }
     foreach ($files as $file) {
         try {
             include $file;
         } catch (\Exception $e) {
         }
         $strRelpath = str_replace(TL_ROOT . DIRECTORY_SEPARATOR, '', $file);
         if (!unlink($file)) {
             throw new \Exception("The file {$strRelpath} cannot be deleted. Please remove the file manually and correct the file permission settings on your server.");
         }
         \System::log("File {$strRelpath} ran once and has then been removed successfully", __METHOD__, TL_GENERAL);
     }
 }
Esempio n. 16
0
 /**
  * Get the details of a page including inherited parameters
  *
  * @return PageModel The page model
  *
  * @throws NoRootPageFoundException If no root page is found
  */
 public function loadDetails()
 {
     // Loaded already
     if ($this->blnDetailsLoaded) {
         return $this;
     }
     // Set some default values
     $this->protected = (bool) $this->protected;
     $this->groups = $this->protected ? \StringUtil::deserialize($this->groups) : false;
     $this->layout = $this->includeLayout ? $this->layout : false;
     $this->mobileLayout = $this->includeLayout ? $this->mobileLayout : false;
     $this->cache = $this->includeCache ? $this->cache : false;
     $pid = $this->pid;
     $type = $this->type;
     $alias = $this->alias;
     $name = $this->title;
     $title = $this->pageTitle ?: $this->title;
     $folderUrl = '';
     $palias = '';
     $pname = '';
     $ptitle = '';
     $trail = array($this->id, $pid);
     // Inherit the settings
     if ($this->type == 'root') {
         $objParentPage = $this;
         // see #4610
     } else {
         // Load all parent pages
         $objParentPage = \PageModel::findParentsById($pid);
         if ($objParentPage !== null) {
             while ($pid > 0 && $type != 'root' && $objParentPage->next()) {
                 $pid = $objParentPage->pid;
                 $type = $objParentPage->type;
                 // Parent title
                 if ($ptitle == '') {
                     $palias = $objParentPage->alias;
                     $pname = $objParentPage->title;
                     $ptitle = $objParentPage->pageTitle ?: $objParentPage->title;
                 }
                 // Page title
                 if ($type != 'root') {
                     $alias = $objParentPage->alias;
                     $name = $objParentPage->title;
                     $title = $objParentPage->pageTitle ?: $objParentPage->title;
                     $folderUrl = basename($alias) . '/' . $folderUrl;
                     $trail[] = $objParentPage->pid;
                 }
                 // Cache
                 if ($objParentPage->includeCache && $this->cache === false) {
                     $this->cache = $objParentPage->cache;
                 }
                 // Layout
                 if ($objParentPage->includeLayout) {
                     if ($this->layout === false) {
                         $this->layout = $objParentPage->layout;
                     }
                     if ($this->mobileLayout === false) {
                         $this->mobileLayout = $objParentPage->mobileLayout;
                     }
                 }
                 // Protection
                 if ($objParentPage->protected && $this->protected === false) {
                     $this->protected = true;
                     $this->groups = \StringUtil::deserialize($objParentPage->groups);
                 }
             }
         }
         // Set the titles
         $this->mainAlias = $alias;
         $this->mainTitle = $name;
         $this->mainPageTitle = $title;
         $this->parentAlias = $palias;
         $this->parentTitle = $pname;
         $this->parentPageTitle = $ptitle;
         $this->folderUrl = $folderUrl;
     }
     // Set the root ID and title
     if ($objParentPage !== null && $objParentPage->type == 'root') {
         $this->rootId = $objParentPage->id;
         $this->rootAlias = $objParentPage->alias;
         $this->rootTitle = $objParentPage->title;
         $this->rootPageTitle = $objParentPage->pageTitle ?: $objParentPage->title;
         $this->domain = $objParentPage->dns;
         $this->rootLanguage = $objParentPage->language;
         $this->language = $objParentPage->language;
         $this->staticFiles = $objParentPage->staticFiles;
         $this->staticPlugins = $objParentPage->staticPlugins;
         $this->dateFormat = $objParentPage->dateFormat;
         $this->timeFormat = $objParentPage->timeFormat;
         $this->datimFormat = $objParentPage->datimFormat;
         $this->adminEmail = $objParentPage->adminEmail;
         // Store whether the root page has been published
         $time = \Date::floorToMinute();
         $this->rootIsPublic = $objParentPage->published && ($objParentPage->start == '' || $objParentPage->start <= $time) && ($objParentPage->stop == '' || $objParentPage->stop > $time + 60);
         $this->rootIsFallback = true;
         $this->rootUseSSL = $objParentPage->useSSL;
         $this->rootFallbackLanguage = $objParentPage->language;
         // Store the fallback language (see #6874)
         if (!$objParentPage->fallback) {
             $this->rootIsFallback = false;
             $this->rootFallbackLanguage = null;
             $objFallback = static::findPublishedFallbackByHostname($objParentPage->dns);
             if ($objFallback !== null) {
                 $this->rootFallbackLanguage = $objFallback->language;
             }
         }
     } elseif (TL_MODE == 'FE' && $this->type != 'root') {
         \System::log('Page ID "' . $this->id . '" does not belong to a root page', __METHOD__, TL_ERROR);
         throw new NoRootPageFoundException('No root page found');
     }
     $this->trail = array_reverse($trail);
     // Do not cache protected pages
     if ($this->protected) {
         $this->cache = 0;
     }
     // Use the global date format if none is set (see #6104)
     if ($this->dateFormat == '') {
         $this->dateFormat = \Config::get('dateFormat');
     }
     if ($this->timeFormat == '') {
         $this->timeFormat = \Config::get('timeFormat');
     }
     if ($this->datimFormat == '') {
         $this->datimFormat = \Config::get('datimFormat');
     }
     // Prevent saving (see #6506 and #7199)
     $this->preventSaving();
     $this->blnDetailsLoaded = true;
     return $this;
 }
Esempio n. 17
0
 /**
  * Add an image to a template
  *
  * @param object  $objTemplate   The template object to add the image to
  * @param array   $arrItem       The element or module as array
  * @param integer $intMaxWidth   An optional maximum width of the image
  * @param string  $strLightboxId An optional lightbox ID
  */
 public static function addImageToTemplate($objTemplate, $arrItem, $intMaxWidth = null, $strLightboxId = null)
 {
     try {
         $objFile = new \File($arrItem['singleSRC']);
     } catch (\Exception $e) {
         $objFile = new \stdClass();
         $objFile->imageSize = false;
     }
     $imgSize = $objFile->imageSize;
     $size = deserialize($arrItem['size']);
     if ($intMaxWidth === null) {
         $intMaxWidth = TL_MODE == 'BE' ? 320 : \Config::get('maxImageWidth');
     }
     $arrMargin = TL_MODE == 'BE' ? array() : deserialize($arrItem['imagemargin']);
     // Store the original dimensions
     $objTemplate->width = $imgSize[0];
     $objTemplate->height = $imgSize[1];
     // Adjust the image size
     if ($intMaxWidth > 0) {
         // Subtract the margins before deciding whether to resize (see #6018)
         if (is_array($arrMargin) && $arrMargin['unit'] == 'px') {
             $intMargin = $arrMargin['left'] + $arrMargin['right'];
             // Reset the margin if it exceeds the maximum width (see #7245)
             if ($intMaxWidth - $intMargin < 1) {
                 $arrMargin['left'] = '';
                 $arrMargin['right'] = '';
             } else {
                 $intMaxWidth = $intMaxWidth - $intMargin;
             }
         }
         if ($size[0] > $intMaxWidth || !$size[0] && !$size[1] && $imgSize[0] > $intMaxWidth) {
             // See #2268 (thanks to Thyon)
             $ratio = $size[0] && $size[1] ? $size[1] / $size[0] : $imgSize[1] / $imgSize[0];
             $size[0] = $intMaxWidth;
             $size[1] = floor($intMaxWidth * $ratio);
         }
     }
     // Disable responsive images in the back end (see #7875)
     if (TL_MODE == 'BE') {
         unset($size[2]);
     }
     try {
         $src = \Image::create($arrItem['singleSRC'], $size)->executeResize()->getResizedPath();
         $picture = \Picture::create($arrItem['singleSRC'], $size)->getTemplateData();
         if ($src !== $arrItem['singleSRC']) {
             $objFile = new \File(rawurldecode($src));
         }
     } catch (\Exception $e) {
         \System::log('Image "' . $arrItem['singleSRC'] . '" could not be processed: ' . $e->getMessage(), __METHOD__, TL_ERROR);
         $src = '';
         $picture = array('img' => array('src' => '', 'srcset' => ''), 'sources' => array());
     }
     // Image dimensions
     if (($imgSize = $objFile->imageSize) !== false) {
         $objTemplate->arrSize = $imgSize;
         $objTemplate->imgSize = ' width="' . $imgSize[0] . '" height="' . $imgSize[1] . '"';
     }
     $picture['alt'] = specialchars($arrItem['alt']);
     $picture['title'] = specialchars($arrItem['title']);
     $objTemplate->picture = $picture;
     // Provide an ID for single lightbox images in HTML5 (see #3742)
     if ($strLightboxId === null && $arrItem['fullsize']) {
         $strLightboxId = 'lightbox[' . substr(md5($objTemplate->getName() . '_' . $arrItem['id']), 0, 6) . ']';
     }
     // Float image
     if ($arrItem['floating'] != '') {
         $objTemplate->floatClass = ' float_' . $arrItem['floating'];
     }
     // Do not override the "href" key (see #6468)
     $strHrefKey = $objTemplate->href != '' ? 'imageHref' : 'href';
     // Image link
     if ($arrItem['imageUrl'] != '' && TL_MODE == 'FE') {
         $objTemplate->{$strHrefKey} = $arrItem['imageUrl'];
         $objTemplate->attributes = '';
         if ($arrItem['fullsize']) {
             // Open images in the lightbox
             if (preg_match('/\\.(jpe?g|gif|png)$/', $arrItem['imageUrl'])) {
                 // Do not add the TL_FILES_URL to external URLs (see #4923)
                 if (strncmp($arrItem['imageUrl'], 'http://', 7) !== 0 && strncmp($arrItem['imageUrl'], 'https://', 8) !== 0) {
                     $objTemplate->{$strHrefKey} = TL_FILES_URL . \System::urlEncode($arrItem['imageUrl']);
                 }
                 $objTemplate->attributes = ' data-lightbox="' . substr($strLightboxId, 9, -1) . '"';
             } else {
                 $objTemplate->attributes = ' target="_blank"';
             }
         }
     } elseif ($arrItem['fullsize'] && TL_MODE == 'FE') {
         $objTemplate->{$strHrefKey} = TL_FILES_URL . \System::urlEncode($arrItem['singleSRC']);
         $objTemplate->attributes = ' data-lightbox="' . substr($strLightboxId, 9, -1) . '"';
     }
     // Do not urlEncode() here because getImage() already does (see #3817)
     $objTemplate->src = TL_FILES_URL . $src;
     $objTemplate->alt = specialchars($arrItem['alt']);
     $objTemplate->title = specialchars($arrItem['title']);
     $objTemplate->linkTitle = $objTemplate->title;
     $objTemplate->fullsize = $arrItem['fullsize'] ? true : false;
     $objTemplate->addBefore = $arrItem['floating'] != 'below';
     $objTemplate->margin = static::generateMargin($arrMargin);
     $objTemplate->caption = $arrItem['caption'];
     $objTemplate->singleSRC = $arrItem['singleSRC'];
     $objTemplate->addImage = true;
 }