Some of the methods have been made static in Contao 3 and can be used in non-object context as well. Usage: echo Controller::getTheme(); Inside a controller: public function generate() { return $this->getArticle(2); }
Inheritance: extends System
Exemple #1
0
 public function export(\Contao\DC_Table $dc)
 {
     $database = \Contao\Database::getInstance();
     $stage_id = $database->query("SELECT s.id FROM tl_beachcup_stage AS s WHERE s.start_date >= UNIX_TIMESTAMP() ORDER BY s.start_date ASC LIMIT 1")->fetchAssoc()["id"];
     $data = $database->query("select tl_beachcup_registration.id as ANMELDUNG_ID, tl_beachcup_tournament.name_de AS TURNIER, DATE_FORMAT(from_unixtime(tl_beachcup_registration.tstamp), '%d.%m.%Y') as DATUM_ANMELDUNG,\n                                    p1.surname as NACHNAME_1, p1.name as VORNAME_1, p1.tax_number as STEUER_NR_1, DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL p1.birth_date SECOND), '%d.%m.%Y') as GEB_DATUM_1, p1.birth_place as GEB_ORT_1, p1.gender as GESCHLECHT_1, p1.address as ADRESSE_1, p1.zip_code as PLZ_1, p1.city as ORT_1, p1.country as LAND_1, p1.email as EMAIL_1, p1.phone_number as TEL_1, p1.shirt_size as SHIRT_1, p1.has_shirt as SHIRT_ERHALTEN_1, p1.is_fipav as FIPAV_1, p1level.description_de as SPIELER_LEVEL_1, p1.has_medical_certificate as AERZTL_ZEUGNIS_1, p1.is_confirmed as EIGENERKLAERUNG_1,\n                                    p2.surname as NACHNAME_2, p2.name as VORNAME_2, p2.tax_number as STEUER_NR_2, DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL p2.birth_date SECOND), '%d.%m.%Y') as GEB_DATUM_2, p2.birth_place as GEB_ORT_2, p2.gender as GESCHLECHT_2, p2.address as ADRESSE_2, p2.zip_code as PLZ_2, p2.city as ORT_2, p2.country as LAND_2, p2.email as EMAIL_2, p2.phone_number as TEL_2, p2.shirt_size as SHIRT_2, p2.has_shirt as SHIRT_ERHALTEN_2, p2.is_fipav as FIPAV_2, p2level.description_de as SPIELER_LEVEL_2, p2.has_medical_certificate as AERZTL_ZEUGNIS_2, p2.is_confirmed as EIGENERKLAERUNG_2,\n                                    tl_beachcup_registration_state.code as STATUS_ANMELDUNG\n                                    from tl_beachcup_registration\n                                    join tl_beachcup_team on tl_beachcup_team.id = tl_beachcup_registration.team_id\n                                    join tl_beachcup_player p1 on p1.id =  tl_beachcup_team.player_1\n                                    join tl_beachcup_player_level p1level on p1level.id = p1.player_level\n                                    join tl_beachcup_player p2 on p2.id =  tl_beachcup_team.player_2\n                                    join tl_beachcup_player_level p2level on p2level.id = p2.player_level\n                                    join tl_beachcup_tournament on tl_beachcup_tournament.id = tl_beachcup_registration.tournament_id\n                                    join tl_beachcup_registration_state on tl_beachcup_registration_state.id = tl_beachcup_registration.state_id\n                                    join tl_beachcup_stage on tl_beachcup_stage.id = tl_beachcup_tournament.stage_id\n                                    where tl_beachcup_stage.id = {$stage_id} and tl_beachcup_registration_state.code != 'REJECTED'\n                                    order by tl_beachcup_tournament.date, tl_beachcup_tournament.name_de, tl_beachcup_registration.tstamp;")->fetchAllAssoc();
     if (count($data) > 0) {
         $headers = array();
         foreach ($data[0] as $key => $value) {
             $headers[] = $key;
         }
         $file = fopen("php://memory", "w");
         fputcsv($file, $headers, ";");
         foreach ($data as $record) {
             fputcsv($file, $record, ";");
         }
         fseek($file, 0);
         header('Content-Encoding: iso-8859-1');
         header('Content-Type: application/csv; charset=iso-8859-1');
         header('Content-Disposition: attachement; filename="Anmeldungen.csv";');
         echo "";
         fpassthru($file);
         exit;
     }
     \Contao\Controller::redirect('contao/main.php?do=registration');
 }
 /**
  * Gets the label for a language, optionally replacing insert tags.
  *
  * @param string $language
  * @param bool   $replaceInsertTags
  *
  * @return string
  */
 public function get($language, $replaceInsertTags = true)
 {
     $language = strtolower($language);
     if (empty($this->map[$language])) {
         return strtoupper($language);
     }
     $value = $this->map[$language];
     if ($replaceInsertTags) {
         $value = Controller::replaceInsertTags($value);
     }
     return $value;
 }
 /**
  * @param DataContainer $objDC
  * @return DataContainer
  */
 public function translateDCObject(DataContainer $objDC)
 {
     // Get table
     $strTable = $objDC->current()->getTable();
     // Load current data container
     Controller::loadDataContainer($strTable);
     if (count($GLOBALS['TL_DCA'][$strTable]['fields']) > 0) {
         foreach ($GLOBALS['TL_DCA'][$strTable]['fields'] as $field => $arrValues) {
             $objDC->{$field} = $this->translateField($arrValues['inputType'], $objDC->{$field});
         }
     }
     return $objDC;
 }
