Example #1
0
 /**
  * editsmilies
  *
  *
  */
 public function editsmilies()
 {
     if (!SecurityUtil::checkPermission('BBSmile::', '::', ACCESS_ADMIN)) {
         return LogUtil::registerPermissionError(System::getHomepageUrl());
     }
     $submit = $this->getPassedValue('submit', null, 'POST');
     if (!$submit) {
         $smilies = $this->getVar('smilie_array');
         $this->view->assign('smilies', $smilies);
         return $this->view->fetch('admin/editsmiles.tpl');
     }
     // submit is set
     $this->checkCsrfToken();
     // Get input
     $keys = $this->getPassedValue('key', array(), 'POST');
     $shorts = $this->getPassedValue('short', array(), 'POST');
     $imgsrcs = $this->getPassedValue('imgsrc', array(), 'POST');
     $alts = $this->getPassedValue('alt', array(), 'POST');
     $aliases = $this->getPassedValue('alias', array(), 'POST');
     $types = $this->getPassedValue('smilietype', array(), 'POST');
     $active = $this->getPassedValue('active', array(), 'POST');
     $smilies = array();
     // Create an array with the input and deaktivate all smilies
     for ($i = 0; $i < sizeof($keys); $i++) {
         $smilies[$keys[$i]] = array('type' => $types[$i], 'short' => $shorts[$i], 'imgsrc' => $imgsrcs[$i], 'alt' => $alts[$i], 'alias' => $aliases[$i], 'active' => 0);
     }
     // And now set the active flag for all selected smilies
     for ($i = 0; $i < sizeof($active); $i++) {
         $smilies[$active[$i]]['active'] = 1;
     }
     $this->setVar('smilie_array', $smilies);
     LogUtil::registerStatus($this->__('The edited smilies have been saved.'));
     $this->redirect(ModUtil::url('BBSmile', 'admin', 'main'));
 }
Example #2
0
/**
 * Plugin to return the homepage address.
 *
 * Available parameters:
 *   - assign:   If set, the results are assigned to the corresponding variable instead of printed out
 *
 * Example
 *   {homepage}
 *
 * @param array       $params All attributes passed to this function from the template.
 * @param Zikula_View $view   Reference to the Zikula_View object.
 *
 * @return string The base URL of the site.
 */
function smarty_function_homepage($params, Zikula_View $view)
{
    $assign = isset($params['assign']) ? $params['assign'] : null;
    $result = htmlspecialchars(System::getHomepageUrl());
    if ($assign) {
        $view->assign($assign, $result);
    } else {
        return $result;
    }
}
Example #3
0
 /**
  * Modify a comment
  *
  * This is a standard function that is called whenever an administrator
  * wishes to modify a comment
  *
  * @param  tid  the id of the comment to be modified
  * @return string the modification page
  */
 public function modify($args)
 {
     // get our input
     $id = isset($args['id']) ? $args['id'] : FormUtil::getPassedValue('id', null, 'GETPOST');
     // Security check
     $securityCheck = ModUtil::apiFunc('EZComments', 'user', 'checkPermission', array('module' => '', 'objectid' => '', 'commentid' => $id, 'level' => ACCESS_EDIT));
     if (!$securityCheck) {
         $redirect = base64_decode(FormUtil::getPassedValue('redirect'));
         if (!isset($redirect)) {
             $redirect = System::getHomepageUrl();
         }
         return LogUtil::registerPermissionError($redirect);
     }
     // Create Form output object
     $render = FormUtil::newForm('EZComments', $this);
     // Return the output that has been generated by this function
     return $render->execute("ezcomments_admin_modify.tpl", new EZComments_Form_Handler_Admin_Modify());
 }
Example #4
0
    /**
     * Generate a configuration for javascript and return script tag to embed in HTML HEAD.
     * 
     * @return string HTML code with script tag
     */
    public static function getJSConfig()
    {
        $return = '';
        $config = array(
                'entrypoint' => System::getHomepageUrl(),
                'baseURL' => System::getBaseUrl(),
                'baseURI' => System::getBaseUri() . '/',
                'ajaxtimeout' => (int)System::getVar('ajaxtimeout', 5000),
                'lang' => ZLanguage::getLanguageCode(),
                'sessionName' => session_name(),
        );
        $config = DataUtil::formatForDisplay($config);
        $return .= "<script type=\"text/javascript\">/* <![CDATA[ */ \n";
        if (System::isLegacyMode()) {
            $return .= 'document.location.entrypoint="' . $config['entrypoint'] . '";';
            $return .= 'document.location.pnbaseURL="' . $config['baseURL'] . '"; ';
            $return .= 'document.location.ajaxtimeout=' . $config['ajaxtimeout'] . ";\n";
        }
        $return .= "if (typeof(Zikula) == 'undefined') {var Zikula = {};}\n";
        $return .= "Zikula.Config = " . json_encode($config) . "\n";
        $return .= ' /* ]]> */</script>' . "\n";

        return $return;
    }
