コード例 #1
0
 /**
  * Load a set of DCA files
  *
  * @param boolean $blnNoCache If true, the cache will be bypassed
  */
 public function load($blnNoCache = false)
 {
     // Return if the data has been loaded already
     if (isset($GLOBALS['loadDataContainer'][$this->strTable]) && !$blnNoCache) {
         return;
     }
     $GLOBALS['loadDataContainer'][$this->strTable] = true;
     // see #6145
     $strCacheDir = \System::getContainer()->getParameter('kernel.cache_dir');
     // Try to load from cache
     if (file_exists($strCacheDir . '/contao/dca/' . $this->strTable . '.php')) {
         include $strCacheDir . '/contao/dca/' . $this->strTable . '.php';
     } else {
         try {
             $files = \System::getContainer()->get('contao.resource_locator')->locate('dca/' . $this->strTable . '.php', null, false);
         } catch (\InvalidArgumentException $e) {
             $files = array();
         }
         foreach ($files as $file) {
             include $file;
         }
     }
     // HOOK: allow to load custom settings
     if (isset($GLOBALS['TL_HOOKS']['loadDataContainer']) && is_array($GLOBALS['TL_HOOKS']['loadDataContainer'])) {
         foreach ($GLOBALS['TL_HOOKS']['loadDataContainer'] as $callback) {
             $this->import($callback[0]);
             $this->{$callback[0]}->{$callback[1]}($this->strTable);
         }
     }
     // Local configuration file
     if (file_exists(TL_ROOT . '/system/config/dcaconfig.php')) {
         include TL_ROOT . '/system/config/dcaconfig.php';
     }
 }
コード例 #2
0
ファイル: tl_content.php プロジェクト: bytehead/core-bundle
 /**
  * Check permissions to edit table tl_content
  */
 public function checkPermission()
 {
     /** @var Symfony\Component\HttpFoundation\Session\SessionInterface $objSession */
     $objSession = System::getContainer()->get('session');
     // Prevent deleting referenced elements (see #4898)
     if (Input::get('act') == 'deleteAll') {
         $objCes = $this->Database->prepare("SELECT cteAlias FROM tl_content WHERE (ptable='tl_article' OR ptable='') AND type='alias'")->execute();
         $session = $objSession->all();
         $session['CURRENT']['IDS'] = array_diff($session['CURRENT']['IDS'], $objCes->fetchEach('cteAlias'));
         $objSession->replace($session);
     }
     if ($this->User->isAdmin) {
         return;
     }
     // Get the pagemounts
     $pagemounts = array();
     foreach ($this->User->pagemounts as $root) {
         $pagemounts[] = $root;
         $pagemounts = array_merge($pagemounts, $this->Database->getChildRecords($root, 'tl_page'));
     }
     $pagemounts = array_unique($pagemounts);
     // Check the current action
     switch (Input::get('act')) {
         case 'paste':
             // Allow
             break;
         case '':
             // empty
         // empty
         case 'create':
         case 'select':
             // Check access to the article
             $this->checkAccessToElement(CURRENT_ID, $pagemounts, true);
             break;
         case 'editAll':
         case 'deleteAll':
         case 'overrideAll':
         case 'cutAll':
         case 'copyAll':
             // Check access to the parent element if a content element is moved
             if (Input::get('act') == 'cutAll' || Input::get('act') == 'copyAll') {
                 $this->checkAccessToElement(Input::get('pid'), $pagemounts, Input::get('mode') == 2);
             }
             $objCes = $this->Database->prepare("SELECT id FROM tl_content WHERE (ptable='tl_article' OR ptable='') AND pid=?")->execute(CURRENT_ID);
             $session = $objSession->all();
             $session['CURRENT']['IDS'] = array_intersect($session['CURRENT']['IDS'], $objCes->fetchEach('id'));
             $objSession->replace($session);
             break;
         case 'cut':
         case 'copy':
             // Check access to the parent element if a content element is moved
             $this->checkAccessToElement(Input::get('pid'), $pagemounts, Input::get('mode') == 2);
             // NO BREAK STATEMENT HERE
         // NO BREAK STATEMENT HERE
         default:
             // Check access to the content element
             $this->checkAccessToElement(Input::get('id'), $pagemounts);
             break;
     }
 }
コード例 #3
0
ファイル: Maintenance.php プロジェクト: contao/core-bundle
 /**
  * Generate the module
  *
  * @return string
  */
 public function run()
 {
     /** @var BackendTemplate|object $objTemplate */
     $objTemplate = new \BackendTemplate('be_maintenance_mode');
     $objTemplate->action = ampersand(\Environment::get('request'));
     $objTemplate->headline = $GLOBALS['TL_LANG']['tl_maintenance']['maintenanceMode'];
     $objTemplate->isActive = $this->isActive();
     try {
         $driver = \System::getContainer()->get('lexik_maintenance.driver.factory')->getDriver();
         $isLocked = $driver->isExists();
     } catch (\Exception $e) {
         return '';
     }
     // Toggle the maintenance mode
     if (\Input::post('FORM_SUBMIT') == 'tl_maintenance_mode') {
         if ($isLocked) {
             $driver->unlock();
         } else {
             $driver->lock();
         }
         $this->reload();
     }
     if ($isLocked) {
         $objTemplate->class = 'tl_confirm';
         $objTemplate->explain = $GLOBALS['TL_LANG']['MSC']['maintenanceEnabled'];
         $objTemplate->submit = $GLOBALS['TL_LANG']['tl_maintenance']['maintenanceDisable'];
     } else {
         $objTemplate->class = 'tl_info';
         $objTemplate->explain = $GLOBALS['TL_LANG']['MSC']['maintenanceDisabled'];
         $objTemplate->submit = $GLOBALS['TL_LANG']['tl_maintenance']['maintenanceEnable'];
     }
     return $objTemplate->parse();
 }
コード例 #4
0
 /**
  * Return all excluded fields as HTML drop down menu
  *
  * @return array
  */
 public function getExcludedFields()
 {
     $processed = array();
     /** @var SplFileInfo[] $files */
     $files = System::getContainer()->get('contao.resource_finder')->findIn('dca')->depth(0)->files()->name('*.php');
     foreach ($files as $file) {
         if (in_array($file->getBasename(), $processed)) {
             continue;
         }
         $processed[] = $file->getBasename();
         $strTable = $file->getBasename('.php');
         System::loadLanguageFile($strTable);
         $this->loadDataContainer($strTable);
     }
     $arrReturn = array();
     // Get all excluded fields
     foreach ($GLOBALS['TL_DCA'] as $k => $v) {
         if (is_array($v['fields'])) {
             foreach ($v['fields'] as $kk => $vv) {
                 if ($vv['exclude'] || $vv['orig_exclude']) {
                     $arrReturn[$k][StringUtil::specialchars($k . '::' . $kk)] = isset($vv['label'][0]) ? $vv['label'][0] . ' <span style="color:#999;padding-left:3px">[' . $kk . ']</span>' : $kk;
                 }
             }
         }
     }
     ksort($arrReturn);
     return $arrReturn;
 }
コード例 #5
0
 /**
  * @param $table
  * @param $field
  */
 public static function convertTranslationField($table, $field)
 {
     $backup = $field . '_backup';
     $objDatabase = Database::getInstance();
     /* @var $objLanguages Languages */
     $objLanguages = \System::getContainer()->get('craffft.translation_fields.service.languages');
     // Backup the original column and then change the column type
     if (!$objDatabase->fieldExists($backup, $table, true)) {
         $objDatabase->query("ALTER TABLE `{$table}` ADD `{$backup}` text NULL");
         $objDatabase->query("UPDATE `{$table}` SET `{$backup}`=`{$field}`");
         $objDatabase->query("ALTER TABLE `{$table}` CHANGE `{$field}` `{$field}` int(10) unsigned NOT NULL default '0'");
         $objDatabase->query("UPDATE `{$table}` SET `{$field}`='0'");
     }
     $objRow = $objDatabase->query("SELECT id, {$backup} FROM {$table} WHERE {$backup}!=''");
     while ($objRow->next()) {
         if (is_numeric($objRow->{$backup})) {
             $intFid = $objRow->{$backup};
         } else {
             if (strlen($objRow->{$backup}) > 0) {
                 $intFid = TranslationFieldsModel::saveValuesAndReturnFid($objLanguages->getLanguagesWithValue($objRow->{$backup}));
             } else {
                 $intFid = 0;
             }
         }
         $objDatabase->prepare("UPDATE {$table} SET {$field}=? WHERE id=?")->execute($intFid, $objRow->id);
     }
 }
