The class functions as an adapter for the global input arrays ($_GET, $_POST, $_COOKIE) and safely returns their values. To prevent XSS vulnerabilities, you should always use the class when reading user input. Usage: if (Input::get('action') == 'register') { $username = Input::post('username'); $password = Input::post('password'); }
 /**
  * Run the controller and parse the template
  *
  * @return Response
  */
 public function run()
 {
     /** @var \BackendTemplate|object $objTemplate */
     $objTemplate = new \BackendTemplate('be_preview');
     $objTemplate->base = \Environment::get('base');
     $objTemplate->language = $GLOBALS['TL_LANGUAGE'];
     $objTemplate->title = specialchars($GLOBALS['TL_LANG']['MSC']['fePreview']);
     $objTemplate->charset = \Config::get('characterSet');
     $objTemplate->site = \Input::get('site', true);
     $objTemplate->switchHref = \System::getContainer()->get('router')->generate('contao_backend_switch');
     if (\Input::get('url')) {
         $objTemplate->url = \Environment::get('base') . \Input::get('url');
     } elseif (\Input::get('page')) {
         $objTemplate->url = $this->redirectToFrontendPage(\Input::get('page'), \Input::get('article'), true);
     } else {
         $objTemplate->url = \System::getContainer()->get('router')->generate('contao_root', [], UrlGeneratorInterface::ABSOLUTE_URL);
     }
     // Switch to a particular member (see #6546)
     if (\Input::get('user') && $this->User->isAdmin) {
         $objUser = \MemberModel::findByUsername(\Input::get('user'));
         if ($objUser !== null) {
             $strHash = $this->getSessionHash('FE_USER_AUTH');
             // Remove old sessions
             $this->Database->prepare("DELETE FROM tl_session WHERE tstamp<? OR hash=?")->execute(time() - \Config::get('sessionTimeout'), $strHash);
             // Insert the new session
             $this->Database->prepare("INSERT INTO tl_session (pid, tstamp, name, sessionID, ip, hash) VALUES (?, ?, ?, ?, ?, ?)")->execute($objUser->id, time(), 'FE_USER_AUTH', \System::getContainer()->get('session')->getId(), \Environment::get('ip'), $strHash);
             // Set the cookie
             $this->setCookie('FE_USER_AUTH', $strHash, time() + \Config::get('sessionTimeout'), null, null, false, true);
             $objTemplate->user = \Input::post('user');
         }
     }
     return $objTemplate->getResponse();
 }
 /**
  * Redirect to the content page when trying to access the content node.
  *
  * This fixes the edit links on the header.
  *
  * @return void
  */
 public function redirect()
 {
     if ($this->input->get('table') === 'tl_content_node') {
         $model = \ContentModel::findByPk($this->input->get('id'));
         if (!$model) {
             \Controller::log(sprintf('Content node "%s" not found', $this->input->get('id')), __METHOD__, TL_ERROR);
             \Controller::redirect('contao/main.php?act=error');
         }
         $nodes = $model->ptable === 'tl_content_node' ? '1' : '';
         $url = \Backend::addToUrl('table=tl_content&amp;nodes=' . $nodes);
         \Controller::redirect($url);
     }
 }
Example #3
0
 /**
  * Run the controller and parse the login template
  *
  * @return Response
  */
 public function run()
 {
     /** @var BackendTemplate|object $objTemplate */
     $objTemplate = new \BackendTemplate('be_login');
     $strHeadline = sprintf($GLOBALS['TL_LANG']['MSC']['loginTo'], \Config::get('websiteTitle'));
     $objTemplate->theme = \Backend::getTheme();
     $objTemplate->messages = \Message::generate();
     $objTemplate->base = \Environment::get('base');
     $objTemplate->language = $GLOBALS['TL_LANGUAGE'];
     $objTemplate->languages = \System::getLanguages(true);
     $objTemplate->title = \StringUtil::specialchars($strHeadline);
     $objTemplate->charset = \Config::get('characterSet');
     $objTemplate->action = ampersand(\Environment::get('request'));
     $objTemplate->userLanguage = $GLOBALS['TL_LANG']['tl_user']['language'][0];
     $objTemplate->headline = $strHeadline;
     $objTemplate->curLanguage = \Input::post('language') ?: str_replace('-', '_', $GLOBALS['TL_LANGUAGE']);
     $objTemplate->curUsername = \Input::post('username') ?: '';
     $objTemplate->uClass = $_POST && empty($_POST['username']) ? ' class="login_error"' : '';
     $objTemplate->pClass = $_POST && empty($_POST['password']) ? ' class="login_error"' : '';
     $objTemplate->loginButton = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['loginBT']);
     $objTemplate->username = $GLOBALS['TL_LANG']['tl_user']['username'][0];
     $objTemplate->password = $GLOBALS['TL_LANG']['MSC']['password'][0];
     $objTemplate->feLink = $GLOBALS['TL_LANG']['MSC']['feLink'];
     $objTemplate->default = $GLOBALS['TL_LANG']['MSC']['default'];
     $objTemplate->jsDisabled = $GLOBALS['TL_LANG']['MSC']['jsDisabled'];
     return $objTemplate->getResponse();
 }
Example #4
0
 /**
  * @param $id
  * @param \Contao\DataContainer $dca
  */
 public function onCopyAddFView($id, \Contao\DataContainer $dca)
 {
     $view = \Contao\Input::get('view');
     if ($id && $view) {
         $this->Database->prepare('UPDATE tl_content SET fview = ? WHERE id = ? LIMIT 1')->execute($view, $id);
     }
 }