Example #5
0
    /**
     * Add a new user to the system.
     *
     * Parameters passed via GET:
     * --------------------------
     * None.
     *
     * Parameters passed via POST:
     * ---------------------------
     * See the definition of {@link Users_Controller_FormData_NewUserForm}.
     *
     * Parameters passed via SESSION:
     * ------------------------------
     * None.
     *
     * @return string HTML string containing the rendered template.
     *
     * @throws Zikula_Exception_Forbidden Thrown if the current user does not have add access, or if the method of accessing this function is improper.
     */
    public function newUser()
    {
        // The user must have ADD access to submit a new user record.
        if (!SecurityUtil::checkPermission($this->name . '::', '::', ACCESS_ADD)) {
            throw new Zikula_Exception_Forbidden();
        }

        // When new user registration is disabled, the user must have ADMIN access instead of ADD access.
        if (!$this->getVar(Users_Constant::MODVAR_REGISTRATION_ENABLED, false) && !SecurityUtil::checkPermission($this->name . '::', '::', ACCESS_ADMIN)) {
            $registrationUnavailableReason = $this->getVar(Users_Constant::MODVAR_REGISTRATION_DISABLED_REASON, $this->__('Sorry! New user registration is currently disabled.'));
            $this->registerError($registrationUnavailableReason);
            // TODO - The home page typically does not display errors.
            $this->redirect(System::getHomepageUrl());
        }

        $proceedToForm = true;
        $formData = new Users_Controller_FormData_NewUserForm('users_newuser', $this->serviceManager);
        $errorFields = array();
        $errorMessages = array();

        if ($this->request->isPost()) {
            // Returning from a form POST operation. Process the input.
            $this->checkCsrfToken();

            $formData->setFromRequestCollection($this->request->request);

            $registrationArgs = array(
                'checkMode'         => 'new',
                'emailagain'        => $formData->getField('emailagain')->getData(),
                'setpass'           => (bool)$formData->getField('setpass')->getData(),
                'antispamanswer'    => '',
            );
            $registrationArgs['passagain'] = $registrationArgs['setpass'] ? $formData->getField('passagain')->getData() : '';

            $registrationInfo = array(
                'uname'         => $formData->getField('uname')->getData(),
                'pass'          => $registrationArgs['setpass'] ? $formData->getField('pass')->getData() : '',
                'passreminder'  => $registrationArgs['setpass'] ? $this->__('(Password provided by site administrator)') : '',
                'email'         => mb_strtolower($formData->getField('email')->getData()),
            );
            $registrationArgs['reginfo'] = $registrationInfo;

            $sendPass = $formData->getField('sendpass')->getData();

            if ($formData->isValid()) {
                $errorFields = ModUtil::apiFunc($this->name, 'registration', 'getRegistrationErrors', $registrationArgs);
            } else {
                $errorFields = $formData->getErrorMessages();
            }

            $event = new Zikula_Event('module.users.ui.validate_edit.new_user', $registrationInfo, array(), new Zikula_Hook_ValidationProviders());
            $validators = $this->eventManager->notify($event)->getData();

            $hook = new Zikula_ValidationHook('users.ui_hooks.user.validate_edit', $validators);
            $this->notifyHooks($hook);
            $validators = $hook->getValidators();

            if (empty($errorFields) && !$validators->hasErrors()) {
                // TODO - Future functionality to suppress e-mail notifications, see ticket #2351
                //$currentUserEmail = UserUtil::getVar('email');
                //$adminNotifyEmail = $this->getVar('reg_notifyemail', '');
                //$adminNotification = (strtolower($currentUserEmail) != strtolower($adminNotifyEmail));

                $registeredObj = ModUtil::apiFunc($this->name, 'registration', 'registerNewUser', array(
                    'reginfo'           => $registrationInfo,
                    'sendpass'          => $sendPass,
                    'usernotification'  => true,
                    'adminnotification' => true,
                ));

                if (isset($registeredObj) && $registeredObj) {
                    $event = new Zikula_Event('module.users.ui.process_edit.new_user', $registeredObj);
                    $this->eventManager->notify($event);

                    $hook = new Zikula_ProcessHook('users.ui_hooks.user.process_edit', $registeredObj['uid']);
                    $this->notifyHooks($hook);

                    if ($registeredObj['activated'] == Users_Constant::ACTIVATED_PENDING_REG) {
                        $this->registerStatus($this->__('Done! Created new registration application.'));
                    } elseif (isset($registeredObj['activated'])) {
                        $this->registerStatus($this->__('Done! Created new user account.'));
                    } else {
                        $this->registerError($this->__('Warning! New user information has been saved, however there may have been an issue saving it properly.'));
                    }

                    $proceedToForm = false;
                } else {
                    $this->registerError($this->__('Error! Could not create the new user account or registration application.'));
                }
            }
        } elseif (!$this->request->isGet()) {
            throw new Zikula_Exception_Forbidden();
        }

        if ($proceedToForm) {
            return $this->view->assign_by_ref('formData', $formData)
                    ->assign('mode', 'new')
                    ->assign('errorMessages', $errorMessages)
                    ->assign('errorFields', $errorFields)
                    ->fetch('users_admin_newuser.tpl');
        } else {
            $this->redirect(ModUtil::url($this->name, 'admin', 'view'));
        }
    }
Example #6
0
    /**
     * Display main admin panel for a category
     *
     * @param  int    $args['acid'] the id of the category to be displayed
     * @return string HTML string
     */
    public function adminpanel($args)
    {
        if (!SecurityUtil::checkPermission('::', '::', ACCESS_EDIT)) {
            // suppress admin display - return to index.
            $this->redirect(System::getHomepageUrl());
        }

        if (!$this->getVar('ignoreinstallercheck') && System::getVar('development') == 0) {
            // check if the Zikula Recovery Console exists
            $zrcexists = file_exists('zrc.php');
            // check if upgrade scripts exist
            if ($zrcexists == true) {
                return $this->view->assign('zrcexists', $zrcexists)
                                  ->assign('adminpanellink', ModUtil::url('Admin','admin', 'adminpanel'))
                                  ->fetch('admin_admin_warning.tpl');
            }
        }

        // Now prepare the display of the admin panel by getting the relevant info.

        // Get parameters from whatever input we need.
        $acid = FormUtil::getPassedValue('acid', (isset($args['acid']) ? $args['acid'] : null), 'GET');

        // cid isn't set, so go to the default category
        if (empty($acid)) {
            $acid = $this->getVar('startcategory');
        }

        // Add category menu to output
        $this->view->assign('menu', $this->categorymenu(array('acid' => $acid)));

        // Check to see if we have access to the requested category.
        if (!SecurityUtil::checkPermission("Admin::", "::$acid", ACCESS_ADMIN)) {
            $acid = -1;
        }

        // Get Details on the selected category
        if ($acid > 0) {
            $category = ModUtil::apiFunc('Admin', 'admin', 'get', array('cid' => $acid));
        } else {
            $category = null;
        }

        if (!$category) {
            // get the default category
            $acid = $this->getVar('startcategory');

            // Check to see if we have access to the requested category.
            if (!SecurityUtil::checkPermission("Admin::", "::$acid", ACCESS_ADMIN)) {
                return LogUtil::registerPermissionError(System::getHomepageUrl());
            }

            $category = ModUtil::apiFunc('Admin', 'admin', 'get', array('cid' => $acid));
        }

        // assign the category
        $this->view->assign('category', $category);

        $displayNameType = $this->getVar('displaynametype', 1);

        // get admin capable modules
        $adminmodules = ModUtil::getAdminMods();
        $adminlinks = array();
        foreach ($adminmodules as $adminmodule) {
            if (SecurityUtil::checkPermission("{$adminmodule['name']}::", 'ANY', ACCESS_EDIT)) {
                $catid = ModUtil::apiFunc('Admin', 'admin', 'getmodcategory',
                        array('mid' => ModUtil::getIdFromName($adminmodule['name'])));
                $order = ModUtil::apiFunc('Admin', 'admin', 'getSortOrder',
                        array('mid' => ModUtil::getIdFromName($adminmodule['name'])));
                if (($catid == $acid) || (($catid == false) && ($acid == $this->getVar('defaultcategory')))) {
                    $modinfo = ModUtil::getInfoFromName($adminmodule['name']);
                    $menutexturl = ModUtil::url($modinfo['name'], 'admin', 'main');
                    $modpath = ($modinfo['type'] == ModUtil::TYPE_SYSTEM) ? 'system' : 'modules';

                    if ($displayNameType == 1) {
                        $menutext = $modinfo['displayname'];
                    } elseif ($displayNameType == 2) {
                        $menutext = $modinfo['name'];
                    } elseif ($displayNameType == 3) {
                        $menutext = $modinfo['displayname'] . ' (' . $modinfo['name'] . ')';
                    }
                    $menutexttitle = $modinfo['description'];

                    $adminicon = ModUtil::getModuleImagePath($adminmodule['name']);

                    $adminlinks[] = array('menutexturl' => $menutexturl,
                            'menutext' => $menutext,
                            'menutexttitle' => $menutexttitle,
                            'modname' => $modinfo['name'],
                            'adminicon' => $adminicon,
                            'id' => $modinfo['id'],
                            'order'=> $order);
                }
            }
        }
        usort($adminlinks, '_sortAdminModsByOrder');
        $this->view->assign('adminlinks', $adminlinks);

        return $this->view->fetch('admin_admin_adminpanel.tpl');
    }
