Exemplo n.º 1
0
 /**
  * Constructor.
  *
  * Use FormUtil::newForm() instead of instantiating Zikula_Form_View directly.
  *
  * @param Zikula_ServiceManager $serviceManager ServiceManager.
  * @param string                $module         Module name.
  * @param integer               $caching        Caching flag (not used - just for e_strict).
  */
 public function __construct(Zikula_ServiceManager $serviceManager, $module, $caching = null)
 {
     // override behaviour of anonymous sessions
     SessionUtil::requireSession();
     // construct and use the available methods
     parent::__construct($serviceManager, $module, false);
     $this->addPluginDir('lib/legacy/viewplugins/formplugins', false);
     $this->setCaching(Zikula_View::CACHE_DISABLED);
     // custom Form setup
     $this->idCount = 1;
     $this->errorMsgSet = false;
     $this->plugins = array();
     $this->blockStack = array();
     $this->redirected = false;
     $this->validators = array();
     $this->validationChecked = false;
     $this->_isValid = null;
     $this->initializeState();
     $this->initializeStateData();
     $this->initializeIncludes();
 }
Exemplo n.º 2
0
 /**
  * Initialise Zikula.
  *
  * Carries out a number of initialisation tasks to get Zikula up and
  * running.
  *
  * @param integer $stage Stage to load.
  *
  * @return boolean True initialisation successful false otherwise.
  */
 public function init($stage = self::STAGE_ALL)
 {
     $coreInitEvent = new Zikula_Event('core.init', $this);
     // store the load stages in a global so other API's can check whats loaded
     $this->stage = $this->stage | $stage;
     if ($stage & self::STAGE_PRE && $this->stage & ~self::STAGE_PRE) {
         ModUtil::flushCache();
         System::flushCache();
         $this->eventManager->notify(new Zikula_Event('core.preinit', $this));
     }
     // Initialise and load configuration
     if ($stage & self::STAGE_CONFIG) {
         if (System::isLegacyMode()) {
             require_once 'lib/legacy/Compat.php';
         }
         // error reporting
         if (!System::isInstalling()) {
             // this is here because it depends on the config.php loading.
             $event = new Zikula_Event('setup.errorreporting', null, array('stage' => $stage));
             $this->eventManager->notify($event);
         }
         // initialise custom event listeners from config.php settings
         $coreInitEvent->setArg('stage', self::STAGE_CONFIG);
         $this->eventManager->notify($coreInitEvent);
     }
     // Check that Zikula is installed before continuing
     if (System::getVar('installed') == 0 && !System::isInstalling()) {
         System::redirect(System::getBaseUrl() . 'install.php?notinstalled');
         System::shutDown();
     }
     if ($stage & self::STAGE_DB) {
         try {
             $dbEvent = new Zikula_Event('core.init', $this, array('stage' => self::STAGE_DB));
             $this->eventManager->notify($dbEvent);
         } catch (PDOException $e) {
             if (!System::isInstalling()) {
                 header('HTTP/1.1 503 Service Unavailable');
                 require_once System::getSystemErrorTemplate('dbconnectionerror.tpl');
                 System::shutDown();
             } else {
                 return false;
             }
         }
     }
     if ($stage & self::STAGE_TABLES) {
         // Initialise dbtables
         ModUtil::dbInfoLoad('Extensions', 'Extensions');
         ModUtil::initCoreVars();
         ModUtil::dbInfoLoad('Settings', 'Settings');
         ModUtil::dbInfoLoad('Theme', 'Theme');
         ModUtil::dbInfoLoad('Users', 'Users');
         ModUtil::dbInfoLoad('Groups', 'Groups');
         ModUtil::dbInfoLoad('Permissions', 'Permissions');
         ModUtil::dbInfoLoad('Categories', 'Categories');
         if (!System::isInstalling()) {
             ModUtil::registerAutoloaders();
         }
         $coreInitEvent->setArg('stage', self::STAGE_TABLES);
         $this->eventManager->notify($coreInitEvent);
     }
     if ($stage & self::STAGE_SESSIONS) {
         SessionUtil::requireSession();
         $coreInitEvent->setArg('stage', self::STAGE_SESSIONS);
         $this->eventManager->notify($coreInitEvent);
     }
     // Have to load in this order specifically since we cant setup the languages until we've decoded the URL if required (drak)
     // start block
     if ($stage & self::STAGE_LANGS) {
         $lang = ZLanguage::getInstance();
     }
     if ($stage & self::STAGE_DECODEURLS) {
         System::queryStringDecode();
         $coreInitEvent->setArg('stage', self::STAGE_DECODEURLS);
         $this->eventManager->notify($coreInitEvent);
     }
     if ($stage & self::STAGE_LANGS) {
         $lang->setup();
         $coreInitEvent->setArg('stage', self::STAGE_LANGS);
         $this->eventManager->notify($coreInitEvent);
     }
     // end block
     if ($stage & self::STAGE_MODS) {
         // Set compression on if desired
         if (System::getVar('UseCompression') == 1) {
             //ob_start("ob_gzhandler");
         }
         ModUtil::load('SecurityCenter');
         $coreInitEvent->setArg('stage', self::STAGE_MODS);
         $this->eventManager->notify($coreInitEvent);
     }
     if ($stage & self::STAGE_THEME) {
         // register default page vars
         PageUtil::registerVar('title');
         PageUtil::setVar('title', System::getVar('defaultpagetitle'));
         PageUtil::registerVar('keywords', true);
         PageUtil::registerVar('stylesheet', true);
         PageUtil::registerVar('javascript', true);
         PageUtil::registerVar('jsgettext', true);
         PageUtil::registerVar('body', true);
         PageUtil::registerVar('header', true);
         PageUtil::registerVar('footer', true);
         $theme = Zikula_View_Theme::getInstance();
         // set some defaults
         // Metadata for SEO
         $this->serviceManager['zikula_view.metatags']['description'] = System::getVar('defaultmetadescription');
         $this->serviceManager['zikula_view.metatags']['keywords'] = System::getVar('metakeywords');
         $coreInitEvent->setArg('stage', self::STAGE_THEME);
         $this->eventManager->notify($coreInitEvent);
     }
     // check the users status, if not 1 then log him out
     if (UserUtil::isLoggedIn()) {
         $userstatus = UserUtil::getVar('activated');
         if ($userstatus != Users_Constant::ACTIVATED_ACTIVE) {
             UserUtil::logout();
             // TODO - When getting logged out this way, the existing session is destroyed and
             //        then a new one is created on the reentry into index.php. The message
             //        set by the registerStatus call below gets lost.
             LogUtil::registerStatus(__('You have been logged out.'));
             System::redirect(ModUtil::url('Users', 'user', 'login'));
         }
     }
     if ($stage & self::STAGE_POST && $this->stage & ~self::STAGE_POST) {
         $this->eventManager->notify(new Zikula_Event('core.postinit', $this, array('stages' => $stage)));
     }
 }
