public function testRegexpPrice()
 {
     \Input::setPost('test_rgxp_price', 'foobar');
     $objWidget = new \TextField(array('name' => 'test_rgxp_price'));
     $objWidget->rgxp = 'price';
     $objWidget->validate();
     $this->assertTrue($objWidget->hasErrors());
     unset($objWidget);
     \Input::setPost('test_rgxp_price', '20.00');
     $objWidget = new \TextField(array('name' => 'test_rgxp_price'));
     $objWidget->rgxp = 'price';
     $objWidget->validate();
     $this->assertFalse($objWidget->hasErrors());
     unset($objWidget);
     \Input::setPost('test_rgxp_price', '20');
     $objWidget = new \TextField(array('name' => 'test_rgxp_price'));
     $objWidget->rgxp = 'price';
     $objWidget->validate();
     $this->assertFalse($objWidget->hasErrors());
     unset($objWidget);
     \Input::setPost('test_rgxp_price', '-20');
     $objWidget = new \TextField(array('name' => 'test_rgxp_price'));
     $objWidget->rgxp = 'price';
     $objWidget->validate();
     $this->assertFalse($objWidget->hasErrors());
     unset($objWidget);
     \Input::setPost('test_rgxp_price', '20.-');
     $objWidget = new \TextField(array('name' => 'test_rgxp_price'));
     $objWidget->rgxp = 'price';
     $objWidget->validate();
     $this->assertFalse($objWidget->hasErrors());
     unset($objWidget);
 }
Example #2
0
 /**
  * Adjust form fields to given page.
  *
  * @param \FormFieldModel[] $formFields
  * @param string            $formId
  * @param \Form             $form
  */
 public function compileFormFields($formFields, $formId, \Form $form)
 {
     // Make sure empty form fields arrays are skipped
     if (0 === count($formFields)) {
         return $formFields;
     }
     $manager = new MPFormsFormManager($form->id);
     // Don't try to render multi page form if no valid combination
     if (!$manager->isValidFormFieldCombination()) {
         return $manager->getFieldsWithoutPageBreaks();
     }
     // Do not let Contao validate anything if user wants to go back
     if ('back' === $_POST['mp_form_pageswitch']) {
         $this->redirectToStep($manager, $manager->getPreviousStep());
     }
     // Validate previous steps data
     if (!$manager->isFirstStep()) {
         $vResult = $manager->validateSteps(0, $manager->getCurrentStep() - 1);
         if (true !== $vResult) {
             $manager->setPreviousStepsWereInvalid();
             $this->redirectToStep($manager, $vResult);
         }
     }
     // If someone wanted to skip the page, fake form submission so fields
     // are validated and show the error message.
     if ($manager->getPreviousStepsWereInvalid()) {
         \Input::setPost('FORM_SUBMIT', $manager->getFormId());
         $manager->resetPreviousStepsWereInvalid();
     }
     return $manager->getFieldsForStep($manager->getCurrentStep());
 }
 /**
  * @dataProvider inputProvider
  */
 public function testInput($input, $output, $exception = null)
 {
     if ($exception) {
         $this->setExpectedException($exception);
     }
     \Input::setPost('test_number_field', $input);
     $objWidget = new BackendWidget(array('name' => 'test_number_field', 'value' => $input));
     $objWidget->validate();
     $this->assertEquals($output, $objWidget->value);
 }
 public function recordUsername($intId, &$arrData)
 {
     if (!strlen($arrData['username'])) {
         $arrData['username'] = $arrData['email'];
         \Input::setPost('username', $arrData['email']);
         \Database::getInstance()->prepare("UPDATE tl_member SET username=? WHERE id=?")->execute($arrData['email'], $intId);
         $memberModel = \MemberModel::findByPk($intId);
         // Fix the problem with versions (see #7)
         if (null !== $memberModel) {
             $memberModel->refresh();
         }
     }
 }
Example #5
0
 public function testBindModel()
 {
     $this->instance->addFormField('pageTitle', array('inputType' => 'text'))->addFormField('jumpTo', array('inputType' => 'text'));
     $objModel = new \PageModel();
     $this->instance->bindModel($objModel);
     \Input::setPost('pageTitle', 'My page title test');
     \Input::setPost('jumpTo', 42);
     if ($this->instance->validate()) {
         $objBoundModel = $this->instance->getBoundModel();
         $this->assertTrue(spl_object_hash($objModel) === spl_object_hash($objBoundModel));
         $this->assertEquals('My page title test', $objBoundModel->pageTitle);
         $this->assertEquals(42, $objBoundModel->jumpTo);
     }
 }
 /**
  * This Hook provides case-insensitive contao-login by email usernames
  *
  * RFC 5321, section-2.3.11 says that email addresses should be treated as case-insensitive
  *
  * @param $strUser
  * @param $strPassword
  * @param $strTable
  *
  * @return bool
  */
 public function importUserHook($strUser, $strPassword, $strTable)
 {
     if (!\Validator::isEmail($strUser)) {
         return false;
     }
     switch ($strTable) {
         case 'tl_member':
             $objUser = \FrontendUser::getInstance();
             if ($objUser->findBy('LOWER(username)', strtolower($strUser)) !== false) {
                 // set post user name to the users username
                 \Input::setPost('username', $objUser->username);
                 return true;
             }
             break;
     }
     return false;
 }
 /**
  * 
  */
 public function changeAjaxPostActions()
 {
     if (version_compare(VERSION, '3.1', '>=')) {
         if (Environment::get('isAjaxRequest')) {
             switch (Input::post('action')) {
                 case 'reloadPagetree':
                 case 'reloadFiletree':
                     //get the fieldnames
                     $strRef = $this->Session->get('filePickerRef');
                     $strRef = substr($strRef, stripos($strRef, 'field=') + 6);
                     $arrRef = explode('&', $strRef);
                     $arrRefField = explode('__', $arrRef[0]);
                     $arrField = preg_split('/_row[0-9]*_/i', \Input::post('name'));
                     //change action if modal selector was found
                     if (count($arrRefField) > 1 && $arrRefField === $arrField) {
                         Input::setPost('action', Input::post('action') . '_mcw');
                     }
                     break;
             }
         }
     }
 }
 /**
  * @param array $arrClasses
  * @param \DataContainer $dc
  */
 protected function saveClassesToCssClass(array $arrClasses, \DataContainer $dc)
 {
     $strCssClassName = $this->getCssClassName($dc->id);
     $strClasses = implode(' ', $arrClasses);
     $strClasses = str_replace('  ', ' ', $strClasses);
     $strClasses = trim($strClasses);
     $dc->activeRecord->cssClass = $strClasses;
     \Input::setPost($strCssClassName, $strClasses);
     $objDatabase = \Database::getInstance();
     $objDatabase->prepare("UPDATE {$dc->table} SET cssClass=? WHERE id=?")->execute($strClasses, $dc->id);
 }
Example #9
0
 /**
  * @param string $strAddresses
  * @param $field
  * @return array
  */
 private function validateEmailAddresses($strAddresses = '', $field)
 {
     $arrEmailAddresses = array();
     trim(strtolower($strAddresses));
     if ($strAddresses == '') {
         // update the db
         $this->Database->prepare('UPDATE tl_be_email SET ' . $field . '=? WHERE id=?')->execute('', \Input::get('id'));
         \Input::setPost($field, '');
         return $arrEmailAddresses;
     }
     $arrEmailAddresses = array();
     preg_match_all('/\\w[-._\\w]*\\w@\\w[-._\\w]*\\w\\.\\w{2,6}/i', $strAddresses, $arrEmailAddresses);
     // remove doubble entries
     $arrEmailAddresses = array_unique($arrEmailAddresses[0]);
     // update the db
     $this->Database->prepare('UPDATE tl_be_email SET ' . $field . '=? WHERE id=?')->execute(implode('; ', $arrEmailAddresses), \Input::get('id'));
     \Input::setPost($field, implode('; ', $arrEmailAddresses));
     return $arrEmailAddresses;
 }