Exemple #4
0
 /**
  * Initialize the object
  *
  * @param string  $strTable
  * @param integer $intPid
  */
 public function __construct($strTable, $intPid)
 {
     $this->import('Database');
     parent::__construct();
     $this->strTable = $strTable;
     $this->intPid = $intPid;
     // Store the path if it is an editable file
     if ($strTable == 'tl_files') {
         $objFile = \FilesModel::findByPk($intPid);
         if ($objFile !== null && in_array($objFile->extension, \StringUtil::trimsplit(',', strtolower(\Config::get('editableFiles'))))) {
             $this->strPath = $objFile->path;
         }
     }
 }
 /**
  * @param $strTable
  * @return array
  */
 protected function getHelpwizardReferencesBy($strTable)
 {
     $arrReferences = array();
     Controller::loadLanguageFile($strTable);
     Controller::loadDataContainer($strTable);
     if (isset($GLOBALS['TL_DCA'][$strTable]['fields']) && is_array($GLOBALS['TL_DCA'][$strTable]['fields'])) {
         foreach ($GLOBALS['TL_DCA'][$strTable]['fields'] as $strField => $arrValues) {
             $strLabel = $strField;
             if (isset($arrValues['label'][0]) && strlen($arrValues['label'][0])) {
                 $strLabel = $arrValues['label'][0];
             }
             $arrReferences[] = array(sprintf('{{%s::%s|%s}}', 'accountmail', $strField, 'refresh'), sprintf($GLOBALS['TL_LANG']['MSC']['helpwizard_insert_tag'], $strLabel));
         }
     }
     return $arrReferences;
 }
 /**
  * @inheritdoc
  *
  * @throws \InvalidArgumentException
  */
 protected function doSwitchView($id)
 {
     list($table, $id) = explode('.', $id);
     $url = Url::removeQueryString(['switchLanguage']);
     switch ($table) {
         case 'tl_article':
             $url = Url::addQueryString('id=' . $id, $url);
             break;
         case 'tl_page':
             Session::getInstance()->set('tl_page_node', (int) $id);
             break;
         default:
             throw new \InvalidArgumentException(sprintf('Table "%s" is not supported', $table));
     }
     Controller::redirect($url);
 }
 /**
  * Generate the module
  *
  * @return string
  */
 public function run()
 {
     $GLOBALS['TL_CSS'][] = 'system/modules/vimeo_api/assets/backend.min.css';
     $elementsData = $this->getContentElements();
     $template = new BackendTemplate('be_vimeo_rebuilder');
     $template->action = ampersand(Environment::get('request'));
     $template->isActive = $this->isActive();
     $template->elementsCount = count($elementsData);
     $template->canRun = true;
     // Add the stats data
     if (($stats = static::generateStats()) !== null) {
         foreach ($stats as $k => $v) {
             $template->{$k} = $v;
         }
     }
     // Generate the elements
     if ($this->isActive()) {
         // Redirect to the maintenance module if the rebuilder cannot be run
         if (!$template->canRun) {
             Controller::redirect('contao/main.php?do=maintenance');
         }
         $elements = [];
         foreach ($elementsData as $data) {
             switch ($data['ptable']) {
                 case 'tl_article':
                     $source = $GLOBALS['TL_LANG']['tl_maintenance']['vimeo.tableSourceRef']['article'];
                     $path = [$data['_page'], $data['_article']];
                     break;
                 case 'tl_news':
                     $source = $GLOBALS['TL_LANG']['tl_maintenance']['vimeo.tableSourceRef']['news'];
                     $path = [$data['_archive'], $data['_news']];
                     break;
                 case 'tl_calendar_events':
                     $source = $GLOBALS['TL_LANG']['tl_maintenance']['vimeo.tableSourceRef']['event'];
                     $path = [$data['_calendar'], $data['_event']];
                     break;
                 default:
                     $source = '';
                     $path = [];
             }
             $elements[] = ['type' => $data['type'], 'ref' => $data['type'] === 'vimeo_album' ? $data['vimeo_albumId'] : $data['vimeo_videoId'], 'id' => $data['id'], 'source' => $source, 'path' => $path];
         }
         $template->elements = $elements;
         $template->ajaxAction = $this->ajaxAction;
     }
     return $template->parse();
 }
 /**
  * Initialize the tests handler
  *
  * @param DataContainer|null $dc
  */
 public function initialize(DataContainer $dc = null)
 {
     if ($dc === null) {
         return;
     }
     $this->table = $this->getTableName();
     $this->dc = $dc;
     // Enable or disable the analyzer
     if (isset($_GET[self::$serpParamName])) {
         Input::get(self::$serpParamName) ? static::enable() : static::disable();
         Controller::redirect(str_replace(['&' . self::$serpParamName . '=' . Input::get(self::$serpParamName), '&' . self::$serpTemporaryParamName . '=' . Input::get(self::$serpTemporaryParamName)], '', Environment::get('request')));
     }
     $this->addGlobalOperations();
     if ($this->isEnabled()) {
         $this->initializeEnabled();
     }
 }
 /**
  * Generate the page title with ##title## as placeholder for dynamic title
  *
  * @param PageModel $pageModel
  *
  * @return string
  */
 protected function generatePageTitle(PageModel $pageModel)
 {
     $pageModel->loadDetails();
     $layoutModel = LayoutModel::findByPk($pageModel->layout);
     if ($layoutModel === null) {
         return '##title##';
     }
     $title = $layoutModel->titleTag ?: '{{page::pageTitle}} - {{page::rootPageTitle}}';
     $title = str_replace('{{page::pageTitle}}', '##title##', $title);
     // Fake the global page object
     $GLOBALS['objPage'] = $pageModel;
     // Replace the insert tags
     $title = Controller::replaceInsertTags($title, false);
     // Remove the faked global page object
     unset($GLOBALS['objPage']);
     return $title;
 }
 /**
  * Run the controller and parse the template
  */
 public function run()
 {
     $template = new BackendTemplate('be_main');
     $template->main = '';
     // Ajax request
     if ($_POST && Environment::get('isAjaxRequest')) {
         $this->objAjax = new Ajax(Input::post('action'));
         $this->objAjax->executePreActions();
     }
     $strTable = Input::get('table');
     $strField = Input::get('field');
     // Define the current ID
     define('CURRENT_ID', Input::get('table') ? $this->Session->get('CURRENT_ID') : Input::get('id'));
     Controller::loadDataContainer($strTable);
     $strDriver = 'DC_' . $GLOBALS['TL_DCA'][$strTable]['config']['dataContainer'];
     $objDca = new $strDriver($strTable);
     $objDca->field = $strField;
     // Set the active record
     if ($this->Database->tableExists($strTable)) {
         /** @var Model $strModel $strModel */
         $strModel = Model::getClassFromTable($strTable);
         if (class_exists($strModel)) {
             $objModel = $strModel::findByPk(Input::get('id'));
             if ($objModel !== null) {
                 $objDca->activeRecord = $objModel;
             }
         }
     }
     // AJAX request
     if ($_POST && Environment::get('isAjaxRequest')) {
         $this->objAjax->executePostActions($objDca);
     }
     $partial = new BackendTemplate('be_rte_table_editor');
     $template->isPopup = true;
     $template->main = $partial->parse();
     $template->theme = Backend::getTheme();
     $template->base = Environment::get('base');
     $template->language = $GLOBALS['TL_LANGUAGE'];
     $template->title = specialchars($GLOBALS['TL_LANG']['MSC']['pagepicker']);
     $template->charset = Config::get('characterSet');
     Config::set('debugMode', false);
     $template->output();
 }
 /**
  * Registers callback for given table.
  *
  * @param string   $table
  * @param callable $callback
  */
 public function register($table, callable $callback)
 {
     Controller::loadDataContainer($table);
     $chain = function () use($callback) {
         $args = func_get_args();
         $result = null;
         if (is_callable($this->previous)) {
             $result = $this->executeCallback($this->previous, $args);
         }
         return $this->executeCallback($callback, [$args, $result]);
     };
     if (4 === $GLOBALS['TL_DCA'][$table]['list']['sorting']['mode']) {
         $this->previous = $GLOBALS['TL_DCA'][$table]['list']['sorting']['child_record_callback'];
         $GLOBALS['TL_DCA'][$table]['list']['sorting']['child_record_callback'] = $chain;
     } else {
         $this->previous = $GLOBALS['TL_DCA'][$table]['list']['label']['label_callback'];
         $GLOBALS['TL_DCA'][$table]['list']['label']['label_callback'] = $chain;
     }
 }