Example #7
0
    /**
     * block configuration
     */
    public function modify($blockinfo)
    {
        $vars = BlockUtil::varsFromContent($blockinfo['content']);

        // set some default vars
        $vars['isnew'] =                    empty($vars);
        $vars['menutree_content'] =         isset($vars['menutree_content']) ? $vars['menutree_content'] : array();
        $vars['menutree_tpl'] =             isset($vars['menutree_tpl']) ? $vars['menutree_tpl'] : '';
        $vars['menutree_stylesheet'] =      isset($vars['menutree_stylesheet']) ? $vars['menutree_stylesheet'] : '';
        $vars['menutree_linkclass'] =       isset($vars['menutree_linkclass']) ? $vars['menutree_linkclass'] : false;
        $vars['menutree_linkclasses'] =     isset($vars['menutree_linkclasses']) ? $vars['menutree_linkclasses'] : array();
        $vars['menutree_titles'] =          isset($vars['menutree_titles']) ? $vars['menutree_titles'] : array();
        $vars['menutree_editlinks'] =       isset($vars['menutree_editlinks']) ? $vars['menutree_editlinks'] : false;
        $vars['menutree_stripbaseurl'] =    isset($vars['menutree_stripbaseurl']) ? $vars['menutree_stripbaseurl'] : true;
        $vars['menutree_maxdepth'] =        isset($vars['menutree_maxdepth']) ? $vars['menutree_maxdepth'] : 0;
        $vars['oldlanguages'] =             isset($vars['oldlanguages']) ? $vars['oldlanguages'] : array();
        $vars['olddefaultanguage'] =        isset($vars['olddefaultanguage']) ? $vars['olddefaultanguage'] :'';

        // get list of languages
        $vars['languages'] = ZLanguage::getInstalledLanguageNames();
        $userlanguage = ZLanguage::getLanguageCode();

        // get default langs
        $vars['defaultanguage'] = !empty($blockinfo['language']) ? $blockinfo['language'] : $userlanguage;

        // rebuild langs array - default lang has to be first
        if (isset($vars['languages']) && count($vars['languages']) > 1) {
            $deflang[$vars['defaultanguage']] = $vars['languages'][$vars['defaultanguage']];
            unset($vars['languages'][$vars['defaultanguage']]);
            $vars['languages'] = array_merge($deflang,$vars['languages']);
            $vars['multilingual'] = true;
        } else {
            $vars['multilingual'] = false;
        }

        $langs = array('list' => array_keys($vars['languages']),
                       'flat' => false);

        // check if there is allredy content
        if (empty($vars['menutree_content'])) {
            // no content - get list of menus to allow import
            $vars['menutree_menus'] = $this->_get_current_menus($blockinfo['bid']);
        } else {
            // are there new langs not present in current menu?
            // check if there are new languages not present in current menu
            // if so - need to set reference lang to copy initial menu items data
            if (count(array_diff($vars['languages'],$vars['oldlanguages'])) > 1) {
                // fisrt try current default lang
                if (in_array($vars['defaultanguage'],$vars['oldlanguages'])) {
                    $langs['ref'] = $vars['defaultanguage'];
                    // or user lang
                } elseif (in_array($userlanguage,$vars['oldlanguages'])) {
                    $langs['ref'] = $userlanguage;
                    // or old default lang
                } elseif (in_array($vars['olddefaultanguage'],$vars['languages'])) {
                    $langs['ref'] = $vars['olddefaultanguage'];
                    // it must be any language present in old and new lang list
                } else {
                    $langs['ref'] = current(array_intersect($vars['languages'], $vars['oldlanguages']));
                }
            }
        }
        // decode tree array
        $tree = new Blocks_MenutreeTree();
        $tree->setOption('id', 'adm-menutree'.$blockinfo['bid']);
        $tree->setOption('sortable', true);
        if (isset($langs)) {
            $tree->setOption('langs', $langs['list']);
        }
        $tree->setOption('stripbaseurl', $vars['menutree_stripbaseurl']);
        $tree->setOption('maxDepth', $vars['menutree_maxdepth']);
        $tree->loadArrayData($vars['menutree_content']);
        $vars['menutree_content'] = $tree->getHTML();

        // get all templates and stylesheets.
        $vars['tpls'] = Blocks_MenutreeUtil::getTemplates();
        $vars['styles'] =  Blocks_MenutreeUtil::getStylesheets();
        $someThemes = $this->__('Only in some themes');
        $vars['somethemes'] = isset($vars['tpls'][$someThemes]) || isset($vars['styles'][$someThemes]) ? true : false;

        // template to use
        if (empty($vars['menutree_tpl']) || !$this->view->template_exists($vars['menutree_tpl'])) {
            $vars['menutree_tpl'] = 'menutree/blocks_block_menutree_default.tpl';
        }

        // prepare block titles array
        foreach (array_keys($vars['languages']) as $lang) {
            if (!array_key_exists($lang, $vars['menutree_titles'])) {
                $vars['menutree_titles'][$lang] = '';
            }
        }

        // for permissions settings get first supported permlevels
        $vars['permlevels']  = $this->_permlevels();

        // check if saved permlevels are correct
        $vars['menutree_titlesperms']   = !empty($vars['menutree_titlesperms']) ? $vars['menutree_titlesperms'] : 'ACCESS_EDIT';
        $vars['menutree_displayperms']  = !empty($vars['menutree_displayperms']) ? $vars['menutree_displayperms'] : 'ACCESS_EDIT';
        $vars['menutree_settingsperms'] = !empty($vars['menutree_settingsperms']) ? $vars['menutree_settingsperms'] : 'ACCESS_EDIT';

        // check user permissions for settings sections
        $useraccess = SecurityUtil::getSecurityLevel(SecurityUtil::getAuthInfo(), 'Blocks::', "$blockinfo[bkey]:$blockinfo[title]:$blockinfo[bid]");
        $vars['menutree_titlesaccess']      = $useraccess >= constant($vars['menutree_titlesperms']);
        $vars['menutree_displayaccess']     = $useraccess >= constant($vars['menutree_displayperms']);
        $vars['menutree_settingsaccess']    = $useraccess >= constant($vars['menutree_settingsperms']);
        $vars['menutree_adminaccess']       = $useraccess >= ACCESS_ADMIN;
        $vars['menutree_anysettingsaccess'] = $vars['menutree_adminaccess'] || $vars['menutree_titlesaccess'] || $vars['menutree_displayaccess'] || $vars['menutree_settingsaccess'];

        // 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');

        $vars['redirect'] = '';
        $vars['menutree_newurl'] = '';
        if ($addurl == 1) {
            // set a marker for redirection later on
            $newurl = System::serverGetVar('HTTP_REFERER');
            $vars['redirect'] = urlencode($newurl);
            $newurl = str_replace(System::getBaseUrl(), '', $newurl);
            if (empty($newurl)) {
                $newurl = System::getHomepageUrl();
            }
            $vars['menutree_newurl'] = $newurl;
        } elseif (isset($fromblock)) {
            $vars['redirect'] = urlencode(System::serverGetVar('HTTP_REFERER'));
        }

        // Create output object
        $this->view->setCaching(Zikula_View::CACHE_DISABLED);

        // assign all block variables
        $this->view->assign($vars)
                   ->assign('blockinfo', $blockinfo);

        // Return the output that has been generated by this function
        return $this->view->fetch('menutree/blocks_block_menutree_modify.tpl');
    }
