The class functions as abstract parent class for all widget classes and provides methods to generate the form field markup and to validate the form field input. Usage: $widget = new TextField(); $widget->name = 'test'; $widget->label = 'Test'; if ($_POST) { $widget->validate(); if (!$widget->hasErrors()) { echo $widget->value; } }
Inheritance: extends contao\BaseTemplate
 /**
  * Replace the default template
  *
  * @param string $buffer
  * @param Widget $widget
  *
  * @return string
  */
 public function onParseWidget($buffer, Widget $widget)
 {
     // Override if the current scope is frontend and the template has no custom template set
     // and the Bootstrap is enabled
     if ($this->requestStack->getCurrentRequest()->get('_scope') === ContaoCoreBundle::SCOPE_FRONTEND && !$widget->customTpl && $this->isBootstrapEnabled()) {
         $templateName = $widget->template;
         // Override if there is a mapped template
         if ($this->templateMapper->has($templateName)) {
             $widget->template = $this->templateMapper->get($templateName);
             $buffer = $widget->inherit();
         }
     }
     return $buffer;
 }
 /**
  * Process a custom date regexp on a widget.
  *
  * @param string $rgxp   The rgxp being evaluated.
  *
  * @param string $value  The value to check.
  *
  * @param Widget $widget The widget to process.
  *
  * @return void
  *
  * @SuppressWarnings(PHPMD.Superglobals)
  * @SuppressWarnings(PHPMD.CamelCaseVariableName)
  */
 public static function processCustomDateRegexp($rgxp, $value, $widget)
 {
     if ('MetaModelsFilterRangeDateRgXp' !== $rgxp) {
         return;
     }
     $format = $widget->dateformat;
     if (!preg_match('~^' . Date::getRegexp($format) . '$~i', $value)) {
         $widget->addError(sprintf($GLOBALS['TL_LANG']['ERR']['date'], Date::getInputFormat($format)));
     } else {
         // Validate the date (see https://github.com/contao/core/issues/5086)
         try {
             new Date($value, $format);
         } catch (\OutOfBoundsException $e) {
             $widget->addError(sprintf($GLOBALS['TL_LANG']['ERR']['invalidDate'], $value));
         }
     }
 }
Exemplo n.º 3
0
 /**
  * Check for a valid option (see #4383)
  */
 public function validate()
 {
     $varValue = $this->getPost($this->strName);
     if (!empty($varValue) && !$this->isValidOption($varValue)) {
         $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['invalid'], is_array($varValue) ? implode(', ', $varValue) : $varValue));
     }
     parent::validate();
 }
Exemplo n.º 4
0
 /**
  * Parse the template file and return it as string
  *
  * @param array $arrAttributes An optional attributes array
  *
  * @return string The template markup
  */
 public function parse($arrAttributes = null)
 {
     // Return a wildcard in the back end
     if (TL_MODE == 'BE') {
         /** @var BackendTemplate|object $objTemplate */
         $objTemplate = new \BackendTemplate('be_wildcard');
         if ($this->fsType == 'fsStart') {
             $objTemplate->wildcard = '### ' . Utf8::strtoupper($GLOBALS['TL_LANG']['tl_form_field']['fsStart'][0]) . ' ###' . ($this->label ? '<br>' . $this->label : '');
         } else {
             $objTemplate->wildcard = '### ' . Utf8::strtoupper($GLOBALS['TL_LANG']['tl_form_field']['fsStop'][0]) . ' ###';
         }
         return $objTemplate->parse();
     }
     return parent::parse($arrAttributes);
 }
Exemplo n.º 5
0
 /**
  * Validate the widget using the value.
  *
  * @param Widget      $widget The widget to validate.
  *
  * @param string|null $value  The value to validate.
  *
  * @return void
  *
  * @SuppressWarnings(PHPMD.Superglobals)
  * @SuppressWarnings(PHPMD.CamelCaseVariableName)
  */
 protected function validateWidget($widget, $value)
 {
     if (null === $value) {
         return;
     }
     $name = $widget->name;
     // Backup $_POST value.
     $keeper = Input::post($name);
     Input::setPost($name, $value);
     $widget->validate();
     // Restore $_POST value.
     Input::setPost($name, $keeper);
 }