Exemplo n.º 3
0
 /**
  * Sets the currently logged in active user to the user account for the given uid.
  *
  * No events are fired from this function. To receive events, use {@link loginUsing()}.
  *
  * @param numeric $uid        The user id of the user who should be logged into the system; required.
  * @param boolean $rememberMe If the user's login should be maintained on the computer from which the user is logging in, set this to true;
  *                                          optional, defaults to false.
  * @param array $authenticationMethod An array containing the authentication method used to log the user in; optional,
  *                                          defaults to the 'Users' module 'uname' method.
  *
  * @return void
  */
 public static function setUserByUid($uid, $rememberMe = false, array $authenticationMethod = null)
 {
     if (!isset($uid) || empty($uid) || (string) (int) $uid != $uid) {
         throw new Zikula_Exception_Fatal(__('Attempt to set the current user with an invalid uid.'));
     }
     $userObj = self::getVars($uid);
     if (!isset($userObj) || !is_array($userObj) || empty($userObj)) {
         throw new Zikula_Exception_Fatal(__('Attempt to set the current user with an unknown uid.'));
     }
     if (!isset($authenticationMethod)) {
         $authenticationMethod = array('modname' => 'Users', 'method' => 'uname');
     } elseif (empty($authenticationMethod) || !isset($authenticationMethod['modname']) || empty($authenticationMethod['modname']) || !isset($authenticationMethod['method']) || empty($authenticationMethod['method'])) {
         throw new Zikula_Exception_Fatal(__('Attempt to set the current user with an invalid authentication method.'));
     }
     // Storing Last Login date -- store it in UTC! Do not use date() function!
     $nowUTC = new DateTime(null, new DateTimeZone('UTC'));
     if (!self::setVar('lastlogin', $nowUTC->format('Y-m-d H:i:s'), $userObj['uid'])) {
         // show messages but continue
         LogUtil::registerError(__('Error! Could not save the log-in date.'));
     }
     if (!System::isInstalling()) {
         SessionUtil::requireSession();
     }
     $session = ServiceUtil::get('request')->getSession();
     // Set session variables -- this is what really does the Zikula login
     $session->set('uid', $userObj['uid']);
     $session->set('users/authentication_method', $authenticationMethod);
     if (!empty($rememberMe)) {
         $session->set('rememberme', 1);
     }
     // now that we've logged in the permissions previously calculated (if any) are invalid
     $GLOBALS['authinfogathered'][$userObj['uid']] = 0;
 }