Exemple #12
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)
 {
     if (stristr($arrItem['singleSRC'], '.svg') !== FALSE) {
         $size = deserialize($arrItem['size']);
         $size = self::_getSvgSize($arrItem['singleSRC'], $size);
         $arrItem['size'] = serialize($size);
         @parent::addImageToTemplate($objTemplate, $arrItem, $intMaxWidth, $strLightboxId);
         $imgSize = '';
         $imgSize .= ' width="' . $size[0] . '"';
         $imgSize .= ' height="' . $size[1] . '"';
         $objTemplate->imgSize = $imgSize;
         $objTemplate->svgImage = TRUE;
         if ($width > 0 && $height > 0) {
             $objTemplate->width = $imgSize[0];
             $objTemplate->height = $imgSize[1];
         }
     } else {
         parent::addImageToTemplate($objTemplate, $arrItem, $intMaxWidth, $strLightboxId);
     }
 }
 /**
  * @return array
  */
 protected function listAllTranslationFields()
 {
     $arrStructure = array();
     $arrFiles = $this->listDataContainerArrayFiles();
     if (is_array($arrFiles)) {
         foreach ($arrFiles as $strFile) {
             // Load data container
             Controller::loadDataContainer($strFile);
             $arrFields =& $GLOBALS['TL_DCA'][$strFile]['fields'];
             foreach ($arrFields as $strField => $varValue) {
                 switch ($varValue['inputType']) {
                     case 'TranslationInputUnit':
                     case 'TranslationTextArea':
                     case 'TranslationTextField':
                         $arrStructure[$strFile][] = $strField;
                         break;
                 }
             }
         }
     }
     return $arrStructure;
 }
 /**
  * Generate the icons by the given conditions.
  *
  * @param array $row The current record.
  *
  * @return string
  */
 public function generateDeviceConditionConfiguration($row)
 {
     if (!Input::get('do') == 'article' || !Input::get('do') == 'postmanager' || Input::get('task') == 'indexmanager') {
         return;
     }
     $conditions = deserialize($row['device_condition']);
     $allConditions = array('desktop', 'mobile');
     $return = '';
     Controller::loadLanguageFile('default');
     if (!$conditions) {
         foreach ($allConditions as $condition) {
             $return .= Image::getHtml('/system/modules/z_device-condition/assets/icons/' . $condition . '.png', $this->getTranslationForCondition($condition));
         }
     } else {
         foreach ($allConditions as $condition) {
             if (in_array($condition, $conditions)) {
                 $return .= Image::getHtml('/system/modules/z_device-condition/assets/icons/' . $condition . '.png', $this->getTranslationForCondition($condition));
             } else {
                 $return .= Image::getHtml('/system/modules/z_device-condition/assets/icons/disabled/' . $condition . '.png', $this->getTranslationForCondition($condition));
             }
         }
     }
     return $return;
 }