Example #8
0
    /**
     * Allow the user to accept active terms of use and/or privacy policy.
     *
     * This function is currently used by the Legal module's handler for the users.login.veto event.
     *
     * @return string The rendered output from the template.
     *
     * @throws Zikula_Exception_Forbidden Thrown if the user is not logged in and the acceptance attempt is not a result of a login attempt.
     *
     * @throws Zikula_Exception_Fatal Thrown if the user is already logged in and the acceptance attempt is a result of a login attempt;
     *      also thrown in cases where expected data is not present or not in an expected form;
     *      also thrown if the call to this function is not the result of a POST operation or a GET operation.
     */
    public function acceptPolicies()
    {
        // Retrieve and delete any session variables being sent in by the log-in process before we give the function a chance to
        // throw an exception. We need to make sure no sensitive data is left dangling in the session variables.
        $sessionVars = $this->request->getSession()->get('Legal_Controller_User_acceptPolicies', null, $this->name);
        $this->request->getSession()->del('Legal_Controller_User_acceptPolicies', $this->name);

        $processed = false;
        $helper = new Legal_Helper_AcceptPolicies();

        if ($this->request->isPost()) {
            $this->checkCsrfToken();

            $isLogin = isset($sessionVars) && !empty($sessionVars);

            if (!$isLogin && !UserUtil::isLoggedIn()) {
                throw new Zikula_Exception_Forbidden();
            } elseif ($isLogin && UserUtil::isLoggedIn()) {
                throw new Zikula_Exception_Fatal();
            }

            $policiesUid = $this->request->getPost()->get('acceptedpolicies_uid', false);
            $acceptedPolicies = array(
                'termsOfUse'                => $this->request->getPost()->get('acceptedpolicies_termsofuse', false),
                'privacyPolicy'             => $this->request->getPost()->get('acceptedpolicies_privacypolicy', false),
                'agePolicy'                 => $this->request->getPost()->get('acceptedpolicies_agepolicy', false),
                'cancellationRightPolicy'   => $this->request->getPost()->get('acceptedpolicies_cancellationrightpolicy', false),
                'tradeConditions'           => $this->request->getPost()->get('acceptedpolicies_tradeconditions', false)
            );

            if (!isset($policiesUid) || empty($policiesUid) || !is_numeric($policiesUid)) {
                throw new Zikula_Exception_Fatal();
            }

            $activePolicies = $helper->getActivePolicies();
            $originalAcceptedPolicies = $helper->getAcceptedPolicies($policiesUid);

            $fieldErrors = array();

            if ($activePolicies['termsOfUse'] && !$originalAcceptedPolicies['termsOfUse'] && !$acceptedPolicies['termsOfUse']) {
                $fieldErrors['termsofuse'] = $this->__('You must accept this site\'s Terms of Use in order to proceed.');
            }

            if ($activePolicies['privacyPolicy'] && !$originalAcceptedPolicies['privacyPolicy'] && !$acceptedPolicies['privacyPolicy']) {
                $fieldErrors['privacypolicy'] = $this->__('You must accept this site\'s Privacy Policy in order to proceed.');
            }

            if ($activePolicies['agePolicy'] && !$originalAcceptedPolicies['agePolicy'] && !$acceptedPolicies['agePolicy']) {
                $fieldErrors['agepolicy'] = $this->__f('In order to log in, you must confirm that you meet the requirements of this site\'s Minimum Age Policy. If you are not %1$s years of age or older, and you do not have a parent\'s permission to use this site, then please ask your parent to contact a site administrator.', array(ModUtil::getVar('Legal', Legal_Constant::MODVAR_MINIMUM_AGE, 0)));
            }

            if ($activePolicies['cancellationRightPolicy'] && !$originalAcceptedPolicies['cancellationRightPolicy'] && !$acceptedPolicies['cancellationRightPolicy']) {
                $fieldErrors['cancellationrightpolicy'] = $this->__('You must accept our cancellation right policy in order to proceed.');
            }

            if ($activePolicies['tradeConditions'] && !$originalAcceptedPolicies['tradeConditions'] && !$acceptedPolicies['tradeConditions']) {
                $fieldErrors['tradeconditions'] = $this->__('You must accept our general terms and conditions of trade in order to proceed.');
            }

            if (empty($fieldErrors)) {
                $now = new DateTime('now', new DateTimeZone('UTC'));
                $nowStr = $now->format(DateTime::ISO8601);

                if ($activePolicies['termsOfUse'] && $acceptedPolicies['termsOfUse']) {
                    $termsOfUseProcessed = UserUtil::setVar(Legal_Constant::ATTRIBUTE_TERMSOFUSE_ACCEPTED, $nowStr, $policiesUid);
                } else {
                    $termsOfUseProcessed = !$activePolicies['termsOfUse'] || $originalAcceptedPolicies['termsOfUse'];
                }

                if ($activePolicies['privacyPolicy'] && $acceptedPolicies['privacyPolicy']) {
                    $privacyPolicyProcessed = UserUtil::setVar(Legal_Constant::ATTRIBUTE_PRIVACYPOLICY_ACCEPTED, $nowStr, $policiesUid);
                } else {
                    $privacyPolicyProcessed = !$activePolicies['privacyPolicy'] || $originalAcceptedPolicies['privacyPolicy'];
                }

                if ($activePolicies['agePolicy'] && $acceptedPolicies['agePolicy']) {
                    $agePolicyProcessed = UserUtil::setVar(Legal_Constant::ATTRIBUTE_AGEPOLICY_CONFIRMED, $nowStr, $policiesUid);
                } else {
                    $agePolicyProcessed = !$activePolicies['agePolicy'] || $originalAcceptedPolicies['agePolicy'];
                }

                if ($activePolicies['cancellationRightPolicy'] && $acceptedPolicies['cancellationRightPolicy']) {
                    $cancellationRightPolicyProcessed = UserUtil::setVar(Legal_Constant::ATTRIBUTE_CANCELLATIONRIGHTPOLICY_ACCEPTED, $nowStr, $policiesUid);
                } else {
                    $cancellationRightPolicyProcessed = !$activePolicies['cancellationRightPolicy'] || $originalAcceptedPolicies['cancellationRightPolicy'];
                }

                if ($activePolicies['tradeConditions'] && $acceptedPolicies['tradeConditions']) {
                    $tradeConditionsProcessed = UserUtil::setVar(Legal_Constant::ATTRIBUTE_TRADECONDITIONS_ACCEPTED, $nowStr, $policiesUid);
                } else {
                    $tradeConditionsProcessed = !$activePolicies['tradeConditions'] || $originalAcceptedPolicies['tradeConditions'];
                }

                $processed = $termsOfUseProcessed && $privacyPolicyProcessed && $agePolicyProcessed && $cancellationRightPolicyProcessed && $tradeConditionsProcessed;
            }

            if ($processed) {
                if ($isLogin) {
                    $loginArgs = $this->request->getSession()->get('Users_Controller_User_login', array(), 'Zikula_Users');
                    $loginArgs['authentication_method'] = $sessionVars['authentication_method'];
                    $loginArgs['authentication_info']   = $sessionVars['authentication_info'];
                    $loginArgs['rememberme']            = $sessionVars['rememberme'];
                    return ModUtil::func('Users', 'user', 'login', $loginArgs);
                } else {
                    $this->redirect(System::getHomepageUrl());
                }
            }
        } elseif ($this->request->isGet()) {
            $isLogin = $this->request->getGet()->get('login', false);
            $fieldErrors = array();
        } else {
            throw new Zikula_Exception_Forbidden();
        }

        // If we are coming here from the login process, then there are certain things that must have been
        // send along in the session variable. If not, then error.
        if ($isLogin && (!isset($sessionVars['user_obj']) || !is_array($sessionVars['user_obj'])
                || !isset($sessionVars['authentication_info']) || !is_array($sessionVars['authentication_info'])
                || !isset($sessionVars['authentication_method']) || !is_array($sessionVars['authentication_method']))
                ) {
            throw new Zikula_Exception_Fatal();
        }

        if ($isLogin) {
            $policiesUid = $sessionVars['user_obj']['uid'];
        } else {
            $policiesUid = UserUtil::getVar('uid');
        }

        if (!$policiesUid || empty($policiesUid)) {
            throw new Zikula_Exception_Fatal();
        }

        if ($isLogin) {
            // Pass along the session vars to updateAcceptance. We didn't want to just keep them in the session variable
            // Legal_Controller_User_acceptPolicies because if we hit an exception or got redirected, then the data
            // would have been orphaned, and it contains some sensitive information.
            SessionUtil::requireSession();
            $this->request->getSession()->set('Legal_Controller_User_acceptPolicies', $sessionVars, $this->name);
        }

        $templateVars = array(
            'login'                     => $isLogin,
            'policiesUid'               => $policiesUid,
            'activePolicies'            => $helper->getActivePolicies(),
            'acceptedPolicies'          => isset($acceptedPolicies) ? $acceptedPolicies : $helper->getAcceptedPolicies($policiesUid),
            'originalAcceptedPolicies'  => isset($originalAcceptedPolicies) ? $originalAcceptedPolicies : $helper->getAcceptedPolicies($policiesUid),
            'fieldErrors'               => $fieldErrors,
        );

        return $this->view->assign($templateVars)
                ->fetch('legal_user_acceptpolicies.tpl');
    }
