Esempio n. 1
0
 public function getDataFromInputPostProcess($data = null)
 {
     if (!$data) {
         $data =& $this->_objData;
     }
     if (!$data) {
         return $data;
     }
     if (isset($data['status'])) {
         $data['status'] = 'A';
     } else {
         $data['status'] = 'I';
     }
     if (!isset($data['is_locked'])) {
         $data['is_locked'] = 0;
     }
     if (!isset($data['is_leaf'])) {
         $data['is_leaf'] = 0;
     }
     $languages = ZLanguage::getInstalledLanguages();
     foreach ($languages as $lang) {
         if (!isset($data['display_name'][$lang]) || !$data['display_name'][$lang]) {
             $data['display_name'][$lang] = $data['name'];
         }
     }
     $this->_objData = $data;
     return $data;
 }
Esempio n. 2
0
 /**
  * Update Config
  */
 public function updateconfig()
 {
     // Confirm the forms authorisation key
     $this->checkCsrfToken();
     // Security check
     $this->throwForbiddenUnless(SecurityUtil::checkPermission($this->name . '::', '::', ACCESS_ADMIN));
     // retrieve the associative preferences array
     $prefs = FormUtil::getPassedValue('preferences', null, 'POST');
     $languages = ZLanguage::getInstalledLanguages();
     // now for each perference entry, set the appropriate module variable
     foreach ($languages as $language) {
         ModUtil::setVar('AddressBook', 'abtitle_' . $language, isset($prefs['abtitle_' . $language]) ? $prefs['abtitle_' . $language] : '');
         ModUtil::setVar('AddressBook', 'abmetatitle_' . $language, isset($prefs['abmetatitle_' . $language]) ? $prefs['abmetatitle_' . $language] : '');
         ModUtil::setVar('AddressBook', 'abmetadescription_' . $language, isset($prefs['abmetadescription_' . $language]) ? $prefs['abmetadescription_' . $language] : '');
         ModUtil::setVar('AddressBook', 'abmetakeyword_' . $language, isset($prefs['abmetakeyword_' . $language]) ? $prefs['abmetakeyword_' . $language] : '');
         ModUtil::setVar('AddressBook', 'custom_tab_' . $language, isset($prefs['custom_tab_' . $language]) ? $prefs['custom_tab_' . $language] : '');
     }
     ModUtil::setVar('AddressBook', 'globalprotect', isset($prefs['globalprotect']) ? $prefs['globalprotect'] : 0);
     ModUtil::setVar('AddressBook', 'allowprivate', isset($prefs['allowprivate']) ? $prefs['allowprivate'] : 0);
     ModUtil::setVar('AddressBook', 'use_prefix', isset($prefs['use_prefix']) ? $prefs['use_prefix'] : 0);
     ModUtil::setVar('AddressBook', 'use_img', isset($prefs['use_img']) ? $prefs['use_img'] : 0);
     ModUtil::setVar('AddressBook', 'images_dir', isset($prefs['images_dir']) ? $prefs['images_dir'] : 'userdata/Addressbook');
     ModUtil::setVar('AddressBook', 'images_manager', isset($prefs['images_manager']) ? $prefs['images_manager'] : 'kcfinder');
     ModUtil::setVar('AddressBook', 'google_api_key', isset($prefs['google_api_key']) ? $prefs['google_api_key'] : '');
     ModUtil::setVar('AddressBook', 'google_zoom', isset($prefs['google_zoom']) ? $prefs['google_zoom'] : 15);
     ModUtil::setVar('AddressBook', 'itemsperpage', $prefs['itemsperpage'] > 1 ? $prefs['itemsperpage'] : 30);
     ModUtil::setVar('AddressBook', 'addressbooktype', isset($prefs['addressbooktype']) ? $prefs['addressbooktype'] : 1);
     ModUtil::setVar('AddressBook', 'showabcfilter', isset($prefs['showabcfilter']) ? $prefs['showabcfilter'] : 0);
     // redirect back to to main admin page
     LogUtil::registerStatus($this->__('Done! Configuration saved.'));
     return System::redirect(ModUtil::url('AddressBook', 'admin', 'main'));
 }
Esempio n. 3
0
    public function edit($args = array())
    {
        $this->checkAjaxToken();

        $mode = $this->request->request->get('mode', 'new');
        $accessLevel = $mode == 'edit' ? ACCESS_EDIT : ACCESS_ADD;
        $this->throwForbiddenUnless(SecurityUtil::checkPermission('Categories::', '::', $accessLevel));

        $cid = isset($args['cid']) ? $args['cid'] : $this->request->request->get('cid', 0);
        $parent = isset($args['parent']) ? $args['parent'] : $this->request->request->get('parent', 1);
        $validationErrors = FormUtil::getValidationErrors();
        $editCat = '';

        $languages = ZLanguage::getInstalledLanguages();

        if ($validationErrors) {
            $category = new Categories_DBObject_Category(DBObject::GET_FROM_VALIDATION_FAILED); // need this for validation info
            $editCat = $category->get();
            $validationErrors = $validationErrors['category'];
        } else {
            // indicates that we're editing
            if ($mode == 'edit') {
                if (!$cid) {
                    return new Zikula_Response_Ajax_BadData($this->__('Error! Cannot determine valid \'cid\' for edit mode in \'Categories_admin_edit\'.'));
                }
                $category = new Categories_DBObject_Category();
                $editCat = $category->select($cid);
                $this->throwNotFoundUnless($editCat, $this->__('Sorry! No such item found.'));
            } else {
                // someone just pressen 'new' -> populate defaults
                $category = new Categories_DBObject_Category(); // need this for validation info
                $editCat['sort_value'] = '0';
                $editCat['parent_id'] = $parent;
            }
        }

        $attributes = isset($editCat['__ATTRIBUTES__']) ? $editCat['__ATTRIBUTES__'] : array();

        Zikula_AbstractController::configureView();
        $this->view->setCaching(Zikula_View::CACHE_DISABLED);

        $this->view->assign('mode', $mode)
            ->assign('category', $editCat)
            ->assign('attributes', $attributes)
            ->assign('languages', $languages)
            ->assign('validation', $category->_objValidation);

        $result = array(
            'action' => $mode == 'new' ? 'add' : 'edit',
            'result' => $this->view->fetch('categories_adminajax_edit.tpl'),
            'validationErrors' => $validationErrors
        );
        if ($validationErrors) {
            return new Zikula_Response_Ajax_BadData($validationErrors, $result);
        }

        return new Zikula_Response_Ajax($result);
    }
Esempio n. 4
0
 public function setInstalled()
 {
     $installed_languages = \ZLanguage::getInstalledLanguages();
     $installed = [];
     foreach ($installed_languages as $langCode) {
         $installed[$langCode]['name'] = \ZLanguage::getLanguageName($langCode);
         $installed[$langCode]['data'] = new \ZLocale($langCode);
     }
     $this->installed = $installed;
     return;
 }
Esempio n. 5
0
 /**
  * Reloads the multilingual routing settings by reading system variables and checking installed languages.
  *
  * @param array $args No arguments available.
  *
  * @return bool
  */
 public function reloadMultilingualRoutingSettings($args)
 {
     unset($args);
     $defaultLocale = \System::getVar('language_i18n', $this->getContainer()->getParameter('locale'));
     $installedLanguages = \ZLanguage::getInstalledLanguages();
     $isRequiredLangParameter = \System::getVar('languageurl', 0);
     $configDumper = $this->get('zikula.dynamic_config_dumper');
     $configDumper->setConfiguration('jms_i18n_routing', array('default_locale' => $defaultLocale, 'locales' => $installedLanguages, 'strategy' => $isRequiredLangParameter ? 'prefix' : 'prefix_except_default'));
     $cacheClearer = $this->get('zikula.cache_clearer');
     $cacheClearer->clear('symfony');
     return true;
 }
Esempio n. 6
0
 public function isNecessary()
 {
     if (version_compare(ZIKULACORE_CURRENT_INSTALLED_VERSION, UpgraderController::ZIKULACORE_MINIMUM_UPGRADE_VERSION, '<')) {
         throw new AbortStageException(__f('The current installed version of Zikula is reporting (%1$s). You must upgrade to version (%2$s) before you can use this upgrade.', array(ZIKULACORE_CURRENT_INSTALLED_VERSION, UpgraderController::ZIKULACORE_MINIMUM_UPGRADE_VERSION)));
     }
     // make sure selected language is installed
     if (!in_array(\ZLanguage::getLanguageCode(), \ZLanguage::getInstalledLanguages())) {
         \System::setVar('language_i18n', 'en');
         \System::setVar('language', 'eng');
         \System::setVar('locale', 'en');
         \ZLanguage::setLocale('en');
     }
     return true;
 }