Example #5
0
 /**
  * F Module Ajax Api
  * More: http://fmodul.alexandernaumov.de/ressourcen.html
  */
 public function getAjaxResponse()
 {
     $action = Input::get('do');
     if ($action) {
         switch ($action) {
             case 'getEntities':
                 $this->getEntities();
                 break;
             case 'getDetail':
                 $this->getDetail();
                 break;
             case 'getAutoCompletion':
                 $this->getAutoCompletion();
                 break;
             default:
                 $this->getDefault();
                 break;
         }
     } else {
         header('HTTP/1.1 500 Internal Server');
         header('Content-Type: application/json; charset=UTF-8');
         echo json_encode(array("No method defined"));
         exit;
     }
 }
Example #6
0
 /**
  * @param $intId
  * @param $blnVisible
  * @param DataContainer|null $dc
  */
 public function toggleVisibility($intId, $blnVisible, DataContainer $dc = null)
 {
     // Set the ID and action
     Input::setGet('id', $intId);
     Input::setGet('act', 'toggle');
     if ($dc) {
         $dc->id = $intId;
         // see #8043
     }
     // Check the field access
     if (!$this->User->hasAccess('tl_api_client::disable', 'alexf')) {
         throw new AccessDeniedException('Not enough permissions to activate/deactivate member ID ' . $intId . '.');
     }
     $objVersions = new Versions('tl_api_client', $intId);
     $objVersions->initialize();
     // Trigger the save_callback
     if (is_array($GLOBALS['TL_DCA']['tl_api_client']['fields']['disable']['save_callback'])) {
         foreach ($GLOBALS['TL_DCA']['tl_api_client']['fields']['disable']['save_callback'] as $callback) {
             if (is_array($callback)) {
                 $this->import($callback[0]);
                 $blnVisible = $this->{$callback[0]}->{$callback[1]}($blnVisible, $dc ?: $this);
             } elseif (is_callable($callback)) {
                 $blnVisible = $callback($blnVisible, $dc ?: $this);
             }
         }
     }
     $time = time();
     // Update the database
     $this->Database->prepare("UPDATE tl_api_client SET tstamp={$time}, disable='" . ($blnVisible ? '' : 1) . "' WHERE id=?")->execute($intId);
     $objVersions->create();
     $this->log('A new version of record "tl_api_client.id=' . $intId . '" has been created' . $this->getParentEntries('tl_api_client', $intId), __METHOD__, TL_GENERAL);
 }
 /**
  * Remove the recipient
  */
 protected function removeSubscriber()
 {
     $varInput = Idna::encodeEmail(Input::get('email', true));
     // Validate e-mail address
     if (!Validator::isEmail($varInput)) {
         $_SESSION['UNSUBSCRIBE_ERROR'] = $GLOBALS['TL_LANG']['ERR']['email'];
         $this->redirect($this->generateFrontendUrl($this->objModel->getRelated('jumpTo')->row()));
     }
     $objCleverReach = new CleverReach();
     switch ($this->clr_unsubscribe) {
         case 'inactive':
             foreach ($this->clr_groups as $strGroupId) {
                 $objCleverReach->receiverSetInactive($varInput, $strGroupId);
             }
             break;
         case 'delete':
             foreach ($this->clr_groups as $strGroupId) {
                 $objCleverReach->receiverDelete($varInput, $strGroupId);
             }
             break;
         case 'email':
         default:
             $objCleverReach->sendUnsubscribeMail($varInput, $this->clr_form);
             break;
     }
     $this->redirect($this->generateFrontendUrl($this->objModel->getRelated('jumpTo')->row()));
 }