Example #9
0
 /**
  * Disable mobile Theme 
  *
  * @return string html output
  */
 public function disableMobileTheme()
 {
     CookieUtil::setCookie('zikulaMobileTheme', '2', time()+3600*24*365, '/');
     return $this->redirect(System::getHomepageUrl());
 }
Example #10
0
    /**
     * Log into a site that is currently "off" (normal logins are not allowed).
     *
     * Allows the administrator to access the site during maintenance.
     *
     * Parameters passed via GET:
     * --------------------------
     * None.
     *
     * Parameters passed via POST:
     * ---------------------------
     * string  user       The user name of the user attempting to log in.
     * string  pass       The password of the user attempting to log in.
     * boolean rememberme Whether the login session should persist.
     *
     * Parameters passed via SESSION:
     * ------------------------------
     * None.
     *
     * @return bool True.
     */
    public function siteOffLogin()
    {
        // do not process if the site is enabled
        $this->redirectIf(!System::getVar('siteoff', false), System::getHomepageUrl());

        if ($this->request->isPost()) {
            $user = $this->request->request->get('user', null);
            $pass = $this->request->request->get('pass', null);
            $rememberme = $this->request->request->get('rememberme', false);
        } else {
            throw new Zikula_Exception_Forbidden();
        }

        $redirectUrl = System::getHomepageUrl();

        $authenticationInfo = array(
            'login_id'  => $user,
            'pass'      => $pass
        );
        $authenticationMethod = array(
            'modname'   => $this->name,
            'method'    => 'uname',
        );

        if (UserUtil::loginUsing($authenticationMethod, $authenticationInfo, $rememberme)) {
            $user = UserUtil::getVars(UserUtil::getVar('uid'));
            if (!SecurityUtil::checkPermission('Settings::', 'SiteOff::', ACCESS_ADMIN)) {
                UserUtil::logout();

                $eventArgs = array(
                    'authentication_method' => $authenticationMethod,
                    'redirecturl'           => '',
                );
                $event = new Zikula_Event('module.users.ui.login.failed', $user, $eventArgs);
                $event = $this->eventManager->notify($event);
                $redirectUrl = $event->hasArg('redirecturl') ? $event->getArg('redirecturl') : $redirectUrl;
            } else {
                $eventArgs = array(
                    'authentication_method' => $authenticationMethod,
                    'redirecturl'           => $redirectUrl,
                );
                $event = new Zikula_Event('module.users.ui.login.succeeded', $user, $eventArgs);
                $event = $this->eventManager->notify($event);
                $redirectUrl = $event->hasArg('redirecturl') ? $event->getArg('redirecturl') : $redirectUrl;
            }
        } else {
            $eventArgs = array(
                'authentication_method' => $authenticationMethod,
                'authentication_info'   => $authenticationInfo,
                'redirecturl'           => '',
            );
            $event = new Zikula_Event('module.users.ui.login.failed', null, $eventArgs);
            $event = $this->eventManager->notify($event);
            $redirectUrl = $event->hasArg('redirecturl') ? $event->getArg('redirecturl') : '';
        }

        $this->redirect($redirectUrl);
    }