function smarty_modifier_zikularoutesmodulePathToString($path, \Zikula\RoutesModule\Entity\RouteEntity $route)
{
    $options = $route->getOptions();
    $prefix = '';
    if (isset($options['i18n_prefix'])) {
        $prefix = '/' . $options['i18n_prefix'];
    }
    if (!isset($options['i18n']) || $options['i18n']) {
        $languages = ZLanguage::getInstalledLanguages();
        $isRequiredLangParam = ZLanguage::isRequiredLangParam();
        if (!$isRequiredLangParam) {
            $defaultLanguage = System::getVar('language_i18n');
            unset($languages[array_search($defaultLanguage, $languages)]);
        }
        if (count($languages) > 0) {
            $prefix = ($isRequiredLangParam ? "/" : "{/") . implode('|', $languages) . ($isRequiredLangParam ? "" : "}");
        }
    }
    $prefix = \DataUtil::formatForDisplay($prefix);
    $path = \DataUtil::formatForDisplay($route->getPathWithBundlePrefix());
    $container = \ServiceUtil::getManager();
    $path = preg_replace_callback('#%(.*?)%#', function ($matches) use($container) {
        return "<abbr title=\"" . \DataUtil::formatForDisplay($matches[0]) . "\">" . \DataUtil::formatForDisplay($container->getParameter($matches[1])) . "</abbr>";
    }, $path);
    $defaults = $route->getDefaults();
    $requirements = $route->getRequirements();
    $dom = ZLanguage::getModuleDomain('ZikulaRoutesModule');
    $path = preg_replace_callback('#{(.*?)}#', function ($matches) use($container, $defaults, $requirements, $dom) {
        $title = "";
        if (isset($defaults[$matches[1]])) {
            $title .= __f('Default: %s', array(\DataUtil::formatForDisplay($defaults[$matches[1]])), $dom);
        }
        if (isset($requirements[$matches[1]])) {
            if ($title != "") {
                $title .= " | ";
            }
            $title .= __f('Requirement: %s', array(\DataUtil::formatForDisplay($requirements[$matches[1]])), $dom);
        }
        if ($title == "") {
            return $matches[0];
        }
        return "<abbr title=\"{$title}\">" . $matches[0] . "</abbr>";
    }, $path);
    return "{$prefix}<strong>{$path}</strong>";
}
Esempio n. 8
0
 public function isNecessary()
 {
     $installedLanguages = \ZLanguage::getInstalledLanguages();
     if (count($installedLanguages) == 1) {
         $this->writeParams(array('locale' => $installedLanguages[0]));
         return false;
     } else {
         // see if the browser has a preference set
         $detector = new \ZLanguageBrowser($installedLanguages);
         $locale = $detector->discover();
         if ($locale !== false && in_array($locale, $installedLanguages)) {
             $this->writeParams(array('locale' => $locale));
             return false;
         } else {
             return true;
         }
     }
 }
Esempio n. 9
0
 /**
  * Dump the routes exposed to javascript to '/web/js/fos_js_routes.js'
  *
  * @param null $lang
  * @return string
  * @throws \Exception
  */
 public function dumpJsRoutes($lang = null)
 {
     // determine list of supported languages
     $langs = array();
     $installedLanguages = \ZLanguage::getInstalledLanguages();
     if (isset($lang) && in_array($lang, $installedLanguages)) {
         // use provided lang if available
         $langs = array($lang);
     } else {
         $multilingual = (bool) \System::getVar('multilingual', 0);
         if ($multilingual) {
             // get all available locales
             $langs = $installedLanguages;
         } else {
             // get only the default locale
             $langs = array(\System::getVar('language_i18n', 'en'));
             //$this->container->getParameter('locale');
         }
     }
     $errors = '';
     // force deletion of existing file
     $targetPath = sprintf('%s/../web/js/fos_js_routes.js', $this->container->getParameter('kernel.root_dir'));
     if (file_exists($targetPath)) {
         try {
             unlink($targetPath);
         } catch (\Exception $e) {
             $errors .= __f("Error: Could not delete '%s' because %s", array($targetPath, $e->getMessage()));
         }
     }
     foreach ($langs as $lang) {
         $command = new DumpCommand();
         $command->setContainer($this->container);
         $input = new ArrayInput(array('--locale' => $lang . I18nLoader::ROUTING_PREFIX));
         $output = new NullOutput();
         try {
             $command->run($input, $output);
         } catch (\RuntimeException $e) {
             $errors .= $e->getMessage() . ". ";
         }
     }
     return $errors;
 }
Esempio n. 10
0
 /**
  * modify block settings
  *
  * @param        array       $blockinfo     a blockinfo structure
  * @return       output      the bock form
  */
 public function modify($blockinfo)
 {
     // Break out options from our content field
     $vars = BlockUtil::varsFromContent($blockinfo['content']);
     $blockinfo['content'] = '';
     // Defaults
     if (empty($vars['displaymodules'])) {
         $vars['displaymodules'] = 0;
     }
     // template to use
     if (empty($vars['template'])) {
         $vars['template'] = 'blocks_block_extmenu.tpl';
     }
     // create default block variables
     if (!isset($vars['blocktitles'])) {
         $vars['blocktitles'] = array();
     }
     if (!isset($vars['links'])) {
         $vars['links'] = array();
     }
     if (!isset($vars['stylesheet'])) {
         $vars['stylesheet'] = '';
     }
     if (!isset($vars['menuid'])) {
         $vars['menuid'] = 0;
     }
     $languages = ZLanguage::getInstalledLanguages();
     $userlanguage = ZLanguage::getLanguageCode();
     // filter out invalid languages
     foreach ($vars['blocktitles'] as $k => $v) {
         if (!in_array($k, $languages)) {
             unset($vars['blocktitles'][$k]);
             unset($vars['links'][$k]);
         }
     }
     // check if the users wants to add a new link via the "Add current url" link in the block
     $addurl = FormUtil::getPassedValue('addurl', 0, 'GET');
     // or if we come from the normal "edit this block" link
     $fromblock = FormUtil::getPassedValue('fromblock', null, 'GET');
     $redirect = '';
     if ($addurl == 1) {
         // set a marker for redirection later on
         $newurl = System::serverGetVar('HTTP_REFERER');
         $redirect = urlencode($newurl);
         $newurl = str_replace(System::getBaseUrl(), '', $newurl);
         if (empty($newurl)) {
             $newurl = System::getHomepageUrl();
         }
         foreach ($languages as $singlelanguage) {
             $vars['links'][$singlelanguage][] = array('name' => $this->__('--New link--'), 'url' => $newurl, 'title' => $this->__('--New link--'), 'level' => 0, 'parentid' => null, 'image' => '', 'active' => 1);
         }
     } elseif (isset($fromblock)) {
         $redirect = urlencode(System::serverGetVar('HTTP_REFERER'));
     }
     // add new languages to the blocktitles and link arrays
     // we need to know which language has the most links, this language will be the "master"
     // for new languages to be added. this ensures that all links for the new language
     // are prepared.
     $link_master = array();
     foreach ($languages as $lang) {
         if (isset($vars['links'][$lang]) && count($link_master) < count($vars['links'][$lang])) {
             $link_master = $vars['links'][$lang];
         }
     }
     foreach ($languages as $lang) {
         // create an empty blocktitle string
         if (!array_key_exists($lang, $vars['blocktitles'])) {
             $vars['blocktitles'][$lang] = '';
         }
         if (!array_key_exists($lang, $vars['links'])) {
             $vars['links'][$lang] = $link_master;
         }
     }
     // menuitems are sorted by language per default for easier
     // access when showing them (which is more often necessary than
     // editing them), but for editing them we need them sorted by id
     $menuitems = array();
     foreach ($vars['links'] as $lang => $langlinks) {
         // langlinks now contains an array of links for a certain language
         // sorted by key=id
         foreach ($langlinks as $linkid => $link) {
             // pre zk1.2 check
             if (!isset($link['id'])) {
                 $link['id'] = $linkid;
             }
             $link['errors'] = array();
             $this->checkImage($link);
             $menuitems[$linkid][$lang] = $link;
         }
     }
     $vars['links'] = $menuitems;
     $this->view->setCaching(Zikula_View::CACHE_DISABLED);
     // assign the vars
     $this->view->assign($vars)->assign('languages', $languages)->assign('userlanguage', $userlanguage)->assign('redirect', $redirect)->assign('blockinfo', $blockinfo);
     // return the output
     return $this->view->fetch('blocks_block_extmenu_modify.tpl');
 }
Esempio n. 11
0
    /**
     * Show a form needed to create a new menu item
     * @author:     Albert Pérez Monfort (aperezm@xtec.cat)
     * @param:
     * @return:	The form needed to create a new item
     */
    public function new_sub($args) {
        // Get parameters from whatever input we need.
        $mid = FormUtil::getPassedValue('mid', isset($args['mid']) ? $args['mid'] : null, 'GETPOST');

        // Security check
        if (!SecurityUtil::checkPermission('IWmenu::', '::', ACCESS_ADMIN)) {
            throw new Zikula_Exception_Forbidden();
        }

        // Get a menu item
        if ($mid != null && $mid > 0) {
            $registre = ModUtil::apiFunc('IWmenu', 'admin', 'get', array('mid' => $mid));
            if (!$registre) {
                return LogUtil::registerError($this->__('Menu option not found'));
            }
        }

        // get the intranet groups
        $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
        $grups = ModUtil::func('IWmain', 'user', 'getAllGroups', array('plus' => $this->__('All'),
                    'less' => ModUtil::getVar('IWmyrole', 'rolegroup'),
                    'sv' => $sv));
        $grups[] = array('id' => '-1',
            'name' => $this->__('Unregistered'));

        // checks if the module IWwebbox is available in order to include the webbox as a target possibility
        $iwwebbox = (ModUtil::available('IWwebbox')) ? true : false;

        $filesPath = ModUtil::getVar('IWmain', 'documentRoot') . '/' . ModUtil::getVar('IWmenu', 'imagedir');
        $folderExists = (file_exists($filesPath)) ? true : false;
        $writeable = (is_writeable($filesPath)) ? true : false;
        $folder = $folderExists && $writeable;

        // get available languages
        $languages = ZLanguage::getInstalledLanguages();

        return $this->view->assign('mid', $mid)
                        ->assign('folder', $folder)
                        ->assign('iwwebbox', $iwwebbox)
                        ->assign('initImagePath', ModUtil::getVar('IWmenu', 'imagedir'))
                        ->assign('grups', $grups)
                        ->assign('languages', $languages)
                        ->fetch('IWmenu_admin_new_sub.htm');
    }
