The class resizes images and prepares data for the element. Usage: $picture = new Picture(new File('example.jpg')); $data = $picture ->setImportantPart(array('x'=>10, 'y'=>10, 'width'=>100, 'height'=>100)) ->setImageSize(ImageSizeModel::findByPk(1)) ->setImageSizeItems(ImageSizeItemModel::findVisibleByPid(1, array('order'=>'sorting ASC'))) ->getTemplateData() ; Shortcut $data = Picture::create('example.jpg', 1)->getTemplateData(); $data = Picture::create('example.jpg', array(100, 100, 'crop'))->getTemplateData();
사용 중단: Deprecated since Contao 4.3, to be removed in Contao 5.0. Use the contao.image.picture_factory service instead.
예제 #1
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;
 }
 /**
  * Recursively compile the navigation menu and return it as HTML string
  * @param integer
  * @param integer
  * @param string
  * @param string
  * @return string
  */
 protected function renderNavigation($pid, $level = 1, $host = null, $language = null)
 {
     // Get all active subpages
     $objSubpages = \PageModel::findPublishedSubpagesWithoutGuestsByPid($pid, $this->showHidden, $this instanceof \ModuleSitemap);
     if ($objSubpages === null) {
         return '';
     }
     $items = array();
     $groups = array();
     // Get all groups of the current front end user
     if (FE_USER_LOGGED_IN) {
         $this->import('FrontendUser', 'User');
         $groups = $this->User->groups;
     }
     // Layout template fallback
     if ($this->navigationTpl == '') {
         $this->navigationTpl = 'nav_default';
     }
     $objTemplate = new \FrontendTemplate($this->navigationTpl);
     $objTemplate->pid = $pid;
     $objTemplate->type = get_class($this);
     $objTemplate->cssID = $this->cssID;
     // see #4897
     $objTemplate->level = 'level_' . $level++;
     // Get page object
     global $objPage;
     // Browse subpages
     while ($objSubpages->next()) {
         // Skip hidden sitemap pages
         if ($this instanceof \ModuleSitemap && $objSubpages->sitemap == 'map_never') {
             continue;
         }
         $subitems = '';
         $_groups = deserialize($objSubpages->groups);
         // Override the domain (see #3765)
         if ($host !== null) {
             $objSubpages->domain = $host;
         }
         // Do not show protected pages unless a back end or front end user is logged in
         if (!$objSubpages->protected || BE_USER_LOGGED_IN || is_array($_groups) && count(array_intersect($_groups, $groups)) || $this->showProtected || $this instanceof \ModuleSitemap && $objSubpages->sitemap == 'map_always') {
             // Check whether there will be subpages
             if ($objSubpages->subpages > 0 && (!$this->showLevel || $this->showLevel >= $level || !$this->hardLimit && ($objPage->id == $objSubpages->id || in_array($objPage->id, $this->Database->getChildRecords($objSubpages->id, 'tl_page'))))) {
                 $subitems = $this->renderNavigation($objSubpages->id, $level, $host, $language);
             }
             // Get href
             switch ($objSubpages->type) {
                 case 'redirect':
                     $href = $objSubpages->url;
                     if (strncasecmp($href, 'mailto:', 7) === 0) {
                         $href = \String::encodeEmail($href);
                     }
                     break;
                 case 'forward':
                     if ($objSubpages->jumpTo) {
                         $objNext = $objSubpages->getRelated('jumpTo');
                     } else {
                         $objNext = \PageModel::findFirstPublishedRegularByPid($objSubpages->id);
                     }
                     if ($objNext !== null) {
                         // Hide the link if the target page is invisible
                         if (!$objNext->published || $objNext->start != '' && $objNext->start > time() || $objNext->stop != '' && $objNext->stop < time()) {
                             continue 2;
                         }
                         $strForceLang = null;
                         $objNext->loadDetails();
                         // Check the target page language (see #4706)
                         if (\Config::get('addLanguageToUrl')) {
                             $strForceLang = $objNext->language;
                         }
                         $href = $this->generateFrontendUrl($objNext->row(), null, $strForceLang, true);
                         break;
                     }
                     // DO NOT ADD A break; STATEMENT
                 // DO NOT ADD A break; STATEMENT
                 default:
                     if ($objSubpages->domain != '' && $objSubpages->domain != \Environment::get('host')) {
                         $objSubpages->current()->loadDetails();
                     }
                     $href = $this->generateFrontendUrl($objSubpages->row(), null, $language, true);
                     break;
             }
             // Insert navImage
             if ($objSubpages->navImage) {
                 $file = \FilesModel::findByUuid($objSubpages->navImage);
                 if ($file->path) {
                     $objSubpages->navImage = Picture::create($file->path, deserialize($this->imgSize, true))->getTemplateData();
                 }
             }
             $row = $objSubpages->row();
             $trail = in_array($objSubpages->id, $objPage->trail);
             // Active page
             if (($objPage->id == $objSubpages->id || $objSubpages->type == 'forward' && $objPage->id == $objSubpages->jumpTo) && !$this instanceof \ModuleSitemap && $href == \Environment::get('request')) {
                 // Mark active forward pages (see #4822)
                 $strClass = ($objSubpages->type == 'forward' && $objPage->id == $objSubpages->jumpTo ? 'forward' . ($trail ? ' trail' : '') : 'active') . ($subitems != '' ? ' submenu' : '') . ($objSubpages->protected ? ' protected' : '') . ($objSubpages->cssClass != '' ? ' ' . $objSubpages->cssClass : '');
                 $row['isActive'] = true;
                 $row['isTrail'] = false;
             } else {
                 $strClass = ($subitems != '' ? 'submenu' : '') . ($objSubpages->protected ? ' protected' : '') . ($trail ? ' trail' : '') . ($objSubpages->cssClass != '' ? ' ' . $objSubpages->cssClass : '');
                 // Mark pages on the same level (see #2419)
                 if ($objSubpages->pid == $objPage->pid) {
                     $strClass .= ' sibling';
                 }
                 $row['isActive'] = false;
                 $row['isTrail'] = $trail;
             }
             $row['subitems'] = $subitems;
             $row['class'] = trim($strClass);
             $row['title'] = specialchars($objSubpages->title, true);
             $row['pageTitle'] = specialchars($objSubpages->pageTitle, true);
             $row['link'] = $objSubpages->title;
             $row['href'] = $href;
             $row['nofollow'] = strncmp($objSubpages->robots, 'noindex', 7) === 0;
             $row['target'] = '';
             $row['description'] = str_replace(array("\n", "\r"), array(' ', ''), $objSubpages->description);
             // Override the link target
             if ($objSubpages->type == 'redirect' && $objSubpages->target) {
                 $row['target'] = $objPage->outputFormat == 'xhtml' ? ' onclick="return !window.open(this.href)"' : ' target="_blank"';
             }
             $items[] = $row;
         }
     }
     // Add classes first and last
     if (!empty($items)) {
         $last = count($items) - 1;
         $items[0]['class'] = trim($items[0]['class'] . ' first');
         $items[$last]['class'] = trim($items[$last]['class'] . ' last');
     }
     $objTemplate->items = $items;
     return !empty($items) ? $objTemplate->parse() : '';
 }
