/** * @param $dc */ public static function deleteDataRecord($dc) { // If this is not the backend than return if (TL_MODE != 'BE') { return; } // Check if there is an active record if ($dc instanceof \DataContainer && $dc->activeRecord) { $intId = $dc->activeRecord->id; $strTable = $dc->table; $strModel = '\\' . \Model::getClassFromTable($strTable); $objTranslationController = new \TranslationController(); // Return if the class does not exist (#9 thanks to tsarma) if (!class_exists($strModel)) { return; } // Get object from model $objModel = $strModel::findByPk($intId); if ($objModel !== null) { $arrData = $objModel->row(); if (is_array($arrData) && count($arrData) > 0) { // Load current data container $objTranslationController->loadDataContainer($strTable); // Get tl_undo data $objUndo = \Database::getInstance()->prepare("SELECT * FROM tl_undo WHERE fromTable=? ORDER BY id DESC")->limit(1)->execute($dc->table); $arrSet = $objUndo->row(); // Deserialize tl_undo data $arrSet['data'] = deserialize($arrSet['data']); foreach ($arrData as $strField => $varValue) { switch ($GLOBALS['TL_DCA'][$strTable]['fields'][$strField]['inputType']) { case 'TranslationInputUnit': case 'TranslationTextArea': case 'TranslationTextField': // Get translation values $objTranslation = \TranslationFieldsModel::findByFid($varValue); if ($objTranslation !== null) { while ($objTranslation->next()) { $t = \TranslationFieldsModel::getTable(); // Add cross table record to undo data $arrSet['data'][$t][] = $objTranslation->row(); // Delete translation $objTranslation->delete(); } } break; } } // Serialize tl_undo data $arrSet['data'] = serialize($arrSet['data']); // Update tl_undo \Database::getInstance()->prepare("UPDATE tl_undo %s WHERE id=?")->set($arrSet)->execute($objUndo->id); } } } }
/** * @param $varValue * @param \DataContainer $dc * @return string */ public static function save($varValue, \DataContainer $dc) { $arrItems = deserialize($varValue); if (!is_array($arrItems)) { $arrItems = array(); } $dca = $GLOBALS['TL_DCA'][$dc->table]['fields'][$dc->field]; $strModel = \Model::getClassFromTable($dca['crossTable']); self::removeOldItems($strModel, $arrItems, $dc->id, $dca['crossCurrentKey'], $dca['crossForeignKey']); self::addNewItems($strModel, $arrItems, $dc->id, $dca['crossCurrentKey'], $dca['crossForeignKey']); return ''; }
protected function onSubmitCallback(\DataContainer $objDc) { parent::onSubmitCallback($objDc); if ($this->publishOnValid) { $strPublishedField = $this->publishedField; if ($this->publishedField) { $strModelClass = \Model::getClassFromTable($this->strTable); $objInstance = $strModelClass::findByPk($objDc->objActiveRecord->id); $objInstance->{$strPublishedField} = $this->invertPublishedField ? '' : 1; $objInstance->save(); } } }
/** * Initialize the object * * @param ContentModel|ModuleModel|FormModel $objElement * @param string $strColumn */ public function __construct($objElement, $strColumn = 'main') { parent::__construct(); // Store the parent element (see #4556) if ($objElement instanceof Model) { $this->objParent = $objElement; } elseif ($objElement instanceof Model\Collection) { $this->objParent = $objElement->current(); } if ($this->strKey == '' || $this->strTable == '') { return; } /** @var Model $strModelClass */ $strModelClass = \Model::getClassFromTable($this->strTable); // Load the model if (class_exists($strModelClass)) { $objHybrid = $strModelClass::findByPk($objElement->{$this->strKey}); if ($objHybrid === null) { return; } $this->objModel = $objHybrid; } else { $objHybrid = $this->Database->prepare("SELECT * FROM " . $this->strTable . " WHERE id=?")->limit(1)->execute($objElement->{$this->strKey}); if ($objHybrid->numRows < 1) { return; } } $cssID = array(); $this->arrData = $objHybrid->row(); // Get the CSS ID from the parent element (!) $this->cssID = deserialize($objElement->cssID, true); if (isset($objHybrid->attributes)) { $cssID = deserialize($objHybrid->attributes, true); } // Override the CSS ID (see #305) if (!empty($this->cssID[0])) { $cssID[0] = $this->cssID[0]; } // Merge the CSS classes (see #6011) if (!empty($this->cssID[1])) { $cssID[1] = trim($cssID[1] . ' ' . $this->cssID[1]); } $this->cssID = $cssID; $this->typePrefix = $objElement->typePrefix; $arrHeadline = deserialize($objElement->headline); $this->headline = is_array($arrHeadline) ? $arrHeadline['value'] : $arrHeadline; $this->hl = is_array($arrHeadline) ? $arrHeadline['unit'] : 'h1'; $this->strColumn = $strColumn; }
/** * run the importer * @return bool */ public function run() { $this->collectItems(); if ($this->objItems === null) { return false; } $strClass = \Model::getClassFromTable(static::$strTable); if (!class_exists($strClass)) { return false; } while ($this->objItems->next()) { $objItem = $this->createObjectFromMapping($this->objItems, $strClass); $this->createImportMessage($objItem); } return true; }
public static function getParentEntitiesAsOptions(\DataContainer $objDc) { $arrOptions = array(); $arrTitleSynonyms = array('title', 'headline', 'name'); if (($strParentTable = $objDc->activeRecord->parentTable) && ($strClass = \Model::getClassFromTable($strParentTable))) { \Controller::loadDataContainer($strParentTable); if (($objEntities = $strClass::findAll()) !== null) { foreach ($arrTitleSynonyms as $strField) { if (\Database::getInstance()->fieldExists($strField, $strParentTable)) { $arrOptions = $objEntities->fetchEach($strField); asort($arrOptions); break; } } } } return $arrOptions; }
/** * Removes the cross table items from the current deleted left table item * * @access public * @static * @param \DataContainer $dc */ public static function deleteCallback(\DataContainer $dc) { if (!$dc->activeRecord) { return; } $intId = $dc->activeRecord->id; $strTable = $dc->table; if (isset($GLOBALS['TL_DCA'][$dc->table]['fields'])) { foreach ($GLOBALS['TL_DCA'][$dc->table]['fields'] as $k => $v) { if (!isset($v['crossTable']) || !isset($v['crossCurrentKey'])) { continue; } // Get model name $strModel = \Model::getClassFromTable($v['crossTable']); // Check if model exists if (!class_exists($strModel)) { return; } // Get model object $objModel = $strModel::findBy($v['crossCurrentKey'], $intId); if ($objModel !== null) { // Get tl_undo data $objUndo = \Database::getInstance()->prepare("SELECT * FROM tl_undo WHERE fromTable=? ORDER BY id DESC")->limit(1)->execute($dc->table); $arrSet = $objUndo->row(); // Deserialize tl_undo data $arrSet['data'] = deserialize($arrSet['data']); while ($objModel->next()) { // Add cross table record to undo data $arrSet['data'][$v['crossTable']][] = $objModel->row(); // Delete cross table item $objModel->delete(); } // Serialize tl_undo data $arrSet['data'] = serialize($arrSet['data']); // Update tl_undo \Database::getInstance()->prepare("UPDATE tl_undo %s WHERE id=?")->set($arrSet)->execute($objUndo->id); } } } }
/** * @param null $dc * @throws \Exception */ public function setAutoPassword($dc = null) { // Front end call if (!$dc instanceof \DataContainer) { return; } if ($this->isDisabledAccountMail($dc)) { return; } $intId = $dc->id; if (\Input::get('act') == 'overrideAll' && \Input::get('fields') && $intId === null) { // Define indicator for given or not given password on overrideAll mode if (!isset($GLOBALS['ACCOUNTMAIL']['AUTO_PASSWORD'])) { $strPassword = $this->getPostPassword(); $GLOBALS['ACCOUNTMAIL']['AUTO_PASSWORD'] = $strPassword == '' || $strPassword == '*****' ? true : false; if ($GLOBALS['ACCOUNTMAIL']['AUTO_PASSWORD'] === true) { // Set password, that no error occurs with "password not set" $strNewPassword = substr(str_shuffle('abcdefghkmnpqrstuvwxyzABCDEFGHKMNOPQRSTUVWXYZ0123456789'), 0, 8); $this->setPostPassword($strNewPassword); } \Message::addConfirmation($GLOBALS['TL_LANG']['MSC']['pw_changed']); } return; } $strPassword = $this->getPostPassword($intId); if ($strPassword !== null && $strPassword == '') { $strModel = \Model::getClassFromTable($dc->table); $objAccount = $strModel::findByPk($intId); if ($objAccount !== null) { $strNewPassword = substr(str_shuffle('abcdefghkmnpqrstuvwxyzABCDEFGHKMNOPQRSTUVWXYZ0123456789'), 0, 8); $this->setPostPassword($strNewPassword, $intId); \Message::addConfirmation($GLOBALS['TL_LANG']['MSC']['pw_changed']); $objAccount->password = \Encryption::hash($strNewPassword); $objAccount->save(); } } }
/** * Initialize the object * @param object * @param string */ public function __construct($objElement, $strColumn = 'main') { parent::__construct(); // Store the parent element (see #4556) if ($objElement instanceof \Model) { $this->objParent = $objElement; } elseif ($objElement instanceof \Model\Collection) { $this->objParent = $objElement->current(); } if ($this->strKey == '' || $this->strTable == '') { return; } $strModelClass = \Model::getClassFromTable($this->strTable); // Load the model if (class_exists($strModelClass)) { $objHybrid = $strModelClass::findByPk($objElement->{$this->strKey}); if ($objHybrid === null) { return; } $this->objModel = $objHybrid; } else { $objHybrid = $this->Database->prepare("SELECT * FROM " . $this->strTable . " WHERE id=?")->limit(1)->execute($objElement->{$this->strKey}); if ($objHybrid->numRows < 1) { return; } } $this->arrData = $objHybrid->row(); // Get space and CSS ID from the parent element (!) $this->space = deserialize($objElement->space); $this->cssID = deserialize($objElement->cssID, true); $this->typePrefix = $objElement->typePrefix; $arrHeadline = deserialize($objElement->headline); $this->headline = is_array($arrHeadline) ? $arrHeadline['value'] : $arrHeadline; $this->hl = is_array($arrHeadline) ? $arrHeadline['unit'] : 'h1'; $this->strColumn = $strColumn; }
/** * @param \Database\Result|int $result Result object or id * @param string $table * @param bool $update Update model to current result if model is in the registry * * @return \Model */ public static function create($result, $table, $update = false) { $model = null; $class = \Model::getClassFromTable($table); $id = is_object($result) ? $result->id : $result; $cto32 = version_compare(VERSION, '3.2', '>='); // Check the registry in Contao 3.2 if ($cto32) { $model = \Model\Registry::getInstance()->fetch($table, $id); // model is already in the registry, shall we update the model to the current record? // This will affect every reference which uses the model // You really have to know what u need - both is dangerous if ($model && $update) { $model->setRow($result->row()); } } // Model is not in the registry if (!$model) { if (is_object($result)) { $model = new $class($result); } else { // we have to get the result from the db $result = \Database::getInstance()->prepare("SELECT * FROM {$table} WHERE id=?")->execute($id); if ($result->numRows) { $model = new $class($result); } else { $model = new $class(); // do not set id if Contao 3.2 is used because a new record is created, so that id is ignored if (!$cto32) { $model->id = $id; } } } } return $model; }
/** * run the importer * * @return bool */ public function run($dry = false) { $this->dryRun = $dry; $this->collectItems(); if ($this->objItems === null) { return false; } $strClass = \Model::getClassFromTable($this->dbTargetTable); if (!class_exists($strClass)) { return false; } while ($this->objItems->next()) { $objItem = $this->createObjectFromMapping($this->objItems, $strClass); $this->createImportMessage($objItem); } // reset the iterator $this->objItems->reset(); $this->runAfterComplete($this->objItems); return true; }
protected function initialize($blnCreated = false) { // load the model // don't load any class if the form's a filter form -> submission should be used instead if ($this->hasDatabaseTable() && !$this->hasNoEntity()) { $strModelClass = \Model::getClassFromTable($this->strTable); } if (class_exists($strModelClass)) { if (!$blnCreated && ($objModel = $strModelClass::findByPk($this->intId)) !== null) { $this->objActiveRecord = $objModel; $this->setMode(FORMHYBRID_MODE_EDIT); if ($this->saveToBlob) { $this->loadFromBlob(deserialize($objModel->formHybridBlob, true)); } // redirect on specific field value static::doFieldDependentRedirect(); } else { if ($this->objModule !== null && Ajax::isRelated(Form::FORMHYBRID_NAME) !== false) { // do nothing, if ajax request but not related to formhybrid // otherwise a new submission will be generated and validation will fail if ($this->hasDatabaseTable()) { $this->setDefaults($GLOBALS['TL_DCA'][$this->strTable]); // set defaults again, as they might has been overwritten within loadDC/modifyDC $this->setSubmission(); $this->save(); // initially try to save record, as ajax requests for example require entity model } elseif ($this->hasDatabaseTable() && !$this->hasNoEntity()) { $this->invalid = true; StatusMessage::addError($GLOBALS['TL_LANG']['formhybrid']['messages']['error']['invalidId'], $this->objModule->id, 'alert alert-danger'); } } } } else { if (!$this->hasDatabaseTable() || $this->hasNoEntity()) { $this->setSubmission(); } } if ($this->viewMode == FORMHYBRID_VIEW_MODE_READONLY) { $this->strTemplate = $this->readonlyTemplate; $this->setDoNotSubmit(true); } }
/** * Create legacy model * * @param ModelInterface $model * @return \Model * @throws */ public static function createLegacy(ModelInterface $model) { $class = \Model::getClassFromTable($model->getProviderName()); if (!class_exists($class)) { throw new \RuntimeException(sprintf('No model class found for "%s"', $model->getProviderName())); } /** @var \Model $legacy */ $legacy = new $class(); $legacy->setRow($model->getPropertiesAsArray()); return $legacy; }
protected function compile() { $this->Template->headline = $this->headline; $this->Template->hl = $this->hl; $this->Template->wrapperClass = $this->strWrapperClass; $this->Template->wrapperId = $this->strWrapperId; $this->strFormId = $this->formHybridDataContainer . '_' . $this->id; $strAction = $this->defaultAction ?: \Input::get('act'); $this->arrEditable = deserialize($this->formHybridEditable, true); $this->strToken = $this->strToken ?: \Input::get('token'); // Do not change this order (see #6191) $this->Template->style = !empty($this->arrStyle) ? implode(' ', $this->arrStyle) : ''; $this->Template->class = trim('mod_' . $this->type . ' ' . $this->cssID[1]); $this->Template->cssID = $this->cssID[0] != '' ? ' id="' . $this->cssID[0] . '"' : ''; $this->Template->inColumn = $this->strColumn; if ($this->Template->headline == '') { $this->Template->headline = $this->headline; } if ($this->Template->hl == '') { $this->Template->hl = $this->hl; } if (!empty($this->classes) && is_array($this->classes)) { $this->Template->class .= ' ' . implode(' ', $this->classes); } $this->addDefaultArchive(); // at first check for the correct request token to be set if (!$this->deactivateTokens && !\RequestToken::validate($this->strToken)) { if (!$this->blnSilentMode) { StatusMessage::addError(sprintf($GLOBALS['TL_LANG']['frontendedit']['requestTokenExpired'], Url::replaceParameterInUri(Url::getUrl(), 'token', \RequestToken::get())), $this->id, 'requestTokenExpired'); } return; } if ($this->formHybridAllowIdAsGetParameter) { $intId = \Input::get($this->formHybridIdGetParameter); if (is_numeric($intId)) { $this->intId = $intId; } } $strItemClass = \Model::getClassFromTable($this->formHybridDataContainer); // get id from share if ($strShare = \Input::get('share')) { if (($objItem = $strItemClass::findByShareToken($strShare)) !== null && !FormHybridList::shareTokenExpiredOrEmpty($objItem, time())) { $this->intId = $objItem->id; } } if (!$this->intId) { if (isset($GLOBALS['TL_HOOKS']['frontendEditAddNoIdBehavior']) && is_array($GLOBALS['TL_HOOKS']['frontendEditAddNoIdBehavior'])) { foreach ($GLOBALS['TL_HOOKS']['frontendEditAddNoIdBehavior'] as $arrCallback) { $this->import($arrCallback[0]); if ($this->{$arrCallback}[0]->{$arrCallback}[1]($this) === false) { return; } } } if ($this->noIdBehavior == 'error') { if (!$this->blnSilentMode) { StatusMessage::addError($GLOBALS['TL_LANG']['frontendedit']['noIdFound'], $this->id, 'noidfound'); } return; } elseif ($this->noIdBehavior == 'redirect' || $this->noIdBehavior == 'create_until') { $arrConditions = deserialize($this->existanceConditions, true); if ($this->existanceConditions && !empty($arrConditions)) { $arrColumns = array(); $arrValues = array(); foreach ($arrConditions as $arrCondition) { if (!$arrCondition['field']) { continue; } $arrColumns[] = $arrCondition['field'] . '=?'; $arrValues[] = $this->replaceInsertTags($arrCondition['value']); } if (!empty($arrColumns) && ($objItem = $strItemClass::findOneBy($arrColumns, $arrValues)) !== null) { $this->intId = $objItem->id; } } } if (!$this->intId) { if ($this->noIdBehavior == 'redirect') { if (!$this->blnSilentMode) { StatusMessage::addError($GLOBALS['TL_LANG']['frontendedit']['noIdFound'], $this->id, 'noidfound'); } return; } else { $strFormId = FormHelper::getFormId($this->formHybridDataContainer, $this->id); // get id from FormSession if ($_POST) { if ($intId = FormSession::getSubmissionId($strFormId)) { $this->intId = $intId; } } if (!$this->intId) { // if no id is given a new instance is initiated $objConfiguration = new FormConfiguration($this->arrData); // ajax handling, required in this manor, as we have no real ajax controller in contao and ajax request not related to this module // might trigger this module beforhand and new submission will be created after the submission was transfered to the user and id wont match any more if (Ajax::isRelated(Form::FORMHYBRID_NAME) !== null) { if ($intId = FormSession::getSubmissionId($strFormId)) { $this->intId = $intId; } else { $objConfiguration->forceCreate = true; } } $this->objForm = new $this->strFormClass($objConfiguration, $this->arrSubmitCallbacks, $this->intId ?: 0, $this); if ($intId = $this->objForm->getId()) { $this->intId = $intId; } } } } } // intId is set at this point! if (!$this->checkEntityExists($this->intId)) { if (!$this->blnSilentMode) { StatusMessage::addError($GLOBALS['TL_LANG']['formhybrid_list']['noPermission'], $this->id, 'nopermission'); } if (Ajax::isRelated(Form::FORMHYBRID_NAME)) { $objResponse = new ResponseError(); $objResponse->setResult(StatusMessage::generate($this->id)); $objResponse->output(); } return; } // page title if ($this->setPageTitle) { global $objPage; if (($objItem = General::getModelInstance($this->formHybridDataContainer, $this->intId)) !== null) { $objPage->pageTitle = $objItem->{$this->pageTitleField}; } } if ($strAction == FRONTENDEDIT_ACT_DELETE) { if ($this->checkDeletePermission($this->intId)) { $blnResult = $this->deleteItem($this->intId); if (\Environment::get('isAjaxRequest')) { die($blnResult); } // return to the list \Controller::redirect(Url::removeQueryString(array('act', 'id', 'token'), Url::getUrl())); } else { if (!$this->blnSilentMode) { StatusMessage::addError($GLOBALS['TL_LANG']['formhybrid_list']['noPermission'], $this->id, 'nopermission'); } return; } } else { if ($this->checkUpdatePermission($this->intId)) { // create a new lock if necessary if (in_array('entity_lock', \ModuleLoader::getActive()) && $this->addEntityLock) { if (\HeimrichHannot\EntityLock\EntityLockModel::isLocked($this->formHybridDataContainer, $this->intId, $this)) { $objLock = \HeimrichHannot\EntityLock\EntityLockModel::findActiveLock($this->formHybridDataContainer, $this->intId, $this); $objItem = General::getModelInstance($this->formHybridDataContainer, $this->intId); if (!$this->blnSilentMode) { $strMessage = \HeimrichHannot\EntityLock\EntityLock::generateErrorMessage($this->formHybridDataContainer, $this->intId, $this); if ($this->allowLockDeletion) { $strUnlockForm = $this->generateUnlockForm($objItem, $objLock); $strMessage .= $strUnlockForm; } StatusMessage::addError($strMessage, $this->id, 'locked'); } if ($this->readOnlyOnLocked) { $this->formHybridViewMode = FORMHYBRID_VIEW_MODE_READONLY; $this->formHybridReadonlyTemplate = 'formhybridreadonly_default'; } else { return; } } else { \HeimrichHannot\EntityLock\EntityLockModel::create($this->formHybridDataContainer, $this->intId, $this); } } if ($this->objForm === null) { $this->objForm = new $this->strFormClass(new FormConfiguration($this->arrData), $this->arrSubmitCallbacks, $this->intId, $this); } $this->Template->form = $this->objForm->generate(); $this->Template->item = $this->objForm->activeRecord; if (\Environment::get('isAjaxRequest') && \Input::get('scope') == 'modal') { $objItem = General::getModelInstance($this->formHybridDataContainer, $this->intId); $objModalWrapper = new \FrontendTemplate($this->modalTpl ?: 'formhybrid_reader_modal_bootstrap'); if ($objItem !== null) { $objModalWrapper->setData($objItem->row()); } $objModalWrapper->module = Arrays::arrayToObject($this->arrData); $objModalWrapper->item = $this->replaceInsertTags($this->Template->parse()); die($objModalWrapper->parse()); } } else { if (!$this->blnSilentMode) { StatusMessage::addError($GLOBALS['TL_LANG']['formhybrid_list']['noPermission'], $this->id, 'nopermission'); } return; } } }
/** * Create a new collection from a database result * * @param \Database\Result $objResult The database result object * @param string $strTable The table name * * @return static The model collection */ public static function createFromDbResult(\Database\Result $objResult, $strTable) { $arrModels = array(); $strClass = \Model::getClassFromTable($strTable); while ($objResult->next()) { /** @var \Model $strClass */ $objModel = \Model\Registry::getInstance()->fetch($strTable, $objResult->{$strClass::getPk()}); if ($objModel !== null) { $objModel->mergeRow($objResult->row()); $arrModels[] = $objModel; } else { $arrModels[] = new $strClass($objResult); } } return new static($arrModels, $strTable); }
public static function getModelInstance($strTable, $intId) { $strItemClass = \Model::getClassFromTable($strTable); return $strItemClass ? $strItemClass::findByPk($intId) : null; }
public function getArchives(\DataContainer $objDc) { if ($strDc = $objDc->activeRecord->formHybridDataContainer) { \Controller::loadDataContainer($strDc); \System::loadLanguageFile($strDc); $arrDca = $GLOBALS['TL_DCA'][$strDc]; if ($strParentTable = $arrDca['config']['ptable']) { if ($strItemClass = \Model::getClassFromTable($strParentTable)) { $arrOptions = array(); if (($objItems = $strItemClass::findAll()) !== null) { $arrTitleSynonyms = array('name', 'title'); while ($objItems->next()) { $strLabel = ''; foreach ($arrTitleSynonyms as $strTitleSynonym) { if ($objItems->{$strTitleSynonym}) { $strLabel = $objItems->{$strTitleSynonym}; break; } } $arrOptions[$objItems->id] = $strLabel ?: 'Archiv ' . $objItems->id; } } asort($arrOptions); return $arrOptions; } } } }
public function listRecords($row) { $strLabel = $row['alias']; if ($row['type'] == '') { return $strLabel; } $strClass = \Model::getClassFromTable($row['type']); if (!class_exists($strClass)) { return $strLabel; } $objModel = new $strClass(); $objModel->setRow($row); return \HeimrichHannot\Participation\ParticipationController::getParticipationLabel($objModel, $strLabel); }
/** * Generate module */ protected function compile() { // Create files if (\Input::post('FORM_SUBMIT') == 'tl_extension') { $objModule = $this->Database->prepare("SELECT * FROM tl_extension WHERE id=?")->limit(1)->execute($this->objDc->id); if ($objModule->numRows < 1) { return; } // Disable the debug mode (see #7068) \Config::set('debugMode', false); // config/config.php $tplConfig = $this->newTemplate('dev_config', $objModule); \File::putContent('system/modules/' . $objModule->folder . '/config/config.php', $tplConfig->parse()); // config/autoload.ini $tplConfig = $this->newTemplate('dev_ini', $objModule); \File::putContent('system/modules/' . $objModule->folder . '/config/autoload.ini', $tplConfig->parse()); // Back end if ($objModule->addBeMod) { $arrClasses = array_filter(trimsplit(',', $objModule->beClasses)); // Classes foreach ($arrClasses as $strClass) { $tplClass = $this->newTemplate('dev_beClass', $objModule); $tplClass->class = $strClass; \File::putContent('system/modules/' . $objModule->folder . '/' . $this->guessSubfolder($strClass) . '/' . $strClass . '.php', $tplClass->parse()); } $arrTables = array_filter(trimsplit(',', $objModule->beTables)); // Back end data container files foreach ($arrTables as $strTable) { $tplTable = $this->newTemplate('dev_dca', $objModule); $tplTable->table = $strTable; \File::putContent('system/modules/' . $objModule->folder . '/dca/' . $strTable . '.php', $tplTable->parse()); } $arrTemplates = array_filter(trimsplit(',', $objModule->beTemplates)); // Templates foreach ($arrTemplates as $strTemplate) { $tplTemplate = $this->newTemplate('dev_beTemplate', $objModule); \File::putContent('system/modules/' . $objModule->folder . '/templates/' . $strTemplate . '.html5', $tplTemplate->parse()); } } $arrTables = array(); // Front end if ($objModule->addFeMod) { $arrClasses = array_filter(trimsplit(',', $objModule->feClasses)); // Classes foreach ($arrClasses as $strClass) { $tplClass = $this->newTemplate('dev_feClass', $objModule); $tplClass->class = $strClass; $tplClass->extends = $this->guessParentClass($strClass); \File::putContent('system/modules/' . $objModule->folder . '/' . $this->guessSubfolder($strClass) . '/' . $strClass . '.php', $tplClass->parse()); } $arrTables = array_filter(trimsplit(',', $objModule->feTables)); // Front end data container files foreach ($arrTables as $strTable) { $tplTable = $this->newTemplate('dev_feDca', $objModule); $tplTable->table = $strTable; \File::putContent('system/modules/' . $objModule->folder . '/dca/' . $strTable . '.php', $tplTable->parse()); } // Models foreach ($arrTables as $strTable) { $strModel = \Model::getClassFromTable($strTable); $tplTable = $this->newTemplate('dev_model', $objModule); $tplTable->table = $strTable; $tplTable->class = $strModel; \File::putContent('system/modules/' . $objModule->folder . '/models/' . $strModel . '.php', $tplTable->parse()); } $arrTemplates = array_filter(trimsplit(',', $objModule->feTemplates)); // Templates foreach ($arrTemplates as $strTemplate) { $tplTemplate = $this->newTemplate('dev_feTemplate', $objModule); $objTemplate = new \File('system/modules/' . $objModule->folder . '/templates/' . $strTemplate . '.html5', true); $objTemplate->write($tplTemplate->parse()); $objTemplate->close(); $objTemplate->copyTo('system/modules/' . $objModule->folder . '/templates/' . $strTemplate . '.xhtml'); } } // Language packs if ($objModule->addLanguage) { $arrLanguages = array_filter(trimsplit(',', $objModule->languages)); foreach ($arrLanguages as $strLanguage) { // languages/xx/default.php $tplLanguage = $this->newTemplate('dev_default', $objModule); $tplLanguage->language = $strLanguage; \File::putContent('system/modules/' . $objModule->folder . '/languages/' . $strLanguage . '/default.php', $tplLanguage->parse()); // languages/xx/modules.php $tplLanguage = $this->newTemplate('dev_modules', $objModule); $tplLanguage->language = $strLanguage; \File::putContent('system/modules/' . $objModule->folder . '/languages/' . $strLanguage . '/modules.php', $tplLanguage->parse()); // languages/xx/<table>.php foreach ($arrTables as $strTable) { $tplLanguage = $this->newTemplate('dev_table', $objModule); $tplLanguage->language = $strLanguage; $tplLanguage->table = $strTable; \File::putContent('system/modules/' . $objModule->folder . '/languages/' . $strLanguage . '/' . $strTable . '.php', $tplLanguage->parse()); } } } // Public folder $tplConfig = $this->newTemplate('dev_htaccess', $objModule); \File::putContent('system/modules/' . $objModule->folder . '/assets/.htaccess', $tplConfig->parse()); // Confirm and reload \Message::addConfirmation($GLOBALS['TL_LANG']['tl_extension']['confirm']); $this->reload(); } $this->Template->base = \Environment::get('base'); $this->Template->href = $this->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_extension']['make'][0]); $this->Template->headline = sprintf($GLOBALS['TL_LANG']['tl_extension']['headline'], \Input::get('id')); $this->Template->explain = $GLOBALS['TL_LANG']['tl_extension']['make'][1]; $this->Template->label = $GLOBALS['TL_LANG']['tl_extension']['label']; }
/** * Compile a Model class name from a table name (e.g. tl_form_field becomes FormFieldModel) * * @param string $strTable The table name * * @return string The model class name * * @deprecated Use Model::getClassFromTable() instead */ public static function getModelClassFromTable($strTable) { return \Model::getClassFromTable($strTable); }
/** * Fetch a model by table name and primary key * * @param string $strTable The table name * @param mixed $varKey The key * @param string $strAlias An optional alias * * @return Model|null The model or null */ public function fetch($strTable, $varKey, $strAlias = null) { /** @var Model $strClass */ $strClass = \Model::getClassFromTable($strTable); $strPk = $strClass::getPk(); // Search by PK (most common case) if ($strAlias === null || $strAlias == $strPk) { if (isset($this->arrRegistry[$strTable][$varKey])) { return $this->arrRegistry[$strTable][$varKey]; } return null; } // Try to find the model by one of its aliases return $this->fetchByAlias($strTable, $strAlias, $varKey); }
public function checkPermission($intId) { if (!is_numeric($intId)) { return false; } $strItemClass = \Model::getClassFromTable($this->formHybridDataContainer); if ($this->addUpdateConditions && ($objItem = $strItemClass::findByPk($intId)) !== null) { $arrConditions = deserialize($this->updateConditions, true); if (!empty($arrConditions)) { foreach ($arrConditions as $arrCondition) { if ($objItem->{$arrCondition['field']} != $this->replaceInsertTags($arrCondition['value'])) { return false; } } } } return true; }
protected function getFilterFieldInformation($field, $data) { if (empty($field) && !is_array($data)) { return null; } global $container, $TL_DCA; $information = array(); if (empty($information) && array_key_exists($field, $TL_DCA['tl_calendar_events']['fields']) && array_key_exists('foreignKey', $TL_DCA['tl_calendar_events']['fields'][$field])) { $cache = array(); $foreignKey = explode('.', $TL_DCA['tl_calendar_events']['fields'][$field]['foreignKey']); /** @var \Model $model */ $model = \Model::getClassFromTable($foreignKey[0]); foreach ($data as $value) { if (!$value[$field]) { continue; } if (!array_key_exists($value[$field], $cache)) { $cache[$value[$field]] = $model::findByPk($value[$field]); } if (array_key_exists($value[$field], $cache)) { $cache[$value[$field]] = $model::findByPk($value[$field]); $information[$value[$field]] = $cache[$value[$field]]; } } } if (empty($information) && array_key_exists('eval', $TL_DCA['tl_calendar_events']['fields']['startDate']) && array_key_exists('rgxp', $TL_DCA['tl_calendar_events']['fields']['startDate']['eval']) && $TL_DCA['tl_calendar_events']['fields']['startDate']['eval']['rgxp'] === 'date') { foreach ($data as $value) { if ($value[$field] && \Validator::isNumeric($value[$field])) { if (array_key_exists('start', $value) && $value['start'] && $value['start'] < time()) { continue; } if (array_key_exists('stop', $value) && $value['stop'] && $value['stop'] > time()) { continue; } $month = \Date::parse('m::3', $value[$field]); $year = \Date::parse('Y', $value[$field]); $stringDate = $month . ' - ' . $year; if (!in_array($stringDate, $information)) { $dateTime = new \DateTime(); $dateTime->setTimestamp($value[$field]); $dateTime->modify('first day of this month'); $beginMonth = $dateTime->getTimestamp(); $dateTime->modify('last day of this month'); $endMonth = $dateTime->getTimestamp(); $information[$beginMonth . '-' . $endMonth] = $stringDate; } } } } /** @var EventDispatcher $eventDispatcher */ $eventDispatcher = $container['event-dispatcher']; $informationEvent = new PostFilterInformationEvent($field, $data); $informationEvent->setInformation($information); $eventDispatcher->dispatch(PostFilterInformationEvent::NAME, $informationEvent); return $informationEvent->getInformation(); }
/** * Load type agent model help * * @param string $strTable */ public function loadTypeAgentHelp($strTable) { $strKey = \Input::get('table'); $strField = \Input::get('field'); if ($strKey !== $strTable) { return; } if ($strKey == 'tl_iso_producttype') { $strKey = 'tl_iso_product'; } if (TL_SCRIPT !== 'contao/help.php' || !isset($GLOBALS['TL_DCA'][$strTable]['fields'][$strField]) || !is_subclass_of(\Model::getClassFromTable($strKey), 'Isotope\\Model\\TypeAgent')) { return; } $arrField =& $GLOBALS['TL_DCA'][$strTable]['fields'][$strField]; // Get the field type /** @var \Widget $strClass */ $strClass = $GLOBALS['BE_FFL'][$arrField['inputType']]; // Abort if the class is not defined if (!class_exists($strClass)) { return; } $arrFieldComplete = $strClass::getAttributesFromDca($arrField, $strField); if (!$arrFieldComplete || !$arrFieldComplete['helpwizard'] || !is_array($arrFieldComplete['options']) || $arrField['explanation'] != '' || isset($GLOBALS['TL_LANG']['XPL']['type'])) { return; } // try to load a type agent model help description $arrField['explanation'] = 'type'; foreach ($arrFieldComplete['options'] as $arrOption) { $arrLabel = $GLOBALS['TL_LANG']['MODEL'][$strKey . '.' . $arrOption['value']]; if ($arrLabel) { $GLOBALS['TL_LANG']['XPL']['type'][] = $arrLabel; } } }
public static function findRelatedNewsEntity($varId, array $arrRelation, \ModuleModel $objModule = null) { if (!isset($arrRelation['table'])) { return null; } $strModelClass = \Model::getClassFromTable($arrRelation['table']); if (!class_exists($strModelClass)) { return null; } if ($objModule === null) { return \NewsModel::findByPk($varId); } return \NewsModel::findPublishedByParentAndIdOrAlias($varId, deserialize($objModule->news_archives)); }
<?php /** * Contao I18n provides some i18n structures for easily l10n websites. * * @package dev * @author David Molineus <*****@*****.**> * @copyright 2015 netzmacht creative David Molineus * @license LGPL 3.0 * @filesource * */ global $container; use Model\Registry; use Netzmacht\Contao\I18n\I18n; use Netzmacht\Contao\I18n\Model\Repository\PageRepository; use Netzmacht\Contao\I18n\Router; $container['i18n.pages'] = ['i18n_regular']; $container['i18n.page-repository'] = $container->share(function ($container) { return new PageRepository($container['database.connection'], Registry::getInstance(), Model::getClassFromTable('tl_page')); }); $container['i18n'] = $container->share(function ($container) { return new I18n($container['i18n.pages'], $container['i18n.page-repository']); }); $container['i18n.router'] = $container->share(function ($container) { $types = empty($GLOBALS['I18N_ROUTING']) ? [] : (array) $GLOBALS['I18N_ROUTING']; return new Router($container['i18n'], $types); });
/** * Run the controller and parse the template */ public function run() { /** @var \BackendTemplate|object $objTemplate */ $objTemplate = new \BackendTemplate('be_picker'); $objTemplate->main = ''; // Ajax request if ($_POST && \Environment::get('isAjaxRequest')) { $this->objAjax = new \Ajax(\Input::post('action')); $this->objAjax->executePreActions(); } $strTable = \Input::get('table'); $strField = \Input::get('field'); // Define the current ID define('CURRENT_ID', \Input::get('table') ? $this->Session->get('CURRENT_ID') : \Input::get('id')); $this->loadDataContainer($strTable); $strDriver = 'DC_' . $GLOBALS['TL_DCA'][$strTable]['config']['dataContainer']; $objDca = new $strDriver($strTable); $objDca->field = $strField; // Set the active record if ($this->Database->tableExists($strTable)) { /** @var \Model $strModel $strModel */ $strModel = \Model::getClassFromTable($strTable); if (class_exists($strModel)) { $objModel = $strModel::findByPk(\Input::get('id')); if ($objModel !== null) { $objDca->activeRecord = $objModel; } } } // AJAX request if ($_POST && \Environment::get('isAjaxRequest')) { $this->objAjax->executePostActions($objDca); } $this->Session->set('filePickerRef', \Environment::get('request')); $arrValues = array_filter(explode(',', \Input::get('value'))); // Call the load_callback if (is_array($GLOBALS['TL_DCA'][$strTable]['fields'][$strField]['load_callback'])) { foreach ($GLOBALS['TL_DCA'][$strTable]['fields'][$strField]['load_callback'] as $callback) { if (is_array($callback)) { $this->import($callback[0]); $arrValues = $this->{$callback[0]}->{$callback[1]}($arrValues, $objDca); } elseif (is_callable($callback)) { $arrValues = $callback($arrValues, $objDca); } } } /** @var \PageSelector $strClass */ $strClass = $GLOBALS['BE_FFL']['pageSelector']; /** @var \PageSelector $objPageTree */ $objPageTree = new $strClass($strClass::getAttributesFromDca($GLOBALS['TL_DCA'][$strTable]['fields'][$strField], $strField, $arrValues, $strField, $strTable, $objDca)); $objTemplate->main = $objPageTree->generate(); $objTemplate->theme = \Backend::getTheme(); $objTemplate->base = \Environment::get('base'); $objTemplate->language = $GLOBALS['TL_LANGUAGE']; $objTemplate->title = specialchars($GLOBALS['TL_LANG']['MSC']['pagepicker']); $objTemplate->charset = \Config::get('characterSet'); $objTemplate->addSearch = true; $objTemplate->search = $GLOBALS['TL_LANG']['MSC']['search']; $objTemplate->action = ampersand(\Environment::get('request')); $objTemplate->value = $this->Session->get('page_selector_search'); $objTemplate->breadcrumb = $GLOBALS['TL_DCA']['tl_page']['list']['sorting']['breadcrumb']; if ($this->User->hasAccess('page', 'modules')) { $objTemplate->manager = $GLOBALS['TL_LANG']['MSC']['pageManager']; $objTemplate->managerHref = 'contao/main.php?do=page&popup=1'; } if (\Input::get('switch') && $this->User->hasAccess('files', 'modules')) { $objTemplate->switch = $GLOBALS['TL_LANG']['MSC']['filePicker']; $objTemplate->switchHref = str_replace('contao/page.php', 'contao/file.php', ampersand(\Environment::get('request'))); } \Config::set('debugMode', false); $objTemplate->output(); }
public static function getModelInstances($strTable, array $arrOptions = array()) { $strItemClass = \Model::getClassFromTable($strTable); return $strItemClass ? $strItemClass::findAll($arrOptions) : null; }
public function getSourceOptions() { $arrOptions = array(); $strModelClass = \Model::getClassFromTable($this->type); if (!class_exists($strModelClass)) { return $arrOptions; } $objSources = $strModelClass::findAll(); if ($objSources === null) { return $arrOptions; } while ($objSources->next()) { $key = $objSources->{$strModelClass::getPk()}; $value = $this->getSourceOptionValue($objSources->current()); if ($this->ptable && ($objParent = $objSources->getRelated('pid')) !== null) { $strParent = $this->getSourceGroupValue($objParent); $arrOptions[$strParent][$key] = $value; continue; } $arrOptions[$key] = $value; } return $arrOptions; }
/** * Update the parent field with its tl_fieldpalette item ids * * @param DataContainer $dc * * @return bool */ public function updateParentField($objCurrentRecord, $intDelete = 0) { $strClass = \Model::getClassFromTable($objCurrentRecord->ptable); if (!class_exists($strClass)) { return false; } /** @var \Model $strClass */ $objParent = $strClass::findByPk($objCurrentRecord->pid); if ($objParent === null) { return false; } $objItems = \HeimrichHannot\FieldPalette\FieldPaletteModel::findByPidAndTableAndField($objCurrentRecord->pid, $objCurrentRecord->ptable, $objCurrentRecord->pfield); $varValue = array(); if ($objItems !== null) { $varValue = $objItems->fetchEach('id'); // ondelete_callback support if ($intDelete > 0 && ($key = array_search($intDelete, $varValue)) !== false) { unset($varValue[$key]); } } if (empty($varValue)) { \Controller::loadDataContainer($objCurrentRecord->ptable); $arrData = $GLOBALS['TL_DCA'][$objCurrentRecord->ptable]['fields'][$objCurrentRecord->pfield]; if (isset($arrData['sql'])) { $varValue = \Widget::getEmptyValueByFieldType($arrData['sql']); } } $objParent->{$objCurrentRecord->pfield} = $varValue; $objParent->save(); }