Esempio n. 12
0
    protected function newBlockPositions()
    {
        $positions = ModUtil::apiFunc('Blocks', 'user', 'getallpositions');

        // create the search block position if doesn't exists
        if (!isset($positions['search'])) {
            $searchpid = ModUtil::apiFunc('Blocks', 'admin', 'createposition', array('name' => 'search', 'description' => $this->__('Search block')));
        } else {
            $searchpid = $positions['search']['pid'];
        }

        // restores the search block if not present
        $dbtable      = DBUtil::getTables();
        $blockscolumn = $dbtable['blocks_column'];
        $searchblocks = DBUtil::selectObjectArray('blocks', "$blockscolumn[bkey] = 'Search'");

        if (empty($searchblocks)) {
            $block = array('bkey' => 'Search', 'collapsable' => 1, 'defaultstate' => 1, 'language' => '', 'mid' => ModUtil::getIdFromName('Search'), 'title' => $this->__('Search box'), 'description' => '', 'positions' => array($searchpid));
            $block['bid'] = ModUtil::apiFunc('Blocks', 'admin', 'create', $block);
            ModUtil::apiFunc('Blocks', 'admin', 'update', $block);
        } else {
            // assign the block to the search position
            $blockplacement = array('bid' => $searchblocks[0]['bid'], 'pid' => $searchpid);
            DBUtil::insertObject($blockplacement, 'block_placements');
        }

        // create new block positions if they don't exist
        if (!isset($positions['header'])) {
            $header = ModUtil::apiFunc('Blocks', 'admin', 'createposition', array('name' => 'header', 'description' => $this->__('Header block')));
        }
        if (!isset($positions['footer'])) {
            $footer = ModUtil::apiFunc('Blocks', 'admin', 'createposition', array('name' => 'footer', 'description' => $this->__('Footer block')));
        }
        if (!isset($positions['bottomnav'])) {
            $bottomnav = ModUtil::apiFunc('Blocks', 'admin', 'createposition', array('name' => 'bottomnav', 'description' => $this->__('Bottom navigation block')));
        }
        if (!isset($positions['topnav'])) {
            $topnav = ModUtil::apiFunc('Blocks', 'admin', 'createposition', array('name' => 'topnav', 'description' => $this->__('Top navigation block')));

            // Build content for the top navigation menu
            $languages = ZLanguage::getInstalledLanguages();
            $saveLanguage = ZLanguage::getLanguageCode();
            foreach ($languages as $lang) {
                ZLanguage::setLocale($lang);
                ZLanguage::bindCoreDomain();
                $topnavcontent = array();
                $topnavcontent['displaymodules'] = '0';
                $topnavcontent['stylesheet'] = 'extmenu.css';
                $topnavcontent['template'] = 'blocks_block_extmenu_topnav.tpl';
                $topnavcontent['blocktitles'][$lang] = $this->__('Top navigation');
                $topnavcontent['links'][$lang][] = array('name' => $this->__('Home'), 'url' => '{homepage}', 'title' => $this->__("Go to the site's home page"), 'level' => 0, 'parentid' => null, 'image' => '', 'active' => '1');
                $topnavcontent['links'][$lang][] = array('name' => $this->__('My Account'), 'url' => '{Users}', 'title' => $this->__('Go to your account panel'), 'level' => 0, 'parentid' => null, 'image' => '', 'active' => '1');
                $topnavcontent['links'][$lang][] = array('name' => $this->__('Site search'), 'url' => '{Search}', 'title' => $this->__('Search this site'), 'level' => 0, 'parentid' => null, 'image' => '', 'active' => '1');
            }

            ZLanguage::setLocale($saveLanguage);
            $topnavcontent = serialize($topnavcontent);
            $topnavblock = array('bkey' => 'Extmenu', 'collapsable' => 1, 'defaultstate' => 1, 'language' => '', 'mid' => ModUtil::getIdFromName('Blocks'), 'title' => $this->__('Top navigation'), 'description' => '', 'content' => $topnavcontent, 'positions' => array($topnav));
            $topnavblock['bid'] = ModUtil::apiFunc('Blocks', 'admin', 'create', $topnavblock);
            ModUtil::apiFunc('Blocks', 'admin', 'update', $topnavblock);
        }
    }
Esempio n. 13
0
 /**
  * Generate a module function URL.
  *
  * If the module is non-API compliant (type 1) then
  * a) $func is ignored.
  * b) $type=admin will generate admin.php?module=... and $type=user will generate index.php?name=...
  *
  * @param string       $modname The name of the module.
  * @param string       $type    The type of function to run.
  * @param string       $func    The specific function to run.
  * @param array        $args    The array of arguments to put on the URL.
  * @param boolean|null $ssl     Set to constant null,true,false $ssl = true not $ssl = 'true'  null - leave the current status untouched,
  *                                     true - create a ssl url, false - create a non-ssl url.
  * @param string         $fragment     The framgment to target within the URL.
  * @param boolean|null   $fqurl        Fully Qualified URL. True to get full URL, eg for Redirect, else gets root-relative path unless SSL.
  * @param boolean        $forcelongurl Force ModUtil::url to not create a short url even if the system is configured to do so.
  * @param boolean|string $forcelang    Force the inclusion of the $forcelang or default system language in the generated url.
  *
  * @return string Absolute URL for call.
  */
 public static function url($modname, $type = null, $func = null, $args = array(), $ssl = null, $fragment = null, $fqurl = null, $forcelongurl = false, $forcelang = false)
 {
     // define input, all numbers and booleans to strings
     $modname = isset($modname) ? (string) $modname : '';
     // note - when this legacy is to be removed, change method signature $type = null to $type making it a required argument.
     if (!$type) {
         if (System::isLegacyMode()) {
             $type = 'user';
             LogUtil::log('ModUtil::url() - $type is a required argument, you must specify it explicitly.', E_USER_DEPRECATED);
         } else {
             throw new UnexpectedValueException('ModUtil::url() - $type is a required argument, you must specify it explicitly.');
         }
     }
     // note - when this legacy is to be removed, change method signature $func = null to $func making it a required argument.
     if (!$func) {
         if (System::isLegacyMode()) {
             $func = 'main';
             LogUtil::log('ModUtil::url() - $func is a required argument, you must specify it explicitly.', E_USER_DEPRECATED);
         } else {
             throw new UnexpectedValueException('ModUtil::url() - $func is a required argument, you must specify it explicitly.');
         }
     }
     // validate
     if (!System::varValidate($modname, 'mod')) {
         return null;
     }
     // Remove from 1.4
     if (System::isLegacyMode() && $modname == 'Modules') {
         LogUtil::log(__('Warning! "Modules" module has been renamed to "Extensions".  Please update your ModUtil::url() or {modurl} calls with $module = "Extensions".'));
         $modname = 'Extensions';
     }
     //get the module info
     $modinfo = self::getInfo(self::getIDFromName($modname));
     // set the module name to the display name if this is present
     if (isset($modinfo['url']) && !empty($modinfo['url'])) {
         $modname = rawurlencode($modinfo['url']);
     }
     $entrypoint = System::getVar('entrypoint');
     $host = System::serverGetVar('HTTP_HOST');
     if (empty($host)) {
         return false;
     }
     $baseuri = System::getBaseUri();
     $https = System::serverGetVar('HTTPS');
     $shorturls = System::getVar('shorturls');
     $shorturlsstripentrypoint = System::getVar('shorturlsstripentrypoint');
     $shorturlsdefaultmodule = System::getVar('shorturlsdefaultmodule');
     // Don't encode URLs with escaped characters, like return urls.
     foreach ($args as $v) {
         if (!is_array($v)) {
             if (strpos($v, '%') !== false) {
                 $shorturls = false;
                 break;
             }
         } else {
             foreach ($v as $vv) {
                 if (is_array($vv)) {
                     foreach ($vv as $vvv) {
                         if (!is_array($vvv) && strpos($vvv, '%') !== false) {
                             $shorturls = false;
                             break;
                         }
                     }
                 } elseif (strpos($vv, '%') !== false) {
                     $shorturls = false;
                     break;
                 }
             }
             break;
         }
     }
     // Setup the language code to use
     if (is_array($args) && isset($args['lang'])) {
         if (in_array($args['lang'], ZLanguage::getInstalledLanguages())) {
             $language = $args['lang'];
         }
         unset($args['lang']);
     }
     if (!isset($language)) {
         $language = ZLanguage::getLanguageCode();
     }
     $language = $forcelang && in_array($forcelang, ZLanguage::getInstalledLanguages()) ? $forcelang : $language;
     // Only produce full URL when HTTPS is on or $ssl is set
     $siteRoot = '';
     if (isset($https) && $https == 'on' || $ssl != null || $fqurl == true) {
         $protocol = 'http' . ($https == 'on' && $ssl !== false || $ssl === true ? 's' : '');
         $secureDomain = System::getVar('secure_domain');
         $siteRoot = $protocol . '://' . ($secureDomain != '' ? $secureDomain : $host . $baseuri) . '/';
     }
     // Only convert type=user. Exclude links that append a theme parameter
     if ($shorturls && $type == 'user' && $forcelongurl == false) {
         if (isset($args['theme'])) {
             $theme = $args['theme'];
             unset($args['theme']);
         }
         // Module-specific Short URLs
         $url = self::apiFunc($modinfo['name'], 'user', 'encodeurl', array('modname' => $modname, 'type' => $type, 'func' => $func, 'args' => $args));
         if (empty($url)) {
             // depending on the settings, we have generic directory based short URLs:
             // [language]/[module]/[function]/[param1]/[value1]/[param2]/[value2]
             // [module]/[function]/[param1]/[value1]/[param2]/[value2]
             $vars = '';
             foreach ($args as $k => $v) {
                 if (is_array($v)) {
                     foreach ($v as $k2 => $w) {
                         if (is_numeric($w) || !empty($w)) {
                             // we suppress '', but allow 0 as value (see #193)
                             $vars .= '/' . $k . '[' . $k2 . ']/' . $w;
                             // &$k[$k2]=$w
                         }
                     }
                 } elseif (is_numeric($v) || !empty($v)) {
                     // we suppress '', but allow 0 as value (see #193)
                     $vars .= "/{$k}/{$v}";
                     // &$k=$v
                 }
             }
             $url = $modname . ($vars || $func != 'main' ? "/{$func}{$vars}" : '');
         }
         if ($modinfo && $shorturlsdefaultmodule && $shorturlsdefaultmodule == $modinfo['name']) {
             $pattern = '/^' . preg_quote($modinfo['url'], '/') . '\\//';
             $url = preg_replace($pattern, '', $url);
         }
         if (isset($theme)) {
             $url = rawurlencode($theme) . '/' . $url;
         }
         // add language param to short url
         if (ZLanguage::isRequiredLangParam() || $forcelang) {
             $url = "{$language}/" . $url;
         }
         if (!$shorturlsstripentrypoint) {
             $url = "{$entrypoint}/{$url}" . (!empty($query) ? '?' . $query : '');
         } else {
             $url = "{$url}" . (!empty($query) ? '?' . $query : '');
         }
     } else {
         // Regular stuff
         $urlargs = "module={$modname}&type={$type}&func={$func}";
         // add lang param to URL
         if (ZLanguage::isRequiredLangParam() || $forcelang) {
             $urlargs .= "&lang={$language}";
         }
         $url = "{$entrypoint}?{$urlargs}";
         if (!is_array($args)) {
             return false;
         } else {
             foreach ($args as $key => $value) {
                 if (is_array($value)) {
                     foreach ($value as $l => $w) {
                         if (is_numeric($w) || !empty($w)) {
                             // we suppress '', but allow 0 as value (see #193)
                             if (is_array($w)) {
                                 foreach ($w as $m => $n) {
                                     if (is_numeric($n) || !empty($n)) {
                                         $n = strpos($n, '%') !== false ? $n : urlencode($n);
                                         $url .= "&{$key}" . "[{$l}][{$m}]={$n}";
                                     }
                                 }
                             } else {
                                 $w = strpos($w, '%') !== false ? $w : urlencode($w);
                                 $url .= "&{$key}" . "[{$l}]={$w}";
                             }
                         }
                     }
                 } elseif (is_numeric($value) || !empty($value)) {
                     // we suppress '', but allow 0 as value (see #193)
                     $w = strpos($value, '%') !== false ? $value : urlencode($value);
                     $url .= "&{$key}={$value}";
                 }
             }
         }
     }
     if (isset($fragment)) {
         $url .= '#' . $fragment;
     }
     return $siteRoot . $url;
 }
