/**
  * Do something before content is loaded from DB
  * 
  * @param \Cx\Core\ContentManager\Model\Entity\Page $page       The resolved page
  */
 public function preContentLoad(\Cx\Core\ContentManager\Model\Entity\Page $page)
 {
     global $section;
     switch ($this->cx->getMode()) {
         case \Cx\Core\Core\Controller\Cx::MODE_FRONTEND:
             if ($section == 'JsonData') {
                 // TODO: move this code to /core/Json/...
                 // TODO: handle expired sessions in any xhr callers.
                 $json = new \Cx\Core\Json\JsonData();
                 // TODO: Verify that the arguments are actually present!
                 $adapter = contrexx_input2raw($_GET['object']);
                 $method = contrexx_input2raw($_GET['act']);
                 // TODO: Replace arguments by something reasonable
                 $arguments = array('get' => $_GET, 'post' => $_POST);
                 echo $json->jsondata($adapter, $method, $arguments);
                 die;
             }
             break;
     }
 }
    /**
     * This function returns the DataElement
     *
     * @param string $name name of the DataElement
     * @param string $type type of the DataElement
     * @param int $length length of the DataElement
     * @param mixed $value value of the DataElement
     * @param array $options options for the DataElement
     * @param int $entityId id of the DataElement
     * @return \Cx\Core\Html\Model\Entity\DataElement
     */
    public function getDataElement($name, $type, $length, $value, &$options, $entityId)
    {
        global $_ARRAYLANG, $_CORELANG;
        if (isset($options['formfield'])) {
            $formFieldGenerator = $options['formfield'];
            $formField = '';
            /* We use json to do the callback. The 'else if' is for backwards compatibility so you can declare
             * the function directly without using json. This is not recommended and not working over session */
            if (is_array($formFieldGenerator) && isset($formFieldGenerator['adapter']) && isset($formFieldGenerator['method'])) {
                $json = new \Cx\Core\Json\JsonData();
                $jsonResult = $json->data($formFieldGenerator['adapter'], $formFieldGenerator['method'], array('name' => $name, 'type' => $type, 'length' => $length, 'value' => $value, 'options' => $options));
                if ($jsonResult['status'] == 'success') {
                    $formField = $jsonResult["data"];
                }
            } else {
                if (is_callable($formFieldGenerator)) {
                    $formField = $formFieldGenerator($name, $type, $length, $value, $options);
                }
            }
            if (is_a($formField, 'Cx\\Core\\Html\\Model\\Entity\\HtmlElement')) {
                return $formField;
            } else {
                $value = $formField;
            }
        }
        if (isset($options['showDetail']) && $options['showDetail'] === false) {
            return '';
        }
        switch ($type) {
            case 'bool':
            case 'boolean':
                // yes/no checkboxes
                $fieldset = new \Cx\Core\Html\Model\Entity\HtmlElement('div');
                $inputYes = new \Cx\Core\Html\Model\Entity\DataElement($name, 'yes');
                $inputYes->setAttribute('type', 'radio');
                $inputYes->setAttribute('value', '1');
                $inputYes->setAttribute('id', 'form-' . $this->formId . '-' . $name . '_yes');
                if (isset($options['attributes'])) {
                    $inputYes->setAttributes($options['attributes']);
                }
                $fieldset->addChild($inputYes);
                $labelYes = new \Cx\Core\Html\Model\Entity\HtmlElement('label');
                $labelYes->setAttribute('for', 'form-' . $this->formId . '-' . $name . '_yes');
                $labelYes->addChild(new \Cx\Core\Html\Model\Entity\TextElement($_ARRAYLANG['TXT_YES']));
                $fieldset->addChild($labelYes);
                $inputNo = new \Cx\Core\Html\Model\Entity\DataElement($name, 'no');
                $inputNo->setAttribute('id', 'form-' . $this->formId . '-' . $name . '_no');
                $inputNo->setAttribute('type', 'radio');
                $inputNo->setAttribute('value', '0');
                if (isset($options['attributes'])) {
                    $inputNo->setAttributes($options['attributes']);
                }
                $fieldset->addChild($inputNo);
                $labelNo = new \Cx\Core\Html\Model\Entity\HtmlElement('label');
                $labelNo->setAttribute('for', 'form-' . $this->formId . '-' . $name . '_no');
                $labelNo->addChild(new \Cx\Core\Html\Model\Entity\TextElement($_ARRAYLANG['TXT_NO']));
                $fieldset->addChild($labelNo);
                if ($value) {
                    $inputYes->setAttribute('checked');
                } else {
                    $inputNo->setAttribute('checked');
                }
                return $fieldset;
                break;
            case 'int':
            case 'integer':
                // input field with type number
                $inputNumber = new \Cx\Core\Html\Model\Entity\DataElement($name, $value, \Cx\Core\Html\Model\Entity\DataElement::TYPE_INPUT, new \Cx\Core\Validate\Model\Entity\RegexValidator('/-?[0-9]*/'));
                if (isset($options['attributes'])) {
                    $inputNumber->setAttributes($options['attributes']);
                }
                $inputNumber->setAttribute('type', 'number');
                return $inputNumber;
                break;
            case 'Cx\\Model\\Base\\EntityBase':
                $associatedClass = get_class($value);
                \JS::registerJS('core/Html/View/Script/Backend.js');
                \ContrexxJavascript::getInstance()->setVariable('Form/Error', $_ARRAYLANG['TXT_CORE_HTML_FORM_VALIDATION_ERROR'], 'core/Html/lang');
                if (\Env::get('em')->getClassMetadata($this->entityClass)->isSingleValuedAssociation($name)) {
                    // this case is used to create a select field for 1 to 1 associations
                    $entities = \Env::get('em')->getRepository($associatedClass)->findAll();
                    $foreignMetaData = \Env::get('em')->getClassMetadata($associatedClass);
                    $primaryKeyName = $foreignMetaData->getSingleIdentifierFieldName();
                    $selected = $foreignMetaData->getFieldValue($value, $primaryKeyName);
                    $arrEntities = array();
                    $closeMetaData = \Env::get('em')->getClassMetadata($this->entityClass);
                    $assocMapping = $closeMetaData->getAssociationMapping($name);
                    $validator = null;
                    if (!isset($assocMapping['joinColumns'][0]['nullable']) || $assocMapping['joinColumns'][0]['nullable']) {
                        $arrEntities['NULL'] = $_ARRAYLANG['TXT_CORE_NONE'];
                    } else {
                        $validator = new \Cx\Core\Validate\Model\Entity\RegexValidator('/^(?!null$|$)/');
                    }
                    foreach ($entities as $entity) {
                        $arrEntities[\Env::get('em')->getClassMetadata($associatedClass)->getFieldValue($entity, $primaryKeyName)] = $entity;
                    }
                    $select = new \Cx\Core\Html\Model\Entity\DataElement($name, \Html::getOptions($arrEntities, $selected), \Cx\Core\Html\Model\Entity\DataElement::TYPE_SELECT, $validator);
                    if (isset($options['attributes'])) {
                        $select->setAttributes($options['attributes']);
                    }
                    return $select;
                } else {
                    // this case is used to list all existing values and show an add button for 1 to many associations
                    $closeMetaData = \Env::get('em')->getClassMetadata($this->entityClass);
                    $assocMapping = $closeMetaData->getAssociationMapping($name);
                    $mainDiv = new \Cx\Core\Html\Model\Entity\HtmlElement('div');
                    $mainDiv->setAttribute('class', 'entityList');
                    $addButton = new \Cx\Core\Html\Model\Entity\HtmlElement('input');
                    $addButton->setAttribute('type', 'button');
                    $addButton->setClass(array('form-control', 'add_' . $this->createCssClassNameFromEntity($associatedClass), 'mappedAssocciationButton'));
                    $addButton->setAttribute('value', $_CORELANG['TXT_ADD']);
                    $addButton->setAttribute('data-params', 'entityClass:' . $associatedClass . ';' . 'mappedBy:' . $assocMapping['mappedBy'] . ';' . 'cssName:' . $this->createCssClassNameFromEntity($associatedClass) . ';' . 'sessionKey:' . $this->entityClass);
                    if (!isset($_SESSION['vgOptions'])) {
                        $_SESSION['vgOptions'] = array();
                    }
                    $_SESSION['vgOptions'][$this->entityClass] = $this->componentOptions;
                    if ($entityId != 0) {
                        // if we edit the main form, we also want to show the existing associated values we already have
                        $existingValues = $this->getIdentifyingDisplayValue($assocMapping, $associatedClass, $entityId);
                    }
                    if (!empty($existingValues)) {
                        foreach ($existingValues as $existingValue) {
                            $mainDiv->addChild($existingValue);
                        }
                    }
                    $mainDiv->addChild($addButton);
                    // if standard tooltip is not disabled, we load the one to n association text
                    if (!isset($options['showstanardtooltip']) || $options['showstanardtooltip']) {
                        if (!empty($options['tooltip'])) {
                            $options['tooltip'] = $options['tooltip'] . '<br /><br /> ' . $_ARRAYLANG['TXT_CORE_RECORD_ONE_TO_N_ASSOCIATION'];
                        } else {
                            $options['tooltip'] = $_ARRAYLANG['TXT_CORE_RECORD_ONE_TO_N_ASSOCIATION'];
                        }
                    }
                    $cxjs = \ContrexxJavascript::getInstance();
                    $cxjs->setVariable('TXT_CANCEL', $_CORELANG['TXT_CANCEL'], 'Html/lang');
                    $cxjs->setVariable('TXT_SUBMIT', $_CORELANG['TXT_SUBMIT'], 'Html/lang');
                    $cxjs->setVariable('TXT_EDIT', $_CORELANG['TXT_EDIT'], 'Html/lang');
                    $cxjs->setVariable('TXT_DELETE', $_CORELANG['TXT_DELETE'], 'Html/lang');
                    return $mainDiv;
                }
                break;
            case 'Country':
                // this is for customizing only:
                $data = \Cx\Core\Country\Controller\Country::getNameById($value);
                if (empty($data)) {
                    $value = 204;
                }
                $options = \Cx\Core\Country\Controller\Country::getMenuoptions($value);
                $select = new \Cx\Core\Html\Model\Entity\DataElement($name, $options, \Cx\Core\Html\Model\Entity\DataElement::TYPE_SELECT);
                if (isset($options['attributes'])) {
                    $select->setAttributes($options['attributes']);
                }
                return $select;
                break;
            case 'DateTime':
            case 'datetime':
            case 'date':
                // input field with type text and class datepicker
                if ($value instanceof \DateTime) {
                    $value = $value->format(ASCMS_DATE_FORMAT);
                }
                if (is_null($value)) {
                    $value = '';
                }
                $input = new \Cx\Core\Html\Model\Entity\DataElement($name, $value);
                $input->setAttribute('type', 'text');
                $input->setAttribute('class', 'datepicker');
                if (isset($options['readonly']) && $options['readonly']) {
                    $input->setAttribute('disabled');
                }
                if (isset($options['attributes'])) {
                    $input->setAttributes($options['attributes']);
                }
                \DateTimeTools::addDatepickerJs();
                \JS::registerCode('
                        cx.jQuery(function() {
                          cx.jQuery(".datepicker").datetimepicker();
                        });
                        ');
                return $input;
                break;
            case 'multiselect':
            case 'select':
                $values = array();
                if (isset($options['validValues'])) {
                    if (is_array($options['validValues'])) {
                        $values = $options['validValues'];
                    } else {
                        $values = explode(',', $options['validValues']);
                        $values = array_combine($values, $values);
                    }
                }
                if ($type == 'multiselect') {
                    $value = explode(',', $value);
                    $value = array_combine($value, $value);
                }
                $selectOptions = \Html::getOptions($values, $value);
                $select = new \Cx\Core\Html\Model\Entity\DataElement($name, $selectOptions, \Cx\Core\Html\Model\Entity\DataElement::TYPE_SELECT);
                if ($type == 'multiselect') {
                    $select->setAttribute('multiple');
                }
                if (isset($options['attributes'])) {
                    $select->setAttributes($options['attributes']);
                }
                return $select;
                break;
            case 'slider':
                // this code should not be here
                // create sorrounding div
                $element = new \Cx\Core\Html\Model\Entity\HtmlElement('div');
                // create div for slider
                $slider = new \Cx\Core\Html\Model\Entity\HtmlElement('div');
                $slider->setAttribute('class', 'slider');
                $element->addChild($slider);
                // create hidden input for slider value
                $input = new \Cx\Core\Html\Model\Entity\DataElement($name, $value + 0, \Cx\Core\Html\Model\Entity\DataElement::TYPE_INPUT);
                $input->setAttribute('type', 'hidden');
                if (isset($options['attributes'])) {
                    $input->setAttributes($options['attributes']);
                }
                $element->addChild($input);
                // add javascript to update input value
                $min = 0;
                $max = 10;
                if (isset($options['validValues'])) {
                    $values = explode(',', $options['validValues']);
                    $min = $values[0];
                    if (isset($values[1])) {
                        $max = $values[1];
                    }
                }
                if (!isset($value)) {
                    $value = 0;
                }
                $script = new \Cx\Core\Html\Model\Entity\HtmlElement('script');
                $script->addChild(new \Cx\Core\Html\Model\Entity\TextElement('
                    cx.jQuery("#form-' . $this->formId . '-' . $name . ' .slider").slider({
                        value: ' . ($value + 0) . ',
                        min: ' . ($min + 0) . ',
                        max: ' . ($max + 0) . ',
                        slide: function( event, ui ) {
                            cx.jQuery("input[name=' . $name . ']").val(ui.value);
                            cx.jQuery("input[name=' . $name . ']").change();
                        }
                    });
                '));
                $element->addChild($script);
                return $element;
                break;
            case 'checkboxes':
                $dataElementGroupType = \Cx\Core\Html\Model\Entity\DataElementGroup::TYPE_CHECKBOX;
            case 'radio':
                $values = array();
                if (isset($options['validValues'])) {
                    $values = explode(',', $options['validValues']);
                    $values = array_combine($values, $values);
                }
                if (!isset($dataElementGroupType)) {
                    $dataElementGroupType = \Cx\Core\Html\Model\Entity\DataElementGroup::TYPE_RADIO;
                }
                $radio = new \Cx\Core\Html\Model\Entity\DataElementGroup($name, $values, $value, $dataElementGroupType);
                if (isset($options['attributes'])) {
                    $radio->setAttributes($options['attributes']);
                }
                return $radio;
                break;
            case 'text':
                // textarea
                $textarea = new \Cx\Core\Html\Model\Entity\HtmlElement('textarea');
                $textarea->setAttribute('name', $name);
                if (isset($options['readonly']) && $options['readonly']) {
                    $textarea->setAttribute('disabled');
                }
                $textarea->addChild(new \Cx\Core\Html\Model\Entity\TextElement($value));
                if (isset($options['attributes'])) {
                    $textarea->setAttributes($options['attributes']);
                }
                return $textarea;
                break;
            case 'phone':
                // input field with type phone
                $input = new \Cx\Core\Html\Model\Entity\DataElement($name, $value);
                $input->setAttribute('type', 'phone');
                if (isset($options['readonly']) && $options['readonly']) {
                    $input->setAttribute('disabled');
                }
                if (isset($options['attributes'])) {
                    $input->setAttributes($options['attributes']);
                }
                return $input;
                break;
            case 'mail':
                // input field with type mail
                $emailValidator = new \Cx\Core\Validate\Model\Entity\EmailValidator();
                $input = new \Cx\Core\Html\Model\Entity\DataElement($name, $value, 'input', $emailValidator);
                $input->setAttribute('onkeyup', $emailValidator->getJavaScriptCode());
                $input->setAttribute('type', 'mail');
                if (isset($options['attributes'])) {
                    $input->setAttributes($options['attributes']);
                }
                if (isset($options['readonly']) && $options['readonly']) {
                    $input->setAttribute('disabled');
                }
                return $input;
                break;
            case 'uploader':
                \JS::registerCode('
                    function javascript_callback_function(data) {
                        if(data.type=="file") {
                                cx.jQuery("#' . $name . '").val(data.data[0].datainfo.filepath);
                        }
                    }

                ');
                $mediaBrowser = new \Cx\Core_Modules\MediaBrowser\Model\Entity\MediaBrowser();
                $mediaBrowser->setOptions(array('type' => 'button'));
                $mediaBrowser->setCallback('javascript_callback_function');
                $mediaBrowser->setOptions(array('data-cx-mb-views' => 'filebrowser,uploader', 'id' => 'page_target_browse', 'cxMbStartview' => 'MediaBrowserList'));
                $input = new \Cx\Core\Html\Model\Entity\DataElement($name, $value);
                $input->setAttribute('type', 'text');
                $input->setAttribute('id', $name);
                $div = new \Cx\Core\Html\Model\Entity\HtmlElement('div');
                $div->addChild($input);
                $div->addChild(new \Cx\Core\Html\Model\Entity\TextElement($mb = $mediaBrowser->getXHtml($_ARRAYLANG['TXT_CORE_CM_BROWSE'])));
                return $div;
                break;
            case 'image':
                \JS::registerCode('
                    function javascript_callback_function(data) {
                        if ( data.data[0].datainfo.extension=="Jpg"
                            || data.data[0].datainfo.extension=="Gif"
                            || data.data[0].datainfo.extension=="Png"
                        ) {
                            cx.jQuery("#' . $name . '").attr(\'value\', data.data[0].datainfo.filepath);
                            cx.jQuery("#' . $name . '").prevAll(\'.deletePreviewImage\').first().css(\'display\', \'inline-block\');
                            cx.jQuery("#' . $name . '").prevAll(\'.previewImage\').first().attr(\'src\', data.data[0].datainfo.filepath);
                        }
                    }

                    jQuery(document).ready(function(){
                        jQuery(\'.deletePreviewImage\').click(function(){
                            cx.jQuery("#' . $name . '").attr(\'value\', \'\');
                            cx.jQuery(this).prev(\'img\').attr(\'src\', \'/images/Downloads/no_picture.gif\');
                            cx.jQuery(this).css(\'display\', \'none\');
                            cx.jQuery(this).nextAll(\'input\').first().attr(\'value\', \'\');
                        });
                    });

                ');
                $mediaBrowser = new \Cx\Core_Modules\MediaBrowser\Model\Entity\MediaBrowser();
                $mediaBrowser->setOptions(array('type' => 'button'));
                $mediaBrowser->setCallback('javascript_callback_function');
                $defaultOptions = array('data-cx-mb-views' => 'filebrowser,uploader', 'id' => 'page_target_browse', 'cxMbStartview' => 'MediaBrowserList');
                $mediaBrowser->setOptions(is_array($options['options']) ? array_merge($defaultOptions, $options['options']) : $defaultOptions);
                // create hidden input to save image
                $input = new \Cx\Core\Html\Model\Entity\DataElement($name, $value);
                $input->setAttribute('type', 'hidden');
                $input->setAttribute('id', $name);
                $div = new \Cx\Core\Html\Model\Entity\HtmlElement('div');
                if (isset($value) && in_array(pathinfo($value, PATHINFO_EXTENSION), array('gif', 'jpg', 'png')) || $name == 'imagePath') {
                    // this image is meant to be a preview of the selected image
                    $previewImage = new \Cx\Core\Html\Model\Entity\HtmlElement('img');
                    $previewImage->setAttribute('class', 'previewImage');
                    $previewImage->setAttribute('src', $value != '' ? $value : '/images/Downloads/no_picture.gif');
                    // this image is uesd as delete function for the selected image over javascript
                    $deleteImage = new \Cx\Core\Html\Model\Entity\HtmlElement('img');
                    $deleteImage->setAttribute('class', 'deletePreviewImage');
                    $deleteImage->setAttribute('src', '/core/Core/View/Media/icons/delete.gif');
                    $div->addChild($previewImage);
                    $div->addChild($deleteImage);
                    $div->addChild(new \Cx\Core\Html\Model\Entity\HtmlElement('br'));
                }
                $div->addChild($input);
                $div->addChild(new \Cx\Core\Html\Model\Entity\TextElement($mediaBrowser->getXHtml($_ARRAYLANG['TXT_CORE_CM_BROWSE'])));
                return $div;
                break;
            case 'sourcecode':
                //set mode
                $mode = 'html';
                if (isset($options['options']['mode'])) {
                    switch ($options['options']['mode']) {
                        case 'js':
                            $mode = 'javascript';
                            break;
                        case 'yml':
                        case 'yaml':
                            $mode = 'yaml';
                            break;
                    }
                }
                //define textarea
                $textarea = new \Cx\Core\Html\Model\Entity\HtmlElement('textarea');
                $textarea->setAttribute('name', $name);
                $textarea->setAttribute('id', $name);
                $textarea->setAttribute('style', 'display:none;');
                $textarea->addChild(new \Cx\Core\Html\Model\Entity\TextElement($value));
                //define pre
                $pre = new \Cx\Core\Html\Model\Entity\HtmlElement('pre');
                $pre->setAttribute('id', 'editor-' . $name);
                $pre->addChild(new \Cx\Core\Html\Model\Entity\TextElement(contrexx_raw2xhtml($value)));
                //set readonly if necessary
                $readonly = '';
                if (isset($options['readonly']) && $options['readonly']) {
                    $readonly = 'editor.setReadOnly(true);';
                    $textarea->setAttribute('disabled');
                }
                //create div and add all stuff
                $div = new \Cx\Core\Html\Model\Entity\HtmlElement('div');
                //     required for the Ace editor to work. Otherwise
                //     it won't be visible as the DIV does have a width of 0px.
                $div->setAttribute('style', 'display:block;');
                $div->addChild($textarea);
                $div->addChild($pre);
                //register js
                $jsCode = <<<CODE
var editor;
\$J(function(){
if (\$J("#editor-{$name}").length) {
    editor = ace.edit("editor-{$name}");
    editor.getSession().setMode("ace/mode/{$mode}");
    editor.setShowPrintMargin(false);
    editor.focus();
    editor.gotoLine(1);
    {$readonly}
}

\$J('form').submit(function(){
    \$J('#{$name}').val(editor.getSession().getValue());
});

});
CODE;
                \JS::activate('ace');
                \JS::registerCode($jsCode);
                return $div;
                break;
            case 'string':
            case 'hidden':
            default:
                // convert NULL to empty string
                if (is_null($value)) {
                    $value = '';
                }
                // input field with type text
                $input = new \Cx\Core\Html\Model\Entity\DataElement($name, $value);
                if (isset($options['validValues'])) {
                    $input->setValidator(new \Cx\Core\Validate\Model\Entity\RegexValidator('/^' . $options['validValues'] . '$/'));
                }
                if ($type == 'hidden') {
                    $input->setAttribute('type', 'hidden');
                } else {
                    $input->setAttribute('type', 'text');
                    $input->setClass('form-control');
                }
                if (isset($options['readonly']) && $options['readonly']) {
                    $input->setAttribute('disabled');
                }
                if (isset($options['attributes'])) {
                    $input->setAttributes($options['attributes']);
                }
                return $input;
                break;
        }
    }
 /**
  * This function will render the form for a given entry by id. If id is null, an empty form will be loaded
  *
  * @access protected
  * @param int $entityId id of the entity
  * @return string rendered view
  */
 protected function renderFormForEntry($entityId)
 {
     global $_CORELANG;
     $renderArray = array('vg_increment_number' => $this->viewId);
     if (!isset($this->options['fields'])) {
         $this->options['fields'] = array();
     }
     $this->options['fields']['vg_increment_number'] = array('type' => 'hidden');
     // the title is used for the heading. For example the heading in edit mode will be "edit [$entityTitle]"
     $entityTitle = isset($this->options['entityName']) ? $this->options['entityName'] : $_CORELANG['TXT_CORE_ENTITY'];
     // get the class name including the whole namspace of the class
     if ($this->object instanceof \Cx\Core_Modules\Listing\Model\Entity\DataSet) {
         $entityClassWithNS = $this->object->getDataType();
     } else {
         $entityClassWithNS = get_class($this->object);
     }
     $entityObject = \Env::get('em')->getClassMetadata($entityClassWithNS);
     $primaryKeyNames = $entityObject->getIdentifierFieldNames();
     // get the name of primary key in database table
     if ($entityId == 0 && !empty($this->options['functions']['add'])) {
         // load add entry form
         $this->setProperCancelUrl('add');
         $actionUrl = clone \Env::get('cx')->getRequest()->getUrl();
         $actionUrl->setParam('add', 1);
         $title = sprintf($_CORELANG['TXT_CORE_ADD_ENTITY'], $entityTitle);
         $entityColumnNames = $entityObject->getColumnNames();
         // get all database field names
         if (empty($entityColumnNames)) {
             return false;
         }
         foreach ($entityColumnNames as $column) {
             $field = $entityObject->getFieldName($column);
             if (in_array($field, $primaryKeyNames)) {
                 continue;
             }
             $fieldDefinition = $entityObject->getFieldMapping($field);
             $this->options[$field]['type'] = $fieldDefinition['type'];
             if ($entityObject->getFieldValue($this->object, $field) !== null) {
                 $renderArray[$field] = $entityObject->getFieldValue($this->object, $field);
                 continue;
             }
             $renderArray[$field] = '';
         }
         // load single-valued-associations
         $associationMappings = \Env::get('em')->getClassMetadata($entityClassWithNS)->getAssociationMappings();
         $classMethods = get_class_methods($entityObject->newInstance());
         foreach ($associationMappings as $field => $associationMapping) {
             if (\Env::get('em')->getClassMetadata($entityClassWithNS)->isSingleValuedAssociation($field) && in_array('set' . ucfirst($field), $classMethods)) {
                 if ($entityObject->getFieldValue($this->object, $field)) {
                     $renderArray[$field] = $entityObject->getFieldValue($this->object, $field);
                     continue;
                 }
                 $renderArray[$field] = new $associationMapping['targetEntity']();
             } elseif (\Env::get('em')->getClassMetadata($entityClassWithNS)->isCollectionValuedAssociation($field)) {
                 $renderArray[$field] = new $associationMapping['targetEntity']();
             }
         }
     } elseif ($entityId != 0 && $this->object->entryExists($entityId)) {
         // load edit entry form
         $this->setProperCancelUrl('editid');
         $actionUrl = clone \Env::get('cx')->getRequest()->getUrl();
         $actionUrl->setParam('editid', null);
         $title = sprintf($_CORELANG['TXT_CORE_EDIT_ENTITY'], $entityTitle);
         // get data of all fields of the entry, except associated fields
         $renderObject = $this->object->getEntry($entityId);
         if (empty($renderObject)) {
             return false;
         }
         // get doctrine field name, database field name and type for each field
         foreach ($renderObject as $name => $value) {
             if ($name == 'virtual' || in_array($name, $primaryKeyNames)) {
                 continue;
             }
             $fieldDefinition['type'] = null;
             if (!\Env::get('em')->getClassMetadata($entityClassWithNS)->hasAssociation($name)) {
                 $fieldDefinition = $entityObject->getFieldMapping($name);
             }
             $this->options[$name]['type'] = $fieldDefinition['type'];
             $renderArray[$name] = $value;
         }
         // load single-valued-associations
         // this is used for those object fields that are associations, but no object has been assigned to yet
         $associationMappings = \Env::get('em')->getClassMetadata($entityClassWithNS)->getAssociationMappings();
         $classMethods = get_class_methods($entityObject->newInstance());
         foreach ($associationMappings as $field => $associationMapping) {
             if (!empty($renderArray[$field])) {
                 if (\Env::get('em')->getClassMetadata($entityClassWithNS)->isCollectionValuedAssociation($field)) {
                     $renderArray[$field] = new $associationMapping['targetEntity']();
                 }
             } elseif (\Env::get('em')->getClassMetadata($entityClassWithNS)->isSingleValuedAssociation($field) && in_array('set' . ucfirst($field), $classMethods)) {
                 $renderArray[$field] = new $associationMapping['targetEntity']();
             }
         }
     } else {
         //var_dump($entityId);
         //var_dump($this->options['functions']['add']);
         //var_dump($this->object->entryExists($entityId));
         throw new ViewGeneratorException('Tried to show form but neither add nor edit view can be shown');
     }
     //sets the order of the fields
     if (!empty($this->options['order']['form'])) {
         $sortedData = array();
         foreach ($this->options['order']['form'] as $orderVal) {
             if (array_key_exists($orderVal, $renderArray)) {
                 $sortedData[$orderVal] = $renderArray[$orderVal];
             }
         }
         $renderArray = array_merge($sortedData, $renderArray);
     }
     $this->formGenerator = new FormGenerator($renderArray, $actionUrl, $entityClassWithNS, $title, $this->options, $entityId, $this->componentOptions);
     // This should be moved to FormGenerator as soon as FormGenerator
     // gets the real entity instead of $renderArray
     $additionalContent = '';
     if (isset($this->options['preRenderDetail'])) {
         $preRender = $this->options['preRenderDetail'];
         /* We use json to do preRender the detail. The 'else if' is for backwards compatibility so you can declare
          * the function directly without using json. This is not recommended and not working over session */
         if (isset($preRender) && is_array($preRender) && isset($preRender['adapter']) && isset($preRender['method'])) {
             $json = new \Cx\Core\Json\JsonData();
             $jsonResult = $json->data($preRender['adapter'], $preRender['method'], array('viewGenerator' => $this, 'formGenerator' => $this->formGenerator, 'entityId' => $entityId));
             if ($jsonResult['status'] == 'success') {
                 $additionalContent .= $jsonResult["data"];
             }
         } else {
             if (is_callable($preRender)) {
                 $additionalContent = $preRender($this, $this->formGenerator, $entityId);
             }
         }
     }
     return $this->formGenerator . $additionalContent;
 }
 /**
  * Shows all files / pages in filebrowser
  */
 function _setContent()
 {
     global $_FRONTEND_LANGID;
     $this->_objTpl->addBlockfile('FILEBROWSER_CONTENT', 'fileBrowser_content', 'module_fileBrowser_content.html');
     $ckEditorFuncNum = isset($_GET['CKEditorFuncNum']) ? '&amp;CKEditorFuncNum=' . contrexx_raw2xhtml($_GET['CKEditorFuncNum']) : '';
     $ckEditor = isset($_GET['CKEditor']) ? '&amp;CKEditor=' . contrexx_raw2xhtml($_GET['CKEditor']) : '';
     $rowNr = 0;
     switch ($this->_mediaType) {
         case 'webpages':
             $jd = new \Cx\Core\Json\JsonData();
             $data = $jd->data('node', 'getTree', array('get' => array('recursive' => 'true')));
             $pageStack = array();
             $ref = 0;
             $data['data']['tree'] = array_reverse($data['data']['tree']);
             foreach ($data['data']['tree'] as &$entry) {
                 $entry['attr']['level'] = 0;
                 array_push($pageStack, $entry);
             }
             while (count($pageStack)) {
                 $entry = array_pop($pageStack);
                 $page = $entry['data'][0];
                 $arrPage['level'] = $entry['attr']['level'];
                 $arrPage['node_id'] = $entry['attr']['rel_id'];
                 $children = $entry['children'];
                 $children = array_reverse($children);
                 foreach ($children as &$entry) {
                     $entry['attr']['level'] = $arrPage['level'] + 1;
                     array_push($pageStack, $entry);
                 }
                 $arrPage['catname'] = $page['title'];
                 $arrPage['catid'] = $page['attr']['id'];
                 $arrPage['lang'] = BACKEND_LANG_ID;
                 $arrPage['protected'] = $page['attr']['protected'];
                 $arrPage['type'] = \Cx\Core\ContentManager\Model\Entity\Page::TYPE_CONTENT;
                 $arrPage['alias'] = $page['title'];
                 $arrPage['frontend_access_id'] = $page['attr']['frontend_access_id'];
                 $arrPage['backend_access_id'] = $page['attr']['backend_access_id'];
                 // JsonNode does not provide those
                 //$arrPage['level'] = ;
                 //$arrPage['type'] = ;
                 //$arrPage['parcat'] = ;
                 //$arrPage['displaystatus'] = ;
                 //$arrPage['moduleid'] = ;
                 //$arrPage['startdate'] = ;
                 //$arrPage['enddate'] = ;
                 // But we can simulate level and type for our purposes: (level above)
                 $jsondata = json_decode($page['attr']['data-href']);
                 $path = $jsondata->path;
                 if (trim($jsondata->module) != '') {
                     $arrPage['type'] = \Cx\Core\ContentManager\Model\Entity\Page::TYPE_APPLICATION;
                     $module = explode(' ', $jsondata->module, 2);
                     $arrPage['modulename'] = $module[0];
                     if (count($module) > 1) {
                         $arrPage['cmd'] = $module[1];
                     }
                 }
                 $url = "'" . '[[' . \Cx\Core\ContentManager\Model\Entity\Page::PLACEHOLDER_PREFIX;
                 // TODO: This only works for regular application pages. Pages of type fallback that are linked to an application
                 //       will be parsed using their node-id ({NODE_<ID>})
                 if ($arrPage['type'] == \Cx\Core\ContentManager\Model\Entity\Page::TYPE_APPLICATION && $this->_mediaMode !== 'alias') {
                     $url .= $arrPage['modulename'];
                     if (!empty($arrPage['cmd'])) {
                         $url .= '_' . $arrPage['cmd'];
                     }
                     $url = strtoupper($url);
                 } else {
                     $url .= $arrPage['node_id'];
                 }
                 // if language != current language or $alwaysReturnLanguage
                 if ($this->_frontendLanguageId != $_FRONTEND_LANGID || isset($_GET['alwaysReturnLanguage']) && $_GET['alwaysReturnLanguage'] == 'true') {
                     $url .= '_' . $this->_frontendLanguageId;
                 }
                 $url .= "]]'";
                 $this->_objTpl->setVariable(array('FILEBROWSER_ROW_CLASS' => $rowNr % 2 == 0 ? "row1" : "row2", 'FILEBROWSER_FILE_PATH_CLICK' => "javascript:{setUrl({$url},null,null,'" . \FWLanguage::getLanguageCodeById($this->_frontendLanguageId) . $path . "','page')}", 'FILEBROWSER_FILE_NAME' => $arrPage['catname'], 'FILEBROWSER_FILESIZE' => '&nbsp;', 'FILEBROWSER_FILE_ICON' => $this->_iconPath . 'htm.png', 'FILEBROWSER_FILE_DIMENSION' => '&nbsp;', 'FILEBROWSER_SPACING_STYLE' => 'style="margin-left: ' . $arrPage['level'] * 15 . 'px;"'));
                 $this->_objTpl->parse('content_files');
                 $rowNr++;
             }
             break;
         case 'Media1':
         case 'Media2':
         case 'Media3':
         case 'Media4':
             \Permission::checkAccess(7, 'static');
             //Access Media-Archive
             \Permission::checkAccess(38, 'static');
             //Edit Media-Files
             \Permission::checkAccess(39, 'static');
             //Upload Media-Files
             //Hier soll wirklich kein break stehen! Beabsichtig!
         //Upload Media-Files
         //Hier soll wirklich kein break stehen! Beabsichtig!
         default:
             if (count($this->_arrDirectories) > 0) {
                 foreach ($this->_arrDirectories as $arrDirectory) {
                     $this->_objTpl->setVariable(array('FILEBROWSER_ROW_CLASS' => $rowNr % 2 == 0 ? "row1" : "row2", 'FILEBROWSER_FILE_PATH_CLICK' => "index.php?cmd=FileBrowser&amp;standalone=true&amp;langId={$this->_frontendLanguageId}&amp;type={$this->_mediaType}&amp;path={$arrDirectory['path']}" . $ckEditor . $ckEditorFuncNum, 'FILEBROWSER_FILE_NAME' => $arrDirectory['name'], 'FILEBROWSER_FILESIZE' => '&nbsp;', 'FILEBROWSER_FILE_ICON' => $arrDirectory['icon'], 'FILEBROWSER_FILE_DIMENSION' => '&nbsp;'));
                     $this->_objTpl->parse('content_files');
                     $rowNr++;
                 }
             }
             if (count($this->_arrFiles) > 0) {
                 $arrEscapedPaths = array();
                 foreach ($this->_arrFiles as $arrFile) {
                     $arrEscapedPaths[] = contrexx_raw2encodedUrl($arrFile['path']);
                     $this->_objTpl->setVariable(array('FILEBROWSER_ROW_CLASS' => $rowNr % 2 == 0 ? "row1" : "row2", 'FILEBROWSER_ROW_STYLE' => in_array($arrFile['name'], $this->highlightedFiles) ? ' style="background: ' . $this->highlightColor . ';"' : '', 'FILEBROWSER_FILE_PATH_DBLCLICK' => "setUrl('" . contrexx_raw2xhtml($arrFile['path']) . "'," . $arrFile['width'] . "," . $arrFile['height'] . ",'')", 'FILEBROWSER_FILE_PATH_CLICK' => "javascript:{showPreview(" . (count($arrEscapedPaths) - 1) . "," . $arrFile['width'] . "," . $arrFile['height'] . ")}", 'FILEBROWSER_FILE_NAME' => contrexx_stripslashes($arrFile['name']), 'FILEBROWSER_FILESIZE' => $arrFile['size'] . ' KB', 'FILEBROWSER_FILE_ICON' => $arrFile['icon'], 'FILEBROWSER_FILE_DIMENSION' => empty($arrFile['width']) && empty($arrFile['height']) ? '' : intval($arrFile['width']) . 'x' . intval($arrFile['height'])));
                     $this->_objTpl->parse('content_files');
                     $rowNr++;
                 }
                 $this->_objTpl->setVariable('FILEBROWSER_FILES_JS', "'" . implode("','", $arrEscapedPaths) . "'");
             }
             if (array_key_exists($this->_mediaType, $this->mediaTypePaths)) {
                 $this->_objTpl->setVariable('FILEBROWSER_IMAGE_PATH', $this->mediaTypePaths[$this->_mediaType][1]);
             } else {
                 $this->_objTpl->setVariable('FILEBROWSER_IMAGE_PATH', ASCMS_CONTENT_IMAGE_WEB_PATH);
             }
             break;
     }
     $this->_objTpl->parse('fileBrowser_content');
 }
 /**
  * Returns the content of the API response for an API URL
  * This gets data internally and does not do a HTTP request!
  * @param string $url API URL
  * @return string API content or empty string
  */
 protected function getApiResponseForUrl($url)
 {
     // Initialize only when needed, we need DB for this!
     if (empty($this->apiUrlString)) {
         $this->apiUrlString = substr(\Cx\Core\Routing\Url::fromApi('', array(), array()), 0, -1);
     }
     $query = parse_url($url, PHP_URL_QUERY);
     $path = parse_url($url, PHP_URL_PATH);
     $params = array();
     parse_str($query, $params);
     $pathParts = explode('/', str_replace($this->apiUrlString, '', $path));
     if (count($pathParts) != 4 || $pathParts[0] != 'Data' || $pathParts[1] != 'Plain') {
         return '';
     }
     $adapter = contrexx_input2raw($pathParts[2]);
     $method = contrexx_input2raw($pathParts[3]);
     unset($params['cmd']);
     unset($params['object']);
     unset($params['act']);
     $arguments = array('get' => contrexx_input2raw($params));
     $json = new \Cx\Core\Json\JsonData();
     $response = $json->data($adapter, $method, $arguments);
     if (!isset($response['status']) || $response['status'] != 'success' || !isset($response['data']) || !isset($response['data']['content'])) {
         return '';
     }
     return $response['data']['content'];
 }
 protected function actRenderCM()
 {
     global $_ARRAYLANG, $_CORELANG, $_CONFIG;
     \JS::activate('jqueryui');
     \JS::activate('cx');
     \JS::activate('ckeditor');
     \JS::activate('cx-form');
     \JS::activate('jstree');
     \JS::registerJS('lib/javascript/lock.js');
     \JS::registerJS('lib/javascript/jquery/jquery.history.max.js');
     // this can be used to debug the tree, just add &tree=verify or &tree=fix
     $tree = null;
     if (isset($_GET['tree'])) {
         $tree = contrexx_input2raw($_GET['tree']);
     }
     if ($tree == 'verify') {
         echo '<pre>';
         print_r($this->nodeRepository->verify());
         echo '</pre>';
     } else {
         if ($tree == 'fix') {
             // this should print "bool(true)"
             var_dump($this->nodeRepository->recover());
         }
     }
     $objCx = \ContrexxJavascript::getInstance();
     $themeRepo = new \Cx\Core\View\Model\Repository\ThemeRepository();
     $defaultTheme = $themeRepo->getDefaultTheme();
     $objCx->setVariable('themeId', $defaultTheme->getId(), 'contentmanager/theme');
     foreach ($themeRepo->findAll() as $theme) {
         if ($theme == $defaultTheme) {
             $objCx->setVariable('themeName', $theme->getFoldername(), 'contentmanager/theme');
         }
     }
     $this->template->addBlockfile('ADMIN_CONTENT', 'content_manager', 'Skeleton.html');
     // user has no permission to create new page, hide navigation item in admin navigation
     if (!\Permission::checkAccess(127, 'static', true)) {
         $this->template->hideBlock('content_manager_create_new_page_navigation_item');
     }
     $this->template->touchBlock('content_manager');
     $this->template->addBlockfile('CONTENT_MANAGER_MEAT', 'content_manager_meat', 'Page.html');
     $this->template->touchBlock('content_manager_meat');
     if (\Permission::checkAccess(78, 'static', true)) {
         \JS::registerCode("var publishAllowed = true;");
     } else {
         \JS::registerCode("var publishAllowed = false;");
     }
     if (\Permission::checkAccess(78, 'static', true) && \Permission::checkAccess(115, 'static', true)) {
         \JS::registerCode("var aliasManagementAllowed = true;");
         $alias_permission = "block";
         $alias_denial = "none !important";
     } else {
         \JS::registerCode("var aliasManagementAllowed = false;");
         $alias_permission = "none !important";
         $alias_denial = "block";
     }
     $mediaBrowser = new MediaBrowser();
     $mediaBrowser->setCallback('target_page_callback');
     $mediaBrowser->setOptions(array('type' => 'button', 'data-cx-mb-views' => 'sitestructure', 'id' => 'page_target_browse'));
     $mediaBrowserCkeditor = new MediaBrowser();
     $mediaBrowserCkeditor->setCallback('ckeditor_image_callback');
     $mediaBrowserCkeditor->setOptions(array('id' => 'ckeditor_image_button', 'type' => 'button', 'style' => 'display:none'));
     $this->template->setVariable(array('MEDIABROWSER_BUTTON' => $mediaBrowser->getXHtml($_ARRAYLANG['TXT_CORE_CM_BROWSE']), 'MEDIABROWSER_BUTTON_CKEDITOR' => $mediaBrowserCkeditor->getXHtml($_ARRAYLANG['TXT_CORE_CM_BROWSE'])));
     $this->template->setVariable(array('ALIAS_PERMISSION' => $alias_permission, 'ALIAS_DENIAL' => $alias_denial, 'CONTREXX_BASE_URL' => ASCMS_PROTOCOL . '://' . $_CONFIG['domainUrl'] . ASCMS_PATH_OFFSET . '/', 'CONTREXX_LANG' => \FWLanguage::getLanguageCodeById(BACKEND_LANG_ID)));
     global $_CORELANG;
     $this->template->setVariable($_CORELANG);
     $objCx->setVariable('TXT_CORE_CM_VIEW', $_CORELANG['TXT_CORE_CM_VIEW'], 'contentmanager/lang');
     $objCx->setVariable('TXT_CORE_CM_ACTIONS', $_CORELANG['TXT_CORE_CM_ACTIONS'], 'contentmanager/lang');
     $objCx->setVariable('TXT_CORE_CM_VALIDATION_FAIL', $_CORELANG['TXT_CORE_CM_VALIDATION_FAIL'], 'contentmanager/lang');
     $objCx->setVariable('TXT_CORE_CM_HOME_FAIL', $_CORELANG['TXT_CORE_CM_HOME_FAIL'], 'contentmanager/lang');
     $arrLangVars = array('actions' => array('new' => 'TXT_CORE_CM_ACTION_NEW', 'copy' => 'TXT_CORE_CM_ACTION_COPY', 'activate' => 'TXT_CORE_CM_ACTION_PUBLISH', 'deactivate' => 'TXT_CORE_CM_ACTION_UNPUBLISH', 'publish' => 'TXT_CORE_CM_ACTION_PUBLISH_DRAFT', 'show' => 'TXT_CORE_CM_ACTION_SHOW', 'hide' => 'TXT_CORE_CM_ACTION_HIDE', 'delete' => 'TXT_CORE_CM_ACTION_DELETE', 'recursiveQuestion' => 'TXT_CORE_CM_RECURSIVE_QUESTION'), 'tooltip' => array('TXT_CORE_CM_LAST_MODIFIED' => 'TXT_CORE_CM_LAST_MODIFIED', 'TXT_CORE_CM_PUBLISHING_INFO_STATUSES' => 'TXT_CORE_CM_PUBLISHING_INFO_STATUSES', 'TXT_CORE_CM_PUBLISHING_INFO_ACTION_ACTIVATE' => 'TXT_CORE_CM_PUBLISHING_INFO_ACTION_ACTIVATE', 'TXT_CORE_CM_PUBLISHING_INFO_ACTION_DEACTIVATE' => 'TXT_CORE_CM_PUBLISHING_INFO_ACTION_DEACTIVATE', 'TXT_CORE_CM_PUBLISHING_DRAFT' => 'TXT_CORE_CM_PUBLISHING_DRAFT', 'TXT_CORE_CM_PUBLISHING_DRAFT_WAITING' => 'TXT_CORE_CM_PUBLISHING_DRAFT_WAITING', 'TXT_CORE_CM_PUBLISHING_LOCKED' => 'TXT_CORE_CM_PUBLISHING_LOCKED', 'TXT_CORE_CM_PUBLISHING_PUBLISHED' => 'TXT_CORE_CM_PUBLISHING_PUBLISHED', 'TXT_CORE_CM_PUBLISHING_UNPUBLISHED' => 'TXT_CORE_CM_PUBLISHING_UNPUBLISHED', 'TXT_CORE_CM_PAGE_INFO_STATUSES' => 'TXT_CORE_CM_PAGE_INFO_STATUSES', 'TXT_CORE_CM_PUBLISHING_INFO_TYPES' => 'TXT_CORE_CM_PUBLISHING_INFO_TYPES', 'TXT_CORE_CM_PAGE_INFO_ACTION_SHOW' => 'TXT_CORE_CM_PAGE_INFO_ACTION_SHOW', 'TXT_CORE_CM_PAGE_INFO_ACTION_HIDE' => 'TXT_CORE_CM_PAGE_INFO_ACTION_HIDE', 'TXT_CORE_CM_PAGE_STATUS_BROKEN' => 'TXT_CORE_CM_PAGE_STATUS_BROKEN', 'TXT_CORE_CM_PAGE_STATUS_VISIBLE' => 'TXT_CORE_CM_PAGE_STATUS_VISIBLE', 'TXT_CORE_CM_PAGE_STATUS_INVISIBLE' => 'TXT_CORE_CM_PAGE_STATUS_INVISIBLE', 'TXT_CORE_CM_PAGE_STATUS_PROTECTED' => 'TXT_CORE_CM_PAGE_STATUS_PROTECTED', 'TXT_CORE_CM_PAGE_TYPE_HOME' => 'TXT_CORE_CM_PAGE_TYPE_HOME', 'TXT_CORE_CM_PAGE_TYPE_CONTENT_SITE' => 'TXT_CORE_CM_PAGE_TYPE_CONTENT_SITE', 'TXT_CORE_CM_PAGE_TYPE_APPLICATION' => 'TXT_CORE_CM_PAGE_TYPE_APPLICATION', 'TXT_CORE_CM_PAGE_TYPE_REDIRECTION' => 'TXT_CORE_CM_PAGE_TYPE_REDIRECTION', 'TXT_CORE_CM_PAGE_TYPE_SYMLINK' => 'TXT_CORE_CM_PAGE_TYPE_SYMLINK', 'TXT_CORE_CM_PAGE_TYPE_FALLBACK' => 'TXT_CORE_CM_PAGE_TYPE_FALLBACK', 'TXT_CORE_CM_PAGE_MOVE_INFO' => 'TXT_CORE_CM_PAGE_MOVE_INFO', 'TXT_CORE_CM_TRANSLATION_INFO' => 'TXT_CORE_CM_TRANSLATION_INFO', 'TXT_CORE_CM_PREVIEW_INFO' => 'TXT_CORE_CM_PREVIEW_INFO'));
     foreach ($arrLangVars as $subscope => $arrLang) {
         foreach ($arrLang as $name => $value) {
             $objCx->setVariable($name, $_CORELANG[$value], 'contentmanager/lang/' . $subscope);
         }
     }
     // Mediabrowser
     $mediaBrowser = new \Cx\Core_Modules\MediaBrowser\Model\Entity\MediaBrowser();
     $mediaBrowser->setOptions(array('type' => 'button'));
     $mediaBrowser->setCallback('setWebPageUrlCallback');
     $mediaBrowser->setOptions(array('data-cx-mb-startview' => 'sitestructure', 'id' => 'page_target_browse'));
     $this->template->setVariable(array('CM_MEDIABROWSER_BUTTON' => $mediaBrowser->getXHtml($_ARRAYLANG['TXT_CORE_CM_BROWSE'])));
     $toggleTitles = !empty($_SESSION['contentManager']['toggleStatuses']['toggleTitles']) ? $_SESSION['contentManager']['toggleStatuses']['toggleTitles'] : 'block';
     $toggleType = !empty($_SESSION['contentManager']['toggleStatuses']['toggleType']) ? $_SESSION['contentManager']['toggleStatuses']['toggleType'] : 'block';
     $toggleNavigation = !empty($_SESSION['contentManager']['toggleStatuses']['toggleNavigation']) ? $_SESSION['contentManager']['toggleStatuses']['toggleNavigation'] : 'block';
     $toggleBlocks = !empty($_SESSION['contentManager']['toggleStatuses']['toggleBlocks']) ? $_SESSION['contentManager']['toggleStatuses']['toggleBlocks'] : 'block';
     $toggleThemes = !empty($_SESSION['contentManager']['toggleStatuses']['toggleThemes']) ? $_SESSION['contentManager']['toggleStatuses']['toggleThemes'] : 'block';
     $toggleApplication = !empty($_SESSION['contentManager']['toggleStatuses']['toggleApplication']) ? $_SESSION['contentManager']['toggleStatuses']['toggleApplication'] : 'block';
     $toggleSidebar = !empty($_SESSION['contentManager']['toggleStatuses']['sidebar']) ? $_SESSION['contentManager']['toggleStatuses']['sidebar'] : 'block';
     $objCx->setVariable('toggleTitles', $toggleTitles, 'contentmanager/toggle');
     $objCx->setVariable('toggleType', $toggleType, 'contentmanager/toggle');
     $objCx->setVariable('toggleNavigation', $toggleNavigation, 'contentmanager/toggle');
     $objCx->setVariable('toggleBlocks', $toggleBlocks, 'contentmanager/toggle');
     $objCx->setVariable('toggleThemes', $toggleThemes, 'contentmanager/toggle');
     $objCx->setVariable('toggleApplication', $toggleApplication, 'contentmanager/toggle');
     $objCx->setVariable('sidebar', $toggleSidebar, 'contentmanager/toggle');
     // get initial tree data
     $objJsonData = new \Cx\Core\Json\JsonData();
     $treeData = $objJsonData->jsondata('node', 'getTree', array('get' => $_GET), false);
     $objCx->setVariable('tree-data', $treeData, 'contentmanager/tree');
     if (!empty($_GET['act']) && $_GET['act'] == 'new') {
         $this->template->setVariable(array('TITLES_DISPLAY_STYLE' => 'display: block;', 'TITLES_TOGGLE_CLASS' => 'open', 'TYPE_DISPLAY_STYLE' => 'display: block;', 'TYPE_TOGGLE_CLASS' => 'open', 'NAVIGATION_DISPLAY_STYLE' => 'display: block;', 'NAVIGATION_TOGGLE_CLASS' => 'open', 'BLOCKS_DISPLAY_STYLE' => 'display: block;', 'BLOCKS_TOGGLE_CLASS' => 'open', 'THEMES_DISPLAY_STYLE' => 'display: block;', 'THEMES_TOGGLE_CLASS' => 'open', 'APPLICATION_DISPLAY_STYLE' => 'display: block;', 'APPLICATION_TOGGLE_CLASS' => 'open', 'MULTIPLE_ACTIONS_STRIKE_STYLE' => 'display: none;'));
     } else {
         $this->template->setVariable(array('TITLES_DISPLAY_STYLE' => $toggleTitles == 'none' ? 'display: none;' : 'display: block;', 'TITLES_TOGGLE_CLASS' => $toggleTitles == 'none' ? 'closed' : 'open', 'TYPE_DISPLAY_STYLE' => $toggleType == 'none' ? 'display: none;' : 'display: block;', 'TYPE_TOGGLE_CLASS' => $toggleType == 'none' ? 'closed' : 'open', 'NAVIGATION_DISPLAY_STYLE' => $toggleNavigation == 'none' ? 'display: none;' : 'display: block;', 'NAVIGATION_TOGGLE_CLASS' => $toggleNavigation == 'none' ? 'closed' : 'open', 'BLOCKS_DISPLAY_STYLE' => $toggleBlocks == 'none' ? 'display: none;' : 'display: block;', 'BLOCKS_TOGGLE_CLASS' => $toggleBlocks == 'none' ? 'closed' : 'open', 'THEMES_DISPLAY_STYLE' => $toggleThemes == 'none' ? 'display: none;' : 'display: block;', 'THEMES_TOGGLE_CLASS' => $toggleThemes == 'none' ? 'closed' : 'open', 'APPLICATION_DISPLAY_STYLE' => $toggleApplication == 'none' ? 'display: none;' : 'display: block;', 'APPLICATION_TOGGLE_CLASS' => $toggleApplication == 'none' ? 'closed' : 'open'));
     }
     $modules = $this->db->Execute("SELECT * FROM " . DBPREFIX . "modules WHERE `status` = 'y' ORDER BY `name`");
     while (!$modules->EOF) {
         $this->template->setVariable('MODULE_KEY', $modules->fields['name']);
         //            $this->template->setVariable('MODULE_TITLE', $_CORELANG[$modules->fields['description_variable']]);
         $this->template->setVariable('MODULE_TITLE', ucwords($modules->fields['name']));
         $this->template->parse('module_option');
         $modules->MoveNext();
     }
     $newPageFirstLevel = isset($_GET['act']) && $_GET['act'] == 'new';
     if (\Permission::checkAccess(36, 'static', true)) {
         $this->template->touchBlock('page_permissions_tab');
         $this->template->touchBlock('page_permissions');
     } else {
         $this->template->hideBlock('page_permissions_tab');
         $this->template->hideBlock('page_permissions');
     }
     //show the caching options only if the caching system is actually active
     if ($_CONFIG['cacheEnabled'] == 'on') {
         $this->template->touchBlock('show_caching_option');
     } else {
         $this->template->hideBlock('show_caching_option');
     }
     if (\Permission::checkAccess(78, 'static', true)) {
         $this->template->hideBlock('release_button');
     } else {
         $this->template->hideBlock('publish_button');
         $this->template->hideBlock('refuse_button');
     }
     // show no access page if the user wants to create new page in first level but he does not have enough permissions
     if ($newPageFirstLevel) {
         \Permission::checkAccess(127, 'static');
     }
     $editViewCssClass = '';
     if ($newPageFirstLevel) {
         $editViewCssClass = 'edit_view';
         $this->template->hideBlock('refuse_button');
     }
     $cxjs = \ContrexxJavascript::getInstance();
     $cxjs->setVariable('confirmDeleteQuestion', $_ARRAYLANG['TXT_CORE_CM_CONFIRM_DELETE'], 'contentmanager/lang');
     $cxjs->setVariable('cleanAccessData', $objJsonData->jsondata('page', 'getAccessData', array(), false), 'contentmanager');
     $cxjs->setVariable('contentTemplates', $this->getCustomContentTemplates(), 'contentmanager');
     $cxjs->setVariable('defaultTemplates', $this->getDefaultTemplates(), 'contentmanager/themes');
     $cxjs->setVariable('templateFolders', $this->getTemplateFolders(), 'contentmanager/themes');
     $cxjs->setVariable('availableBlocks', $objJsonData->jsondata('Block', 'getBlocks', array(), false), 'contentmanager');
     // TODO: move including of add'l JS dependencies to cx obj from /cadmin/index.html
     $getLangOptions = $this->getLangOptions();
     $statusPageLayout = '';
     $languageDisplay = '';
     if ((!empty($_GET['act']) && $_GET['act'] == 'new' || !empty($_GET['page'])) && $getLangOptions == "") {
         $statusPageLayout = 'margin0';
         $languageDisplay = 'display:none';
     }
     $this->template->setVariable('ADMIN_LIST_MARGIN', $statusPageLayout);
     $this->template->setVariable('LANGUAGE_DISPLAY', $languageDisplay);
     // TODO: move including of add'l JS dependencies to cx obj from /cadmin/index.html
     $this->template->setVariable('SKIN_OPTIONS', $this->getSkinOptions());
     $this->template->setVariable('LANGSWITCH_OPTIONS', $this->getLangOptions());
     $this->template->setVariable('LANGUAGE_ARRAY', json_encode($this->getLangArray()));
     $this->template->setVariable('FALLBACK_ARRAY', json_encode($this->getFallbackArray()));
     $this->template->setVariable('LANGUAGE_LABELS', json_encode($this->getLangLabels()));
     $this->template->setVariable('EDIT_VIEW_CSS_CLASS', $editViewCssClass);
     $this->template->touchBlock('content_manager_language_selection');
     $editmodeTemplate = new \Cx\Core\Html\Sigma(ASCMS_CORE_PATH . '/ContentManager/View/Template/Backend');
     $editmodeTemplate->loadTemplateFile('content_editmode.html');
     $editmodeTemplate->setVariable(array('TXT_EDITMODE_TEXT' => $_CORELANG['TXT_FRONTEND_EDITING_SELECTION_TEXT'], 'TXT_EDITMODE_CODE' => $_CORELANG['TXT_FRONTEND_EDITING_SELECTION_MODE_PAGE'], 'TXT_EDITMODE_CONTENT' => $_CORELANG['TXT_FRONTEND_EDITING_SELECTION_MODE_CONTENT']));
     $cxjs->setVariable(array('editmodetitle' => $_CORELANG['TXT_FRONTEND_EDITING_SELECTION_TITLE'], 'editmodecontent' => $editmodeTemplate->get(), 'ckeditorconfigpath' => substr(\Env::get('ClassLoader')->getFilePath(ASCMS_CORE_PATH . '/Wysiwyg/ckeditor.config.js.php'), strlen(ASCMS_DOCUMENT_ROOT) + 1), 'regExpUriProtocol' => \FWValidator::REGEX_URI_PROTO, 'contrexxBaseUrl' => ASCMS_PROTOCOL . '://' . $_CONFIG['domainUrl'] . ASCMS_PATH_OFFSET . '/', 'contrexxPathOffset' => ASCMS_PATH_OFFSET), 'contentmanager');
 }
 /**
  * Initializes listing for the given object
  * @param Cx\Core_Modules\Listing\Model\Listable $listableObject
  * @param int $mode (optional) A combination of the paging, sorting and filtering modes above (use |)
  * @returm Cx\Core_Modules\Listing\Model\DataSet Parsed data
  */
 public function getData()
 {
     $params = array('offset' => $this->offset, 'count' => $this->count, 'order' => $this->order, 'criteria' => $this->criteria);
     foreach ($this->handlers as $handler) {
         $params = $handler->handle($params, $this->args);
     }
     $this->offset = $params['offset'];
     $this->count = $params['count'];
     $this->order = $params['order'];
     $this->criteria = $params['criteria'];
     // handle ajax requests
     if (false) {
         $jd = new \Cx\Core\Json\JsonData();
         $jd->json(array('filtering' => $this->getAjaxFilteringData(), 'sorting' => $this->getAjaxSortingData(), 'paging' => $this->getAjaxPagingData()), true);
         // JsonData->json() does call die() itself
     }
     if ($this->entityClass instanceof \Cx\Core_Modules\Listing\Model\Entity\DataSet) {
         //$data = new \Cx\Core_Modules\Listing\Model\Entity\DataSet();
         $data = $this->entityClass;
         $data = $data->sort($this->order);
         // add sorting and filtering
         $data = $data->limit($this->count, $this->offset);
         return $data;
     }
     // If a callback was specified, use it:
     $qb = \Env::get('em')->createQueryBuilder();
     $qb->select('e')->from($this->entityClass, 'e');
     $query = $qb->getQuery();
     if (is_callable($this->callback)) {
         $callable = $this->callback;
         $query = $callable($this->offset, $this->count, $this->order, $this->criteria);
         if (!$query instanceof \Doctrine\ORM\Query) {
             return $query;
         }
     }
     if (!class_exists($this->entityClass)) {
         //throw new ListingException('No such entity "' . $this->entityClass . '"');
     }
     // build query
     // TODO: check if entity class is managed
     //$qb = new \Doctrine\ORM\QueryBuilder();
     $query->setFirstResult($this->offset);
     $query->setMaxResults($this->count);
     /*foreach ($this->order as $field=>$order) {
           $query->orderBy($field, $order);
       }
       foreach ($this->criteria as $crit=>$param) {
           $query->addWhere($crit);
           if ($param) {
               $query->addParameter($param[0], $param[1]);
           }
       }
       var_dump($query->getDQL());*/
     $entities = $query->getResult();
     // @todo: check if entities should be encapsulated in a class
     $data = new \Cx\Core_Modules\Listing\Model\Entity\DataSet($entities);
     // return calculated data
     return $data;
 }
 protected function fetchResponse($license, $_CONFIG, $forceTemplate, $_CORELANG)
 {
     $v = preg_split('#\\.#', $_CONFIG['coreCmsVersion']);
     $e = $_CONFIG['coreCmsEdition'];
     $version = current($v);
     unset($v[key($v)]);
     foreach ($v as $part) {
         $version *= 100;
         $version += $part;
     }
     $srvUri = 'updatesrv1.contrexx.com';
     $srvPath = '/';
     $data = array('installationId' => $license->getInstallationId(), 'licenseKey' => $license->getLicenseKey(), 'edition' => $license->getEditionName(), 'version' => $this->coreCmsVersion, 'versionstate' => $this->coreCmsStatus, 'domainName' => $this->domainUrl, 'sendTemplate' => $forceTemplate);
     if (true) {
         try {
             $objFile = new \Cx\Lib\FileSystem\File(ASCMS_INSTANCE_PATH . ASCMS_INSTANCE_OFFSET . '/config/License.lic');
             $rawData = $objFile->getData();
             $response = json_decode(base64_decode($rawData));
         } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
             $license->setState(License::LICENSE_ERROR);
             $license->setGrayzoneMessages(array(\FWLanguage::getLanguageCodeById(LANG_ID) => new Message(\FWLanguage::getLanguageCodeById(LANG_ID), $_CORELANG['TXT_LICENSE_COMMUNICATION_ERROR'])));
             $license->check();
             throw $e;
         }
         return $response;
     }
     $a = $_SERVER['REMOTE_ADDR'];
     $r = 'http://';
     if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
         $r = 'https://';
     }
     $r .= $_SERVER['SERVER_NAME'] . ASCMS_INSTANCE_OFFSET;
     $request = new \HTTP_Request2('http://' . $srvUri . $srvPath . '?v=' . $version, \HTTP_Request2::METHOD_POST);
     $request->setHeader('X-Edition', $e);
     $request->setHeader('X-Remote-Addr', $a);
     $request->setHeader('Referer', $r);
     $jd = new \Cx\Core\Json\JsonData();
     $request->addPostParameter('data', $jd->json($data));
     try {
         $objResponse = $request->send();
         if ($objResponse->getStatus() !== 200) {
             $license->setState(License::LICENSE_ERROR);
             $license->setGrayzoneMessages(array(\FWLanguage::getLanguageCodeById(LANG_ID) => new Message(\FWLanguage::getLanguageCodeById(LANG_ID), $_CORELANG['TXT_LICENSE_COMMUNICATION_ERROR'])));
             $license->check();
             return null;
         } else {
             \DBG::dump($objResponse->getBody());
             $response = json_decode($objResponse->getBody());
         }
     } catch (\HTTP_Request2_Exception $objException) {
         $license->setState(License::LICENSE_ERROR);
         $license->setGrayzoneMessages(array(\FWLanguage::getLanguageCodeById(LANG_ID) => new Message(\FWLanguage::getLanguageCodeById(LANG_ID), $_CORELANG['TXT_LICENSE_COMMUNICATION_ERROR'])));
         $license->check();
         throw $objException;
     }
     return $response;
 }
 protected function getFunctionsCode($rowname, $rowData, $functions, $virtual = false)
 {
     global $_ARRAYLANG;
     $baseUrl = $functions['baseUrl'];
     $code = '<span class="functions">';
     if (!$virtual) {
         $editUrl = clone $baseUrl;
         $params = $editUrl->getParamArray();
         $editId = '';
         if (!empty($params['editid'])) {
             $editId = $params['editid'] . ',';
         }
         $editId .= '{' . $functions['vg_increment_number'] . ',' . $rowname . '}';
         /* We use json to do the action callback. So all callbacks are functions in the json controller of the
          * corresponding component. The 'else if' is for backwards compatibility so you can declare the function
          * directly without using json. This is not recommended and not working over session */
         if (isset($functions['actions']) && is_array($functions['actions']) && isset($functions['actions']['adapter']) && isset($functions['actions']['method'])) {
             $json = new \Cx\Core\Json\JsonData();
             $jsonResult = $json->data($functions['actions']['adapter'], $functions['actions']['method'], array('rowData' => $rowData, 'editId' => $editId));
             if ($jsonResult['status'] == 'success') {
                 $code .= $jsonResult["data"];
             }
         } else {
             if (isset($functions['actions']) && is_callable($functions['actions'])) {
                 $code .= $functions['actions']($rowData, $editId);
             }
         }
         if (isset($functions['edit']) && $functions['edit']) {
             $editUrl->setParam('editid', $editId);
             //remove the parameter 'vg_increment_number' from editUrl
             //if the baseUrl contains the parameter 'vg_increment_number'
             if (isset($params['vg_increment_number'])) {
                 \Html::stripUriParam($editUrl, 'vg_increment_number');
             }
             $code .= '<a href="' . $editUrl . '" class="edit" title="' . $_ARRAYLANG['TXT_CORE_RECORD_EDIT_TITLE'] . '"></a>';
         }
         if (isset($functions['delete']) && $functions['delete']) {
             $deleteUrl = clone $baseUrl;
             $deleteUrl->setParam('deleteid', $rowname);
             $deleteUrl->setParam('vg_increment_number', $functions['vg_increment_number']);
             $deleteUrl .= '&csrf=' . \Cx\Core\Csrf\Controller\Csrf::code();
             $onclick = 'if (confirm(\'' . $_ARRAYLANG['TXT_CORE_RECORD_DELETE_CONFIRM'] . '\'))' . 'window.location.replace(\'' . $deleteUrl . '\');';
             $_uri = 'javascript:void(0);';
             $code .= '<a onclick="' . $onclick . '" href="' . $_uri . '" class="delete" title="' . $_ARRAYLANG['TXT_CORE_RECORD_DELETE_TITLE'] . '"></a>';
         }
     }
     return $code . '</span>';
 }
 /**
  * Modify Group Page
  *
  * This page shows the dialog to modify a group.
  *
  * @return unknown
  */
 function _modifyGroup()
 {
     global $_ARRAYLANG, $_CORELANG, $objDatabase;
     $arrAreas = array();
     $associatedUsers = '';
     $arrContentAccessIds = array();
     $arrSelectedAccessIds = array();
     $notAssociatedUsers = '';
     $objFWUser = \FWUser::getFWUserObject();
     $objGroup = $objFWUser->objGroup->getGroup(isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
     if (isset($_POST['access_save_group'])) {
         // only administrators are allowed to modify a group
         if (!\Permission::hasAllAccess()) {
             \Permission::noAccess();
         }
         $objGroup->setName(!empty($_POST['access_group_name']) ? trim(contrexx_input2raw($_POST['access_group_name'])) : '');
         $objGroup->setDescription(!empty($_POST['access_group_description']) ? trim(contrexx_input2raw($_POST['access_group_description'])) : '');
         $objGroup->setActiveStatus(isset($_POST['access_group_status']) ? (bool) $_POST['access_group_status'] : false);
         $objGroup->setType(!empty($_POST['access_group_type']) ? $_POST['access_group_type'] : '');
         $objGroup->setHomepage(!empty($_POST['access_group_homepage']) ? trim(contrexx_input2raw($_POST['access_group_homepage'])) : '');
         $objGroup->setUsers(isset($_POST['access_group_associated_users']) && is_array($_POST['access_group_associated_users']) ? $_POST['access_group_associated_users'] : array());
         $objGroup->setStaticPermissionIds(isset($_POST['access_area_id']) && is_array($_POST['access_area_id']) ? $_POST['access_area_id'] : array());
         // set dynamic access ids
         $arrSelectedPageIds = isset($_POST['access_page_id']) && is_array($_POST['access_page_id']) ? $_POST['access_page_id'] : array();
         $objJsonData = new \Cx\Core\Json\JsonData();
         $jsonData = $objJsonData->data('node', 'getTree', array('get' => array('recursive' => 'true')));
         $nodeStack = $jsonData['data']['tree'];
         while (count($nodeStack)) {
             $node = array_pop($nodeStack);
             foreach ($node['data'] as $page) {
                 if ($page['attr']['id'] == 'broken') {
                     continue;
                 }
                 if (empty($page['attr'][$objGroup->getType() . '_access_id'])) {
                     continue;
                 }
                 $arrContentAccessIds[] = $page['attr'][$objGroup->getType() . '_access_id'];
                 if (in_array($page['attr']['id'], $arrSelectedPageIds)) {
                     $arrSelectedAccessIds[] = $page['attr'][$objGroup->getType() . '_access_id'];
                 }
             }
             $children = $node['children'];
             $hasChilds = count($children) > 0;
             if ($hasChilds) {
                 foreach ($children as $child) {
                     array_push($nodeStack, $child);
                 }
             }
         }
         $arrCurrentAccessIds = $objGroup->getDynamicPermissionIds();
         foreach ($arrContentAccessIds as $accessId) {
             // add new access ids
             if (in_array($accessId, $arrSelectedAccessIds) && !in_array($accessId, $arrCurrentAccessIds)) {
                 $arrCurrentAccessIds[] = $accessId;
             }
             // delete access ids
             if (!in_array($accessId, $arrSelectedAccessIds) && in_array($accessId, $arrCurrentAccessIds)) {
                 unset($arrCurrentAccessIds[array_search($accessId, $arrCurrentAccessIds)]);
             }
         }
         $objGroup->setDynamicPermissionIds($arrCurrentAccessIds);
         if (isset($_POST['access_save_group'])) {
             if ($objGroup->store()) {
                 self::$arrStatusMsg['ok'][] = $_ARRAYLANG['TXT_ACCESS_GROUP_STORED_SUCCESSFULLY'];
                 $objFWUser->objUser->getDynamicPermissionIds(true);
                 $objFWUser->objUser->getStaticPermissionIds(true);
                 $this->_groupList();
                 return;
             } else {
                 self::$arrStatusMsg['error'][] = $objGroup->getErrorMsg();
             }
         }
     } elseif (isset($_POST['access_create_group'])) {
         $objGroup->setType(isset($_POST['access_group_type']) ? $_POST['access_group_type'] : '');
     }
     $this->_objTpl->addBlockfile('ACCESS_GROUP_TEMPLATE', 'module_access_group_modify', 'module_access_group_modify.html');
     $this->_pageTitle = $objGroup->getId() ? $_ARRAYLANG['TXT_ACCESS_MODIFY_GROUP'] : $_ARRAYLANG['TXT_ACCESS_CREATE_NEW_USER_GROUP'];
     $objUser = $objFWUser->objUser->getUsers(null, null, array('username' => 'asc', 'email' => 'asc'), array('id', 'username', 'email', 'firstname', 'lastname'));
     if ($objUser) {
         $arrGroupUsers = $objGroup->getAssociatedUserIds();
         while (!$objUser->EOF) {
             $arrUsers[] = $objUser->getId();
             $objUser->next();
         }
         $arrOtherUsers = array_diff($arrUsers, $arrGroupUsers);
         foreach ($arrGroupUsers as $uId) {
             $objUser = $objFWUser->objUser->getUser($uId);
             if ($objUser) {
                 $associatedUsers .= "<option value=\"" . $objUser->getId() . "\">" . htmlentities($objUser->getUsername(), ENT_QUOTES, CONTREXX_CHARSET) . ($objUser->getProfileAttribute('lastname') != '' || $objUser->getProfileAttribute('firstname') != '' ? " (" . htmlentities($objUser->getProfileAttribute('firstname'), ENT_QUOTES, CONTREXX_CHARSET) . " " . htmlentities($objUser->getProfileAttribute('lastname'), ENT_QUOTES, CONTREXX_CHARSET) . ")" : '') . "</option>\n";
             }
         }
         foreach ($arrOtherUsers as $uId) {
             $objUser = $objFWUser->objUser->getUser($uId);
             if ($objUser) {
                 $notAssociatedUsers .= "<option value=\"" . $objUser->getId() . "\">" . htmlentities($objUser->getUsername(), ENT_QUOTES, CONTREXX_CHARSET) . ($objUser->getProfileAttribute('lastname') != '' || $objUser->getProfileAttribute('firstname') != '' ? " (" . htmlentities($objUser->getProfileAttribute('firstname'), ENT_QUOTES, CONTREXX_CHARSET) . " " . htmlentities($objUser->getProfileAttribute('lastname'), ENT_QUOTES, CONTREXX_CHARSET) . ")" : '') . "</option>\n";
             }
         }
     }
     $this->_objTpl->setVariable('ACCESS_WEBSITE_TAB_NAME', 'Webseiten');
     $arrModules = array();
     $objResult = $objDatabase->Execute("SELECT id, name FROM " . DBPREFIX . "modules");
     if ($objResult !== false) {
         while (!$objResult->EOF) {
             $arrModules[$objResult->fields['id']] = $objResult->fields['name'];
             $objResult->MoveNext();
         }
     }
     $this->_objTpl->setGlobalVariable(array('TXT_ACCESS_SHOW_PAGE_IN_NEW_DOCUMENT' => $_ARRAYLANG['TXT_ACCESS_SHOW_PAGE_IN_NEW_DOCUMENT'], 'TXT_ACCESS_MODIFY_PAGE_IN_NEW_DOCUMENT' => $_ARRAYLANG['TXT_ACCESS_MODIFY_PAGE_IN_NEW_DOCUMENT'], 'TXT_ACCESS_CHECK_ALL' => $_ARRAYLANG['TXT_ACCESS_CHECK_ALL'], 'TXT_ACCESS_UNCHECK_ALL' => $_ARRAYLANG['TXT_ACCESS_UNCHECK_ALL']));
     \JS::registerCSS('core/ContentManager/View/Style/Main.css');
     $objJsonData = new \Cx\Core\Json\JsonData();
     $jsonData = $objJsonData->data('node', 'getTree', array('get' => array('recursive' => 'true')));
     $nodeTree = $jsonData['data']['tree'];
     $this->parseContentTree($nodeTree, $objGroup->getType(), $objGroup->getDynamicPermissionIds());
     $objResult = $objDatabase->Execute("\n            SELECT\n                `areas`.`area_id`,\n                `areas`.`area_name`,\n                `areas`.`access_id`,\n                `areas`.`module_id`,\n                `areas`.`is_active`,\n                `areas`.`type`,\n                `areas`.`scope`,\n                `areas`.`parent_area_id`,\n                `modules`.`name` AS `module_name`\n            FROM\n                `" . DBPREFIX . "backend_areas` AS `areas`\n            INNER JOIN\n                `" . DBPREFIX . "modules` AS `modules`\n            ON\n                `modules`.`id` = `areas`.`module_id`\n            WHERE\n                `areas`.`is_active` = 1 AND\n                `areas`.`access_id` != '0'\n            ORDER BY\n                `areas`.`parent_area_id`,\n                `areas`.`order_id`\n        ");
     if ($objResult) {
         while (!$objResult->EOF) {
             if (isset($_CORELANG[$objResult->fields['area_name']])) {
                 $areaName = $_CORELANG[$objResult->fields['area_name']];
             } else {
                 // load language file
                 $objInit = \Env::get('init');
                 $moduleLanguageData = $objInit->getComponentSpecificLanguageData($objResult->fields['module_name'], false, $objInit->backendLangId);
                 if (isset($moduleLanguageData[$objResult->fields['area_name']])) {
                     $areaName = $moduleLanguageData[$objResult->fields['area_name']];
                 } else {
                     $areaName = $objResult->fields['area_name'];
                 }
             }
             $arrAreas[$objResult->fields['area_id']] = array('name' => $areaName, 'access_id' => $objResult->fields['access_id'], 'status' => $objResult->fields['is_active'], 'type' => $objResult->fields['type'], 'module_id' => $objResult->fields['module_id'], 'scope' => $objResult->fields['scope'], 'group_id' => $objResult->fields['parent_area_id'], 'allowed' => in_array($objResult->fields['access_id'], $objGroup->getStaticPermissionIds()) ? 1 : 0);
             $objResult->MoveNext();
         }
     }
     $tabNr = 1;
     foreach ($arrAreas as $groupId => $arrAreaGroup) {
         if ($arrAreaGroup['type'] == 'group') {
             $arrAreaTree = array();
             if ($arrAreaGroup['scope'] == $objGroup->getType() || $arrAreaGroup['scope'] == 'global') {
                 $arrAreaTree[] = array($groupId, $objGroup->getType());
                 $groupParsed = true;
             } else {
                 $groupParsed = false;
             }
             foreach ($arrAreas as $navigationId => $arrAreaNavigation) {
                 if ($groupId == $arrAreaNavigation['group_id'] && $arrAreaNavigation['type'] == 'navigation') {
                     if ($arrAreaNavigation['scope'] == $objGroup->getType() || $arrAreaNavigation['scope'] == 'global') {
                         if (!$groupParsed) {
                             $arrAreaTree[] = array($groupId, $objGroup->getType());
                             $groupParsed = true;
                         }
                         $arrAreaTree[] = array($navigationId, $objGroup->getType());
                         $navigationParsed = true;
                     } else {
                         $navigationParsed = false;
                     }
                     foreach ($arrAreas as $functionId => $arrAreaFunction) {
                         if ($navigationId == $arrAreaFunction['group_id'] && $arrAreaFunction['type'] == 'function') {
                             if ($arrAreaFunction['scope'] == $objGroup->getType() || $arrAreaFunction['scope'] == 'global') {
                                 if (!$navigationParsed) {
                                     if (!$groupParsed) {
                                         $arrAreaTree[] = array($groupId, $objGroup->getType());
                                         $groupParsed = true;
                                     }
                                     $arrAreaTree[] = array($navigationId, $objGroup->getType());
                                     $navigationParsed = true;
                                 }
                                 $arrAreaTree[] = array($functionId, $objGroup->getType());
                             }
                         }
                     }
                 }
             }
             if ($groupParsed) {
                 foreach ($arrAreaTree as $arrArea) {
                     $this->_parsePermissionAreas($arrAreas, $arrArea[0], $arrArea[1]);
                 }
                 $this->_objTpl->setGlobalVariable('ACCESS_TAB_NR', $tabNr);
                 $this->_objTpl->setVariable('ACCESS_TAB_NAME', isset($_CORELANG[$arrAreaGroup['name']]) ? htmlentities($_CORELANG[$arrAreaGroup['name']], ENT_QUOTES, CONTREXX_CHARSET) : $arrAreaGroup['name']);
                 $this->_objTpl->parse('access_permission_tab_menu');
                 $this->_objTpl->parse('access_permission_tabs');
                 $tabNr++;
             }
         }
     }
     if ($tabNr > 1) {
         $this->_objTpl->parse('access_permission_tabs_menu');
     } else {
         $this->_objTpl->hideBlock('access_permission_tabs_menu');
     }
     //Display MediaBrowser for selecting webpage
     $mediaBrowser = new \Cx\Core_Modules\MediaBrowser\Model\Entity\MediaBrowser();
     $mediaBrowser->setOptions(array('type' => 'button', 'data-cx-mb-views' => 'sitestructure', 'id' => 'media-browser-button', 'style' => 'display: none;'));
     $mediaBrowser->setCallback('SetUrl');
     $this->attachJavaScriptFunction('accessSetWebpage');
     $this->attachJavaScriptFunction('accessSelectAllGroups');
     $this->attachJavaScriptFunction('accessDeselectAllGroups');
     $this->attachJavaScriptFunction('accessAddGroupToList');
     $this->attachJavaScriptFunction('accessRemoveGroupFromList');
     $this->_objTpl->setVariable(array('ACCESS_MEDIA_BROWSER_BUTTON' => $mediaBrowser->getXHtml($_ARRAYLANG['TXT_ACCESS_BROWSE']), 'TXT_ACCESS_GENERAL' => $_ARRAYLANG['TXT_ACCESS_GENERAL'], 'TXT_ACCESS_PERMISSIONS' => $_ARRAYLANG['TXT_ACCESS_PERMISSIONS'], 'TXT_ACCESS_NAME' => $_ARRAYLANG['TXT_ACCESS_NAME'], 'TXT_ACCESS_DESCRIPTION' => $_ARRAYLANG['TXT_ACCESS_DESCRIPTION'], 'TXT_ACCESS_STATUS' => $_ARRAYLANG['TXT_ACCESS_STATUS'], 'TXT_ACCESS_ACTIVE' => $_ARRAYLANG['TXT_ACCESS_ACTIVE'], 'TXT_ACCESS_CANCEL' => $_ARRAYLANG['TXT_ACCESS_CANCEL'], 'TXT_ACCESS_SAVE' => $_ARRAYLANG['TXT_ACCESS_SAVE'], 'TXT_ACCESS_USERS' => $_ARRAYLANG['TXT_ACCESS_USERS'], 'TXT_ACCESS_AVAILABLE_USERS' => $_ARRAYLANG['TXT_ACCESS_AVAILABLE_USERS'], 'TXT_ACCESS_CHECK_ALL' => $_ARRAYLANG['TXT_ACCESS_CHECK_ALL'], 'TXT_ACCESS_UNCHECK_ALL' => $_ARRAYLANG['TXT_ACCESS_UNCHECK_ALL'], 'TXT_ACCESS_ASSOCIATED_USERS' => $_ARRAYLANG['TXT_ACCESS_ASSOCIATED_USERS'], 'TXT_ACCESS_UNPROTECT_PAGE' => $_ARRAYLANG['TXT_ACCESS_UNPROTECT_PAGE'], 'TXT_ACCESS_PROTECT_PAGE' => $_ARRAYLANG['TXT_ACCESS_PROTECT_PAGE'], 'TXT_ACCESS_PROMT_EXEC_WARNING' => $_ARRAYLANG['TXT_ACCESS_PROMT_EXEC_WARNING'], 'TXT_ACCESS_HOMEPAGE' => $_ARRAYLANG['TXT_ACCESS_HOMEPAGE'], 'TXT_ACCESS_HOMEPAGE_DESC' => $_ARRAYLANG['TXT_ACCESS_HOMEPAGE_DESC'], 'TXT_ACCESS_BROWSE' => $_ARRAYLANG['TXT_ACCESS_BROWSE']));
     $this->_objTpl->setVariable(array('ACCESS_GROUP_ID' => $objGroup->getId(), 'ACCESS_GROUP_NAME' => contrexx_raw2xhtml($objGroup->getName()), 'ACCESS_GROUP_DESCRIPTION' => contrexx_raw2xhtml($objGroup->getDescription()), 'ACCESS_GROUP_STATUS' => $objGroup->getActiveStatus() ? 'checked="checked"' : '', 'ACCESS_GROUP_TYPE' => $objGroup->getType(), 'ACCESS_GROUP_HOMEPAGE' => $objGroup->getHomepage(), 'ACCESS_GROUP_NOT_ASSOCIATED_USERS' => $notAssociatedUsers, 'ACCESS_GROUP_ASSOCIATED_USERS' => $associatedUsers, 'ACCESS_PROTECT_PAGE_TXT' => $objGroup->getType() == 'backend' ? $_ARRAYLANG['TXT_ACCESS_CONFIRM_LOCK_PAGE'] : $_ARRAYLANG['TXT_ACCESS_CONFIRM_PROTECT_PAGE'], 'ACCESS_UNPROTECT_PAGE_TXT' => $objGroup->getType() == 'backend' ? $_ARRAYLANG['TXT_ACCESS_CONFIRM_UNLOCK_PAGE'] : $_ARRAYLANG['TXT_ACCESS_CONFIRM_UNPROTECT_PAGE'], 'ACCESS_JAVASCRIPT_FUNCTIONS' => $this->getJavaScriptCode()));
     $this->_objTpl->parse('module_access_group_modify');
 }
 /**
  * Show modify block
  *
  * Show the block modification page
  *
  * @access private
  * @global array
  * @see blockLibrary::_getBlockContent(), blockLibrary::blockNamePrefix
  */
 private function _showModifyBlock($copy = false)
 {
     global $_ARRAYLANG;
     \JS::activate('cx');
     \JS::activate('ckeditor');
     \JS::activate('jqueryui');
     \JS::registerJS('lib/javascript/tag-it/js/tag-it.min.js');
     \JS::registerCss('lib/javascript/tag-it/css/tag-it.css');
     $mediaBrowserCkeditor = new MediaBrowser();
     $mediaBrowserCkeditor->setCallback('ckeditor_image_button');
     $mediaBrowserCkeditor->setOptions(array('id' => 'ckeditor_image_button', 'type' => 'button', 'style' => 'display:none'));
     $blockId = !empty($_REQUEST['blockId']) ? intval($_REQUEST['blockId']) : 0;
     $blockCat = 0;
     $blockName = '';
     $blockStart = 0;
     $blockEnd = 0;
     $blockRandom = 0;
     $blockRandom2 = 0;
     $blockRandom3 = 0;
     $blockRandom4 = 0;
     $blockGlobal = 0;
     $blockDirect = 0;
     $blockCategory = 0;
     $blockWysiwygEditor = 1;
     $blockContent = array();
     $blockAssociatedPageIds = array();
     $blockLangActive = array();
     $blockGlobalAssociatedPageIds = array();
     $blockDirectAssociatedPageIds = array();
     $blockCategoryAssociatedPageIds = array();
     $this->_objTpl->loadTemplateFile('module_block_modify.html');
     $this->_objTpl->setGlobalVariable(array('TXT_BLOCK_CONTENT' => $_ARRAYLANG['TXT_BLOCK_CONTENT'], 'TXT_BLOCK_NAME' => $_ARRAYLANG['TXT_BLOCK_NAME'], 'TXT_BLOCK_RANDOM' => $_ARRAYLANG['TXT_BLOCK_RANDOM'], 'TXT_BLOCK_GLOBAL' => $_ARRAYLANG['TXT_BLOCK_SHOW_IN_GLOBAL'], 'TXT_BLOCK_SAVE' => $_ARRAYLANG['TXT_BLOCK_SAVE'], 'TXT_BLOCK_DEACTIVATE' => $_ARRAYLANG['TXT_BLOCK_DEACTIVATE'], 'TXT_BLOCK_ACTIVATE' => $_ARRAYLANG['TXT_BLOCK_ACTIVATE'], 'TXT_DONT_SHOW_ON_PAGES' => $_ARRAYLANG['TXT_DONT_SHOW_ON_PAGES'], 'TXT_SHOW_ON_ALL_PAGES' => $_ARRAYLANG['TXT_SHOW_ON_ALL_PAGES'], 'TXT_SHOW_ON_SELECTED_PAGES' => $_ARRAYLANG['TXT_SHOW_ON_SELECTED_PAGES'], 'TXT_BLOCK_CATEGORY' => $_ARRAYLANG['TXT_BLOCK_CATEGORY'], 'TXT_BLOCK_NONE' => $_ARRAYLANG['TXT_BLOCK_NONE'], 'TXT_BLOCK_SHOW_FROM' => $_ARRAYLANG['TXT_BLOCK_SHOW_FROM'], 'TXT_BLOCK_SHOW_UNTIL' => $_ARRAYLANG['TXT_BLOCK_SHOW_UNTIL'], 'TXT_BLOCK_SHOW_TIMED' => $_ARRAYLANG['TXT_BLOCK_SHOW_TIMED'], 'TXT_BLOCK_SHOW_ALWAYS' => $_ARRAYLANG['TXT_BLOCK_SHOW_ALWAYS'], 'TXT_BLOCK_LANG_SHOW' => $_ARRAYLANG['TXT_BLOCK_SHOW_BLOCK_IN_THIS_LANGUAGE'], 'TXT_BLOCK_BASIC_DATA' => $_ARRAYLANG['TXT_BLOCK_BASIC_DATA'], 'TXT_BLOCK_ADDITIONAL_OPTIONS' => $_ARRAYLANG['TXT_BLOCK_ADDITIONAL_OPTIONS'], 'TXT_BLOCK_SELECTED_PAGES' => $_ARRAYLANG['TXT_BLOCK_SELECTED_PAGES'], 'TXT_BLOCK_AVAILABLE_PAGES' => $_ARRAYLANG['TXT_BLOCK_AVAILABLE_PAGES'], 'TXT_BLOCK_SELECT_ALL' => $_ARRAYLANG['TXT_BLOCK_SELECT_ALL'], 'TXT_BLOCK_UNSELECT_ALL' => $_ARRAYLANG['TXT_BLOCK_UNSELECT_ALL'], 'TXT_BLOCK_GLOBAL_PLACEHOLDERS' => $_ARRAYLANG['TXT_BLOCK_GLOBAL_PLACEHOLDERS'], 'TXT_BLOCK_GLOBAL_PLACEHOLDERS_INFO' => $_ARRAYLANG['TXT_BLOCK_GLOBAL_PLACEHOLDERS_INFO'], 'TXT_BLOCK_DIRECT_PLACEHOLDERS' => $_ARRAYLANG['TXT_BLOCK_DIRECT_PLACEHOLDERS'], 'TXT_BLOCK_DIRECT_PLACEHOLDERS_INFO' => $_ARRAYLANG['TXT_BLOCK_DIRECT_PLACEHOLDERS_INFO'], 'TXT_BLOCK_CATEGORY_PLACEHOLDERS' => $_ARRAYLANG['TXT_BLOCK_CATEGORY_PLACEHOLDERS'], 'TXT_BLOCK_CATEGORY_PLACEHOLDERS_INFO' => $_ARRAYLANG['TXT_BLOCK_CATEGORY_PLACEHOLDERS_INFO'], 'TXT_BLOCK_DISPLAY_TIME' => $_ARRAYLANG['TXT_BLOCK_DISPLAY_TIME'], 'TXT_BLOCK_FORM_DESC' => $_ARRAYLANG['TXT_BLOCK_CONTENT'], 'TXT_BLOCK_USE_WYSIWYG_EDITOR' => $_ARRAYLANG['TXT_BLOCK_USE_WYSIWYG_EDITOR'], 'TXT_BLOCK_TARGETING' => $_ARRAYLANG['TXT_BLOCK_TARGETING'], 'TXT_BLOCK_TARGETING_SHOW_PANE' => $_ARRAYLANG['TXT_BLOCK_TARGETING_SHOW_PANE'], 'TXT_BLOCK_TARGETING_ALL_USERS' => $_ARRAYLANG['TXT_BLOCK_TARGETING_ALL_USERS'], 'TXT_BLOCK_TARGETING_VISITOR_CONDITION_BELOW' => $_ARRAYLANG['TXT_BLOCK_TARGETING_VISITOR_CONDITION_BELOW'], 'TXT_BLOCK_TARGETING_INCLUDE' => $_ARRAYLANG['TXT_BLOCK_TARGETING_INCLUDE'], 'TXT_BLOCK_TARGETING_EXCLUDE' => $_ARRAYLANG['TXT_BLOCK_TARGETING_EXCLUDE'], 'TXT_BLOCK_TARGETING_TYPE_LOCATION' => $_ARRAYLANG['TXT_BLOCK_TARGETING_TYPE_LOCATION'], 'TXT_BLOCK_TARGETING_GEOIP_DISABLED_WARNING' => $_ARRAYLANG['TXT_BLOCK_TARGETING_GEOIP_DISABLED_WARNING']));
     $targetingStatus = isset($_POST['targeting_status']) ? contrexx_input2int($_POST['targeting_status']) : 0;
     $targeting = array();
     foreach ($this->availableTargeting as $targetingType) {
         $targetingArr = isset($_POST['targeting'][$targetingType]) ? $_POST['targeting'][$targetingType] : array();
         if (empty($targetingArr)) {
             continue;
         }
         $targeting[$targetingType] = array('filter' => !empty($targetingArr['filter']) && in_array($targetingArr['filter'], array('include', 'exclude')) ? contrexx_input2raw($targetingArr['filter']) : 'include', 'value' => isset($targetingArr['value']) ? contrexx_input2raw($targetingArr['value']) : array());
     }
     if (isset($_POST['block_save_block'])) {
         $blockCat = !empty($_POST['blockCat']) ? intval($_POST['blockCat']) : 0;
         $blockContent = isset($_POST['blockFormText_']) ? array_map('contrexx_input2raw', $_POST['blockFormText_']) : array();
         $blockName = !empty($_POST['blockName']) ? contrexx_input2raw($_POST['blockName']) : $_ARRAYLANG['TXT_BLOCK_NO_NAME'];
         $blockStart = strtotime($_POST['inputStartDate']);
         $blockEnd = strtotime($_POST['inputEndDate']);
         $blockRandom = !empty($_POST['blockRandom']) ? intval($_POST['blockRandom']) : 0;
         $blockRandom2 = !empty($_POST['blockRandom2']) ? intval($_POST['blockRandom2']) : 0;
         $blockRandom3 = !empty($_POST['blockRandom3']) ? intval($_POST['blockRandom3']) : 0;
         $blockRandom4 = !empty($_POST['blockRandom4']) ? intval($_POST['blockRandom4']) : 0;
         $blockWysiwygEditor = isset($_POST['wysiwyg_editor']) ? 1 : 0;
         $blockLangActive = isset($_POST['blockFormLanguages']) ? array_map('intval', $_POST['blockFormLanguages']) : array();
         // placeholder configurations
         // global block
         // 0 = not activated , 1 = on all pages , 2 = selected pages
         $blockGlobal = !empty($_POST['blockGlobal']) ? intval($_POST['blockGlobal']) : 0;
         // direct block and category block placeholders
         // 0 = on all pages , 1 = selected pages
         $blockDirect = !empty($_POST['blockDirect']) ? intval($_POST['blockDirect']) : 0;
         $blockCategory = !empty($_POST['blockCategory']) ? intval($_POST['blockCategory']) : 0;
         // block on page relations for each placeholder
         $blockGlobalAssociatedPageIds = isset($_POST['globalSelectedPagesList']) ? array_map('intval', explode(",", $_POST['globalSelectedPagesList'])) : array();
         $blockDirectAssociatedPageIds = isset($_POST['directSelectedPagesList']) ? array_map('intval', explode(",", $_POST['directSelectedPagesList'])) : array();
         $blockCategoryAssociatedPageIds = isset($_POST['categorySelectedPagesList']) ? array_map('intval', explode(",", $_POST['categorySelectedPagesList'])) : array();
         if ($blockId) {
             if ($this->_updateBlock($blockId, $blockCat, $blockContent, $blockName, $blockStart, $blockEnd, $blockRandom, $blockRandom2, $blockRandom3, $blockRandom4, $blockWysiwygEditor, $blockLangActive)) {
                 if ($this->storePlaceholderSettings($blockId, $blockGlobal, $blockDirect, $blockCategory, $blockGlobalAssociatedPageIds, $blockDirectAssociatedPageIds, $blockCategoryAssociatedPageIds)) {
                     $this->storeTargetingSettings($blockId, $targetingStatus, $targeting);
                     \Cx\Core\Csrf\Controller\Csrf::header('location: index.php?cmd=Block&modified=true&blockname=' . $blockName);
                     exit;
                 }
             }
             $this->_strErrMessage = $_ARRAYLANG['TXT_BLOCK_BLOCK_COULD_NOT_BE_UPDATED'];
         } else {
             if ($blockId = $this->_addBlock($blockCat, $blockContent, $blockName, $blockStart, $blockEnd, $blockRandom, $blockRandom2, $blockRandom3, $blockRandom4, $blockWysiwygEditor, $blockLangActive)) {
                 if ($this->storePlaceholderSettings($blockId, $blockGlobal, $blockDirect, $blockCategory, $blockGlobalAssociatedPageIds, $blockDirectAssociatedPageIds, $blockCategoryAssociatedPageIds)) {
                     $this->storeTargetingSettings($blockId, $targetingStatus, $targeting);
                     \Cx\Core\Csrf\Controller\Csrf::header('location: index.php?cmd=Block&added=true&blockname=' . $blockName);
                     exit;
                 }
             }
             $this->_strErrMessage = $_ARRAYLANG['TXT_BLOCK_BLOCK_COULD_NOT_BE_ADDED'];
         }
     } elseif (($arrBlock = $this->_getBlock($blockId)) !== false) {
         $blockStart = $arrBlock['start'];
         $blockEnd = $arrBlock['end'];
         $blockCat = $arrBlock['cat'];
         $blockRandom = $arrBlock['random'];
         $blockRandom2 = $arrBlock['random2'];
         $blockRandom3 = $arrBlock['random3'];
         $blockRandom4 = $arrBlock['random4'];
         $blockWysiwygEditor = $arrBlock['wysiwyg_editor'];
         $blockContent = $arrBlock['content'];
         $blockLangActive = $arrBlock['lang_active'];
         $blockName = $arrBlock['name'];
         $blockGlobal = $arrBlock['global'];
         $blockDirect = $arrBlock['direct'];
         $blockCategory = $arrBlock['category'];
         $blockGlobalAssociatedPageIds = $this->_getAssociatedPageIds($blockId, 'global');
         $blockDirectAssociatedPageIds = $this->_getAssociatedPageIds($blockId, 'direct');
         $blockCategoryAssociatedPageIds = $this->_getAssociatedPageIds($blockId, 'category');
         $targeting = $this->loadTargetingSettings($blockId);
         if (!empty($targeting)) {
             $targetingStatus = 1;
         }
     }
     $pageTitle = $blockId != 0 ? sprintf($copy ? $_ARRAYLANG['TXT_BLOCK_COPY_BLOCK'] : $_ARRAYLANG['TXT_BLOCK_MODIFY_BLOCK'], contrexx_raw2xhtml($blockName)) : $_ARRAYLANG['TXT_BLOCK_ADD_BLOCK'];
     $this->_pageTitle = $pageTitle;
     if ($copy) {
         $blockId = 0;
     }
     $this->_objTpl->setVariable(array('BLOCK_ID' => $blockId, 'BLOCK_MODIFY_TITLE' => $pageTitle, 'BLOCK_NAME' => contrexx_raw2xhtml($blockName), 'BLOCK_CATEGORIES_PARENT_DROPDOWN' => $this->_getCategoriesDropdown($blockCat), 'BLOCK_START' => !empty($blockStart) ? strftime('%Y-%m-%d %H:%M', $blockStart) : $blockStart, 'BLOCK_END' => !empty($blockEnd) ? strftime('%Y-%m-%d %H:%M', $blockEnd) : $blockEnd, 'BLOCK_WYSIWYG_EDITOR' => $blockWysiwygEditor == 1 ? 'checked="checked"' : '', 'BLOCK_RANDOM' => $blockRandom == '1' ? 'checked="checked"' : '', 'BLOCK_RANDOM_2' => $blockRandom2 == '1' ? 'checked="checked"' : '', 'BLOCK_RANDOM_3' => $blockRandom3 == '1' ? 'checked="checked"' : '', 'BLOCK_RANDOM_4' => $blockRandom4 == '1' ? 'checked="checked"' : '', 'BLOCK_GLOBAL_0' => $blockGlobal == '0' ? 'checked="checked"' : '', 'BLOCK_GLOBAL_1' => $blockGlobal == '1' ? 'checked="checked"' : '', 'BLOCK_GLOBAL_2' => $blockGlobal == '2' ? 'checked="checked"' : '', 'BLOCK_GLOBAL_SHOW_PAGE_SELECTOR' => $blockGlobal == '2' ? 'block' : 'none', 'BLOCK_DIRECT_0' => $blockDirect == '0' ? 'checked="checked"' : '', 'BLOCK_DIRECT_1' => $blockDirect == '1' ? 'checked="checked"' : '', 'BLOCK_DIRECT_SHOW_PAGE_SELECTOR' => $blockDirect == '1' ? 'block' : 'none', 'BLOCK_CATEGORY_0' => $blockCategory == '0' ? 'checked="checked"' : '', 'BLOCK_CATEGORY_1' => $blockCategory == '1' ? 'checked="checked"' : '', 'BLOCK_CATEGORY_SHOW_PAGE_SELECTOR' => $blockCategory == '1' ? 'block' : 'none', 'BLOCK_WYSIWYG_MEDIABROWSER' => $mediaBrowserCkeditor->getXHtml(), 'BLOCK_TARGETING_ALL_USERS' => $targetingStatus == 0 ? 'checked="checked"' : '', 'BLOCK_TARGETING_VISITOR_CONDITION_BELOW' => $targetingStatus == 1 ? 'checked="checked"' : '', 'BLOCK_TARGETING_COUNTRY_INCLUDE' => !empty($targeting['country']) && $targeting['country']['filter'] == 'include' ? 'selected="selected"' : '', 'BLOCK_TARGETING_COUNTRY_EXCLUDE' => !empty($targeting['country']) && $targeting['country']['filter'] == 'exclude' ? 'selected="selected"' : ''));
     if (!empty($targeting['country']) && !empty($targeting['country']['value'])) {
         foreach ($targeting['country']['value'] as $countryId) {
             $countryName = \Cx\Core\Country\Controller\Country::getNameById($countryId);
             if (empty($countryName)) {
                 continue;
             }
             $this->_objTpl->setVariable(array('BLOCK_TARGET_COUNTRY_ID' => contrexx_raw2xhtml($countryId), 'BLOCK_TARGET_COUNTRY_NAME' => contrexx_raw2xhtml($countryName)));
             $this->_objTpl->parse('block_targeting_country');
         }
     }
     $jsonData = new \Cx\Core\Json\JsonData();
     $pageTitlesTree = $jsonData->data('node', 'getPageTitlesTree');
     $pageTitlesTree = $pageTitlesTree['data'];
     $objJs = \ContrexxJavascript::getInstance();
     $blockGlobalPageSelects = $this->getPageSelections($pageTitlesTree, $blockGlobalAssociatedPageIds);
     $blockDirectPageSelects = $this->getPageSelections($pageTitlesTree, $blockDirectAssociatedPageIds);
     $blockCategoryPageSelects = $this->getPageSelections($pageTitlesTree, $blockCategoryAssociatedPageIds);
     $objJs->setVariable('globalPagesUnselectedOptions', $jsonData->json($blockGlobalPageSelects[1]), 'block');
     $objJs->setVariable('globalPagesSelectedOptions', $jsonData->json($blockGlobalPageSelects[0]), 'block');
     $objJs->setVariable('directPagesUnselectedOptions', $jsonData->json($blockDirectPageSelects[1]), 'block');
     $objJs->setVariable('directPagesSelectedOptions', $jsonData->json($blockDirectPageSelects[0]), 'block');
     $objJs->setVariable('categoryPagesUnselectedOptions', $jsonData->json($blockCategoryPageSelects[1]), 'block');
     $objJs->setVariable('categoryPagesSelectedOptions', $jsonData->json($blockCategoryPageSelects[0]), 'block');
     $objJs->setVariable('ckeditorconfigpath', substr(\Env::get('ClassLoader')->getFilePath(ASCMS_CORE_PATH . '/Wysiwyg/ckeditor.config.js.php'), strlen(ASCMS_DOCUMENT_ROOT) + 1), 'block');
     $arrActiveSystemFrontendLanguages = \FWLanguage::getActiveFrontendLanguages();
     $this->parseLanguageOptionsByPlaceholder($arrActiveSystemFrontendLanguages, 'global');
     $this->parseLanguageOptionsByPlaceholder($arrActiveSystemFrontendLanguages, 'direct');
     $this->parseLanguageOptionsByPlaceholder($arrActiveSystemFrontendLanguages, 'category');
     if (count($arrActiveSystemFrontendLanguages) > 0) {
         $intLanguageCounter = 0;
         $arrLanguages = array(0 => '', 1 => '', 2 => '');
         $strJsTabToDiv = '';
         foreach ($arrActiveSystemFrontendLanguages as $langId => $arrLanguage) {
             $boolLanguageIsActive = $blockId == 0 && $intLanguageCounter == 0 ? true : (isset($blockLangActive[$langId]) && $blockLangActive[$langId] == 1 ? true : false);
             $arrLanguages[$intLanguageCounter % 3] .= '<input id="languagebar_' . $langId . '" ' . ($boolLanguageIsActive ? 'checked="checked"' : '') . ' type="checkbox" name="blockFormLanguages[' . $langId . ']" value="1" onclick="switchBoxAndTab(this, \'lang_blockContent_' . $langId . '\');" /><label for="languagebar_' . $langId . '">' . contrexx_raw2xhtml($arrLanguage['name']) . ' [' . $arrLanguage['lang'] . ']</label><br />';
             $strJsTabToDiv .= 'arrTabToDiv["lang_blockContent_' . $langId . '"] = "langTab_' . $langId . '";' . "\n";
             ++$intLanguageCounter;
         }
         $this->_objTpl->setVariable(array('TXT_BLOCK_LANGUAGE' => $_ARRAYLANG['TXT_BLOCK_LANGUAGE'], 'EDIT_LANGUAGES_1' => $arrLanguages[0], 'EDIT_LANGUAGES_2' => $arrLanguages[1], 'EDIT_LANGUAGES_3' => $arrLanguages[2], 'EDIT_JS_TAB_TO_DIV' => $strJsTabToDiv));
     }
     $arrLanguages = \FWLanguage::getLanguageArray();
     $i = 0;
     $activeFlag = 0;
     foreach ($arrLanguages as $langId => $arrLanguage) {
         if ($arrLanguage['frontend'] != 1) {
             continue;
         }
         $tmpBlockContent = isset($blockContent[$langId]) ? $blockContent[$langId] : '';
         $tmpBlockLangActive = isset($blockLangActive[$langId]) ? $blockLangActive[$langId] : 0;
         $tmpBlockContent = preg_replace('/\\{([A-Z0-9_-]+)\\}/', '[[\\1]]', $tmpBlockContent);
         if ($blockId != 0) {
             if (!$activeFlag && isset($blockLangActive[$langId])) {
                 $activeClass = 'active';
                 $activeFlag = 1;
             }
         } elseif (!$activeFlag) {
             $activeClass = 'active';
             $activeFlag = 1;
         }
         $this->_objTpl->setVariable(array('BLOCK_LANG_TAB_LANG_ID' => intval($langId), 'BLOCK_LANG_TAB_CLASS' => isset($activeClass) ? $activeClass : '', 'TXT_BLOCK_LANG_TAB_LANG_NAME' => contrexx_raw2xhtml($arrLanguage['name']), 'BLOCK_LANGTAB_DISPLAY' => $tmpBlockLangActive == 1 ? 'display:inline;' : ($blockId == 0 && $i == 0 ? 'display:inline;' : 'display:none;')));
         $this->_objTpl->parse('block_language_tabs');
         $this->_objTpl->setVariable(array('BLOCK_LANG_ID' => intval($langId), 'BLOCK_CONTENT_TEXT_HIDDEN' => contrexx_raw2xhtml($tmpBlockContent)));
         $this->_objTpl->parse('block_language_content');
         $activeClass = '';
         $i++;
     }
     if (!$this->getGeoIpComponent() || !$this->getGeoIpComponent()->getGeoIpServiceStatus()) {
         $this->_objTpl->touchBlock('warning_geoip_disabled');
     } else {
         $this->_objTpl->hideBlock('warning_geoip_disabled');
     }
 }
 function removeModules()
 {
     global $objDatabase;
     if (isset($_POST['removeModule']) && is_array($_POST['removeModule'])) {
         foreach (array_keys($_POST['removeModule']) as $moduleId) {
             $query = "\n                    SELECT name\n                    FROM " . DBPREFIX . "modules\n                    WHERE id='" . $moduleId . "'\n                ";
             $objResult = $objDatabase->Execute($query);
             if ($objResult) {
                 if (!$objResult->EOF) {
                     $moduleName = $objResult->fields['name'];
                 }
             } else {
                 $this->errorHandling();
                 return false;
             }
             $em = \Env::get('em');
             $pageRepo = $em->getRepository('Cx\\Core\\ContentManager\\Model\\Entity\\Page');
             $pages = $pageRepo->findBy(array('module' => $moduleName, 'lang' => $this->langId));
             $nodeIds = array();
             foreach ($pages as $page) {
                 $nodeIds[] = $page->getNode()->getId();
             }
             $jd = new \Cx\Core\Json\JsonData();
             $jd->data('node', 'multipleDelete', array('post' => array('nodes' => array_unique($nodeIds))));
         }
         return true;
     } else {
         return false;
     }
 }