Example #8
0
 /**
  * Generate the module
  *
  * @return string
  */
 public function run()
 {
     $arrJobs = array();
     /** @var BackendTemplate|object $objTemplate */
     $objTemplate = new \BackendTemplate('be_purge_data');
     $objTemplate->isActive = $this->isActive();
     $objTemplate->message = \Message::generateUnwrapped();
     // Run the jobs
     if (\Input::post('FORM_SUBMIT') == 'tl_purge') {
         $purge = \Input::post('purge');
         if (!empty($purge) && is_array($purge)) {
             foreach ($purge as $group => $jobs) {
                 foreach ($jobs as $job) {
                     list($class, $method) = $GLOBALS['TL_PURGE'][$group][$job]['callback'];
                     $this->import($class);
                     $this->{$class}->{$method}();
                 }
             }
         }
         \Message::addConfirmation($GLOBALS['TL_LANG']['tl_maintenance']['cacheCleared']);
         $this->reload();
     }
     // Tables
     foreach ($GLOBALS['TL_PURGE']['tables'] as $key => $config) {
         $arrJobs[$key] = array('id' => 'purge_' . $key, 'title' => $GLOBALS['TL_LANG']['tl_maintenance_jobs'][$key][0], 'description' => $GLOBALS['TL_LANG']['tl_maintenance_jobs'][$key][1], 'group' => 'tables', 'affected' => '');
         // Get the current table size
         foreach ($config['affected'] as $table) {
             $objCount = $this->Database->execute("SELECT COUNT(*) AS count FROM " . $table);
             $arrJobs[$key]['affected'] .= '<br>' . $table . ': <span>' . sprintf($GLOBALS['TL_LANG']['MSC']['entries'], $objCount->count) . ', ' . $this->getReadableSize($this->Database->getSizeOf($table), 0) . '</span>';
         }
     }
     $strCachePath = str_replace(TL_ROOT . DIRECTORY_SEPARATOR, '', \System::getContainer()->getParameter('kernel.cache_dir'));
     // Folders
     foreach ($GLOBALS['TL_PURGE']['folders'] as $key => $config) {
         $arrJobs[$key] = array('id' => 'purge_' . $key, 'title' => $GLOBALS['TL_LANG']['tl_maintenance_jobs'][$key][0], 'description' => $GLOBALS['TL_LANG']['tl_maintenance_jobs'][$key][1], 'group' => 'folders', 'affected' => '');
         // Get the current folder size
         foreach ($config['affected'] as $folder) {
             $total = 0;
             $folder = sprintf($folder, $strCachePath);
             // Only check existing folders
             if (is_dir(TL_ROOT . '/' . $folder)) {
                 $objFiles = Finder::create()->in(TL_ROOT . '/' . $folder)->files();
                 $total = iterator_count($objFiles);
             }
             $arrJobs[$key]['affected'] .= '<br>' . $folder . ': <span>' . sprintf($GLOBALS['TL_LANG']['MSC']['files'], $total) . '</span>';
         }
     }
     // Custom
     foreach ($GLOBALS['TL_PURGE']['custom'] as $key => $job) {
         $arrJobs[$key] = array('id' => 'purge_' . $key, 'title' => $GLOBALS['TL_LANG']['tl_maintenance_jobs'][$key][0], 'description' => $GLOBALS['TL_LANG']['tl_maintenance_jobs'][$key][1], 'group' => 'custom');
     }
     $objTemplate->jobs = $arrJobs;
     $objTemplate->action = ampersand(\Environment::get('request'));
     $objTemplate->headline = $GLOBALS['TL_LANG']['tl_maintenance']['clearCache'];
     $objTemplate->job = $GLOBALS['TL_LANG']['tl_maintenance']['job'];
     $objTemplate->description = $GLOBALS['TL_LANG']['tl_maintenance']['description'];
     $objTemplate->submit = \StringUtil::specialchars($GLOBALS['TL_LANG']['tl_maintenance']['clearCache']);
     $objTemplate->help = \Config::get('showHelp') && $GLOBALS['TL_LANG']['tl_maintenance']['cacheTables'][1] != '' ? $GLOBALS['TL_LANG']['tl_maintenance']['cacheTables'][1] : '';
     return $objTemplate->parse();
 }
 /**
  * Generate the module
  */
 protected function compile()
 {
     /** @var PageModel $objPage */
     global $objPage;
     $this->Template->content = '';
     $this->Template->referer = 'javascript:history.go(-1)';
     $this->Template->back = $GLOBALS['TL_LANG']['MSC']['goBack'];
     $objNewsletter = \NewsletterModel::findSentByParentAndIdOrAlias(\Input::get('items'), $this->nl_channels);
     if (null === $objNewsletter) {
         throw new PageNotFoundException('Page not found: ' . \Environment::get('uri'));
     }
     // Overwrite the page title (see #2853 and #4955)
     if ($objNewsletter->subject != '') {
         $objPage->pageTitle = strip_tags(\StringUtil::stripInsertTags($objNewsletter->subject));
     }
     // Add enclosure
     if ($objNewsletter->addFile) {
         $this->addEnclosuresToTemplate($this->Template, $objNewsletter->row(), 'files');
     }
     // Support plain text newsletters (thanks to Hagen Klemp)
     if ($objNewsletter->sendText) {
         $strContent = nl2br_html5($objNewsletter->text);
     } else {
         $strContent = str_ireplace(' align="center"', '', $objNewsletter->content);
     }
     // Parse simple tokens and insert tags
     $strContent = $this->replaceInsertTags($strContent);
     $strContent = \StringUtil::parseSimpleTokens($strContent, array());
     // Encode e-mail addresses
     $strContent = \StringUtil::encodeEmail($strContent);
     $this->Template->content = $strContent;
     $this->Template->subject = $objNewsletter->subject;
 }
 /**
  * Generate the module
  */
 protected function compile()
 {
     $this->import('FrontendUser', 'User');
     // Initialize the password widget
     $arrField = array('name' => 'password', 'inputType' => 'text', 'label' => $GLOBALS['TL_LANG']['MSC']['password'][0], 'eval' => array('hideInput' => true, 'mandatory' => true, 'required' => true));
     $objWidget = new \FormTextField(\FormTextField::getAttributesFromDca($arrField, $arrField['name']));
     $objWidget->rowClass = 'row_0 row_first even';
     $strFormId = 'tl_close_account_' . $this->id;
     // Validate widget
     if (\Input::post('FORM_SUBMIT') == $strFormId) {
         $objWidget->validate();
         // Validate the password
         if (!$objWidget->hasErrors()) {
             // The password has been generated with crypt()
             if (\Encryption::test($this->User->password)) {
                 $blnAuthenticated = \Encryption::verify($objWidget->value, $this->User->password);
             } else {
                 list($strPassword, $strSalt) = explode(':', $this->User->password);
                 $blnAuthenticated = $strSalt == '' ? $strPassword === sha1($objWidget->value) : $strPassword === sha1($strSalt . $objWidget->value);
             }
             if (!$blnAuthenticated) {
                 $objWidget->value = '';
                 $objWidget->addError($GLOBALS['TL_LANG']['ERR']['invalidPass']);
             }
         }
         // Close account
         if (!$objWidget->hasErrors()) {
             // HOOK: send account ID
             if (isset($GLOBALS['TL_HOOKS']['closeAccount']) && is_array($GLOBALS['TL_HOOKS']['closeAccount'])) {
                 foreach ($GLOBALS['TL_HOOKS']['closeAccount'] as $callback) {
                     $this->import($callback[0]);
                     $this->{$callback[0]}->{$callback[1]}($this->User->id, $this->reg_close, $this);
                 }
             }
             $objMember = \MemberModel::findByPk($this->User->id);
             // Remove the account
             if ($this->reg_close == 'close_delete') {
                 $objMember->delete();
                 $this->log('User account ID ' . $this->User->id . ' (' . \Idna::decodeEmail($this->User->email) . ') has been deleted', __METHOD__, TL_ACCESS);
             } else {
                 $objMember->disable = 1;
                 $objMember->tstamp = time();
                 $objMember->save();
                 $this->log('User account ID ' . $this->User->id . ' (' . \Idna::decodeEmail($this->User->email) . ') has been deactivated', __METHOD__, TL_ACCESS);
             }
             $this->User->logout();
             // Check whether there is a jumpTo page
             if (($objJumpTo = $this->objModel->getRelated('jumpTo')) instanceof PageModel) {
                 $this->jumpToOrReload($objJumpTo->row());
             }
             $this->reload();
         }
     }
     $this->Template->fields = $objWidget->parse();
     $this->Template->formId = $strFormId;
     $this->Template->action = \Environment::get('indexFreeRequest');
     $this->Template->slabel = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['closeAccount']);
     $this->Template->rowLast = 'row_1 row_last odd';
 }