Esempio n. 14
0
 /**
  * Process the display name of a category
  *
  * @param array $displayname The display name of the category.
  * @param array $name        The name of the category.
  *
  * @return array the processed display name.
  */
 public static function processCategoryDisplayName($displayname, $name)
 {
     $languages = \ZLanguage::getInstalledLanguages();
     foreach ($languages as $lang) {
         if (!isset($displayname[$lang]) || !$displayname[$lang]) {
             $displayname[$lang] = $name;
         }
     }
     return $displayname;
 }
Esempio n. 15
0
    /**
     * Return an array of items to show in the the user's account panel.
     *
     * @param mixed $args Not used.
     *
     * @return array Indexed array of items.
     */
    public function getAll($args)
    {
        $items = array();

        // Show change password action only if the account record contains a password, and the password is not the
        // special marker for an account created without a Users module authentication password.
        $pass = UserUtil::getVar('pass');
        if (!empty($pass) && ($pass != Users_Constant::PWD_NO_USERS_AUTHENTICATION)) {
            // show edit password link
            $items['1'] = array(
                'url'   => ModUtil::url($this->name, 'user', 'changePassword'),
                'module'=> $this->name,
                'title' => $this->__('Password changer'),
                'icon'  => 'password.png'
            );
        }

        // show edit email link if configured to manage email address
        if ($this->getVar('changeemail', true)) {
            $items['2'] = array(
                'url'   => ModUtil::url($this->name, 'user', 'changeEmail'),
                'module'=> $this->name,
                'title' => $this->__('E-mail address manager'),
                'icon'  => 'message.png'
            );
        }

        // check if the users block exists
        $blocks = ModUtil::apiFunc('Blocks', 'user', 'getall');
        $usersModuleID = ModUtil::getIdFromName($this->name);
        $found = false;
        if (is_array($blocks)) {
            foreach ($blocks as $block) {
                if (($block['mid'] == $usersModuleID) && ($block['bkey'] == 'user')) {
                    $found = true;
                    break;
                }
            }
        }

        if ($found) {
            $items['3'] = array(
                'url'   => ModUtil::url($this->name, 'user', 'usersBlock'),
                'module'=> $this->name,
                'title' => $this->__('Personal custom block'),
                'icon'  => 'folder_home.png'
            );
        }

        if (System::getVar('multilingual')) {
            if (count(ZLanguage::getInstalledLanguages()) > 1) {
                $items['4'] = array(
                    'url'   => ModUtil::url($this->name, 'user', 'changeLang'),
                    'module'=> $this->name,
                    'title' => $this->__('Language switcher'),
                    'icon'  => 'locale.png'
                );
            }
        }

        $items['5'] = array(
            'url'   => ModUtil::url($this->name, 'user', 'logout'),
            'module'=> $this->name,
            'title' => $this->__('Log out'),
            'icon'  => 'exit.png'
        );

        // Return the items
        return $items;
    }
Esempio n. 16
0
 /**
  * Decode the path string into a set of variable/value pairs.
  *
  * This API works in conjunction with the new short urls
  * system to extract a path based variable set into the Get, Post
  * and request superglobals.
  * A sample path is /modname/function/var1:value1.
  *
  * @return void
  */
 public static function queryStringDecode(Request $request)
 {
     if (self::isInstalling()) {
         return;
     }
     // Try to match a route first.
     // Make sure we have the correct request context.
     $requestContext = ServiceUtil::get('router.request_context');
     $requestContext->fromRequest($request);
     /** @var \Symfony\Component\Routing\Matcher\RequestMatcherInterface $router */
     $router = ServiceUtil::get('router');
     try {
         $parameters = $router->matchRequest($request);
         if (!isset($parameters['_zkModule']) || !isset($parameters['_zkType']) || !isset($parameters['_zkFunc'])) {
             // This might be the web profiler or another native bundle.
             return;
         }
         // The following block is needed as long as not every url is a route. To be removed when all legacy routing
         // is removed.
         if ($parameters['_route'] == 'zikularoutesmodule_redirectingcontroller_removetrailingslash') {
             $pathInfo = $request->getPathInfo();
             $requestUri = $request->getRequestUri();
             // Check if url without slash exists. If it doesn't exist, it will throw an exception which is caught
             // by the try->catch below.
             $url = str_replace($pathInfo, rtrim($pathInfo, ' /'), $requestUri);
             $router->match($url);
         }
         $modname = strtolower($parameters['_zkModule']);
         $type = strtolower($parameters['_zkType']);
         $func = strtolower($parameters['_zkFunc']);
         if (isset($parameters['_locale'])) {
             $lang = strtolower($parameters['_locale']);
             $request->query->set('lang', $lang);
             self::queryStringSetVar('lang', $lang);
         }
         $request->attributes->set('_zkModule', $modname);
         $request->attributes->set('_zkType', $type);
         $request->attributes->set('_zkFunc', $func);
         $request->query->set('module', $modname);
         $request->query->set('type', $type);
         $request->query->set('func', $func);
         self::queryStringSetVar('module', $modname);
         self::queryStringSetVar('type', $type);
         self::queryStringSetVar('func', $func);
         return;
     } catch (ResourceNotFoundException $e) {
         // This is an old style url.
     } catch (RouteNotFoundException $e) {
         // This is an old style url.
     } catch (MethodNotAllowedException $e) {
         // this is an old style url.
     }
     // get our base parameters to work out if we need to decode the url
     $module = FormUtil::getPassedValue('module', null, 'GETPOST', FILTER_SANITIZE_STRING);
     $func = FormUtil::getPassedValue('func', null, 'GETPOST', FILTER_SANITIZE_STRING);
     $type = FormUtil::getPassedValue('type', null, 'GETPOST', FILTER_SANITIZE_STRING);
     // check if we need to decode the url
     $shorturls = self::getVar('shorturls');
     if ($shorturls && empty($module) && empty($type) && empty($func)) {
         // user language is not set at this stage
         $lang = self::getVar('language_i18n', '');
         $customentrypoint = self::getVar('entrypoint');
         $expectEntrypoint = !self::getVar('shorturlsstripentrypoint');
         $root = empty($customentrypoint) ? 'index.php' : $customentrypoint;
         // check if we hit baseurl, e.g. domain.com/ and if we require the language URL
         // then we should redirect to the language URL.
         if (ZLanguage::isRequiredLangParam() && self::getCurrentUrl() == self::getBaseUrl()) {
             $uri = $expectEntrypoint ? "{$root}/{$lang}" : $lang;
             self::redirect(self::getBaseUrl() . $uri);
             self::shutDown();
         }
         // check if entry point is part of the URL expectation.  If so throw error if it's not present
         // since this URL is technically invalid.
         if ($expectEntrypoint && self::getCurrentUrl() != self::getBaseUrl() && strpos(self::getCurrentUrl(), self::getBaseUrl() . $root) !== 0) {
             $protocol = self::serverGetVar('SERVER_PROTOCOL');
             header("{$protocol} 404 Not Found");
             echo __('The requested URL cannot be found');
             self::shutDown();
         }
         if (!$expectEntrypoint && self::getCurrentUrl() == self::getBaseUrl() . $root) {
             self::redirect(self::getHomepageUrl(), array(), 302, true);
             self::shutDown();
         }
         if (!$expectEntrypoint && strpos(self::getCurrentUrl(), self::getBaseUrl() . $root) === 0) {
             $protocol = self::serverGetVar('SERVER_PROTOCOL');
             header("{$protocol} 404 Not Found");
             echo __('The requested URL cannot be found');
             self::shutDown();
         }
         // get base path to work out our current url
         $parsedURL = parse_url(self::getCurrentUri());
         // strip any unwanted content from the provided URL
         $tobestripped = array(self::getBaseUri(), "{$root}");
         $path = str_replace($tobestripped, '', $parsedURL['path']);
         $path = trim($path, '/');
         // split the path into a set of argument strings
         $args = explode('/', rtrim($path, '/'));
         // ensure that each argument is properly decoded
         foreach ($args as $k => $v) {
             $args[$k] = urldecode($v);
         }
         $modinfo = null;
         $frontController = $expectEntrypoint ? "{$root}/" : '';
         // if no arguments present
         if (!$args[0] && !isset($_GET['lang']) && !isset($_GET['theme'])) {
             // we are in the homepage, checks if language code is forced
             if (ZLanguage::getLangUrlRule() && $lang) {
                 // and redirect then
                 self::redirect(self::getCurrentUrl() . "/{$lang}", array(), 302, true);
                 self::shutDown();
             }
         } else {
             // check the existing shortURL parameters
             // validation of the first parameter as language code
             if (ZLanguage::isLangParam($args[0]) && in_array($args[0], ZLanguage::getInstalledLanguages())) {
                 // checks if the language is not enforced and this url is passing the default lang
                 if (!ZLanguage::getLangUrlRule() && $lang == $args[0]) {
                     // redirects the passed arguments without the default site language
                     array_shift($args);
                     foreach ($args as $k => $v) {
                         $args[$k] = urlencode($v);
                     }
                     self::redirect(self::getBaseUrl() . $frontController . ($args ? implode('/', $args) : ''), array(), 302, true);
                     self::shutDown();
                 }
                 self::queryStringSetVar('lang', $args[0], $request);
                 array_shift($args);
             } elseif (ZLanguage::getLangUrlRule()) {
                 // if the lang is forced, redirects the passed arguments plus the lang
                 foreach ($args as $k => $v) {
                     $args[$k] = urlencode($v);
                 }
                 $langTheme = isset($_GET['theme']) ? "{$lang}/{$_GET['theme']}" : $lang;
                 self::redirect(self::getBaseUrl() . $frontController . $langTheme . '/' . implode('/', $args), array(), 302, true);
                 self::shutDown();
             }
             // check if there are remaining arguments
             if ($args) {
                 // try the first argument as a module
                 $modinfo = ModUtil::getInfoFromName($args[0]);
                 if ($modinfo) {
                     array_shift($args);
                 }
             }
             // if that fails maybe it's a theme
             if ($args && !$modinfo) {
                 $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($args[0]));
                 if ($themeinfo) {
                     self::queryStringSetVar('theme', $themeinfo['name'], $request);
                     $request->attributes->set('_theme', $themeinfo['name']);
                     // now shift the vars and continue as before
                     array_shift($args);
                     if ($args) {
                         $modinfo = ModUtil::getInfoFromName($args[0]);
                         if ($modinfo) {
                             array_shift($args);
                         }
                     }
                 }
             }
             // if there are parameters (not homepage)
             // try to see if there's a default shortURLs module
             if ($args && !$modinfo) {
                 // add the default module handler into the code
                 $modinfo = ModUtil::getInfoFromName(self::getVar('shorturlsdefaultmodule'));
             }
         }
         // check if there is a module and a custom url handler for it
         // if not decode the url using the default handler
         if ($modinfo && $modinfo['type'] != 0) {
             // prepare the arguments to the module handler
             array_unshift($args, '');
             // support for 1.2- empty parameter due the initial explode
             array_unshift($args, $modinfo['url']);
             // set the REQUEST parameters
             self::queryStringSetVar('module', $modinfo['name'], $request);
             // the user.function name can be the second argument string, set a default
             // later the custom module handler (if exists) must setup a new one if needed
             self::queryStringSetVar('type', 'user', $request);
             if (isset($args[2])) {
                 self::queryStringSetVar('func', $args[2], $request);
             } else {
                 self::queryStringSetVar('func', 'main', $request);
             }
             if (!ModUtil::apiFunc($modinfo['name'], 'user', 'decodeurl', array('vars' => $args))) {
                 // any remaining arguments are specific to the module
                 $argscount = count($args);
                 for ($i = 3; $i < $argscount; $i = $i + 2) {
                     if (isset($args[$i]) && isset($args[$i + 1])) {
                         self::queryStringSetVar($args[$i], urldecode($args[$i + 1]), $request);
                     }
                 }
             }
         }
     }
     $module = ucfirst(FormUtil::getPassedValue('module', null, 'GETPOST', FILTER_SANITIZE_STRING));
     $func = ucfirst(FormUtil::getPassedValue('func', null, 'GETPOST', FILTER_SANITIZE_STRING));
     $type = ucfirst(FormUtil::getPassedValue('type', null, 'GETPOST', FILTER_SANITIZE_STRING));
     $arguments = array();
     if (!$module) {
         // set the start parameters
         $module = self::getVar('startpage');
         $type = self::getVar('starttype');
         $func = self::getVar('startfunc');
         $args = explode(',', self::getVar('startargs'));
         foreach ($args as $arg) {
             if (!empty($arg)) {
                 $argument = explode('=', $arg);
                 $arguments[$argument[0]] = $argument[1];
             }
         }
     } else {
         $arguments = $_GET;
         unset($arguments['module']);
         unset($arguments['type']);
         unset($arguments['func']);
     }
     if ($shorturls) {
         $request->query->replace($_GET);
     }
     $request->attributes->set('_zkModule', strtolower($module));
     // legacy - this is how they are received originally
     $request->attributes->set('_zkType', strtolower($type));
     // legacy - this is how they are received originally
     $request->attributes->set('_zkFunc', strtolower($func));
     // legacy - this is how they are received originally
     $request->attributes->set('_zkArgs', $arguments);
 }
