getValidLanguages() публичный статический Метод

public static getValidLanguages ( ) : array
Результат array
Пример #1
0
 private function storeLanguage()
 {
     if ($this->mySessionSite->Locale) {
         \Zend_Registry::set("Zend_Locale", $this->mySessionSite->Locale);
     }
     if ($this->_getParam("lg")) {
         $locale = new \Zend_Locale($this->_getParam("lg"));
         \Zend_Registry::set("Zend_Locale", $locale);
     }
     if (\Zend_Registry::isRegistered("Zend_Locale") and $this->mySessionSite->Locale) {
         //init forcée à french à reprendre
         $locale = \Zend_Registry::get("Zend_Locale");
     } else {
         $locale = new \Zend_Locale("fr_FR");
         \Zend_Registry::set("Zend_Locale", $locale);
     }
     $this->mySessionSite->Locale = $locale;
     $this->view->language = $this->language = $locale->getLanguage();
     $languages = \Pimcore\Tool::getValidLanguages();
     $languageOptions = array();
     foreach ($languages as $short) {
         if (!empty($short)) {
             $languageOptions[] = array("language" => $short, "display" => \Zend_Locale::getTranslation($short == "fr_FR" ? "fr" : $short, 'Language', $locale));
             $validLanguages[] = $short;
         }
     }
     $this->view->languageOptions = $languageOptions;
     $this->view->isAjax = $this->isAjax();
 }
Пример #2
0
 /**
  * @throws Exception
  */
 public function languageDetectionAction()
 {
     // Get the browser language
     $locale = new Zend_Locale();
     $browserLanguage = $locale->getLanguage();
     $languages = Tool::getValidLanguages();
     // Check if the browser language is a valid frontend language
     if (in_array($browserLanguage, $languages)) {
         $language = $browserLanguage;
     } else {
         // If it is not, take the first frontend language as default
         $language = reset($languages);
     }
     // Get the folder of the current language (in the current site)
     $currentSitePath = $this->document->getRealFullPath();
     $folder = Document\Page::getByPath($currentSitePath . '/' . $language);
     if ($folder) {
         $document = $this->findFirstDocumentByParentId($folder->getId());
         if ($document) {
             $this->redirect($document->getPath() . $document->getKey());
         } else {
             throw new Exception('No document found in your browser language');
         }
     } else {
         throw new Exception('No language folder found that matches your browser language');
     }
 }
Пример #3
0
 public function addLanguage($languageToAdd)
 {
     // Check if language is not already added
     if (in_array($languageToAdd, Tool::getValidLanguages())) {
         $result = false;
     } else {
         // Read all the documents from the first language
         $availableLanguages = Tool::getValidLanguages();
         $firstLanguageDocument = \Pimcore\Model\Document::getByPath('/' . reset($availableLanguages));
         \Zend_Registry::set('SEI18N_add', 1);
         // Add the language main folder
         $document = Page::create(1, array('key' => $languageToAdd, "userOwner" => 1, "userModification" => 1, "published" => true, "controller" => 'default', "action" => 'go-to-first-child'));
         $document->setProperty('language', 'text', $languageToAdd);
         // Set the language to this folder and let it inherit to the child pages
         $document->setProperty('isLanguageRoot', 'text', 1, false, false);
         // Set as language root document
         $document->save();
         // Add Link to other languages
         $t = new Keys();
         $t->insert(array("document_id" => $document->getId(), "language" => $languageToAdd, "sourcePath" => $firstLanguageDocument->getFullPath()));
         // Lets add all the docs
         $this->addDocuments($firstLanguageDocument->getId(), $languageToAdd);
         \Zend_Registry::set('SEI18N_add', 0);
         $oldConfig = Config::getSystemConfig();
         $settings = $oldConfig->toArray();
         $languages = explode(',', $settings['general']['validLanguages']);
         $languages[] = $languageToAdd;
         $settings['general']['validLanguages'] = implode(',', $languages);
         $config = new \Zend_Config($settings, true);
         $writer = new \Zend_Config_Writer_Xml(array("config" => $config, "filename" => PIMCORE_CONFIGURATION_SYSTEM));
         $writer->write();
         $result = true;
     }
     return $result;
 }
 /**
  *
  */
 public function configureOptions()
 {
     $validLanguages = (array) Tool::getValidLanguages();
     $locales = Tool::getSupportedLocales();
     $options = array();
     foreach ($locales as $short => $translation) {
         if ($this->getOnlySystemLanguages()) {
             if (!in_array($short, $validLanguages)) {
                 continue;
             }
         }
         $options[] = array("key" => $translation, "value" => $short);
     }
     $this->setOptions($options);
 }
Пример #5
0
 /**
  * Original function
  * @see Admin_DocumentController::treeGetChildsByIdAction()
  */
 public function treeGetChildsByIdAction()
 {
     $languages = Tool::getValidLanguages();
     $language = $this->_getParam("language", reset($languages));
     $document = Document::getById($this->getParam("node"));
     $documents = array();
     if ($document->hasChilds()) {
         $limit = intval($this->getParam("limit"));
         if (!$this->getParam("limit")) {
             $limit = 100000000;
         }
         $offset = intval($this->getParam("start"));
         $list = new Document\Listing();
         if ($this->getUser()->isAdmin()) {
             $list->setCondition("parentId = ? ", $document->getId());
         } else {
             $userIds = $this->getUser()->getRoles();
             $userIds[] = $this->getUser()->getId();
             $list->setCondition("parentId = ? and\r\n                                        (\r\n                                        (select list from users_workspaces_document where userId in (" . implode(',', $userIds) . ") and LOCATE(CONCAT(path,`key`),cpath)=1  ORDER BY LENGTH(cpath) DESC LIMIT 1)=1\r\n                                        or\r\n                                        (select list from users_workspaces_document where userId in (" . implode(',', $userIds) . ") and LOCATE(cpath,CONCAT(path,`key`))=1  ORDER BY LENGTH(cpath) DESC LIMIT 1)=1\r\n                                        )", $document->getId());
         }
         $list->setOrderKey("index");
         $list->setOrder("asc");
         $list->setLimit($limit);
         $list->setOffset($offset);
         $childsList = $list->load();
         foreach ($childsList as $childDocument) {
             // only display document if listing is allowed for the current user
             if ($childDocument->isAllowed("list")) {
                 if ($childDocument instanceof Document\Page && $childDocument->hasProperty('isLanguageRoot') && $childDocument->getProperty('isLanguageRoot') == 1) {
                     if ($childDocument->getKey() == $language) {
                         //                            $documents[] = $this->getTreeNodeConfig($childDocument);
                         $config = $this->getTreeNodeConfig($childDocument);
                         $config['expanded'] = true;
                         $documents[] = $config;
                     }
                 } else {
                     $documents[] = $this->getTreeNodeConfig($childDocument);
                 }
             }
         }
     }
     if ($this->getParam("limit")) {
         $this->_helper->json(array("offset" => $offset, "limit" => $limit, "total" => $document->getChildAmount($this->getUser()), "nodes" => $documents));
     } else {
         $this->_helper->json($documents);
     }
     $this->_helper->json(false);
 }
 /**
  * @param $path
  *
  * @return string
  * @throws \Zend_Exception
  */
 public static function parse($path)
 {
     $currentCountry = NULL;
     if (\Zend_Registry::isRegistered('Website_Country')) {
         $currentCountry = \Zend_Registry::get('Website_Country');
     }
     //only parse if country in l10n is active!
     if (!is_null($currentCountry)) {
         $validLanguages = Tool::getValidLanguages();
         $currentIsoCode = strtolower($currentCountry);
         $shiftCountry = FALSE;
         $pathCountry = '';
         $globalString = 'global';
         $urlPath = parse_url($path, PHP_URL_PATH);
         $urlPathFragments = explode('/', ltrim($urlPath, '/'));
         //it's a global page, link is correct.
         if ($currentIsoCode === $globalString) {
             return $path;
         }
         if (isset($urlPathFragments[0])) {
             $pathElements = explode('-', $urlPathFragments[0]);
             //first needs to be country
             $pathCountry = isset($pathElements[0]) ? $pathElements[0] : NULL;
             //second needs to be language.
             $pathLanguage = isset($pathElements[1]) ? $pathElements[1] : NULL;
             $isValidLanguage = in_array($pathLanguage, $validLanguages);
             //if 2. fragment is invalid language and 1. fragment is valid language, 1. fragment is missing!
             $shiftCountry = $isValidLanguage == FALSE && in_array($pathCountry, $validLanguages);
         }
         //country is missing. add it.
         if ($shiftCountry) {
             $path = '/' . $currentIsoCode . '-' . ltrim($path, '/');
         } else {
             if (substr($path, 0, strlen($globalString) + 2) === '/' . $globalString . '-') {
                 $path = substr_replace($path, '/' . $currentIsoCode . '-', 0, strlen($globalString) + 2);
             }
         }
         return $path;
     }
     return $path;
 }
 public function installProperties()
 {
     $defProperty = Property\Predefined::getByKey('assigned_language');
     if (!$defProperty instanceof Property\Predefined) {
         $languages = \Pimcore\Tool::getValidLanguages();
         $data = 'all,';
         foreach ($languages as $language) {
             $data .= $language . ',';
         }
         $data = rtrim($data, ',');
         $property = new Property\Predefined();
         $property->setType('select');
         $property->setName('Assigned Language');
         $property->setKey('assigned_language');
         $property->setDescription('set a specific language which lucene search should respect while crawling.');
         $property->setCtype('asset');
         $property->setData('all');
         $property->setConfig($data);
         $property->setInheritable(FALSE);
         $property->save();
     }
 }
