- <?php
- /**
-  * Contao Open Source CMS
-  *
-  * Copyright (c) 2005-2015 Leo Feyer
-  *
-  * @package   SgReferences
-  * @author    Sg-Medien GmbH <info@sg-medien.com>
-  * @license   EULA
-  * @copyright Sg-Medien GmbH 2017
-  */
- /**
-  * Set custom namespace
-  */
- namespace SgM;
- use Contao\StringUtil;
- /**
-  * Class SgModuleReferencesList
-  *
-  * Frontend module "references list".
-  *
-  * @package   SgReferences
-  * @author    Sg-Medien GmbH <info@sg-medien.com>
-  * @copyright Sg-Medien GmbH 2017
-  */
- class SgModuleReferencesList extends \SgModuleReferences
- {
-     /**
-      * Template
-      * @var string
-      */
-     protected $strTemplate = 'mod_references_list';
-     /**
-      * Display a wildcard in the backend
-      * @return string
-      */
-     public function generate()
-     {
-         if (TL_MODE == 'BE') {
-             $objTemplate = new \BackendTemplate('be_wildcard');
-             $objTemplate->wildcard = '### ' . utf8_strtoupper($GLOBALS['TL_LANG']['FMD']['references_list'][0]) . ' ###';
-             $objTemplate->title = $this->headline;
-             $objTemplate->id = $this->id;
-             $objTemplate->link = $this->name;
-             $objTemplate->href = 'contao/main.php?do=themes&table=tl_module&act=edit&id=' . $this->id;
-             return $objTemplate->parse();
-         }
-         $this->reference_categories = deserialize($this->reference_categories);
-         // return if there are no reference categories
-         if (!is_array($this->reference_categories) || empty($this->reference_categories)) {
-             return '';
-         }
-         $file = \Input::get('file', true);
-         $fid = \Input::get('fid', true);
-         $ffid = \Input::get('ffid', true);
-         // send the file to the browser and do not send a 404 header
-         if ($file != '' AND is_numeric($fid) AND is_numeric($ffid)) {
-             $objItem = \SgReferencesModel::findByParentAndIdOrAlias($ffid, $this->reference_categories);
-             if ($objItem !== null) {
-                 if ($objItem->useDownloads AND $objItem->multiDownloadsSRC != '') {
-                     $objFile = \FilesModel::findByPk($fid);
-                     if ($file == $objFile->path) {
-                         \Controller::sendFileToBrowser($file);
-                     }
-                 }
-             }
-         }
-         return parent::generate();
-     }
-     /**
-      * Generate the module
-      */
-     protected function compile()
-     {
-         global $objPage;
-         $strRequest = ampersand(\Environment::get('request'), true);
-         $arrJumpTo = array();
-         $arrSqlFilter = array();
-         $arrSqlOptions = array();
-         // keyword filter
-         $curKeywords = \Input::get('keywords', true);
-         if ($curKeywords AND !empty($curKeywords)) {
-             $arrSqlFilter['keywords'] = array
-             (
-                 'sql' => '(%t.reference_headline LIKE ? OR %t.text LIKE ?)',
-                 'values' => array
-                 (
-                     '%' . $curKeywords . '%',
-                     '%' . $curKeywords . '%'
-                 )
-             );
-         }
-         // sort
-         $curSort = \Input::get('sort', true);
-         $curDir = \Input::get('dir', true);
-         $arrAvailableSort = array('reference');
-         if ($curSort AND !empty($curSort) AND in_array($curSort, $arrAvailableSort)) {
-             $field = $curSort;
-             if ($curSort == 'reference') {
-                 $field = 'reference_headline';
-             }
-             $arrSqlOptions['order'] = '%t.' . $field;
-             if (isset($arrSqlOptions['order']) AND !empty($arrSqlOptions['order'])) {
-                 if ($curDir AND $curDir == 'desc') {
-                     $arrSqlOptions['order'] .= ' DESC';
-                 }
-             }
-         } else {
-             $arrSqlOptions['order'] = '%t.sorting ASC';
-         }
-         $offset = intval($this->skipFirst);
-         $limit = null;
-         // maximum number of items
-         if ($this->numberOfItems > 0) {
-             $limit = $this->numberOfItems;
-         }
-         // get the total number of items
-         $intTotal = \SgReferencesModel::countAllOrByPids($this->reference_categories, $arrSqlFilter, $arrSqlOptions);
-         $total = $intTotal >= 1 ? $intTotal - $offset : 0;
-         // split the results
-         if ($total > 0 && $this->perPage > 0 && (!isset($limit) || $this->numberOfItems > $this->perPage)) {
-             // adjust the overall limit
-             if (isset($limit)) {
-                 $total = min($limit, $total);
-             }
-             // get the current page
-             $id = 'page_r' . $this->id;
-             $page = \Input::get($id) ?: 1;
-             // do not index or cache the page if the page number is outside the range
-             if ($page < 1 || $page > max(ceil($total / $this->perPage), 1)) {
-                 $objPage->noSearch = 1;
-                 $objPage->cache = 0;
-                 // send a 404 header
-                 header('HTTP/1.1 404 Not Found');
-                 return;
-             }
-             // set limit and offset
-             $limit = $this->perPage;
-             $offset += (max($page, 1) - 1) * $this->perPage;
-             $skip = intval($this->skipFirst);
-             // overall limit
-             if ($offset + $limit > $total + $skip) {
-                 $limit = $total + $skip - $offset;
-             }
-             // add the pagination menu
-             $objPagination = new \Pagination($total, $this->perPage, \Config::get('maxPaginationLinks'), $id);
-             $this->Template->pagination = $objPagination->generate("\n  ");
-         }
-         // get the items
-         if (isset($limit)) {
-             $objItems = \SgReferencesModel::findAllOrByPids($this->reference_categories, $limit, $offset, $arrSqlFilter, $arrSqlOptions);
-         } else {
-             $objItems = \SgReferencesModel::findAllOrByPids($this->reference_categories, 0, $offset, $arrSqlFilter, $arrSqlOptions);
-         }
-         // add the items
-         $items = array();
-         if ($objItems !== null) {
-             while ($objItems->next()) {
-                 if (($objTarget = $objItems->getRelated('pid')) === null) {
-                     continue;
-                 }
-                 $jumpTo = intval($objTarget->jumpTo);
-                 $href = false;
-                 if ($jumpTo > 0) {
-                     $strUrl = $strRequest;
-                     if (!isset($arrJumpTo[$objTarget->jumpTo])) {
-                         $objJumpTo = $objTarget->getRelated('jumpTo')->loadDetails();
-                         if ($objJumpTo !== null) {
-                             $arrJumpTo[$objTarget->jumpTo] = $this->generateFrontendUrl($objJumpTo->row(), ((\Config::get('useAutoItem') && !\Config::get('disableAlias')) ? '/%s' : '/items/%s'));
-                         } else {
-                             $arrJumpTo[$objTarget->jumpTo] = $strUrl;
-                         }
-                     }
-                     $strUrl = $arrJumpTo[$objTarget->jumpTo];
-                     $strAlias = ($objItems->alias != '' && !\Config::get('disableAlias')) ? $objItems->alias : $objItems->id;
-                     $href = sprintf($strUrl, $strAlias);
-                 }
-                 // add customer logo
-                 $customerLogo = false;
-                 if ($objItems->addCustomerLogo AND $objItems->logoSRC != '') {
-                     $objModel = \FilesModel::findByUuid($objItems->logoSRC);
-                     if ($objModel !== null) {
-                         $objFile = new \File($objModel->path, true);
-                         if (!$objFile->isImage) {
-                             continue;
-                         }
-                         $arrMeta = $this->getMetaData($objModel->meta, $objPage->language);
-                         if (!empty($arrMeta)) {
-                             if ($objPage->rootFallbackLanguage !== null) {
-                                 $arrMeta = $this->getMetaData($objModel->meta, $objPage->rootFallbackLanguage);
-                             }
-                         }
-                         // use the file name as title if none is given
-                         if (empty($arrMeta['title'])) {
-                             $arrMeta['title'] = StringUtil::specialchars($objFile->basename);
-                         }
-                         // add the customer logo
-                         $objLogo = new \stdClass();
-                         $this->addImageToTemplate($objLogo, array
-                         (
-                             'id' => $objModel->id,
-                             'uuid' => $objModel->uuid,
-                             'name' => $objFile->basename,
-                             'singleSRC' => $objModel->path,
-                             'alt' => $arrMeta['title'],
-                             'imageUrl' => ($arrMeta['link'] ?? null),
-                             'caption' => ($arrMeta['caption'] ?? null),
-                             'size' => $this->imgSize
-                         ), floor(\Config::get('maxImageWidth')));
-                         $customerLogo = $objLogo;
-                     }
-                 }
-                 // add image
-                 $image = false;
-                 if ($objItems->addImage AND $objItems->singleSRC != '') {
-                     $objModel = \FilesModel::findByUuid($objItems->singleSRC);
-                     if ($objModel !== null) {
-                         $objFile = new \File($objModel->path, true);
-                         if (!$objFile->isImage) {
-                             continue;
-                         }
-                         $arrMeta = $this->getMetaData($objModel->meta, $objPage->language);
-                         if (!empty($arrMeta)) {
-                             if ($objPage->rootFallbackLanguage !== null) {
-                                 $arrMeta = $this->getMetaData($objModel->meta, $objPage->rootFallbackLanguage);
-                             }
-                         }
-                         // use the file name as title if none is given
-                         if (empty($arrMeta['title'])) {
-                             $arrMeta['title'] = StringUtil::specialchars($objFile->basename);
-                         }
-                         // add the image
-                         $objImg = new \stdClass();
-                         $this->addImageToTemplate($objImg, array
-                         (
-                             'id' => $objModel->id,
-                             'uuid' => $objModel->uuid,
-                             'name' => $objFile->basename,
-                             'singleSRC' => $objModel->path,
-                             'alt' => $arrMeta['title'],
-                             'imageUrl' => ($arrMeta['link'] ?? null),
-                             'caption' => ($arrMeta['caption'] ?? null),
-                             'size' => $this->imgSize
-                         ), floor(\Config::get('maxImageWidth')));
-                         $image = $objImg;
-                     }
-                 }
-                 // add gallery
-                 $gallery = false;
-                 if ($objItems->useImages AND $objItems->multiImagesSRC != '') {
-                     $objItems->multiImagesSRC = deserialize($objItems->multiImagesSRC);
-                     if (is_array($objItems->multiImagesSRC) && !empty($objItems->multiImagesSRC)) {
-                         $images = [];
-                         $objFiles = \FilesModel::findMultipleByUuids($objItems->multiImagesSRC);
-                         if ($objFiles !== null) {
-                             // Get all images
-                             while ($objFiles->next()) {
-                                 // Continue if the files has been processed or does not exist
-                                 if (isset($images[$objFiles->path]) || !file_exists(TL_ROOT . '/' . $objFiles->path)) {
-                                     continue;
-                                 }
-                                 // Single files
-                                 if ($objFiles->type == 'file') {
-                                     $objFile = new \File($objFiles->path, true);
-                                     if (!$objFile->isImage) {
-                                         continue;
-                                     }
-                                     $arrMeta = $this->getMetaData($objFiles->meta, $objPage->language);
-                                     if (!empty($arrMeta)) {
-                                         if ($objPage->rootFallbackLanguage !== null) {
-                                             $arrMeta = $this->getMetaData($objFiles->meta, $objPage->rootFallbackLanguage);
-                                         }
-                                     }
-                                     // use the file name as title if none is given
-                                     if (empty($arrMeta['title'])) {
-                                         $arrMeta['title'] = StringUtil::specialchars($objFile->basename);
-                                     }
-                                     // add the image
-                                     $objImg = new \stdClass();
-                                     $objImg->uuid = $objFiles->uuid;
-                                     $this->addImageToTemplate($objImg, array
-                                     (
-                                         'id' => $objFiles->id,
-                                         'uuid' => $objFiles->uuid,
-                                         'name' => $objFile->basename,
-                                         'singleSRC' => $objFiles->path,
-                                         'alt' => $arrMeta['title'],
-                                         'imageUrl' => ($arrMeta['link'] ?? null),
-                                         'caption' => ($arrMeta['caption'] ?? null),
-                                         'size' => $this->imgSize
-                                     ), floor(\Config::get('maxImageWidth')));
-                                     $images[] = $objImg;
-                                 } // Folders
-                                 else {
-                                     $objSubfiles = \FilesModel::findByPid($objFiles->uuid);
-                                     if ($objSubfiles === null) {
-                                         continue;
-                                     }
-                                     while ($objSubfiles->next()) {
-                                         // Skip subfolders
-                                         if ($objSubfiles->type == 'folder') {
-                                             continue;
-                                         }
-                                         $objFile = new \File($objSubfiles->path, true);
-                                         if (!$objFile->isImage) {
-                                             continue;
-                                         }
-                                         $arrMeta = $this->getMetaData($objSubfiles->meta, $objPage->language);
-                                         if (!empty($arrMeta)) {
-                                             if ($objPage->rootFallbackLanguage !== null) {
-                                                 $arrMeta = $this->getMetaData($objSubfiles->meta, $objPage->rootFallbackLanguage);
-                                             }
-                                         }
-                                         // use the file name as title if none is given
-                                         if (empty($arrMeta['title'])) {
-                                             $arrMeta['title'] = StringUtil::specialchars($objFile->basename);
-                                         }
-                                         // add the image
-                                         $objImg = new \stdClass();
-                                         $objImg->uuid = $objSubfiles->uuid;
-                                         $this->addImageToTemplate($objImg, array
-                                         (
-                                             'id' => $objSubfiles->id,
-                                             'uuid' => $objSubfiles->uuid,
-                                             'name' => $objFile->basename,
-                                             'singleSRC' => $objSubfiles->path,
-                                             'alt' => $arrMeta['title'],
-                                             'imageUrl' => ($arrMeta['link'] ?? null),
-                                             'caption' => ($arrMeta['caption'] ?? null),
-                                             'size' => $this->imgSize
-                                         ), floor(\Config::get('maxImageWidth')));
-                                         $images[] = $objImg;
-                                     }
-                                 }
-                             }
-                             if (!empty($images)) {
-                                 if ($objItems->orderImagesSRC != '') {
-                                     $tmp = deserialize($objItems->orderImagesSRC);
-                                     if (!empty($tmp) && is_array($tmp)) {
-                                         // Remove all values
-                                         $arrOrder = array_map(function () {
-                                         }, array_flip($tmp));
-                                         // Move the matching elements to their position in $arrOrder
-                                         foreach ($images as $k => $v) {
-                                             if (array_key_exists($v->uuid, $arrOrder)) {
-                                                 $arrOrder[$v->uuid] = $v;
-                                                 unset($images[$k]);
-                                             }
-                                         }
-                                         // Append the left-over images at the end
-                                         if (!empty($images)) {
-                                             $arrOrder = array_merge($arrOrder, array_values($images));
-                                         }
-                                         // Remove empty (unreplaced) entries
-                                         $images = array_values(array_filter($arrOrder));
-                                         unset($arrOrder);
-                                     }
-                                 }
-                                 $gallery = array_values($images);
-                             }
-                         }
-                     }
-                 }
-                 // add downloads
-                 $downloads = false;
-                 if ($objItems->useDownloads AND $objItems->multiDownloadsSRC != '') {
-                     $objItems->multiDownloadsSRC = deserialize($objItems->multiDownloadsSRC);
-                     if (is_array($objItems->multiDownloadsSRC) && !empty($objItems->multiDownloadsSRC)) {
-                         $dls = [];
-                         $objFiles = \FilesModel::findMultipleByUuids($objItems->multiDownloadsSRC);
-                         if ($objFiles !== null) {
-                             // Get all downloads
-                             while ($objFiles->next()) {
-                                 // Continue if the files has been processed or does not exist
-                                 if (isset($dls[$objFiles->path]) || !file_exists(TL_ROOT . '/' . $objFiles->path)) {
-                                     continue;
-                                 }
-                                 // Single files
-                                 if ($objFiles->type == 'file') {
-                                     if ($objFiles === null) {
-                                         if (!\Validator::isUuid($objFiles->uuid)) {
-                                             return '<p class="error">' . $GLOBALS['TL_LANG']['ERR']['version2format'] . '</p>';
-                                         }
-                                     }
-                                     $allowedDownload = trimsplit(',', strtolower(\Config::get('allowedDownload')));
-                                     if (in_array($objFiles->extension, $allowedDownload)) {
-                                         $objFile = new \File($objFiles->path, true);
-                                         $strHref = $strRequest;
-                                         $strHref = preg_replace('/(\&(amp;)?|\?)(file)=(.+?)?(\&(amp;)?|$)/', '$1', $strHref);
-                                         $strHref = preg_replace('/(\&(amp;)?|\?)(fid)=(.+?)?(\&(amp;)?|$)/', '$1', $strHref);
-                                         $strHref = preg_replace('/(\&(amp;)?|\?)(ffid)=(.+?)?(\&(amp;)?|$)/', '$1', $strHref);
-                                         $strHref .= ((\Config::get('disableAlias') || strpos($strHref, '?') !== false) ? '&' : '?') . 'file=' . \System::urlEncode($objFile->value) . '&fid=' . \System::urlEncode($objFiles->id) . '&ffid=' . \System::urlEncode($objItems->id);
-                                         $dls[] = array
-                                         (
-                                             'link' => StringUtil::specialchars($objFile->basename),
-                                             'title' => StringUtil::specialchars(sprintf($GLOBALS['TL_LANG']['MSC']['download'], $objFile->basename)),
-                                             'href' => $strHref,
-                                             'filesize' => $this->getReadableSize($objFile->filesize, 1),
-                                             'icon' => TL_ASSETS_URL . 'assets/contao/images/' . $objFile->icon,
-                                             'mime' => $objFile->mime,
-                                             'extension' => $objFile->extension,
-                                             'path' => $objFile->dirname,
-                                             'uuid' => $objFiles->uuid,
-                                         );
-                                     }
-                                 } // Folders
-                                 else {
-                                     $objSubfiles = \FilesModel::findByPid($objFiles->uuid);
-                                     if ($objSubfiles === null) {
-                                         continue;
-                                     }
-                                     while ($objSubfiles->next()) {
-                                         // Skip subfolders
-                                         if ($objSubfiles->type == 'folder') {
-                                             continue;
-                                         }
-                                         if ($objSubfiles === null) {
-                                             if (!\Validator::isUuid($objSubfiles->uuid)) {
-                                                 return '<p class="error">' . $GLOBALS['TL_LANG']['ERR']['version2format'] . '</p>';
-                                             }
-                                         }
-                                         $allowedDownload = trimsplit(',', strtolower(\Config::get('allowedDownload')));
-                                         if (in_array($objSubfiles->extension, $allowedDownload)) {
-                                             $objFile = new \File($objSubfiles->path, true);
-                                             $strHref = $strRequest;
-                                             $strHref = preg_replace('/(\&(amp;)?|\?)(file)=(.+?)?(\&(amp;)?|$)/', '$1', $strHref);
-                                             $strHref = preg_replace('/(\&(amp;)?|\?)(fid)=(.+?)?(\&(amp;)?|$)/', '$1', $strHref);
-                                             $strHref = preg_replace('/(\&(amp;)?|\?)(ffid)=(.+?)?(\&(amp;)?|$)/', '$1', $strHref);
-                                             $strHref .= ((\Config::get('disableAlias') || strpos($strHref, '?') !== false) ? '&' : '?') . 'file=' . \System::urlEncode($objFile->value) . '&fid=' . \System::urlEncode($objSubfiles->id) . '&ffid=' . \System::urlEncode($objItems->id);
-                                             $dls[] = array
-                                             (
-                                                 'link' => StringUtil::specialchars($objFile->basename),
-                                                 'title' => StringUtil::specialchars(sprintf($GLOBALS['TL_LANG']['MSC']['download'], $objFile->basename)),
-                                                 'href' => $strHref,
-                                                 'filesize' => $this->getReadableSize($objFile->filesize, 1),
-                                                 'icon' => TL_ASSETS_URL . 'assets/contao/images/' . $objFile->icon,
-                                                 'mime' => $objFile->mime,
-                                                 'extension' => $objFile->extension,
-                                                 'path' => $objFile->dirname,
-                                                 'uuid' => $objSubfiles->uuid,
-                                             );
-                                         }
-                                     }
-                                 }
-                             }
-                             if (!empty($dls)) {
-                                 if ($objItems->orderDownloadsSRC != '') {
-                                     $tmp = deserialize($objItems->orderDownloadsSRC);
-                                     if (!empty($tmp) && is_array($tmp)) {
-                                         // Remove all values
-                                         $arrOrder = array_map(function () {
-                                         }, array_flip($tmp));
-                                         // Move the matching elements to their position in $arrOrder
-                                         foreach ($dls as $k => $v) {
-                                             if (array_key_exists($v['uuid'], $arrOrder)) {
-                                                 $arrOrder[$v['uuid']] = $v;
-                                                 unset($dls[$k]);
-                                             }
-                                         }
-                                         // Append the left-over downloads at the end
-                                         if (!empty($dls)) {
-                                             $arrOrder = array_merge($arrOrder, array_values($dls));
-                                         }
-                                         // Remove empty (unreplaced) entries
-                                         $dls = array_values(array_filter($arrOrder));
-                                         unset($arrOrder);
-                                     }
-                                 }
-                                 $downloads = array_values($dls);
-                             }
-                         }
-                     }
-                 }
-                 // clean service list items
-                 $arrListItems = array();
-                 $arrListItemsTemp = deserialize($objItems->service_listitems);
-                 if (is_array($arrListItemsTemp)) {
-                     for ($i = 0, $c = count($arrListItemsTemp); $i < $c; $i++) {
-                         if (trim($arrListItemsTemp[$i]) !== '') {
-                             $arrListItems[] = $arrListItemsTemp[$i];
-                         }
-                     }
-                 }
-                 $objItems->service_listitems = $arrListItems;
-                 // add item
-                 $item = $objItems->row();
-                 $item['customerLogo'] = $customerLogo;
-                 $item['service_listitems'] = $objItems->service_listitems;
-                 $item['href'] = $href;
-                 $item['image'] = $image;
-                 $item['gallery'] = $gallery;
-                 $item['downloads'] = $downloads;
-                 // add item
-                 $items[] = $item;
-             }
-         }
-         $arrFilter = array();
-         // build filter href
-         $filterHref = $strRequest;
-         $filterHref = preg_replace('/(\&(amp;))+$/', '', preg_replace('/(\&(amp;)?|\?)(page_r[0-9]+)=(.+?)?(\&(amp;)?|$)/', '$1', $filterHref));
-         // build sort array
-         $arrSort = array();
-         if (is_array($arrAvailableSort) AND count($arrAvailableSort)) {
-             foreach ($arrAvailableSort AS $sort) {
-                 $arrSort[$sort] = array
-                 (
-                     'isActive' => $curSort == $sort ? true : false,
-                     'activeDir' => $curSort == $sort ? ($curDir == 'desc' ? 'desc' : 'asc') : false,
-                     'hrefAsc' => \SgReferences::addToUrl('sort=' . \System::urlEncode($sort), array($id, 'sort', 'dir')),
-                     'hrefDesc' => \SgReferences::addToUrl('sort=' . \System::urlEncode($sort) . '&' . 'dir=desc', array($id, 'sort'))
-                 );
-             }
-         }
-         // build action url
-         $action = $filterHref;
-         $action = preg_replace('/\?.+?$/', '', $action);
-         // add template vars
-         $this->Template->sorts = $arrSort;
-         $this->Template->filter = $arrFilter;
-         $this->Template->action = $action;
-         $this->Template->keywords = $curKeywords;
-         $this->Template->count = $total;
-         $this->Template->items = $items;
-     }
- }
-