Esempio n. 17
0
    /**
     * edit the main information of a form
     * @author:     Albert Pérez Monfort (aperezm@xtec.cat)
     * @param:	args   with the form identity
     * @return:	A form necessary to modify the form
     */
    public function edit($args) {
        $fid = FormUtil::getPassedValue('fid', isset($args['fid']) ? $args['fid'] : null, 'POST');
        $aio = FormUtil::getPassedValue('aio', isset($args['aio']) ? $args['aio'] : null, 'POST');
        // Security check
        if (!SecurityUtil::checkPermission('IWforms::', "::", ACCESS_ADMIN)) {
            throw new Zikula_Exception_Forbidden();
        }
        //Get item
        $item = ModUtil::apiFunc('IWforms', 'user', 'getFormDefinition', array('fid' => $fid));
        if ($item == false) {
            LogUtil::registerError($this->__('Could not find form'));
            return System::redirect(ModUtil::url('IWforms', 'admin', 'main'));
        }
        //get all categories
        $categories = ModUtil::apiFunc('IWforms', 'user', 'getAllCategories');
        global $Intraweb;
        $multizk = (isset($GLOBALS['ZConfig']['Multisites']['multi']) && $GLOBALS['ZConfig']['Multisites']['multi'] == 1) ? 1 : 0;

        $filesFolder = ModUtil::getVar('IWmain', 'documentRoot') . '/' . ModUtil::getVar('IWforms', 'attached');

        $languages = ZLanguage::getInstalledLanguages();
        $languagesArray = array();
        foreach ($languages as $lang) {
            $languagesArray[] = array('code' => $lang,
                'name' => ZLanguage::getLanguageName($lang),
            );
        }

        $fields = ModUtil::apiFunc('IWforms', 'user', 'getAllFormFields', array('fid' => $fid));

        return $this->view->assign('cats', $categories)
                        ->assign('aio', $aio)
                        ->assign('item', $item)
                        ->assign('multizk', $multizk)
                        ->assign('filesFolder', $filesFolder)
                        ->assign('new', ModUtil::func('IWforms', 'user', 'makeTimeForm', $item['new']))
                        ->assign('caducity', ModUtil::func('IWforms', 'user', 'makeTimeForm', $item['caducity']))
                        ->assign('languages', $languagesArray)
                        ->assign('fields', $fields)
                        ->fetch('IWforms_admin_form_definitionEdit.tpl');
    }
Esempio n. 18
0
    /**
     * Update the IWmenu module
     * @author Albert Perez Monfort (aperezm@xtec.cat)
     * @return bool true if successful, false otherwise
     */
    public function upgrade($oldversion) {
        DBUtil::changeTable('IWmenu');
        switch ($oldversion) {
            case '3.0.0':
                // add language features
                // get current lang code
                $currentLang = ZLanguage::getLanguageCode();
                // get current items
                $items = DBUtil::selectObjectArray('IWmenu', '', '');
                // get installed languages
                $languages = ZLanguage::getInstalledLanguages();
                // update items with languages array
                $table = DBUtil::getTables();
                $c = $table['IWmenu_column'];
                foreach ($items as $item) {
                    $langArray = array();
                    $langText = '';
                    foreach ($languages as $lang) {
                        $langArray[$lang] = ($lang == $currentLang) ? $item['text'] : '';
                    }
                    $langText = serialize($langArray);
                    // update text value with the serialised array
                    $i = array('text' => $langText);
                    $where = "$c[mid] = $item[mid]";
                    DBUtil::updateObject($i, 'IWmenu', $where);
                }
            case '3.0.1':
                // add language features for url fields
                // get current lang code
                $currentLang = ZLanguage::getLanguageCode();
                // get current items
                $items = DBUtil::selectObjectArray('IWmenu', '', '');
                // get installed languages
                $languages = ZLanguage::getInstalledLanguages();
                // update items with languages array
                $table = DBUtil::getTables();
                $c = $table['IWmenu_column'];
                foreach ($items as $item) {
                    $langArray = array();
                    $langText = '';
                    foreach ($languages as $lang) {
                        $langArray[$lang] = ($lang == $currentLang) ? $item['url'] : '';
                    }
                    $langText = serialize($langArray);
                    // update text value with the serialised array
                    $i = array('url' => $langText);
                    $where = "$c[mid] = $item[mid]";
                    DBUtil::updateObject($i, 'IWmenu', $where);
                }

            case '3.0.2': // future version
        }
        return true;
    }
Esempio n. 19
0
 /**
  * Checks if string field value is a valid language code.
  *
  * @param string  $fieldName     The name of the property to be checked
  * @param boolean $onlyInstalled Whether to accept only installed languages (default false)
  * @return boolean result of this check
  */
 public function isValidLanguage($fieldName, $onlyInstalled = false)
 {
     $languageMap = ZLanguage::languagemap();
     $result = in_array($this->entity[$fieldName], array_keys($languageMap));
     if (!$result || !$onlyInstalled) {
         return $result;
     }
     $available = ZLanguage::getInstalledLanguages();
     return in_array($this->entity[$fieldName], $available);
 }