Пример #8
0
 public function getAvailableLanguagesAction()
 {
     if ($languages = Tool::getValidLanguages()) {
         $this->_helper->json($languages);
     }
     $t = new Model\Translation\Website();
     $this->_helper->json($t->getAvailableLanguages());
 }
Пример #9
0
 /**
  *
  */
 public function createUpdateTable()
 {
     $table = $this->getTableName();
     $context = $this->model->getContext();
     if ($context && $context["containerType"] == "fieldcollection") {
         $this->db->query("CREATE TABLE IF NOT EXISTS `" . $table . "` (\n              `ooo_id` int(11) NOT NULL default '0',\n              `index` INT(11) NOT NULL DEFAULT '0',\n              `fieldname` VARCHAR(190) NOT NULL DEFAULT '',\n              `language` varchar(10) NOT NULL DEFAULT '',\n              PRIMARY KEY (`ooo_id`, `language`, `index`, `fieldname`),\n              INDEX `ooo_id` (`ooo_id`),\n              INDEX `index` (`index`),\n              INDEX `fieldname` (`fieldname`),\n              INDEX `language` (`language`)\n            ) DEFAULT CHARSET=utf8mb4;");
     } else {
         $this->db->query("CREATE TABLE IF NOT EXISTS `" . $table . "` (\n              `ooo_id` int(11) NOT NULL default '0',\n              `language` varchar(10) NOT NULL DEFAULT '',\n              PRIMARY KEY (`ooo_id`,`language`),\n              INDEX `ooo_id` (`ooo_id`),\n              INDEX `language` (`language`)\n            ) DEFAULT CHARSET=utf8mb4;");
     }
     $existingColumns = $this->getValidTableColumns($table, false);
     // no caching of table definition
     $columnsToRemove = $existingColumns;
     Object\ClassDefinition\Service::updateTableDefinitions($this->tableDefinitions, [$table]);
     if ($context && $context["containerType"] == "fieldcollection") {
         $protectedColumns = ["ooo_id", "language", "index", "fieldname"];
         $containerKey = $context["containerKey"];
         $container = Object\Fieldcollection\Definition::getByKey($containerKey);
     } else {
         $protectedColumns = ["ooo_id", "language"];
         $container = $this->model->getClass();
     }
     foreach ($container->getFielddefinition("localizedfields")->getFielddefinitions() as $value) {
         if ($value->getColumnType()) {
             $key = $value->getName();
             if (is_array($value->getColumnType())) {
                 // if a datafield requires more than one field
                 foreach ($value->getColumnType() as $fkey => $fvalue) {
                     $this->addModifyColumn($table, $key . "__" . $fkey, $fvalue, "", "NULL");
                     $protectedColumns[] = $key . "__" . $fkey;
                 }
             } else {
                 if ($value->getColumnType()) {
                     $this->addModifyColumn($table, $key, $value->getColumnType(), "", "NULL");
                     $protectedColumns[] = $key;
                 }
             }
             $this->addIndexToField($value, $table);
         }
     }
     $this->removeUnusedColumns($table, $columnsToRemove, $protectedColumns);
     $validLanguages = Tool::getValidLanguages();
     if ($container instanceof Object\ClassDefinition) {
         foreach ($validLanguages as &$language) {
             $queryTable = $this->getQueryTableName();
             $queryTable .= "_" . $language;
             $this->db->query("CREATE TABLE IF NOT EXISTS `" . $queryTable . "` (\n                      `ooo_id` int(11) NOT NULL default '0',\n                      `language` varchar(10) NOT NULL DEFAULT '',\n                      PRIMARY KEY (`ooo_id`,`language`),\n                      INDEX `ooo_id` (`ooo_id`),\n                      INDEX `language` (`language`)\n                    ) DEFAULT CHARSET=utf8mb4;");
             // create object table if not exists
             $protectedColumns = ["ooo_id", "language"];
             $existingColumns = $this->getValidTableColumns($queryTable, false);
             // no caching of table definition
             $columnsToRemove = $existingColumns;
             Object\ClassDefinition\Service::updateTableDefinitions($this->tableDefinitions, [$queryTable]);
             $fieldDefinitions = $this->model->getClass()->getFielddefinition("localizedfields")->getFielddefinitions();
             // add non existing columns in the table
             if (is_array($fieldDefinitions) && count($fieldDefinitions)) {
                 foreach ($fieldDefinitions as $value) {
                     if ($value->getQueryColumnType()) {
                         $key = $value->getName();
                         // if a datafield requires more than one column in the query table
                         if (is_array($value->getQueryColumnType())) {
                             foreach ($value->getQueryColumnType() as $fkey => $fvalue) {
                                 $this->addModifyColumn($queryTable, $key . "__" . $fkey, $fvalue, "", "NULL");
                                 $protectedColumns[] = $key . "__" . $fkey;
                             }
                         }
                         // everything else
                         if (!is_array($value->getQueryColumnType()) && $value->getQueryColumnType()) {
                             $this->addModifyColumn($queryTable, $key, $value->getQueryColumnType(), "", "NULL");
                             $protectedColumns[] = $key;
                         }
                         // add indices
                         $this->addIndexToField($value, $queryTable);
                     }
                 }
             }
             // remove unused columns in the table
             $this->removeUnusedColumns($queryTable, $columnsToRemove, $protectedColumns);
         }
         $this->createLocalizedViews();
     }
     $this->tableDefinitions = null;
 }