Exemplo n.º 6
0
 /**
  * Load the database object
  *
  * @param array $arrAttributes
  */
 public function __construct($arrAttributes = null)
 {
     $this->import('Database');
     parent::__construct($arrAttributes);
 }
 /**
  * Handle the widget preparation.
  *
  * @param GetAttributesFromDcaEvent $event The event.
  *
  * @return void
  */
 public function handleGetAttributesFromDca(GetAttributesFromDcaEvent $event)
 {
     $event->setResult(Widget::getAttributesFromDca($event->getFieldConfiguration(), $event->getWidgetName(), $event->getValue(), $event->getWidgetId(), $event->getTable(), $event->getDataContainer()));
 }
Exemplo n.º 8
0
 /**
  * Restore a version
  *
  * @param integer $intVersion
  */
 public function restore($intVersion)
 {
     if (!$GLOBALS['TL_DCA'][$this->strTable]['config']['enableVersioning']) {
         return;
     }
     $objData = $this->Database->prepare("SELECT * FROM tl_version WHERE fromTable=? AND pid=? AND version=?")->limit(1)->execute($this->strTable, $this->intPid, $intVersion);
     if ($objData->numRows < 1) {
         return;
     }
     $data = \StringUtil::deserialize($objData->data);
     if (!is_array($data)) {
         return;
     }
     // Restore the content
     if ($this->strPath !== null) {
         $objFile = new \File($this->strPath);
         $objFile->write($data['content']);
         $objFile->close();
     }
     // Get the currently available fields
     $arrFields = array_flip($this->Database->getFieldNames($this->strTable));
     // Unset fields that do not exist (see #5219)
     $data = array_intersect_key($data, $arrFields);
     $this->loadDataContainer($this->strTable);
     // Reset fields added after storing the version to their default value (see #7755)
     foreach (array_diff_key($arrFields, $data) as $k => $v) {
         $data[$k] = \Widget::getEmptyValueByFieldType($GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['sql']);
     }
     $this->Database->prepare("UPDATE " . $this->strTable . " %s WHERE id=?")->set($data)->execute($this->intPid);
     $this->Database->prepare("UPDATE tl_version SET active='' WHERE fromTable=? AND pid=?")->execute($this->strTable, $this->intPid);
     $this->Database->prepare("UPDATE tl_version SET active=1 WHERE fromTable=? AND pid=? AND version=?")->execute($this->strTable, $this->intPid, $intVersion);
     // Trigger the onrestore_version_callback
     if (is_array($GLOBALS['TL_DCA'][$this->strTable]['config']['onrestore_version_callback'])) {
         foreach ($GLOBALS['TL_DCA'][$this->strTable]['config']['onrestore_version_callback'] as $callback) {
             if (is_array($callback)) {
                 $this->import($callback[0]);
                 $this->{$callback[0]}->{$callback[1]}($this->strTable, $this->intPid, $intVersion, $data);
             } elseif (is_callable($callback)) {
                 $callback($this->strTable, $this->intPid, $intVersion, $data);
             }
         }
     }
     // Trigger the deprecated onrestore_callback
     if (is_array($GLOBALS['TL_DCA'][$this->strTable]['config']['onrestore_callback'])) {
         @trigger_error('Using the onrestore_callback has been deprecated and will no longer work in Contao 5.0. Use the onrestore_version_callback instead.', E_USER_DEPRECATED);
         foreach ($GLOBALS['TL_DCA'][$this->strTable]['config']['onrestore_callback'] as $callback) {
             if (is_array($callback)) {
                 $this->import($callback[0]);
                 $this->{$callback[0]}->{$callback[1]}($this->intPid, $this->strTable, $data, $intVersion);
             } elseif (is_callable($callback)) {
                 $callback($this->intPid, $this->strTable, $data, $intVersion);
             }
         }
     }
     $this->log('Version ' . $intVersion . ' of record "' . $this->strTable . '.id=' . $this->intPid . '" has been restored' . $this->getParentEntries($this->strTable, $this->intPid), __METHOD__, TL_GENERAL);
 }
Exemplo n.º 9
0
 /**
  * Parse the template file and return it as string
  *
  * @param array $arrAttributes An optional attributes array
  *
  * @return string The template markup
  */
 public function parse($arrAttributes = null)
 {
     $this->confirmLabel = sprintf($GLOBALS['TL_LANG']['MSC']['confirmation'], $this->strLabel);
     return parent::parse($arrAttributes);
 }