Example #11
0
 public function executePreActions($strAction, DataContainer $dc)
 {
     if ($strAction === 'boxSystemChange') {
         $elementId = Input::post('id');
         $boxSystemId = Input::post('boxSystemId');
         $this->Database->prepare("UPDATE tl_content SET tstamp=" . time() . ", boxSystem='" . $boxSystemId . "' WHERE id=?")->execute($elementId);
     }
 }
 /**
  * Generate the message filter
  *
  * @return string
  */
 public function generateMessageFilter()
 {
     if (Input::post('FORM_SUBMIT') === 'tl_filters' && Input::post($this->filterName, true) !== 'tl_' . $this->filterName) {
         $session = Session::getInstance()->getData();
         $session['seo_serp_expand_tree'] = 'tl_page';
         Session::getInstance()->setData($session);
     }
     return parent::generateMessageFilter();
 }
 public function checkAccess()
 {
     $this->import('Input');
     // If no access
     if (Input::get('id') != '' && Input::get('id') != null && in_array(Input::get('id'), $this->filterFields(true))) {
         $this->log('No access on secure access data ID "' . Input::get('id') . '"', 'tl_secure_accessdata __construct', TL_ERROR);
         $this->redirect('main.php?act=error');
     }
 }
 public function getAllEvents($arrEvents, $arrCalendars, $intStart, $intEnd, \Contao\Module $objModule)
 {
     // FIXME it's possible to filter a list for categories, it doesn't allow by its configuration
     $result = array();
     $modCats = deserialize($objModule->event_categories, true);
     $hasCatCfg = is_array($modCats) && count($modCats) > 0;
     $filterParam_ar = array('category');
     $objFilterMod = Database::getInstance()->prepare("SELECT mae_event_catname FROM tl_module WHERE mae_event_catname != '' AND type='mae_event_filter' AND mae_event_list=?")->execute($objModule->id);
     while ($objFilterMod->fetchAssoc()) {
         $filterParam_ar[] = $objFilterMod->mae_event_catname;
     }
     foreach ($filterParam_ar as $paramName) {
         $filterCat = Input::get($paramName);
         if (!empty($filterCat) && $filterCat != "all") {
             if (!is_numeric($filterCat)) {
                 $objCat = Database::getInstance()->prepare("SELECT id FROM tl_mae_event_cat WHERE alias=?")->execute($filterCat);
                 if ($objCat->numRows == 1) {
                     $filterCat = $objCat->id;
                 }
             }
             if ($hasCatCfg) {
                 $modCats = array($filterCat);
                 $hasCatCfg = false;
             } else {
                 $modCats[] = $filterCat;
             }
         }
         // have filter value
     }
     // each possible category url parameter
     if (is_array($arrEvents) && count($arrEvents) > 0 && count($modCats) > 0) {
         foreach ($arrEvents as $day => $times) {
             foreach ($times as $time => $events) {
                 foreach ($events as $event) {
                     $evtCats = unserialize($event['categories']);
                     if (!is_array($evtCats)) {
                         $evtCats = array();
                     }
                     foreach ($modCats as $modCat) {
                         if (in_array($modCat, $evtCats)) {
                             $result[$day][$time][] = $event;
                             break;
                         }
                     }
                     // compare categories module <=> event
                 }
                 // event
             }
             // times
         }
         // days
     } else {
         $result = $arrEvents;
     }
     // if no category filter set
     return $result;
 }