Exemple #15
0
    /**
     * Add a breadcrumb menu to the file tree
     *
     * @param string $strKey
     *
     * @throws AccessDeniedException
     * @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['fn'])) {
            // Check the path (thanks to Arnaud Buchoux)
            if (\Validator::isInsecurePath(\Input::get('fn', true))) {
                throw new \RuntimeException('Insecure path ' . \Input::get('fn', true));
            }
            $objSession->set($strKey, \Input::get('fn', true));
            \Controller::redirect(preg_replace('/(&|\\?)fn=[^&]*/', '', \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[] = \Image::getHtml('filemounts.svg') . ' <a href="' . \Backend::addToUrl('fn=') . '" title="' . \StringUtil::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 ($strPath == $strNode) {
                $arrLinks[] = \Image::getHtml('folderC.svg') . ' ' . $strFolder;
            } else {
                $arrLinks[] = \Image::getHtml('folderC.svg') . ' <a href="' . \Backend::addToUrl('fn=' . $strPath) . '" title="' . \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['selectNode']) . '">' . $strFolder . '</a>';
            }
        }
        // Check whether the node is mounted
        if (!$objUser->hasAccess($strNode, 'filemounts')) {
            $objSession->set($strKey, '');
            throw new AccessDeniedException('Folder ID "' . $strNode . '" is not mounted');
        }
        // 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>';
    }
 public function __construct()
 {
     parent::__construct();
     $this->import('Config');
 }
Exemple #17
0
 /**
  * Generate a front end URL
  *
  * @param string $strParams    An optional string of URL parameters
  * @param string $strForceLang Force a certain language
  *
  * @return string An URL that can be used in the front end
  */
 public function getFrontendUrl($strParams = null, $strForceLang = null)
 {
     return \Controller::generateFrontendUrl($this->row(), $strParams, $strForceLang);
 }
 /**
  * @inheritdoc
  */
 protected function doSwitchView($id)
 {
     Session::getInstance()->set('tl_page_node', (int) $id);
     Controller::redirect(Url::removeQueryString(['switchLanguage']));
 }
 /**
  * Load or create the extract
  *
  * @param string $strTable The table name
  *
  * @throws \Exception If $strTable is empty
  */
 protected function __construct($strTable)
 {
     if ($strTable == '') {
         throw new \Exception('The table name must not be empty');
     }
     parent::__construct();
     $this->strTable = $strTable;
     $strFile = \System::getContainer()->getParameter('kernel.cache_dir') . '/contao/sql/' . $strTable . '.php';
     // Try to load from cache
     if (file_exists($strFile)) {
         include $strFile;
     } else {
         $this->createExtract();
     }
 }