Exemplo n.º 4
0
/**
 * Generate the upgrade module page.
 *
 * This function upgrade available module to an upgrade
 *
 * @param string $username Username of the admin user.
 * @param string $password Password of the admin user.
 *
 * @return void
 */
function _upg_upgrademodules($username, $password)
{
    _upg_header();
    $modvars = DBUtil::selectObjectArray('module_vars');
    foreach ($modvars as $modvar) {
        if ($modvar['value'] == '0' || $modvar['value'] == '1') {
            $modvar['value'] = serialize($modvar['value']);
            DBUtil::updateObject($modvar, 'module_vars');
        }
    }
    // force load the modules admin API
    ModUtil::loadApi('Extensions', 'admin', true);
    echo '<h2>' . __('Starting upgrade') . '</h2>' . "\n";
    echo '<ul id="upgradelist" class="check">' . "\n";
    // reset for User module
    //$GLOBALS['_ZikulaUpgrader']['_ZikulaUpgradeFrom12x'] = false;
    $results = ModUtil::apiFunc('Extensions', 'admin', 'upgradeall');
    if ($results) {
        foreach ($results as $modname => $result) {
            if ($result) {
                echo '<li class="passed">' . DataUtil::formatForDisplay($modname) . ' ' . __('upgraded') . '</li>' . "\n";
            } else {
                echo '<li class="failed">' . DataUtil::formatForDisplay($modname) . ' ' . __('not upgraded') . '</li>' . "\n";
            }
        }
    }
    echo '</ul>' . "\n";
    if (!$results) {
        echo '<ul class="check"><li class="passed">' . __('No modules required upgrading') . '</li></ul>';
    }
    // wipe out the deprecated modules from Modules list.
    $modTable = 'modules';
    $sql = "DELETE FROM {$modTable} WHERE name = 'Header_Footer' OR name = 'AuthPN' OR name = 'pnForm' OR name = 'Workflow' OR name = 'pnRender' OR name = 'Admin_Messages'";
    DBUtil::executeSQL($sql);
    // store localized displayname and description for Extensions module
    $extensionsDisplayname = __('Extensions');
    $extensionsDescription = __('Manage your modules and plugins.');
    $sql = "UPDATE modules SET name = 'Extensions', displayname = '{$extensionsDisplayname}', description = '{$extensionsDescription}' WHERE modules.name = 'Extensions'";
    DBUtil::executeSQL($sql);
    // regenerate the themes list
    ModUtil::apiFunc('Theme', 'admin', 'regenerate');
    // store the recent version in a config var for later usage. This enables us to determine the version we are upgrading from
    System::setVar('Version_Num', Zikula_Core::VERSION_NUM);
    System::setVar('language_i18n', ZLanguage::getLanguageCode());
    // Relogin the admin user to give a proper admin link
    SessionUtil::requireSession();
    echo '<p class="z-statusmsg">' . __('Finished upgrade') . " - \n";
    $authenticationInfo = array('login_id' => $username, 'pass' => $password);
    $authenticationMethod = array('modname' => 'Users', 'method' => 'uname');
    if (!UserUtil::loginUsing($authenticationMethod, $authenticationInfo)) {
        $url = sprintf('<a href="%s">%s</a>', DataUtil::formatForDisplay(System::getBaseUrl()), DataUtil::formatForDisplay(System::getVar('sitename')));
        echo __f('Go to the startpage for %s', $url);
    } else {
        upgrade_clear_caches();
        $url = sprintf('<a href="%s">%s</a>', ModUtil::url('Admin', 'admin', 'adminpanel'), DataUtil::formatForDisplay(System::getVar('sitename')));
        echo __f('Go to the admin panel for %s', $url);
    }
    echo "</p>\n";
    _upg_footer();
}
Exemplo n.º 5
0
 /**
  * Generate auth key.
  *
  * @param string $modname Module name.
  *
  * @deprecated since 1.3.0
  *
  * @return string An encrypted key for use in authorisation of operations.
  */
 public static function generateAuthKey($modname = '')
 {
     // Ugly hack for Zikula_Response_Ajax which for BC reasons needs to add authid to response
     // So when this method is called by Zikula_Response_Ajax  or Zikula_Response_Ajax_Error class
     // do not mark it as deprecated.
     $trace = debug_backtrace(false);
     if (!isset($trace[1]['class']) || !in_array($trace[1]['class'], array('Zikula_Response_Ajax', 'Zikula_Response_Ajax_Error'))) {
         LogUtil::log(__f('Warning! Static call %1$s is deprecated. Please use %2$s instead.', array('SecurityUtil::generateAuthKey()', 'SecurityUtil::generateCsrfToken()')), E_USER_DEPRECATED);
     }
     // since we need sessions for authorisation keys we should check
     // if a session exists and if not create one
     SessionUtil::requireSession();
     if (empty($modname)) {
         $modname = ModUtil::getName();
     }
     // Remove from 1.4
     if (System::isLegacyMode() && $modname == 'Modules') {
         LogUtil::log(__('Warning! "Modules" module has been renamed to "Extensions".  Please update any generateAuthKey calls in PHP or templates.'));
         $modname = 'ZikulaExtensionsModule';
     }
     // get the module info
     $modinfo = ModUtil::getInfoFromName($modname);
     $modname = strtolower($modinfo['name']);
     // get the array of randomed values per module
     // and generate the one of the current module if doesn't exist
     $rand_arr = SessionUtil::getVar('rand');
     if (!isset($rand_arr[$modname])) {
         $rand_arr[$modname] = RandomUtil::getString(32, 40, false, true, true, false, true, true, false);
         SessionUtil::setVar('rand', $rand_arr);
     }
     $key = $rand_arr[$modname] . $modname;
     if (System::getVar('keyexpiry') > 0) {
         $timestamp = time();
         $authid = sha1($key . $timestamp) . $timestamp;
     } else {
         $authid = sha1($key);
     }
     // Return encrypted key
     return $authid;
 }