Example #15
0
 /**
  * Redirect to an internal page
  *
  * @param \PageModel $objPage
  */
 public function generate($objPage)
 {
     // Forward to the jumpTo or first published page
     if ($objPage->jumpTo) {
         /** @var \PageModel $objNextPage */
         $objNextPage = $objPage->getRelated('jumpTo');
     } else {
         $objNextPage = \PageModel::findFirstPublishedRegularByPid($objPage->id);
     }
     // Forward page does not exist
     if ($objNextPage === null) {
         $this->log('Forward page ID "' . $objPage->jumpTo . '" does not exist', __METHOD__, TL_ERROR);
         throw new ForwardPageNotFoundException('Forward page not found');
     }
     $strForceLang = null;
     // Check the target page language (see #4706)
     if (\Config::get('addLanguageToUrl')) {
         $objNextPage->loadDetails();
         // see #3983
         $strForceLang = $objNextPage->language;
     }
     $strGet = '';
     $strQuery = \Environment::get('queryString');
     $arrQuery = array();
     // Extract the query string keys (see #5867)
     if ($strQuery != '') {
         $arrChunks = explode('&', $strQuery);
         foreach ($arrChunks as $strChunk) {
             list($k, ) = explode('=', $strChunk, 2);
             $arrQuery[] = $k;
         }
     }
     // Add $_GET parameters
     if (!empty($_GET)) {
         foreach (array_keys($_GET) as $key) {
             if (\Config::get('addLanguageToUrl') && $key == 'language') {
                 continue;
             }
             // Ignore the query string parameters (see #5867)
             if (in_array($key, $arrQuery)) {
                 continue;
             }
             // Ignore the auto_item parameter (see #5886)
             if ($key == 'auto_item') {
                 $strGet .= '/' . \Input::get($key);
             } else {
                 $strGet .= '/' . $key . '/' . \Input::get($key);
             }
         }
     }
     // Append the query string (see #5867)
     if ($strQuery != '') {
         $strQuery = '?' . $strQuery;
     }
     $this->redirect($this->generateFrontendUrl($objNextPage->row(), $strGet, $strForceLang) . $strQuery, $objPage->redirect == 'temporary' ? 302 : 301);
 }
Example #16
0
 /**
  * Generate the module
  */
 protected function compile()
 {
     $limit = null;
     $offset = intval($this->skipFirst);
     // Maximum number of items
     if ($this->numberOfItems > 0) {
         $limit = $this->numberOfItems;
     }
     // Handle featured news
     if ($this->news_featured == 'featured') {
         $blnFeatured = true;
     } elseif ($this->news_featured == 'unfeatured') {
         $blnFeatured = false;
     } else {
         $blnFeatured = null;
     }
     $this->Template->articles = array();
     $this->Template->empty = $GLOBALS['TL_LANG']['MSC']['emptyList'];
     // Get the total number of items
     $intTotal = $this->countItems($this->news_archives, $blnFeatured);
     if ($intTotal < 1) {
         return;
     }
     $total = $intTotal - $offset;
     // Split the results
     if ($this->perPage > 0 && (!isset($limit) || $this->numberOfItems > $this->perPage)) {
         // Adjust the overall limit
         if (isset($limit)) {
             $total = min($limit, $total);
         }
         // Get the current page
         $id = 'page_n' . $this->id;
         $page = \Input::get($id) !== null ? \Input::get($id) : 1;
         // Do not index or cache the page if the page number is outside the range
         if ($page < 1 || $page > max(ceil($total / $this->perPage), 1)) {
             throw new PageNotFoundException('Page not found');
         }
         // Set limit and offset
         $limit = $this->perPage;
         $offset += (max($page, 1) - 1) * $this->perPage;
         $skip = intval($this->skipFirst);
         // Overall limit
         if ($offset + $limit > $total + $skip) {
             $limit = $total + $skip - $offset;
         }
         // Add the pagination menu
         $objPagination = new \Pagination($total, $this->perPage, \Config::get('maxPaginationLinks'), $id);
         $this->Template->pagination = $objPagination->generate("\n  ");
     }
     $objArticles = $this->fetchItems($this->news_archives, $blnFeatured, $limit ?: 0, $offset);
     // Add the articles
     if ($objArticles !== null) {
         $this->Template->articles = $this->parseArticles($objArticles);
     }
     $this->Template->archives = $this->news_archives;
 }