Exemplo n.º 10
0
 /**
  * Validate the subscription form
  *
  * @param Widget $objWidget
  *
  * @return array|bool
  */
 protected function validateForm(Widget $objWidget = null)
 {
     // Validate the e-mail address
     $varInput = \Idna::encodeEmail(\Input::post('email', true));
     if (!\Validator::isEmail($varInput)) {
         $this->Template->mclass = 'error';
         $this->Template->message = $GLOBALS['TL_LANG']['ERR']['email'];
         return false;
     }
     $this->Template->email = $varInput;
     // Validate the channel selection
     $arrChannels = \Input::post('channels');
     if (!is_array($arrChannels)) {
         $this->Template->mclass = 'error';
         $this->Template->message = $GLOBALS['TL_LANG']['ERR']['noChannels'];
         return false;
     }
     $arrChannels = array_intersect($arrChannels, $this->nl_channels);
     // see #3240
     if (!is_array($arrChannels) || empty($arrChannels)) {
         $this->Template->mclass = 'error';
         $this->Template->message = $GLOBALS['TL_LANG']['ERR']['noChannels'];
         return false;
     }
     $this->Template->selectedChannels = $arrChannels;
     // Check if there are any new subscriptions
     $arrSubscriptions = array();
     if (($objSubscription = \NewsletterRecipientsModel::findBy(array("email=? AND active=1"), $varInput)) !== null) {
         $arrSubscriptions = $objSubscription->fetchEach('pid');
     }
     $arrRemove = array_intersect($arrChannels, $arrSubscriptions);
     if (!is_array($arrRemove) || empty($arrRemove)) {
         $this->Template->mclass = 'error';
         $this->Template->message = $GLOBALS['TL_LANG']['ERR']['unsubscribed'];
         return false;
     }
     // Validate the captcha
     if ($objWidget !== null) {
         $objWidget->validate();
         if ($objWidget->hasErrors()) {
             return false;
         }
     }
     return array($varInput, $arrRemove);
 }
Exemplo n.º 11
0
 /**
  * Return a "checked" attribute if the option is checked
  *
  * @param string $strOption The option to check
  * @param mixed  $varValues One or more values to check against
  *
  * @return string The attribute or an empty string
  *
  * @deprecated Deprecated since Contao 4.0, to be removed in Contao 5.0.
  *             Use Widget::optionChecked() instead.
  */
 public static function optionChecked($strOption, $varValues)
 {
     trigger_error('Using Controller::optionChecked() has been deprecated and will no longer work in Contao 5.0. Use Widget::optionChecked() instead.', E_USER_DEPRECATED);
     return \Widget::optionChecked($strOption, $varValues);
 }
Exemplo n.º 12
0
 /**
  * Return a parameter
  *
  * @param string $strKey The parameter key
  *
  * @return mixed The parameter value
  */
 public function __get($strKey)
 {
     switch ($strKey) {
         case 'name':
             return $this->strCaptchaKey;
             break;
         case 'question':
             return $this->strQuestion;
             break;
         default:
             return parent::__get($strKey);
             break;
     }
 }