コード例 #6
0
 /**
  * Generate module
  */
 protected function compile()
 {
     $carService = \System::getContainer()->get('xuad_car.service.carservice');
     $carList = $carService->findAll();
     $twigRenderer = \System::getContainer()->get('templating');
     $rendered = $twigRenderer->render('@XuadCar/mod_car_list.twig', ['carList' => $carList]);
     $this->Template->renderedTwig = $rendered;
 }
コード例 #7
0
 protected function updateConfig($activeRecord)
 {
     Message::addInfo("Updating Config");
     $row = $activeRecord->row();
     $row['skipInternalHook'] = true;
     $url = Controller::generateFrontendUrl($row);
     System::getContainer()->get('phpbb_bridge.connector')->updateConfig(array('contao.forum_pageId' => $activeRecord->id, 'contao.forum_pageUrl' => $url));
 }
コード例 #8
0
ファイル: tl_faq.php プロジェクト: contao/faq-bundle
 /**
  * Check permissions to edit table tl_faq
  */
 public function checkPermission()
 {
     $bundles = System::getContainer()->getParameter('kernel.bundles');
     // HOOK: comments extension required
     if (!isset($bundles['ContaoCommentsBundle'])) {
         $key = array_search('allowComments', $GLOBALS['TL_DCA']['tl_faq']['list']['sorting']['headerFields']);
         unset($GLOBALS['TL_DCA']['tl_faq']['list']['sorting']['headerFields'][$key]);
     }
 }
コード例 #9
0
 /**
  * Increases the login count.
  */
 public function increaseLoginCount()
 {
     $cache = \System::getContainer()->get('contao.cache');
     if ($cache->contains('login-count')) {
         $count = intval($cache->fetch('login-count')) + 1;
     } else {
         $count = 1;
     }
     $cache->save('login-count', $count);
 }
コード例 #10
0
ファイル: ModuleLoader.php プロジェクト: contao/core-bundle
 /**
  * Return the active modules as array
  *
  * @return array An array of active modules
  */
 public static function getActive()
 {
     $bundles = array_keys(\System::getContainer()->getParameter('kernel.bundles'));
     foreach (static::$legacy as $bundleName => $module) {
         if (in_array($bundleName, $bundles)) {
             $bundles[] = $module;
         }
     }
     return $bundles;
 }
コード例 #11
0
ファイル: ModuleLoader.php プロジェクト: Mozan/core-bundle
 /**
  * Return the active modules as array
  *
  * @return array An array of active modules
  */
 public static function getActive()
 {
     @trigger_error('Using ModuleLoader::getActive() has been deprecated and will no longer work in Contao 5.0. Use the container parameter "kernel.bundles" instead.', E_USER_DEPRECATED);
     $bundles = array_keys(\System::getContainer()->getParameter('kernel.bundles'));
     foreach (static::$legacy as $bundleName => $module) {
         if (in_array($bundleName, $bundles)) {
             $bundles[] = $module;
         }
     }
     return $bundles;
 }
コード例 #12
0
ファイル: Messages.php プロジェクト: Mozan/core-bundle
 /**
  * Check for maintenance mode
  *
  * @return string
  */
 public function maintenanceCheck()
 {
     try {
         if (\System::getContainer()->get('lexik_maintenance.driver.factory')->getDriver()->isExists()) {
             return '<p class="tl_error"><a href="contao/main.php?do=maintenance">' . $GLOBALS['TL_LANG']['MSC']['maintenanceEnabled'] . '</a></p>';
         }
     } catch (\Exception $e) {
         // ignore
     }
     return '';
 }
コード例 #13
0
ファイル: ImageSize.php プロジェクト: contao/core-bundle
 /**
  * Trim values
  *
  * @param mixed $varInput
  *
  * @return mixed
  */
 protected function validator($varInput)
 {
     $this->import('BackendUser', 'User');
     $varInput[0] = parent::validator($varInput[0]);
     $varInput[1] = parent::validator($varInput[1]);
     $varInput[2] = preg_replace('/[^a-z0-9_]+/', '', $varInput[2]);
     $imageSizes = \System::getContainer()->get('contao.image.image_sizes');
     $this->arrAvailableOptions = $this->User->isAdmin ? $imageSizes->getAllOptions() : $imageSizes->getOptionsForUser($this->User);
     if (!$this->isValidOption($varInput[2])) {
         $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['invalid'], $varInput[2]));
     }
     return $varInput;
 }
コード例 #14
0
 /**
  * @param $strContent
  * @param int $intHeight
  * @return string
  * @throws \Exception
  */
 public static function generate($strContent, $intHeight = 35)
 {
     // Handle height
     if (!is_numeric($intHeight)) {
         $intHeight = 35;
     }
     $strPath = 'barcode/cache';
     $strAbsolutePath = \System::getContainer()->get('kernel')->getRootDir() . '/../web/' . $strPath . '/';
     $objBarcode = new Base1DBarcode();
     $objBarcode->savePath = $strAbsolutePath;
     $strAbsoluteFilePath = $objBarcode->getBarcodePNGPath($strContent, 'C128', 1.5, $intHeight);
     $strFile = substr($strAbsoluteFilePath, strlen($strAbsolutePath));
     return $strPath . '/' . $strFile;
 }
コード例 #15
0
 /**
  * @param $strContent
  * @param string $strType
  * @param int $intSize
  * @return string
  * @throws \Exception
  */
 public static function generate($strContent, $strType = self::QRCODE_H, $intSize = 3)
 {
     // Handle size
     if (!is_numeric($intSize) || $intSize < 1 || $intSize > 10) {
         $intSize = 3;
     }
     $strPath = 'qrcode/cache';
     $strAbsolutePath = \System::getContainer()->get('kernel')->getRootDir() . '/../web/' . $strPath . '/';
     $objQrcode = new Base2DBarcode();
     $objQrcode->savePath = $strAbsolutePath;
     $strAbsoluteFilePath = $objQrcode->getBarcodePNGPath($strContent, $strType, $intSize, $intSize);
     $strFile = substr($strAbsoluteFilePath, strlen($strAbsolutePath));
     return $strPath . '/' . $strFile;
 }
コード例 #16
0
ファイル: Messages.php プロジェクト: contao/core-bundle
 /**
  * Check for maintenance mode
  *
  * @return string
  */
 public function maintenanceCheck()
 {
     $this->import('BackendUser', 'User');
     if (!$this->User->hasAccess('maintenance', 'modules')) {
         return '';
     }
     try {
         if (\System::getContainer()->get('lexik_maintenance.driver.factory')->getDriver()->isExists()) {
             return '<p class="tl_error">' . $GLOBALS['TL_LANG']['MSC']['maintenanceEnabled'] . '</p>';
         }
     } catch (\Exception $e) {
         // ignore
     }
     return '';
 }
コード例 #17
0
ファイル: tl_style_sheet.php プロジェクト: contao/core-bundle
 /**
  * Schedule a style sheet update
  *
  * This method is triggered when a single style sheet or multiple style
  * sheets are modified (edit/editAll) or duplicated (copy/copyAll).
  *
  * @param mixed $id
  */
 public function scheduleUpdate($id)
 {
     // The onsubmit_callback passes a DataContainer object
     if (is_object($id)) {
         $id = $id->id;
     }
     // Return if there is no ID
     if (!$id || Input::get('act') == 'copy') {
         return;
     }
     /** @var Symfony\Component\HttpFoundation\Session\SessionInterface $objSession */
     $objSession = System::getContainer()->get('session');
     // Store the ID in the session
     $session = $objSession->get('style_sheet_updater');
     $session[] = $id;
     $objSession->set('style_sheet_updater', array_unique($session));
 }
コード例 #18
0
 /**
  * Check permissions to edit table tl_comments
  */
 public function checkPermission()
 {
     switch (Input::get('act')) {
         case 'select':
         case 'show':
             // Allow
             break;
         case 'edit':
         case 'delete':
         case 'toggle':
             $objComment = $this->Database->prepare("SELECT id, parent, source FROM tl_comments WHERE id=?")->limit(1)->execute(Input::get('id'));
             if ($objComment->numRows < 1) {
                 $this->log('Comment ID ' . Input::get('id') . ' does not exist', __METHOD__, TL_ERROR);
                 $this->redirect('contao/main.php?act=error');
             }
             if (!$this->isAllowedToEditComment($objComment->parent, $objComment->source)) {
                 $this->log('Not enough permissions to ' . Input::get('act') . ' comment ID ' . Input::get('id') . ' (parent element: ' . $objComment->source . ' ID ' . $objComment->parent . ')', __METHOD__, TL_ERROR);
                 $this->redirect('contao/main.php?act=error');
             }
             break;
         case 'editAll':
         case 'deleteAll':
         case 'overrideAll':
             /** @var Symfony\Component\HttpFoundation\Session\SessionInterface $objSession */
             $objSession = System::getContainer()->get('session');
             $session = $objSession->all();
             if (!is_array($session['CURRENT']['IDS']) || empty($session['CURRENT']['IDS'])) {
                 break;
             }
             $objComment = $this->Database->execute("SELECT id, parent, source FROM tl_comments WHERE id IN(" . implode(',', array_map('intval', $session['CURRENT']['IDS'])) . ")");
             while ($objComment->next()) {
                 if (!$this->isAllowedToEditComment($objComment->parent, $objComment->source) && ($key = array_search($objComment->id, $session['CURRENT']['IDS'])) !== false) {
                     unset($session['CURRENT']['IDS'][$key]);
                 }
             }
             $session['CURRENT']['IDS'] = array_values($session['CURRENT']['IDS']);
             $objSession->replace($session);
             break;
         default:
             if (strlen(Input::get('act'))) {
                 $this->log('Invalid command "' . Input::get('act') . '"', __METHOD__, TL_ERROR);
                 $this->redirect('contao/main.php?act=error');
             }
             break;
     }
 }