Example #17
0
 /**
  * Generate the widget and return it as string
  *
  * @return string
  */
 public function generate()
 {
     $arrOptions = array();
     if (!$this->multiple && count($this->arrOptions) > 1) {
         $this->arrOptions = array($this->arrOptions[0]);
     }
     // The "required" attribute only makes sense for single checkboxes
     if ($this->mandatory && !$this->multiple) {
         $this->arrAttributes['required'] = 'required';
     }
     /** @var AttributeBagInterface $objSessionBag */
     $objSessionBag = \System::getContainer()->get('session')->getBag('contao_backend');
     $state = $objSessionBag->get('checkbox_groups');
     // Toggle the checkbox group
     if (\Input::get('cbc')) {
         $state[\Input::get('cbc')] = isset($state[\Input::get('cbc')]) && $state[\Input::get('cbc')] == 1 ? 0 : 1;
         $objSessionBag->set('checkbox_groups', $state);
         $this->redirect(preg_replace('/(&(amp;)?|\\?)cbc=[^& ]*/i', '', \Environment::get('request')));
     }
     $blnFirst = true;
     $blnCheckAll = true;
     foreach ($this->arrOptions as $i => $arrOption) {
         // Single dimension array
         if (is_numeric($i)) {
             $arrOptions[] = $this->generateCheckbox($arrOption, $i);
             continue;
         }
         $id = 'cbc_' . $this->strId . '_' . \StringUtil::standardize($i);
         $img = 'folPlus.svg';
         $display = 'none';
         if (!isset($state[$id]) || !empty($state[$id])) {
             $img = 'folMinus.svg';
             $display = 'block';
         }
         $arrOptions[] = '<div class="checkbox_toggler' . ($blnFirst ? '_first' : '') . '"><a href="' . $this->addToUrl('cbc=' . $id) . '" onclick="AjaxRequest.toggleCheckboxGroup(this,\'' . $id . '\');Backend.getScrollOffset();return false">' . \Image::getHtml($img) . '</a>' . $i . '</div><fieldset id="' . $id . '" class="tl_checkbox_container checkbox_options" style="display:' . $display . '"><input type="checkbox" id="check_all_' . $id . '" class="tl_checkbox" onclick="Backend.toggleCheckboxGroup(this, \'' . $id . '\')"> <label for="check_all_' . $id . '" style="color:#a6a6a6"><em>' . $GLOBALS['TL_LANG']['MSC']['selectAll'] . '</em></label>';
         // Multidimensional array
         foreach ($arrOption as $k => $v) {
             $arrOptions[] = $this->generateCheckbox($v, standardize($i) . '_' . $k);
         }
         $arrOptions[] = '</fieldset>';
         $blnFirst = false;
         $blnCheckAll = false;
     }
     // Add a "no entries found" message if there are no options
     if (empty($arrOptions)) {
         $arrOptions[] = '<p class="tl_noopt">' . $GLOBALS['TL_LANG']['MSC']['noResult'] . '</p>';
         $blnCheckAll = false;
     }
     if ($this->multiple) {
         return sprintf('<fieldset id="ctrl_%s" class="tl_checkbox_container%s"><legend>%s%s%s%s</legend><input type="hidden" name="%s" value="">%s%s</fieldset>%s', $this->strId, $this->strClass != '' ? ' ' . $this->strClass : '', $this->mandatory ? '<span class="invisible">' . $GLOBALS['TL_LANG']['MSC']['mandatory'] . ' </span>' : '', $this->strLabel, $this->mandatory ? '<span class="mandatory">*</span>' : '', $this->xlabel, $this->strName, $blnCheckAll ? '<input type="checkbox" id="check_all_' . $this->strId . '" class="tl_checkbox" onclick="Backend.toggleCheckboxGroup(this,\'ctrl_' . $this->strId . '\')' . ($this->onclick ? ';' . $this->onclick : '') . '"> <label for="check_all_' . $this->strId . '" style="color:#a6a6a6"><em>' . $GLOBALS['TL_LANG']['MSC']['selectAll'] . '</em></label><br>' : '', str_replace('<br></fieldset><br>', '</fieldset>', implode('<br>', $arrOptions)), $this->wizard);
     } else {
         return sprintf('<div id="ctrl_%s" class="tl_checkbox_single_container%s"><input type="hidden" name="%s" value="">%s</div>%s', $this->strId, $this->strClass != '' ? ' ' . $this->strClass : '', $this->strName, str_replace('<br></div><br>', '</div>', implode('<br>', $arrOptions)), $this->wizard);
     }
 }
 /**
  * Append all current palettes with the device-condition field.
  *
  * @param string $table The current table.
  *
  * @return void
  *
  * @SuppressWarnings(PHPMD.Superglobals)
  */
 public function appendPalettes($table)
 {
     if (!is_array($GLOBALS['TL_DCA'][$table]['palettes']) || (!Input::get('do') == 'article' || !Input::get('do') == 'postmanager' || Input::get('task') == 'indexmanager')) {
         return;
     }
     foreach (array_keys($GLOBALS['TL_DCA'][$table]['palettes']) as $palette) {
         if ($palette != '__selector__') {
             $GLOBALS['TL_DCA'][$table]['palettes'][$palette] .= ';{device_condition_legend},device_condition';
         }
     }
 }
Example #19
0
 /**
  * Tests the getPost() method.
  *
  * @dataProvider postProvider
  */
 public function testGetPost($key, $input, $value, $expected)
 {
     $widget = $this->getMock('Contao\\Widget');
     $class = new \ReflectionClass('Contao\\Widget');
     $method = $class->getMethod('getPost');
     $method->setAccessible(true);
     $_POST[$input] = $value;
     Input::resetCache();
     Input::initialize();
     $this->assertEquals($expected, $method->invoke($widget, $key));
 }
Example #20
0
 /**
  * Run the controller and parse the password template
  *
  * @return Response
  */
 public function run()
 {
     /** @var BackendTemplate|object $objTemplate */
     $objTemplate = new \BackendTemplate('be_password');
     if (\Input::post('FORM_SUBMIT') == 'tl_password') {
         $pw = \Input::postUnsafeRaw('password');
         $cnf = \Input::postUnsafeRaw('confirm');
         // The passwords do not match
         if ($pw != $cnf) {
             \Message::addError($GLOBALS['TL_LANG']['ERR']['passwordMatch']);
         } elseif (Utf8::strlen($pw) < \Config::get('minPasswordLength')) {
             \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['passwordLength'], \Config::get('minPasswordLength')));
         } elseif ($pw == $this->User->username) {
             \Message::addError($GLOBALS['TL_LANG']['ERR']['passwordName']);
         } else {
             // Make sure the password has been changed
             if (\Encryption::verify($pw, $this->User->password)) {
                 \Message::addError($GLOBALS['TL_LANG']['MSC']['pw_change']);
             } else {
                 $this->loadDataContainer('tl_user');
                 // Trigger the save_callback
                 if (is_array($GLOBALS['TL_DCA']['tl_user']['fields']['password']['save_callback'])) {
                     foreach ($GLOBALS['TL_DCA']['tl_user']['fields']['password']['save_callback'] as $callback) {
                         if (is_array($callback)) {
                             $this->import($callback[0]);
                             $pw = $this->{$callback[0]}->{$callback[1]}($pw);
                         } elseif (is_callable($callback)) {
                             $pw = $callback($pw);
                         }
                     }
                 }
                 $objUser = \UserModel::findByPk($this->User->id);
                 $objUser->pwChange = '';
                 $objUser->password = \Encryption::hash($pw);
                 $objUser->save();
                 \Message::addConfirmation($GLOBALS['TL_LANG']['MSC']['pw_changed']);
                 $this->redirect('contao/main.php');
             }
         }
         $this->reload();
     }
     $objTemplate->theme = \Backend::getTheme();
     $objTemplate->messages = \Message::generate();
     $objTemplate->base = \Environment::get('base');
     $objTemplate->language = $GLOBALS['TL_LANGUAGE'];
     $objTemplate->title = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['pw_new']);
     $objTemplate->charset = \Config::get('characterSet');
     $objTemplate->action = ampersand(\Environment::get('request'));
     $objTemplate->headline = $GLOBALS['TL_LANG']['MSC']['pw_change'];
     $objTemplate->submitButton = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['continue']);
     $objTemplate->password = $GLOBALS['TL_LANG']['MSC']['password'][0];
     $objTemplate->confirm = $GLOBALS['TL_LANG']['MSC']['confirm'][0];
     return $objTemplate->getResponse();
 }