Exemple #20
0
 /**
  * Return an object property
  *
  * @param string $strKey The property name
  *
  * @return string The property value
  */
 public function __get($strKey)
 {
     switch ($strKey) {
         case 'id':
             return $this->strId;
             break;
         case 'name':
             return $this->strName;
             break;
         case 'label':
             return $this->strLabel;
             break;
         case 'value':
             // Encrypt the value
             if ($this->arrConfiguration['encrypt']) {
                 return \Encryption::encrypt($this->varValue);
             } elseif ($this->varValue == '') {
                 return $this->getEmptyStringOrNull();
             }
             return $this->varValue;
             break;
         case 'class':
             return $this->strClass;
             break;
         case 'prefix':
             return $this->strPrefix;
             break;
         case 'template':
             return $this->strTemplate;
             break;
         case 'wizard':
             return $this->strWizard;
             break;
         case 'required':
             return $this->arrConfiguration[$strKey];
             break;
         case 'forAttribute':
             return $this->blnForAttribute;
             break;
         case 'dataContainer':
             return $this->objDca;
             break;
         case 'activeRecord':
             return $this->objDca->activeRecord;
             break;
         default:
             if (isset($this->arrAttributes[$strKey])) {
                 return $this->arrAttributes[$strKey];
             } elseif (isset($this->arrConfiguration[$strKey])) {
                 return $this->arrConfiguration[$strKey];
             }
             break;
     }
     return parent::__get($strKey);
 }
Exemple #21
0
 /**
  * Return an object property
  *
  * @param string $strKey The property name
  *
  * @return mixed The property value
  */
 public function __get($strKey)
 {
     if (isset($this->arrData[$strKey])) {
         if (is_object($this->arrData[$strKey]) && is_callable($this->arrData[$strKey])) {
             return $this->arrData[$strKey]();
         }
         return $this->arrData[$strKey];
     }
     return parent::__get($strKey);
 }
 /**
  * Redirect the user to given module
  *
  * @param string $target
  */
 protected function redirectToModule($target)
 {
     list($module, $params) = trimsplit('|', $target);
     $modules = $this->getModules();
     if (!isset($modules[$module])) {
         return;
     }
     $session = Session::getInstance()->getData();
     // Set the filters of all module tables to show all message types
     foreach ($modules[$module]['tables'] as $table) {
         $session['filter'][$table][AbstractHandler::$filterName] = AbstractHandler::getAvailableFilters()[0];
     }
     // Decode the params
     if ($params) {
         $params = '&' . base64_decode($params);
     }
     Session::getInstance()->setData($session);
     Controller::redirect('contao/main.php?do=' . $module . $params . '&' . AbstractHandler::$serpTemporaryParamName . '=1');
 }
Exemple #23
0
 /**
  * Convert a string to a response object
  *
  * @param string $str
  *
  * @return Response
  */
 protected function convertToResponse($str)
 {
     return new Response(\Controller::replaceOldBePaths($str));
 }
 public function generateStandardGroup(ActionEvent $event)
 {
     $action = $event->getAction();
     $environment = $event->getEnvironment();
     $dataDefinition = $environment->getDataDefinition();
     if ($dataDefinition->getName() !== 'orm_avisota_salutation_group' || $action->getName() !== 'generate') {
         return;
     }
     global $AVISOTA_SALUTATION;
     $eventDispatcher = $environment->getEventDispatcher();
     $translator = $environment->getTranslator();
     $eventDispatcher->dispatch(ContaoEvents::SYSTEM_LOAD_LANGUAGE_FILE, new LoadLanguageFileEvent('avisota_salutation'));
     $eventDispatcher->dispatch(ContaoEvents::SYSTEM_LOAD_LANGUAGE_FILE, new LoadLanguageFileEvent('orm_avisota_salutation_group'));
     $predefinedSalutations = $AVISOTA_SALUTATION;
     $entityDataProvider = new EntityDataProvider();
     $entityDataProvider->setBaseConfig(array('source' => 'orm_avisota_salutation_group'));
     $entityManager = $entityDataProvider->getEntityManager();
     $entityAccessor = $entityDataProvider->getEntityAccessor();
     $salutationGroup = new \Avisota\Contao\Entity\SalutationGroup();
     $salutationGroup->setTitle('Default group generated at ' . date(Config::get('datimFormat')));
     $salutationGroup->setAlias(null);
     $sorting = 64;
     foreach ($predefinedSalutations as $index => $predefinedSalutation) {
         $salutation = new \Avisota\Contao\Entity\Salutation();
         $entityAccessor->setProperties($salutation, $predefinedSalutation);
         $salutation->setSalutation($translator->translate($index, 'avisota_salutation'));
         $salutation->setSalutationGroup($salutationGroup);
         $salutation->setSorting($sorting);
         $salutationGroup->addSalutation($salutation);
         $sorting *= 2;
     }
     $entityManager->persist($salutationGroup);
     $entityManager->flush($salutationGroup);
     $sessionConfirm = Session::getInstance()->get('TL_CONFIRM');
     if (!is_array($sessionConfirm)) {
         $sessionConfirm = (array) $sessionConfirm;
     }
     $sessionConfirm[] = $translator->translate('group_generated', 'orm_avisota_salutation_group');
     Session::getInstance()->set('TL_CONFIRM', $sessionConfirm);
     Controller::redirect('contao/main.php?do=avisota_salutation');
 }