Exemplo n.º 13
0
 /**
  * Process form data, store it in the session and redirect to the jumpTo page
  *
  * @param array $arrSubmitted
  * @param array $arrLabels
  * @param array $arrFields
  */
 protected function processFormData($arrSubmitted, $arrLabels, $arrFields)
 {
     // HOOK: prepare form data callback
     if (isset($GLOBALS['TL_HOOKS']['prepareFormData']) && is_array($GLOBALS['TL_HOOKS']['prepareFormData'])) {
         foreach ($GLOBALS['TL_HOOKS']['prepareFormData'] as $callback) {
             $this->import($callback[0]);
             $this->{$callback[0]}->{$callback[1]}($arrSubmitted, $arrLabels, $arrFields, $this);
         }
     }
     // Send form data via e-mail
     if ($this->sendViaEmail) {
         $keys = array();
         $values = array();
         $fields = array();
         $message = '';
         foreach ($arrSubmitted as $k => $v) {
             if ($k == 'cc') {
                 continue;
             }
             $v = \StringUtil::deserialize($v);
             // Skip empty fields
             if ($this->skipEmpty && !is_array($v) && !strlen($v)) {
                 continue;
             }
             // Add field to message
             $message .= (isset($arrLabels[$k]) ? $arrLabels[$k] : ucfirst($k)) . ': ' . (is_array($v) ? implode(', ', $v) : $v) . "\n";
             // Prepare XML file
             if ($this->format == 'xml') {
                 $fields[] = array('name' => $k, 'values' => is_array($v) ? $v : array($v));
             }
             // Prepare CSV file
             if ($this->format == 'csv') {
                 $keys[] = $k;
                 $values[] = is_array($v) ? implode(',', $v) : $v;
             }
         }
         $recipients = \StringUtil::splitCsv($this->recipient);
         // Format recipients
         foreach ($recipients as $k => $v) {
             $recipients[$k] = str_replace(array('[', ']', '"'), array('<', '>', ''), $v);
         }
         $email = new \Email();
         // Get subject and message
         if ($this->format == 'email') {
             $message = $arrSubmitted['message'];
             $email->subject = $arrSubmitted['subject'];
         }
         // Set the admin e-mail as "from" address
         $email->from = $GLOBALS['TL_ADMIN_EMAIL'];
         $email->fromName = $GLOBALS['TL_ADMIN_NAME'];
         // Get the "reply to" address
         if (strlen(\Input::post('email', true))) {
             $replyTo = \Input::post('email', true);
             // Add name
             if (strlen(\Input::post('name'))) {
                 $replyTo = '"' . \Input::post('name') . '" <' . $replyTo . '>';
             }
             $email->replyTo($replyTo);
         }
         // Fallback to default subject
         if (!strlen($email->subject)) {
             $email->subject = $this->replaceInsertTags($this->subject, false);
         }
         // Send copy to sender
         if (strlen($arrSubmitted['cc'])) {
             $email->sendCc(\Input::post('email', true));
             unset($_SESSION['FORM_DATA']['cc']);
         }
         // Attach XML file
         if ($this->format == 'xml') {
             /** @var FrontendTemplate|object $objTemplate */
             $objTemplate = new \FrontendTemplate('form_xml');
             $objTemplate->fields = $fields;
             $objTemplate->charset = \Config::get('characterSet');
             $email->attachFileFromString($objTemplate->parse(), 'form.xml', 'application/xml');
         }
         // Attach CSV file
         if ($this->format == 'csv') {
             $email->attachFileFromString(\StringUtil::decodeEntities('"' . implode('";"', $keys) . '"' . "\n" . '"' . implode('";"', $values) . '"'), 'form.csv', 'text/comma-separated-values');
         }
         $uploaded = '';
         // Attach uploaded files
         if (!empty($_SESSION['FILES'])) {
             foreach ($_SESSION['FILES'] as $file) {
                 // Add a link to the uploaded file
                 if ($file['uploaded']) {
                     $uploaded .= "\n" . \Environment::get('base') . str_replace(TL_ROOT . '/', '', dirname($file['tmp_name'])) . '/' . rawurlencode($file['name']);
                     continue;
                 }
                 $email->attachFileFromString(file_get_contents($file['tmp_name']), $file['name'], $file['type']);
             }
         }
         $uploaded = strlen(trim($uploaded)) ? "\n\n---\n" . $uploaded : '';
         $email->text = \StringUtil::decodeEntities(trim($message)) . $uploaded . "\n\n";
         // Send the e-mail
         try {
             $email->sendTo($recipients);
         } catch (\Swift_SwiftException $e) {
             $this->log('Form "' . $this->title . '" could not be sent: ' . $e->getMessage(), __METHOD__, TL_ERROR);
         }
     }
     // Store the values in the database
     if ($this->storeValues && $this->targetTable != '') {
         $arrSet = array();
         // Add the timestamp
         if ($this->Database->fieldExists('tstamp', $this->targetTable)) {
             $arrSet['tstamp'] = time();
         }
         // Fields
         foreach ($arrSubmitted as $k => $v) {
             if ($k != 'cc' && $k != 'id') {
                 $arrSet[$k] = $v;
                 // Convert date formats into timestamps (see #6827)
                 if ($arrSet[$k] != '' && in_array($arrFields[$k]->rgxp, array('date', 'time', 'datim'))) {
                     $objDate = new \Date($arrSet[$k], \Date::getFormatFromRgxp($arrFields[$k]->rgxp));
                     $arrSet[$k] = $objDate->tstamp;
                 }
             }
         }
         // Files
         if (!empty($_SESSION['FILES'])) {
             foreach ($_SESSION['FILES'] as $k => $v) {
                 if ($v['uploaded']) {
                     $arrSet[$k] = str_replace(TL_ROOT . '/', '', $v['tmp_name']);
                 }
             }
         }
         // HOOK: store form data callback
         if (isset($GLOBALS['TL_HOOKS']['storeFormData']) && is_array($GLOBALS['TL_HOOKS']['storeFormData'])) {
             foreach ($GLOBALS['TL_HOOKS']['storeFormData'] as $callback) {
                 $this->import($callback[0]);
                 $arrSet = $this->{$callback[0]}->{$callback[1]}($arrSet, $this);
             }
         }
         // Set the correct empty value (see #6284, #6373)
         foreach ($arrSet as $k => $v) {
             if ($v === '') {
                 $arrSet[$k] = \Widget::getEmptyValueByFieldType($GLOBALS['TL_DCA'][$this->targetTable]['fields'][$k]['sql']);
             }
         }
         // Do not use Models here (backwards compatibility)
         $this->Database->prepare("INSERT INTO " . $this->targetTable . " %s")->set($arrSet)->execute();
     }
     // Store all values in the session
     foreach (array_keys($_POST) as $key) {
         $_SESSION['FORM_DATA'][$key] = $this->allowTags ? \Input::postHtml($key, true) : \Input::post($key, true);
     }
     $arrFiles = $_SESSION['FILES'];
     // HOOK: process form data callback
     if (isset($GLOBALS['TL_HOOKS']['processFormData']) && is_array($GLOBALS['TL_HOOKS']['processFormData'])) {
         foreach ($GLOBALS['TL_HOOKS']['processFormData'] as $callback) {
             $this->import($callback[0]);
             $this->{$callback[0]}->{$callback[1]}($arrSubmitted, $this->arrData, $arrFiles, $arrLabels, $this);
         }
     }
     $_SESSION['FILES'] = array();
     // DO NOT CHANGE
     // Add a log entry
     if (FE_USER_LOGGED_IN) {
         $this->import('FrontendUser', 'User');
         $this->log('Form "' . $this->title . '" has been submitted by "' . $this->User->username . '".', __METHOD__, TL_FORMS);
     } else {
         $this->log('Form "' . $this->title . '" has been submitted by ' . \System::anonymizeIp(\Environment::get('ip')) . '.', __METHOD__, TL_FORMS);
     }
     // Check whether there is a jumpTo page
     if (($objJumpTo = $this->objModel->getRelated('jumpTo')) instanceof PageModel) {
         $this->jumpToOrReload($objJumpTo->row());
     }
     $this->reload();
 }