Example #21
0
 /**
  * Run the controller
  *
  * @return RedirectResponse
  */
 public function run()
 {
     switch (\Input::get('p')) {
         case 'facebook':
             return new RedirectResponse('https://www.facebook.com/sharer/sharer.php' . '?u=' . rawurlencode(\Input::get('u', true)));
         case 'twitter':
             return new RedirectResponse('https://twitter.com/intent/tweet' . '?url=' . rawurlencode(\Input::get('u', true)) . '&text=' . rawurlencode(\Input::get('t', true)));
         case 'gplus':
             return new RedirectResponse('https://plus.google.com/share' . '?url=' . rawurlencode(\Input::get('u', true)));
     }
     return new RedirectResponse('../');
 }
 /**
  * Restrict the content elements.
  *
  * @param int  $contentId The id of the current content element.
  * @param Node $node      The node type.
  *
  * @return void
  * @throws AccessDeniedException When an invalid content element type is accessed.
  *
  * @SuppressWarnings(PHPMD.Superglobals)
  */
 public function restrict($contentId, Node $node = null)
 {
     $nodeType = $node ? $node->getName() : null;
     $allowedElements = $this->registry->filterContentElements($GLOBALS['TL_CTE'], $nodeType);
     if (empty($allowedElements)) {
         $this->closeDataContainer();
     } elseif (!in_array($this->definition->get('fields/type/default'), $allowedElements)) {
         $this->setDefaults($allowedElements);
     }
     if ($this->input->get('act') != '' && $this->input->get('act') !== 'select') {
         $GLOBALS['TL_CTE'] = $allowedElements;
         $this->restrictIds($allowedElements, $contentId);
     }
 }
Example #23
0
 /**
  * Tests the getPost() method.
  *
  * @param string $key
  * @param string $input
  * @param mixed  $value
  * @param string $expected
  *
  * @dataProvider postProvider
  */
 public function testGetPost($key, $input, $value, $expected)
 {
     // Prevent "undefined index" errors
     $errorReporting = error_reporting();
     error_reporting($errorReporting & ~E_NOTICE);
     $widget = $this->getMock('Contao\\Widget');
     $class = new \ReflectionClass('Contao\\Widget');
     $method = $class->getMethod('getPost');
     $method->setAccessible(true);
     $_POST[$input] = $value;
     Input::resetCache();
     Input::initialize();
     $this->assertEquals($expected, $method->invoke($widget, $key));
     // Restore the error reporting level
     error_reporting($errorReporting);
 }