コード例 #19
0
 public function updateConfig(DataContainer $dc)
 {
     // Return if there is no active record (override all)
     if (!$dc->activeRecord || $dc->activeRecord->type != 'phpbb_forum') {
         return;
     }
     $row = $dc->activeRecord->row();
     // If it's a new object with no values we can skip here
     if (empty($row['phpbb_path']) && empty($row['phpbb_alias'])) {
         return;
     }
     Message::addInfo("Updating Config");
     $row['skipInternalHook'] = true;
     $url = Controller::generateFrontendUrl($row);
     $db = ['host' => System::getContainer()->getParameter('database_host'), 'port' => System::getContainer()->getParameter('database_port'), 'user' => System::getContainer()->getParameter('database_user'), 'password' => System::getContainer()->getParameter('database_password'), 'dbname' => System::getContainer()->getParameter('database_name')];
     System::getContainer()->get('phpbb_bridge.connector')->updateConfig(array('contao.forum_pageId' => $dc->activeRecord->id, 'contao.forum_pageUrl' => Environment::get('url') . '/' . $url, 'contao.url' => Environment::get('url'), 'contao.forum_pageAlias' => $dc->activeRecord->phpbb_alias, 'contao.bridge_is_installed' => true, 'contao.db' => $db));
     System::getContainer()->get('phpbb_bridge.connector')->setMandatoryDbConfigValues();
     Message::addInfo('<strong>You may want to clear the forum cache to make sure the new values are active</strong>');
     System::getContainer()->get('phpbb_bridge.connector')->testCookieDomain();
 }
コード例 #20
0
 /**
  * @param array $arrItems
  * @return string
  */
 public static function getTranslationLanguagesList(array $arrItems)
 {
     // Generate langauge list
     $arrLanguagesList = array();
     $i = 0;
     /* @var $objLanguages Languages */
     $objLanguages = \System::getContainer()->get('craffft.translation_fields.service.languages');
     $arrLanguages = $objLanguages->getLanguages();
     foreach ($arrLanguages as $key => $value) {
         $strFlagname = strtolower(strlen($key) > 2 ? substr($key, -2) : $key);
         // Set empty flagname, if flag doesn't exist
         if (!file_exists(sprintf('%s/web/%s/images/flag-icons/%s.png', TL_ROOT, CRAFFFT_TRANSLATION_FIELDS_PUBLIC_PATH, $strFlagname))) {
             $strFlagname = 'xx';
         }
         $strLanguageIcon = sprintf('<img src="%s/images/flag-icons/%s.png" width="16" height="11" alt="%s">', CRAFFFT_TRANSLATION_FIELDS_PUBLIC_PATH, $strFlagname, $value);
         $arrLanguagesList[] = sprintf('<li id="lng_list_item_%s" class="tf_lng_item%s">%s%s</li>', $key, isset($arrItems[$key]) && strlen(specialchars($arrItems[$key])) > 0 ? ' translated' : '', $strLanguageIcon, $value);
         $i++;
     }
     $strLanguageList = sprintf('<ul class="tf_lng_list">%s</ul>', implode(' ', $arrLanguagesList));
     return $strLanguageList;
 }
コード例 #21
0
ファイル: tl_newsletter.php プロジェクト: burguin/test02
 /**
  * Check permissions to edit table tl_newsletter
  *
  * @throws Contao\CoreBundle\Exception\AccessDeniedException
  */
 public function checkPermission()
 {
     if ($this->User->isAdmin) {
         return;
     }
     // Set root IDs
     if (!is_array($this->User->newsletters) || empty($this->User->newsletters)) {
         $root = array(0);
     } else {
         $root = $this->User->newsletters;
     }
     $id = strlen(Input::get('id')) ? Input::get('id') : CURRENT_ID;
     // Check current action
     switch (Input::get('act')) {
         case 'paste':
         case 'select':
             // Allow
             break;
         case 'create':
             if (!strlen(Input::get('pid')) || !in_array(Input::get('pid'), $root)) {
                 throw new Contao\CoreBundle\Exception\AccessDeniedException('Not enough permissions to create newsletters in channel ID ' . Input::get('pid') . '.');
             }
             break;
         case 'cut':
         case 'copy':
             if (!in_array(Input::get('pid'), $root)) {
                 throw new Contao\CoreBundle\Exception\AccessDeniedException('Not enough permissions to ' . Input::get('act') . ' newsletter ID ' . $id . ' to channel ID ' . Input::get('pid') . '.');
             }
             // NO BREAK STATEMENT HERE
         // NO BREAK STATEMENT HERE
         case 'edit':
         case 'show':
         case 'delete':
             $objChannel = $this->Database->prepare("SELECT pid FROM tl_newsletter WHERE id=?")->limit(1)->execute($id);
             if ($objChannel->numRows < 1) {
                 throw new Contao\CoreBundle\Exception\AccessDeniedException('Invalid newsletter ID ' . $id . '.');
             }
             if (!in_array($objChannel->pid, $root)) {
                 throw new Contao\CoreBundle\Exception\AccessDeniedException('Not enough permissions to ' . Input::get('act') . ' newsletter ID ' . $id . ' of newsletter channel ID ' . $objChannel->pid . '.');
             }
             break;
         case 'editAll':
         case 'deleteAll':
         case 'overrideAll':
         case 'cutAll':
         case 'copyAll':
             if (!in_array($id, $root)) {
                 throw new Contao\CoreBundle\Exception\AccessDeniedException('Not enough permissions to access newsletter channel ID ' . $id . '.');
             }
             $objChannel = $this->Database->prepare("SELECT id FROM tl_newsletter WHERE pid=?")->execute($id);
             if ($objChannel->numRows < 1) {
                 throw new Contao\CoreBundle\Exception\AccessDeniedException('Invalid newsletter channel ID  ' . $id . '.');
             }
             /** @var Symfony\Component\HttpFoundation\Session\SessionInterface $objSession */
             $objSession = System::getContainer()->get('session');
             $session = $objSession->all();
             $session['CURRENT']['IDS'] = array_intersect($session['CURRENT']['IDS'], $objChannel->fetchEach('id'));
             $objSession->replace($session);
             break;
         default:
             if (strlen(Input::get('act'))) {
                 throw new Contao\CoreBundle\Exception\AccessDeniedException('Invalid command "' . Input::get('act') . '".');
             }
             if (Input::get('key') == 'send') {
                 $objChannel = $this->Database->prepare("SELECT pid FROM tl_newsletter WHERE id=?")->limit(1)->execute($id);
                 if ($objChannel->numRows < 1) {
                     throw new Contao\CoreBundle\Exception\AccessDeniedException('Invalid newsletter ID ' . $id . '.');
                 }
                 if (!in_array($objChannel->pid, $root)) {
                     throw new Contao\CoreBundle\Exception\AccessDeniedException('Not enough permissions to send newsletter ID ' . $id . ' of newsletter channel ID ' . $objChannel->pid . '.');
                 }
             } elseif (!in_array($id, $root)) {
                 throw new Contao\CoreBundle\Exception\AccessDeniedException('Not enough permissions to access newsletter channel ID ' . $id . '.');
             }
             break;
     }
 }