Example #10
0
 /**
  * @param $strNewPassword
  * @param null $intId
  */
 protected function setPostPassword($strNewPassword, $intId = null)
 {
     if (\Input::get('act') == 'editAll' && is_numeric($intId)) {
         \Input::setPost('password_' . $intId, $strNewPassword);
         \Input::setPost('password_' . $intId . '_confirm', $strNewPassword);
     } else {
         \Input::setPost('password', $strNewPassword);
         \Input::setPost('password_confirm', $strNewPassword);
     }
 }
 /**
  * Generate the module
  */
 protected function compile()
 {
     global $objPage;
     if (\Input::post('FORM_SUBMIT') == 'tl_bn_edit_entry' && (int) $this->User->library_id > 0) {
         $bnImageArr = $this->getBnImages();
         $set = array('bibliotheksname' => \Input::post('bibliotheksname'), 'zweigstellenname' => \Input::post('zweigstellenname'), 'traeger' => \Input::post('traeger'), 'medienbestand' => \Input::post('medienbestand'), 'strasse' => \Input::post('strasse'), 'hausnummer' => \Input::post('hausnummer'), 'plz' => \Input::post('plz'), 'ort' => \Input::post('ort'), 'gemeinde' => \Input::post('gemeinde'), 'landkreis' => \Input::post('landkreis'), 'leiter_name' => \Input::post('leiter_name'), 'telefon' => \Input::post('telefon'), 'fax' => \Input::post('fax'), 'email' => \Input::post('email'), 'website' => \Input::post('website'), 'blog' => \Input::post('blog'), 'facebook' => \Input::post('facebook'), 'twitter' => \Input::post('twitter'), 'gplus' => \Input::post('gplus'), 'onleihe' => \Input::post('onleihe'), 'webkatalog' => \Input::post('webkatalog'), 'medien' => \Input::post('medien'), 'leistungen' => \Input::post('leistungen'), 'sonst_oeffnungszeiten' => \Input::post('sonst_oeffnungszeiten'), 'sonstmedien' => \Input::post('sonstmedien'), 'sonstleistungen' => \Input::post('sonstleistungen'), 'image_1' => $bnImageArr[1], 'image_2' => $bnImageArr[2], 'image_3' => $bnImageArr[3], 'image_4' => $bnImageArr[4], 'image_5' => $bnImageArr[5]);
         $opendates = $this->getOpenDatesForDB();
         $set = array_merge($set, $opendates);
         $geoData = $this->getcurrentGeoData();
         $set = array_merge($set, $geoData);
         $this->Database->prepare('UPDATE `tl_bn_libraries` %s WHERE `id`=?')->set($set)->execute($this->User->library_id);
         \Input::setPost('FORM_SUBMIT', '');
         $this->reload();
     }
     // Get the total number of items
     $objLibrary = \BnLibrariesModel::findLibByIdOrAlias($this->User->library_id);
     if ($objLibrary === null) {
         // Do not index or cache the page
         $objPage->noSearch = 1;
         $objPage->cache = 0;
         // Send a 404 header
         header('HTTP/1.1 404 Not Found');
         $this->Template->articles = '<p class="error">' . sprintf($GLOBALS['TL_LANG']['MSC']['invalidPage'], \Input::get('items')) . '</p>';
         return;
     }
     $libData = $objLibrary->row();
     // print_r($libData);
     // Leitungen
     $leitungen = array();
     $leitungenObj = $this->Database->prepare('SELECT * FROM `tl_bn_leitung` ORDER BY `sorting`')->execute();
     if ($leitungenObj->numRows > 0) {
         while ($leitungenObj->next()) {
             $leitungen[$leitungenObj->id] = $leitungenObj->name;
         }
     }
     $libData['leitungenArr'] = $leitungen;
     // Traeger
     $traeger = array();
     $traegerObj = $this->Database->prepare('SELECT * FROM `tl_bn_traeger` ORDER BY `sorting`')->execute();
     if ($traegerObj->numRows > 0) {
         while ($traegerObj->next()) {
             $traeger[$traegerObj->id] = $traegerObj->name;
         }
     }
     $libData['traegerArr'] = $traeger;
     // Medien
     $medien = array();
     $medienObj = $this->Database->prepare('SELECT * FROM `tl_bn_medien` ORDER BY `sorting`')->execute();
     if ($medienObj->numRows > 0) {
         while ($medienObj->next()) {
             $medien[$medienObj->id] = $medienObj->name;
         }
     }
     $libData['medienArr'] = $medien;
     // Leistungen
     $leistungen = array();
     $leistungenObj = $this->Database->prepare('SELECT * FROM `tl_bn_leistungen` ORDER BY `sorting`')->execute();
     if ($leistungenObj->numRows > 0) {
         while ($leistungenObj->next()) {
             $leistungen[$leistungenObj->id] = $leistungenObj->name;
         }
     }
     $libData['leistungenArr'] = $leistungen;
     // Email
     $this->import('String');
     $libData['email'] = $this->String->encodeEmail($libData['email']);
     // Open-Status
     $libData['open_status'] = $this->getCurrentOpenStatus($objLibrary);
     $GLOBALS['TL_JAVASCRIPT'][] = '.' . BN_PATH . '/assets/js/bn_fe.js';
     // Google-Maps url-search-string
     $libData['gmapsplace'] = ampersand($libData['strasse'] . ' ' . $libData['hausnummer'] . ', ' . $libData['plz'] . ' ' . $libData['ort'] . ', Niedersachsen');
     // media
     $medienIds = unserialize($libData['medien']);
     if (is_array($medienIds) && count($medienIds) > 0) {
         $medienArr = array();
         $medienObj = $this->Database->prepare("SELECT * FROM `tl_bn_medien` WHERE id IN(" . implode(',', array_map('intval', $medienIds)) . ")")->execute();
         if ($medienObj->numRows > 0) {
             while ($medienObj->next()) {
                 $medienArr[] = $medienObj->name;
             }
             $libData['medien'] = $medienArr;
         }
     }
     // leistungen
     $leistungenIds = unserialize($libData['leistungen']);
     if (is_array($leistungenIds) && count($leistungenIds) > 0) {
         $leistungenArr = array();
         $leistungenObj = $this->Database->prepare("SELECT * FROM `tl_bn_leistungen` WHERE id IN(" . implode(',', array_map('intval', $leistungenIds)) . ")")->execute();
         if ($leistungenObj->numRows > 0) {
             while ($leistungenObj->next()) {
                 $leistungenArr[] = $leistungenObj->name;
             }
             $libData['leistungen'] = $leistungenArr;
         }
     }
     $this->Template->data = $libData;
     $this->Template->articles = '';
     $this->Template->referer = 'javascript:history.go(-1)';
     $this->Template->back = $GLOBALS['TL_LANG']['MSC']['goBack'];
 }
 /**
  * @param array   $events
  * @param array   $calendars
  * @param         $startTime
  * @param         $endTime
  * @param \Module $eventList
  *
  * @return array
  */
 public function filterAllEvents(array $events, array $calendars, $startTime, $endTime, \Module &$eventList)
 {
     global $container;
     if (!$eventList->calendarFilterField) {
         return $events;
     }
     $eventList->calendarFilterField = deserialize($eventList->calendarFilterField);
     if (!empty($eventList->calendarFilterField)) {
         if (empty($eventList->customTpl)) {
             $eventList->Template->setName('mod_eventlist_filter');
         }
         $eventList->Template->filterForm = '';
         if ($eventList->calendarFilterMergeMonth) {
             $eventList->calendarFilterField = implode(',', $eventList->calendarFilterField);
             $eventList->calendarFilterField = str_replace('startDate', 'startDate,mergeMonth', $eventList->calendarFilterField);
             $eventList->calendarFilterField = explode(',', $eventList->calendarFilterField);
         }
     }
     $this->eventList =& $eventList;
     $this->events = $events;
     $deleteSession = true;
     foreach ($eventList->calendarFilterField as $filterField) {
         if (\Input::post($filterField)) {
             continue;
         }
         $deleteSession = false;
     }
     if ($deleteSession) {
         \Session::getInstance()->remove('eventlistfilterreload_' . $this->eventList->id);
     }
     if (\Input::post('resetFilter') === '') {
         foreach ($eventList->calendarFilterField as $filterField) {
             if (!\Input::post($filterField)) {
                 continue;
             }
             \Input::setPost($filterField, '');
         }
     }
     \Session::getInstance()->set('eventlistfilterreload_' . $this->eventList->id, true);
     $restorePost = \Session::getInstance()->get('eventlistfilterpost_' . $this->eventList->id);
     if ($restorePost) {
         foreach ($restorePost as $postField => $postValue) {
             if (\Input::post($postField) === null) {
                 \Input::setPost($postField, $postValue);
             }
         }
         \Session::getInstance()->set('eventlistfilterreload_' . $this->eventList->id, false);
     }
     /** @var EventDispatcher $eventDispatcher */
     $eventDispatcher = $container['event-dispatcher'];
     if (!($filter = \Session::getInstance()->get('eventlistfilter_' . $this->eventList->id))) {
         $filter = array();
         foreach ($eventList->calendarFilterField as $filterField) {
             $filter[$filterField] = '';
         }
     }
     foreach ($filter as $post => $value) {
         if ($postValue = \Input::post($post)) {
             $filterEventsEvent = new PostFilterEventsEvent($post, $postValue);
             $filterEventsEvent->setEvents($this->events);
             $eventDispatcher->dispatch(PostFilterEventsEvent::NAME, $filterEventsEvent);
             $this->events = $filterEventsEvent->getEvents();
             $filterOptionsEvent = new GetFilterOptionsEvent();
             $eventDispatcher->dispatch(GetFilterOptionsEvent::NAME, $filterOptionsEvent);
             if ($filterOptionsEvent->hasOption($post)) {
                 continue;
             }
             $this->filterCalendar($this->events, array('field' => $post, 'value' => $postValue));
         }
     }
     $this->getFilter($filter);
     $postSession = array();
     foreach (array_keys($filter) as $postField) {
         $postValue = \Input::post($postField);
         if (!$postValue || $postValue === '') {
             continue;
         }
         $postSession[$postField] = $postValue;
     }
     if (count($postSession) > 0) {
         \Session::getInstance()->set('eventlistfilterpost_' . $this->eventList->id, $postSession);
     }
     if (count($postSession) < 1) {
         \Session::getInstance()->set('eventlistfilterpost_' . $this->eventList->id, null);
     }
     $this->eventList->Template->filterForm = $this->compileFilterForm($filter);
     $reload = false;
     if (\Session::getInstance()->get('eventlistfilterreload_' . $this->eventList->id)) {
         foreach ($this->eventList->calendarFilterField as $filterField) {
             if (\Input::post($filterField) != null && \Input::post($filterField) !== '0') {
                 $reload = true;
             }
         }
     }
     if ($reload) {
         \Session::getInstance()->set('eventlistfilterreload_' . $this->eventList->id, true);
         \Controller::reload();
     }
     return $this->events;
 }