Exemplo n.º 14
0
 /**
  * @param mixed $varInput
  * @return mixed
  */
 protected function validator($varInput)
 {
     return parent::validator(trim(DataCallback::getInstance()->getData($this)));
 }
Exemplo n.º 15
0
 public function validator($varInput)
 {
     return parent::validator($varInput);
 }
Exemplo n.º 16
0
 /**
  * Save the current value
  *
  * @param mixed $varValue
  *
  * @throws \Exception
  */
 protected function save($varValue)
 {
     if (\Input::post('FORM_SUBMIT') != $this->strTable) {
         return;
     }
     $arrData = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField];
     // File names
     if ($this->strField == 'name') {
         if (!file_exists(TL_ROOT . '/' . $this->strPath . '/' . $this->varValue . $this->strExtension) || !$this->isMounted($this->strPath . '/' . $this->varValue . $this->strExtension) || $this->varValue === $varValue) {
             return;
         }
         $this->import('Files');
         $varValue = Utf8::toAscii($varValue);
         // Trigger the save_callback
         if (is_array($arrData['save_callback'])) {
             foreach ($arrData['save_callback'] as $callback) {
                 if (is_array($callback)) {
                     $this->import($callback[0]);
                     $varValue = $this->{$callback[0]}->{$callback[1]}($varValue, $this);
                 } elseif (is_callable($callback)) {
                     $varValue = $callback($varValue, $this);
                 }
             }
         }
         // The target exists
         if (strcasecmp($this->strPath . '/' . $this->varValue . $this->strExtension, $this->strPath . '/' . $varValue . $this->strExtension) !== 0 && file_exists(TL_ROOT . '/' . $this->strPath . '/' . $varValue . $this->strExtension)) {
             throw new \Exception(sprintf($GLOBALS['TL_LANG']['ERR']['fileExists'], $varValue));
         }
         $arrImageTypes = trimsplit(',', strtolower(\Config::get('validImageTypes')));
         // Remove potentially existing thumbnails (see #6641)
         if (in_array(substr($this->strExtension, 1), $arrImageTypes)) {
             foreach (glob(TL_ROOT . '/' . \System::getContainer()->getParameter('contao.image.target_path') . '/*/' . $this->varValue . '-*' . $this->strExtension) as $strThumbnail) {
                 $this->Files->delete(str_replace(TL_ROOT . '/', '', $strThumbnail));
             }
         }
         // Rename the file
         $this->Files->rename($this->strPath . '/' . $this->varValue . $this->strExtension, $this->strPath . '/' . $varValue . $this->strExtension);
         // New folders
         if (stristr($this->intId, '__new__') !== false) {
             // Update the database
             if ($this->blnIsDbAssisted && \Dbafs::shouldBeSynchronized($this->strPath . '/' . $varValue . $this->strExtension)) {
                 $this->objActiveRecord = \Dbafs::addResource($this->strPath . '/' . $varValue . $this->strExtension);
             }
             $this->log('Folder "' . $this->strPath . '/' . $varValue . $this->strExtension . '" has been created', __METHOD__, TL_FILES);
         } else {
             // Update the database
             if ($this->blnIsDbAssisted) {
                 $syncSource = \Dbafs::shouldBeSynchronized($this->strPath . '/' . $this->varValue . $this->strExtension);
                 $syncTarget = \Dbafs::shouldBeSynchronized($this->strPath . '/' . $varValue . $this->strExtension);
                 if ($syncSource && $syncTarget) {
                     \Dbafs::moveResource($this->strPath . '/' . $this->varValue . $this->strExtension, $this->strPath . '/' . $varValue . $this->strExtension);
                 } elseif ($syncSource) {
                     \Dbafs::deleteResource($this->strPath . '/' . $this->varValue . $this->strExtension);
                 } elseif ($syncTarget) {
                     \Dbafs::addResource($this->strPath . '/' . $varValue . $this->strExtension);
                 }
             }
             $this->log('File or folder "' . $this->strPath . '/' . $this->varValue . $this->strExtension . '" has been renamed to "' . $this->strPath . '/' . $varValue . $this->strExtension . '"', __METHOD__, TL_FILES);
         }
         // Update the symlinks
         if (is_link(TL_ROOT . '/web/' . $this->strPath . '/' . $this->varValue . $this->strExtension)) {
             $this->Files->delete('web/' . $this->strPath . '/' . $this->varValue . $this->strExtension);
             SymlinkUtil::symlink($this->strPath . '/' . $varValue . $this->strExtension, 'web/' . $this->strPath . '/' . $varValue . $this->strExtension, TL_ROOT);
         }
         // Set the new value so the input field can show it
         if (\Input::get('act') == 'editAll') {
             /** @var SessionInterface $objSession */
             $objSession = \System::getContainer()->get('session');
             $session = $objSession->all();
             if (($index = array_search($this->strPath . '/' . $this->varValue . $this->strExtension, $session['CURRENT']['IDS'])) !== false) {
                 $session['CURRENT']['IDS'][$index] = $this->strPath . '/' . $varValue . $this->strExtension;
                 $objSession->replace($session);
             }
         }
         $this->varValue = $varValue;
     } elseif ($this->blnIsDbAssisted && $this->objActiveRecord !== null) {
         // Convert date formats into timestamps
         if ($varValue != '' && in_array($arrData['eval']['rgxp'], array('date', 'time', 'datim'))) {
             $objDate = new \Date($varValue, \Date::getFormatFromRgxp($arrData['eval']['rgxp']));
             $varValue = $objDate->tstamp;
         }
         // Make sure unique fields are unique
         if ($arrData['eval']['unique'] && $varValue != '' && !$this->Database->isUniqueValue($this->strTable, $this->strField, $varValue, $this->objActiveRecord->id)) {
             throw new \Exception(sprintf($GLOBALS['TL_LANG']['ERR']['unique'], $arrData['label'][0] ?: $this->strField));
         }
         // Handle multi-select fields in "override all" mode
         if (\Input::get('act') == 'overrideAll' && ($arrData['inputType'] == 'checkbox' || $arrData['inputType'] == 'checkboxWizard') && $arrData['eval']['multiple']) {
             if ($this->objActiveRecord !== null) {
                 $new = deserialize($varValue, true);
                 $old = deserialize($this->objActiveRecord->{$this->strField}, true);
                 switch (\Input::post($this->strInputName . '_update')) {
                     case 'add':
                         $varValue = array_values(array_unique(array_merge($old, $new)));
                         break;
                     case 'remove':
                         $varValue = array_values(array_diff($old, $new));
                         break;
                     case 'replace':
                         $varValue = $new;
                         break;
                 }
                 if (!is_array($varValue) || empty($varValue)) {
                     $varValue = '';
                 } elseif (isset($arrData['eval']['csv'])) {
                     $varValue = implode($arrData['eval']['csv'], $varValue);
                     // see #2890
                 } else {
                     $varValue = serialize($varValue);
                 }
             }
         }
         // Convert arrays (see #2890)
         if ($arrData['eval']['multiple'] && isset($arrData['eval']['csv'])) {
             $varValue = implode($arrData['eval']['csv'], deserialize($varValue, true));
         }
         // Trigger the save_callback
         if (is_array($arrData['save_callback'])) {
             foreach ($arrData['save_callback'] as $callback) {
                 if (is_array($callback)) {
                     $this->import($callback[0]);
                     $varValue = $this->{$callback[0]}->{$callback[1]}($varValue, $this);
                 } elseif (is_callable($callback)) {
                     $varValue = $callback($varValue, $this);
                 }
             }
         }
         // Save the value if there was no error
         if (($varValue != '' || !$arrData['eval']['doNotSaveEmpty']) && ($this->varValue != $varValue || $arrData['eval']['alwaysSave'])) {
             // If the field is a fallback field, empty all other columns
             if ($arrData['eval']['fallback'] && $varValue != '') {
                 $this->Database->execute("UPDATE " . $this->strTable . " SET " . $this->strField . "=''");
             }
             // Set the correct empty value (see #6284, #6373)
             if ($varValue === '') {
                 $varValue = \Widget::getEmptyValueByFieldType($GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField]['sql']);
             }
             $this->objActiveRecord->{$this->strField} = $varValue;
             $this->objActiveRecord->save();
             $this->blnCreateNewVersion = true;
             $this->varValue = deserialize($varValue);
         }
     }
 }