コード例 #22
0
ファイル: FrontendUser.php プロジェクト: contao/core-bundle
 /**
  * Set all user properties from a database record
  */
 protected function setUserFromDb()
 {
     $this->intId = $this->id;
     // Unserialize values
     foreach ($this->arrData as $k => $v) {
         if (!is_numeric($v)) {
             $this->{$k} = \StringUtil::deserialize($v);
         }
     }
     // Set language
     if ($this->language != '') {
         \System::getContainer()->get('request_stack')->getCurrentRequest()->setLocale($this->language);
         \System::getContainer()->get('translator')->setLocale($this->language);
         // Deprecated since Contao 4.0, to be removed in Contao 5.0
         $GLOBALS['TL_LANGUAGE'] = str_replace('_', '-', $this->language);
     }
     $GLOBALS['TL_USERNAME'] = $this->username;
     // Make sure that groups is an array
     if (!is_array($this->groups)) {
         $this->groups = $this->groups != '' ? array($this->groups) : array();
     }
     // Skip inactive groups
     if (($objGroups = \MemberGroupModel::findAllActive()) !== null) {
         $this->groups = array_intersect($this->groups, $objGroups->fetchEach('id'));
     }
     // Get the group login page
     if ($this->groups[0] > 0) {
         $objGroup = \MemberGroupModel::findPublishedById($this->groups[0]);
         if ($objGroup !== null && $objGroup->redirect && $objGroup->jumpTo) {
             $this->strLoginPage = $objGroup->jumpTo;
         }
     }
 }
コード例 #23
0
ファイル: tl_article.php プロジェクト: Mozan/core-bundle
 /**
  * Automatically generate the folder URL aliases
  *
  * @param array $arrButtons
  *
  * @return array
  */
 public function addAliasButton($arrButtons)
 {
     // Generate the aliases
     if (Input::post('FORM_SUBMIT') == 'tl_select' && isset($_POST['alias'])) {
         /** @var Symfony\Component\HttpFoundation\Session\SessionInterface $objSession */
         $objSession = System::getContainer()->get('session');
         $session = $objSession->all();
         $ids = $session['CURRENT']['IDS'];
         foreach ($ids as $id) {
             $objArticle = ArticleModel::findByPk($id);
             if ($objArticle === null) {
                 continue;
             }
             // Set the new alias
             $strAlias = StringUtil::generateAlias($objArticle->title);
             // The alias has not changed
             if ($strAlias == $objArticle->alias) {
                 continue;
             }
             // Initialize the version manager
             $objVersions = new Versions('tl_article', $id);
             $objVersions->initialize();
             // Store the new alias
             $this->Database->prepare("UPDATE tl_article SET alias=? WHERE id=?")->execute($strAlias, $id);
             // Create a new version
             $objVersions->create();
         }
         $this->redirect($this->getReferer());
     }
     // Add the button
     $arrButtons['alias'] = '<button type="submit" name="alias" id="alias" class="tl_submit" accesskey="a">' . $GLOBALS['TL_LANG']['MSC']['aliasSelected'] . '</button> ';
     return $arrButtons;
 }
コード例 #24
0
ファイル: Config.php プロジェクト: eakcantey/core-bundle
 /**
  * Override the database and SMTP parameters
  */
 protected static function loadParameters()
 {
     $container = \System::getContainer();
     if ($container === null) {
         return;
     }
     $arrMap = array('dbHost' => 'database_host', 'dbPort' => 'database_port', 'dbUser' => 'database_user', 'dbPass' => 'database_password', 'dbDatabase' => 'database_name', 'smtpHost' => 'mailer_host', 'smtpUser' => 'mailer_user', 'smtpPass' => 'mailer_password', 'smtpPort' => 'mailer_port', 'smtpEnc' => 'mailer_encryption', 'addLanguageToUrl' => 'contao.prepend_locale', 'encryptionKey' => 'contao.encryption_key', 'urlSuffix' => 'contao.url_suffix', 'uploadPath' => 'contao.upload_path');
     foreach ($arrMap as $strKey => $strParam) {
         if ($container->hasParameter($strParam)) {
             $GLOBALS['TL_CONFIG'][$strKey] = $container->getParameter($strParam);
         }
     }
     $GLOBALS['TL_CONFIG']['debugMode'] = $container->getParameter('kernel.debug');
 }
コード例 #25
0
 /**
  * Get the DCA table settings from the database.sql files
  *
  * @return array An array of DCA table settings
  */
 public function getFromFile()
 {
     try {
         $files = \System::getContainer()->get('contao.resource_locator')->locate('config/database.sql', null, false);
     } catch (\InvalidArgumentException $e) {
         return array();
     }
     $table = '';
     $return = array();
     foreach ($files as $file) {
         $data = file($file);
         foreach ($data as $k => $v) {
             $key_name = array();
             $subpatterns = array();
             // Unset comments and empty lines
             if (preg_match('/^[#-]+/', $v) || !strlen(trim($v))) {
                 unset($data[$k]);
                 continue;
             }
             // Store the table names
             if (preg_match('/^CREATE TABLE `([^`]+)`/i', $v, $subpatterns)) {
                 $table = $subpatterns[1];
             } elseif ($table != '' && preg_match('/^\\)([^;]+);/', $v, $subpatterns)) {
                 $return[$table]['TABLE_OPTIONS'] = $subpatterns[1];
                 $table = '';
             } elseif ($table != '') {
                 preg_match('/^[^`]*`([^`]+)`/', trim($v), $key_name);
                 $first = preg_replace('/\\s[^\\n\\r]+/', '', $key_name[0]);
                 $key = $key_name[1];
                 // Create definitions
                 if (in_array($first, array('KEY', 'PRIMARY', 'PRIMARY KEY', 'FOREIGN', 'FOREIGN KEY', 'INDEX', 'UNIQUE', 'FULLTEXT', 'CHECK'))) {
                     if (strncmp($first, 'PRIMARY', 7) === 0) {
                         $key = 'PRIMARY';
                     }
                     $return[$table]['TABLE_CREATE_DEFINITIONS'][$key] = preg_replace('/,$/', '', trim($v));
                 } else {
                     $return[$table]['TABLE_FIELDS'][$key] = preg_replace('/,$/', '', trim($v));
                 }
             }
         }
     }
     // HOOK: allow third-party developers to modify the array (see #3281)
     if (isset($GLOBALS['TL_HOOKS']['sqlGetFromFile']) && is_array($GLOBALS['TL_HOOKS']['sqlGetFromFile'])) {
         foreach ($GLOBALS['TL_HOOKS']['sqlGetFromFile'] as $callback) {
             $this->import($callback[0]);
             $return = $this->{$callback[0]}->{$callback[1]}($return);
         }
     }
     return $return;
 }
コード例 #26
0
ファイル: GdImage.php プロジェクト: contao/core-bundle
 /**
  * Save the GD image to a file
  *
  * @param string $path The image path
  *
  * @return static
  *
  * @throws \InvalidArgumentException If the image type cannot be generated
  */
 public function saveToFile($path)
 {
     $arrGdInfo = gd_info();
     $extension = strtolower(substr($path, strrpos($path, '.') + 1));
     // Fallback to PNG if GIF ist not supported
     if ($extension == 'gif' && !$arrGdInfo['GIF Create Support']) {
         $extension = 'png';
     }
     // Get the relative path
     $folder = str_replace(TL_ROOT . '/', '', $path);
     // Create the parent folder
     if (($dirname = dirname($folder)) != '.' && !is_dir(TL_ROOT . '/' . $dirname)) {
         new \Folder($dirname);
     }
     // Create the new image
     switch ($extension) {
         case 'gif':
             $this->convertToPaletteImage();
             imagegif($this->gdResource, $path);
             break;
         case 'jpg':
         case 'jpeg':
             imageinterlace($this->gdResource, 1);
             // see #6529
             imagejpeg($this->gdResource, $path, \System::getContainer()->getParameter('contao.image.imagine_options')['jpeg_quality'] ?: 80);
             break;
         case 'png':
             if ($this->countColors(256) <= 256 && !$this->isSemitransparent()) {
                 $this->convertToPaletteImage();
             }
             imagepng($this->gdResource, $path);
             break;
         default:
             throw new \InvalidArgumentException('Image type "' . $extension . '" cannot be generated');
             break;
     }
     return $this;
 }
