Example #1
0
 /**
  * @static
  * @return MetaModelFactory
  */
 public static function getInstance()
 {
     if (!isset(self::$factory)) {
         self::$factory = new MetaModelFactory();
     }
     return self::$factory;
 }
 /**
  * retrieve the MetaModel this filter belongs to.
  *
  * @return IMetaModel
  */
 public function getMetaModel()
 {
     if (!$this->arrData['pid']) {
         throw new Exception(sprintf('Error: Filtersetting %d not attached to a MetaModel', $this->arrData['id']));
     }
     return MetaModelFactory::byId($this->arrData['pid']);
 }
    public function getDatasetMetaData($datasetName) {
        $datasetName = StringHelper::trim($datasetName);

        $metamodel = data_controller_get_metamodel();

        $dataset = $metamodel->getDataset($datasetName);
        if (!$dataset->isComplete()) {
            $callcontext = $this->prepareCallContext();

            MetaModelFactory::getInstance()->startGlobalModification();
            try {
                RequestChainFactory::getInstance()->initializeChain()->loadDatasetMetaData(
                    $this->getDataSourceQueryHandlerByDataset($dataset), $callcontext, $dataset);

                $dataset->markAsComplete();
            }
            catch (Exception $e) {
                MetaModelFactory::getInstance()->finishGlobalModification(FALSE);
                throw $e;
            }
            MetaModelFactory::getInstance()->finishGlobalModification(TRUE);
        }

        return $dataset;
    }
Example #4
0
 /**
  * Fetch all attribute names for the current metamodel
  *
  * @param DataContainer $objDC the datacontainer calling this method.
  *
  * @return string[string] array of all attributes as colName => human name
  */
 public function getAttributeNames(DataContainer $objDC)
 {
     $arrAttributeNames = array('sorting' => $GLOBALS['TL_LANG']['MSC']['sorting'], 'random' => $GLOBALS['TL_LANG']['MSC']['random']);
     $objMetaModel = MetaModelFactory::byId($objDC->activeRecord->metamodel);
     if ($objMetaModel) {
         foreach ($objMetaModel->getAttributes() as $objAttribute) {
             $arrAttributeNames[$objAttribute->getColName()] = $objAttribute->getName();
         }
     }
     return $arrAttributeNames;
 }
 /**
  * Create a MetaModelAttribute instance with the given information.
  *
  * @param array $arrData the meta information for the MetaModelAttribute.
  *
  * @return IMetaModelAttribute|null the created instance or null if unable to construct.
  */
 protected static function createInstance($arrData)
 {
     $strFactoryName = self::getAttributeTypeFactory($arrData['type']);
     $objAttribute = null;
     if ($strFactoryName) {
         $objAttribute = call_user_func_array(array($strFactoryName, 'createInstance'), array($arrData));
     } else {
         $strClassName = self::getAttributeTypeClass($arrData['type']);
         if ($strClassName) {
             $objMetaModel = MetaModelFactory::byId($arrData['pid']);
             $objAttribute = new $strClassName($objMetaModel, $arrData);
         }
     }
     return $objAttribute;
 }
    /**
     * @param DataControllerCallContext $callcontext
     * @param DatasetMetaData $dataset
     * @param DatasetStorageObserver[] $observers
     * @throws Exception
     */
    protected function disableDatasetStorage(DataControllerCallContext $callcontext, DatasetMetaData $dataset, array $observers = NULL) {
        MetaModelFactory::getInstance()->startGlobalModification();
        try {
            $transaction = db_transaction();
            try {
                $dataset->used = FALSE;

                if (isset($observers)) {
                    foreach ($observers as $observer) {
                        $observer->disableDataset($callcontext, $dataset);
                    }
                }
            }
            catch (Exception $e) {
                $transaction->rollback();
                throw $e;
            }
        }
        catch (Exception $e) {
            MetaModelFactory::getInstance()->finishGlobalModification(FALSE);
            throw $e;
        }
        MetaModelFactory::getInstance()->finishGlobalModification(TRUE);
    }
 /**
  * {@inheritdoc}
  */
 public function getMetaModel()
 {
     return MetaModelFactory::byTableName($this->strMetaModel);
 }
Example #8
0
 public function getAttributes()
 {
     $objMetaModel = MetaModelFactory::byId();
     $tables = array();
     foreach ($this->Database->listTables() as $table) {
         $tables[$table] = $table;
     }
     return $tables;
 }
 /**
  *
  * @param type $objDC
  * @return type
  * @throws Exception
  */
 public function onLoadCallback($objDC)
 {
     // do nothing if not in edit/create mode.
     if (!(($this->Input->get('pid') || $this->Input->get('id')) && in_array($this->Input->get('act'), array('create', 'edit')))) {
         return;
     }
     if ($objDC->id) {
         $objMetaModel = MetaModelFactory::byId($this->Database->prepare('SELECT pid FROM tl_metamodel_rendersettings WHERE id = ?')->execute($objDC->id)->pid);
     } else {
         if ($this->Input->get('pid')) {
             $objMetaModel = MetaModelFactory::byId($this->Input->get('pid'));
         }
     }
     if (!$objMetaModel) {
         throw new Exception('unexpected condition, metamodel unknown', 1);
     }
     $this->prepareJumpToMcw($objMetaModel);
 }