Example #13
0
 /**
  * Display a login form
  *
  * @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']['login'][0]) . ' ###';
         $objTemplate->title = $this->headline;
         $objTemplate->id = $this->id;
         $objTemplate->link = $this->name;
         $objTemplate->href = '' . $GLOBALS['TL_CONFIG']['backendPath'] . '/main.php?do=themes&amp;table=tl_module&amp;act=edit&amp;id=' . $this->id;
         return $objTemplate->parse();
     }
     // Set the last page visited
     if (!$_POST && $this->redirectBack) {
         $_SESSION['LAST_PAGE_VISITED'] = $this->getReferer();
     }
     // Login
     if (\Input::post('FORM_SUBMIT') == 'tl_login') {
         // Check whether username and password are set
         if (empty($_POST['username']) || empty($_POST['password'])) {
             $_SESSION['LOGIN_ERROR'] = $GLOBALS['TL_LANG']['MSC']['emptyField'];
             $this->reload();
         }
         $this->import('FrontendUser', 'User');
         $strRedirect = \Environment::get('request');
         // Redirect to the last page visited
         if ($this->redirectBack && $_SESSION['LAST_PAGE_VISITED'] != '') {
             $strRedirect = $_SESSION['LAST_PAGE_VISITED'];
         } else {
             // Redirect to the jumpTo page
             if ($this->jumpTo && ($objTarget = $this->objModel->getRelated('jumpTo')) !== null) {
                 $strRedirect = $this->generateFrontendUrl($objTarget->row());
             }
             // Overwrite the jumpTo page with an individual group setting
             $objMember = \MemberModel::findByUsername(\Input::post('username'));
             if ($objMember !== null) {
                 $arrGroups = deserialize($objMember->groups);
                 if (!empty($arrGroups) && is_array($arrGroups)) {
                     $objGroupPage = \MemberGroupModel::findFirstActiveWithJumpToByIds($arrGroups);
                     if ($objGroupPage !== null) {
                         $strRedirect = $this->generateFrontendUrl($objGroupPage->row());
                     }
                 }
             }
         }
         // Auto login is not allowed
         if (isset($_POST['autologin']) && !$this->autologin) {
             unset($_POST['autologin']);
             \Input::setPost('autologin', null);
         }
         // Login and redirect
         if ($this->User->login()) {
             $this->redirect($strRedirect);
         }
         $this->reload();
     }
     // Logout and redirect to the website root if the current page is protected
     if (\Input::post('FORM_SUBMIT') == 'tl_logout') {
         /** @var \PageModel $objPage */
         global $objPage;
         $this->import('FrontendUser', 'User');
         $strRedirect = \Environment::get('request');
         // Redirect to last page visited
         if ($this->redirectBack && strlen($_SESSION['LAST_PAGE_VISITED'])) {
             $strRedirect = $_SESSION['LAST_PAGE_VISITED'];
         } elseif ($objPage->protected) {
             $strRedirect = \Environment::get('base');
         }
         // Logout and redirect
         if ($this->User->logout()) {
             $this->redirect($strRedirect);
         }
         $this->reload();
     }
     return parent::generate();
 }
Example #14
0
 /**
  * Pre-fill the "alt" and "caption" fields with the file meta data
  * @param mixed
  * @param \DataContainer
  * @return mixed
  */
 public function storeFileMetaInformation($varValue, \DataContainer $dc)
 {
     if ($dc->activeRecord->singleSRC == $varValue) {
         return $varValue;
     }
     $objFile = \FilesModel::findByUuid($varValue);
     if ($objFile !== null) {
         $arrMeta = deserialize($objFile->meta);
         if (!empty($arrMeta)) {
             $strLanguage = "de";
             if (isset($arrMeta[$strLanguage])) {
                 \Input::setPost('alt', $arrMeta[$strLanguage]['title']);
                 \Input::setPost('caption', $arrMeta[$strLanguage]['caption']);
             }
         }
     }
     return $varValue;
 }
 /**
  * loadDataContainer hook
  *
  * - Saves the referrer in the session if it is a frontend URL
  * - Preselects the original template in the template editor
  *
  * @param  string $table The data container table name
  * @return void
  */
 public function loadDataContainerHook($table)
 {
     if (TL_MODE !== 'BE') {
         return;
     }
     if (defined('TL_REFERER_ID') && \Input::get('ref')) {
         $referrerSession = \Session::getInstance()->get('referer');
         if (!empty($referrerSession[\Input::get('ref')]['current'])) {
             $referrerSession[\Input::get('ref')]['current'] = preg_replace('(([&?])rsfhr=1(&|$))', '$1', $referrerSession[\Input::get('ref')]['current']);
             \Session::getInstance()->set('referer', $referrerSession);
         }
     }
     // Only handle requests from the frontend helper
     if (!\Input::get('rsfhr')) {
         return;
     }
     if ($table === 'tl_templates' && \Input::get('key') === 'new_tpl') {
         if (\Input::get('original') && !\Input::post('original')) {
             // Preselect the original template
             \Input::setPost('original', \Input::get('original'));
         }
         if (\Input::get('target') && !\Input::post('target')) {
             // Preselect the target template folder
             \Input::setPost('target', \Input::get('target'));
         }
     }
     $base = \Environment::get('path');
     if (version_compare(VERSION, '4.0', '>=')) {
         $base .= \System::getContainer()->get('router')->generate('contao_backend');
     } else {
         $base .= '/contao';
     }
     $referrer = parse_url(\Environment::get('httpReferer'));
     $referrer = $referrer['path'] . ($referrer['query'] ? '?' . $referrer['query'] : '');
     // Stop if the referrer is a backend URL
     if (substr($referrer, 0, strlen($base)) === $base && in_array(substr($referrer, strlen($base), 1), array(false, '/', '?'), true)) {
         return;
     }
     // Fix empty referrers
     if (empty($referrer)) {
         $referrer = '/';
     }
     // Make homepage possible as referrer
     if ($referrer === \Environment::get('path') . '/') {
         $referrer .= '?';
     }
     $assetsDir = version_compare(VERSION, '4.0', '>=') ? 'bundles/rocksolidfrontendhelper' : 'system/modules/rocksolid-frontend-helper/assets';
     $referrer = \Environment::get('path') . '/' . $assetsDir . '/html/referrer.html?referrer=' . rawurlencode($referrer);
     // set the frontend URL as referrer
     $referrerSession = \Session::getInstance()->get('referer');
     if (defined('TL_REFERER_ID') && !\Input::get('ref')) {
         $referrer = substr($referrer, strlen(TL_PATH) + 1);
         $tlRefererId = substr(md5(TL_START - 1), 0, 8);
         $referrerSession[$tlRefererId]['current'] = $referrer;
         \Input::setGet('ref', $tlRefererId);
         $requestUri = \Environment::get('requestUri');
         $requestUri .= (strpos($requestUri, '?') === false ? '?' : '&') . 'ref=' . $tlRefererId;
         \Environment::set('requestUri', $requestUri);
         if (version_compare(VERSION, '4.0', '>=')) {
             \System::getContainer()->get('request_stack')->getCurrentRequest()->query->set('ref', $tlRefererId);
         }
     } else {
         if (!defined('TL_REFERER_ID')) {
             $referrerSession['current'] = $referrer;
         }
     }
     \Session::getInstance()->set('referer', $referrerSession);
 }
 /**
  * generate an albumalias based on the albumname and create a directory of the same name
  * and register the directory in tl files
  * @param $strAlias
  * @param \Contao\DataContainer $dc
  * @return mixed|string
  */
 public function saveCbGenerateAlias($strAlias, \Contao\DataContainer $dc)
 {
     $blnDoNotCreateDir = false;
     // get current row
     $objAlbum = GalleryCreatorAlbumsModel::findByPk($dc->id);
     if ($objAlbum === null) {
         return;
     }
     // Save assigned Dir if it was defined.
     if ($this->Input->post('FORM_SUBMIT') && strlen($this->Input->post('assignedDir'))) {
         $objAlbum->assignedDir = $this->Input->post('assignedDir');
         $objAlbum->save();
         $blnDoNotCreateDir = true;
     }
     $strAlias = standardize($strAlias);
     // if there isn't an existing albumalias generate one from the albumname
     if (!strlen($strAlias)) {
         $strAlias = standardize($dc->activeRecord->name);
     }
     // limit alias to 50 characters
     $strAlias = substr($strAlias, 0, 43);
     // remove invalid characters
     $strAlias = preg_replace("/[^a-z0-9\\_\\-]/", "", $strAlias);
     // if alias already exists add the album-id to the alias
     $objAlb = $this->Database->prepare('SELECT * FROM tl_gallery_creator_albums WHERE id!=? AND alias=?')->execute($dc->activeRecord->id, $strAlias);
     if ($objAlb->numRows) {
         $strAlias = 'id-' . $dc->id . '-' . $strAlias;
     }
     // Create default upload folder
     if ($blnDoNotCreateDir === false) {
         // create the new folder and register it in tl_files
         $objFolder = new Folder($this->uploadPath . '/' . $strAlias);
         $oFolder = Dbafs::addResource($objFolder->path, true);
         $objAlbum->assignedDir = $oFolder->uuid;
         $objAlbum->save();
         // Important
         Input::setPost('assignedDir', String::binToUuid($objAlbum->assignedDir));
     }
     return $strAlias;
 }