Esempio n. 20
0
    /**
     * edit category
     */
    public function edit()
    {
        $cid = FormUtil::getPassedValue('cid', 0);
        $root_id = FormUtil::getPassedValue('dr', 1);
        $mode = FormUtil::getPassedValue('mode', 'new');
        $allCats = '';
        $editCat = '';

        $languages = ZLanguage::getInstalledLanguages();

        // indicates that we're editing
        if ($mode == 'edit') {
            if (!SecurityUtil::checkPermission('Categories::category', "::", ACCESS_ADMIN)) {
                return LogUtil::registerPermissionError();
            }

            if (!$cid) {
                return LogUtil::registerError($this->__('Error! Cannot determine valid \'cid\' for edit mode in \'Categories_admin_edit\'.'));
            }

            $category = new Categories_DBObject_Category();
            $editCat = $category->select($cid);
            if ($editCat == false) {
                return LogUtil::registerError($this->__('Sorry! No such item found.'), 404);
            }
        } else {
            // new category creation
            if (!SecurityUtil::checkPermission('Categories::category', '::', ACCESS_ADD)) {
                return LogUtil::registerPermissionError();
            }

            // since we inherit the domain settings from the parent, we get
            // the inherited (and merged) object from session
            if (isset($_SESSION['newCategory']) && $_SESSION['newCategory']) {
                $editCat = $_SESSION['newCategory'];
                unset($_SESSION['newCategory']);
                $category = new Categories_DBObject_Category(); // need this for validation info
            }
            // if we're back from validation get the object from input
            elseif (FormUtil::getValidationErrors()) {
                $category = new Categories_DBObject_Category(DBObject::GET_FROM_VALIDATION_FAILED); // need this for validation info
                $editCat = $category->get();
            }
            // someone just pressen 'new' -> populate defaults
            else {
                $category = new Categories_DBObject_Category(); // need this for validation info
                $editCat['sort_value'] = '0';
            }
        }

        $reloadOnCatChange = ($mode != 'edit');
        $allCats = CategoryUtil::getSubCategories($root_id, true, true, true, false, true);

        // now remove the categories which are below $editCat ...
        // you should not be able to set these as a parent category as it creates a circular hierarchy (see bug #4992)
        if (isset($editCat['ipath'])) {
            $cSlashEdit = StringUtil::countInstances($editCat['ipath'], '/');
            foreach ($allCats as $k => $v) {
                $cSlashCat = StringUtil::countInstances($v['ipath'], '/');
                if ($cSlashCat >= $cSlashEdit && strpos($v['ipath'], $editCat['ipath']) !== false) {
                    unset($allCats[$k]);
                }
            }
        }

        $selector = CategoryUtil::getSelector_Categories($allCats, 'id', (isset($editCat['parent_id']) ? $editCat['parent_id'] : 0), 'category[parent_id]', isset($defaultValue) ? $defaultValue : null, null, $reloadOnCatChange);

        $attributes = isset($editCat['__ATTRIBUTES__']) ? $editCat['__ATTRIBUTES__'] : array();

        $this->view->assign('mode', $mode)
                ->assign('category', $editCat)
                ->assign('attributes', $attributes)
                ->assign('languages', $languages)
                ->assign('categorySelector', $selector)
                ->assign('validation', $category->_objValidation);

        if ($mode == 'edit') {
            $this->view->assign('haveSubcategories', CategoryUtil::haveDirectSubcategories($cid))
                    ->assign('haveLeafSubcategories', CategoryUtil::haveDirectSubcategories($cid, false, true));
        }

        return $this->view->fetch('categories_admin_edit.tpl');
    }
Esempio n. 21
0
    /**
     * edit category for a simple, non-recursive set of categories
     */
    public function edit()
    {
        $docroot = FormUtil::getPassedValue('dr', 0);
        $cid = FormUtil::getPassedValue('cid', 0);
        $url = ModUtil::url('Categories', 'user', 'edit', array('dr' => $docroot));

        if (!SecurityUtil::checkPermission('Categories::category', "ID::$docroot", ACCESS_EDIT)) {
            return LogUtil::registerPermissionError($url);
        }

        $referer = System::serverGetVar('HTTP_REFERER');
        if (strpos($referer, 'module=Categories') === false) {
            SessionUtil::setVar('categories_referer', $referer);
        }

        $rootCat = array();
        $allCats = array();
        $editCat = array();

        if (!$docroot) {
            return LogUtil::registerError($this->__("Error! The URL contains an invalid 'document root' parameter."), null, $url);
        }
        if ($docroot == 1) {
            return LogUtil::registerError($this->__("Error! The root directory cannot be modified in 'user' mode"), null, $url);
        }

        if (is_int((int)$docroot) && $docroot > 0) {
            $rootCat = CategoryUtil::getCategoryByID($docroot);
        } else {
            $rootCat = CategoryUtil::getCategoryByPath($docroot);
            if (!$rootCat) {
                $rootCat = CategoryUtil::getCategoryByPath($docroot, 'ipath');
            }
        }

        // now check if someone is trying edit another user's categories
        $userRoot = $this->getVar('userrootcat', 0);
        if ($userRoot) {
            $userRootCat = CategoryUtil::getCategoryByPath($userRoot);
            if ($userRootCat) {
                $userRootCatIPath = $userRootCat['ipath'];
                $rootCatIPath = $rootCat['ipath'];
                if (strpos($rootCatIPath, $userRootCatIPath) !== false) {
                    if (!SecurityUtil::checkPermission('Categories::category', "ID::$docroot", ACCESS_ADMIN)) {
                        $thisUserRootCategoryName = ModUtil::apiFunc('Categories', 'user', 'getusercategoryname');
                        $thisUserRootCatPath = $userRootCat['path'] . '/' . $thisUserRootCategoryName;
                        $userRootCatPath = $userRootCat['path'];
                        $rootCatPath = $rootCat['path'];
                        if (strpos($rootCatPath, $userRootCatPath) === false) {
                            //! %s represents the root path (id), passed in the url
                            return LogUtil::registerError($this->__f("Error! It looks like you are trying to edit another user's categories. Only site administrators can do that (%s).", $docroot), null, $url);
                        }
                    }
                }
            }
        }

        if ($cid) {
            $editCat = CategoryUtil::getCategoryByID($cid);
            if ($editCat['is_locked']) {
                //! %1$s is the id, %2$s is the name
                return LogUtil::registerError($this->__f('Notice: The administrator has locked the category \'%2$s\' (ID \'%$1s\'). You cannot edit or delete it.', array($cid, $editCat['name'])), null, $url);
            }
        }

        if (!$rootCat) {
            return LogUtil::registerError($this->__f("Error! Cannot access root directory (%s).", $docroot), null, $url);
        }
        if ($editCat && !$editCat['is_leaf']) {
            return LogUtil::registerError($this->__f('Error! The specified category is not a leaf-level category (%s).', $cid), null, $url);
        }
        if ($editCat && !CategoryUtil::isDirectSubCategory($rootCat, $editCat)) {
            return LogUtil::registerError($this->__f('Error! The specified category is not a child of the document root (%1$s; %2$s).', array($docroot, $cid)), null, $url);
        }

        $allCats = CategoryUtil::getSubCategoriesForCategory($rootCat, false, false, false, true, true);

        $attributes = isset($editCat['__ATTRIBUTES__']) ? $editCat['__ATTRIBUTES__'] : array();

        $languages = ZLanguage::getInstalledLanguages();

        $this->view->setCaching(Zikula_View::CACHE_DISABLED);

        return $this->view->assign('rootCat', $rootCat)
                    ->assign('category', $editCat)
                    ->assign('attributes', $attributes)
                    ->assign('allCats', $allCats)
                    ->assign('languages', $languages)
                    ->assign('userlanguage', ZLanguage::getLanguageCode())
                    ->assign('referer', SessionUtil::getVar('categories_referer'))
                    ->fetch('categories_user_edit.tpl');
    }
Esempio n. 22
0
    public function getAvailableLanguages($translate)
    {
        $savedLanguage = ZLanguage::getLanguageCode();
        $langlist = ZLanguage::getInstalledLanguages();

        $list = array();
        foreach ($langlist as $code) {
            $img = file_exists("images/flags/flag-$code.png");

            if ($translate == 2) {
                // configuration requires to translate each item in the list into the language of the country being shown
                ZLanguage::setLocale($code);
                $langname = ZLanguage::getLanguageName($code);
                ZLanguage::setLocale($savedLanguage);
            } else {
                $langname = ZLanguage::getLanguageName($code);
            }
            $list[] = array('code' => $code,
                            'name' => $langname,
                            'flag' => $img ? "images/flags/flag-$code.png" : '');
        }

        usort($list, '_blocks_thelangblock_sort');

        return $list;
    }
Esempio n. 23
0
 public function onKernelRequest(GetResponseEvent $event)
 {
     if (!$event->isMasterRequest()) {
         return;
     }
     if (\System::isInstalling()) {
         return;
     }
     $request = $event->getRequest();
     if ($request->attributes->has('_controller')) {
         // routing is already done
         return;
     }
     /**
      * It is possible the code below will throw an exception. The absence of a try/catch block here
      * allows this exception to 'bubble up' to the exception handler.
      * @see \Zikula\Bundle\CoreBundle\EventListener\ExceptionListener
      */
     if ($request->isXmlHttpRequest()) {
         $this->ajax($event);
     }
     $module = $request->attributes->get('_zkModule');
     $type = $request->attributes->get('_zkType', 'user');
     $func = $request->attributes->get('_zkFunc', 'index');
     $arguments = $request->attributes->get('_zkArgs');
     // get module information
     $modinfo = ModUtil::getInfoFromName($module);
     if (!$module) {
         // module could not be filtered from url.
         $path = $event->getRequest()->getPathInfo();
         if ($path == '' || $path == '/') {
             $isAllowedNonModulePage = true;
         } else {
             $customentrypoint = System::getVar('entrypoint');
             $root = empty($customentrypoint) ? 'index.php' : $customentrypoint;
             // get base path to work out our current url
             $parsedURL = parse_url($request->getRequestUri());
             // strip any unwanted content from the provided URL
             $toBeStripped = array($request->getBasePath(), "{$root}");
             $path = str_replace($toBeStripped, '', $parsedURL['path']);
             $path = trim($path, '/');
             $args = explode('/', rtrim($path, '/'));
             // if only arg is a lang param, then allow this Uri
             $isAllowedNonModulePage = count($args) == 1 && \ZLanguage::isLangParam($args[0]) && in_array($args[0], \ZLanguage::getInstalledLanguages());
         }
         if ($isAllowedNonModulePage) {
             // we have a static homepage
             $this->setResponse($event, new Response(''));
         } else {
             throw new NotFoundHttpException(__('Page not found.'));
         }
     } else {
         if (!$modinfo) {
             throw new NotFoundHttpException(__('Page not found.'));
         }
         // call the requested/homepage module
         $moduleBundle = ModUtil::getModule($module);
         if (null !== $moduleBundle) {
             $return = ModUtil::func($modinfo['name'], $type, $func);
         } else {
             $return = ModUtil::func($modinfo['name'], $type, $func, $arguments);
         }
         if (false === $return) {
             // hack for BC since modules currently use ModUtil::func without expecting exceptions - drak.
             throw new NotFoundHttpException(__('Page not found.'));
         } else {
             if (true === $return) {
                 // controllers should not return boolean anymore, this is BC for the time being.
                 $response = new PlainResponse();
             } else {
                 if (false === $return instanceof Response) {
                     $response = new Response($return);
                 } else {
                     $response = $return;
                 }
             }
             $this->setResponse($event, $response);
         }
     }
 }