/**
 * BlankTheme plugin to display the user navigation menu.
 *
 * Available parameters:
 *  - id           (string) ID of the wrapper div (default: 'nav_main')
 *  - current      (string) Current screen ID (.ini current value or module name) (optional)
 *  - currentclass (string) CSS class name of the current tab, list item (default: 'current')
 *  - span         (bool)   Flag to enable SPAN wrappers on the links text, useful for sliding doors (default: false)
 *  - desc         (bool)   Flag to put the parent links descriptions inside SPAN.bt_desc instead the link title (default: false)
 *
 * Example:
 *  {bt_userlinks id='myId' current='home' currentclass='myActiveClass'}
 *
 * @author Mateo Tibaquirá
 * @since  08/11/07
 *
 * @param array             $params All parameters passed to this function from the template.
 * @param Zikula_View_Theme &$view  Reference to the View_Theme object.
 *
 * @return string User menu output.
 */
function smarty_function_bt_userlinks($params, Zikula_View_Theme &$view)
{
    $dom = ZLanguage::getThemeDomain('BlankTheme');

    $id = isset($params['id']) ? $params['id'] : 'nav_main';
    if (!isset($params['current'])) {
        $current = $view->getTplVar('current') ? $view->getTplVar('current') : $view->getToplevelmodule();
    } else {
        $current = $params['current'];
    }
    $currentclass = isset($params['currentclass']) ? $params['currentclass'] : 'current';
    $span = isset($params['span']) ? (bool)$params['span'] : false;
    $desc = isset($params['desc']) ? (bool)$params['desc'] : false;

    /*** Build the menu-array ***/
    $menu   = array();
    $menu[] = array(
                  'home',                      // page id / module name
                  __('Home', $dom),            // translatable title
                  __('Go to home page', $dom), // translatable description
                  System::getHomepageUrl(),    // link
                  null                         // array of sublinks (optional)
              );

    if (ModUtil::available('News')) {
        $menu[] = array(
                      'News',
                      __('News', $dom),
                      __('Articles index', $dom),
                      ModUtil::url('News', 'user', 'main')
                  );
    }

    if (ModUtil::available('Pages')) {
        $menu[] = array(
                      'Pages',
                      __('Pages', $dom),
                      __('Content section', $dom),
                      ModUtil::url('Pages', 'user', 'main')
                  );
    }

    if (ModUtil::available('Dizkus')) {
        $menu[] = array(
                      'Dizkus',
                      __('Forums', $dom),
                      __('Discuss area', $dom),
                      ModUtil::url('Dizkus', 'user', 'main')
                  );
    }

    if (ModUtil::available('FAQ')) {
        $menu[] = array(
                      'FAQ',
                      __('FAQ', $dom),
                      __('Frequent questions', $dom),
                      ModUtil::url('FAQ', 'user', 'main')
                  );
    }

    if (ModUtil::available('Wikula')) {
        $menu[] = array(
                      'Wikula',
                      __('Wiki', $dom),
                      __('Documents', $dom),
                      ModUtil::url('Wikula', 'user', 'main')
                  );
    }

    if (ModUtil::available('TimeIt')) {
        $menu[] = array(
                      'TimeIt',
                      __('Calendar', $dom),
                      __('List of events', $dom),
                      ModUtil::url('TimeIt', 'user', 'main')
                  );
    }

    if (ModUtil::available('crpCalendar')) {
        $menu[] = array(
                      'crpCalendar',
                      __('Calendar', $dom),
                      __('List of events', $dom),
                      ModUtil::url('crpCalendar', 'user', 'main')
                  );
    }

    if (ModUtil::available('Formicula')) {
        $menu[] = array(
                      'Formicula',
                      __('Contact us', $dom),
                      __('Comment or suggest', $dom),
                      ModUtil::url('Formicula', 'user', 'main')
                  );
    }

    // render the menu
    $output  = '<div id="'.$id.'"><ul>';
    foreach ($menu as $option) {
        $output .= bt_userlinks_drawmenu($option, $current, $currentclass, $span, $desc);
    }
    $output .= '</ul></div>';

    return $output;
}
Example #12
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", '');
}
Example #13
0
 /**
  * main funcion
  * The main function is not used in the bbsmile module, we just rediret to homepage
  *
  */
 public function main()
 {
     return System::redirect(System::getHomepageUrl());
 }