コード例 #27
0
ファイル: InsertTags.php プロジェクト: bytehead/core-bundle
 /**
  * Replace insert tags with their values
  *
  * @param string  $strBuffer The text with the tags to be replaced
  * @param boolean $blnCache  If false, non-cacheable tags will be replaced
  *
  * @return string The text with the replaced tags
  */
 protected function doReplace($strBuffer, $blnCache)
 {
     /** @var PageModel $objPage */
     global $objPage;
     // Preserve insert tags
     if (\Config::get('disableInsertTags')) {
         return \StringUtil::restoreBasicEntities($strBuffer);
     }
     $tags = preg_split('/{{([^{}]+)}}/', $strBuffer, -1, PREG_SPLIT_DELIM_CAPTURE);
     if (count($tags) < 2) {
         return \StringUtil::restoreBasicEntities($strBuffer);
     }
     $strBuffer = '';
     // Create one cache per cache setting (see #7700)
     static $arrItCache;
     $arrCache =& $arrItCache[$blnCache];
     for ($_rit = 0, $_cnt = count($tags); $_rit < $_cnt; $_rit += 2) {
         $strBuffer .= $tags[$_rit];
         $strTag = $tags[$_rit + 1];
         // Skip empty tags
         if ($strTag == '') {
             continue;
         }
         $flags = explode('|', $strTag);
         $tag = array_shift($flags);
         $elements = explode('::', $tag);
         // Load the value from cache
         if (isset($arrCache[$strTag]) && !in_array('refresh', $flags)) {
             $strBuffer .= $arrCache[$strTag];
             continue;
         }
         // Skip certain elements if the output will be cached
         if ($blnCache) {
             if ($elements[0] == 'date' || $elements[0] == 'ua' || $elements[0] == 'post' || $elements[0] == 'file' || $elements[1] == 'back' || $elements[1] == 'referer' || $elements[0] == 'request_token' || $elements[0] == 'toggle_view' || strncmp($elements[0], 'cache_', 6) === 0 || in_array('uncached', $flags)) {
                 $strBuffer .= '{{' . $strTag . '}}';
                 continue;
             }
         }
         $arrCache[$strTag] = '';
         // Replace the tag
         switch (strtolower($elements[0])) {
             // Date
             case 'date':
                 $arrCache[$strTag] = \Date::parse($elements[1] ?: \Config::get('dateFormat'));
                 break;
                 // Accessibility tags
             // Accessibility tags
             case 'lang':
                 if ($elements[1] == '') {
                     $arrCache[$strTag] = '</span>';
                 } else {
                     $arrCache[$strTag] = $arrCache[$strTag] = '<span lang="' . $elements[1] . '">';
                 }
                 break;
                 // Line break
             // Line break
             case 'br':
                 $arrCache[$strTag] = '<br>';
                 break;
                 // E-mail addresses
             // E-mail addresses
             case 'email':
             case 'email_open':
             case 'email_url':
                 if ($elements[1] == '') {
                     $arrCache[$strTag] = '';
                     break;
                 }
                 $strEmail = \StringUtil::encodeEmail($elements[1]);
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'email':
                         $arrCache[$strTag] = '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;' . $strEmail . '" class="email">' . preg_replace('/\\?.*$/', '', $strEmail) . '</a>';
                         break;
                     case 'email_open':
                         $arrCache[$strTag] = '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;' . $strEmail . '" title="' . $strEmail . '" class="email">';
                         break;
                     case 'email_url':
                         $arrCache[$strTag] = $strEmail;
                         break;
                 }
                 break;
                 // Label tags
             // Label tags
             case 'label':
                 $keys = explode(':', $elements[1]);
                 if (count($keys) < 2) {
                     $arrCache[$strTag] = '';
                     break;
                 }
                 $file = $keys[0];
                 // Map the key (see #7217)
                 switch ($file) {
                     case 'CNT':
                         $file = 'countries';
                         break;
                     case 'LNG':
                         $file = 'languages';
                         break;
                     case 'MOD':
                     case 'FMD':
                         $file = 'modules';
                         break;
                     case 'FFL':
                         $file = 'tl_form_field';
                         break;
                     case 'CACHE':
                         $file = 'tl_page';
                         break;
                     case 'XPL':
                         $file = 'explain';
                         break;
                     case 'XPT':
                         $file = 'exception';
                         break;
                     case 'MSC':
                     case 'ERR':
                     case 'CTE':
                     case 'PTY':
                     case 'FOP':
                     case 'CHMOD':
                     case 'DAYS':
                     case 'MONTHS':
                     case 'UNITS':
                     case 'CONFIRM':
                     case 'DP':
                     case 'COLS':
                         $file = 'default';
                         break;
                 }
                 \System::loadLanguageFile($file);
                 if (count($keys) == 2) {
                     $arrCache[$strTag] = $GLOBALS['TL_LANG'][$keys[0]][$keys[1]];
                 } else {
                     $arrCache[$strTag] = $GLOBALS['TL_LANG'][$keys[0]][$keys[1]][$keys[2]];
                 }
                 break;
                 // Front end user
             // Front end user
             case 'user':
                 if (FE_USER_LOGGED_IN) {
                     $this->import('FrontendUser', 'User');
                     $value = $this->User->{$elements[1]};
                     if ($value == '') {
                         $arrCache[$strTag] = $value;
                         break;
                     }
                     $this->loadDataContainer('tl_member');
                     if ($GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['inputType'] == 'password') {
                         $arrCache[$strTag] = '';
                         break;
                     }
                     $value = \StringUtil::deserialize($value);
                     // Decrypt the value
                     if ($GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['eval']['encrypt']) {
                         $value = \Encryption::decrypt($value);
                     }
                     $rgxp = $GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['eval']['rgxp'];
                     $opts = $GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['options'];
                     $rfrc = $GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['reference'];
                     if ($rgxp == 'date') {
                         $arrCache[$strTag] = \Date::parse(\Config::get('dateFormat'), $value);
                     } elseif ($rgxp == 'time') {
                         $arrCache[$strTag] = \Date::parse(\Config::get('timeFormat'), $value);
                     } elseif ($rgxp == 'datim') {
                         $arrCache[$strTag] = \Date::parse(\Config::get('datimFormat'), $value);
                     } elseif (is_array($value)) {
                         $arrCache[$strTag] = implode(', ', $value);
                     } elseif (is_array($opts) && array_is_assoc($opts)) {
                         $arrCache[$strTag] = isset($opts[$value]) ? $opts[$value] : $value;
                     } elseif (is_array($rfrc)) {
                         $arrCache[$strTag] = isset($rfrc[$value]) ? is_array($rfrc[$value]) ? $rfrc[$value][0] : $rfrc[$value] : $value;
                     } else {
                         $arrCache[$strTag] = $value;
                     }
                     // Convert special characters (see #1890)
                     $arrCache[$strTag] = \StringUtil::specialchars($arrCache[$strTag]);
                 }
                 break;
                 // Link
             // Link
             case 'link':
             case 'link_open':
             case 'link_url':
             case 'link_title':
             case 'link_target':
             case 'link_name':
                 $strTarget = null;
                 // Back link
                 if ($elements[1] == 'back') {
                     $strUrl = 'javascript:history.go(-1)';
                     $strTitle = $GLOBALS['TL_LANG']['MSC']['goBack'];
                     // No language files if the page is cached
                     if (!strlen($strTitle)) {
                         $strTitle = 'Go back';
                     }
                     $strName = $strTitle;
                 } elseif (strncmp($elements[1], 'http://', 7) === 0 || strncmp($elements[1], 'https://', 8) === 0) {
                     $strUrl = $elements[1];
                     $strTitle = $elements[1];
                     $strName = str_replace(array('http://', 'https://'), '', $elements[1]);
                 } else {
                     // User login page
                     if ($elements[1] == 'login') {
                         if (!FE_USER_LOGGED_IN) {
                             break;
                         }
                         $this->import('FrontendUser', 'User');
                         $elements[1] = $this->User->loginPage;
                     }
                     $objNextPage = \PageModel::findByIdOrAlias($elements[1]);
                     if ($objNextPage === null) {
                         break;
                     }
                     // Page type specific settings (thanks to Andreas Schempp)
                     switch ($objNextPage->type) {
                         case 'redirect':
                             $strUrl = $objNextPage->url;
                             if (strncasecmp($strUrl, 'mailto:', 7) === 0) {
                                 $strUrl = \StringUtil::encodeEmail($strUrl);
                             }
                             break;
                         case 'forward':
                             if ($objNextPage->jumpTo) {
                                 /** @var PageModel $objNext */
                                 $objNext = $objNextPage->getRelated('jumpTo');
                             } else {
                                 $objNext = \PageModel::findFirstPublishedRegularByPid($objNextPage->id);
                             }
                             if ($objNext instanceof PageModel) {
                                 $strUrl = $objNext->getFrontendUrl();
                                 break;
                             }
                             // DO NOT ADD A break; STATEMENT
                         // DO NOT ADD A break; STATEMENT
                         default:
                             $strUrl = $objNextPage->getFrontendUrl();
                             break;
                     }
                     $strName = $objNextPage->title;
                     $strTarget = $objNextPage->target ? ' target="_blank"' : '';
                     $strTitle = $objNextPage->pageTitle ?: $objNextPage->title;
                 }
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'link':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s"%s>%s</a>', $strUrl, \StringUtil::specialchars($strTitle), $strTarget, $strName);
                         break;
                     case 'link_open':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s"%s>', $strUrl, \StringUtil::specialchars($strTitle), $strTarget);
                         break;
                     case 'link_url':
                         $arrCache[$strTag] = $strUrl;
                         break;
                     case 'link_title':
                         $arrCache[$strTag] = \StringUtil::specialchars($strTitle);
                         break;
                     case 'link_target':
                         $arrCache[$strTag] = $strTarget;
                         break;
                     case 'link_name':
                         $arrCache[$strTag] = $strName;
                         break;
                 }
                 break;
                 // Closing link tag
             // Closing link tag
             case 'link_close':
             case 'email_close':
                 $arrCache[$strTag] = '</a>';
                 break;
                 // Insert article
             // Insert article
             case 'insert_article':
                 if (($strOutput = $this->getArticle($elements[1], false, true)) !== false) {
                     $arrCache[$strTag] = ltrim($strOutput);
                 } else {
                     $arrCache[$strTag] = '<p class="error">' . sprintf($GLOBALS['TL_LANG']['MSC']['invalidPage'], $elements[1]) . '</p>';
                 }
                 break;
                 // Insert content element
             // Insert content element
             case 'insert_content':
                 $arrCache[$strTag] = $this->getContentElement($elements[1]);
                 break;
                 // Insert module
             // Insert module
             case 'insert_module':
                 $arrCache[$strTag] = $this->getFrontendModule($elements[1]);
                 break;
                 // Insert form
             // Insert form
             case 'insert_form':
                 $arrCache[$strTag] = $this->getForm($elements[1]);
                 break;
                 // Article
             // Article
             case 'article':
             case 'article_open':
             case 'article_url':
             case 'article_title':
                 if (($objArticle = \ArticleModel::findByIdOrAlias($elements[1])) === null || !($objPid = $objArticle->getRelated('pid')) instanceof PageModel) {
                     break;
                 }
                 /** @var PageModel $objPid */
                 $strUrl = $objPid->getFrontendUrl('/articles/' . ($objArticle->alias ?: $objArticle->id));
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'article':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">%s</a>', $strUrl, \StringUtil::specialchars($objArticle->title), $objArticle->title);
                         break;
                     case 'article_open':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">', $strUrl, \StringUtil::specialchars($objArticle->title));
                         break;
                     case 'article_url':
                         $arrCache[$strTag] = $strUrl;
                         break;
                     case 'article_title':
                         $arrCache[$strTag] = \StringUtil::specialchars($objArticle->title);
                         break;
                 }
                 break;
                 // Article teaser
             // Article teaser
             case 'article_teaser':
                 $objTeaser = \ArticleModel::findByIdOrAlias($elements[1]);
                 if ($objTeaser !== null) {
                     $arrCache[$strTag] = \StringUtil::toHtml5($objTeaser->teaser);
                 }
                 break;
                 // Last update
             // Last update
             case 'last_update':
                 $strQuery = "SELECT MAX(tstamp) AS tc";
                 $bundles = \System::getContainer()->getParameter('kernel.bundles');
                 if (isset($bundles['ContaoNewsBundle'])) {
                     $strQuery .= ", (SELECT MAX(tstamp) FROM tl_news) AS tn";
                 }
                 if (isset($bundles['ContaoCalendarBundle'])) {
                     $strQuery .= ", (SELECT MAX(tstamp) FROM tl_calendar_events) AS te";
                 }
                 $strQuery .= " FROM tl_content";
                 $objUpdate = \Database::getInstance()->query($strQuery);
                 if ($objUpdate->numRows) {
                     $arrCache[$strTag] = \Date::parse($elements[1] ?: \Config::get('datimFormat'), max($objUpdate->tc, $objUpdate->tn, $objUpdate->te));
                 }
                 break;
                 // Version
             // Version
             case 'version':
                 $arrCache[$strTag] = VERSION . '.' . BUILD;
                 break;
                 // Request token
             // Request token
             case 'request_token':
                 $arrCache[$strTag] = REQUEST_TOKEN;
                 break;
                 // POST data
             // POST data
             case 'post':
                 $arrCache[$strTag] = \Input::post($elements[1]);
                 break;
                 // Mobile/desktop toggle (see #6469)
             // Mobile/desktop toggle (see #6469)
             case 'toggle_view':
                 $strUrl = ampersand(\Environment::get('request'));
                 $strGlue = strpos($strUrl, '?') === false ? '?' : '&amp;';
                 if (\Input::cookie('TL_VIEW') == 'mobile' || \Environment::get('agent')->mobile && \Input::cookie('TL_VIEW') != 'desktop') {
                     $arrCache[$strTag] = '<a href="' . $strUrl . $strGlue . 'toggle_view=desktop" class="toggle_desktop" title="' . \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['toggleDesktop'][1]) . '">' . $GLOBALS['TL_LANG']['MSC']['toggleDesktop'][0] . '</a>';
                 } else {
                     $arrCache[$strTag] = '<a href="' . $strUrl . $strGlue . 'toggle_view=mobile" class="toggle_mobile" title="' . \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['toggleMobile'][1]) . '">' . $GLOBALS['TL_LANG']['MSC']['toggleMobile'][0] . '</a>';
                 }
                 break;
                 // Conditional tags (if)
             // Conditional tags (if)
             case 'iflng':
                 if ($elements[1] != '' && $elements[1] != $objPage->language) {
                     for (; $_rit < $_cnt; $_rit += 2) {
                         if ($tags[$_rit + 1] == 'iflng' || $tags[$_rit + 1] == 'iflng::' . $objPage->language) {
                             break;
                         }
                     }
                 }
                 unset($arrCache[$strTag]);
                 break;
                 // Conditional tags (if not)
             // Conditional tags (if not)
             case 'ifnlng':
                 if ($elements[1] != '') {
                     $langs = \StringUtil::trimsplit(',', $elements[1]);
                     if (in_array($objPage->language, $langs)) {
                         for (; $_rit < $_cnt; $_rit += 2) {
                             if ($tags[$_rit + 1] == 'ifnlng') {
                                 break;
                             }
                         }
                     }
                 }
                 unset($arrCache[$strTag]);
                 break;
                 // Environment
             // Environment
             case 'env':
                 switch ($elements[1]) {
                     case 'host':
                         $arrCache[$strTag] = \Idna::decode(\Environment::get('host'));
                         break;
                     case 'http_host':
                         $arrCache[$strTag] = \Idna::decode(\Environment::get('httpHost'));
                         break;
                     case 'url':
                         $arrCache[$strTag] = \Idna::decode(\Environment::get('url'));
                         break;
                     case 'path':
                         $arrCache[$strTag] = \Idna::decode(\Environment::get('base'));
                         break;
                     case 'request':
                         $arrCache[$strTag] = \Environment::get('indexFreeRequest');
                         break;
                     case 'ip':
                         $arrCache[$strTag] = \Environment::get('ip');
                         break;
                     case 'referer':
                         $arrCache[$strTag] = $this->getReferer(true);
                         break;
                     case 'files_url':
                         $arrCache[$strTag] = TL_FILES_URL;
                         break;
                     case 'assets_url':
                     case 'plugins_url':
                     case 'script_url':
                         $arrCache[$strTag] = TL_ASSETS_URL;
                         break;
                     case 'base_url':
                         $arrCache[$strTag] = \System::getContainer()->get('request_stack')->getCurrentRequest()->getBaseUrl();
                         break;
                 }
                 break;
                 // Page
             // Page
             case 'page':
                 if ($elements[1] == 'pageTitle' && $objPage->pageTitle == '') {
                     $elements[1] = 'title';
                 } elseif ($elements[1] == 'parentPageTitle' && $objPage->parentPageTitle == '') {
                     $elements[1] = 'parentTitle';
                 } elseif ($elements[1] == 'mainPageTitle' && $objPage->mainPageTitle == '') {
                     $elements[1] = 'mainTitle';
                 }
                 // Do not use \StringUtil::specialchars() here (see #4687)
                 $arrCache[$strTag] = $objPage->{$elements[1]};
                 break;
                 // User agent
             // User agent
             case 'ua':
                 $ua = \Environment::get('agent');
                 if ($elements[1] != '') {
                     $arrCache[$strTag] = $ua->{$elements[1]};
                 } else {
                     $arrCache[$strTag] = '';
                 }
                 break;
                 // Abbreviations
             // Abbreviations
             case 'abbr':
             case 'acronym':
                 if ($elements[1] != '') {
                     $arrCache[$strTag] = '<abbr title="' . $elements[1] . '">';
                 } else {
                     $arrCache[$strTag] = '</abbr>';
                 }
                 break;
                 // Images
             // Images
             case 'image':
             case 'picture':
                 $width = null;
                 $height = null;
                 $alt = '';
                 $class = '';
                 $rel = '';
                 $strFile = $elements[1];
                 $mode = '';
                 $size = null;
                 $strTemplate = 'picture_default';
                 // Take arguments
                 if (strpos($elements[1], '?') !== false) {
                     $arrChunks = explode('?', urldecode($elements[1]), 2);
                     $strSource = \StringUtil::decodeEntities($arrChunks[1]);
                     $strSource = str_replace('[&]', '&', $strSource);
                     $arrParams = explode('&', $strSource);
                     foreach ($arrParams as $strParam) {
                         list($key, $value) = explode('=', $strParam);
                         switch ($key) {
                             case 'width':
                                 $width = $value;
                                 break;
                             case 'height':
                                 $height = $value;
                                 break;
                             case 'alt':
                                 $alt = \StringUtil::specialchars($value);
                                 break;
                             case 'class':
                                 $class = $value;
                                 break;
                             case 'rel':
                                 $rel = $value;
                                 break;
                             case 'mode':
                                 $mode = $value;
                                 break;
                             case 'size':
                                 $size = (int) $value;
                                 break;
                             case 'template':
                                 $strTemplate = preg_replace('/[^a-z0-9_]/i', '', $value);
                                 break;
                         }
                     }
                     $strFile = $arrChunks[0];
                 }
                 if (\Validator::isUuid($strFile)) {
                     // Handle UUIDs
                     $objFile = \FilesModel::findByUuid($strFile);
                     if ($objFile === null) {
                         $arrCache[$strTag] = '';
                         break;
                     }
                     $strFile = $objFile->path;
                 } elseif (is_numeric($strFile)) {
                     // Handle numeric IDs (see #4805)
                     $objFile = \FilesModel::findByPk($strFile);
                     if ($objFile === null) {
                         $arrCache[$strTag] = '';
                         break;
                     }
                     $strFile = $objFile->path;
                 } else {
                     // Check the path
                     if (\Validator::isInsecurePath($strFile)) {
                         throw new \RuntimeException('Invalid path ' . $strFile);
                     }
                 }
                 // Check the maximum image width
                 if (\Config::get('maxImageWidth') > 0 && $width > \Config::get('maxImageWidth')) {
                     $width = \Config::get('maxImageWidth');
                     $height = null;
                 }
                 // Generate the thumbnail image
                 try {
                     // Image
                     if (strtolower($elements[0]) == 'image') {
                         $dimensions = '';
                         $imageObj = \Image::create($strFile, array($width, $height, $mode));
                         $src = $imageObj->executeResize()->getResizedPath();
                         $objFile = new \File(rawurldecode($src));
                         // Add the image dimensions
                         if (($imgSize = $objFile->imageSize) !== false) {
                             $dimensions = ' width="' . $imgSize[0] . '" height="' . $imgSize[1] . '"';
                         }
                         $arrCache[$strTag] = '<img src="' . TL_FILES_URL . $src . '" ' . $dimensions . ' alt="' . $alt . '"' . ($class != '' ? ' class="' . $class . '"' : '') . '>';
                     } else {
                         $picture = \Picture::create($strFile, array(0, 0, $size))->getTemplateData();
                         $picture['alt'] = $alt;
                         $picture['class'] = $class;
                         $pictureTemplate = new \FrontendTemplate($strTemplate);
                         $pictureTemplate->setData($picture);
                         $arrCache[$strTag] = $pictureTemplate->parse();
                     }
                     // Add a lightbox link
                     if ($rel != '') {
                         if (strncmp($rel, 'lightbox', 8) !== 0) {
                             $attribute = ' rel="' . $rel . '"';
                         } else {
                             $attribute = ' data-lightbox="' . substr($rel, 8) . '"';
                         }
                         $arrCache[$strTag] = '<a href="' . TL_FILES_URL . $strFile . '"' . ($alt != '' ? ' title="' . $alt . '"' : '') . $attribute . '>' . $arrCache[$strTag] . '</a>';
                     }
                 } catch (\Exception $e) {
                     $arrCache[$strTag] = '';
                 }
                 break;
                 // Files (UUID or template path)
             // Files (UUID or template path)
             case 'file':
                 if (\Validator::isUuid($elements[1])) {
                     $objFile = \FilesModel::findByUuid($elements[1]);
                     if ($objFile !== null) {
                         $arrCache[$strTag] = $objFile->path;
                         break;
                     }
                 }
                 $arrGet = $_GET;
                 \Input::resetCache();
                 $strFile = $elements[1];
                 // Take arguments and add them to the $_GET array
                 if (strpos($elements[1], '?') !== false) {
                     $arrChunks = explode('?', urldecode($elements[1]));
                     $strSource = \StringUtil::decodeEntities($arrChunks[1]);
                     $strSource = str_replace('[&]', '&', $strSource);
                     $arrParams = explode('&', $strSource);
                     foreach ($arrParams as $strParam) {
                         $arrParam = explode('=', $strParam);
                         $_GET[$arrParam[0]] = $arrParam[1];
                     }
                     $strFile = $arrChunks[0];
                 }
                 // Check the path
                 if (\Validator::isInsecurePath($strFile)) {
                     throw new \RuntimeException('Invalid path ' . $strFile);
                 }
                 // Include .php, .tpl, .xhtml and .html5 files
                 if (preg_match('/\\.(php|tpl|xhtml|html5)$/', $strFile) && file_exists(TL_ROOT . '/templates/' . $strFile)) {
                     ob_start();
                     include TL_ROOT . '/templates/' . $strFile;
                     $arrCache[$strTag] = ob_get_clean();
                 }
                 $_GET = $arrGet;
                 \Input::resetCache();
                 break;
                 // HOOK: pass unknown tags to callback functions
             // HOOK: pass unknown tags to callback functions
             default:
                 if (isset($GLOBALS['TL_HOOKS']['replaceInsertTags']) && is_array($GLOBALS['TL_HOOKS']['replaceInsertTags'])) {
                     foreach ($GLOBALS['TL_HOOKS']['replaceInsertTags'] as $callback) {
                         $this->import($callback[0]);
                         $varValue = $this->{$callback[0]}->{$callback[1]}($tag, $blnCache, $arrCache[$strTag], $flags, $tags, $arrCache, $_rit, $_cnt);
                         // see #6672
                         // Replace the tag and stop the loop
                         if ($varValue !== false) {
                             $arrCache[$strTag] = $varValue;
                             break;
                         }
                     }
                 }
                 if (\Config::get('debugMode')) {
                     $GLOBALS['TL_DEBUG']['unknown_insert_tags'][] = $strTag;
                 }
                 break;
         }
         // Handle the flags
         if (!empty($flags)) {
             foreach ($flags as $flag) {
                 switch ($flag) {
                     case 'addslashes':
                     case 'stripslashes':
                     case 'standardize':
                     case 'ampersand':
                     case 'specialchars':
                     case 'nl2br':
                     case 'nl2br_pre':
                     case 'strtolower':
                     case 'utf8_strtolower':
                     case 'strtoupper':
                     case 'utf8_strtoupper':
                     case 'ucfirst':
                     case 'lcfirst':
                     case 'ucwords':
                     case 'trim':
                     case 'rtrim':
                     case 'ltrim':
                     case 'utf8_romanize':
                     case 'strrev':
                     case 'urlencode':
                     case 'rawurlencode':
                         $arrCache[$strTag] = $flag($arrCache[$strTag]);
                         break;
                     case 'encodeEmail':
                     case 'decodeEntities':
                         $arrCache[$strTag] = \StringUtil::$flag($arrCache[$strTag]);
                         break;
                     case 'number_format':
                         $arrCache[$strTag] = \System::getFormattedNumber($arrCache[$strTag], 0);
                         break;
                     case 'currency_format':
                         $arrCache[$strTag] = \System::getFormattedNumber($arrCache[$strTag], 2);
                         break;
                     case 'readable_size':
                         $arrCache[$strTag] = \System::getReadableSize($arrCache[$strTag]);
                         break;
                     case 'flatten':
                         if (!is_array($arrCache[$strTag])) {
                             break;
                         }
                         $it = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arrCache[$strTag]));
                         $result = array();
                         foreach ($it as $leafValue) {
                             $keys = array();
                             foreach (range(0, $it->getDepth()) as $depth) {
                                 $keys[] = $it->getSubIterator($depth)->key();
                             }
                             $result[] = implode('.', $keys) . ': ' . $leafValue;
                         }
                         $arrCache[$strTag] = implode(', ', $result);
                         break;
                         // HOOK: pass unknown flags to callback functions
                     // HOOK: pass unknown flags to callback functions
                     default:
                         if (isset($GLOBALS['TL_HOOKS']['insertTagFlags']) && is_array($GLOBALS['TL_HOOKS']['insertTagFlags'])) {
                             foreach ($GLOBALS['TL_HOOKS']['insertTagFlags'] as $callback) {
                                 $this->import($callback[0]);
                                 $varValue = $this->{$callback[0]}->{$callback[1]}($flag, $tag, $arrCache[$strTag], $flags, $blnCache, $tags, $arrCache, $_rit, $_cnt);
                                 // see #5806
                                 // Replace the tag and stop the loop
                                 if ($varValue !== false) {
                                     $arrCache[$strTag] = $varValue;
                                     break;
                                 }
                             }
                         }
                         if (\Config::get('debugMode')) {
                             $GLOBALS['TL_DEBUG']['unknown_insert_tag_flags'][] = $flag;
                         }
                         break;
                 }
             }
         }
         $strBuffer .= $arrCache[$strTag];
     }
     return \StringUtil::restoreBasicEntities($strBuffer);
 }