Esempio n. 24
0
 /**
  * Decode the path string into a set of variable/value pairs.
  *
  * This API works in conjunction with the new short urls
  * system to extract a path based variable set into the Get, Post
  * and request superglobals.
  * A sample path is /modname/function/var1:value1.
  *
  * @return void
  */
 public static function queryStringDecode()
 {
     if (self::isInstalling()) {
         return;
     }
     // get our base parameters to work out if we need to decode the url
     $module = FormUtil::getPassedValue('module', null, 'GETPOST', FILTER_SANITIZE_STRING);
     $func = FormUtil::getPassedValue('func', null, 'GETPOST', FILTER_SANITIZE_STRING);
     $type = FormUtil::getPassedValue('type', null, 'GETPOST', FILTER_SANITIZE_STRING);
     // check if we need to decode the url
     if (self::getVar('shorturls') && (empty($module) && empty($type) && empty($func))) {
         // user language is not set at this stage
         $lang = System::getVar('language_i18n', '');
         $customentrypoint = self::getVar('entrypoint');
         $expectEntrypoint = !self::getVar('shorturlsstripentrypoint');
         $root = empty($customentrypoint) ? 'index.php' : $customentrypoint;
         // check if we hit baseurl, e.g. domain.com/ and if we require the language URL
         // then we should redirect to the language URL.
         if (ZLanguage::isRequiredLangParam() && self::getCurrentUrl() == self::getBaseUrl()) {
             $uri = $expectEntrypoint ? "{$root}/{$lang}" : "{$lang}";
             self::redirect(self::getBaseUrl() . $uri);
             self::shutDown();
         }
         // check if entry point is part of the URL expectation.  If so throw error if it's not present
         // since this URL is technically invalid.
         if ($expectEntrypoint && strpos(self::getCurrentUrl(), self::getBaseUrl() . $root) !== 0) {
             $protocol = System::serverGetVar('SERVER_PROTOCOL');
             header("{$protocol} 404 Not Found");
             echo __('The requested URL cannot be found');
             system::shutDown();
         }
         if (!$expectEntrypoint && self::getCurrentUrl() == self::getBaseUrl() . $root) {
             self::redirect(self::getHomepageUrl());
             self::shutDown();
         }
         if (!$expectEntrypoint && strpos(self::getCurrentUrl(), self::getBaseUrl() . $root) === 0) {
             $protocol = System::serverGetVar('SERVER_PROTOCOL');
             header("{$protocol} 404 Not Found");
             echo __('The requested URL cannot be found');
             system::shutDown();
         }
         // get base path to work out our current url
         $parsedURL = parse_url(self::getCurrentUri());
         // strip any unwanted content from the provided URL
         $tobestripped = array(self::getBaseUri(), "{$root}");
         $path = str_replace($tobestripped, '', $parsedURL['path']);
         $path = trim($path, '/');
         // split the path into a set of argument strings
         $args = explode('/', rtrim($path, '/'));
         // ensure that each argument is properly decoded
         foreach ($args as $k => $v) {
             $args[$k] = urldecode($v);
         }
         $modinfo = null;
         $frontController = $expectEntrypoint ? "{$root}/" : '';
         // if no arguments present
         if (!$args[0] && !isset($_GET['lang']) && !isset($_GET['theme'])) {
             // we are in the homepage, checks if language code is forced
             if (ZLanguage::getLangUrlRule() && $lang) {
                 // and redirect then
                 $response = new RedirectResponse(self::getCurrentUrl() . "/{$lang}");
                 $respose->send();
                 System::shutDown();
             }
         } else {
             // check the existing shortURL parameters
             // validation of the first parameter as language code
             if (ZLanguage::isLangParam($args[0]) && in_array($args[0], ZLanguage::getInstalledLanguages())) {
                 // checks if the language is not enforced and this url is passing the default lang
                 if (!ZLanguage::getLangUrlRule() && $lang == $args[0]) {
                     // redirects the passed arguments without the default site language
                     array_shift($args);
                     foreach ($args as $k => $v) {
                         $args[$k] = urlencode($v);
                     }
                     $response = new RedirectResponse(self::getBaseUrl() . $frontController . ($args ? implode('/', $args) : ''));
                     $respose->send();
                     System::shutDown();
                 }
                 self::queryStringSetVar('lang', $args[0]);
                 array_shift($args);
             } elseif (ZLanguage::getLangUrlRule()) {
                 // if the lang is forced, redirects the passed arguments plus the lang
                 foreach ($args as $k => $v) {
                     $args[$k] = urlencode($v);
                 }
                 $langTheme = isset($_GET['theme']) ? "{$lang}/{$_GET['theme']}" : $lang;
                 $response = new RedirectResponse(self::getBaseUrl() . $frontController . $langTheme . '/' . implode('/', $args));
                 $response->send();
                 System::shutDown();
             }
             // check if there are remaining arguments
             if ($args) {
                 // try the first argument as a module
                 $modinfo = ModUtil::getInfoFromName($args[0]);
                 if ($modinfo) {
                     array_shift($args);
                 }
             }
             // if that fails maybe it's a theme
             if ($args && !$modinfo) {
                 $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($args[0]));
                 if ($themeinfo) {
                     self::queryStringSetVar('theme', $themeinfo['name']);
                     // now shift the vars and continue as before
                     array_shift($args);
                     if ($args) {
                         $modinfo = ModUtil::getInfoFromName($args[0]);
                         if ($modinfo) {
                             array_shift($args);
                         }
                     }
                 }
             }
             // if there are parameters (not homepage)
             // try to see if there's a default shortURLs module
             if ($args && !$modinfo) {
                 // add the default module handler into the code
                 $modinfo = ModUtil::getInfoFromName(self::getVar('shorturlsdefaultmodule'));
             }
         }
         // check if there is a module and a custom url handler for it
         // if not decode the url using the default handler
         if ($modinfo && $modinfo['type'] != 0) {
             // prepare the arguments to the module handler
             array_unshift($args, '');
             // support for 1.2- empty parameter due the initial explode
             array_unshift($args, $modinfo['url']);
             // set the REQUEST parameters
             self::queryStringSetVar('module', $modinfo['name']);
             // the user.function name can be the second argument string, set a default
             // later the custom module handler (if exists) must setup a new one if needed
             self::queryStringSetVar('type', 'user');
             if (isset($args[2])) {
                 self::queryStringSetVar('func', $args[2]);
             } else {
                 self::queryStringSetVar('func', 'index');
             }
             if (!ModUtil::apiFunc($modinfo['name'], 'user', 'decodeurl', array('vars' => $args))) {
                 // any remaining arguments are specific to the module
                 $argscount = count($args);
                 for ($i = 3; $i < $argscount; $i = $i + 2) {
                     if (isset($args[$i]) && isset($args[$i + 1])) {
                         self::queryStringSetVar($args[$i], urldecode($args[$i + 1]));
                     }
                 }
             }
         }
     }
 }
Esempio n. 25
0
/**
 * Install controller.
 *
 * @return void
 */