Exemplo n.º 6
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');
    }
Exemplo n.º 7
0
 /**
  * Initialise Zikula.
  *
  * Carries out a number of initialisation tasks to get Zikula up and
  * running.
  *
  * @param integer $stage Stage to load.
  *
  * @return boolean True initialisation successful false otherwise.
  */
 public function onInit(GetResponseEvent $event)
 {
     if ($event->getRequestType() === HttpKernelInterface::SUB_REQUEST) {
         return;
     }
     $this->dispatcher = $event->getDispatcher();
     $this->stage = $stage = self::STAGE_ALL;
     $coreInitEvent = new GenericEvent($this);
     $coreInitEvent['request'] = $event->getRequest();
     // store the load stages in a global so other API's can check whats loaded
     $this->dispatcher->dispatch(CoreEvents::PREINIT, new GenericEvent($this));
     //        // Initialise and load configuration
     //        if ($stage & self::STAGE_CONFIG) {
     //            // error reporting
     //            if (!\System::isInstalling()) {
     //                // this is here because it depends on the config.php loading.
     //                $event = new GenericEvent(null, array('stage' => $stage));
     //                $this->dispatcher->dispatch(CoreEvents::ERRORREPORTING, $event);
     //            }
     //
     //            // initialise custom event listeners from config.php settings
     //            $coreInitEvent->setArg('stage', self::STAGE_CONFIG);
     //            $this->dispatcher->dispatch(CoreEvents::INIT, $coreInitEvent);
     //        }
     //        // Check that Zikula is installed before continuing
     //        if (\System::getVar('installed') == 0 && !\System::isInstalling()) {
     //            $response = new RedirectResponse(\System::getBaseUrl().'install.php?notinstalled');
     //            $response->send();
     //            \System::shutdown();
     //        }
     if ($stage & self::STAGE_DB) {
         try {
             $dbEvent = new GenericEvent();
             $this->dispatcher->dispatch('doctrine.init_connection', $dbEvent);
             $dbEvent = new GenericEvent($this, array('stage' => self::STAGE_DB));
             $this->dispatcher->dispatch(CoreEvents::INIT, $dbEvent);
         } catch (\PDOException $e) {
             if (!\System::isInstalling()) {
                 header('HTTP/1.1 503 Service Unavailable');
                 require_once \System::getSystemErrorTemplate('dbconnectionerror.tpl');
                 \System::shutDown();
             } else {
                 return false;
             }
         }
     }
     if ($stage & self::STAGE_TABLES) {
         // Initialise dbtables
         \ModUtil::initCoreVars();
         \ModUtil::dbInfoLoad('SettingsModule', 'SettingsModule');
         \ModUtil::dbInfoLoad('ThemeModule', 'ThemeModule');
         \ModUtil::dbInfoLoad('UsersModule', 'UsersModule');
         \ModUtil::dbInfoLoad('GroupsModule', 'GroupsModule');
         \ModUtil::dbInfoLoad('PermissionsModule', 'PermissionsModule');
         \ModUtil::dbInfoLoad('CategoriesModule', 'CategoriesModule');
         if (!\System::isInstalling()) {
             \ModUtil::registerAutoloaders();
         }
         $coreInitEvent->setArg('stage', self::STAGE_TABLES);
         $this->dispatcher->dispatch(CoreEvents::INIT, $coreInitEvent);
     }
     if ($stage & self::STAGE_SESSIONS) {
         \SessionUtil::requireSession();
         $coreInitEvent->setArg('stage', self::STAGE_SESSIONS);
         $this->dispatcher->dispatch(CoreEvents::INIT, $coreInitEvent);
     }
     // Have to load in this order specifically since we cant setup the languages until we've decoded the URL if required (drak)
     // start block
     if ($stage & self::STAGE_LANGS) {
         $lang = \ZLanguage::getInstance();
     }
     if ($stage & self::STAGE_DECODEURLS) {
         \System::queryStringDecode();
         $coreInitEvent->setArg('stage', self::STAGE_DECODEURLS);
         $this->dispatcher->dispatch(CoreEvents::INIT, $coreInitEvent);
     }
     if ($stage & self::STAGE_LANGS) {
         $lang->setup();
         $coreInitEvent->setArg('stage', self::STAGE_LANGS);
         $this->dispatcher->dispatch(CoreEvents::INIT, $coreInitEvent);
     }
     // end block
     if ($stage & self::STAGE_MODS) {
         // Set compression on if desired
         if (\System::getVar('UseCompression') == 1) {
             //ob_start("ob_gzhandler");
         }
         \ModUtil::load('SecurityCenter');
         $coreInitEvent->setArg('stage', self::STAGE_MODS);
         $this->dispatcher->dispatch(CoreEvents::INIT, $coreInitEvent);
     }
     if ($stage & self::STAGE_THEME) {
         // register default page vars
         \PageUtil::registerVar('title');
         \PageUtil::setVar('title', \System::getVar('defaultpagetitle'));
         \PageUtil::registerVar('keywords', true);
         \PageUtil::registerVar('stylesheet', true);
         \PageUtil::registerVar('javascript', true);
         \PageUtil::registerVar('jsgettext', true);
         \PageUtil::registerVar('body', true);
         \PageUtil::registerVar('header', true);
         \PageUtil::registerVar('footer', true);
         $theme = \Zikula_View_Theme::getInstance();
         // set some defaults
         // Metadata for SEO
         $this->container['zikula_view.metatags']['description'] = \System::getVar('defaultmetadescription');
         $this->container['zikula_view.metatags']['keywords'] = \System::getVar('metakeywords');
         $coreInitEvent->setArg('stage', self::STAGE_THEME);
         $this->dispatcher->dispatch(CoreEvents::INIT, $coreInitEvent);
     }
     // check the users status, if not 1 then log him out
     if (\UserUtil::isLoggedIn()) {
         $userstatus = \UserUtil::getVar('activated');
         if ($userstatus != UsersConstant::ACTIVATED_ACTIVE) {
             \UserUtil::logout();
             // TODO - When getting logged out this way, the existing session is destroyed and
             //        then a new one is created on the reentry into index.php. The message
             //        set by the registerStatus call below gets lost.
             \LogUtil::registerStatus(__('You have been logged out.'));
             $response = new RedirectResponse(\ModUtil::url('Users', 'user', 'login'));
             $response->send();
             exit;
         }
     }
     if ($stage & self::STAGE_POST && $this->stage & ~self::STAGE_POST) {
         $this->dispatcher->dispatch(CoreEvents::POSTINIT, new GenericEvent($this, array('stages' => $stage)));
     }
     $this->dispatcher->dispatch('frontcontroller.predispatch', new GenericEvent());
 }