예제 #3
0
 /**
  * Tests the getTemplateData() method with encoded file names.
  */
 public function testGetTemplateDataUrlEncoded()
 {
     copy(__DIR__ . '/../Fixtures/images/dummy.jpg', self::$rootDir . '/dummy with spaces.jpg');
     $picture = new Picture(new \File('dummy with spaces.jpg'));
     $picture->setImageSize((object) ['width' => 0, 'height' => 0, 'resizeMode' => '', 'zoom' => 0]);
     $pictureData = $picture->getTemplateData();
     $this->assertEquals(200, $pictureData['img']['width']);
     $this->assertEquals(200, $pictureData['img']['height']);
     $this->assertEquals('dummy%20with%20spaces.jpg', $pictureData['img']['src']);
     $this->assertEquals('dummy%20with%20spaces.jpg', $pictureData['img']['srcset']);
     $this->assertEquals([], $pictureData['sources']);
 }
예제 #4
0
 /**
  * Tests the getTemplateData() method with an old resize mode.
  */
 public function testGetTemplateDataOldResizeMode()
 {
     $picture = new Picture(new \File('dummy.jpg'));
     $picture->setImageSize((object) ['width' => 100, 'height' => 100, 'resizeMode' => 'center_center', 'zoom' => 0]);
     $pictureData = $picture->getTemplateData();
     $this->assertEquals(100, $pictureData['img']['width']);
     $this->assertEquals(100, $pictureData['img']['height']);
     $this->assertEquals($pictureData['img']['src'], $pictureData['img']['srcset'], 'Attributes src and srcset should be equal');
     $this->assertEquals([], $pictureData['sources']);
 }