Exemple #25
0
 /**
  * @param $db
  * @param $doTable
  * @param $table
  * @return null|string
  */
 public function setTitle($db, $doTable, $table)
 {
     // sorted by priority
     if (!$doTable) {
         return null;
     }
     $colsForTitle = $this->modules[$doTable]['title'];
     array_unshift($colsForTitle, 'ps_title');
     $colsForTitle = $colsForTitle ? $colsForTitle : array();
     // hook for custom title
     if ($this->modules[$doTable] && is_array($this->modules[$doTable]['setCustomTitle'])) {
         foreach ($this->modules[$doTable]['setCustomTitle'] as $callable) {
             $this->import($callable[0]);
             return $this->{$callable[0]}->{$callable[1]}($table, $db, $colsForTitle, $doTable);
         }
     }
     foreach ($colsForTitle as $title) {
         if (!$db[$title]) {
             continue;
         }
         $ct = deserialize($db[$title]);
         // check if value is serialize
         if (is_array($ct) && !empty($ct)) {
             $meta = Helper::parseStrForMeta($db[$title]);
             $db[$title] = $meta;
         }
         if ($db[$title] && (is_string($db[$title]) || is_numeric($db[$title]))) {
             $return = $db[$title];
             $return = Controller::replaceInsertTags($return);
             $return = strip_tags($return);
             $return = trim($return);
             return $return;
             break;
         }
     }
     return null;
 }
Exemple #26
0
 /**
  * Load the database object
  *
  * Make the constructor public, so pages can be instantiated (see #6182)
  */
 public function __construct()
 {
     parent::__construct();
     $this->import('Database');
 }
Exemple #27
0
 /**
  * Generate the navigation menu and return it as array
  *
  * @param boolean $blnShowAll
  *
  * @return array
  */
 public function navigation($blnShowAll = false)
 {
     /** @var AttributeBagInterface $objSessionBag */
     $objSessionBag = \System::getContainer()->get('session')->getBag('contao_backend');
     $arrModules = array();
     $session = $objSessionBag->all();
     // Toggle nodes
     if (\Input::get('mtg')) {
         $session['backend_modules'][\Input::get('mtg')] = isset($session['backend_modules'][\Input::get('mtg')]) && $session['backend_modules'][\Input::get('mtg')] == 0 ? 1 : 0;
         $objSessionBag->replace($session);
         \Controller::redirect(preg_replace('/(&(amp;)?|\\?)mtg=[^& ]*/i', '', \Environment::get('request')));
     }
     foreach ($GLOBALS['BE_MOD'] as $strGroupName => $arrGroupModules) {
         if (!empty($arrGroupModules) && ($strGroupName == 'system' || $this->hasAccess(array_keys($arrGroupModules), 'modules'))) {
             $arrModules[$strGroupName]['icon'] = 'modMinus.gif';
             $arrModules[$strGroupName]['title'] = specialchars($GLOBALS['TL_LANG']['MSC']['collapseNode']);
             $arrModules[$strGroupName]['label'] = ($label = is_array($GLOBALS['TL_LANG']['MOD'][$strGroupName]) ? $GLOBALS['TL_LANG']['MOD'][$strGroupName][0] : $GLOBALS['TL_LANG']['MOD'][$strGroupName]) != false ? $label : $strGroupName;
             $arrModules[$strGroupName]['href'] = \Controller::addToUrl('mtg=' . $strGroupName);
             // Do not show the modules if the group is closed
             if (!$blnShowAll && isset($session['backend_modules'][$strGroupName]) && $session['backend_modules'][$strGroupName] < 1) {
                 $arrModules[$strGroupName]['modules'] = false;
                 $arrModules[$strGroupName]['icon'] = 'modPlus.gif';
                 $arrModules[$strGroupName]['title'] = specialchars($GLOBALS['TL_LANG']['MSC']['expandNode']);
             } else {
                 foreach ($arrGroupModules as $strModuleName => $arrModuleConfig) {
                     // Check access
                     if ($strModuleName == 'undo' || $this->hasAccess($strModuleName, 'modules')) {
                         $arrModules[$strGroupName]['modules'][$strModuleName] = $arrModuleConfig;
                         $arrModules[$strGroupName]['modules'][$strModuleName]['title'] = specialchars($GLOBALS['TL_LANG']['MOD'][$strModuleName][1]);
                         $arrModules[$strGroupName]['modules'][$strModuleName]['label'] = ($label = is_array($GLOBALS['TL_LANG']['MOD'][$strModuleName]) ? $GLOBALS['TL_LANG']['MOD'][$strModuleName][0] : $GLOBALS['TL_LANG']['MOD'][$strModuleName]) != false ? $label : $strModuleName;
                         $arrModules[$strGroupName]['modules'][$strModuleName]['icon'] = !empty($arrModuleConfig['icon']) ? sprintf(' style="background-image:url(\'%s%s\')"', TL_ASSETS_URL, $arrModuleConfig['icon']) : '';
                         $arrModules[$strGroupName]['modules'][$strModuleName]['class'] = 'navigation ' . $strModuleName;
                         $arrModules[$strGroupName]['modules'][$strModuleName]['href'] = TL_SCRIPT . '?do=' . $strModuleName . '&amp;ref=' . TL_REFERER_ID;
                         // Mark the active module and its group
                         if (\Input::get('do') == $strModuleName) {
                             $arrModules[$strGroupName]['class'] = ' trail';
                             $arrModules[$strGroupName]['modules'][$strModuleName]['class'] .= ' active';
                         }
                     }
                 }
             }
         }
     }
     // HOOK: add custom logic
     if (isset($GLOBALS['TL_HOOKS']['getUserNavigation']) && is_array($GLOBALS['TL_HOOKS']['getUserNavigation'])) {
         foreach ($GLOBALS['TL_HOOKS']['getUserNavigation'] as $callback) {
             $this->import($callback[0]);
             $arrModules = $this->{$callback[0]}->{$callback[1]}($arrModules, $blnShowAll);
         }
     }
     return $arrModules;
 }