function install(Core $core)
{
    define('_ZINSTALLVER', Core::VERSION_NUM);
    $serviceManager = $core->getContainer();
    $eventManager = $core->getDispatcher();
    // Lazy load DB connection to avoid testing DSNs that are not yet valid (e.g. no DB created yet)
    $dbEvent = new GenericEvent(null, array('lazy' => true));
    $eventManager->dispatch('doctrine.init_connection', $dbEvent);
    $core->init(Core::STAGE_ALL & ~Core::STAGE_THEME & ~Core::STAGE_MODS & ~Core::STAGE_LANGS & ~Core::STAGE_DECODEURLS & ~Core::STAGE_SESSIONS);
    // Power users might have moved the temp folder out of the root and changed the config.php
    // accordingly. Make sure we respect this security related settings
    $tempDir = isset($GLOBALS['ZConfig']['System']['temp']) ? $GLOBALS['ZConfig']['System']['temp'] : 'ztemp';
    // define our smarty object
    $smarty = new Smarty();
    $smarty->caching = false;
    $smarty->compile_check = true;
    $smarty->left_delimiter = '{';
    $smarty->right_delimiter = '}';
    $smarty->compile_dir = $tempDir . '/view_compiled';
    $smarty->template_dir = 'install/templates';
    $smarty->plugins_dir = array('plugins', 'install/templates/plugins');
    $smarty->clear_compiled_tpl();
    file_put_contents("{$tempDir}/view_compiled/index.html", '');
    $lang = FormUtil::getPassedValue('lang', '', 'GETPOST');
    $dbhost = FormUtil::getPassedValue('dbhost', '', 'GETPOST');
    $dbusername = FormUtil::getPassedValue('dbusername', '', 'GETPOST');
    $dbpassword = FormUtil::getPassedValue('dbpassword', '', 'GETPOST');
    $dbname = FormUtil::getPassedValue('dbname', '', 'GETPOST');
    $dbprefix = '';
    $dbdriver = FormUtil::getPassedValue('dbdriver', '', 'GETPOST');
    $dbtabletype = FormUtil::getPassedValue('dbtabletype', '', 'GETPOST');
    $username = FormUtil::getPassedValue('username', '', 'POST');
    $password = FormUtil::getPassedValue('password', '', 'POST');
    $repeatpassword = FormUtil::getPassedValue('repeatpassword', '', 'POST');
    $email = FormUtil::getPassedValue('email', '', 'GETPOST');
    $action = FormUtil::getPassedValue('action', '', 'GETPOST');
    $notinstalled = isset($_GET['notinstalled']);
    $installedState = isset($GLOBALS['ZConfig']['System']['installed']) ? $GLOBALS['ZConfig']['System']['installed'] : 0;
    // If somehow we are browsing the not installed page but installed, redirect back to homepage
    if ($installedState && $notinstalled) {
        $response = new RedirectResponse(System::getHomepageUrl());
        return $response->send();
    }
    // see if the language was already selected
    $languageAlreadySelected = $lang ? true : false;
    if (!$notinstalled && $languageAlreadySelected && empty($action)) {
        $response = new RedirectResponse(System::getBaseUri() . "/install.php?action=requirements&lang={$lang}");
        return $response->send();
    }
    // see if the language was already selected
    $languageAlreadySelected = $lang ? true : false;
    if (!$notinstalled && $languageAlreadySelected && empty($action)) {
        $response = new RedirectResponse(System::getBaseUri() . "/install.php?action=requirements&lang={$lang}");
        return $response->send();
    }
    // load the installer language files
    if (empty($lang)) {
        if (is_readable('config/installer.ini')) {
            $test = parse_ini_file('config/installer.ini');
            $lang = isset($test['language']) ? $test['language'] : 'en';
        } else {
            $available = ZLanguage::getInstalledLanguages();
            $detector = new ZLanguageBrowser($available);
            $lang = $detector->discover();
        }
        $lang = DataUtil::formatForDisplay($lang);
    }
    // setup multilingual
    $GLOBALS['ZConfig']['System']['language_i18n'] = $lang;
    $GLOBALS['ZConfig']['System']['multilingual'] = true;
    $GLOBALS['ZConfig']['System']['languageurl'] = true;
    $GLOBALS['ZConfig']['System']['language_detect'] = false;
    $serviceManager->loadArguments($GLOBALS['ZConfig']['System']);
    $_lang = ZLanguage::getInstance();
    $_lang->setup();
    $lang = ZLanguage::getLanguageCode();
    $installbySQL = file_exists("install/sql/custom-{$lang}.sql") ? "install/sql/custom-{$lang}.sql" : false;
    $smarty->assign('lang', $lang);
    $smarty->assign('installbySQL', $installbySQL);
    $smarty->assign('langdirection', ZLanguage::getDirection());
    $smarty->assign('charset', ZLanguage::getEncoding());
    // show not installed case
    if ($notinstalled) {
        header('HTTP/1.1 503 Service Unavailable');
        $smarty->display('notinstalled.tpl');
        $smarty->clear_compiled_tpl();
        file_put_contents("{$tempDir}/view_compiled/index.html", '');
        exit;
    }
    // assign the values from config.php
    $smarty->assign($GLOBALS['ZConfig']['System']);
    // if the system is already installed, halt.
    if ($GLOBALS['ZConfig']['System']['installed']) {
        _installer_alreadyinstalled($smarty);
    }
    // check for an empty action - if so then show the first installer page
    if (empty($action)) {
        $action = 'lang';
    }
    // perform tasks based on our action
    switch ($action) {
        case 'processBDInfo':
            $dbname = trim($dbname);
            $dbusername = trim($dbusername);
            if (empty($dbname) || empty($dbusername)) {
                $action = 'dbinformation';
                $smarty->assign('dbconnectmissing', true);
            } elseif (!preg_match('/^[\\w-]*$/', $dbname) || strlen($dbname) > 64) {
                $action = 'dbinformation';
                $smarty->assign('dbinvalidname', true);
            } else {
                update_config_php($dbhost, $dbusername, $dbpassword, $dbname, $dbdriver, $dbtabletype);
                update_installed_status(0);
                try {
                    $dbh = new PDO("{$dbdriver}:host={$dbhost};dbname={$dbname}", $dbusername, $dbpassword);
                } catch (PDOException $e) {
                    $action = 'dbinformation';
                    $smarty->assign('reason', $e->getMessage());
                    $smarty->assign('dbconnectfailed', true);
                }
            }
            if ($action != 'dbinformation') {
                $action = 'createadmin';
            }
            break;
        case 'finish':
            if (!$username || preg_match('/[^\\p{L}\\p{N}_\\.\\-]/u', $username)) {
                $action = 'createadmin';
                $smarty->assign('uservalidatefailed', true);
                $smarty->assign(array('username' => $username, 'password' => $password, 'repeatpassword' => $repeatpassword, 'email' => $email));
            } elseif (mb_strlen($password) < 7) {
                $action = 'createadmin';
                $smarty->assign('badpassword', true);
                $smarty->assign(array('username' => $username, 'password' => $password, 'repeatpassword' => $repeatpassword, 'email' => $email));
            } elseif ($password !== $repeatpassword) {
                $action = 'createadmin';
                $smarty->assign('passwordcomparefailed', true);
                $smarty->assign(array('username' => $username, 'password' => $password, 'repeatpassword' => $repeatpassword, 'email' => $email));
            } elseif (!validateMail($email)) {
                $action = 'createadmin';
                $smarty->assign('emailvalidatefailed', true);
                $smarty->assign(array('username' => $username, 'password' => $password, 'repeatpassword' => $repeatpassword, 'email' => $email));
            } else {
                $installedOk = false;
                // if it is the distribution and the process have not failed in a previous step
                if ($installbySQL) {
                    // checks if exists a previous installation with the same prefix
                    $proceed = true;
                    $dbnameConfig = $GLOBALS['ZConfig']['DBInfo']['databases']['default']['dbname'];
                    $exec = $dbdriver == 'mysql' || $dbdriver == 'mysqli' ? "SHOW TABLES FROM `{$dbnameConfig}` LIKE '%'" : "SHOW TABLES FROM {$dbnameConfig} LIKE '%'";
                    $tables = DBUtil::executeSQL($exec);
                    if ($tables->rowCount() > 0) {
                        $proceed = false;
                        $action = 'dbinformation';
                        $smarty->assign('dbexists', true);
                    }
                    if ($proceed) {
                        // checks if file exists
                        if (!file_exists($installbySQL)) {
                            $action = 'dbinformation';
                            $smarty->assign('dbdumpfailed', true);
                        } else {
                            // execute the SQL dump
                            $lines = file($installbySQL);
                            $exec = '';
                            foreach ($lines as $line_num => $line) {
                                $line = trim($line);
                                if (empty($line) || strpos($line, '--') === 0) {
                                    continue;
                                }
                                $exec .= $line;
                                if (strrpos($line, ';') === strlen($line) - 1) {
                                    if (!DBUtil::executeSQL($exec)) {
                                        $action = 'dbinformation';
                                        $smarty->assign('dbdumpfailed', true);
                                        break;
                                    }
                                    $exec = '';
                                }
                            }
                            ModUtil::dbInfoLoad('Users', 'Users');
                            ModUtil::dbInfoLoad('Extensions', 'Extensions');
                            ModUtil::initCoreVars(true);
                            createuser($username, $password, $email);
                            $installedOk = true;
                        }
                    }
                } else {
                    installmodules($lang);
                    createuser($username, $password, $email);
                    $installedOk = true;
                }
                if ($installedOk) {
                    // create our new site admin
                    // TODO: Email username/password to administrator email address.  Cannot use ModUtil::apiFunc for this.
                    $serviceManager->get('session')->start();
                    $authenticationInfo = array('login_id' => $username, 'pass' => $password);
                    $authenticationMethod = array('modname' => 'Users', 'method' => 'uname');
                    UserUtil::loginUsing($authenticationMethod, $authenticationInfo);
                    // add admin email as site email
                    System::setVar('adminmail', $email);
                    if (!$installbySQL) {
                        Theme_Util::regenerate();
                    }
                    // set site status as installed and protect config.php file
                    update_installed_status(1);
                    @chmod('config/config.php', 0400);
                    if (!is_readable('config/config.php')) {
                        @chmod('config/config.php', 0440);
                        if (!is_readable('config/config.php')) {
                            @chmod('config/config.php', 0444);
                        }
                    }
                    // install all plugins
                    $systemPlugins = PluginUtil::loadAllSystemPlugins();
                    foreach ($systemPlugins as $plugin) {
                        PluginUtil::install($plugin);
                    }
                    LogUtil::registerStatus(__('Congratulations! Zikula has been successfullly installed.'));
                    $response = new RedirectResponse(ModUtil::url('Admin', 'admin', 'adminpanel'));
                    $response->send();
                    exit;
                }
            }
            break;
        case 'requirements':
            $checks = _check_requirements();
            $ok = true;
            foreach ($checks as $check) {
                if (!$check) {
                    $ok = false;
                    break;
                }
            }
            foreach ($checks['files'] as $check) {
                if (!$check['writable']) {
                    $ok = false;
                    break;
                }
            }
            if ($ok) {
                $response = new RedirectResponse(System::getBaseUri() . "/install.php?action=dbinformation&lang={$lang}");
                $response->send();
                exit;
            }
            $smarty->assign('checks', $checks);
            break;
    }
    // check our action template exists
    $action = DataUtil::formatForOS($action);
    if ($smarty->template_exists("installer_{$action}.tpl")) {
        $smarty->assign('action', $action);
        $templateName = "installer_{$action}.tpl";
    } else {
        $smarty->assign('action', 'error');
        $templateName = 'installer_error.tpl';
    }
    $smarty->assign('maincontent', $smarty->fetch($templateName));
    $smarty->display('installer_page.tpl');
    $smarty->clear_compiled_tpl();
    file_put_contents("{$tempDir}/view_compiled/index.html", '');
}