Example #10
0
 /**
  * Prepare the MetaModel.
  *
  * @return void
  *
  * @throws RuntimeException
  */
 protected function prepareMetaModel()
 {
     $this->objMetaModel = MetaModelFactory::byId($this->intMetaModel);
     if (!$this->objMetaModel) {
         throw new \RuntimeException('Could get metamodel id: ' . $this->intMetaModel);
     }
 }
    /**
     * Add the type of input field
     * @param array
     * @return string
     */
    public function renderField($arrRow)
    {
        $objMetaModel = MetaModelFactory::byId($arrRow['pid']);
        $strColName = $arrRow['colname'];
        $strType = $arrRow['type'];
        $strImages = '';
        $strTypeImage = '';
        $arrName = deserialize($arrRow['name']);
        if (is_array($arrName)) {
            $strName = $arrName[$GLOBALS['TL_LANGUAGE']];
            if (!$strName) {
                $strName = $arrName[$objMetaModel->getFallbackLanguage()];
            }
        } else {
            $strName = $arrRow['name'];
        }
        $arrDescription = deserialize($arrRow['description']);
        if (is_array($arrDescription)) {
            $strDescription = $arrDescription[$GLOBALS['TL_LANGUAGE']];
            if (!$strDescription) {
                $strDescription = $arrDescription[$objMetaModel->getFallbackLanguage()];
            }
        } else {
            $strDescription = $arrRow['name'];
        }
        $strTypeImage = '<img src="' . $GLOBALS['METAMODELS']['attributes'][$strType]['image'] . '" />';
        return sprintf('<div class="field_heading cte_type"><strong>%s</strong> <em>[%s]</em></div>
<div class="field_type block">
	<div style="padding-top:3px; float:right;">%s</div>
	%s<strong>%s</strong> - %s<br />
	' . ($arrRow['insertBreak'] ? '<span style="padding-left:20px;" class="legend" title="' . $GLOBALS['TL_LANG']['tl_metamodel_attribute']['legendTitle'][0] . '">' . $legendImage . ' ' . $arrRow['legendTitle'] . '</span>' : '') . '
</div>', $strColName, $strType, $strImages, $strTypeImage, $strName, $strDescription);
    }
 public function subpaletteButton($row, $href, $label, $title, $icon, $attributes)
 {
     // Check if we have a attribute
     if ($row['dcatype'] != 'attribute' || strlen($this->Input->get('subpaletteid')) != 0) {
         return $this->makeDisabledButton($icon, $label);
     }
     // Get MM and check if we have a valide one.
     $intId = $this->Database->prepare('SELECT pid FROM tl_metamodel_dca WHERE id=?')->execute($row['pid'])->pid;
     $objMetaModel = MetaModelFactory::byId($intId);
     if (is_null($objMetaModel)) {
         return $this->makeDisabledButton($icon, $label);
     }
     // Get attribute and check if we have a valide one.
     $objAttribute = $objMetaModel->getAttributeById($row['attr_id']);
     if (is_null($objAttribute)) {
         return $this->makeDisabledButton($icon, $label);
     }
     // TODO: add some attribute::supports method to add only for attributes that indeed support subpaletting.
     // For the moment we add a dirty check, only for checkboxes.
     if (in_array($objAttribute->get('type'), array('checkbox'))) {
         return '<a href="' . $this->addToUrl($href . '&amp;id=' . $row['pid'] . '&amp;subpaletteid=' . $row['id']) . '" title="' . specialchars($title) . '"' . $attributes . '>' . $this->generateImage($icon, $label) . '</a> ';
     }
     return $this->makeDisabledButton($icon, $label);
 }
    public static function prepareReference(MetaModel $metamodel, $referenceNode, array $referencePointNodes = NULL) {
        $referencePoints = $lookupReferencePoints = $interlookupReferences = NULL;

        // loading reference points
        $referencePointIndex = 0;
        while (TRUE) {
            $point_nid = get_node_field_int_value($referenceNode, 'field_reference_point', $referencePointIndex, 'nid');
            if (!isset($point_nid)) {
                break;
            }

            $referencePointNode = $referencePointNodes[$point_nid];

            $datasetName = get_node_field_value($referencePointNode, 'field_ref_point_dataset_sysname', 0, 'value', TRUE);
            $dataset = $metamodel->findDataset($datasetName);
            if (isset($dataset)) {
                $referencePoint = new DatasetReferencePoint();
                $lookupReferencePoint = new DatasetReferencePoint();

                $loader = MetaModelFactory::getInstance()->getLoader($dataset->loaderName);

                $cube = $metamodel->getCube($dataset->name);
                $referenceDatasetName = $cube->factsDatasetName;

                // preparing list of columns
                $referencePointColumnIndex = 0;
                while (TRUE) {
                    $columnName = get_node_field_value($referencePointNode, 'field_ref_point_column_sysname', $referencePointColumnIndex);
                    if (isset($columnName) || ($referencePointColumnIndex === 0)) {
                        $referencePointColumn = $referencePoint->initiateColumn();
                        $referencePointColumn->datasetName = $referenceDatasetName;
                        $referencePoint->registerColumnInstance($referencePointColumn);
                        if (isset($columnName)) {
                            $referencePointColumn->columnName = $columnName;
                        }

                        $interlookupLookupReferencePointColumn = $lookupReferencePoint->initiateColumn();
                        $interlookupLookupReferencePointColumn->datasetName = $referenceDatasetName;
                        $interlookupLookupReferencePointColumn->columnName = $referencePointColumn->columnName;
                        ReferenceMetaModelLoaderHelper::adjustReferencePointColumn($loader, $metamodel, $interlookupLookupReferencePointColumn);
                        if (!$interlookupLookupReferencePointColumn->isShared()) {
                            $interlookupReferences[$referencePointColumnIndex][$referencePointIndex] = $interlookupLookupReferencePointColumn;
                        }

                        $lookupReferencePointColumn = clone $interlookupLookupReferencePointColumn;
                        $lookupReferencePointColumn->columnName = NULL;
                        $lookupReferencePoint->registerColumnInstance($lookupReferencePointColumn);
                    }
                    if (!isset($columnName)) {
                        break;
                    }

                    $referencePointColumnIndex++;
                }

                $referencePoints[$referencePointIndex] = $referencePoint;
                $lookupReferencePoints[$referencePointIndex] = $lookupReferencePoint;
            }

            $referencePointIndex++;
        }

        $referencePointCount = count($referencePoints);
        if ($referencePointCount == 0) {
            return;
        }

        // checking if we need to add references between lookup reference point columns (second reference point in each reference)
        if (isset($interlookupReferences)) {
            // creating separate references for each reference point
            foreach ($referencePoints as $referencePointIndex => $referencePoint) {
                $lookupReferencePoint = $lookupReferencePoints[$referencePointIndex];

                $reference = new DatasetReference();
                $reference->name = get_node_field_value($referenceNode, 'field_reference_sysname', 0, 'value', TRUE) . '_rp' . $referencePointIndex;

                $reference->registerPointInstance($referencePoint);
                $reference->registerPointInstance($lookupReferencePoint);
                $metamodel->registerReference($reference);
            }

            // linking lookup reference point columns
            foreach ($interlookupReferences as $columnIndex => $interlookupReferencePointColumns) {
                if (count($interlookupReferencePointColumns) < $referencePointCount) {
                    throw new UnsupportedOperationException(t('All reference point columns with the same reference point column index have to be non-shared'));
                }

                $interLookupReferenceName = get_node_field_value($referenceNode, 'field_reference_sysname', 0, 'value', TRUE) . '_rpci' . $columnIndex;
                foreach ($interlookupReferencePointColumns as $interlookupReferencePointColumn) {
                    $metamodel->registerSimpleReferencePoint(
                        $interLookupReferenceName,
                        $interlookupReferencePointColumn->datasetName, $interlookupReferencePointColumn->columnName);
                }
            }
        }
        else {
            // checking that all lookup reference points are the same
            $masterLookupReferencePoint = NULL;
            foreach ($lookupReferencePoints as $lookupReferencePoint) {
                if (isset($masterLookupReferencePoint)) {
                    if (!$masterLookupReferencePoint->equals($lookupReferencePoint)) {
                        throw new UnsupportedOperationException(t('Unlinkable lookup reference points are not the same'));
                    }
                }
                else {
                    $masterLookupReferencePoint = $lookupReferencePoint;
                }
            }

            // combining all reference points into one reference
            $reference = new DatasetReference();
            $reference->name = get_node_field_value($referenceNode, 'field_reference_sysname', 0, 'value', TRUE);
            foreach ($referencePoints as $referencePointIndex => $referencePoint) {
                $lookupReferencePoint = $lookupReferencePoints[$referencePointIndex];

                $reference->registerPointInstance($referencePoint);
                $reference->registerPointInstance($lookupReferencePoint);
            }
            $metamodel->registerReference($reference);
        }
    }
 /**
  * Set base config with source and other necessary parameter.
  *
  * @param array $arrConfig The configuration to use.
  *
  * @return void
  *
  * @throws Exception when no source has been defined.
  */
 public function setBaseConfig(array $arrConfig)
 {
     // Check Vars
     if (!$arrConfig["source"]) {
         throw new Exception("Missing table name.");
     }
     // Init Vars
     $this->strTable = $arrConfig["source"];
     $this->objMetaModel = MetaModelFactory::byTableName($this->strTable);
 }
 /**
  * Generate module
  */
 public function addAll()
 {
     $this->loadLanguageFile('default');
     $this->loadLanguageFile('tl_metamodel_rendersetting');
     $this->Template = new BackendTemplate('be_autocreateview');
     $this->Template->cacheMessage = '';
     $this->Template->updateMessage = '';
     $this->Template->href = $this->getReferer(true);
     $this->Template->headline = $GLOBALS['TL_LANG']['tl_metamodel_rendersetting']['addall'][1];
     // severity: error, confirm, info, new
     $arrMessages = array();
     $objPalette = $this->Database->prepare('SELECT * FROM tl_metamodel_rendersettings WHERE id=?')->execute($this->Input->get('id'));
     $objMetaModel = MetaModelFactory::byId($objPalette->pid);
     $objAlreadyExist = $this->Database->prepare('SELECT * FROM tl_metamodel_rendersetting WHERE pid=?')->execute($this->Input->get('id'));
     $arrKnown = array();
     $intMax = 128;
     while ($objAlreadyExist->next()) {
         $arrKnown[$objAlreadyExist->attr_id] = $objAlreadyExist->row();
         if ($intMax < $objAlreadyExist->sorting) {
             $intMax = $objAlreadyExist->sorting;
         }
     }
     $blnWantPerform = false;
     // perform the labour work
     if ($this->Input->post('act') == 'perform') {
         // loop over all attributes now.
         foreach ($objMetaModel->getAttributes() as $objAttribute) {
             if (!array_key_exists($objAttribute->get('id'), $arrKnown)) {
                 $arrData = array();
                 $objRenderSetting = $objAttribute->getDefaultRenderSettings();
                 foreach ($objRenderSetting->getKeys() as $key) {
                     $arrData[$key] = $objRenderSetting->get($key);
                 }
                 $arrData = array_replace_recursive($arrData, array('pid' => $this->Input->get('id'), 'sorting' => $intMax, 'tstamp' => time(), 'attr_id' => $objAttribute->get('id')));
                 $intMax += 128;
                 $this->Database->prepare('INSERT INTO tl_metamodel_rendersetting %s')->set($arrData)->execute();
                 $arrMessages[] = array('severity' => 'confirm', 'message' => sprintf($GLOBALS['TL_LANG']['tl_metamodel_rendersetting']['addAll_addsuccess'], $objAttribute->getName()));
             }
         }
     } else {
         // loop over all attributes now.
         foreach ($objMetaModel->getAttributes() as $objAttribute) {
             if (array_key_exists($objAttribute->get('id'), $arrKnown)) {
                 $arrMessages[] = array('severity' => 'info', 'message' => sprintf($GLOBALS['TL_LANG']['tl_metamodel_rendersetting']['addAll_alreadycontained'], $objAttribute->getName()));
             } else {
                 $arrMessages[] = array('severity' => 'confirm', 'message' => sprintf($GLOBALS['TL_LANG']['tl_metamodel_rendersetting']['addAll_willadd'], $objAttribute->getName()));
                 $blnWantPerform = true;
             }
         }
     }
     if ($blnWantPerform) {
         $this->Template->action = ampersand($this->Environment->request);
         $this->Template->submit = $GLOBALS['TL_LANG']['MSC']['continue'];
     } else {
         $this->Template->action = ampersand($this->getReferer(true));
         $this->Template->submit = $GLOBALS['TL_LANG']['MSC']['saveNclose'];
     }
     $this->Template->error = $arrMessages;
     return $this->Template->parse();
 }
 /**
  * Get a list with all allowed attributes for meta description.
  * 
  * @param DataContainer $objDC
  * 
  * @return array A list with all found attributes.
  */
 public function getAttributeNamesForModel($intMetaModel, $arrTypes = array())
 {
     $arrAttributeNames = array();
     $objMetaModel = MetaModelFactory::byId($intMetaModel);
     if ($objMetaModel) {
         foreach ($objMetaModel->getAttributes() as $objAttribute) {
             if (empty($arrTypes) || in_array($objAttribute->get('type'), $arrTypes)) {
                 $arrAttributeNames[$objAttribute->getColName()] = $objAttribute->getName() . ' [' . $objAttribute->getColName() . ']';
             }
         }
     }
     return $arrAttributeNames;
 }
    /**
     * @param DataControllerCallContext $callcontext
     * @param DatasetMetaData $originalDataset
     * @param DatasetMetaData $modifiedDataset
     * @param DatasetStorageObserver[] $observers
     * @throws Exception
     */
    protected function updateProperties(DataControllerCallContext $callcontext, DatasetMetaData $originalDataset, DatasetMetaData $modifiedDataset, array $observers = NULL) {
        $justPersistedColumns = NULL;
        ArrayHelper::merge($justPersistedColumns, $callcontext->changeAction->newIncludedColumns);
        ArrayHelper::merge($justPersistedColumns, $callcontext->changeAction->restoredColumns);
        ArrayHelper::merge($justPersistedColumns, $callcontext->changeAction->updatedDataTypeIncludedColumns);

        $columns = $justPersistedColumns;
        ArrayHelper::merge($columns, $callcontext->changeAction->updatedColumns);
        if ($callcontext->changeAction->isDatasetUpdated || isset($columns) || $callcontext->changeAction->isKeyUpdated) {
            MetaModelFactory::getInstance()->startGlobalModification();
            try {
                $transaction = db_transaction();
                try {
                    if (isset($columns)) {
                        foreach ($columns as $column) {
                            if (isset($justPersistedColumns[$column->name])) {
                                $column->used = TRUE;
                            }

                            if (isset($callcontext->changeAction->updatedColumns[$column->name])) {
                                $modifiedColumn = $modifiedDataset->getColumn($column->name);

                                $column->publicName = $modifiedColumn->publicName;
                                $column->description = $modifiedColumn->description;
                                $column->source = $modifiedColumn->source;
                                $column->key = $modifiedColumn->key;
                            }

                            if (isset($observers)) {
                                foreach ($observers as $observer) {
                                    $observer->updateColumn($callcontext, $originalDataset, $column->name);
                                }
                            }
                        }
                    }

                    if ($callcontext->changeAction->isDatasetUpdated) {
                        $originalDataset->publicName = $modifiedDataset->publicName;
                        $originalDataset->description = $modifiedDataset->description;
                        $originalDataset->initializeSourceFrom($modifiedDataset->source, TRUE);
                        $originalDataset->initializeAliasesFrom($modifiedDataset->aliases, TRUE);

                        if (isset($observers)) {
                            foreach ($observers as $observer) {
                                $observer->updateDataset($callcontext, $originalDataset);
                            }
                        }
                    }

                    if ($callcontext->changeAction->isKeyUpdated) {
                        $modifiedDatasetKeyColumnNames = $modifiedDataset->findKeyColumnNames();
                        if (isset($modifiedDatasetKeyColumnNames)) {
                            $this->executeDatasetUpdateOperations(
                                $callcontext,
                                $originalDataset,
                                array(new CreateDatasetKeyOperation()));
                        }
                    }
                }
                catch (Exception $e) {
                    $transaction->rollback();
                    throw $e;
                }
            }
            catch (Exception $e) {
                MetaModelFactory::getInstance()->finishGlobalModification(FALSE);
                throw $e;
            }
            MetaModelFactory::getInstance()->finishGlobalModification(TRUE);
        }
    }
    protected function objectsFromUrl($objDC)
    {
        if ($this->Input->get('do') != 'metamodels' || (is_object($objDC) && $objDC->table != 'tl_metamodel_filtersetting' || !is_object($objDC) && $objDC != 'tl_metamodel_filtersetting')) {
            return;
        }
        // TODO: detect all other ways we might end up here and fetch $objMetaModel accordingly.
        if ($this->objMetaModel) {
            return;
        }
        if (is_object($objDC) && $objDC->getCurrentModel()) {
            $this->strSettingType = $objDC->getCurrentModel()->getProperty('type');
            $this->objFilter = $this->Database->prepare('SELECT * FROM tl_metamodel_filter WHERE id=?')->execute($objDC->getCurrentModel()->getProperty('fid'));
            $this->objMetaModel = MetaModelFactory::byId($this->objFilter->pid);
        }
        if ($this->Input->get('act')) {
            // act present, but we have an id
            switch ($this->Input->get('act')) {
                case 'edit':
                    if ($this->Input->get('id')) {
                        $this->objFilter = $this->Database->prepare('
							SELECT tl_metamodel_filter.*,
								tl_metamodel_filtersetting.type AS tl_metamodel_filtersetting_type,
								tl_metamodel_filtersetting.id AS tl_metamodel_filtersetting_id
							FROM tl_metamodel_filtersetting
							LEFT JOIN tl_metamodel_filter
							ON (tl_metamodel_filtersetting.fid = tl_metamodel_filter.id)
							WHERE (tl_metamodel_filtersetting.id=?)')->execute($this->Input->get('id'));
                        $this->strSettingType = $this->objFilter->tl_metamodel_filtersetting_type;
                        $this->objMetaModel = MetaModelFactory::byId($this->objFilter->pid);
                    }
                    break;
                case 'paste':
                    if ($this->Input->get('id')) {
                        switch ($this->Input->get('mode')) {
                            case 'create':
                                $this->objFilter = $this->Database->prepare('SELECT * FROM tl_metamodel_filter WHERE id=?')->execute($this->Input->get('id'));
                                $this->objMetaModel = MetaModelFactory::byId($this->objFilter->pid);
                                break;
                            case 'cut':
                                $this->objFilter = $this->Database->prepare('
									SELECT tl_metamodel_filter.*,
										tl_metamodel_filtersetting.type AS tl_metamodel_filtersetting_type,
										tl_metamodel_filtersetting.id AS tl_metamodel_filtersetting_id
									FROM tl_metamodel_filtersetting
									LEFT JOIN tl_metamodel_filter
									ON (tl_metamodel_filtersetting.fid = tl_metamodel_filter.id)
									WHERE (tl_metamodel_filtersetting.id=?)')->execute($this->Input->get('source'));
                                $this->strSettingType = $this->objFilter->tl_metamodel_filtersetting_type;
                                $this->objMetaModel = MetaModelFactory::byId($this->objFilter->pid);
                                break;
                        }
                    }
                    break;
                case 'create':
                    $this->objFilter = $this->Database->prepare('SELECT * FROM tl_metamodel_filter WHERE id=?')->execute($this->Input->get('id'));
                    $this->objMetaModel = MetaModelFactory::byId($this->objFilter->pid);
                    break;
                default:
            }
        } else {
            // no act but we have an id, should be list mode then, no type name available.
            if ($this->Input->get('id')) {
                $this->objFilter = $this->Database->prepare('SELECT * FROM tl_metamodel_filter WHERE id=?')->execute($this->Input->get('id'));
                $this->objMetaModel = MetaModelFactory::byId($this->objFilter->pid);
            }
        }
        // select all root entries for the current filter.
        $GLOBALS['TL_DCA']['tl_metamodel_filtersetting']['list']['sorting']['root'] = $this->Database->prepare('SELECT * FROM tl_metamodel_filtersetting WHERE fid=? AND pid=0')->execute($this->objFilter->id)->fetchEach('id');
        $GLOBALS['TL_DCA']['tl_metamodel_filtersetting']['list']['sorting']['rootPaste'] = true;
        if ($this->objMetaModel) {
            $GLOBALS['TL_LANG']['MSC']['editRecord'] = sprintf($GLOBALS['TL_LANG']['MSC']['metamodel_filtersetting']['editRecord'], $this->objFilter->name, $this->objMetaModel->getName());
            $GLOBALS['TL_DCA']['tl_metamodel_filtersetting']['config']['label'] = sprintf($GLOBALS['TL_LANG']['MSC']['metamodel_filtersetting']['label'], $this->objFilter->name, $this->objMetaModel->getName());
        }
    }
    /**
     * @param DataControllerCallContext $callcontext
     * @param DatasetMetaData $dataset
     * @param DatasetStorageObserver[] $observers
     * @throws Exception
     */
    protected function dropDatasetStorage(DataControllerCallContext $callcontext, DatasetMetaData $dataset, array $observers = NULL) {
        MetaModelFactory::getInstance()->startGlobalModification();
        try {
            $transaction = db_transaction();
            try {
                if (isset($observers)) {
                    foreach ($observers as $observer) {
                        $observer->unregisterDataset($callcontext, $dataset, DatasetStorageObserver::STAGE__BEFORE);
                    }
                }

                // dropping physical storage of the dataset
                $request = new DatasetStorageRequest($dataset->name);
                LogHelper::log_debug($request);
                $this->datasourceStructureHandler->dropDatasetStorage($callcontext, $request);

                $dataset->used = FALSE;

                if (isset($observers)) {
                    foreach ($observers as $observer) {
                        $observer->unregisterDataset($callcontext, $dataset, DatasetStorageObserver::STAGE__AFTER);
                    }
                }
            }
            catch (Exception $e) {
                $transaction->rollback();
                throw $e;
            }
        }
        catch (Exception $e) {
            MetaModelFactory::getInstance()->finishGlobalModification(FALSE);
            throw $e;
        }
        MetaModelFactory::getInstance()->finishGlobalModification(TRUE);
    }
    protected function update(Import\ImportStream $stream, Import\ImportContext $context) {
        $datasets = $stream->get('datasets');
        if (empty($datasets)) {
            return;
        }

        gd_datasource_set_active($context->get('datasourceName'));
        $metamodel = data_controller_get_metamodel();

        $environment_metamodel = data_controller_get_environment_metamodel();
        $datasource = $environment_metamodel->getDataSource($context->get('datasourceName'));

        foreach ( $datasets as $dataset ) {
            $existingDataset = GD_DatasetMetaModelLoaderHelper::findDatasetByUUID($metamodel->datasets, $dataset->uuid);
            if ( !$existingDataset ) {

                // map for re-linking dependent objects
                $dataset->originalName = $dataset->name;

                // create new name
                $newDatasetName = GD_NamingConvention::generateDatasetName();
                $dataset->name = $newDatasetName;
                $dataset->source = $newDatasetName;
                $dataset->datasourceName = $datasource->name;
            } else {
                // map for re-linking dependent objects
                $dataset->originalName = $dataset->name;

                $dataset->name = $existingDataset->name;
                $dataset->source = $existingDataset->source;
                $dataset->datasourceName = $existingDataset->datasourceName;
            }
        }

        // prepare dataset columns for import
        $this->prepareColumns($datasets);

        // prepares the metadata object, has to be of type RecordMetaData
        foreach ( $datasets as $key => $dataset ) {
            $metadata = new DatasetMetaData();
            $metadata->initializeFrom($dataset);
            $datasets[$key] = $metadata;
        }

        // ensure datasets are created in order to satisfy dependencies
        usort($datasets, array(new ReferencedDatasetComparator(), 'compare'));

        foreach ( $datasets as $dataset ) {
            $existingDataset = GD_DatasetMetaModelLoaderHelper::findDatasetByUUID($metamodel->datasets, $dataset->uuid);
            if ($existingDataset) {
                gd_data_controller_ddl_modify_dataset($dataset);
            } else {
                MetaModelFactory::getInstance()->startGlobalModification();
                try {
                    $transaction = db_transaction();
                    try {
                        gd_data_controller_ddl_create_dataset($dataset);
                    } catch (Exception $e) {
                        $transaction->rollback();
                        throw $e;
                    }
                } catch (Exception $e) {
                    MetaModelFactory::getInstance()->finishGlobalModification(false);
                    throw $e;
                }
                MetaModelFactory::getInstance()->finishGlobalModification(true);
            }
        }

        $stream->set('datasets',$datasets);
    }
 /**
  * Fetch all attributes from the parenting MetaModel. Called as options_callback.
  *
  * @return array
  */
 public function getAllAttributes()
 {
     $intID = $this->Input->get('id');
     $intPid = $this->Input->get('pid');
     $arrReturn = array();
     if (empty($intPid)) {
         $objResult = $this->Database->prepare('SELECT pid FROM tl_metamodel_dca WHERE id=?')->limit(1)->execute($intID);
         if ($objResult->numRows == 0) {
             return $arrReturn;
         }
         $objMetaModel = MetaModelFactory::byId($objResult->pid);
     } else {
         $objMetaModel = MetaModelFactory::byId($intPid);
     }
     foreach ($objMetaModel->getAttributes() as $objAttribute) {
         $arrReturn[$objAttribute->getColName()] = $objAttribute->getName();
     }
     return $arrReturn;
 }
 public function injectIntoBackendModules()
 {
     $arrPTables = $this->arrPTables;
     $intCount = count($arrPTables);
     // loop until all tables are injected or until there was no injection during one run.
     // This is important, as we might have models that are child of another model.
     while ($arrPTables) {
         foreach ($arrPTables as $strTable => $arrModels) {
             foreach ($GLOBALS['BE_MOD'] as $strGroup => $arrModules) {
                 foreach ($arrModules as $strModule => $arrConfig) {
                     if (isset($arrConfig['tables']) && in_array($strTable, $arrConfig['tables'])) {
                         $arrSubTables = array();
                         foreach ($arrModels as $intModel) {
                             $arrSubTables[] = MetaModelFactory::byId($intModel)->getTableName();
                         }
                         $GLOBALS['BE_MOD'][$strGroup][$strModule]['tables'] = array_merge($GLOBALS['BE_MOD'][$strGroup][$strModule]['tables'], $arrSubTables);
                         unset($arrPTables[$strTable]);
                     }
                 }
             }
         }
         if (count($arrPTables) == $intCount) {
             break;
         }
         $intCount = count($arrPTables);
     }
 }
 /**
  * Try to load the mm by id or name.
  * 
  * @param mixed $nameOrId Name or id of mm.
  * 
  * @return IMetaModel|null
  */
 protected function loadMM($nameOrId)
 {
     // ID.
     if (is_numeric($nameOrId)) {
         return MetaModelFactory::byId($nameOrId);
     } elseif (is_string($nameOrId)) {
         return MetaModelFactory::byTableName($nameOrId);
     }
     // Unknown.
     return null;
 }
 /**
  * Create the data container of a metamodel table.
  *
  * @param string $strTableName the name of the meta model table that shall be created.
  *
  * @return bool true on success, false otherwise.
  */
 public function createDataContainer($strTableName)
 {
     if (!in_array($strTableName, MetaModelFactory::getAllTables())) {
         return false;
     }
     // call the loadDataContainer from Controller.php for the base DCA.
     parent::loadDataContainer('tl_metamodel_item');
     parent::loadLanguageFile('tl_metamodel_item');
     $GLOBALS['TL_DCA'][$strTableName] = array_replace_recursive($GLOBALS['TL_DCA']['tl_metamodel_item'], (array) $GLOBALS['TL_DCA'][$strTableName]);
     $arrDCA =& $GLOBALS['TL_DCA'][$strTableName];
     $arrDCA['dca_config']['data_provider']['default']['source'] = $strTableName;
     $objMetaModel = MetaModelFactory::byTableName($strTableName);
     if ($objMetaModel->isTranslated()) {
         $this->loadLanguageFile('languages');
     }
     $arrDCASettings = MetaModelDcaBuilder::getInstance()->getDca($objMetaModel->get('id'));
     $arrViewSettings = MetaModelDcaBuilder::getInstance()->getView($objMetaModel->get('id'));
     if (!$arrDCASettings) {
         $strMessage = sprintf($GLOBALS['TL_LANG']['ERR']['no_palette'], $objMetaModel->getName(), self::getUser()->username);
         MetaModelBackendModule::addMessageEntry($strMessage, METAMODELS_ERROR, $this->addToUrl('do=metamodels&table=tl_metamodel_dca&id=' . $objMetaModel->get('id')));
         $this->log($strMessage, 'MetaModelDatabase createDataContainer()', TL_ERROR);
         return true;
     }
     if (!$arrViewSettings) {
         $strMessage = sprintf($GLOBALS['TL_LANG']['ERR']['no_view'], $objMetaModel->getName(), self::getUser()->username);
         MetaModelBackendModule::addMessageEntry($strMessage, METAMODELS_ERROR, $this->addToUrl('do=metamodels&table=tl_metamodel_rendersettings&id=' . $objMetaModel->get('id')));
         $this->log($strMessage, 'MetaModelDatabase createDataContainer()', TL_ERROR);
         return true;
     }
     $arrDCA['config']['metamodel_view'] = $arrViewSettings['id'];
     $arrDCA['palettes']['default'] = $this->getPaletteAndFields($arrDCASettings['id'], $objMetaModel, $arrDCA);
     if ($arrDCASettings['backendcaption']) {
         $arrCaptions = deserialize($arrDCASettings['backendcaption'], true);
         foreach ($arrCaptions as $arrLangEntry) {
             if ($arrLangEntry['label'] != '' && $arrLangEntry['langcode'] == $objMetaModel->getActiveLanguage()) {
                 $arrDCA['config']['label'] = $arrLangEntry['label'];
             } else {
                 if ($arrLangEntry['label'] != '' && !$arrDCA['config']['label'] && $arrLangEntry['langcode'] == $objMetaModel->getFallbackLanguage()) {
                     $arrDCA['config']['label'] = $arrLangEntry['label'];
                 }
             }
         }
     }
     if (!$arrDCA['config']['label']) {
         $arrDCA['config']['label'] = $objMetaModel->get('name');
     }
     // Check access level.
     if ($arrDCASettings['isclosed']) {
         $arrDCA['config']['closed'] = true;
         $arrDCA['config']['notDeletable'] = true;
         unset($arrDCA['list']['operations']['delete']);
     }
     // FIXME: if we have variants, we force mode 5 here, no matter what the DCA configs say.
     if ($objMetaModel->hasVariants()) {
         $this->createDataContainerWithVariants($objMetaModel, $arrDCASettings, $arrDCA);
     } else {
         $this->createDataContainerNormal($objMetaModel, $arrDCASettings, $arrDCA);
     }
     $GLOBALS['TL_LANG'][$objMetaModel->getTableName()] = array_replace_recursive($GLOBALS['TL_LANG']['tl_metamodel_item'], (array) $GLOBALS['TL_LANG'][$objMetaModel->getTableName()]);
     // TODO: add a HOOK here for extensions to manipulate the DCA. loadMetaModelDataContainer($objMetaModel)
     //$GLOBALS['METAMODEL_HOOKS']['loadDataContainer']
     return true;
 }
 protected function getFourthLevel($strTable, $strParentTable, $strIcon)
 {
     $strUrl = 'contao/main.php?do=metamodels&table=' . $strTable . '&id=' . $intCurrrentID;
     switch ($strTable) {
         case 'metamodel_dcasetting_subpalette':
             $objParent = Database::getInstance()->prepare('SELECT id, pid, name FROM tl_metamodel_attribute WHERE id=(SELECT attr_id FROM tl_metamodel_dcasetting WHERE pid=? AND id=?)')->executeUncached($this->intID, Input::getInstance()->get('subpaletteid'));
             /**
              * @var IMetaModel
              */
             $objMetaModel = MetaModelFactory::byId($objParent->pid);
             $objAttribute = $objMetaModel->getAttributeById($objParent->id);
             // Change id for next entry.
             $strName = $objAttribute->getName();
             $intCurrrentID = $this->intID;
             //$this->intID = $objParent->pid;
             $strSubfilter = 'subpaletteid=' . Input::getInstance()->get('subpaletteid');
             $strUrl = 'contao/main.php?do=metamodels&table=' . $strParentTable . '&id=' . $intCurrrentID . '&' . $strSubfilter;
             break;
     }
     return array('url' => $strUrl, 'text' => sprintf($this->getLanguage($strTable), $strName), 'icon' => !empty($strIcon) ? Environment::getInstance()->base . '/system/modules/metamodels/html/' . $strIcon : null);
 }