コード例 #28
0
    /**
     * Create a new template
     *
     * @return string
     */
    public function addNewTemplate()
    {
        $arrAllTemplates = array();
        $arrAllowed = StringUtil::trimsplit(',', strtolower(Config::get('templateFiles')));
        /** @var SplFileInfo[] $files */
        $files = System::getContainer()->get('contao.resource_finder')->findIn('templates')->files()->name('/\\.(' . implode('|', $arrAllowed) . ')$/');
        foreach ($files as $file) {
            $strRelpath = str_replace(TL_ROOT . DIRECTORY_SEPARATOR, '', $file->getPathname());
            $strModule = preg_replace('@^(vendor|system/modules)/([^/]+(/.*-bundle)?)/.*$@', '$2', strtr($strRelpath, '\\', '/'));
            $arrAllTemplates[$strModule][$strRelpath] = basename($strRelpath);
        }
        $strError = '';
        // Copy an existing template
        if (Input::post('FORM_SUBMIT') == 'tl_create_template') {
            $strOriginal = Input::post('original', true);
            if (Validator::isInsecurePath($strOriginal)) {
                throw new RuntimeException('Invalid path ' . $strOriginal);
            }
            $strTarget = Input::post('target', true);
            if (Validator::isInsecurePath($strTarget)) {
                throw new RuntimeException('Invalid path ' . $strTarget);
            }
            // Validate the target path
            if (strncmp($strTarget, 'templates', 9) !== 0 || !is_dir(TL_ROOT . '/' . $strTarget)) {
                $strError = sprintf($GLOBALS['TL_LANG']['tl_templates']['invalid'], $strTarget);
            } else {
                $blnFound = false;
                // Validate the source path
                foreach ($arrAllTemplates as $arrTemplates) {
                    if (isset($arrTemplates[$strOriginal])) {
                        $blnFound = true;
                        break;
                    }
                }
                if (!$blnFound) {
                    $strError = sprintf($GLOBALS['TL_LANG']['tl_templates']['invalid'], $strOriginal);
                } else {
                    $strTarget .= '/' . basename($strOriginal);
                    // Check whether the target file exists
                    if (file_exists(TL_ROOT . '/' . $strTarget)) {
                        $strError = sprintf($GLOBALS['TL_LANG']['tl_templates']['exists'], $strTarget);
                    } else {
                        $this->import('Files');
                        $this->Files->copy($strOriginal, $strTarget);
                        $this->redirect($this->getReferer());
                    }
                }
            }
        }
        $strAllTemplates = '';
        // Group the templates by module
        foreach ($arrAllTemplates as $k => $v) {
            $strAllTemplates .= '<optgroup label="' . $k . '">';
            foreach ($v as $kk => $vv) {
                $strAllTemplates .= sprintf('<option value="%s"%s>%s</option>', $kk, Input::post('original') == $kk ? ' selected="selected"' : '', $vv);
            }
            $strAllTemplates .= '</optgroup>';
        }
        // Show form
        return '
<div id="tl_buttons">
<a href="' . $this->getReferer(true) . '" class="header_back" title="' . StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['backBTTitle']) . '" accesskey="b" onclick="Backend.getScrollOffset()">' . $GLOBALS['TL_LANG']['MSC']['backBT'] . '</a>
</div>' . ($strError != '' ? '

<div class="tl_message">
<p class="tl_error">' . $strError . '</p>
</div>' : '') . '

<form action="' . ampersand(Environment::get('request')) . '" id="tl_create_template" class="tl_form" method="post">
<div class="tl_formbody_edit">
<input type="hidden" name="FORM_SUBMIT" value="tl_create_template">
<input type="hidden" name="REQUEST_TOKEN" value="' . REQUEST_TOKEN . '">
<fieldset class="tl_tbox nolegend">
<div>
  <h3><label for="ctrl_original">' . $GLOBALS['TL_LANG']['tl_templates']['original'][0] . '</label></h3>
  <select name="original" id="ctrl_original" class="tl_select tl_chosen" onfocus="Backend.getScrollOffset()">' . $strAllTemplates . '</select>' . ($GLOBALS['TL_LANG']['tl_templates']['original'][1] && Config::get('showHelp') ? '
  <p class="tl_help tl_tip">' . $GLOBALS['TL_LANG']['tl_templates']['original'][1] . '</p>' : '') . '
</div>
<div>
  <h3><label for="ctrl_target">' . $GLOBALS['TL_LANG']['tl_templates']['target'][0] . '</label></h3>
  <select name="target" id="ctrl_target" class="tl_select" onfocus="Backend.getScrollOffset()"><option value="templates">templates</option>' . $this->getTargetFolders('templates') . '</select>' . ($GLOBALS['TL_LANG']['tl_templates']['target'][1] && Config::get('showHelp') ? '
  <p class="tl_help tl_tip">' . $GLOBALS['TL_LANG']['tl_templates']['target'][1] . '</p>' : '') . '
</div>
</fieldset>
</div>

<div class="tl_formbody_submit">
<div class="tl_submit_container">
  <button type="submit" name="create" id="create" class="tl_submit" accesskey="s">' . $GLOBALS['TL_LANG']['tl_templates']['newTpl'] . '</button>
</div>
</div>
</form>';
    }