Example #17
0
 /**
  * Validate input and return address data
  * @return  array
  */
 protected function validateFields($blnValidate)
 {
     $arrAddress = array();
     $arrWidgets = $this->getWidgets();
     foreach ($arrWidgets as $strName => $objWidget) {
         $arrData =& $GLOBALS['TL_DCA'][\Isotope\Model\Address::getTable()]['fields'][$strName];
         // Validate input
         if ($blnValidate) {
             $objWidget->validate();
             $varValue = $objWidget->value;
             // Convert date formats into timestamps
             if (strlen($varValue) && in_array($arrData['eval']['rgxp'], array('date', 'time', 'datim'))) {
                 try {
                     $objDate = new \Date($varValue, $GLOBALS['TL_CONFIG'][$arrData['eval']['rgxp'] . 'Format']);
                     $varValue = $objDate->tstamp;
                 } catch (\OutOfBoundsException $e) {
                     $objWidget->addError(sprintf($GLOBALS['TL_LANG']['ERR'][$arrData['eval']['rgxp']], $GLOBALS['TL_CONFIG'][$arrData['eval']['rgxp'] . 'Format']));
                 }
             }
             // Do not submit if there are errors
             if ($objWidget->hasErrors()) {
                 $this->blnError = true;
             } elseif ($objWidget->submitInput()) {
                 $arrAddress[$strName] = $varValue;
             }
         } else {
             \Input::setPost($objWidget->name, $objWidget->value);
             $objValidator = clone $objWidget;
             $objValidator->validate();
             if ($objValidator->hasErrors()) {
                 $this->blnError = true;
             }
         }
     }
     return $arrAddress;
 }
 /**
  * Validates a field.
  *
  * @param \FormFieldModel $formField
  * @param int             $step
  *
  * @return bool
  */
 public function validateField(\FormFieldModel $formField, $step)
 {
     $class = $GLOBALS['TL_FFL'][$formField->type];
     if (!class_exists($class)) {
         return true;
     }
     /** @var \Widget $widget */
     $widget = new $class($formField->row());
     $widget->required = $formField->mandatory ? true : false;
     // Needed for the hook
     $form = $this->createDummyForm();
     // HOOK: load form field callback
     if (isset($GLOBALS['TL_HOOKS']['loadFormField']) && is_array($GLOBALS['TL_HOOKS']['loadFormField'])) {
         foreach ($GLOBALS['TL_HOOKS']['loadFormField'] as $callback) {
             $objCallback = \System::importStatic($callback[0]);
             $widget = $objCallback->{$callback[1]}($widget, $this->getFormId(), $this->formModel->row(), $form);
         }
     }
     // Validation (needs to set POST values because the widget class searches
     // only in POST values :-(
     // This should only happen if value is not currently submitted and if
     // the value is neither submitted in POST nor in the session, we have
     // to default it to an empty string so the widget validates for mandatory
     // fields
     $fakeValidation = false;
     if (!isset($_POST[$widget->name])) {
         if ($this->isStoredInData($widget->name, $step)) {
             $value = $this->fetchFromData($widget->name, $step);
         } else {
             $value = '';
         }
         \Input::setPost($formField->name, $value);
         $fakeValidation = true;
     }
     $widget->validate();
     // Reset fake validation
     if ($fakeValidation) {
         \Input::setPost($formField->name, null);
     }
     // Special hack for upload fields because they delete $_FILES and thus
     // multiple validation calls will fail - sigh
     if ($widget instanceof \uploadable && isset($_SESSION['FILES'][$widget->name])) {
         $_FILES[$widget->name] = $_SESSION['FILES'][$widget->name];
     }
     // HOOK: validate form field callback
     if (isset($GLOBALS['TL_HOOKS']['validateFormField']) && is_array($GLOBALS['TL_HOOKS']['validateFormField'])) {
         foreach ($GLOBALS['TL_HOOKS']['validateFormField'] as $callback) {
             $objCallback = \System::importStatic($callback[0]);
             $widget = $objCallback->{$callback[1]}($widget, $this->getFormId(), $this->formModel->row(), $form);
         }
     }
     return !$widget->hasErrors();
 }
 /**
  * Add the file meta information to the request
  *
  * @param string  $strUuid
  * @param string  $strPtable
  * @param integer $intPid
  */
 public static function addFileMetaInformationToRequest($strUuid, $strPtable, $intPid)
 {
     $objFile = \FilesModel::findByUuid($strUuid);
     if ($objFile === null) {
         return;
     }
     $arrMeta = deserialize($objFile->meta);
     if (empty($arrMeta)) {
         return;
     }
     $objPage = null;
     $db = \Database::getInstance();
     switch ($strPtable) {
         case 'tl_article':
             $objPage = $db->prepare("SELECT * FROM tl_page WHERE id=(SELECT pid FROM tl_article WHERE id=?)")->execute($intPid);
             break;
         case 'tl_news':
             $objPage = $db->prepare("SELECT * FROM tl_page WHERE id=(SELECT jumpTo FROM tl_news_archive WHERE id=(SELECT pid FROM tl_news WHERE id=?))")->execute($intPid);
             break;
         case 'tl_news_archive':
             $objPage = $db->prepare("SELECT * FROM tl_page WHERE id=(SELECT jumpTo FROM tl_news_archive WHERE id=?)")->execute($intPid);
             break;
         case 'tl_calendar_events':
             $objPage = $db->prepare("SELECT * FROM tl_page WHERE id=(SELECT jumpTo FROM tl_calendar WHERE id=(SELECT pid FROM tl_calendar_events WHERE id=?))")->execute($intPid);
             break;
         case 'tl_calendar':
             $objPage = $db->prepare("SELECT * FROM tl_page WHERE id=(SELECT jumpTo FROM tl_calendar WHERE id=?)")->execute($intPid);
             break;
         case 'tl_faq_category':
             $objPage = $db->prepare("SELECT * FROM tl_page WHERE id=(SELECT jumpTo FROM tl_faq_category WHERE id=?)")->execute($intPid);
             break;
         default:
             // HOOK: support custom modules
             if (isset($GLOBALS['TL_HOOKS']['addFileMetaInformationToRequest']) && is_array($GLOBALS['TL_HOOKS']['addFileMetaInformationToRequest'])) {
                 foreach ($GLOBALS['TL_HOOKS']['addFileMetaInformationToRequest'] as $callback) {
                     if (($val = \System::importStatic($callback[0])->{$callback[1]}($strPtable, $intPid)) !== false) {
                         $objPage = $val;
                     }
                 }
             }
             break;
     }
     if ($objPage === null || $objPage->numRows < 1) {
         return;
     }
     $objModel = new \PageModel();
     $objModel->setRow($objPage->row());
     $objModel->loadDetails();
     // Convert the language to a locale (see #5678)
     $strLanguage = str_replace('-', '_', $objModel->rootLanguage);
     if (isset($arrMeta[$strLanguage])) {
         if (\Input::post('alt') == '' && !empty($arrMeta[$strLanguage]['title'])) {
             \Input::setPost('alt', $arrMeta[$strLanguage]['title']);
         }
         if (\Input::post('caption') == '' && !empty($arrMeta[$strLanguage]['caption'])) {
             \Input::setPost('caption', $arrMeta[$strLanguage]['caption']);
         }
     }
 }
 public function generate()
 {
     if (TL_MODE == 'BE') {
         $objTemplate = new \BackendTemplate('be_wildcard');
         $objTemplate->wildcard = '### ' . utf8_strtoupper($GLOBALS['TL_LANG']['FMD']['loginregistration'][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();
     }
     // required by ModuleRegistration::generate();
     $this->editable = array('username', 'password');
     $this->allowedMailDomains = deserialize($this->allowedMailDomains, true);
     $this->domainCheck = false;
     $this->domainList = $this->getDomainList();
     if (is_array($this->domainList) && !empty($this->domainList)) {
         $this->domainCheck = true;
     }
     // Set the last page visited
     if ($this->redirectBack) {
         $_SESSION['LAST_PAGE_VISITED'] = $this->getReferer();
     }
     // Redirect to the jumpTo page if user is logged in and permanentRedirect is enables
     if (FE_USER_LOGGED_IN && $this->redirectPermanent) {
         $this->redirect($this->getJumpTo());
     }
     // Login
     if (\Input::post('FORM_SUBMIT') == 'tl_login') {
         // Check whether username and password are set
         if (empty($_POST['username']) || empty($_POST['password'])) {
             $_SESSION['LOGIN_ERROR'] = $GLOBALS['TL_LANG']['MSC']['emptyField'];
             $this->reload();
         }
         $strRedirect = $this->getJumpTo();
         $this->import('FrontendUser', 'User');
         // Auto login is not allowed
         if (isset($_POST['autologin']) && !$this->autologin) {
             unset($_POST['autologin']);
             \Input::setPost('autologin', null);
         }
         // Login existing user, or try to get username-domain-combination or register
         if ($this->User->login()) {
             $this->redirect($strRedirect);
         } else {
             $username = $_POST['username'];
             if ($this->domainCheck || \Validator::isEmail($username)) {
                 if (($username = $this->getValidDomainUsername()) === null) {
                     $this->reload();
                 }
                 // overwrite the username
                 $username = strtolower($username);
                 $_POST['username'] = $username;
                 \Input::setPost('username', $username);
                 if ($this->User->login()) {
                     $this->redirect($strRedirect);
                 }
                 $this->registerUser($username);
             }
         }
         $this->reload();
     }
     // Logout and redirect to the website root if the current page is protected
     if (\Input::post('FORM_SUBMIT') == 'tl_logout') {
         global $objPage;
         $this->import('FrontendUser', 'User');
         $strRedirect = \Environment::get('request');
         // Redirect to last page visited
         if ($this->redirectBack && strlen($_SESSION['LAST_PAGE_VISITED'])) {
             $strRedirect = $_SESSION['LAST_PAGE_VISITED'];
         } elseif ($objPage->protected) {
             $strRedirect = \Environment::get('base');
         }
         // Logout and redirect
         if ($this->User->logout()) {
             $this->redirect($strRedirect);
         }
         $this->reload();
     }
     return parent::generate();
 }
Example #21
0
 /**
  * Run the communication as client
  *
  * @return void
  */
 public function run()
 {
     // If we have a ping, just do nothing
     if (\Input::get("act") == "ping") {
         // Clean output buffer
         while (@ob_end_clean()) {
         }
         exit;
     }
     /* ---------------------------------------------------------------------
      * Check if we have a old AES or a new AES with IV.
      * Set codifyengine keys.
      * Check the connection ID and refresh/delete it.
      */
     // Check if IV was send, when send use the new AES else the old one.
     try {
         $this->objCodifyengineBasic = Factory::getEngine("aes");
         $this->setCodifyengine(\Input::get("engine"));
     } catch (\RuntimeException $exc) {
         \System::log("Try to load the engine for ctoCommunication with error: " . $exc->getMessage(), __FUNCTION__ . " | " . __CLASS__, TL_ERROR);
         // Clean output buffer
         while (@ob_end_clean()) {
         }
         exit;
     }
     // Check if we have a incomming connection for handshake
     if (in_array(\Input::get("act"), array("CTOCOM_HELLO", "CTOCOM_START_HANDSHAKE", "CTOCOM_CHECK_HANDSHAKE", "CTOCOM_VERSION"))) {
         $this->objCodifyengine->setKey($GLOBALS['TL_CONFIG']['ctoCom_APIKey']);
         $this->objCodifyengineBasic->setKey($GLOBALS['TL_CONFIG']['ctoCom_APIKey']);
         $strCodifyKey = $GLOBALS['TL_CONFIG']['ctoCom_APIKey'];
     } else {
         // Use the private key from connection pool
         if (strlen(\Input::get("con")) != 0) {
             // Check if we have some data
             $arrConnections = \Database::getInstance()->prepare("SELECT * FROM tl_ctocom_cache WHERE uid=?")->execute(\Input::get("con"))->fetchAllAssoc();
             if (count($arrConnections) == 0) {
                 \System::log(vsprintf("Call from %s with a unknown connection ID.", \Environment::get('ip')), __FUNCTION__ . " | " . __CLASS__, TL_ERROR);
                 // Clean output buffer
                 while (@ob_end_clean()) {
                 }
                 exit;
             }
             // Check if time out isn't reached.
             if ($arrConnections[0]["tstamp"] + $this->intHandshakeTimeout < time()) {
                 \Database::getInstance()->prepare("DELETE FROM tl_ctocom_cache WHERE uid=?")->execute(\Input::get("con"));
                 \System::log(vsprintf("Call from %s with a expired connection ID.", \Environment::get('ip')), __FUNCTION__ . " | " . __CLASS__, TL_ERROR);
                 // Clean output buffer
                 while (@ob_end_clean()) {
                 }
                 exit;
             }
             // Reset timestamp
             \Database::getInstance()->prepare("UPDATE tl_ctocom_cache %s WHERE uid=?")->set(array("tstamp" => time()))->execute(\Input::get("con"));
             // Set codify key from database
             $this->objCodifyengineBasic->setKey($arrConnections[0]["shared_secret_key"]);
             $this->objCodifyengine->setKey($arrConnections[0]["shared_secret_key"]);
             $strCodifyKey = $arrConnections[0]["shared_secret_key"];
         } else {
             \System::log(vsprintf("Call from %s without a connection ID.", \Environment::get('ip')), __FUNCTION__ . " | " . __CLASS__, TL_ERROR);
             // Clean output buffer
             while (@ob_end_clean()) {
             }
             exit;
         }
     }
     /* ---------------------------------------------------------------------
      * Check the API key.
      * Check if the API Key was send.
      * Check if the API key contains the RPC Call and the API Key from this
      * Contao Version.
      */
     // Check if a API-Key was send
     if (strlen(\Input::get("apikey")) == 0) {
         \System::log(vsprintf("Call from %s without a API Key.", \Environment::get('ip')), __FUNCTION__ . " | " . __CLASS__, TL_ERROR);
         // Clean output buffer
         while (@ob_end_clean()) {
         }
         exit;
     }
     // Check RPC Call from get and the RPC Call from API-Key
     $mixVar = $this->objCodifyengineBasic->Decrypt(base64_decode(\Input::get("apikey", true)));
     $mixVar = trimsplit("@\\|@", $mixVar);
     $strApiKey = $mixVar[1];
     $strAction = $mixVar[0];
     if ($strAction != \Input::get("act")) {
         \System::log(vsprintf("Error Api Key from %s. Request action: %s | Key action: %s | Api: %s", array(\Environment::get('ip'), \Input::get("act"), $strAction, $strApiKey)), __FUNCTION__ . " | " . __CLASS__, TL_ERROR);
         // Clean output buffer
         while (@ob_end_clean()) {
         }
         exit;
     }
     if ($GLOBALS['TL_CONFIG']['ctoCom_APIKey'] != $strApiKey) {
         \System::log(vsprintf("Call from %s with a wrong API Key: %s", array(\Environment::get('ip'), \Input::get("apikey"))), __FUNCTION__ . " | " . __CLASS__, TL_ERROR);
         // Clean output buffer
         while (@ob_end_clean()) {
         }
         exit;
     }
     /* ---------------------------------------------------------------------
      * Check language settings
      */
     if (empty($GLOBALS['TL_LANGUAGE'])) {
         $GLOBALS['TL_LANGUAGE'] = "en";
     }
     /* ---------------------------------------------------------------------
      * Set I/O System
      */
     if (strlen(\Input::get("format")) != 0) {
         if (\CtoCommunication\InputOutput\Factory::engineExist(\Input::get("format"))) {
             $this->setIOEngine(\Input::get("format"));
         } else {
             $this->setIOEngine();
             $this->objError = new Error();
             $this->objError->setLanguage("unknown_io");
             $this->objError->setID(10);
             $this->objError->setObject("");
             $this->objError->setMessage("No I/O Interface found for accept.");
             $this->objError->setRPC("");
             $this->objError->setClass("");
             $this->objError->setFunction("");
             $this->generateOutput();
             exit;
         }
     } else {
         $strAccept = $_SERVER['HTTP_ACCEPT'];
         $strAccept = preg_replace("/;q=\\d\\.\\d/", "", $strAccept);
         $arrAccept = trimsplit(",", $strAccept);
         $strIOEngine = false;
         foreach ($arrAccept as $key => $value) {
             $strIOEngine = \CtoCommunication\InputOutput\Factory::getEngingenameForAccept($value);
             if ($strIOEngine !== false) {
                 break;
             }
         }
         if ($strIOEngine === false) {
             $this->objIOEngine = \CtoCommunication\InputOutput\Factory::getEngine('default');
             $this->objError = new Error();
             $this->objError->setLanguage("unknown_io");
             $this->objError->setID(10);
             $this->objError->setObject("");
             $this->objError->setMessage("No I/O Interface found for accept: {$strAccept}");
             $this->objError->setRPC("");
             $this->objError->setClass("");
             $this->objError->setFunction("");
             $this->generateOutput();
             exit;
         } else {
             $this->setIOEngine($strIOEngine);
         }
     }
     /* ---------------------------------------------------------------------
      * Run RPC-Check function
      */
     // Check if act is set
     $mixRPCCall = \Input::get("act");
     if (strlen($mixRPCCall) == 0) {
         $this->objError = new Error();
         $this->objError->setLanguage("rpc_missing");
         $this->objError->setID(1);
         $this->objError->setObject("");
         $this->objError->setMessage("Missing RPC Call");
         $this->objError->setRPC($mixRPCCall);
         $this->objError->setClass("");
         $this->objError->setFunction("");
         $this->generateOutput();
         exit;
     }
     if (!array_key_exists($mixRPCCall, $this->arrRpcList)) {
         $this->objError = new Error();
         $this->objError->setLanguage("rpc_unknown");
         $this->objError->setID(1);
         $this->objError->setObject("");
         $this->objError->setMessage("Unknown RPC Call");
         $this->objError->setRPC($mixRPCCall);
         $this->objError->setClass("");
         $this->objError->setFunction("");
         $this->generateOutput();
         exit;
     }
     /* ---------------------------------------------------------------------
      * Build a list with parameter from the POST
      */
     $arrParameter = array();
     if ($this->arrRpcList[$mixRPCCall]["parameter"] != false && is_array($this->arrRpcList[$mixRPCCall]["parameter"])) {
         switch ($this->arrRpcList[$mixRPCCall]["typ"]) {
             // Decode post
             case "POST":
                 // Decode each post
                 $arrPostValues = array();
                 foreach ($_POST as $key => $value) {
                     if (version_compare('3.2.16', VERSION . '.' . BUILD, '<=') && version_compare('3.3.0', VERSION . '.' . BUILD, '>') || version_compare('3.3.7', VERSION . '.' . BUILD, '<=')) {
                         // Get the raw data.
                         $mixPost = \Input::postUnsafeRaw($key);
                     } else {
                         // Get the raw data for older contao versions.
                         $mixPost = \Input::postRaw($key);
                     }
                     $mixPost = $this->objIOEngine->InputPost($mixPost, $this->objCodifyengine);
                     $arrPostValues[$key] = $mixPost;
                     \Input::setPost($key, $mixPost);
                 }
                 // Check if all post are set
                 foreach ($this->arrRpcList[$mixRPCCall]["parameter"] as $value) {
                     $arrPostKey = array_keys($arrPostValues);
                     if (!in_array($value, $arrPostKey)) {
                         $arrParameter[$value] = null;
                     } else {
                         // Get the raw data.
                         $arrParameter[$value] = $arrPostValues[$value];
                     }
                 }
                 unset($arrPostValues);
                 break;
             default:
                 break;
         }
     }
     /* ---------------------------------------------------------------------
      * Call function
      */
     try {
         $strClassname = $this->arrRpcList[$mixRPCCall]["class"];
         if (!class_exists($strClassname)) {
             $this->objError = new Error();
             $this->objError->setLanguage("rpc_class_not_exists");
             $this->objError->setID(4);
             $this->objError->setObject($value);
             $this->objError->setMessage("The choosen class didn`t exists.");
             $this->objError->setRPC($mixRPCCall);
             $this->objError->setClass($this->arrRpcList[$mixRPCCall]["class"]);
             $this->objError->setFunction($this->arrRpcList[$mixRPCCall]["function"]);
             $this->generateOutput();
             exit;
         }
         $objReflection = new \ReflectionClass($strClassname);
         if ($objReflection->hasMethod("getInstance")) {
             $object = call_user_func_array(array($this->arrRpcList[$mixRPCCall]["class"], "getInstance"), array());
             $this->mixOutput = call_user_func_array(array($object, $this->arrRpcList[$mixRPCCall]["function"]), $arrParameter);
         } else {
             $object = new $this->arrRpcList[$mixRPCCall]["class"]();
             $this->mixOutput = call_user_func_array(array($object, $this->arrRpcList[$mixRPCCall]["function"]), $arrParameter);
         }
     } catch (\Exception $exc) {
         $this->objError = new Error();
         $this->objError->setLanguage("rpc_unknown_exception");
         $this->objError->setID(3);
         $this->objError->setObject("");
         $this->objError->setMessage($exc->getMessage());
         $this->objError->setRPC($mixRPCCall);
         $this->objError->setClass($this->arrRpcList[$mixRPCCall]["class"]);
         $this->objError->setFunction($this->arrRpcList[$mixRPCCall]["function"]);
         $this->objError->setException($exc);
         \System::log(vsprintf("RPC Exception: %s | %s", array($exc->getMessage(), nl2br($exc->getTraceAsString()))), __CLASS__ . " | " . __FUNCTION__, TL_ERROR);
         $this->generateOutput();
         exit;
     }
     $this->generateOutput();
     exit;
 }
 /**
  * Restore the GET and POST vars to Contao's Input class
  */
 public static function restore()
 {
     if (isset(static::$arrCache['getEncoded'])) {
         foreach (static::$arrCache['getEncoded'] as $strKey => $varValue) {
             \Input::setGet($strKey, $varValue);
         }
     }
     if (isset(static::$arrCache['postEncoded'])) {
         foreach (static::$arrCache['postEncoded'] as $strKey => $varValue) {
             \Input::setPost($strKey, $varValue);
         }
     }
 }
 /**
  * @param \File $objCsvFile
  * @param $strTable
  * @param $strImportMode
  * @param null $arrSelectedFields
  * @param string $strFieldseparator
  * @param string $strFieldenclosure
  * @param string $strPrimaryKey
  * @param string $arrDelim
  */
 public function importCsv(\File $objCsvFile, $strTable, $strImportMode, $arrSelectedFields = null, $strFieldseparator = ';', $strFieldenclosure = '', $strPrimaryKey = 'id', $arrDelim = '||', $blnTestMode = false)
 {
     // store sucess or failure message in the session
     $_SESSION['import_from_csv']['report'] = array();
     // load language file
     \System::loadLanguageFile($strTable);
     // load dca
     $this->loadDataContainer($strTable);
     // store the options in $this->arrData
     $this->arrData = array('tablename' => $strTable, 'primaryKey' => $strPrimaryKey, 'importMode' => $strImportMode, 'selectedFields' => is_array($arrSelectedFields) ? $arrSelectedFields : array(), 'fieldSeparator' => $strFieldseparator, 'fieldEnclosure' => $strFieldenclosure);
     // truncate table
     if ($this->arrData['importMode'] == 'truncate_table') {
         $this->Database->execute('TRUNCATE TABLE `' . $strTable . '`');
     }
     if (count($this->arrData['selectedFields']) < 1) {
         return;
     }
     // get content as array
     $arrFileContent = $objCsvFile->getContentAsArray();
     $arrFieldnames = explode($this->arrData['fieldSeparator'], $arrFileContent[0]);
     // trim quotes in the first line and get the fieldnames
     $arrFieldnames = array_map(array($this, 'myTrim'), $arrFieldnames);
     // count rows
     $rows = 0;
     // count errors
     $insertError = 0;
     // store each line as an entry in the db
     foreach ($arrFileContent as $line => $lineContent) {
         $doNotSave = false;
         // line 0 contains the fieldnames
         if ($line == 0) {
             continue;
         }
         // count rows
         $rows++;
         // separate the line into the different fields
         $arrLine = explode($this->arrData['fieldSeparator'], $lineContent);
         // Set the associative Array with the line content
         $assocArrayLine = array();
         foreach ($arrFieldnames as $k => $fieldname) {
             $assocArrayLine[$fieldname] = $arrLine[$k];
         }
         $set = array();
         foreach ($arrFieldnames as $k => $fieldname) {
             $blnCustomValidation = false;
             // continue if field is excluded from import
             if (!in_array($fieldname, $this->arrData['selectedFields'])) {
                 continue;
             }
             // if entries are appended autoincrement id
             if ($this->arrData['importMode'] == 'append_entries' && strtolower($fieldname) == $this->arrData['primaryKey']) {
                 continue;
             }
             // get the field content
             $fieldValue = $arrLine[$k];
             // trim quotes
             $fieldValue = $this->myTrim($fieldValue);
             // convert variable to a string (see #2)
             $fieldValue = strval($fieldValue);
             // get the DCA of the current field
             $arrDCA =& $GLOBALS['TL_DCA'][$strTable]['fields'][$fieldname];
             $arrDCA = is_array($arrDCA) ? $arrDCA : array();
             // Prepare FormWidget object !set inputType to "text" if there is no definition
             $inputType = $arrDCA['inputType'] != '' ? $arrDCA['inputType'] : 'text';
             // Map checkboxWizards to regular checkbox widgets
             if ($inputType == 'checkboxWizard') {
                 $inputType = 'checkbox';
             }
             $strClass =& $GLOBALS['TL_FFL'][$inputType];
             // HOOK: add custom validation
             if (isset($GLOBALS['TL_HOOKS']['importFromCsv']) && is_array($GLOBALS['TL_HOOKS']['importFromCsv'])) {
                 $arrCustomValidation = array('strTable' => $strTable, 'arrDCA' => $arrDCA, 'fieldname' => $fieldname, 'value' => $fieldValue, 'arrayLine' => $assocArrayLine, 'line' => $line, 'objCsvFile' => $objCsvFile, 'skipWidgetValidation' => false, 'hasErrors' => false, 'errorMsg' => null, 'doNotSave' => false, 'blnTestMode' => $blnTestMode);
                 $blnCustomValidation = false;
                 foreach ($GLOBALS['TL_HOOKS']['importFromCsv'] as $callback) {
                     $this->import($callback[0]);
                     $arrCustomValidation = $this->{$callback[0]}->{$callback[1]}($arrCustomValidation, $this);
                     if (!is_array($arrCustomValidation)) {
                         die('Als Rückgabewert wird ein Array erwartet. Fehler in ' . __FILE__ . ' in Zeile ' . __LINE__ . '.');
                     }
                     $fieldValue = $arrCustomValidation['value'];
                     // Check if widget-validation should be skipped
                     if ($blnCustomValidation['skipWidgetValidation'] === true) {
                         $blnCustomValidation = true;
                     }
                 }
                 if ($arrCustomValidation['errorMsg'] != '') {
                     $fieldValue = sprintf('<span class="errMsg">%s</span>', $arrCustomValidation['errorMsg']);
                 }
                 if ($arrCustomValidation['doNotSave']) {
                     $doNotSave = true;
                 }
             }
             // Continue if the class does not exist
             // Use form widgets for input validation
             if (class_exists($strClass) && $blnCustomValidation === false) {
                 $objWidget = new $strClass($strClass::getAttributesFromDca($arrDCA, $fieldname, $fieldValue, '', '', $this));
                 $objWidget->storeValues = false;
                 // Set post var, so the content can be validated
                 \Input::setPost($fieldname, $fieldValue);
                 if ($fieldname == 'password') {
                     \Input::setPost('password_confirm', $fieldValue);
                 }
                 // add option values in the csv like this: value1||value2||value3
                 if ($inputType == 'radio' || $inputType == 'checkbox' || $inputType == 'select') {
                     if ($arrDCA['eval']['multiple'] === true) {
                         // Security issues in Contao #6695
                         if (version_compare(VERSION . BUILD, '3.2.5', '>=')) {
                             $fieldValue = $fieldValue != '' ? explode($arrDelim, $fieldValue) : null;
                         }
                         \Input::setPost($fieldname, $fieldValue);
                         $objWidget->value = $fieldValue;
                     }
                 }
                 // validate input
                 $objWidget->validate();
                 $fieldValue = $objWidget->value;
                 // Convert date formats into timestamps
                 $rgxp = $arrDCA['eval']['rgxp'];
                 if (($rgxp == 'date' || $rgxp == 'time' || $rgxp == 'datim') && $fieldValue != '' && !$objWidget->hasErrors()) {
                     try {
                         $strTimeFormat = $GLOBALS['TL_CONFIG'][$rgxp . 'Format'];
                         $objDate = new \Date($fieldValue, $strTimeFormat);
                         $fieldValue = $objDate->tstamp;
                     } catch (\OutOfBoundsException $e) {
                         $objWidget->addError(sprintf($GLOBALS['TL_LANG']['ERR']['invalidDate'], $fieldValue));
                     }
                 }
                 // Make sure that unique fields are unique
                 if ($arrDCA['eval']['unique'] && $fieldValue != '' && !$this->Database->isUniqueValue($strTable, $fieldname, $fieldValue, null)) {
                     $objWidget->addError(sprintf($GLOBALS['TL_LANG']['ERR']['unique'], $arrDCA['label'][0] ?: $fieldname));
                 }
                 // Do not save the field if there are errors
                 if ($objWidget->hasErrors()) {
                     $doNotSave = true;
                     $fieldValue = sprintf('"%s" => <span class="errMsg">%s</span>', $fieldValue, $objWidget->getErrorsAsString());
                 } else {
                     // Set the correct empty value
                     if ($fieldValue === '') {
                         $fieldValue = $objWidget->getEmptyValue();
                     }
                 }
             }
             $set[$fieldname] = is_array($fieldValue) ? serialize($fieldValue) : $fieldValue;
         }
         // insert data record
         if (!$doNotSave) {
             // insert tstamp
             if ($this->Database->fieldExists('tstamp', $strTable)) {
                 if (!$set['tstamp'] > 0) {
                     $set['tstamp'] = time();
                 }
             }
             // insert dateAdded (tl_member)
             if ($this->Database->fieldExists('dateAdded', $strTable)) {
                 if (!$set['dateAdded'] > 0) {
                     $set['dateAdded'] = time();
                 }
             }
             // add new member to newsletter recipient list
             if ($strTable == 'tl_member' && $set['email'] != '' && $set['newsletter'] != '') {
                 foreach (deserialize($set['newsletter'], true) as $newsletterId) {
                     // check for unique email-address
                     $objRecipient = $this->Database->prepare("SELECT * FROM tl_newsletter_recipients WHERE email=? AND pid=(SELECT pid FROM tl_newsletter_recipients WHERE id=?) AND id!=?")->execute($set['email'], $newsletterId, $newsletterId);
                     if (!$objRecipient->numRows) {
                         $arrRecipient = array();
                         $arrRecipient['tstamp'] = time();
                         $arrRecipient['pid'] = $newsletterId;
                         $arrRecipient['email'] = $set['email'];
                         $arrRecipient['active'] = '1';
                         if ($blnTestMode !== true) {
                             $this->Database->prepare('INSERT INTO tl_newsletter_recipients %s')->set($arrRecipient)->execute();
                         }
                     }
                 }
             }
             try {
                 if ($blnTestMode !== true) {
                     // insert entry into database
                     $this->Database->prepare('INSERT INTO ' . $strTable . ' %s')->set($set)->execute();
                 }
             } catch (\Exception $e) {
                 $set['insertError'] = $e->getMessage();
                 $doNotSave = true;
             }
         }
         // generate html markup for the import report table
         $htmlReport = '';
         $cssClass = 'allOk';
         if ($doNotSave) {
             $cssClass = 'error';
             $htmlReport .= sprintf('<tr class="%s"><td class="tdTitle" colspan="2">#%s Datensatz konnte nicht angelegt werden!</td></tr>', $cssClass, $line);
             // increment error counter if necessary
             $insertError++;
         } else {
             $htmlReport .= sprintf('<tr class="%s"><td class="tdTitle" colspan="2">#%s Datensatz erfolgreich angelegt!</td></tr>', $cssClass, $line);
         }
         foreach ($set as $k => $v) {
             if (is_array($v)) {
                 $v = serialize($v);
             }
             $htmlReport .= sprintf('<tr class="%s"><td>%s</td><td>%s</td></tr>', $cssClass, \StringUtil::substr($k, 30), \StringUtil::substrHtml($v, 90));
         }
         $htmlReport .= '<tr class="delim"><td>&nbsp;</td><td>&nbsp;</td></tr>';
         $_SESSION['import_from_csv']['report'][] = $htmlReport;
     }
     $_SESSION['import_from_csv']['status'] = array('blnTestMode' => $blnTestMode, 'rows' => $rows, 'success' => $rows - $insertError, 'errors' => $insertError);
 }
Example #24
0
 /**
  * Pre-fill the "alt" and "caption" fields with the file meta data
  *
  * @param mixed         $varValue
  * @param DataContainer $dc
  *
  * @return mixed
  */
 public function storeFileMetaInformation($varValue, DataContainer $dc)
 {
     if ($dc->activeRecord->singleSRC == $varValue) {
         return $varValue;
     }
     $objFile = FilesModel::findByUuid($varValue);
     if ($objFile !== null) {
         $arrMeta = deserialize($objFile->meta);
         if (!empty($arrMeta)) {
             $objPage = $this->Database->prepare("SELECT * FROM tl_page WHERE id=(SELECT pid FROM " . ($dc->activeRecord->ptable ?: 'tl_article') . " WHERE id=?)")->execute($dc->activeRecord->pid);
             if ($objPage->numRows) {
                 $objModel = new PageModel();
                 $objModel->setRow($objPage->row());
                 $objModel->loadDetails();
                 // Convert the language to a locale (see #5678)
                 $strLanguage = str_replace('-', '_', $objModel->rootLanguage);
                 if (isset($arrMeta[$strLanguage])) {
                     Input::setPost('alt', $arrMeta[$strLanguage]['title']);
                     Input::setPost('caption', $arrMeta[$strLanguage]['caption']);
                 }
             }
         }
     }
     return $varValue;
 }
Example #25
0
 /**
  * @param $arrData
  * @throws \Exception
  */
 protected function createNewEntity($arrData)
 {
     $tableData = $this->strTableData;
     // set default values
     $arrData['tstamp'] = time();
     $arrData['pid'] = $this->strPid;
     $arrData['alias'] = $this->generateAlias($arrData['alias'], $arrData);
     // search for geo cords
     $arrData = $this->createGeoCoding($arrData);
     // set default values from fe
     if ($this->fm_defaultValues) {
         $defaultValues = $this->fm_defaultValues ? deserialize($this->fm_defaultValues) : array();
         foreach ($defaultValues as $defaultValue) {
             $col = $defaultValue['key'];
             // parse value
             $value = $defaultValue['value'];
             $value = $this->decodeValue($value);
             $value = $this->replaceInsertTags($value);
             $dcaData = $this->dcaFields[$col];
             $dcaData = $this->convertWidgetToField($dcaData);
             \Input::setPost($col, $value);
             // check if get or post
             $strClass = $this->fieldClassExist($dcaData['inputType']);
             if ($strClass == false) {
                 continue;
             }
             // validate
             $objWidget = new $strClass($strClass::getAttributesFromDca($dcaData, $col, $dcaData['default'], '', '', $this));
             $objWidget->storeValues = true;
             $objWidget->validate();
             $varValue = $objWidget->value;
             $rgxp = $dcaData['eval']['rgxp'];
             // Convert date formats into timestamps (check the eval setting first -> #3063)
             if ($varValue != '' && in_array($rgxp, array('date', 'time', 'datim'))) {
                 try {
                     $objDate = new \Date($varValue, \Date::getFormatFromRgxp($rgxp));
                     $varValue = $objDate->tstamp;
                 } catch (\OutOfBoundsException $e) {
                     $objWidget->addError(sprintf($GLOBALS['TL_LANG']['ERR']['invalidDate'], $varValue));
                 }
             }
             // Make sure that unique fields are unique (check the eval setting first -> #3063)
             if ($dcaData['eval']['unique'] && $varValue != '' && !$this->Database->isUniqueValue($this->strTableData, $col, $varValue)) {
                 $objWidget->addError(sprintf($GLOBALS['TL_LANG']['ERR']['unique'], $dcaData['label'][0] ?: $col));
             }
             // Save callback
             if ($objWidget->submitInput() && !$objWidget->hasErrors() && is_array($dcaData['save_callback'])) {
                 foreach ($dcaData['save_callback'] as $callback) {
                     try {
                         if (is_array($callback)) {
                             $this->import($callback[0]);
                             $varValue = $this->{$callback[0]}->{$callback[1]}($varValue, null);
                         } elseif (is_callable($callback)) {
                             $varValue = $callback($varValue, null);
                         }
                     } catch (\Exception $e) {
                         $objWidget->class = 'error';
                         $objWidget->addError($e->getMessage());
                     }
                 }
             }
             if (!$objWidget->hasErrors()) {
                 // Set the correct empty value (see #6284, #6373)
                 if ($varValue === '') {
                     $varValue = $objWidget->getEmptyValue();
                 }
                 // Encrypt the value (see #7815)
                 if ($dcaData['eval']['encrypt']) {
                     $varValue = \Encryption::encrypt($varValue);
                 }
                 // Set the new value
                 $arrData[$col] = $varValue;
             }
         }
     }
     // set author
     if (!$arrData['author']) {
         $arrData['author'] = $this->fm_EntityAuthor;
     }
     // generate sql query
     $values = array();
     $cols = array();
     $placeholder = array();
     $arrCheckBoxes = array('markerSRC' => 'addMarker', 'singleSRC' => 'addImage', 'enclosure' => 'addEnclosure');
     // nur ein Hack
     $arrActive = array();
     foreach ($arrData as $col => $value) {
         $eval = $this->dcaFields[$col]['eval'];
         // activate palette in BE
         if ($arrCheckBoxes[$col] && $value) {
             $cols[] = $arrCheckBoxes[$col];
             $values[] = '1';
             $placeholder[] = '?';
         }
         $cols[] = $col;
         // check for multiple values
         if (isset($eval['multiple']) && $eval['multiple'] == true && isset($eval['csv'])) {
             // delimiter
             $delimiter = $eval['csv'];
             if ($delimiter === ',' && is_array($value)) {
                 $value = implode($delimiter, $value);
             }
         }
         // exception for cssID
         if ($col == 'cssID') {
             $value = explode(',', $value);
             $value = serialize($value);
         }
         $arrActive[$col] = $value;
         $values[] = $value;
         $placeholder[] = '?';
     }
     $strCols = implode(',', $cols);
     $strPlaceholder = implode(',', $placeholder);
     $strQuery = 'INSERT INTO ' . $tableData . ' (' . $strCols . ') VALUES (' . $strPlaceholder . ')';
     // save item
     \Session::getInstance()->set('FModuleActiveAttributes', $arrActive);
     unset($arrActive);
     // create new entity
     $this->Database->prepare($strQuery)->execute($values);
     // send Notification
     if ($this->fm_addNotificationEmail) {
         $this->sendNotification($arrData);
     }
     // send Confirmation
     if ($this->fm_addConfirmationEmail) {
         $this->sendConfirmation($arrData);
     }
     // Check whether there is a jumpTo page
     if ($this->jumpTo) {
         $objPage = \PageModel::findWithDetails($this->jumpTo);
         $this->jumpToOrReload($objPage->row());
     }
     $this->reload();
 }
Example #26
0
 /**
  * Set up the database connection
  */
 protected function setUpDatabaseConnection()
 {
     $strDrivers = '';
     $arrDrivers = array('');
     if (class_exists('mysqli', false)) {
         $arrDrivers[] = 'MySQLi';
     }
     if (function_exists('mysql_connect')) {
         $arrDrivers[] = 'MySQL';
     }
     // If there is another driver defined, add it here as well
     if (\Config::get('dbDriver') != '' && !in_array(\Config::get('dbDriver'), $arrDrivers)) {
         $arrDrivers[] = \Config::get('dbDriver');
     }
     foreach ($arrDrivers as $strDriver) {
         $strDrivers .= sprintf('<option value="%s"%s>%s</option>', $strDriver, $strDriver == \Config::get('dbDriver') ? ' selected="selected"' : '', $strDriver ?: '-');
     }
     $this->Template->drivers = $strDrivers;
     $this->Template->driver = \Config::get('dbDriver');
     $this->Template->host = \Config::get('dbHost');
     $this->Template->user = \Config::get('dbUser');
     $this->Template->pass = \Config::get('dbPass') != '' ? '*****' : '';
     $this->Template->port = \Config::get('dbPort');
     $this->Template->socket = \Config::get('dbSocket');
     $this->Template->pconnect = \Config::get('dbPconnect');
     $this->Template->dbcharset = \Config::get('dbCharset');
     $this->Template->database = \Config::get('dbDatabase');
     // Store the database connection parameters
     if (\Input::post('FORM_SUBMIT') == 'tl_database_login') {
         foreach (preg_grep('/^db/', array_keys($_POST)) as $strKey) {
             if ($strKey == 'dbPass' && \Input::postUnsafeRaw($strKey) == '*****') {
                 continue;
             }
             // The port number must not be empty (see #7950)
             if ($strKey == 'dbPort' && \Input::post($strKey, true) == '') {
                 \Input::setPost($strKey, 3306);
             }
             \Config::persist($strKey, $strKey == 'dbPass' ? \Input::postUnsafeRaw($strKey) : \Input::post($strKey, true));
         }
         $this->reload();
     }
     // No driver selected (see #6088)
     if (\Config::get('dbDriver') == '') {
         $this->Template->dbConnection = false;
         $this->outputAndExit();
     }
     // Try to connect
     try {
         $this->import('Database');
         $this->Database->listTables();
         $this->Template->dbConnection = true;
     } catch (\Exception $e) {
         $this->Template->dbConnection = false;
         $this->Template->dbError = $e->getMessage();
         $this->outputAndExit();
     }
 }
Example #27
0
 public function importFile()
 {
     if (\Input::get('key') != 'import') {
         return '';
     }
     if (null === $this->arrImportIgnoreFields) {
         $this->arrImportIgnoreFields = array('id', 'pid', 'tstamp', 'form', 'ip', 'date', 'confirmationSent', 'confirmationDate', 'import_source');
     }
     if (null === $this->arrImportableFields) {
         $arrFdFields = array_merge($this->arrBaseFields, $this->arrDetailFields);
         $arrFdFields = array_diff($arrFdFields, $this->arrImportIgnoreFields);
         foreach ($arrFdFields as $strFdField) {
             $this->arrImportableFields[$strFdField] = $GLOBALS['TL_DCA']['tl_formdata']['fields'][$strFdField]['label'][0];
         }
     }
     $arrSessionData = $this->Session->get('EFG');
     if (null == $arrSessionData) {
         $arrSessionData = array();
     }
     $this->Session->set('EFG', $arrSessionData);
     // Import CSV
     if ($_POST['FORM_SUBMIT'] == 'tl_formdata_import') {
         $this->loadDataContainer('tl_files');
         $strMode = 'preview';
         $arrSessionData['import'][$this->strFormKey]['separator'] = $_POST['separator'];
         $arrSessionData['import'][$this->strFormKey]['csv_has_header'] = $_POST['csv_has_header'] == '1' ? '1' : '';
         $this->Session->set('EFG', $arrSessionData);
         if (intval(\Input::post('import_source')) == 0) {
             \Message::addError($GLOBALS['TL_LANG']['tl_formdata']['error_select_source']);
             \Controller::reload();
         }
         $objFileModel = \FilesModel::findById(\Input::post('import_source'));
         $objFile = new \File($objFileModel->path, true);
         if ($objFile->extension != 'csv') {
             \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['filetype'], $objFile->extension));
             setcookie('BE_PAGE_OFFSET', 0, 0, '/');
             \Controller::reload();
         }
         // Get separator
         switch (\Input::post('separator')) {
             case 'semicolon':
                 $strSeparator = ';';
                 break;
             case 'tabulator':
                 $strSeparator = '\\t';
                 break;
             case 'comma':
             default:
                 $strSeparator = ',';
                 break;
         }
         if ($_POST['FORM_MODE'] == 'import') {
             $strMode = 'import';
             $time = time();
             $intTotal = null;
             $intInvalid = 0;
             $intValid = 0;
             $arrImportCols = \Input::post('import_cols');
             $arrSessionData['import'][$this->strFormKey]['import_cols'] = $arrImportCols;
             $this->Session->set('EFG', $arrSessionData);
             $arrMapFields = array_flip($arrImportCols);
             if (isset($arrMapFields['__IGNORE__'])) {
                 unset($arrMapFields['__IGNORE__']);
             }
             $blnUseCsvHeader = $arrSessionData['import'][$this->strFormKey]['csv_has_header'] == '1' ? true : false;
             $arrEntries = array();
             $resFile = $objFile->handle;
             $timeNow = time();
             $strFormTitle = $this->Formdata->arrFormsDcaKey[substr($this->strFormKey, 3)];
             $strAliasField = strlen($this->Formdata->arrStoringForms[substr($this->strFormKey, 3)]['efgAliasField']) ? $this->Formdata->arrStoringForms[substr($this->strFormKey, 3)]['efgAliasField'] : '';
             $objForm = \FormModel::findOneBy('title', $strFormTitle);
             if ($objForm !== null) {
                 $arrFormFields = $this->Formdata->getFormfieldsAsArray($objForm->id);
             }
             while (($arrRow = @fgetcsv($resFile, null, $strSeparator)) !== false) {
                 if (null === $intTotal) {
                     $intTotal = 0;
                     if ($blnUseCsvHeader) {
                         continue;
                     }
                 }
                 $strAlias = '';
                 if (isset($arrRow[$arrMapFields['alias']]) && strlen($arrRow[$arrMapFields['alias']])) {
                     $strAlias = $arrRow[$arrMapFields['alias']];
                 } elseif (isset($arrRow[$arrMapFields[$strAliasField]]) && strlen($arrRow[$arrMapFields[$strAliasField]])) {
                     \Input::setPost($strAliasField, $arrRow[$arrMapFields[$strAliasField]]);
                 }
                 $arrDetailSets = array();
                 // prepare base data
                 $arrSet = array('tstamp' => $timeNow, 'fd_member' => 0, 'fd_user' => intval($this->User->id), 'form' => $strFormTitle, 'ip' => \Environment::get('ip'), 'date' => $timeNow, 'published' => $GLOBALS['TL_DCA']['tl_formdata']['fields']['published']['default'] == '1' ? '1' : '');
                 foreach ($arrMapFields as $strField => $intCol) {
                     if (in_array($strField, $this->arrImportIgnoreFields)) {
                         continue;
                     }
                     if (in_array($strField, $this->arrBaseFields)) {
                         $arrField = $GLOBALS['TL_DCA']['tl_formdata']['fields'][$strField];
                         if (in_array($strField, $this->arrOwnerFields)) {
                             switch ($strField) {
                                 case 'fd_user':
                                     $array = 'arrUsers';
                                     break;
                                 case 'fd_member':
                                     $array = 'arrMembers';
                                     break;
                                 case 'fd_user_group':
                                     $array = 'arrUserGroups';
                                     break;
                                 case 'fd_member_group':
                                     $array = 'arrMemberGroups';
                                     break;
                             }
                             if (is_numeric($arrRow[$intCol]) && array_key_exists($arrRow[$intCol], $this->{$array})) {
                                 $varValue = $arrRow[$intCol];
                             } elseif (is_string($arrRow[$intCol])) {
                                 $varValue = intval(array_search($arrRow[$intCol], $this->{$array}));
                             }
                         } elseif ($strField == 'published') {
                             if ($arrRow[$intCol] == $arrField['label'][0] || intval($arrRow[$intCol]) == 1) {
                                 $varValue = '1';
                             } else {
                                 $varValue = '';
                             }
                         } elseif ($strField == 'alias') {
                             continue;
                         } else {
                             $varValue = $arrRow[$intCol];
                         }
                         $arrSet[$strField] = $varValue;
                     }
                 }
                 // prepare details data
                 foreach ($arrMapFields as $strField => $intCol) {
                     if (in_array($strField, $this->arrImportIgnoreFields)) {
                         continue;
                     }
                     if (in_array($strField, $this->arrDetailFields)) {
                         // $arrField = array_merge($arrFormFields[$strField], $GLOBALS['TL_DCA']['tl_formdata']['fields'][$strField]);
                         $arrField = $GLOBALS['TL_DCA']['tl_formdata']['fields'][$strField];
                         $varValue = $this->Formdata->prepareImportValueForDatabase($arrRow[$intCol], $arrField);
                         // prepare details data
                         $arrDetailSet = array('sorting' => $arrFormFields[$strField]['sorting'], 'tstamp' => $timeNow, 'ff_id' => $arrField['ff_id'], 'ff_name' => $strField, 'value' => $varValue);
                         $arrDetailSets[] = $arrDetailSet;
                     }
                 }
                 $intNewId = 0;
                 $blnSaved = true;
                 if (!empty($arrDetailSets)) {
                     $objNewFormdata = \Database::getInstance()->prepare("INSERT INTO tl_formdata %s")->set($arrSet)->execute();
                     $intNewId = $objNewFormdata->insertId;
                     $strAlias = $this->Formdata->generateAlias($strAlias, $this->strFormFilterValue, $intNewId);
                     if (strlen($strAlias)) {
                         \Database::getInstance()->prepare("UPDATE tl_formdata %s WHERE id=?")->set(array('alias' => $strAlias))->execute($intNewId);
                     }
                     foreach ($arrDetailSets as $kD => $arrDetailSet) {
                         $arrDetailSet['pid'] = $intNewId;
                         try {
                             $objNewFormdataDetails = \Database::getInstance()->prepare("INSERT INTO tl_formdata_details %s")->set($arrDetailSet)->execute();
                         } catch (\Exception $ee) {
                             $blnSaved = false;
                         }
                     }
                     if ($blnSaved === false && $intNewId > 0) {
                         \Database::getInstance()->prepare("DELETE FROM tl_formdata WHERE id=?")->execute($intNewId);
                     }
                 } else {
                     $blnSaved = false;
                 }
                 if ($blnSaved) {
                     $intValid++;
                 } else {
                     $intInvalid++;
                 }
                 $intTotal++;
             }
             \Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['tl_formdata']['import_confirm'], $intValid));
             if ($intInvalid > 0) {
                 \Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_formdata']['import_invalid'], $intInvalid));
             }
             // Add a log entry
             $this->log('Imported file "' . $objFile->filename . '" into form data "' . $strFormTitle . '", created ' . $intValid . ' new records', __METHOD__, TL_GENERAL);
             setcookie('BE_PAGE_OFFSET', 0, 0, '/');
             \Controller::reload();
         }
         // Generate preview and form to select import fields
         if ($strMode == 'preview') {
             return $this->formImportPreview($objFile, $strSeparator);
         }
     }
     return $this->formImportSource();
 }