Example #24
0
    /**
     * Generate the widget and return it as string
     *
     * @return string
     */
    public function generate()
    {
        $action = Input::get('actionPSTag');
        $tags = Input::get('ps_tags');
        $requestUri = Environment::get('requestUri');
        $requestUri = Helper::removeRequestTokenFromUri($requestUri);
        if ($action && $action == 'updateTags') {
            $this->updateTags($tags);
        }
        if ($action && $action == 'removeTags') {
            $this->removeTags($tags);
        }
        $GLOBALS['TL_JAVASCRIPT'][] = $GLOBALS['PS_PUBLIC_PATH'] . 'vendor/mootagify.js|static';
        $GLOBALS['TL_CSS'][] = $GLOBALS['PS_PUBLIC_PATH'] . 'css/mootagify-bootstrap.css|static';
        $GLOBALS['TL_CSS'][] = $GLOBALS['PS_PUBLIC_PATH'] . 'css/mootagify.css|static';
        $options = $this->options ? $this->options : array();
        $script = sprintf('<script>' . 'window.addEvent("domready", function(){

                var tagify = new mooTagify(document.id("tagWrap_%s"), null ,{
                    autoSuggest: true,
                    availableOptions: ' . json_encode($options) . '
                });

                tagify.addEvent("tagsUpdate", function(){

                    var tags = tagify.getTags();
                    document.id("ctrl_%s").set("value", tags.join());

                    new Request({url: "%s&actionPSTag=updateTags"}).get({"ps_tags": tags, "rt": Contao.request_token });

                });

                tagify.addEvent("tagRemove", function(tag){

                    var tags = tagify.getTags()

                    var deleted = tag;

                    document.id("ctrl_%s").set("value", tags.join());

                    new Request({url: "%s&actionPSTag=removeTags"}).get({ "ps_tags": deleted, "rt": Contao.request_token });

                });
            });' . '</script>', $this->strId, $this->strId, $requestUri, $this->strId, $requestUri);
        return sprintf('<input type="hidden" id="ctrl_%s" name="%s" value="%s"><div id="tagWrap_%s" class="hide"> <div class="tag-wrapper"></div> <div class="tag-input"> <input type="text" id="listTags" class="tl_text" name="listTags" value="%s" placeholder="%s"> </div> <div class="clear"></div></div>' . $script . '', $this->strId, $this->strName, specialchars($this->varValue), $this->strId, specialchars($this->varValue), $GLOBALS['TL_LANG']['MSC']['TagTextField']['tag']);
    }
 protected function compile()
 {
     global $objPage;
     // Get the current event
     $objEvent = CalendarEventsModel::findPublishedByParentAndIdOrAlias(Input::get('events'), $this->cal_calendar);
     if ($objEvent === null) {
         parent::compile();
     }
     $objPage->canonicalType = $objEvent->canonicalType;
     $objPage->canonicalJumpTo = $objEvent->canonicalJumpTo;
     $objPage->canonicalWebsite = $objEvent->canonicalWebsite;
     if ($objEvent->canonicalType == 'self') {
         $objPage->canonicalType = 'external';
         $objPage->canonicalWebsite = Environment::get('url') . TL_PATH . '/' . Environment::get('request');
     }
     parent::compile();
 }
 protected function compile()
 {
     global $objPage;
     // Get the current news item
     $objNewsItem = NewsModel::findPublishedByParentAndIdOrAlias(Input::get('items'), $this->news_archives);
     if ($objNewsItem === null) {
         parent::compile();
     }
     $objPage->canonicalType = $objNewsItem->canonicalType;
     $objPage->canonicalJumpTo = $objNewsItem->canonicalJumpTo;
     $objPage->canonicalWebsite = $objNewsItem->canonicalWebsite;
     if ($objNewsItem->canonicalType == 'self') {
         $objPage->canonicalType = 'external';
         $objPage->canonicalWebsite = Environment::get('url') . TL_PATH . '/' . Environment::get('request');
     }
     parent::compile();
 }
 /**
  * Redirect to the selected page
  *
  * @return string
  */
 public function generate()
 {
     if (TL_MODE == 'BE') {
         /** @var BackendTemplate|object $objTemplate */
         $objTemplate = new \BackendTemplate('be_wildcard');
         $objTemplate->wildcard = '### ' . Utf8::strtoupper($GLOBALS['TL_LANG']['FMD']['quicknav'][0]) . ' ###';
         $objTemplate->title = $this->headline;
         $objTemplate->id = $this->id;
         $objTemplate->link = $this->name;
         $objTemplate->href = 'contao/main.php?do=themes&amp;table=tl_module&amp;act=edit&amp;id=' . $this->id;
         return $objTemplate->parse();
     }
     if (\Input::post('FORM_SUBMIT') == 'tl_quicknav_' . $this->id) {
         $this->redirect(\Input::post('target', true));
     }
     return parent::generate();
 }
 /**
  * Generate the module
  *
  * @throws \Exception
  */
 protected function compile()
 {
     if (Input::get($this->redirectParamName)) {
         $this->redirectToModule(Input::get($this->redirectParamName, true));
     }
     System::loadLanguageFile('seo_serp_module');
     $this->Template->backHref = System::getReferer(true);
     $modules = $this->getModules();
     if (count($modules) > 0) {
         $GLOBALS['TL_CSS'][] = 'system/modules/seo_serp_preview/assets/css/module.min.css';
         $GLOBALS['TL_CSS'][] = 'system/modules/seo_serp_preview/assets/css/tests.min.css';
         $this->Template->modules = $this->generateModules($modules);
     }
     // Rebuild the cache in status manager
     $statusManager = new StatusManager();
     $statusManager->rebuildCache();
 }
 /**
  * Generate the widget and return it as string
  *
  * @return string
  */
 public function generate()
 {
     if (!is_array($this->varValue)) {
         $this->varValue = [];
     }
     $options = [];
     // Generate the options
     foreach ((array) $this->options as $option) {
         $linkId = sprintf('ctrl_%s_%s_%s_%s_link', $this->objDca->field, $this->objDca->id, $this->strId, $option['value']);
         $reference = $GLOBALS['TL_DCA'][$this->objDca->table]['fields'][$this->objDca->field]['reference'][$option['value']];
         $options[] = ['type' => ['label' => $option['label'], 'hint' => is_array($reference) ? $reference[1] : ''], 'picker' => ['tag' => $linkId, 'url' => sprintf('contao/page.php?do=%s&table=%s&field=%s&value=%s', Input::get('do'), $this->objDca->table, $this->objDca->field, str_replace(['{{link_url::', '}}'], '', $this->varValue[$option['value']]['link']))], 'link' => ['id' => $linkId, 'name' => sprintf('%s[%s][link]', $this->strId, $option['value']), 'value' => $this->varValue[$option['value']]['link']], 'title' => ['name' => sprintf('%s[%s][title]', $this->strId, $option['value']), 'value' => $this->varValue[$option['value']]['title']]];
     }
     $template = new BackendTemplate('be_cfg_link_registry_widget');
     $template->options = $options;
     $template->field = $this->objDca->field;
     $template->picker = ['id' => $this->objDca->field, 'title' => str_replace("'", "\\'", $GLOBALS['TL_LANG']['MOD']['page'][0]), 'image' => Image::getHtml('pickpage.gif', $GLOBALS['TL_LANG']['MSC']['pagepicker'], 'style="vertical-align:top;cursor:pointer"')];
     return $template->parse();
 }
Example #30
0
 /**
  * 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();
 }