Пример #10
0
</td>
    </tr>

    <tr class="">
        <td colspan="3">&nbsp;</td>
    </tr>

<?php 
$c = 0;
foreach ($fields as $fieldName => $definition) {
    ?>
    <?php 
    if ($definition instanceof Object\ClassDefinition\Data\Localizedfields) {
        ?>
        <?php 
        foreach (\Pimcore\Tool::getValidLanguages() as $language) {
            ?>
            <?php 
            foreach ($definition->getFieldDefinitions() as $lfd) {
                ?>
                <?php 
                $v1 = $lfd->getVersionPreview($this->object1->getValueForFieldName($fieldName)->getLocalizedValue($lfd->getName(), $language));
                $v2 = $lfd->getVersionPreview($this->object2->getValueForFieldName($fieldName)->getLocalizedValue($lfd->getName(), $language));
                ?>
                <tr<?php 
                if ($c % 2) {
                    ?>
 class="odd"<?php 
                }
                ?>
>
Пример #11
0
 /**
  * @param $name
  * @param $value
  * @param null $language
  * @return void
  */
 public function setLocalizedValue($name, $value, $language = null)
 {
     if (self::$strictMode) {
         if (!$language || !in_array($language, Tool::getValidLanguages())) {
             throw new \Exception("Language " . $language . " not accepted in strict mode");
         }
     }
     $language = $this->getLanguage($language);
     if (!$this->languageExists($language)) {
         $this->items[$language] = array();
     }
     $fieldDefinition = $this->getObject()->getClass()->getFieldDefinition("localizedfields")->getFieldDefinition($name);
     if (method_exists($fieldDefinition, "preSetData")) {
         $value = $fieldDefinition->preSetData($this, $value, array("language" => $language, "name" => $name));
     }
     $this->items[$language][$name] = $value;
     return $this;
 }
Пример #12
0
 public function getValidLanguages()
 {
     if ($this->localized) {
         $validLanguages = Tool::getValidLanguages();
     } else {
         $validLanguages = [];
     }
     array_unshift($validLanguages, "default");
     return $validLanguages;
 }
Пример #13
0
 public function gridGetColumnConfigAction()
 {
     if ($this->getParam("id")) {
         $class = Object\ClassDefinition::getById($this->getParam("id"));
     } else {
         if ($this->getParam("name")) {
             $class = Object\ClassDefinition::getByName($this->getParam("name"));
         }
     }
     $gridType = "search";
     if ($this->getParam("gridtype")) {
         $gridType = $this->getParam("gridtype");
     }
     $objectId = $this->getParam("objectId");
     if ($objectId) {
         $fields = Object\Service::getCustomGridFieldDefinitions($class->getId(), $objectId);
     }
     if (!$fields) {
         $fields = $class->getFieldDefinitions();
     }
     $types = array();
     if ($this->getParam("types")) {
         $types = explode(",", $this->getParam("types"));
     }
     // grid config
     $gridConfig = array();
     if ($objectId) {
         $configFiles["configFileClassUser"] = PIMCORE_CONFIGURATION_DIRECTORY . "/object/grid/" . $this->getParam("objectId") . "_" . $class->getId() . "-user_" . $this->getUser()->getId() . ".psf";
         $configFiles["configFileUser"] = PIMCORE_CONFIGURATION_DIRECTORY . "/object/grid/" . $this->getParam("objectId") . "-user_" . $this->getUser()->getId() . ".psf";
         foreach ($configFiles as $configFile) {
             if (is_file($configFile)) {
                 $gridConfig = Tool\Serialize::unserialize(file_get_contents($configFile));
                 if (is_array($gridConfig) && array_key_exists("classId", $gridConfig)) {
                     if ($gridConfig["classId"] == $class->getId()) {
                         break;
                     } else {
                         $gridConfig = array();
                     }
                 } else {
                     break;
                 }
             }
         }
     }
     $localizedFields = array();
     $objectbrickFields = array();
     foreach ($fields as $key => $field) {
         if ($field instanceof Object\ClassDefinition\Data\Localizedfields) {
             $localizedFields[] = $field;
         } else {
             if ($field instanceof Object\ClassDefinition\Data\Objectbricks) {
                 $objectbrickFields[] = $field;
             }
         }
     }
     $availableFields = array();
     $systemColumns = array("id", "fullpath", "published", "creationDate", "modificationDate", "filename", "classname");
     if (empty($gridConfig)) {
         $count = 0;
         if (!$this->getParam("no_system_columns")) {
             $vis = $class->getPropertyVisibility();
             foreach ($systemColumns as $sc) {
                 $key = $sc;
                 if ($key == "fullpath") {
                     $key = "path";
                 }
                 if (empty($types) && ($vis[$gridType][$key] || $gridType == "all")) {
                     $availableFields[] = array("key" => $sc, "type" => "system", "label" => $sc, "position" => $count);
                     $count++;
                 }
             }
         }
         $includeBricks = !$this->getParam("no_brick_columns");
         foreach ($fields as $key => $field) {
             if ($field instanceof Object\ClassDefinition\Data\Localizedfields) {
                 foreach ($field->getFieldDefinitions() as $fd) {
                     if (empty($types) || in_array($fd->getFieldType(), $types)) {
                         $fieldConfig = $this->getFieldGridConfig($fd, $gridType, $count);
                         if (!empty($fieldConfig)) {
                             $availableFields[] = $fieldConfig;
                             $count++;
                         }
                     }
                 }
             } else {
                 if ($field instanceof Object\ClassDefinition\Data\Objectbricks && $includeBricks) {
                     if (in_array($field->getFieldType(), $types)) {
                         $fieldConfig = $this->getFieldGridConfig($field, $gridType, $count);
                         if (!empty($fieldConfig)) {
                             $availableFields[] = $fieldConfig;
                             $count++;
                         }
                     } else {
                         $allowedTypes = $field->getAllowedTypes();
                         if (!empty($allowedTypes)) {
                             foreach ($allowedTypes as $t) {
                                 $brickClass = Object\Objectbrick\Definition::getByKey($t);
                                 $brickFields = $brickClass->getFieldDefinitions();
                                 if (!empty($brickFields)) {
                                     foreach ($brickFields as $bf) {
                                         $fieldConfig = $this->getFieldGridConfig($bf, $gridType, $count, false, $t . "~");
                                         if (!empty($fieldConfig)) {
                                             $availableFields[] = $fieldConfig;
                                             $count++;
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 } else {
                     if (empty($types) || in_array($field->getFieldType(), $types)) {
                         $fieldConfig = $this->getFieldGridConfig($field, $gridType, $count, !empty($types));
                         if (!empty($fieldConfig)) {
                             $availableFields[] = $fieldConfig;
                             $count++;
                         }
                     }
                 }
             }
         }
     } else {
         $savedColumns = $gridConfig['columns'];
         foreach ($savedColumns as $key => $sc) {
             if (!$sc['hidden']) {
                 if (in_array($key, $systemColumns)) {
                     $colConfig = array("key" => $key, "type" => "system", "label" => $key, "position" => $sc['position']);
                     if (isset($sc['width'])) {
                         $colConfig['width'] = $sc['width'];
                     }
                     $availableFields[] = $colConfig;
                 } else {
                     $keyParts = explode("~", $key);
                     if (substr($key, 0, 1) == "~") {
                         // not needed for now
                         //                            $type = $keyParts[1];
                         //                            $field = $keyParts[2];
                         //                            $keyid = $keyParts[3];
                     } else {
                         if (count($keyParts) > 1) {
                             $brick = $keyParts[0];
                             $key = $keyParts[1];
                             $brickClass = Object\Objectbrick\Definition::getByKey($brick);
                             $fd = $brickClass->getFieldDefinition($key);
                             if (!empty($fd)) {
                                 $fieldConfig = $this->getFieldGridConfig($fd, $gridType, $sc['position'], true, $brick . "~");
                                 if (!empty($fieldConfig)) {
                                     if (isset($sc['width'])) {
                                         $fieldConfig['width'] = $sc['width'];
                                     }
                                     $availableFields[] = $fieldConfig;
                                 }
                             }
                         } else {
                             $fd = $class->getFieldDefinition($key);
                             //if not found, look for localized fields
                             if (empty($fd)) {
                                 foreach ($localizedFields as $lf) {
                                     $fd = $lf->getFieldDefinition($key);
                                     if (!empty($fd)) {
                                         break;
                                     }
                                 }
                             }
                             if (!empty($fd)) {
                                 $fieldConfig = $this->getFieldGridConfig($fd, $gridType, $sc['position'], true);
                                 if (!empty($fieldConfig)) {
                                     if (isset($sc['width'])) {
                                         $fieldConfig['width'] = $sc['width'];
                                     }
                                     $availableFields[] = $fieldConfig;
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     usort($availableFields, function ($a, $b) {
         if ($a["position"] == $b["position"]) {
             return 0;
         }
         return $a["position"] < $b["position"] ? -1 : 1;
     });
     $config = \Pimcore\Config::getSystemConfig();
     $frontendLanguages = Tool\Admin::reorderWebsiteLanguages(\Pimcore\Tool\Admin::getCurrentUser(), $config->general->validLanguages);
     if ($frontendLanguages) {
         $language = explode(',', $frontendLanguages)[0];
     } else {
         $language = $this->getLanguage();
     }
     if (!Tool::isValidLanguage($language)) {
         $validLanguages = Tool::getValidLanguages();
         $language = $validLanguages[0];
     }
     if (!empty($gridConfig) && !empty($gridConfig['language'])) {
         $language = $gridConfig['language'];
     }
     $this->_helper->json(array("sortinfo" => $gridConfig['sortinfo'], "language" => $language, "availableFields" => $availableFields, "onlyDirectChildren" => $gridConfig['onlyDirectChildren'], "pageSize" => $gridConfig['pageSize']));
 }
Пример #14
0
 /**
  * Try to set the locale from different sources
  *
  * @param $locale
  * @return $this
  */
 public function setLocale($locale = null)
 {
     if ($locale instanceof \Zend_Locale) {
         $this->locale = $locale;
     } elseif (is_string($locale)) {
         $this->locale = new \Zend_Locale($locale);
     } elseif ($this->getParam('locale') || $this->getParam('language')) {
         $this->setLocale($this->getParam('locale') ? $this->getParam('locale') : $this->getParam('language'));
     } else {
         $document = $this->getDocument();
         if ($document instanceof Document && $document->getProperty("language")) {
             $this->setLocale($document->getProperty("language"));
         }
         if (is_null($this->locale)) {
             //last chance -> get it from registry or use the first Language defined in the system settings
             if (\Zend_Registry::isRegistered("Zend_Locale")) {
                 $this->locale = \Zend_Registry::get("Zend_Locale");
             } else {
                 list($language) = \Pimcore\Tool::getValidLanguages();
                 $this->locale = new \Zend_Locale($language);
             }
         }
     }
     return $this;
 }
Пример #15
0
 public function translationsAction()
 {
     $admin = $this->getParam("admin");
     if ($admin) {
         $class = "\\Pimcore\\Model\\Translation\\Admin";
         $this->checkPermission("translations_admin");
     } else {
         $class = "\\Pimcore\\Model\\Translation\\Website";
         $this->checkPermission("translations");
     }
     // clear translation cache
     Translation\Website::clearDependentCache();
     if ($this->getParam("data")) {
         $data = \Zend_Json::decode($this->getParam("data"));
         if ($this->getParam("xaction") == "destroy") {
             $data = \Zend_Json::decode($this->getParam("data"));
             if (\Pimcore\Tool\Admin::isExtJS6()) {
                 $t = $class::getByKey($data["key"]);
             } else {
                 $t = $class::getByKey($data);
             }
             $t->delete();
             $this->_helper->json(array("success" => true, "data" => array()));
         } else {
             if ($this->getParam("xaction") == "update") {
                 $t = $class::getByKey($data["key"]);
                 foreach ($data as $key => $value) {
                     if ($key != "key") {
                         $t->addTranslation($key, $value);
                     }
                 }
                 if ($data["key"]) {
                     $t->setKey($data["key"]);
                 }
                 $t->setModificationDate(time());
                 $t->save();
                 $return = array_merge(array("key" => $t->getKey(), "creationDate" => $t->getCreationDate(), "modificationDate" => $t->getModificationDate()), $t->getTranslations());
                 $this->_helper->json(array("data" => $return, "success" => true));
             } else {
                 if ($this->getParam("xaction") == "create") {
                     try {
                         $t = $class::getByKey($data["key"]);
                     } catch (\Exception $e) {
                         $t = new $class();
                         $t->setKey($data["key"]);
                         $t->setCreationDate(time());
                         $t->setModificationDate(time());
                         foreach (Tool::getValidLanguages() as $lang) {
                             $t->addTranslation($lang, "");
                         }
                         $t->save();
                     }
                     $return = array_merge(array("key" => $t->getKey(), "creationDate" => $t->getCreationDate(), "modificationDate" => $t->getModificationDate()), $t->getTranslations());
                     $this->_helper->json(array("data" => $return, "success" => true));
                 }
             }
         }
     } else {
         // get list of types
         if ($admin) {
             $list = new Translation\Admin\Listing();
         } else {
             $list = new Translation\Website\Listing();
         }
         $list->setOrder("asc");
         $list->setOrderKey("key");
         $sortingSettings = \Pimcore\Admin\Helper\QueryParams::extractSortingSettings($this->getAllParams());
         if ($sortingSettings['orderKey']) {
             $list->setOrderKey($sortingSettings['orderKey']);
         }
         if ($sortingSettings['order']) {
             $list->setOrder($sortingSettings['order']);
         }
         $list->setLimit($this->getParam("limit"));
         $list->setOffset($this->getParam("start"));
         $condition = $this->getGridFilterCondition();
         if ($condition) {
             $list->setCondition($condition);
         }
         $list->load();
         $translations = array();
         foreach ($list->getTranslations() as $t) {
             $translations[] = array_merge($t->getTranslations(), array("key" => $t->getKey(), "creationDate" => $t->getCreationDate(), "modificationDate" => $t->getModificationDate()));
         }
         $this->_helper->json(array("data" => $translations, "success" => true, "total" => $list->getTotalCount()));
     }
 }
Пример #16
0
 public function roleGetAction()
 {
     $role = User\Role::getById(intval($this->getParam("id")));
     // workspaces
     $types = ["asset", "document", "object"];
     foreach ($types as $type) {
         $workspaces = $role->{"getWorkspaces" . ucfirst($type)}();
         foreach ($workspaces as $workspace) {
             $el = Element\Service::getElementById($type, $workspace->getCid());
             if ($el) {
                 // direct injection => not nice but in this case ok ;-)
                 $workspace->path = $el->getRealFullPath();
             }
         }
     }
     // get available permissions
     $availableUserPermissionsList = new User\Permission\Definition\Listing();
     $availableUserPermissions = $availableUserPermissionsList->load();
     $availablePerspectives = \Pimcore\Config::getAvailablePerspectives(null);
     $this->_helper->json(["success" => true, "role" => $role, "permissions" => $role->generatePermissionList(), "classes" => $role->getClasses(), "docTypes" => $role->getDocTypes(), "availablePermissions" => $availableUserPermissions, "availablePerspectives" => $availablePerspectives, "validLanguages" => Tool::getValidLanguages()]);
 }
Пример #17
0
        }
        ?>
 
    
    <?php 
    }
}
?>


<?php 
// language icons
?>

<?php 
$languages = \Pimcore\Tool::getValidLanguages();
?>

<?php 
foreach ($languages as $language) {
    $iconFile = \Pimcore\Tool::getLanguageFlagFile($language);
    $iconFile = preg_replace("@^" . preg_quote(PIMCORE_DOCUMENT_ROOT, "@") . "@", "", $iconFile);
    ?>
    /* tab icon for localized fields [ <?php 
    echo $language;
    ?>
 ] */
    .pimcore_icon_language_<?php 
    echo strtolower($language);
    ?>
 {
Пример #18
0
 /**
  * Imports translations from a csv file
  * The CSV file has to have the same format as an Pimcore translation-export-file
  *
  * @static
  * @param $file - path to the csv file
  * @param bool $replaceExistingTranslations
  * @throws \Exception
  */
 public static function importTranslationsFromFile($file, $replaceExistingTranslations = true, $languages = null)
 {
     $delta = [];
     if (is_readable($file)) {
         if (!$languages || empty($languages) || !is_array($languages)) {
             $languages = Tool::getValidLanguages();
         }
         //read import data
         $tmpData = file_get_contents($file);
         //replace magic excel bytes
         $tmpData = str_replace("", "", $tmpData);
         //convert to utf-8 if needed
         $tmpData = Tool\Text::convertToUTF8($tmpData);
         //store data for further usage
         $importFile = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/import_translations";
         File::put($importFile, $tmpData);
         $importFileOriginal = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/import_translations_original";
         File::put($importFileOriginal, $tmpData);
         // determine csv type
         $dialect = Tool\Admin::determineCsvDialect(PIMCORE_SYSTEM_TEMP_DIRECTORY . "/import_translations_original");
         //read data
         if (($handle = fopen(PIMCORE_SYSTEM_TEMP_DIRECTORY . "/import_translations", "r")) !== false) {
             while (($rowData = fgetcsv($handle, 0, $dialect->delimiter, $dialect->quotechar, $dialect->escapechar)) !== false) {
                 $data[] = $rowData;
             }
             fclose($handle);
         }
         //process translations
         if (is_array($data) and count($data) > 1) {
             $keys = $data[0];
             // remove wrong quotes in some export/import constellations
             $keys = array_map(function ($value) {
                 return trim($value, '""');
             }, $keys);
             $data = array_slice($data, 1);
             foreach ($data as $row) {
                 $keyValueArray = [];
                 for ($counter = 0; $counter < count($row); $counter++) {
                     $rd = str_replace("&quot;", '"', $row[$counter]);
                     $keyValueArray[$keys[$counter]] = $rd;
                 }
                 $textKey = $keyValueArray["key"];
                 if ($textKey) {
                     $t = static::getByKey($textKey, true);
                     $dirty = false;
                     foreach ($keyValueArray as $key => $value) {
                         if (in_array($key, $languages)) {
                             $currentTranslation = $t->getTranslation($key);
                             if ($replaceExistingTranslations) {
                                 $t->addTranslation($key, $value);
                                 if ($currentTranslation != $value) {
                                     $dirty = true;
                                 }
                             } else {
                                 if (!$t->getTranslation($key)) {
                                     $t->addTranslation($key, $value);
                                     if ($currentTranslation != $value) {
                                         $dirty = true;
                                     }
                                 } elseif ($t->getTranslation($key) != $value && $value) {
                                     $delta[] = ["lg" => $key, "key" => $textKey, "text" => $t->getTranslation($key), "csv" => $value];
                                 }
                             }
                         }
                     }
                     if ($dirty) {
                         if ($keyValueArray['creationDate']) {
                             $t->setCreationDate($keyValueArray['creationDate']);
                         }
                         $t->setModificationDate(time());
                         //ignore modificationDate from file
                         $t->save();
                     }
                 }
             }
             Model\Translation\AbstractTranslation::clearDependentCache();
         } else {
             throw new \Exception("less than 2 rows of data - nothing to import");
         }
     } else {
         throw new \Exception("{$file} is not readable");
     }
     return $delta;
 }
Пример #19
0
 /**
  * @param $data
  * @param $object
  * @param $fieldData
  * @param $metaData
  * @param int $level
  * @return array
  */
 private function doGetDataForEditMode($data, $object, &$fieldData, &$metaData, $level = 1)
 {
     $class = $object->getClass();
     $inheritanceAllowed = $class->getAllowInherit();
     $inherited = false;
     $items = $data->getItems();
     foreach ($items as $groupId => $keys) {
         foreach ($keys as $keyId => $languages) {
             $keyConfig = Object\Classificationstore\DefinitionCache::get($keyId);
             $fd = Object\Classificationstore\Service::getFieldDefinitionFromKeyConfig($keyConfig);
             foreach ($languages as $language => $value) {
                 $fdata = $value;
                 if (!isset($fieldData[$language][$groupId][$keyId]) || $fd->isEmpty($fieldData[$language][$groupId][$keyId])) {
                     // never override existing data
                     $fieldData[$language][$groupId][$keyId] = $fdata;
                     if (!$fd->isEmpty($fdata)) {
                         $metaData[$language][$groupId][$keyId] = array("inherited" => $level > 1, "objectid" => $object->getId());
                     }
                 }
             }
         }
     }
     // TODO
     if ($inheritanceAllowed) {
         // check if there is a parent with the same type
         $parent = Object\Service::hasInheritableParentObject($object);
         if ($parent) {
             // same type, iterate over all language and all fields and check if there is something missing
             if ($this->localized) {
                 $validLanguages = Tool::getValidLanguages();
             } else {
                 $validLanguages = array();
             }
             array_unshift($validLanguages, "default");
             $foundEmptyValue = false;
             $activeGroupIds = $this->recursiveGetActiveGroupsIds($object);
             foreach ($validLanguages as $language) {
                 foreach ($activeGroupIds as $groupId => $enabled) {
                     if (!$enabled) {
                         continue;
                     }
                     $relation = new Object\Classificationstore\KeyGroupRelation\Listing();
                     $relation->setCondition("groupId = " . $relation->quote($groupId));
                     $relation = $relation->load();
                     foreach ($relation as $key) {
                         $keyId = $key->getKeyId();
                         $fd = Object\Classificationstore\Service::getFieldDefinitionFromKeyConfig($key);
                         if ($fd->isEmpty($fieldData[$language][$groupId][$keyId])) {
                             $foundEmptyValue = true;
                             $inherited = true;
                             $metaData[$language][$groupId][$keyId] = array("inherited" => true, "objectid" => $parent->getId());
                         }
                     }
                 }
             }
             if ($foundEmptyValue) {
                 // still some values are passing, ask the parent
                 $getter = "get" . ucfirst($this->getName());
                 $parentData = $parent->{$getter}();
                 $parentResult = $this->doGetDataForEditMode($parentData, $parent, $fieldData, $metaData, $level + 1);
             }
         }
     }
     $result = array("data" => $fieldData, "metaData" => $metaData, "inherited" => $inherited);
     return $result;
 }
Пример #20
0
 /**
  * Returns array of languages allowed for viewing. If view languages are empty all languages are allowed.
  *
  * @return array|null
  */
 public function getAllowedLanguagesForViewingWebsiteTranslations()
 {
     $mergedWebsiteTranslationLanguagesView = $this->getMergedWebsiteTranslationLanguagesView();
     if (empty($mergedWebsiteTranslationLanguagesView)) {
         return Tool::getValidLanguages();
     } else {
         return $mergedWebsiteTranslationLanguagesView;
     }
 }
Пример #21
0
 /**
  * @return null|\Pimcore\Translate|\Pimcore\Translate\Website
  * @throws \Zend_Exception
  */
 public function initTranslation()
 {
     $translate = null;
     if (\Zend_Registry::isRegistered("Zend_Translate")) {
         $t = \Zend_Registry::get("Zend_Translate");
         // this check is necessary for the case that a document is rendered within an admin request
         // example: send test newsletter
         if ($t instanceof \Pimcore\Translate) {
             $translate = $t;
         }
     }
     if (!$translate) {
         // setup \Zend_Translate
         try {
             $locale = \Zend_Registry::get("Zend_Locale");
             $translate = new \Pimcore\Translate\Website($locale);
             if (Tool::isValidLanguage($locale)) {
                 $translate->setLocale($locale);
             } else {
                 \Logger::error("You want to use an invalid language which is not defined in the system settings: " . $locale);
                 // fall back to the first (default) language defined
                 $languages = Tool::getValidLanguages();
                 if ($languages[0]) {
                     \Logger::error("Using '" . $languages[0] . "' as a fallback, because the language '" . $locale . "' is not defined in system settings");
                     $translate = new \Pimcore\Translate\Website($languages[0]);
                     // reinit with new locale
                     $translate->setLocale($languages[0]);
                 } else {
                     throw new \Exception("You have not defined a language in the system settings (Website -> Frontend-Languages), please add at least one language.");
                 }
             }
             // register the translator in \Zend_Registry with the key "\Zend_Translate" to use the translate helper for \Zend_View
             \Zend_Registry::set("Zend_Translate", $translate);
         } catch (\Exception $e) {
             \Logger::error("initialization of Pimcore_Translate failed");
             \Logger::error($e);
         }
     }
     return $translate;
 }
Пример #22
0
 /**
  * save rule config
  */
 public function saveAction()
 {
     // send json respone
     $return = array('success' => false, 'message' => '');
     // save rule config
     try {
         $data = json_decode($this->getParam('data'));
         $rule = OnlineShop_Framework_Impl_Pricing_Rule::getById((int) $this->getParam('id'));
         // apply basic settings
         $rule->setBehavior($data->settings->behavior)->setActive((bool) $data->settings->active);
         // apply lang fields
         foreach (\Pimcore\Tool::getValidLanguages() as $lang) {
             $rule->setLabel($data->settings->{'label.' . $lang}, $lang);
             $rule->setDescription($data->settings->{'description.' . $lang}, $lang);
         }
         // create root condition
         $rootContainer = new stdClass();
         $rootContainer->parent = null;
         $rootContainer->operator = null;
         $rootContainer->type = 'Bracket';
         $rootContainer->conditions = array();
         // create a tree from the flat structure
         $currentContainer = $rootContainer;
         foreach ($data->conditions as $settings) {
             // handle brackets
             if ($settings->bracketLeft == true) {
                 $newContainer = new stdClass();
                 $newContainer->parent = $currentContainer;
                 $newContainer->type = 'Bracket';
                 $newContainer->conditions = array();
                 // move condition from current item to bracket item
                 $newContainer->operator = $settings->operator;
                 $settings->operator = null;
                 $currentContainer->conditions[] = $newContainer;
                 $currentContainer = $newContainer;
             }
             $currentContainer->conditions[] = $settings;
             if ($settings->bracketRight == true) {
                 $old = $currentContainer;
                 $currentContainer = $currentContainer->parent;
                 unset($old->parent);
             }
         }
         // create rule condition
         $condition = OnlineShop_Framework_Factory::getInstance()->getPricingManager()->getCondition($rootContainer->type);
         $condition->fromJSON(json_encode($rootContainer));
         $rule->setCondition($condition);
         // save action
         $arrActions = array();
         foreach ($data->actions as $setting) {
             $action = OnlineShop_Framework_Factory::getInstance()->getPricingManager()->getAction($setting->type);
             $action->fromJSON(json_encode($setting));
             $arrActions[] = $action;
         }
         $rule->setActions($arrActions);
         // save rule
         $rule->save();
         // finish
         $return['success'] = true;
         $return['id'] = $rule->getId();
     } catch (Exception $e) {
         $return['message'] = $e->getMessage();
     }
     // send respone
     $this->_helper->json($return);
 }
Пример #23
0
         ?>
 <?php 
     } else {
         if ($definition instanceof Object\ClassDefinition\Data\Classificationstore) {
             /** @var $storedata Object\Classificationstore */
             $storedata = $definition->getVersionPreview($this->object->getValueForFieldName($fieldName));
             if (!$storedata) {
                 continue;
             }
             $activeGroups = $storedata->getActiveGroups();
             if (!$activeGroups) {
                 continue;
             }
             $languages = array("default");
             if ($definition->isLocalized()) {
                 $languages = array_merge($languages, \Pimcore\Tool::getValidLanguages());
             }
             foreach ($activeGroups as $activeGroupId => $enabled) {
                 if (!$enabled) {
                     continue;
                 }
                 /** @var $groupDefinition Object\Classificationstore\GroupConfig */
                 $groupDefinition = Pimcore\Model\Object\Classificationstore\GroupConfig::getById($activeGroupId);
                 if (!$groupDefinition) {
                     continue;
                 }
                 /** @var $keyGroupRelation Object\Classificationstore\KeyGroupRelation */
                 $keyGroupRelations = $groupDefinition->getRelations();
                 foreach ($keyGroupRelations as $keyGroupRelation) {
                     $keyDef = Object\Classificationstore\Service::getFieldDefinitionFromJson(json_decode($keyGroupRelation->getDefinition()), $keyGroupRelation->getType());
                     if (!$keyDef) {
Пример #24
0
 /**
  * @param $name
  * @param $value
  * @param null $language
  * @return void
  */
 public function setLocalizedValue($name, $value, $language = null)
 {
     if (self::$strictMode) {
         if (!$language || !in_array($language, Tool::getValidLanguages())) {
             throw new \Exception("Language " . $language . " not accepted in strict mode");
         }
     }
     $language = $this->getLanguage($language);
     if (!$this->languageExists($language)) {
         $this->items[$language] = [];
     }
     $contextInfo = $this->getContext();
     if ($contextInfo && $contextInfo["containerType"] == "block") {
         $classId = $contextInfo["classId"];
         $containerDefinition = ClassDefinition::getById($classId);
         $blockDefinition = $containerDefinition->getFieldDefinition($contextInfo["fieldname"]);
         $fieldDefinition = $blockDefinition->getFieldDefinition("localizedfields");
     } else {
         if ($contextInfo && $contextInfo["containerType"] == "fieldcollection") {
             $containerKey = $contextInfo["containerKey"];
             $containerDefinition = Fieldcollection\Definition::getByKey($containerKey);
         } else {
             $containerDefinition = $this->getObject()->getClass();
         }
         $localizedFieldDefinition = $containerDefinition->getFieldDefinition("localizedfields");
         $fieldDefinition = $localizedFieldDefinition->getFieldDefinition($name);
     }
     if (method_exists($fieldDefinition, "preSetData")) {
         $value = $fieldDefinition->preSetData($this, $value, ["language" => $language, "name" => $name]);
     }
     $this->items[$language][$name] = $value;
     return $this;
 }
Пример #25
0
 public function importTranslations()
 {
     foreach (Tool::getValidLanguages() as $lang) {
         $src = sprintf('%s/i18n/%s.csv', $this->baseDir, $lang);
         $csv = new \Csv_Reader($src, new \Csv_Dialect(['delimiter' => ',', 'quotechar' => '"']));
         foreach ($csv as $row) {
             $t = Translation\Website::getByKey($row[0], true);
             $t->addTranslation($lang, $row[1]);
             $t->save();
         }
     }
 }
 /**
  * Rewrites id from source to target, $idMapping contains
  * array(
  *  "document" => array(
  *      SOURCE_ID => TARGET_ID,
  *      SOURCE_ID => TARGET_ID
  *  ),
  *  "object" => array(...),
  *  "asset" => array(...)
  * )
  * @param mixed $object
  * @param array $idMapping
  * @param array $params
  * @return Element\ElementInterface
  */
 public function rewriteIds($object, $idMapping, $params = array())
 {
     $data = $this->getDataFromObjectParam($object, $params);
     $validLanguages = Tool::getValidLanguages();
     foreach ($validLanguages as $language) {
         foreach ($this->getFieldDefinitions() as $fd) {
             if (method_exists($fd, "rewriteIds")) {
                 $d = $fd->rewriteIds($data, $idMapping, array("language" => $language));
                 $data->setLocalizedValue($fd->getName(), $d, $language);
             }
         }
     }
     return $data;
 }
Пример #27
0
 /**
  * Event that handles the update of a Document
  *
  * @param $e \Zend_EventManager_Event
  * @throws Exception
  * @throws \Zend_Exception
  */
 public function updateDocument($e)
 {
     // Check if this function is not in progress
     if (\Zend_Registry::isRegistered('Multilingual_' . __FUNCTION__) && \Zend_Registry::get('Multilingual_' . __FUNCTION__) == 1) {
         return;
     }
     // Lock this event-trigger
     \Zend_Registry::set('Multilingual_' . __FUNCTION__, 1);
     /**@var Document\Page $sourceDocument */
     $sourceDocument = $e->getTarget();
     // Get current language
     $sourceLanguage = $sourceDocument->getProperty('language');
     // Get the Source Parent (we have to do it this way, due to a bug in Pimcore)
     $sourceParent = Document::getById($sourceDocument->getParentId());
     // Update SourcePath in Multilingual table
     $t = new Keys();
     $row = $t->fetchRow('document_id = ' . $sourceDocument->getId());
     $t->update(array('sourcePath' => $sourceDocument->getFullPath()), 'sourcePath = "' . $row->sourcePath . '"');
     // Update each language
     $languages = Tool::getValidLanguages();
     foreach ($languages as $language) {
         if ($language != $sourceLanguage) {
             // Find the target document
             /** @var Document $targetDocument */
             $targetDocument = \Multilingual\Document::getDocumentInOtherLanguage($sourceDocument, $language);
             if ($targetDocument) {
                 // Find the parent
                 // If the parent is the root, document, no need to do a lookup
                 if ($sourceParent->getId() == 1) {
                     $targetParent = $sourceParent;
                 } else {
                     $targetParent = \Multilingual\Document::getDocumentInOtherLanguage($sourceParent, $language);
                 }
                 // Only sync properties when it is allowed
                 if (!$targetDocument->hasProperty('doNotSyncProperties') && !$sourceDocument->hasProperty('doNotSyncProperties')) {
                     $typeHasChanged = false;
                     // Set document type (for conversion)
                     if ($targetDocument->getType() != $sourceDocument->getType()) {
                         $typeHasChanged = true;
                         $targetDocument->setType($sourceDocument->getType());
                         if ($targetDocument->getType() == "hardlink" || $targetDocument->getType() == "folder") {
                             // remove navigation settings
                             foreach (["name", "title", "target", "exclude", "class", "anchor", "parameters", "relation", "accesskey", "tabindex"] as $propertyName) {
                                 $targetDocument->removeProperty("navigation_" . $propertyName);
                             }
                         }
                         // overwrite internal store to avoid "duplicate full path" error
                         \Zend_Registry::set("document_" . $targetDocument->getId(), $targetDocument);
                     }
                     // Set the controller the same
                     $editableDocumentTypes = array('page', 'email', 'snippet');
                     if (!$typeHasChanged && in_array($sourceDocument->getType(), $editableDocumentTypes)) {
                         /** @var Document\Page $targetDocument */
                         $targetDocument->setController($sourceDocument->getController());
                         $targetDocument->setAction($sourceDocument->getAction());
                     }
                     // Set the properties the same
                     // But only if they have not been added already
                     $sourceProperties = $sourceDocument->getProperties();
                     /** @var string $key
                      * @var Property $value
                      */
                     foreach ($sourceProperties as $key => $value) {
                         if (strpos($key, 'navigation_') === false) {
                             if (!$targetDocument->hasProperty($key)) {
                                 $propertyValue = $value->getData();
                                 if ($value->getType() == 'document') {
                                     $propertyValue = \Multilingual\Document::getDocumentIdInOtherLanguage($value->getData()->getId(), $language);
                                 }
                                 $targetDocument->setProperty($key, $value->getType(), $propertyValue, false, $value->getInheritable());
                             }
                         }
                     }
                 }
                 // Make sure the parent stays the same
                 $targetDocument->setParent($targetParent);
                 $targetDocument->setParentId($targetParent->getId());
                 $targetDocument->setPath($targetParent->getFullPath() . '/');
                 // Make sure the index stays the same
                 $targetDocument->setIndex($sourceDocument->getIndex());
                 // Make sure the index follows in all the pages at current level
                 $list = new Document\Listing();
                 $list->setCondition("parentId = ? AND id != ?", array($targetParent->getId(), $sourceDocument->getId()));
                 $list->setOrderKey("index");
                 $list->setOrder("asc");
                 $childsList = $list->load();
                 $count = 0;
                 /** @var Document $child */
                 foreach ($childsList as $child) {
                     if ($count == intval($targetDocument->getIndex())) {
                         $count++;
                     }
                     $child->saveIndex($count);
                     $count++;
                 }
                 $targetDocument->save();
             }
         }
     }
     // Unlock this event-trigger
     \Zend_Registry::set('Multilingual_' . __FUNCTION__, 0);
 }
Пример #28
0
 /**
  * @param $locale
  * @param $messageId
  * @return mixed
  */
 protected function createEmptyTranslation($locale, $messageId)
 {
     $messageIdOriginal = $messageId;
     $messageId = mb_strtolower($messageId);
     // don't create translation if it's just empty
     if (array_key_exists($messageId, $this->_translate[$locale])) {
         return;
     }
     $class = self::getBackend();
     // no translation found create key
     if (Tool::isValidLanguage($locale)) {
         try {
             $t = $class::getByKey($messageId);
             $t->addTranslation($locale, "");
         } catch (\Exception $e) {
             $t = new $class();
             $t->setKey($messageId);
             // add all available languages
             $availableLanguages = (array) Tool::getValidLanguages();
             foreach ($availableLanguages as $language) {
                 $t->addTranslation($language, "");
             }
         }
         $t->save();
     }
     // put it into the store, otherwise when there are more calls to the same key during one process
     // the key would be inserted/updated several times, what would be redundant
     $this->_translate[$locale][$messageId] = $messageIdOriginal;
 }
Пример #29
0
 public function getCurrentUserAction()
 {
     header("Content-Type: text/javascript");
     $user = $this->getUser();
     $list = new User\Permission\Definition\Listing();
     $definitions = $list->load();
     foreach ($definitions as $definition) {
         $user->setPermission($definition->getKey(), $user->isAllowed($definition->getKey()));
     }
     // unset confidential informations
     $userData = object2array($user);
     $contentLanguages = Tool\Admin::reorderWebsiteLanguages($user, Tool::getValidLanguages());
     $userData["contentLanguages"] = $contentLanguages;
     unset($userData["password"]);
     echo "pimcore.currentuser = " . \Zend_Json::encode($userData);
     exit;
 }
Пример #30
0
 public function translationsAction()
 {
     $admin = $this->getParam("admin");
     if ($admin) {
         $class = "\\Pimcore\\Model\\Translation\\Admin";
         $this->checkPermission("translations_admin");
     } else {
         $class = "\\Pimcore\\Model\\Translation\\Website";
         $this->checkPermission("translations");
     }
     $tableName = call_user_func($class . "\\Dao::getTableName");
     // clear translation cache
     Translation\Website::clearDependentCache();
     if ($this->getParam("data")) {
         $data = \Zend_Json::decode($this->getParam("data"));
         if ($this->getParam("xaction") == "destroy") {
             $data = \Zend_Json::decode($this->getParam("data"));
             if (\Pimcore\Tool\Admin::isExtJS6()) {
                 $t = $class::getByKey($data["key"]);
             } else {
                 $t = $class::getByKey($data);
             }
             $t->delete();
             $this->_helper->json(["success" => true, "data" => []]);
         } elseif ($this->getParam("xaction") == "update") {
             $t = $class::getByKey($data["key"]);
             foreach ($data as $key => $value) {
                 if ($key != "key") {
                     $t->addTranslation($key, $value);
                 }
             }
             if ($data["key"]) {
                 $t->setKey($data["key"]);
             }
             $t->setModificationDate(time());
             $t->save();
             $return = array_merge(["key" => $t->getKey(), "creationDate" => $t->getCreationDate(), "modificationDate" => $t->getModificationDate()], $t->getTranslations());
             $this->_helper->json(["data" => $return, "success" => true]);
         } elseif ($this->getParam("xaction") == "create") {
             try {
                 $t = $class::getByKey($data["key"]);
             } catch (\Exception $e) {
                 $t = new $class();
                 $t->setKey($data["key"]);
                 $t->setCreationDate(time());
                 $t->setModificationDate(time());
                 foreach (Tool::getValidLanguages() as $lang) {
                     $t->addTranslation($lang, "");
                 }
                 $t->save();
             }
             $return = array_merge(["key" => $t->getKey(), "creationDate" => $t->getCreationDate(), "modificationDate" => $t->getModificationDate()], $t->getTranslations());
             $this->_helper->json(["data" => $return, "success" => true]);
         }
     } else {
         // get list of types
         if ($admin) {
             $list = new Translation\Admin\Listing();
         } else {
             $list = new Translation\Website\Listing();
         }
         $validLanguages = $this->getUser()->getAllowedLanguagesForViewingWebsiteTranslations();
         $list->setOrder("asc");
         $list->setOrderKey($tableName . ".key", false);
         $sortingSettings = \Pimcore\Admin\Helper\QueryParams::extractSortingSettings($this->getAllParams());
         $joins = [];
         if ($sortingSettings['orderKey']) {
             if (in_array($sortingSettings['orderKey'], $validLanguages)) {
                 $joins[] = ["language" => $sortingSettings['orderKey']];
                 $list->setOrderKey($sortingSettings['orderKey']);
             } else {
                 $list->setOrderKey($tableName . "." . $sortingSettings['orderKey'], false);
             }
         }
         if ($sortingSettings['order']) {
             $list->setOrder($sortingSettings['order']);
         }
         $list->setLimit($this->getParam("limit"));
         $list->setOffset($this->getParam("start"));
         $condition = $this->getGridFilterCondition($tableName);
         $filters = $this->getGridFilterCondition($tableName, true);
         if ($filters) {
             $joins = array_merge($joins, $filters["joins"]);
         }
         if ($condition) {
             $list->setCondition($condition);
         }
         $this->extendTranslationQuery($joins, $list, $tableName, $filters);
         $list->load();
         $translations = [];
         foreach ($list->getTranslations() as $t) {
             $translations[] = array_merge($t->getTranslations(), ["key" => $t->getKey(), "creationDate" => $t->getCreationDate(), "modificationDate" => $t->getModificationDate()]);
         }
         $this->_helper->json(["data" => $translations, "success" => true, "total" => $list->getTotalCount()]);
     }
 }