Example #14
0
    /**
     * When Zikula authentication has failed, start SiriusXtecAuth
     * 
     * @return bool true authetication succesful
     */
    public static function trySiriusXtecAuth(Zikula_Event $event)
    {
        $authentication_info = FormUtil::getPassedValue('authentication_info', isset($args['authentication_info']) ? $args['authentication_info'] : null, 'POST');
        // Argument check
        if ($authentication_info['login_id'] == '' || $authentication_info['pass'] == '') {
            LogUtil::registerError(__('Usuari o contrasenya en blanc.'));
            return System::redirect(System::getHomepageUrl());
        }

        $uname = $authentication_info['login_id'];
        $pass = $authentication_info['pass'];

        // check if ldap is active
        if (!ModUtil::getVar('SiriusXtecAuth','ldap_active',false)) return false;
        // checking new users case
        $userid = UserUtil::getIdFromName($uname);
        if (($userid === false) && (ModUtil::getVar('SiriusXtecAuth','users_creation',false) === false)) return false;
        
        // connect to ldap server
        if (!$ldap_ds = ldap_connect(ModUtil::getVar('SiriusXtecAuth', 'ldap_server'))) {
            LogUtil::registerError(__('No ha pogut connectar amb el servidor ldap.'));
            return false;
        }        
        ///////////////////
        // Checking ldap validation
        $ldaprdn = ModUtil::getVar('SiriusXtecAuth', 'ldap_searchattr') . '=' . $uname . ',' . ModUtil::getVar('SiriusXtecAuth', 'ldap_basedn');
        $bind = @ldap_bind($ldap_ds, $ldaprdn, $pass);
        if (!$bind) {
            LogUtil::registerError(__('La informació introduïda no correspon a cap validació manual ni XTEC.'));
            return false;
        }
        LogUtil::getErrorMessages();
        // Case new users
        if ($userid === false) {
            $userLdapFields = array ('cn', 'uid', 'givenname', 'sn', 'mail');
            // search the directory for our user
            if (!$ldap_sr = ldap_search($ldap_ds, ModUtil::getVar('SiriusXtecAuth', 'ldap_basedn'), ModUtil::getVar('SiriusXtecAuth', 'ldap_searchattr') . '=' . DataUtil::formatForStore($uname),$userLdapFields)) {
                LogUtil::registerError(__('Problemes en la creació d\'un nou usuari de Sirus des de la validació XTEC (I).'));
                return false;
            }
            $info = ldap_get_entries($ldap_ds, $ldap_sr);
            if (!$info || $info['count'] == 0) {
                LogUtil::registerError('Problemes en la creació d\'un nou usuari de Sirus des de la validació XTEC (II).');
                return false;
            } else {
                if (!isset($info[0]['dn'])) {
                    LogUtil::registerError('Problemes en la creació d\'un nou usuari de Sirus des de la validació XTEC (III).');
                    return false;
                }
            }
            
            $user['zk']['uname'] =$uname;
            $user['zk']['email'] = $info[0]['mail'][0];
            if (ModUtil::getVar('SiriusXtecAuth','iw_write',false) && ModUtil::available('IWusers')) {
                $user['iw']['nom'] = ucwords(strtolower($info[0]['givenname'][0]));
                $cognom_separator = strpos($info[0]['sn'][0],' ');
                if ($cognom_separator && ModUtil::getVar('SiriusXtecAuth','iw_lastnames',false)) {
                    $user['iw']['cognom1'] = ucwords(strtolower(substr($info[0]['sn'][0],0,$cognom_separator)));
                    $user['iw']['cognom2'] = ucwords(strtolower(substr($info[0]['sn'][0],$cognom_separator+1)));
                } else{
                    $user['iw']['cognom1'] = ucwords(strtolower($info[0]['sn'][0]));
                    $user['iw']['cognom1'] = '';
                }
            }
            if (ModUtil::getVar('SiriusXtecAuth','new_users_activation', false)) {
                $user['zk']['activated'] = 1;
            }else {
                $user['zk']['activated'] = 0;
            }
            $user['gr'] = ModUtil::getVar('SiriusXtecAuth','new_users_groups');
            
            $userid = ModUtil::apifunc('SiriusXtecAuth', 'listeners', 'createUser', $user);
            if (!$userid) {
                LogUtil::registerError(__('No s\'ha pogut crear l\'usuari. Torneu a validar-vos.'));
                return false;
            }
            
        }
        
        @ldap_unbind($ldap_ds);
        UserUtil::setUserByUid($userid);
        
        if (!ModUtil::getVar('SiriusXtecAuth','loginXtecApps',false)) {
            return System::redirect(System::getHomepageUrl());
        } else {
			$pass_e = urlencode(base64_encode($pass));
            return System::redirect(ModUtil::url('SiriusXtecAuth', 'user', 'logingXtecApps',array('uname'=>$uname,'pass'=>$pass_e,'logtype'=>'in')));
        }

    }