Exemple #28
0
 /**
  * Check whether there is a cached version of the page and return a response object
  *
  * @return Response|null
  */
 public static function getResponseFromCache()
 {
     // Build the page if a user is (potentially) logged in or there is POST data
     if (!empty($_POST) || \Input::cookie('BE_USER_AUTH') || \Input::cookie('FE_USER_AUTH') || \Input::cookie('FE_AUTO_LOGIN') || $_SESSION['DISABLE_CACHE'] || isset($_SESSION['LOGIN_ERROR']) || \Message::hasMessages() || \Config::get('debugMode')) {
         return null;
     }
     $strCacheDir = \System::getContainer()->getParameter('kernel.cache_dir');
     // Try to map the empty request
     if (\Environment::get('relativeRequest') == '') {
         // Return if the language is added to the URL and the empty domain will be redirected
         if (\Config::get('addLanguageToUrl') && !\Config::get('doNotRedirectEmpty')) {
             return null;
         }
         $strCacheKey = null;
         $arrLanguage = \Environment::get('httpAcceptLanguage');
         $strMappingFile = $strCacheDir . '/contao/config/mapping.php';
         // Try to get the cache key from the mapper array
         if (file_exists($strMappingFile)) {
             $arrMapper = (include $strMappingFile);
             $arrPaths = array(\Environment::get('host'), '*');
             // Try the language specific keys
             foreach ($arrLanguage as $strLanguage) {
                 foreach ($arrPaths as $strPath) {
                     $strKey = $strPath . '/empty.' . $strLanguage;
                     if (isset($arrMapper[$strKey])) {
                         $strCacheKey = $arrMapper[$strKey];
                         break;
                     }
                 }
             }
             // Try the fallback key
             if ($strCacheKey === null) {
                 foreach ($arrPaths as $strPath) {
                     $strKey = $strPath . '/empty.fallback';
                     if (isset($arrMapper[$strKey])) {
                         $strCacheKey = $arrMapper[$strKey];
                         break;
                     }
                 }
             }
         }
         // Fall back to the first accepted language
         if ($strCacheKey === null) {
             $strCacheKey = \Environment::get('host') . '/empty.' . $arrLanguage[0];
         }
     } else {
         $strCacheKey = \Environment::get('host') . '/' . \Environment::get('relativeRequest');
     }
     // HOOK: add custom logic
     if (isset($GLOBALS['TL_HOOKS']['getCacheKey']) && is_array($GLOBALS['TL_HOOKS']['getCacheKey'])) {
         foreach ($GLOBALS['TL_HOOKS']['getCacheKey'] as $callback) {
             $strCacheKey = \System::importStatic($callback[0])->{$callback[1]}($strCacheKey);
         }
     }
     $blnFound = false;
     $strCacheFile = null;
     // Check for a mobile layout
     if (\Input::cookie('TL_VIEW') == 'mobile' || \Environment::get('agent')->mobile && \Input::cookie('TL_VIEW') != 'desktop') {
         $strMd5CacheKey = md5($strCacheKey . '.mobile');
         $strCacheFile = $strCacheDir . '/contao/html/' . substr($strMd5CacheKey, 0, 1) . '/' . $strMd5CacheKey . '.html';
         if (file_exists($strCacheFile)) {
             $blnFound = true;
         }
     } else {
         $strMd5CacheKey = md5($strCacheKey . '.desktop');
         $strCacheFile = $strCacheDir . '/contao/html/' . substr($strMd5CacheKey, 0, 1) . '/' . $strMd5CacheKey . '.html';
         if (file_exists($strCacheFile)) {
             $blnFound = true;
         }
     }
     // Check for a regular layout
     if (!$blnFound) {
         $strMd5CacheKey = md5($strCacheKey);
         $strCacheFile = $strCacheDir . '/contao/html/' . substr($strMd5CacheKey, 0, 1) . '/' . $strMd5CacheKey . '.html';
         if (file_exists($strCacheFile)) {
             $blnFound = true;
         }
     }
     // Return if the file does not exist
     if (!$blnFound) {
         return null;
     }
     $expire = null;
     $content = null;
     $type = null;
     $files = null;
     $assets = null;
     // Include the file
     ob_start();
     require_once $strCacheFile;
     // The file has expired
     if ($expire < time()) {
         ob_end_clean();
         return null;
     }
     // Define the static URL constants (see #7914)
     define('TL_FILES_URL', $files);
     define('TL_ASSETS_URL', $assets);
     // Read the buffer
     $strBuffer = ob_get_clean();
     /** @var AttributeBagInterface $session */
     $session = \System::getContainer()->get('session')->getBag('contao_frontend');
     // Session required to determine the referer
     $data = $session->all();
     // Set the new referer
     if (!isset($_GET['pdf']) && !isset($_GET['file']) && !isset($_GET['id']) && $data['referer']['current'] != \Environment::get('requestUri')) {
         $data['referer']['last'] = $data['referer']['current'];
         $data['referer']['current'] = substr(\Environment::get('requestUri'), strlen(\Environment::get('path')) + 1);
     }
     // Store the session data
     $session->replace($data);
     // Load the default language file (see #2644)
     \System::loadLanguageFile('default');
     // Replace the insert tags and then re-replace the request_token tag in case a form element has been loaded via insert tag
     $strBuffer = \Controller::replaceInsertTags($strBuffer, false);
     $strBuffer = str_replace(array('{{request_token}}', '[{]', '[}]'), array(REQUEST_TOKEN, '{{', '}}'), $strBuffer);
     // HOOK: allow to modify the compiled markup (see #4291 and #7457)
     if (isset($GLOBALS['TL_HOOKS']['modifyFrontendPage']) && is_array($GLOBALS['TL_HOOKS']['modifyFrontendPage'])) {
         foreach ($GLOBALS['TL_HOOKS']['modifyFrontendPage'] as $callback) {
             $strBuffer = \System::importStatic($callback[0])->{$callback[1]}($strBuffer, null);
         }
     }
     // Content type
     if (!$content) {
         $content = 'text/html';
     }
     $response = new Response($strBuffer);
     // Send the status header (see #6585)
     if ($type == 'error_403') {
         $response->setStatusCode(Response::HTTP_FORBIDDEN);
     } elseif ($type == 'error_404') {
         $response->setStatusCode(Response::HTTP_NOT_FOUND);
     }
     $response->headers->set('Vary', 'User-Agent', false);
     $response->headers->set('Content-Type', $content . '; charset=' . \Config::get('characterSet'));
     // Send the cache headers
     if ($expire !== null && (\Config::get('cacheMode') == 'both' || \Config::get('cacheMode') == 'browser')) {
         $response->headers->set('Cache-Control', 'public, max-age=' . ($expire - time()));
         $response->headers->set('Pragma', 'public');
         $response->headers->set('Last-Modified', gmdate('D, d M Y H:i:s', time()) . ' GMT');
         $response->headers->set('Expires', gmdate('D, d M Y H:i:s', $expire) . ' GMT');
     } else {
         $response->headers->set('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
         $response->headers->set('Pragma', 'no-cache');
         $response->headers->set('Last-Modified', gmdate('D, d M Y H:i:s') . ' GMT');
         $response->headers->set('Expires', 'Fri, 06 Jun 1975 15:10:00 GMT');
     }
     return $response;
 }
 /**
  * getAlbums function.
  *
  * @access public
  * @return object
  */
 public function getAlbums()
 {
     if (count($this->items) > 0) {
         $objAlbum = \Photoalbums2AlbumModel::findMultipleByIds($this->items);
         if ($objAlbum !== null) {
             while ($objAlbum->next()) {
                 // Translate fields
                 if ($objAlbum->current() instanceof \Photoalbums2\Photoalbums2AlbumModel) {
                     Controller::loadDataContainer($objAlbum->current()->getTable());
                     $arrRow = \TranslationFields::translateDCArray($objAlbum->row(), $objAlbum->current()->getTable());
                     $objAlbum->setRow($arrRow);
                 }
                 // Get preview image as Pa2Image object
                 $objImage = new \Pa2Image($objAlbum->previewImage);
                 $objAlbum->objPreviewImage = $objImage->getPa2Image();
                 // Deserialize arrays
                 $objAlbum->images = deserialize($objAlbum->images);
                 $objAlbum->imageSort = deserialize($objAlbum->imageSort);
                 // Set sortedImageIds
                 $objPa2ImageSorter = new \Pa2ImageSorter($objAlbum->imageSortType, $objAlbum->images, $objAlbum->imageSort);
                 $objAlbum->arrSortedImageUuids = $objPa2ImageSorter->getSortedUuids();
             }
             $objAlbum->reset();
         }
         return $objAlbum;
     }
     return null;
 }
Exemple #30
0
 /**
  * Redirect to another page
  *
  * @param string  $strLocation The target URL
  * @param integer $intStatus   The HTTP status code (defaults to 303)
  *
  * @deprecated Deprecated since Contao 4.0, to be removed in Contao 5.0.
  *             Use Controller::redirect() instead.
  */
 public static function redirect($strLocation, $intStatus = 303)
 {
     @trigger_error('Using System::redirect() has been deprecated and will no longer work in Contao 5.0. Use Controller::redirect() instead.', E_USER_DEPRECATED);
     \Controller::redirect($strLocation, $intStatus);
 }