Exemplo n.º 8
0
    /**
     * Update the user's password.
     *
     * Parameters passed via GET:
     * --------------------------
     * None.
     *
     * Parameters passed via POST:
     * ---------------------------
     * string oldpassword        The original password.
     * string newpassword        The new password to be stored for the user.
     * string newpasswordconfirm Verification of the new password to be stored for the user.
     *
     * Parameters passed via SESSION:
     * ------------------------------
     * Namespace: Zikula_Users
     * Variable:  Users_Controller_User_updatePassword
     * Type:      array
     * Contents:  An array containing the information saved from the log-in attempt in order to re-enter it, including:
     *              'authentication_method', an array containing the selected authentication module name and method name,
     *              'authentication_info', an array containing the authentication information entered by the user,
     *              'user_obj', a user record containing the user information found during the log-in attempt,
     *              'password_errors', errors that have occurred during a previous pass through this function.
     *
     * @return bool True on success, otherwise false.
     */
    public function updatePassword()
    {
        $sessionVars = $this->request->getSession()->get('Users_Controller_User_updatePassword', null, 'Zikula_Users');
        $this->request->getSession()->del('Users_Controller_User_updatePassword', 'Zikula_Users');

        if (!$this->request->isPost()) {
            throw new Zikula_Exception_Forbidden();
        }

        $this->checkCsrfToken();

        if (isset($sessionVars) && !empty($sessionVars)) {
            $login = true;
            $userObj = $sessionVars['user_obj'];
        } else {
            $login = false;
            $userObj = UserUtil::getVars(UserUtil::getVar('uid'), true);
        }
        $uid = $userObj['uid'];

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

        $passwordChanged    = false;
        $currentPassword    = $this->request->request->get('oldpassword', '');
        $newPassword        = $this->request->request->get('newpassword', '');
        $newPasswordAgain   = $this->request->request->get('newpasswordconfirm', '');
        $newPasswordReminder= $this->request->request->get('passreminder', '');
        $passwordErrors     = array();

        if (empty($currentPassword) || !UserUtil::passwordsMatch($currentPassword, $userObj['pass'])) {
            $passwordErrors['oldpass'][] = $this->__('The current password you entered is not correct. Please correct your entry and try again.');
        } else {
            $passwordErrors = ModUtil::apiFunc($this->name, 'registration', 'getPasswordErrors', array(
                'uname'         => $userObj['uname'],
                'pass'          => $newPassword,
                'passagain'     => $newPasswordAgain,
                'passreminder'  => $newPasswordReminder
            ));

            if ($login && ($currentPassword == $newPassword)) {
                $passwordErrors['reginfo_pass'][] = $this->__('Your new password cannot match your current password.');
            }
        }

        if (empty($passwordErrors)) {
            if (UserUtil::setPassword($newPassword, $uid)) {
                // no user.update event for password chagnes.

                $passwordChanged = true;

                // Clear the forced change of password flag, if it exists.
                UserUtil::delVar('_Users_mustChangePassword', $uid);

                if (!UserUtil::setVar('passreminder', $newPasswordReminder, $uid)) {
                    $this->registerError($this->__('Warning! Your new password was saved, however there was a problem saving your new password reminder.'));
                } else {
                    $this->registerStatus($this->__('Done! Saved your new password.'));
                }

                $userObj = UserUtil::getVars(UserUtil::getVar('uid'), true);
                if ($login) {
                    $sessionVars['user_obj'] = $userObj;
                    if ($sessionVars['authentication_method']['modname'] == $this->name) {
                        // The password for Users module authentication was just changed.
                        // In order to successfully log in the user, we need to change it on the authentication_info.
                        $sessionVars['authentication_info']['pass'] = $newPassword;
                    }
                }
            } else {
                throw new Zikula_Exception_Fatal($this->__('Sorry! There was a problem saving your new password.'));
            }
        }

        if ($passwordChanged) {
            if ($login) {
                $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($this->name, 'user', 'login', $loginArgs);
            } else {
                return $this->redirect(ModUtil::url($this->name, 'user', 'main'));
            }
        } else {
            $sessionVars['password_errors'] = $passwordErrors;
            SessionUtil::requireSession();
            $this->request->getSession()->set('Users_Controller_User_changePassword', $sessionVars, 'Zikula_Users');
            $this->redirect(ModUtil::url($this->name, 'user', 'changePassword', array('login' => $login)));
        }
    }