Exemplo n.º 17
0
    /**
     * Return a select menu to limit results
     *
     * @param boolean $blnOptional
     *
     * @return string
     */
    protected function limitMenu($blnOptional = false)
    {
        /** @var AttributeBagInterface $objSessionBag */
        $objSessionBag = \System::getContainer()->get('session')->getBag('contao_backend');
        $session = $objSessionBag->all();
        $filter = $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['mode'] == 4 ? $this->strTable . '_' . CURRENT_ID : $this->strTable;
        $fields = '';
        // Set limit from user input
        if (\Input::post('FORM_SUBMIT') == 'tl_filters' || \Input::post('FORM_SUBMIT') == 'tl_filters_limit') {
            $strLimit = \Input::post('tl_limit');
            if ($strLimit == 'tl_limit') {
                unset($session['filter'][$filter]['limit']);
            } else {
                // Validate the user input (thanks to aulmn) (see #4971)
                if ($strLimit == 'all' || preg_match('/^[0-9]+,[0-9]+$/', $strLimit)) {
                    $session['filter'][$filter]['limit'] = $strLimit;
                }
            }
            $objSessionBag->replace($session);
            if (\Input::post('FORM_SUBMIT') == 'tl_filters_limit') {
                $this->reload();
            }
        } else {
            $this->limit = $session['filter'][$filter]['limit'] != '' ? $session['filter'][$filter]['limit'] == 'all' ? null : $session['filter'][$filter]['limit'] : '0,' . \Config::get('resultsPerPage');
            $arrProcedure = $this->procedure;
            $arrValues = $this->values;
            $query = "SELECT COUNT(*) AS count FROM " . $this->strTable;
            if (!empty($this->root) && is_array($this->root)) {
                $arrProcedure[] = 'id IN(' . implode(',', $this->root) . ')';
            }
            // Support empty ptable fields
            if ($GLOBALS['TL_DCA'][$this->strTable]['config']['dynamicPtable']) {
                $arrProcedure[] = $this->ptable == 'tl_article' ? "(ptable=? OR ptable='')" : "ptable=?";
                $arrValues[] = $this->ptable;
            }
            if (!empty($arrProcedure)) {
                $query .= " WHERE " . implode(' AND ', $arrProcedure);
            }
            $objTotal = $this->Database->prepare($query)->execute($arrValues);
            $this->total = $objTotal->count;
            $options_total = 0;
            $blnIsMaxResultsPerPage = false;
            // Overall limit
            if ($this->total > \Config::get('maxResultsPerPage') && ($this->limit === null || preg_replace('/^.*,/', '', $this->limit) == \Config::get('maxResultsPerPage'))) {
                if ($this->limit === null) {
                    $this->limit = '0,' . \Config::get('maxResultsPerPage');
                }
                $blnIsMaxResultsPerPage = true;
                \Config::set('resultsPerPage', \Config::get('maxResultsPerPage'));
                $session['filter'][$filter]['limit'] = \Config::get('maxResultsPerPage');
            }
            $options = '';
            // Build options
            if ($this->total > 0) {
                $options = '';
                $options_total = ceil($this->total / \Config::get('resultsPerPage'));
                // Reset limit if other parameters have decreased the number of results
                if ($this->limit !== null && ($this->limit == '' || preg_replace('/,.*$/', '', $this->limit) > $this->total)) {
                    $this->limit = '0,' . \Config::get('resultsPerPage');
                }
                // Build options
                for ($i = 0; $i < $options_total; $i++) {
                    $this_limit = $i * \Config::get('resultsPerPage') . ',' . \Config::get('resultsPerPage');
                    $upper_limit = $i * \Config::get('resultsPerPage') + \Config::get('resultsPerPage');
                    if ($upper_limit > $this->total) {
                        $upper_limit = $this->total;
                    }
                    $options .= '
  <option value="' . $this_limit . '"' . \Widget::optionSelected($this->limit, $this_limit) . '>' . ($i * \Config::get('resultsPerPage') + 1) . ' - ' . $upper_limit . '</option>';
                }
                if (!$blnIsMaxResultsPerPage) {
                    $options .= '
  <option value="all"' . \Widget::optionSelected($this->limit, null) . '>' . $GLOBALS['TL_LANG']['MSC']['filterAll'] . '</option>';
                }
            }
            // Return if there is only one page
            if ($blnOptional && ($this->total < 1 || $options_total < 2)) {
                return '';
            }
            $fields = '
<select name="tl_limit" class="tl_select' . ($session['filter'][$filter]['limit'] != 'all' && $this->total > \Config::get('resultsPerPage') ? ' active' : '') . '" onchange="this.form.submit()">
  <option value="tl_limit">' . $GLOBALS['TL_LANG']['MSC']['filterRecords'] . '</option>' . $options . '
</select> ';
        }
        return '

<div class="tl_limit tl_subpanel">
<strong>' . $GLOBALS['TL_LANG']['MSC']['showOnly'] . ':</strong> ' . $fields . '
</div>';
    }
Exemplo n.º 18
0
 /**
  * Validate input and set value
  *
  * @param mixed $varInput
  *
  * @return string
  */
 protected function validator($varInput)
 {
     $this->blnSubmitInput = false;
     if (($varInput == '' || $varInput == '*****') && $this->varValue != '') {
         return '*****';
     }
     if (Utf8::strlen($varInput) < \Config::get('minPasswordLength')) {
         $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['passwordLength'], \Config::get('minPasswordLength')));
     }
     if ($varInput != $this->getPost($this->strName . '_confirm')) {
         $this->addError($GLOBALS['TL_LANG']['ERR']['passwordMatch']);
     }
     if ($varInput == $GLOBALS['TL_USERNAME']) {
         $this->addError($GLOBALS['TL_LANG']['ERR']['passwordName']);
     }
     $varInput = parent::validator($varInput);
     if (!$this->hasErrors()) {
         $this->blnSubmitInput = true;
         \Message::addConfirmation($GLOBALS['TL_LANG']['MSC']['pw_changed']);
         return \Encryption::hash($varInput);
     }
     return '';
 }