Example #15
0
    /**
     * Create a new user or registration.
     *
     * This is the primary and almost exclusive method for creating new user accounts, and the primary and
     * exclusive method for creating registration applications that are either pending approval, pending e-mail
     * verification, or both. 99.9% of all cases where a new user record needs to be created should use this
     * function to create the user or registration. This will ensure that all users and registrations are created
     * consistently, and that the system configuration for approval and verification is carried out correctly.
     * Only a few system-related internal edge cases should attempt to create user accounts without going through
     * this function.
     *
     * All information provided to this function is in the form of registration data, even if it is expected that
     * the end result will be a fully active user account.
     *
     * Parameters passed in the $args array:
     * -------------------------------------
     * array   $args['reginfo']                 The core registration or user information collected from the user.
     * numeric $args['reginfo']['uid']          If the information is for a new user registration, then this should not be set. Otherwise,
     *                                                  the uid of the registration record.
     * string  $args['reginfo']['uname']        The user name for the registering user.
     * string  $args['reginfo']['pass']         The password for the registering user.
     * string  $args['reginfo']['passreminder'] The password reminder for the registering user.
     * string  $args['reginfo']['email']        The e-mail address for the registering user.
     *
     * @param array $args All arguments passed to this function.
     *
     * @return array|bool If the user registration information is successfully saved (either full user record was
     *                      created or a pending registration record was created in the users table), then the array containing
     *                      the information saved is returned; false on error.
     *
     * @throws Zikula_Exception_Forbidden Thrown if the user does not have read access.
     */
    public function registerNewUser($args)
    {
        if (!SecurityUtil::checkPermission('Users::', '::', ACCESS_READ)) {
            throw new Zikula_Exception_Forbidden();
        }

        $isAdmin = $this->currentUserIsAdmin();
        $isAdminOrSubAdmin = $this->currentUserIsAdminOrSubAdmin();

        if (!$isAdmin && !$this->getVar('reg_allowreg', false)) {
            $registrationUnavailableReason = $this->getVar('reg_noregreasons', $this->__('New user registration is currently disabled.'));
            $this->registerError($registrationUnavailableReason, 403, System::getHomepageUrl());

            return false;
        }

        if (!isset($args['reginfo']) || empty($args['reginfo']) || !is_array($args['reginfo'])) {
            $this->registerError(LogUtil::getErrorMsgArgs());

            return false;
        }
        $reginfo = $args['reginfo'];

        $adminWantsVerification = $isAdminOrSubAdmin && ((isset($args['usermustverify']) ? (bool)$args['usermustverify'] : false)
            || !isset($reginfo['pass']) || empty($reginfo['pass']));
        $reginfo['isverified'] = ($isAdminOrSubAdmin && !$adminWantsVerification) || (!$isAdminOrSubAdmin && ($this->getVar('reg_verifyemail') == Users_Constant::VERIFY_NO));
        $reginfo['isapproved'] = $isAdminOrSubAdmin || !$this->getVar('moderation', false);
        $createRegistration = !$reginfo['isapproved'] || !$reginfo['isverified'];

        // Notification flags
        $userNotification = isset($args['usernotification']) ? $args['usernotification'] : true;
        $adminNotification = isset($args['adminnotification']) ? $args['adminnotification'] : true;

        // Handle password
        $sendPassword = isset($args['sendpass']) ? $args['sendpass'] : false;

        if ($sendPassword) {
            // Function called by admin adding user/reg, administrator created the password; no approval needed, so must need verification.
            $passwordCreatedForUser = $reginfo['pass'];
        } else {
            $passwordCreatedForUser = '';
        }

        if (isset($reginfo['pass']) && !empty($reginfo['pass']) && ($reginfo['pass'] != Users_Constant::PWD_NO_USERS_AUTHENTICATION)) {
            $reginfo['pass'] = UserUtil::getHashedPassword($reginfo['pass']);
        }

        // Dispatch to the appropriate function, depending on whether a registration record or a full user record is needed.
        if ($createRegistration) {
            // We need a registration record
            $registeredObj = $this->createRegistration($reginfo, $userNotification, $adminNotification, $passwordCreatedForUser);
        } else {
            // Everything is in order for a full user record
            $registeredObj = $this->createUser($reginfo, $userNotification, $adminNotification, $passwordCreatedForUser);
        }

        return $registeredObj;
    }
Example #16
0
 /**
  * Handle an AccessDeniedException
  *
  * @param GetResponseForExceptionEvent $event
  * @param $userLoggedIn
  * @param string $message a custom error message (default: 'Access Denied') (The default message from Symfony)
  * @see http://api.symfony.com/2.6/Symfony/Component/Security/Core/Exception/AccessDeniedException.html
  */
 private function handleAccessDeniedException(GetResponseForExceptionEvent $event, $userLoggedIn, $message = 'Access Denied')
 {
     if (!$userLoggedIn) {
         $message = $message == 'Access Denied' ? __('You do not have permission. You must login first.') : $message;
         $event->getRequest()->getSession()->getFlashBag()->add('error', $message);
         $params = array('returnpage' => urlencode($event->getRequest()->getSchemeAndHttpHost() . $event->getRequest()->getRequestUri()));
         // redirect to login page
         $route = $this->router->generate('zikulausersmodule_user_login', $params, RouterInterface::ABSOLUTE_URL);
     } else {
         $message = $message == 'Access Denied' ? __('You do not have permission for that action.') : $message;
         $event->getRequest()->getSession()->getFlashBag()->add('error', $message);
         // redirect to previous page
         $route = $event->getRequest()->server->get('HTTP_REFERER', \System::getHomepageUrl());
     }
     // optionally add logging action here
     $response = new RedirectResponse($route);
     $event->setResponse($response);
     $event->stopPropagation();
 }
Example #17
0
    /**
     * Common method for decoding url from bracket notation.
     *
     * @param strign url String to decode.
     *
     * @return string Decoded url.
     */
    public function encodebracketurl($url)
    {
        // allow a simple portable way to link to the home page of the site
        if (empty($url) || $url == '{homepage}') {
            return htmlspecialchars(System::getHomepageUrl());
        }

        if (!preg_match('#\{(.*)\}#', $url, $matches)) {
            return $url;
        }

        $url = explode(':', $matches[1]);

        $modname = $url[0];
        if (isset($url[1])) {
            $type = $url[1];
        } else {
            // defaults allowed here for usability
            $type = 'user';
        }

        if (isset($url[2])) {
            $func = $url[2];
        } else {
            // defaults allowed here for usability
            $func = 'main';
        }

        $params = array();
        if (isset($url[3])) {
            $urlparts = explode('&', $url[3]);
            foreach ($urlparts as $urlpart) {
                $part = explode('=', $urlpart);
                $params[trim($part[0])] = trim($part[1]);
            }
        }

        return ModUtil::url($modname, $type, $func, $params);
    }
Example #18
0
 public function processEdit(Zikula_ProcessHook $hook)
 {
     // will need this to update URLs in table
     // get db table and column for where statement
     ModUtil::dbInfoLoad('EZComments');
     $tables = DBUtil::getTables();
     $column = $tables['EZComments_column'];
     $mod = DataUtil::formatForStore($hook->getCaller());
     $objectid = DataUtil::formatForStore($hook->getId());
     $areaid = DataUtil::formatForStore($hook->getAreaId());
     $where = "{$column['modname']} = '{$mod}' AND {$column['objectid']} = '{$objectid}' AND {$column['areaid']} = '{$areaid}'";
     $objUrl = $hook->getUrl()->getUrl(null, null, false, false);
     // objecturl provided by subscriber
     // the fourth arg is forceLang and if left to default (true) then the url is malformed - core bug as of 1.3.0
     $comment = array('url' => System::getHomepageUrl() . DataUtil::formatForStore($objUrl));
     DBUtil::updateObject($comment, 'EZComments', $where);
 }
Example #19
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');
 }
Example #20
0
/**
 * get homepage URL for Zikula
 *
 * @deprecated Deprecated since version 1.3.0.
 * @see System::getHomepageUrl()
 *
 * @return string homepage URL for Zikula
 */
function pnGetHomepageURL()
{
    LogUtil::log(__f('Warning! Function %1$s is deprecated. Please use %2$s instead.', array(__FUNCTION__, 'System::getHomepageUrl')), E_USER_DEPRECATED);
    return System::getHomepageUrl();
}