/** * Generate the module */ protected function compile() { /** @var IsotopeIntegrityCheck[] $arrChecks */ $arrChecks = array(); $arrTasks = array(); $blnReload = false; if (\Input::post('FORM_SUBMIT') == 'tl_iso_integrity') { $arrTasks = (array) \Input::post('tasks'); } $this->Template->hasFixes = false; foreach ($GLOBALS['ISO_INTEGRITY'] as $strClass) { /** @var IsotopeIntegrityCheck $objCheck */ $objCheck = new $strClass(); if (!$objCheck instanceof IsotopeIntegrityCheck) { throw new \LogicException('Class "' . $strClass . '" must implement IsotopeIntegrityCheck interface'); } if (in_array($objCheck->getId(), $arrTasks) && $objCheck->hasError() && $objCheck->canRepair()) { $objCheck->repair(); $blnReload = true; } else { $blnError = $objCheck->hasError(); $blnRepair = $objCheck->canRepair(); $arrChecks[] = array('id' => $objCheck->getId(), 'name' => $objCheck->getName(), 'description' => $objCheck->getDescription(), 'error' => $blnError, 'repair' => $blnError && $blnRepair); if ($blnError && $blnRepair) { $this->Template->hasFixes = true; } } } if ($blnReload) { \Controller::reload(); } $this->Template->checks = $arrChecks; $this->Template->action = \Environment::get('request'); $this->Template->back = str_replace('&mod=integrity', '', \Environment::get('request')); }
/** * Generate the module * * @return string */ public function run() { $template = new \BackendTemplate('be_css_class_replacer_update'); $template->isActive = $this->isActive(); $template->action = ampersand(\Environment::get('request')); $template->message = \Message::generate(); $template->headline = specialchars($GLOBALS['TL_LANG']['tl_maintenance']['css-class-replacer-headline']); $template->description = specialchars($GLOBALS['TL_LANG']['tl_maintenance']['css-class-replacer-description']); $template->submit = specialchars($GLOBALS['TL_LANG']['tl_maintenance']['css-class-replacer-submit']); if ($this->isActive()) { $rules = RuleModel::findAll(); $helper = new BackendHelper(); $helper->updateCacheableValues($rules); \Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['tl_maintenance']['css-class-replacer-message'], $rules->count())); \Controller::reload(); } return $template->parse(); }
/** * @param Database_Result $objPage * @param Database_Result $objLayout * @param PageRegular $objPageRegular */ public function login($objPage, $objLayout, $objPageRegular) { $time = time(); $objMember = \Database::getInstance()->prepare("SELECT * FROM tl_member WHERE loginLink = ? AND (loginLinkExpire > ? OR loginLinkExpire = '')")->execute($this->authKey, $time); $objMemberModel = \MemberModel::findById($objMember->id); if ($objMember->numRows != 1 || $objMember->loginLink != $this->authKey) { return; } if (!FE_USER_LOGGED_IN) { // Generate the cookie hash $this->strHash = sha1(session_id() . (!\Config::get('disableIpCheck') ? \Environment::get('ip') : '') . 'FE_USER_AUTH'); // Clean up old sessions \Database::getInstance()->prepare("DELETE FROM tl_session WHERE tstamp<? OR hash=?")->execute($time - \Config::get('sessionTimeout'), $this->strHash); // Save the session in the database \Database::getInstance()->prepare("INSERT INTO tl_session (pid, tstamp, name, sessionID, ip, hash) VALUES (?, ?, ?, ?, ?, ?)")->execute($objMember->id, $time, 'FE_USER_AUTH', session_id(), \Environment::get('ip'), $this->strHash); // Set the authentication cookie \System::setCookie('FE_USER_AUTH', $this->strHash, $time + \Config::get('sessionTimeout'), null, null, false, true); // Set the login status (backwards compatibility) $_SESSION['TL_USER_LOGGED_IN'] = true; // Save the login status $_SESSION['TL_USER_LOGGED_IN'] = true; \System::log('User "' . $objMember->username . '" logged in by authKey', 'LoginLink()', TL_ACCESS); \Controller::reload(); } if ($objMember->jumpTo) { $objPage = \PageModel::findByPk($objMember->jumpTo); } $strUrl = \Controller::generateFrontendUrl($objPage->row()); $strParam = ''; foreach ($_GET as $index => $value) { if ($index == 'key') { continue; } if (!$strParam) { $strParam .= '?' . $index . '=' . \Input::get($index); } else { $strParam .= '&' . $index . '=' . \Input::get($index); } } \Controller::redirect($strUrl . $strParam); }
/** * Generate module */ protected function compile() { // Create files if (\Input::post('FORM_SUBMIT') == 'tl_entity_import') { $objModel = EntityImportConfigModel::findByPk($this->objDc->id); if ($objModel === null) { return; } if (class_exists($objModel->importerClass)) { // use a particular importer (e.g. NewsImporter) \Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_entity_import_config']['importerInfo'], $objModel->importerClass)); $importer = new $objModel->importerClass($objModel); } else { \Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_entity_import_config']['importerInfo'], 'Importer')); $importer = new Importer($objModel); } if ($importer->run(\Input::post('dry-run'))) { // Confirm and reload $strMessage = $GLOBALS['TL_LANG']['tl_entity_import_config']['confirm']; if (\Input::post('dry-run')) { $strMessage = $GLOBALS['TL_LANG']['tl_entity_import_config']['confirmDry']; } \Message::addConfirmation($strMessage); \Controller::reload(); } } $this->Template->base = \Environment::get('base'); $this->Template->href = \Controller::getReferer(true); $this->Template->title = specialchars($GLOBALS['TL_LANG']['MSC']['backBTTitle']); $this->Template->action = ampersand(\Environment::get('request')); $this->Template->selectAll = $GLOBALS['TL_LANG']['MSC']['selectAll']; $this->Template->button = $GLOBALS['TL_LANG']['MSC']['backBT']; $this->Template->message = \Message::generate(); $this->Template->submit = specialchars($GLOBALS['TL_LANG']['tl_entity_import_config']['import'][0]); $this->Template->dryRun = specialchars($GLOBALS['TL_LANG']['tl_entity_import_config']['dryRun'][0]); $this->Template->headline = sprintf($GLOBALS['TL_LANG']['tl_entity_import_config']['headline'], \Input::get('id')); $this->Template->explain = $GLOBALS['TL_LANG']['tl_entity_import_config']['make'][1]; $this->Template->label = $GLOBALS['TL_LANG']['tl_entity_import_config']['label']; }
public function compile() { \System::loadLanguageFile('tl_iso_gallery'); $strBuffer = ' <table style="width:100%"> <thead> <tr> <th>' . $GLOBALS['TL_LANG']['tl_iso_gallery']['name'][0] . '</th> <th>' . $GLOBALS['TL_LANG']['tl_iso_gallery']['lightbox_template'][0] . '<span class="mandatory">*</span></th> </tr> </thead> <tbody>'; foreach ($this->objGaleries as $objGallery) { $objSelect = new \SelectMenu(\Widget::getAttributesFromDca(array('options' => array_merge(\Controller::getTemplateGroup('moo_'), \Controller::getTemplateGroup('j_')), 'eval' => array('includeBlankOption' => true, 'mandatory' => true)), 'gallery[' . $objGallery->id . ']')); if (\Input::post('FORM_SUBMIT') == 'tl_iso_upgrade_20010000') { $objSelect->validate(); if (!$objSelect->hasErrors()) { $objGallery->lightbox_template = serialize(array($objSelect->value)); $objGallery->save(); } } $strBuffer .= ' <tr> <td>' . $objGallery->name . '</td> <td>' . $objSelect->generateWithError() . '</td> </tr>'; } $strBuffer .= ' </tbody> </table>'; $this->Template->formSubmit = 'tl_iso_upgrade_20010000'; $this->Template->fields = $strBuffer; $this->Template->matter = $GLOBALS['TL_LANG']['UPG']['20010000']; if (\Input::post('FORM_SUBMIT') == 'tl_iso_upgrade_20010000') { \Controller::reload(); } }
/** * Authenticate a user * * @return boolean */ public function authenticate() { // Default authentication if (parent::authenticate()) { return true; } // Check whether auto login is enabled if (\Config::get('autologin') > 0 && ($strCookie = \Input::cookie('FE_AUTO_LOGIN')) != '') { // Try to find the user by his auto login cookie if ($this->findBy('autologin', $strCookie) !== false) { // Check the auto login period if ($this->createdOn >= time() - \Config::get('autologin')) { // Validate the account status if ($this->checkAccountStatus() !== false) { $this->setUserFromDb(); // Last login date $this->lastLogin = $this->currentLogin; $this->currentLogin = time(); $this->save(); // Generate the session $this->generateSession(); $this->log('User "' . $this->username . '" was logged in automatically', __METHOD__, TL_ACCESS); // Reload the page \Controller::reload(); return true; } } } // Remove the cookie if it is invalid to enable loading cached pages $this->setCookie('FE_AUTO_LOGIN', $strCookie, time() - 86400, null, null, \Environment::get('ssl'), true); } return false; }
/** * Reload the current page * * @deprecated Use Controller::reload() instead */ public static function reload() { \Controller::reload(); }
/** * Import files from selected folder * * @param string $strPath */ protected function importFromPath($strPath) { $arrFiles = scan(TL_ROOT . '/' . $strPath); if (empty($arrFiles)) { \Message::addError($GLOBALS['TL_LANG']['MSC']['noFilesInFolder']); \Controller::reload(); } $blnEmpty = true; $arrDelete = array(); $objProducts = \Database::getInstance()->prepare("SELECT * FROM tl_iso_product WHERE pid=0")->execute(); while ($objProducts->next()) { $arrImageNames = array(); $arrImages = deserialize($objProducts->images); if (!is_array($arrImages)) { $arrImages = array(); } else { foreach ($arrImages as $row) { if ($row['src']) { $arrImageNames[] = $row['src']; } } } $arrPattern = array(); $arrPattern[] = $objProducts->alias ? standardize($objProducts->alias) : null; $arrPattern[] = $objProducts->sku ? $objProducts->sku : null; $arrPattern[] = $objProducts->sku ? standardize($objProducts->sku) : null; $arrPattern[] = !empty($arrImageNames) ? implode('|', $arrImageNames) : null; // !HOOK: add custom import regex patterns if (isset($GLOBALS['ISO_HOOKS']['addAssetImportRegexp']) && is_array($GLOBALS['ISO_HOOKS']['addAssetImportRegexp'])) { foreach ($GLOBALS['ISO_HOOKS']['addAssetImportRegexp'] as $callback) { $objCallback = \System::importStatic($callback[0]); $arrPattern = $objCallback->{$callback}[1]($arrPattern, $objProducts); } } $strPattern = '@^(' . implode('|', array_filter($arrPattern)) . ')@i'; $arrMatches = preg_grep($strPattern, $arrFiles); if (!empty($arrMatches)) { $arrNewImages = array(); foreach ($arrMatches as $file) { if (is_dir(TL_ROOT . '/' . $strPath . '/' . $file)) { $arrSubfiles = scan(TL_ROOT . '/' . $strPath . '/' . $file); if (!empty($arrSubfiles)) { foreach ($arrSubfiles as $subfile) { if (is_file($strPath . '/' . $file . '/' . $subfile)) { $objFile = new \File($strPath . '/' . $file . '/' . $subfile); if ($objFile->isGdImage) { $arrNewImages[] = $strPath . '/' . $file . '/' . $subfile; } } } } } elseif (is_file(TL_ROOT . '/' . $strPath . '/' . $file)) { $objFile = new \File($strPath . '/' . $file); if ($objFile->isGdImage) { $arrNewImages[] = $strPath . '/' . $file; } } } if (!empty($arrNewImages)) { foreach ($arrNewImages as $strFile) { $pathinfo = pathinfo(TL_ROOT . '/' . $strFile); // Will recursively create the folder $objFolder = new \Folder('isotope/' . strtolower(substr($pathinfo['filename'], 0, 1))); $strCacheName = $pathinfo['filename'] . '-' . substr(md5_file(TL_ROOT . '/' . $strFile), 0, 8) . '.' . $pathinfo['extension']; \Files::getInstance()->copy($strFile, $objFolder->path . '/' . $strCacheName); $arrImages[] = array('src' => $strCacheName); $arrDelete[] = $strFile; \Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['MSC']['assetImportConfirmation'], $pathinfo['filename'] . '.' . $pathinfo['extension'], $objProducts->name)); $blnEmpty = false; } \Database::getInstance()->prepare("UPDATE tl_iso_product SET images=? WHERE id=?")->execute(serialize($arrImages), $objProducts->id); } } } if (!empty($arrDelete)) { $arrDelete = array_unique($arrDelete); foreach ($arrDelete as $file) { \Files::getInstance()->delete($file); } } if ($blnEmpty) { \Message::addInfo($GLOBALS['TL_LANG']['MSC']['assetImportNoFilesFound']); } \Controller::reload(); }
/** * Generate module */ protected function compile() { if (Isotope::getCart()->isEmpty()) { $this->Template->empty = true; $this->Template->type = 'empty'; $this->Template->message = $this->iso_emptyMessage ? $this->iso_noProducts : $GLOBALS['TL_LANG']['MSC']['noItemsInCart']; return; } // Remove from cart if (\Input::get('remove') > 0 && Isotope::getCart()->deleteItemById((int) \Input::get('remove'))) { \Controller::redirect(preg_replace('/([?&])remove=[^&]*(&|$)/', '$1', \Environment::get('request'))); } $objTemplate = new \Isotope\Template($this->iso_collectionTpl); Isotope::getCart()->addToTemplate($objTemplate, array('gallery' => $this->iso_gallery, 'sorting' => Isotope::getCart()->getItemsSortingCallable($this->iso_orderCollectionBy))); $blnReload = false; $arrQuantity = \Input::post('quantity'); $arrItems = $objTemplate->items; foreach ($arrItems as $k => $arrItem) { // Update cart data if form has been submitted if (\Input::post('FORM_SUBMIT') == $this->strFormId && is_array($arrQuantity) && isset($arrQuantity[$arrItem['id']])) { $blnReload = true; Isotope::getCart()->updateItemById($arrItem['id'], array('quantity' => $arrQuantity[$arrItem['id']])); continue; // no need to generate $arrProductData, we reload anyway } $arrItem['remove_href'] = \Haste\Util\Url::addQueryString('remove=' . $arrItem['id']); $arrItem['remove_title'] = specialchars(sprintf($GLOBALS['TL_LANG']['MSC']['removeProductLinkTitle'], $arrItem['name'])); $arrItem['remove_link'] = $GLOBALS['TL_LANG']['MSC']['removeProductLinkText']; $arrItems[$k] = $arrItem; } $arrButtons = $this->generateButtons(); // Reload the page if no button has handled it if ($blnReload) { // Unset payment and shipping method because they could get invalid due to the change // @todo change this to check availability, but that's an API/BC break if (($objShipping = Isotope::getCart()->getShippingMethod()) !== null && !$objShipping->isAvailable()) { Isotope::getCart()->setShippingMethod(null); } if (($objPayment = Isotope::getCart()->getPaymentMethod()) !== null && !$objPayment->isAvailable()) { Isotope::getCart()->setPaymentMethod(null); } \Controller::reload(); } $objTemplate->items = $arrItems; $objTemplate->isEditable = true; $objTemplate->linkProducts = true; $objTemplate->formId = $this->strFormId; $objTemplate->formSubmit = $this->strFormId; $objTemplate->action = \Environment::get('request'); $objTemplate->buttons = $arrButtons; $objTemplate->custom = ''; // HOOK: order status has been updated if (isset($GLOBALS['ISO_HOOKS']['compileCart']) && is_array($GLOBALS['ISO_HOOKS']['compileCart'])) { $strCustom = ''; foreach ($GLOBALS['ISO_HOOKS']['compileCart'] as $callback) { $objCallback = \System::importStatic($callback[0]); $strCustom .= $objCallback->{$callback}[1]($this); } $objTemplate->custom = $strCustom; } $this->Template->empty = false; $this->Template->collection = Isotope::getCart(); $this->Template->products = $objTemplate->parse(); }
/** * Reload the current page. * * @return void */ public static function handleReload() { \Controller::reload(); }
/** * Check the Ajax pre actions * * @param string $action * * @return string */ public function executePreActions($action) { switch ($action) { // Move the product case 'moveProduct': \Session::getInstance()->set('iso_products_gid', intval(\Input::post('value'))); \Controller::redirect(html_entity_decode(\Input::post('redirect'))); break; // Move multiple products // Move multiple products case 'moveProducts': \Session::getInstance()->set('iso_products_gid', intval(\Input::post('value'))); exit; break; // Filter the groups // Filter the groups case 'filterGroups': \Session::getInstance()->set('iso_products_gid', intval(\Input::post('value'))); $this->reload(); break; // Filter the pages // Filter the pages case 'filterPages': $filter = \Session::getInstance()->get('filter'); $filter['tl_iso_product']['iso_page'] = (int) \Input::post('value'); \Session::getInstance()->set('filter', $filter); $this->reload(); break; // Sorty products by page // Sorty products by page case 'sortByPage': if (\Input::post('value') > 0) { \Controller::redirect(\Backend::addToUrl('table=tl_iso_product_category&id=' . (int) \Input::post('value') . '&page_id=' . (int) \Input::post('value'))); } else { \Controller::reload(); } } }
/** * Delete all incomplete and unrelated records */ protected function reviseTable() { $reload = false; $ptable = $this->arrDca['config']['ptable']; $ctable = $this->arrDca['config']['ctable']; $new_records = $this->Session->get('new_records'); // HOOK: add custom logic if (isset($GLOBALS['TL_HOOKS']['reviseTable']) && is_array($GLOBALS['TL_HOOKS']['reviseTable'])) { foreach ($GLOBALS['TL_HOOKS']['reviseTable'] as $callback) { $status = null; if (is_array($callback)) { $this->import($callback[0]); $status = $this->{$callback[0]}->{$callback[1]}($this->strTable, $new_records[$this->strTable], $ptable, $ctable); } elseif (is_callable($callback)) { $status = $callback($this->strTable, $new_records[$this->strTable], $ptable, $ctable); } if ($status === true) { $reload = true; } } } // Delete all new but incomplete fieldpalette records (tstamp=0) if (!empty($new_records[\Config::get('fieldpalette_table')]) && is_array($new_records[\Config::get('fieldpalette_table')])) { $objStmt = $this->Database->prepare("DELETE FROM " . \Config::get('fieldpalette_table') . " WHERE id IN(" . implode(',', array_map('intval', $new_records[\Config::get('fieldpalette_table')])) . ") AND tstamp=0 AND (? IS NULL OR id != ?)")->execute($this->activeRecord->id, $this->activeRecord->id); if ($objStmt->affectedRows > 0) { $reload = true; } } // Delete all fieldpalette records whose child record isn't existing if ($ptable != '') { if ($this->arrDca['config']['dynamicPtable']) { $objStmt = $this->Database->execute("DELETE FROM " . \Config::get('fieldpalette_table') . " WHERE ptable='" . $ptable . "' AND NOT EXISTS (SELECT * FROM (SELECT * FROM " . $ptable . ") AS fpp WHERE " . \Config::get('fieldpalette_table') . ".pid = fpp.id)"); } else { $objStmt = $this->Database->execute("DELETE FROM " . \Config::get('fieldpalette_table') . " WHERE NOT EXISTS " . "(SELECT * FROM (SELECT * FROM " . $ptable . ") AS fpp WHERE " . \Config::get('fieldpalette_table') . ".pid = fpp.id)"); } if ($objStmt->affectedRows > 0) { $reload = true; } } // Delete all records of the child table that are not related to the current table if (!empty($ctable) && is_array($ctable)) { foreach ($ctable as $v) { if ($v != '') { // Load the DCA configuration so we can check for "dynamicPtable" if (!isset($GLOBALS['loadDataContainer'][$v])) { \Controller::loadDataContainer($v); } if ($GLOBALS['TL_DCA'][$v]['config']['dynamicPtable']) { $objStmt = $this->Database->execute("DELETE FROM {$v} WHERE ptable='" . \Config::get('fieldpalette_table') . "' AND NOT EXISTS (SELECT * FROM " . "(SELECT * FROM " . \Config::get('fieldpalette_table') . ") AS fp WHERE {$v}.pid = fp.id)"); } else { $objStmt = $this->Database->execute("DELETE FROM {$v} WHERE NOT EXISTS (SELECT * FROM (SELECT * FROM " . \Config::get('fieldpalette_table') . ") AS fp WHERE {$v}.pid = fp.id)"); } if ($objStmt->affectedRows > 0) { $reload = true; } } } } // Reload the page if ($reload) { if (\Environment::get('isAjaxRequest')) { return; } \Controller::reload(); } }
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(); }
/** * Purge the advanced asset cache. * * @return void * * @SuppressWarnings(PHPMD.Superglobals) */ public function purgeAdvancedAssetCache() { if ($this->cache instanceof CacheProvider) { $this->cache->deleteAll(); } else { $_SESSION['CLEAR_CACHE_CONFIRM'] = $GLOBALS['TL_LANG']['tl_maintenance_jobs']['theme_plus_aac'][2]; \Controller::reload(); } }
public function validateStockCollectionUpdate($objItem, $arrSet) { $objProduct = Product::findPublishedByPk($objItem->product_id); if (!static::validateQuantity($objProduct, $arrSet['quantity'])) { \Controller::reload(); } return $arrSet; }
/** * Merge guest cart if necessary */ public function mergeGuestCart() { $this->ensureNotLocked(); $strHash = \Input::cookie(static::$strCookie); // Temporary cart available, move to this cart. Must be after creating a new cart! if (FE_USER_LOGGED_IN === true && $strHash != '' && $this->member > 0) { $blnMerge = $this->countItems() > 0 ? true : false; $objTemp = static::findOneBy(array('uniqid=?', 'store_id=?'), array($strHash, $this->store_id)); if (null !== $objTemp) { $arrIds = $this->copyItemsFrom($objTemp); if ($blnMerge && !empty($arrIds)) { Message::addConfirmation($GLOBALS['TL_LANG']['MSC']['cartMerged']); } $objTemp->delete(); } // Delete cookie \System::setCookie(static::$strCookie, '', time() - 3600, $GLOBALS['TL_CONFIG']['websitePath']); \Controller::reload(); } }
/** * @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; }
/** * Return a select menu to limit results * @param boolean * @return string */ protected function limitMenu($blnOptional = false) { $session = $this->Session->getData(); $filter = \Input::get('id') ? $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; } } $this->Session->setData($session); if (\Input::post('FORM_SUBMIT') == 'tl_filters_limit') { \Controller::reload(); } } else { $this->limit = $session['filter'][$filter]['limit'] != '' ? $session['filter'][$filter]['limit'] == 'all' ? null : $session['filter'][$filter]['limit'] : '0,' . $GLOBALS['TL_CONFIG']['resultsPerPage']; $query = "SELECT COUNT(*) AS count FROM " . $this->strTable; if (\Input::get('id')) { $this->procedure[] = "pid=?"; $this->values[] = \Input::get('id'); } else { $this->procedure[] = "pid=0"; } if (!empty($this->root) && is_array($this->root)) { $this->procedure[] = 'id IN(' . implode(',', $this->root) . ')'; } if (!empty($this->procedure)) { $query .= " WHERE " . implode(' AND ', $this->procedure); } $objTotal = $this->Database->prepare($query)->execute($this->values); $total = $objTotal->count; $options_total = 0; $blnIsMaxResultsPerPage = false; // Overall limit if ($total > $GLOBALS['TL_CONFIG']['maxResultsPerPage'] && ($this->limit === null || preg_replace('/^.*,/', '', $this->limit) == $GLOBALS['TL_CONFIG']['maxResultsPerPage'])) { if ($this->limit === null) { $this->limit = '0,' . $GLOBALS['TL_CONFIG']['maxResultsPerPage']; } $blnIsMaxResultsPerPage = true; $GLOBALS['TL_CONFIG']['resultsPerPage'] = $GLOBALS['TL_CONFIG']['maxResultsPerPage']; $session['filter'][$filter]['limit'] = $GLOBALS['TL_CONFIG']['maxResultsPerPage']; } $options = ''; // Build options if ($total > 0) { $options = ''; $options_total = ceil($total / $GLOBALS['TL_CONFIG']['resultsPerPage']); // Reset limit if other parameters have decreased the number of results if ($this->limit !== null && ($this->limit == '' || preg_replace('/,.*$/', '', $this->limit) > $total)) { $this->limit = '0,' . $GLOBALS['TL_CONFIG']['resultsPerPage']; } // Build options for ($i = 0; $i < $options_total; $i++) { $this_limit = $i * $GLOBALS['TL_CONFIG']['resultsPerPage'] . ',' . $GLOBALS['TL_CONFIG']['resultsPerPage']; $upper_limit = $i * $GLOBALS['TL_CONFIG']['resultsPerPage'] + $GLOBALS['TL_CONFIG']['resultsPerPage']; if ($upper_limit > $total) { $upper_limit = $total; } $options .= ' <option value="' . $this_limit . '"' . \Widget::optionSelected($this->limit, $this_limit) . '>' . ($i * $GLOBALS['TL_CONFIG']['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 && ($total < 1 || $options_total < 2)) { return ''; } $fields = ' <select name="tl_limit" class="tl_select' . ($session['filter'][$filter]['limit'] != 'all' && $total > $GLOBALS['TL_CONFIG']['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>'; }
/** * Generate the form * @return string */ protected function compile() { $hasUpload = false; $doNotSubmit = false; $arrSubmitted = array(); $blnAddDateJS = true; $this->loadDataContainer('tl_form_field'); $formId = $this->formID != '' ? 'auto_' . $this->formID : 'auto_form_' . $this->id; $arrUnset = array('FORM_NEXT', 'FORM_BACK'); foreach ($arrUnset as $strKey) { unset($_SESSION['FORM_DATA'][$strKey]); } // Form is used to edit existing formdata record if ($this->objEditRecord instanceof \Database\Result) { $arrEditRecord = $this->objEditRecord->row(); $this->blnEditform = true; $this->import('Formdata'); } // Check if the form is a multipage form $objPaginators = \Database::getInstance()->prepare("SELECT id,pid,invisible,`sorting`,`type`,`name`,`label`,`value`,`imageSubmit`,`singleSRC`,`sLabel`,`efgAddBackButton`,`efgBackStoreSessionValues`,`efgBackSlabel`,`efgBackImageSubmit`,`efgBackSingleSRC` FROM tl_form_field WHERE pid=? AND `type`=?" . (!BE_USER_LOGGED_IN ? " AND invisible=''" : "") . " ORDER BY `sorting`")->execute($this->id, 'efgFormPaginator'); if ($objPaginators->numRows) { $this->blnMultipage = true; $this->intTotalPages = (int) $objPaginators->numRows; while ($objPaginators->next()) { $this->arrPaginators[] = $objPaginators->row(); } } // Use the core class Form if this is not a multi page form and not frontend edit form if (!$this->blnMultipage && !$this->blnEditform || $this->method == 'GET' || TL_MODE == 'BE') { // unset files in session to avoid wrong validation and submission of file uploads // .. files may be stored in session after frontend editing or submission of multi page form $_SESSION['FILES'] = array(); $this->strTemplate = 'form'; return parent::compile(); } global $objPage; if ($objPage->outputFormat == 'html5') { $blnIsHtml5 = true; } $this->blnAllowSkipRequired = false; // allow form submission, if ALL required fields are empty $this->arrWidgetsFailedValidation = array(); // validation result of required widgets $doNotValidate = false; $strMode = ''; $intActivePage = 1; $this->Template = new \FrontendTemplate($this->strTemplate); \System::loadLanguageFile('tl_form'); // render a previous completed page if (strlen($_SESSION['EFP'][$formId]['render_page'])) { $intActivePage = (int) $_SESSION['EFP'][$formId]['render_page']; $this->intActivePage = (int) $_SESSION['EFP'][$formId]['render_page']; $strMode = 'reload'; unset($_SESSION['EFP'][$formId]['render_page']); } elseif (!strlen($_POST['FORM_SUBMIT'])) { unset($_SESSION['EFP'][$formId]['render_page']); unset($_SESSION['EFP'][$formId]['completed']); } if (\Input::post('FORM_SUBMIT') == $formId && (strlen($_POST['FORM_PAGE']) || is_array($_POST['FORM_STEP']))) { $intActivePage = (int) $_POST['FORM_PAGE']; $intGoto = 0; if (strlen($_POST['FORM_BACK']) || strlen($_POST['FORM_BACK_x'])) { $intActivePage = (int) $_POST['FORM_PAGE']; $doNotValidate = true; $strMode = 'back'; } elseif (is_array($_POST['FORM_STEP']) || is_array($_POST['FORM_STEP_x'])) { $intGoto = is_array($_POST['FORM_STEP']) ? key($_POST['FORM_STEP']) : key($_POST['FORM_STEP_x']); if ($intGoto < $intActivePage) { $_SESSION['EFP'][$formId]['render_page'] = $intGoto < 1 ? 1 : $intGoto; \Controller::reload(); } elseif ($intGoto > $intActivePage && $_SESSION['EFP'][$formId]['completed']['page_' . $intGoto]) { $_SESSION['EFP'][$formId]['render_page'] = $intGoto; \Controller::reload(); } } if ($intActivePage < 1) { $intActivePage = 1; } if ($intActivePage > $this->intTotalPages) { $intActivePage = $this->intTotalPages; } $this->intActivePage = $intActivePage; } $this->Template->fields = ''; $this->Template->hidden = ''; $this->Template->formSubmit = $formId; $this->Template->tableless = $this->tableless ? true : false; $this->Template->method = $this->method == 'GET' ? 'get' : 'post'; if ($this->blnMultipage || $this->blnEditform) { $objPageWidget = new \FormHidden(array('name' => 'FORM_PAGE', 'value' => $this->intActivePage)); $this->Template->hidden .= $objPageWidget->parse(); } $this->initializeSession($formId); $arrLabels = array(); // Get all form fields $arrFields = array(); $objFields = \FormFieldModel::findPublishedByPid($this->id); if ($objFields !== null) { while ($objFields->next()) { $arrFields[] = $objFields->current(); } } // HOOK: compile form fields if (isset($GLOBALS['TL_HOOKS']['compileFormFields']) && is_array($GLOBALS['TL_HOOKS']['compileFormFields'])) { foreach ($GLOBALS['TL_HOOKS']['compileFormFields'] as $callback) { $this->import($callback[0]); $arrFields = $this->{$callback}[0]->{$callback}[1]($arrFields, $formId, $this); } } // Process the fields if (!empty($arrFields) && is_array($arrFields)) { $row = 0; $max_row = count($arrFields); foreach ($arrFields as $objField) { // Skip fields outside range of active page if ($this->intTotalPages > 1 && ($this->blnMultipage || $this->blnEditform)) { $intFieldSorting = (int) $objField->sorting; if ($this->intActivePage <= 1 && $intFieldSorting > (int) $this->arrPaginators[$this->intActivePage - 1]['sorting']) { continue; } elseif ($this->intActivePage > 1 && $this->intActivePage < $this->intTotalPages && ($intFieldSorting <= (int) $this->arrPaginators[$this->intActivePage - 2]['sorting'] || $intFieldSorting > (int) $this->arrPaginators[$this->intActivePage - 1]['sorting'])) { continue; } elseif ($this->intActivePage == $this->intTotalPages && $intFieldSorting <= (int) $this->arrPaginators[$this->intActivePage - 2]['sorting']) { continue; } } $strClass = $GLOBALS['TL_FFL'][$objField->type]; // Continue if the class is not defined if (!class_exists($strClass)) { continue; } $arrData = $objField->row(); $arrData['decodeEntities'] = true; $arrData['allowHtml'] = $this->allowTags; $arrData['rowClass'] = 'row_' . $row . ($row == 0 ? ' row_first' : ($row == $max_row - 1 ? ' row_last' : '')) . ($row % 2 == 0 ? ' even' : ' odd'); $arrData['tableless'] = $this->tableless; if ($this->blnMultipage || $this->blnEditform) { $arrData['formMultipage'] = $this->blnMultipage; $arrData['formActivePage'] = $this->intActivePage; $arrData['formTotalPages'] = $this->intTotalPages; } // Increase the row count if it is a password field if ($objField->type == 'password') { ++$row; ++$max_row; $arrData['rowClassConfirm'] = 'row_' . $row . ($row == $max_row - 1 ? ' row_last' : '') . ($row % 2 == 0 ? ' even' : ' odd'); } // Submit buttons do not use the name attribute if ($objField->type == 'submit') { $arrData['name'] = ''; } $objWidget = new $strClass($arrData); $objWidget->required = $objField->mandatory ? true : false; if ($objWidget->required) { $this->arrWidgetsFailedValidation[$objField->name] = 0; } // Unset session values if no FORM_SUBMIT or form page has not been completed // (to avoid wrong validation against session values and to avoid usage of values of other forms): // This behaviour can be deactivated by setting: $GLOBALS['EFP'][$formId]['doNotCleanStoredSessionData'] = true; if ($strMode != 'reload' && strlen($objField->name)) { if (!strlen($_POST['FORM_SUBMIT']) || !$_SESSION['EFP'][$formId]['completed']['page_' . $this->intActivePage]) { if (!$GLOBALS['EFP'][$formId]['doNotCleanStoredSessionData']) { unset($_SESSION['FORM_DATA'][$objField->name]); } if ($objWidget instanceof \uploadable) { unset($_SESSION['FILES'][$objField->name]); } } } // Always populate from existing session data if configured if ($GLOBALS['EFP'][$formId]['doNotCleanStoredSessionData'] == true && isset($_SESSION['FORM_DATA'][$objField->name])) { $objWidget->value = $_SESSION['FORM_DATA'][$objField->name]; } if ($strMode == 'reload' || $this->blnEditform && !strlen($_POST['FORM_BACK']) && !strlen($_POST['FORM_BACK_x'])) { // Frontend editing if ($this->blnEditform && !$_SESSION['EFP'][$formId]['completed']['page_' . $this->intActivePage]) { if (is_array($objWidget->options)) { $arrData['options'] = $objWidget->options; } // Prepare options array $arrData['options'] = $this->Formdata->prepareWidgetOptions($arrData); // Set rgxp 'date' for field type 'calendar' if not set if ($arrData['type'] == 'calendar') { if (!isset($arrData['rgxp'])) { $arrData['rgxp'] = 'date'; } } elseif ($arrData['type'] == 'xdependentcalendarfields') { $arrData['rgxp'] = 'date'; $arrData['dateFormat'] = $arrData['xdateformat']; } if ($objWidget instanceof \uploadable) { unset($_SESSION['FILES'][$objField->name]); } // Prepare value $varFieldValue = $this->Formdata->prepareDatabaseValueForWidget($arrEditRecord[$objField->name], $arrData); $objWidget->value = $varFieldValue; } else { // Populate field if page has been completed if ($_SESSION['EFP'][$formId]['completed']['page_' . $this->intActivePage] == true) { $objWidget->value = $_SESSION['FORM_DATA'][$objField->name]; } else { if ($objWidget instanceof \uploadable) { unset($_SESSION['FILES'][$objField->name]); } } } } // HOOK: Load form field callback if (!strlen($_POST['FORM_BACK']) && !strlen($_POST['FORM_BACK_x'])) { if (isset($GLOBALS['TL_HOOKS']['loadFormField']) && is_array($GLOBALS['TL_HOOKS']['loadFormField'])) { foreach ($GLOBALS['TL_HOOKS']['loadFormField'] as $callback) { $this->import($callback[0]); $objWidget = $this->{$callback}[0]->{$callback}[1]($objWidget, $formId, $this->arrData); } } } // Validate the input if (\Input::post('FORM_SUBMIT') == $formId) { // Populate field if (strlen($_POST['FORM_BACK']) || strlen($_POST['FORM_BACK_x'])) { if ($strMode == 'back' && strlen($this->arrPaginators[$this->intActivePage - 1]['efgBackStoreSessionValues'])) { unset($_SESSION['FORM_DATA'][$objField->name]); $objWidget->value = \Input::post($objField->name); } elseif ($_SESSION['EFP'][$formId]['completed']['page_' . $this->intActivePage] == true) { $objWidget->value = $_SESSION['FORM_DATA'][$objField->name]; unset($_SESSION['FORM_DATA'][$objField->name]); } } if (!$doNotValidate) { if ($objWidget instanceof \uploadable) { // If the widget does not store the file, store it in tmp folder and session to make it available for mails etc. if (!$objWidget->storeFile) { if ($this->intActivePage <= $this->intTotalPages) { // Unset the file in session, if this page has not been completed if (!$_SESSION['EFP'][$formId]['completed']['page_' . $this->intActivePage]) { unset($_SESSION['FILES'][$objField->name]); } $objWidget->validate(); // File has been uploaded, store it in temp folder if (is_uploaded_file($_SESSION['FILES'][$objField->name]['tmp_name'])) { $this->import('Files'); $strDstFile = TL_ROOT . '/system/tmp/' . md5_file($_SESSION['FILES'][$objField->name]['tmp_name']); if (@copy($_SESSION['FILES'][$objField->name]['tmp_name'], $strDstFile)) { $_SESSION['FILES'][$objField->name]['tmp_name'] = $strDstFile; $_SESSION['FILES'][$objField->name]['uploaded'] = true; $this->Files->chmod($strDstFile, 0644); } } } } else { $objWidget->validate(); } } else { $objWidget->validate(); } // HOOK: validate form field callback if (isset($GLOBALS['TL_HOOKS']['validateFormField']) && is_array($GLOBALS['TL_HOOKS']['validateFormField'])) { foreach ($GLOBALS['TL_HOOKS']['validateFormField'] as $callback) { $this->import($callback[0]); $objWidget = $this->{$callback}[0]->{$callback}[1]($objWidget, $formId, $this->arrData); } } } if ($objWidget->hasErrors()) { if ($objWidget->required) { $this->arrWidgetsFailedValidation[$objField->name] = 1; } $doNotSubmit = true; } elseif ($objWidget->submitInput() || $strMode == 'back') { if ($objWidget->submitInput()) { $arrSubmitted[$objField->name] = $objWidget->value; $_SESSION['FORM_DATA'][$objField->name] = $objWidget->value; unset($_POST[$objField->name]); // see #5474 } } } if ($objWidget instanceof \FormHidden) { $this->Template->hidden .= $objWidget->parse(); continue; } if ($objWidget instanceof \uploadable) { $hasUpload = true; if ($this->blnMultipage || $this->blnEditform) { // Save file info in the session in frontend edit mode if ($this->blnEditform && strlen($arrEditRecord[$objField->name]) && (!isset($_SESSION['FILES'][$objField->name]) || empty($_SESSION['FILES'][$objField->name]))) { $objFile = new \File($arrEditRecord[$objField->name]); if ($objFile->size) { $_SESSION['FILES'][$objField->name] = array('name' => $objFile->basename, 'type' => $objFile->mime, 'tmp_name' => TL_ROOT . '/' . $objFile->value, 'size' => $objFile->size, 'uploaded' => true); } } // Add info about uploaded file to upload input if (isset($_SESSION['FILES'][$objField->name]) && $_SESSION['FILES'][$objField->name]['uploaded']) { $this->Template->fields .= preg_replace('/(.*?)(<input.*?>)(.*?)/sim', '$1<p class="upload_info">' . sprintf($GLOBALS['TL_LANG']['MSC']['fileUploaded'], $_SESSION['FILES'][$objField->name]['name']) . '</p>$2$3', $objWidget->parse()); ++$row; continue; } } } if ($objWidget->name != '' && $objWidget->label != '') { $arrLabels[$objWidget->name] = $this->replaceInsertTags($objWidget->label); } $this->Template->fields .= $objWidget->parse(); ++$row; } } if ($doNotSubmit && $this->blnAllowSkipRequired) { if (!empty($this->arrWidgetsFailedValidation) && count(array_count_values($this->arrWidgetsFailedValidation)) == 1) { $doNotSubmit = false; } } // Process form data if (\Input::post('FORM_SUBMIT') == $formId && !$doNotSubmit) { if ($this->intTotalPages == 1 || !$this->blnMultipage && !$this->blnEditform) { $this->processFormData($arrSubmitted, $arrLabels); } else { // If not last page but page is completed, render next page if ($this->intActivePage < $this->intTotalPages && (strlen($_POST['FORM_NEXT']) || strlen($_POST['FORM_NEXT_x']))) { $_SESSION['EFP'][$formId]['render_page'] = (int) $_POST['FORM_PAGE'] + 1; $_SESSION['EFP'][$formId]['completed']['page_' . $_POST['FORM_PAGE']] = true; \Controller::reload(); } elseif ($strMode == 'back' && $this->intActivePage <= $this->intTotalPages && (strlen($_POST['FORM_BACK']) || strlen($_POST['FORM_BACK_x']))) { $_SESSION['EFP'][$formId]['render_page'] = (int) $_POST['FORM_PAGE'] - 1; $_SESSION['EFP'][$formId]['completed']['page_' . $_POST['FORM_PAGE']] = true; \Controller::reload(); } else { if ((int) $_POST['FORM_PAGE'] == $this->intTotalPages && (strlen($_POST['FORM_NEXT']) || strlen($_POST['FORM_NEXT_x']))) { unset($_SESSION['EFP'][$formId]['render_page']); unset($_SESSION['EFP'][$formId]['completed']); unset($_SESSION['FORM_DATA']['FORM_PAGE']); unset($_SESSION['FORM_DATA']['FORM_NEXT']); unset($_SESSION['FORM_DATA']['FORM_BACK']); // Populate arrSubmitted from session $arrSubmitted = $_SESSION['FORM_DATA']; $this->processFormData($arrSubmitted, $arrLabels); } } } } $strAttributes = ''; $arrAttributes = deserialize($this->attributes, true); // Add a css class if ($this->blnMultipage) { $arrAttributes[1] = trim($arrAttributes[1] . ' multipage form_page_' . $this->intActivePage); } if (strlen($arrAttributes[1])) { $strAttributes .= ' class="' . $arrAttributes[1] . '"'; } $this->Template->hasError = $doNotSubmit; $this->Template->attributes = $strAttributes; $this->Template->enctype = $hasUpload ? 'multipart/form-data' : 'application/x-www-form-urlencoded'; $this->Template->formId = strlen($arrAttributes[0]) ? $arrAttributes[0] : 'f' . $this->id; $this->Template->action = \Environment::get('indexFreeRequest'); $this->Template->maxFileSize = $hasUpload ? $this->objModel->getMaxUploadFileSize() : false; $this->Template->novalidate = $this->novalidate ? ' novalidate' : ''; // Get the target URL if ($this->method == 'GET' && $this->jumpTo && ($objTarget = $this->objModel->getRelated('jumpTo')) !== null) { $this->Template->action = $this->generateFrontendUrl($objTarget->row()); } // Add Javascript to handle html5 input attribute 'required' on back button if ($blnIsHtml5) { $this->Template->fields .= ' <script>' . $this->getBackButtonJavascriptString() . ' </script>'; } if ($blnAddDateJS) { $this->Template->fields .= ' <script' . (!$blnIsHtml5 ? ' type="text/javascript"' : '') . '>' . $this->getDateString() . ' </script>'; } return $this->Template->parse(); }
/** * Build language variables key files. * * @return string * @SuppressWarnings(PHPMD.Superglobals) * @SuppressWarnings(PHPMD.ExitExpression) */ public function buildLanguageVariableKeys() { $template = new \BackendTemplate('be_translation_search_build_keys'); if (\Input::post('FORM_SUBMIT') == 'tl_translation_search_build_keys') { $this->cleanTranslationFiles(); $template->translations = $this->getTranslations(); if (!$template->translations) { $_SESSION['TL_INFO'][] = $GLOBALS['TL_LANG']['tl_translation']['nothingtodo']; \Controller::reload(); } } elseif (\Input::get('translation')) { // get the next translation group $translation = \Input::get('translation'); $file = new File('system/languages/langkeys.' . $translation . '.php'); $file->write("<?php if (!defined('TL_ROOT')) die('You can not access this file directly!');\n\n/**\n * DO NOT MODIFY THIS FILE, IT IS GENERATED BY THE LANGUAGE EDITOR!\n */\n"); // load the language \Controller::loadLanguageFile($this->languageEditor->getLanguageFileName($translation)); if (is_array($GLOBALS['TL_LANG'][$translation])) { $this->languageVariableKeys = array(); $this->buildLanguageVariableKeysFrom($translation, $translation, $GLOBALS['TL_LANG'][$translation]); ksort($this->languageVariableKeys); foreach ($this->languageVariableKeys as $translation => $v) { foreach ($v as $path => $config) { $key = sprintf('$GLOBALS[\'TL_TRANSLATION\'][\'%s\'][\'%s\']', $translation, $path); $value = var_export($config, true); $file->append($key . ' = ' . $value . ";\n"); } } } $file->close(); header('Content-Type: image/png'); $handle = fopen(TL_ROOT . '/system/modules/language-editor/html/complete.png', 'rb'); fpassthru($handle); fclose($handle); exit; } else { // get translation keys found by the TranslationSearch::buildTranslationKeys method $files = new \RegexIterator(new \DirectoryIterator(TL_ROOT . '/system/languages/'), '#^langkeys\\..*\\.php$#'); foreach ($files as $file) { require_once $file->getPathname(); } } return $template->parse(); }
/** * Send the notification */ public function sendNotification() { if (!\Input::get('master') || !\Leads\NotificationCenterIntegration::available(true)) { \Controller::redirect('contao/main.php?act=error'); } // No need to check for null as NotificationCenterIntegration::available(true) already does $notificationsCollection = \NotificationCenter\Model\Notification::findBy('type', 'core_form'); $notifications = []; // Generate the notifications foreach ($notificationsCollection as $notification) { $notifications[$notification->id] = $notification->title; } // Process the form if ('tl_leads_notification' === \Input::post('FORM_SUBMIT')) { /** * @var \FormModel $form * @var \NotificationCenter\Model\Notification $notification */ if (!isset($notifications[\Input::post('notification')]) || !is_array(\Input::post('IDS')) || ($form = \FormModel::findByPk(\Input::get('master'))) === null || null === ($notification = \NotificationCenter\Model\Notification::findByPk(\Input::post('notification')))) { \Controller::reload(); } if (\Input::get('id')) { $ids = [(int) \Input::get('id')]; } else { $session = \Session::getInstance()->getData(); $ids = array_map('intval', $session['CURRENT']['IDS']); } foreach ($ids as $id) { if (\Leads\NotificationCenterIntegration::send($id, $form, $notification)) { \Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['tl_lead']['notification_confirm'], $id)); } } \Controller::redirect($this->getReferer()); } return \Leads\NotificationCenterIntegration::generateForm($notifications, [\Input::get('id')]); }