コード例 #29
0
ファイル: Message.php プロジェクト: contao/core-bundle
 /**
  * Check if there are raw messages
  *
  * @param string $strScope An optional message scope
  *
  * @return boolean True if there are raw messages
  */
 public static function hasRaw($strScope = TL_MODE)
 {
     return \System::getContainer()->get('session')->getFlashBag()->has(static::getFlashBagKey('raw', $strScope));
 }
コード例 #30
0
ファイル: Updater.php プロジェクト: Mozan/core-bundle
 /**
  * Update all FileTree fields
  */
 public function updateFileTreeFields()
 {
     $processed = array();
     /** @var SplFileInfo[] $files */
     $files = \System::getContainer()->get('contao.resource_finder')->findIn('dca')->depth(0)->files()->name('*.php');
     foreach ($files as $file) {
         if (in_array($file->getBasename(), $processed)) {
             continue;
         }
         $strTable = $file->getBasename('.php');
         try {
             $this->loadDataContainer($strTable);
         } catch (\Exception $e) {
             continue;
         }
         $arrConfig =& $GLOBALS['TL_DCA'][$strTable]['config'];
         // Skip non-database DCAs
         if ($arrConfig['dataContainer'] == 'File') {
             continue;
         }
         if ($arrConfig['dataContainer'] == 'Folder' && !$arrConfig['databaseAssisted']) {
             continue;
         }
         // Make sure there are fields (see #6437)
         if (is_array($GLOBALS['TL_DCA'][$strTable]['fields'])) {
             foreach ($GLOBALS['TL_DCA'][$strTable]['fields'] as $strField => $arrField) {
                 if ($arrField['inputType'] == 'fileTree') {
                     if ($this->Database->fieldExists($strField, $strTable, true)) {
                         $key = $arrField['eval']['multiple'] ? 'multiple' : 'single';
                         $arrFields[$key][] = $strTable . '.' . $strField;
                     }
                     // Convert the order fields as well
                     if (isset($arrField['eval']['orderField']) && isset($GLOBALS['TL_DCA'][$strTable]['fields'][$arrField['eval']['orderField']])) {
                         if ($this->Database->fieldExists($arrField['eval']['orderField'], $strTable, true)) {
                             $arrFields['order'][] = $strTable . '.' . $arrField['eval']['orderField'];
                         }
                     }
                 }
             }
         }
     }
     // Update the existing singleSRC entries
     if (isset($arrFields['single'])) {
         foreach ($arrFields['single'] as $val) {
             list($table, $field) = explode('.', $val);
             static::convertSingleField($table, $field);
         }
     }
     // Update the existing multiSRC entries
     if (isset($arrFields['multiple'])) {
         foreach ($arrFields['multiple'] as $val) {
             list($table, $field) = explode('.', $val);
             static::convertMultiField($table, $field);
         }
     }
     // Update the existing orderField entries
     if (isset($arrFields['order'])) {
         foreach ($arrFields['order'] as $val) {
             list($table, $field) = explode('.', $val);
             static::convertOrderField($table, $field);
         }
     }
 }