From ae4b03163792f0b6e933933e5d37df87dc3fd566 Mon Sep 17 00:00:00 2001 From: mattab Date: Thu, 28 Mar 2013 12:42:39 +1300 Subject: Mass conversion of all files to the newly agreed coding standard: PSR 1/2 Converting Piwik core source files, PHP, JS, TPL, CSS More info: http://piwik.org/participate/coding-standards/ --- plugins/UsersManager/API.php | 1307 +++++++++++------------ plugins/UsersManager/Controller.php | 675 ++++++------ plugins/UsersManager/UsersManager.php | 245 +++-- plugins/UsersManager/templates/UsersManager.js | 315 +++--- plugins/UsersManager/templates/UsersManager.tpl | 251 ++--- plugins/UsersManager/templates/userSettings.js | 99 +- plugins/UsersManager/templates/userSettings.tpl | 225 ++-- 7 files changed, 1522 insertions(+), 1595 deletions(-) (limited to 'plugins/UsersManager') diff --git a/plugins/UsersManager/API.php b/plugins/UsersManager/API.php index a5e58a703e..340fb97961 100644 --- a/plugins/UsersManager/API.php +++ b/plugins/UsersManager/API.php @@ -1,698 +1,661 @@ Managing Users in Piwik. * @package Piwik_UsersManager */ -class Piwik_UsersManager_API +class Piwik_UsersManager_API { - static private $instance = null; - - /** - * You can create your own Users Plugin to override this class. - * Example of how you would overwrite the UsersManager_API with your own class: - * Call the following in your plugin __construct() for example: - * - * Zend_Registry::set('UsersManager_API',Piwik_MyCustomUsersManager_API::getInstance()); - * - * @throws Exception - * @return Piwik_UsersManager_API - */ - static public function getInstance() - { - try { - $instance = Zend_Registry::get('UsersManager_API'); - if( !($instance instanceof Piwik_UsersManager_API) ) { - // Exception is caught below and corrected - throw new Exception('UsersManager_API must inherit Piwik_UsersManager_API'); - } - self::$instance = $instance; - } - catch (Exception $e) { - self::$instance = new self; - Zend_Registry::set('UsersManager_API', self::$instance); - } - return self::$instance; - } - const PREFERENCE_DEFAULT_REPORT = 'defaultReport'; - const PREFERENCE_DEFAULT_REPORT_DATE = 'defaultReportDate'; - - /** - * Sets a user preference - * @param string $userLogin - * @param string $preferenceName - * @param string $preferenceValue - * @return void - */ - public function setUserPreference($userLogin, $preferenceName, $preferenceValue) - { - Piwik::checkUserIsSuperUserOrTheUser($userLogin); - Piwik_SetOption($this->getPreferenceId($userLogin, $preferenceName), $preferenceValue); - } - - /** - * Gets a user preference - * @param string $userLogin - * @param string $preferenceName - * @return bool|string - */ - public function getUserPreference($userLogin, $preferenceName) - { - Piwik::checkUserIsSuperUserOrTheUser($userLogin); - return Piwik_GetOption($this->getPreferenceId($userLogin, $preferenceName)); - } - - private function getPreferenceId($login, $preference) - { - return $login . '_' . $preference; - } - - /** - * Returns the list of all the users - * - * @param string $userLogins Comma separated list of users to select. If not specified, will return all users - * @return array the list of all the users - */ - public function getUsers( $userLogins = '' ) - { - Piwik::checkUserHasSomeAdminAccess(); - - $where = ''; - $bind = array(); - if(!empty($userLogins)) - { - $userLogins = explode(',', $userLogins); - $where = 'WHERE login IN ('. Piwik_Common::getSqlStringFieldsArray($userLogins).')'; - $bind = $userLogins; - } - $db = Zend_Registry::get('db'); - $users = $db->fetchAll("SELECT * - FROM ".Piwik_Common::prefixTable("user")." + static private $instance = null; + + /** + * You can create your own Users Plugin to override this class. + * Example of how you would overwrite the UsersManager_API with your own class: + * Call the following in your plugin __construct() for example: + * + * Zend_Registry::set('UsersManager_API',Piwik_MyCustomUsersManager_API::getInstance()); + * + * @throws Exception + * @return Piwik_UsersManager_API + */ + static public function getInstance() + { + try { + $instance = Zend_Registry::get('UsersManager_API'); + if (!($instance instanceof Piwik_UsersManager_API)) { + // Exception is caught below and corrected + throw new Exception('UsersManager_API must inherit Piwik_UsersManager_API'); + } + self::$instance = $instance; + } catch (Exception $e) { + self::$instance = new self; + Zend_Registry::set('UsersManager_API', self::$instance); + } + return self::$instance; + } + + const PREFERENCE_DEFAULT_REPORT = 'defaultReport'; + const PREFERENCE_DEFAULT_REPORT_DATE = 'defaultReportDate'; + + /** + * Sets a user preference + * @param string $userLogin + * @param string $preferenceName + * @param string $preferenceValue + * @return void + */ + public function setUserPreference($userLogin, $preferenceName, $preferenceValue) + { + Piwik::checkUserIsSuperUserOrTheUser($userLogin); + Piwik_SetOption($this->getPreferenceId($userLogin, $preferenceName), $preferenceValue); + } + + /** + * Gets a user preference + * @param string $userLogin + * @param string $preferenceName + * @return bool|string + */ + public function getUserPreference($userLogin, $preferenceName) + { + Piwik::checkUserIsSuperUserOrTheUser($userLogin); + return Piwik_GetOption($this->getPreferenceId($userLogin, $preferenceName)); + } + + private function getPreferenceId($login, $preference) + { + return $login . '_' . $preference; + } + + /** + * Returns the list of all the users + * + * @param string $userLogins Comma separated list of users to select. If not specified, will return all users + * @return array the list of all the users + */ + public function getUsers($userLogins = '') + { + Piwik::checkUserHasSomeAdminAccess(); + + $where = ''; + $bind = array(); + if (!empty($userLogins)) { + $userLogins = explode(',', $userLogins); + $where = 'WHERE login IN (' . Piwik_Common::getSqlStringFieldsArray($userLogins) . ')'; + $bind = $userLogins; + } + $db = Zend_Registry::get('db'); + $users = $db->fetchAll("SELECT * + FROM " . Piwik_Common::prefixTable("user") . " $where ORDER BY login ASC", $bind); - // Non Super user can only access login & alias - if(!Piwik::isUserIsSuperUser()) - { - foreach($users as &$user) - { - $user = array('login' => $user['login'], 'alias' => $user['alias'] ); - } - } - return $users; - } - - /** - * Returns the list of all the users login - * - * @return array the list of all the users login - */ - public function getUsersLogin() - { - Piwik::checkUserHasSomeAdminAccess(); - - $db = Zend_Registry::get('db'); - $users = $db->fetchAll("SELECT login - FROM ".Piwik_Common::prefixTable("user")." + // Non Super user can only access login & alias + if (!Piwik::isUserIsSuperUser()) { + foreach ($users as &$user) { + $user = array('login' => $user['login'], 'alias' => $user['alias']); + } + } + return $users; + } + + /** + * Returns the list of all the users login + * + * @return array the list of all the users login + */ + public function getUsersLogin() + { + Piwik::checkUserHasSomeAdminAccess(); + + $db = Zend_Registry::get('db'); + $users = $db->fetchAll("SELECT login + FROM " . Piwik_Common::prefixTable("user") . " ORDER BY login ASC"); - $return = array(); - foreach($users as $login) - { - $return[] = $login['login']; - } - return $return; - } - - /** - * For each user, returns the list of website IDs where the user has the supplied $access level. - * If a user doesn't have the given $access to any website IDs, - * the user will not be in the returned array. - * - * @param string Access can have the following values : 'view' or 'admin' - * - * @return array The returned array has the format - * array( - * login1 => array ( idsite1,idsite2), - * login2 => array(idsite2), - * ... - * ) - * - */ - public function getUsersSitesFromAccess( $access ) - { - Piwik::checkUserIsSuperUser(); - - $this->checkAccessType($access); - - $db = Zend_Registry::get('db'); - $users = $db->fetchAll("SELECT login,idsite - FROM ".Piwik_Common::prefixTable("access") - ." WHERE access = ? + $return = array(); + foreach ($users as $login) { + $return[] = $login['login']; + } + return $return; + } + + /** + * For each user, returns the list of website IDs where the user has the supplied $access level. + * If a user doesn't have the given $access to any website IDs, + * the user will not be in the returned array. + * + * @param string Access can have the following values : 'view' or 'admin' + * + * @return array The returned array has the format + * array( + * login1 => array ( idsite1,idsite2), + * login2 => array(idsite2), + * ... + * ) + * + */ + public function getUsersSitesFromAccess($access) + { + Piwik::checkUserIsSuperUser(); + + $this->checkAccessType($access); + + $db = Zend_Registry::get('db'); + $users = $db->fetchAll("SELECT login,idsite + FROM " . Piwik_Common::prefixTable("access") + . " WHERE access = ? ORDER BY login, idsite", $access); - $return = array(); - foreach($users as $user) - { - $return[$user['login']][] = $user['idsite']; - } - return $return; - - } - - /** - * For each user, returns his access level for the given $idSite. - * If a user doesn't have any access to the $idSite ('noaccess'), - * the user will not be in the returned array. - * - * @param string website ID - * - * @return array The returned array has the format - * array( - * login1 => 'view', - * login2 => 'admin', - * login3 => 'view', - * ... - * ) - */ - public function getUsersAccessFromSite( $idSite ) - { - Piwik::checkUserHasAdminAccess( $idSite ); - - $db = Zend_Registry::get('db'); - $users = $db->fetchAll("SELECT login,access - FROM ".Piwik_Common::prefixTable("access") - ." WHERE idsite = ?", $idSite); - $return = array(); - foreach($users as $user) - { - $return[$user['login']] = $user['access']; - } - return $return; - } - - public function getUsersWithSiteAccess( $idSite, $access ) - { - Piwik::checkUserHasAdminAccess( $idSite ); - $this->checkAccessType( $access ); - - $db = Zend_Registry::get('db'); - $users = $db->fetchAll("SELECT login - FROM ".Piwik_Common::prefixTable("access") - ." WHERE idsite = ? AND access = ?", array($idSite, $access)); - $logins = array(); - foreach($users as $user) - { - $logins[] = $user['login']; - } - if(empty($logins)) - { - return array(); - } - $logins = implode(',', $logins); - return $this->getUsers($logins); - } - - /** - * For each website ID, returns the access level of the given $userLogin. - * If the user doesn't have any access to a website ('noaccess'), - * this website will not be in the returned array. - * If the user doesn't have any access, the returned array will be an empty array. - * - * @param string User that has to be valid - * - * @return array The returned array has the format - * array( - * idsite1 => 'view', - * idsite2 => 'admin', - * idsite3 => 'view', - * ... - * ) - */ - public function getSitesAccessFromUser( $userLogin ) - { - Piwik::checkUserIsSuperUser(); - $this->checkUserExists($userLogin); - $this->checkUserIsNotSuperUser($userLogin); - - $db = Zend_Registry::get('db'); - $users = $db->fetchAll("SELECT idsite,access - FROM ".Piwik_Common::prefixTable("access") - ." WHERE login = ?", $userLogin); - $return = array(); - foreach($users as $user) - { - $return[] = array( - 'site' => $user['idsite'], - 'access' => $user['access'], - ); - } - return $return; - } - - /** - * Returns the user information (login, password md5, alias, email, date_registered, etc.) - * - * @param string the user login - * - * @return array the user information - */ - public function getUser( $userLogin ) - { - Piwik::checkUserIsSuperUserOrTheUser($userLogin); - $this->checkUserExists($userLogin); - $this->checkUserIsNotSuperUser($userLogin); - - $db = Zend_Registry::get('db'); - $user = $db->fetchRow("SELECT * - FROM ".Piwik_Common::prefixTable("user") - ." WHERE login = ?", $userLogin); - return $user; - } - - /** - * Returns the user information (login, password md5, alias, email, date_registered, etc.) - * - * @param string the user email - * - * @return array the user information - */ - public function getUserByEmail( $userEmail ) - { - Piwik::checkUserIsSuperUser(); - $this->checkUserEmailExists($userEmail); - - $db = Zend_Registry::get('db'); - $user = $db->fetchRow("SELECT * - FROM ".Piwik_Common::prefixTable("user") - ." WHERE email = ?", $userEmail); - return $user; - } - - private function checkLogin($userLogin) - { - if($this->userExists($userLogin)) - { - throw new Exception(Piwik_TranslateException('UsersManager_ExceptionLoginExists', $userLogin)); - } - - Piwik::checkValidLoginString($userLogin); - } - - private function checkEmail($email) - { - if($this->userEmailExists($email)) - { - throw new Exception(Piwik_TranslateException('UsersManager_ExceptionEmailExists', $email)); - } - - if(!Piwik::isValidEmailString($email)) - { - throw new Exception(Piwik_TranslateException('UsersManager_ExceptionInvalidEmail')); - } - } - - private function getCleanAlias($alias,$userLogin) - { - if(empty($alias)) - { - $alias = $userLogin; - } - return $alias; - } - - /** - * Add a user in the database. - * A user is defined by - * - a login that has to be unique and valid - * - a password that has to be valid - * - an alias - * - an email that has to be in a correct format - * - * @see userExists() - * @see isValidLoginString() - * @see isValidPasswordString() - * @see isValidEmailString() - * - * @exception in case of an invalid parameter - */ - public function addUser( $userLogin, $password, $email, $alias = false ) - { - Piwik::checkUserIsSuperUser(); - - $this->checkLogin($userLogin); - $this->checkUserIsNotSuperUser($userLogin); - $this->checkEmail($email); - - $password = Piwik_Common::unsanitizeInputValue($password); - Piwik_UsersManager::checkPassword($password); - - $alias = $this->getCleanAlias($alias,$userLogin); - $passwordTransformed = Piwik_UsersManager::getPasswordHash($password); - - $token_auth = $this->getTokenAuth($userLogin, $passwordTransformed); - - $db = Zend_Registry::get('db'); - - $db->insert( Piwik_Common::prefixTable("user"), array( - 'login' => $userLogin, - 'password' => $passwordTransformed, - 'alias' => $alias, - 'email' => $email, - 'token_auth' => $token_auth, - 'date_registered' => Piwik_Date::now()->getDatetime() - ) - ); - - // we reload the access list which doesn't yet take in consideration this new user - Zend_Registry::get('access')->reloadAccess(); - Piwik_Tracker_Cache::deleteTrackerCache(); - - Piwik_PostEvent('UsersManager.addUser', $userLogin); - } - - /** - * Updates a user in the database. - * Only login and password are required (case when we update the password). - * When the password changes, the key token for this user will change, which could break - * its API calls. - * - * @see addUser() for all the parameters - */ - public function updateUser( $userLogin, $password = false, $email = false, $alias = false, - $_isPasswordHashed = false ) - { - Piwik::checkUserIsSuperUserOrTheUser($userLogin); - $this->checkUserIsNotAnonymous( $userLogin ); - $this->checkUserIsNotSuperUser($userLogin); - $userInfo = $this->getUser($userLogin); - - if(empty($password)) - { - $password = $userInfo['password']; - } - else - { - $password = Piwik_Common::unsanitizeInputValue($password); - if (!$_isPasswordHashed) - { - Piwik_UsersManager::checkPassword($password); - $password = Piwik_UsersManager::getPasswordHash($password); - } - } - - if(empty($alias)) - { - $alias = $userInfo['alias']; - } - - if(empty($email)) - { - $email = $userInfo['email']; - } - - if($email != $userInfo['email']) - { - $this->checkEmail($email); - } - - $alias = $this->getCleanAlias($alias,$userLogin); - $token_auth = $this->getTokenAuth($userLogin,$password); - - $db = Zend_Registry::get('db'); - - $db->update( Piwik_Common::prefixTable("user"), - array( - 'password' => $password, - 'alias' => $alias, - 'email' => $email, - 'token_auth' => $token_auth, - ), - "login = '$userLogin'" - ); - Piwik_Tracker_Cache::deleteTrackerCache(); - - Piwik_PostEvent('UsersManager.updateUser', $userLogin); - } - - /** - * Delete a user and all its access, given its login. - * - * @param string $userLogin the user login. - * - * @throws Exception if the user doesn't exist - * - * @return bool true on success - */ - public function deleteUser( $userLogin ) - { - Piwik::checkUserIsSuperUser(); - $this->checkUserIsNotAnonymous( $userLogin ); - $this->checkUserIsNotSuperUser($userLogin); - if(!$this->userExists($userLogin)) - { - throw new Exception(Piwik_TranslateException("UsersManager_ExceptionDeleteDoesNotExist", $userLogin)); - } - - $this->deleteUserOnly( $userLogin ); - $this->deleteUserAccess( $userLogin ); - Piwik_Tracker_Cache::deleteTrackerCache(); - } - - /** - * Returns true if the given userLogin is known in the database - * - * @return bool true if the user is known - */ - public function userExists( $userLogin ) - { - $count = Piwik_FetchOne("SELECT count(*) - FROM ".Piwik_Common::prefixTable("user"). " + $return = array(); + foreach ($users as $user) { + $return[$user['login']][] = $user['idsite']; + } + return $return; + + } + + /** + * For each user, returns his access level for the given $idSite. + * If a user doesn't have any access to the $idSite ('noaccess'), + * the user will not be in the returned array. + * + * @param string website ID + * + * @return array The returned array has the format + * array( + * login1 => 'view', + * login2 => 'admin', + * login3 => 'view', + * ... + * ) + */ + public function getUsersAccessFromSite($idSite) + { + Piwik::checkUserHasAdminAccess($idSite); + + $db = Zend_Registry::get('db'); + $users = $db->fetchAll("SELECT login,access + FROM " . Piwik_Common::prefixTable("access") + . " WHERE idsite = ?", $idSite); + $return = array(); + foreach ($users as $user) { + $return[$user['login']] = $user['access']; + } + return $return; + } + + public function getUsersWithSiteAccess($idSite, $access) + { + Piwik::checkUserHasAdminAccess($idSite); + $this->checkAccessType($access); + + $db = Zend_Registry::get('db'); + $users = $db->fetchAll("SELECT login + FROM " . Piwik_Common::prefixTable("access") + . " WHERE idsite = ? AND access = ?", array($idSite, $access)); + $logins = array(); + foreach ($users as $user) { + $logins[] = $user['login']; + } + if (empty($logins)) { + return array(); + } + $logins = implode(',', $logins); + return $this->getUsers($logins); + } + + /** + * For each website ID, returns the access level of the given $userLogin. + * If the user doesn't have any access to a website ('noaccess'), + * this website will not be in the returned array. + * If the user doesn't have any access, the returned array will be an empty array. + * + * @param string User that has to be valid + * + * @return array The returned array has the format + * array( + * idsite1 => 'view', + * idsite2 => 'admin', + * idsite3 => 'view', + * ... + * ) + */ + public function getSitesAccessFromUser($userLogin) + { + Piwik::checkUserIsSuperUser(); + $this->checkUserExists($userLogin); + $this->checkUserIsNotSuperUser($userLogin); + + $db = Zend_Registry::get('db'); + $users = $db->fetchAll("SELECT idsite,access + FROM " . Piwik_Common::prefixTable("access") + . " WHERE login = ?", $userLogin); + $return = array(); + foreach ($users as $user) { + $return[] = array( + 'site' => $user['idsite'], + 'access' => $user['access'], + ); + } + return $return; + } + + /** + * Returns the user information (login, password md5, alias, email, date_registered, etc.) + * + * @param string the user login + * + * @return array the user information + */ + public function getUser($userLogin) + { + Piwik::checkUserIsSuperUserOrTheUser($userLogin); + $this->checkUserExists($userLogin); + $this->checkUserIsNotSuperUser($userLogin); + + $db = Zend_Registry::get('db'); + $user = $db->fetchRow("SELECT * + FROM " . Piwik_Common::prefixTable("user") + . " WHERE login = ?", $userLogin); + return $user; + } + + /** + * Returns the user information (login, password md5, alias, email, date_registered, etc.) + * + * @param string the user email + * + * @return array the user information + */ + public function getUserByEmail($userEmail) + { + Piwik::checkUserIsSuperUser(); + $this->checkUserEmailExists($userEmail); + + $db = Zend_Registry::get('db'); + $user = $db->fetchRow("SELECT * + FROM " . Piwik_Common::prefixTable("user") + . " WHERE email = ?", $userEmail); + return $user; + } + + private function checkLogin($userLogin) + { + if ($this->userExists($userLogin)) { + throw new Exception(Piwik_TranslateException('UsersManager_ExceptionLoginExists', $userLogin)); + } + + Piwik::checkValidLoginString($userLogin); + } + + private function checkEmail($email) + { + if ($this->userEmailExists($email)) { + throw new Exception(Piwik_TranslateException('UsersManager_ExceptionEmailExists', $email)); + } + + if (!Piwik::isValidEmailString($email)) { + throw new Exception(Piwik_TranslateException('UsersManager_ExceptionInvalidEmail')); + } + } + + private function getCleanAlias($alias, $userLogin) + { + if (empty($alias)) { + $alias = $userLogin; + } + return $alias; + } + + /** + * Add a user in the database. + * A user is defined by + * - a login that has to be unique and valid + * - a password that has to be valid + * - an alias + * - an email that has to be in a correct format + * + * @see userExists() + * @see isValidLoginString() + * @see isValidPasswordString() + * @see isValidEmailString() + * + * @exception in case of an invalid parameter + */ + public function addUser($userLogin, $password, $email, $alias = false) + { + Piwik::checkUserIsSuperUser(); + + $this->checkLogin($userLogin); + $this->checkUserIsNotSuperUser($userLogin); + $this->checkEmail($email); + + $password = Piwik_Common::unsanitizeInputValue($password); + Piwik_UsersManager::checkPassword($password); + + $alias = $this->getCleanAlias($alias, $userLogin); + $passwordTransformed = Piwik_UsersManager::getPasswordHash($password); + + $token_auth = $this->getTokenAuth($userLogin, $passwordTransformed); + + $db = Zend_Registry::get('db'); + + $db->insert(Piwik_Common::prefixTable("user"), array( + 'login' => $userLogin, + 'password' => $passwordTransformed, + 'alias' => $alias, + 'email' => $email, + 'token_auth' => $token_auth, + 'date_registered' => Piwik_Date::now()->getDatetime() + ) + ); + + // we reload the access list which doesn't yet take in consideration this new user + Zend_Registry::get('access')->reloadAccess(); + Piwik_Tracker_Cache::deleteTrackerCache(); + + Piwik_PostEvent('UsersManager.addUser', $userLogin); + } + + /** + * Updates a user in the database. + * Only login and password are required (case when we update the password). + * When the password changes, the key token for this user will change, which could break + * its API calls. + * + * @see addUser() for all the parameters + */ + public function updateUser($userLogin, $password = false, $email = false, $alias = false, + $_isPasswordHashed = false) + { + Piwik::checkUserIsSuperUserOrTheUser($userLogin); + $this->checkUserIsNotAnonymous($userLogin); + $this->checkUserIsNotSuperUser($userLogin); + $userInfo = $this->getUser($userLogin); + + if (empty($password)) { + $password = $userInfo['password']; + } else { + $password = Piwik_Common::unsanitizeInputValue($password); + if (!$_isPasswordHashed) { + Piwik_UsersManager::checkPassword($password); + $password = Piwik_UsersManager::getPasswordHash($password); + } + } + + if (empty($alias)) { + $alias = $userInfo['alias']; + } + + if (empty($email)) { + $email = $userInfo['email']; + } + + if ($email != $userInfo['email']) { + $this->checkEmail($email); + } + + $alias = $this->getCleanAlias($alias, $userLogin); + $token_auth = $this->getTokenAuth($userLogin, $password); + + $db = Zend_Registry::get('db'); + + $db->update(Piwik_Common::prefixTable("user"), + array( + 'password' => $password, + 'alias' => $alias, + 'email' => $email, + 'token_auth' => $token_auth, + ), + "login = '$userLogin'" + ); + Piwik_Tracker_Cache::deleteTrackerCache(); + + Piwik_PostEvent('UsersManager.updateUser', $userLogin); + } + + /** + * Delete a user and all its access, given its login. + * + * @param string $userLogin the user login. + * + * @throws Exception if the user doesn't exist + * + * @return bool true on success + */ + public function deleteUser($userLogin) + { + Piwik::checkUserIsSuperUser(); + $this->checkUserIsNotAnonymous($userLogin); + $this->checkUserIsNotSuperUser($userLogin); + if (!$this->userExists($userLogin)) { + throw new Exception(Piwik_TranslateException("UsersManager_ExceptionDeleteDoesNotExist", $userLogin)); + } + + $this->deleteUserOnly($userLogin); + $this->deleteUserAccess($userLogin); + Piwik_Tracker_Cache::deleteTrackerCache(); + } + + /** + * Returns true if the given userLogin is known in the database + * + * @return bool true if the user is known + */ + public function userExists($userLogin) + { + $count = Piwik_FetchOne("SELECT count(*) + FROM " . Piwik_Common::prefixTable("user") . " WHERE login = ?", $userLogin); - return $count != 0; - } - - /** - * Returns true if user with given email (userEmail) is known in the database, or the super user - * - * @return bool true if the user is known - */ - public function userEmailExists( $userEmail ) - { - Piwik::checkUserIsNotAnonymous(); - $count = Piwik_FetchOne("SELECT count(*) - FROM ".Piwik_Common::prefixTable("user"). " + return $count != 0; + } + + /** + * Returns true if user with given email (userEmail) is known in the database, or the super user + * + * @return bool true if the user is known + */ + public function userEmailExists($userEmail) + { + Piwik::checkUserIsNotAnonymous(); + $count = Piwik_FetchOne("SELECT count(*) + FROM " . Piwik_Common::prefixTable("user") . " WHERE email = ?", $userEmail); - return $count != 0 - || Piwik_Config::getInstance()->superuser['email'] == $userEmail; - } - - /** - * Set an access level to a given user for a list of websites ID. - * - * If access = 'noaccess' the current access (if any) will be deleted. - * If access = 'view' or 'admin' the current access level is deleted and updated with the new value. - * - * @param string $userLogin The user login - * @param string $access Access to grant. Must have one of the following value : noaccess, view, admin - * @param int|array $idSites The array of idSites on which to apply the access level for the user. - * If the value is "all" then we apply the access level to all the websites ID for which the current authentificated user has an 'admin' access. - * - * @throws Exception if the user doesn't exist - * @throws Exception if the access parameter doesn't have a correct value - * @throws Exception if any of the given website ID doesn't exist - * - * @return bool true on success - */ - public function setUserAccess( $userLogin, $access, $idSites) - { - $this->checkAccessType( $access ); - $this->checkUserExists( $userLogin); - $this->checkUserIsNotSuperUser($userLogin); - - if($userLogin == 'anonymous' - && $access == 'admin') - { - throw new Exception(Piwik_TranslateException("UsersManager_ExceptionAdminAnonymous")); - } - - // in case idSites is null we grant access to all the websites on which the current connected user - // has an 'admin' access - if($idSites === 'all') - { - $idSites = Piwik_SitesManager_API::getInstance()->getSitesIdWithAdminAccess(); - } - // in case the idSites is an integer we build an array - else - { - $idSites = Piwik_Site::getIdSitesFromIdSitesString($idSites); - } - - if(empty($idSites)) - { - throw new Exception('Specify at least one website ID in &idSites='); - } - // it is possible to set user access on websites only for the websites admin - // basically an admin can give the view or the admin access to any user for the websites he manages - Piwik::checkUserHasAdminAccess( $idSites ); - - $this->deleteUserAccess( $userLogin, $idSites); - - // delete UserAccess - $db = Zend_Registry::get('db'); - - // if the access is noaccess then we don't save it as this is the default value - // when no access are specified - if($access != 'noaccess') - { - foreach($idSites as $idsite) - { - $db->insert( Piwik_Common::prefixTable("access"), - array( "idsite" => $idsite, - "login" => $userLogin, - "access" => $access) - ); - } - } - - // we reload the access list which doesn't yet take in consideration this new user access - Zend_Registry::get('access')->reloadAccess(); - Piwik_Tracker_Cache::deleteTrackerCache(); - } - - /** - * Throws an exception is the user login doesn't exist - * - * @param string $userLogin user login - * @throws Exception if the user doesn't exist - */ - private function checkUserExists( $userLogin ) - { - if(!$this->userExists($userLogin)) - { - throw new Exception(Piwik_TranslateException("UsersManager_ExceptionUserDoesNotExist", $userLogin)); - } - } - - /** - * Throws an exception is the user email cannot be found - * - * @param string $userEmail user email - * @throws Exception if the user doesn't exist - */ - private function checkUserEmailExists( $userEmail ) - { - if(!$this->userEmailExists($userEmail)) - { - throw new Exception(Piwik_TranslateException("UsersManager_ExceptionUserDoesNotExist", $userEmail)); - } - } - - private function checkUserIsNotAnonymous( $userLogin ) - { - if($userLogin == 'anonymous') - { - throw new Exception(Piwik_TranslateException("UsersManager_ExceptionEditAnonymous")); - } - } - - private function checkUserIsNotSuperUser( $userLogin ) - { - if($userLogin == Piwik_Config::getInstance()->superuser['login']) - { - throw new Exception(Piwik_TranslateException("UsersManager_ExceptionSuperUser")); - } - } - - private function checkAccessType($access) - { - $accessList = Piwik_Access::getListAccess(); - - // do not allow to set the superUser access - unset($accessList[array_search("superuser", $accessList)]); - - if(!in_array($access,$accessList)) - { - throw new Exception(Piwik_TranslateException("UsersManager_ExceptionAccessValues", implode(", ", $accessList))); - } - } - - /** - * Delete a user given its login. - * The user's access are not deleted. - * - * @param string the user login. - * - */ - private function deleteUserOnly( $userLogin ) - { - $db = Zend_Registry::get('db'); - $db->query("DELETE FROM ".Piwik_Common::prefixTable("user")." WHERE login = ?", $userLogin); - - Piwik_PostEvent('UsersManager.deleteUser', $userLogin); - } - - - /** - * Delete the user access for the given websites. - * The array of idsite must be either null OR the values must have been checked before for their validity! - * - * @param string the user login - * @param array array of idsites on which to delete the access. If null then delete all the access for this user. - * - * @return bool true on success - */ - private function deleteUserAccess( $userLogin, $idSites = null ) - { - $db = Zend_Registry::get('db'); - - if(is_null($idSites)) - { - $db->query( "DELETE FROM ".Piwik_Common::prefixTable("access"). - " WHERE login = ?", - array( $userLogin) ); - } - else - { - foreach($idSites as $idsite) - { - $db->query( "DELETE FROM ".Piwik_Common::prefixTable("access"). - " WHERE idsite = ? AND login = ?", - array($idsite, $userLogin) - ); - } - } - } - - /** - * Generates a unique MD5 for the given login & password - * - * @param string $userLogin Login - * @param string $md5Password MD5ied string of the password - * @throws Exception - * @return string - */ - public function getTokenAuth($userLogin, $md5Password) - { - if(strlen($md5Password) != 32) - { - throw new Exception(Piwik_TranslateException('UsersManager_ExceptionPasswordMD5HashExpected')); - } - return md5($userLogin . $md5Password ); - } + return $count != 0 + || Piwik_Config::getInstance()->superuser['email'] == $userEmail; + } + + /** + * Set an access level to a given user for a list of websites ID. + * + * If access = 'noaccess' the current access (if any) will be deleted. + * If access = 'view' or 'admin' the current access level is deleted and updated with the new value. + * + * @param string $userLogin The user login + * @param string $access Access to grant. Must have one of the following value : noaccess, view, admin + * @param int|array $idSites The array of idSites on which to apply the access level for the user. + * If the value is "all" then we apply the access level to all the websites ID for which the current authentificated user has an 'admin' access. + * + * @throws Exception if the user doesn't exist + * @throws Exception if the access parameter doesn't have a correct value + * @throws Exception if any of the given website ID doesn't exist + * + * @return bool true on success + */ + public function setUserAccess($userLogin, $access, $idSites) + { + $this->checkAccessType($access); + $this->checkUserExists($userLogin); + $this->checkUserIsNotSuperUser($userLogin); + + if ($userLogin == 'anonymous' + && $access == 'admin' + ) { + throw new Exception(Piwik_TranslateException("UsersManager_ExceptionAdminAnonymous")); + } + + // in case idSites is null we grant access to all the websites on which the current connected user + // has an 'admin' access + if ($idSites === 'all') { + $idSites = Piwik_SitesManager_API::getInstance()->getSitesIdWithAdminAccess(); + } // in case the idSites is an integer we build an array + else { + $idSites = Piwik_Site::getIdSitesFromIdSitesString($idSites); + } + + if (empty($idSites)) { + throw new Exception('Specify at least one website ID in &idSites='); + } + // it is possible to set user access on websites only for the websites admin + // basically an admin can give the view or the admin access to any user for the websites he manages + Piwik::checkUserHasAdminAccess($idSites); + + $this->deleteUserAccess($userLogin, $idSites); + + // delete UserAccess + $db = Zend_Registry::get('db'); + + // if the access is noaccess then we don't save it as this is the default value + // when no access are specified + if ($access != 'noaccess') { + foreach ($idSites as $idsite) { + $db->insert(Piwik_Common::prefixTable("access"), + array("idsite" => $idsite, + "login" => $userLogin, + "access" => $access) + ); + } + } + + // we reload the access list which doesn't yet take in consideration this new user access + Zend_Registry::get('access')->reloadAccess(); + Piwik_Tracker_Cache::deleteTrackerCache(); + } + + /** + * Throws an exception is the user login doesn't exist + * + * @param string $userLogin user login + * @throws Exception if the user doesn't exist + */ + private function checkUserExists($userLogin) + { + if (!$this->userExists($userLogin)) { + throw new Exception(Piwik_TranslateException("UsersManager_ExceptionUserDoesNotExist", $userLogin)); + } + } + + /** + * Throws an exception is the user email cannot be found + * + * @param string $userEmail user email + * @throws Exception if the user doesn't exist + */ + private function checkUserEmailExists($userEmail) + { + if (!$this->userEmailExists($userEmail)) { + throw new Exception(Piwik_TranslateException("UsersManager_ExceptionUserDoesNotExist", $userEmail)); + } + } + + private function checkUserIsNotAnonymous($userLogin) + { + if ($userLogin == 'anonymous') { + throw new Exception(Piwik_TranslateException("UsersManager_ExceptionEditAnonymous")); + } + } + + private function checkUserIsNotSuperUser($userLogin) + { + if ($userLogin == Piwik_Config::getInstance()->superuser['login']) { + throw new Exception(Piwik_TranslateException("UsersManager_ExceptionSuperUser")); + } + } + + private function checkAccessType($access) + { + $accessList = Piwik_Access::getListAccess(); + + // do not allow to set the superUser access + unset($accessList[array_search("superuser", $accessList)]); + + if (!in_array($access, $accessList)) { + throw new Exception(Piwik_TranslateException("UsersManager_ExceptionAccessValues", implode(", ", $accessList))); + } + } + + /** + * Delete a user given its login. + * The user's access are not deleted. + * + * @param string the user login. + * + */ + private function deleteUserOnly($userLogin) + { + $db = Zend_Registry::get('db'); + $db->query("DELETE FROM " . Piwik_Common::prefixTable("user") . " WHERE login = ?", $userLogin); + + Piwik_PostEvent('UsersManager.deleteUser', $userLogin); + } + + + /** + * Delete the user access for the given websites. + * The array of idsite must be either null OR the values must have been checked before for their validity! + * + * @param string the user login + * @param array array of idsites on which to delete the access. If null then delete all the access for this user. + * + * @return bool true on success + */ + private function deleteUserAccess($userLogin, $idSites = null) + { + $db = Zend_Registry::get('db'); + + if (is_null($idSites)) { + $db->query("DELETE FROM " . Piwik_Common::prefixTable("access") . + " WHERE login = ?", + array($userLogin)); + } else { + foreach ($idSites as $idsite) { + $db->query("DELETE FROM " . Piwik_Common::prefixTable("access") . + " WHERE idsite = ? AND login = ?", + array($idsite, $userLogin) + ); + } + } + } + + /** + * Generates a unique MD5 for the given login & password + * + * @param string $userLogin Login + * @param string $md5Password MD5ied string of the password + * @throws Exception + * @return string + */ + public function getTokenAuth($userLogin, $md5Password) + { + if (strlen($md5Password) != 32) { + throw new Exception(Piwik_TranslateException('UsersManager_ExceptionPasswordMD5HashExpected')); + } + return md5($userLogin . $md5Password); + } } diff --git a/plugins/UsersManager/Controller.php b/plugins/UsersManager/Controller.php index c44a5df6e8..77d7f5f8ce 100644 --- a/plugins/UsersManager/Controller.php +++ b/plugins/UsersManager/Controller.php @@ -1,370 +1,335 @@ getSitesIdWithAdminAccess(); - $idSiteSelected = 1; - - if(count($IdSitesAdmin) > 0) - { - $defaultWebsiteId = $IdSitesAdmin[0]; - $idSiteSelected = Piwik_Common::getRequestVar('idSite', $defaultWebsiteId); - } - - if($idSiteSelected==='all') - { - $usersAccessByWebsite = array(); - $defaultReportSiteName = Piwik_Translate('UsersManager_ApplyToAllWebsites'); - } - else - { - $usersAccessByWebsite = Piwik_UsersManager_API::getInstance()->getUsersAccessFromSite( $idSiteSelected ); - $defaultReportSiteName = Piwik_Site::getNameFor($idSiteSelected); - } - - // we dont want to display the user currently logged so that the user can't change his settings from admin to view... - $currentlyLogged = Piwik::getCurrentUserLogin(); - $usersLogin = Piwik_UsersManager_API::getInstance()->getUsersLogin(); - foreach($usersLogin as $login) - { - if(!isset($usersAccessByWebsite[$login])) - { - $usersAccessByWebsite[$login] = 'noaccess'; - } - } - unset($usersAccessByWebsite[$currentlyLogged]); - - - // $usersAccessByWebsite is not supposed to contain unexistant logins, but it does when upgrading from some old Piwik version - foreach($usersAccessByWebsite as $login => $access) - { - if(!in_array($login, $usersLogin)) - { - unset($usersAccessByWebsite[$login]); - continue; - } - } - - ksort($usersAccessByWebsite); - - $users = array(); - $usersAliasByLogin = array(); - if(Piwik::isUserHasSomeAdminAccess()) - { - $users = Piwik_UsersManager_API::getInstance()->getUsers(); - foreach($users as $user) - { - $usersAliasByLogin[$user['login']] = $user['alias']; - } - } - $view->anonymousHasViewAccess = $this->hasAnonymousUserViewAccess($usersAccessByWebsite); - $view->idSiteSelected = $idSiteSelected; - $view->defaultReportSiteName = $defaultReportSiteName; - $view->users = $users; - $view->usersAliasByLogin = $usersAliasByLogin; - $view->usersCount = count($users) - 1; - $view->usersAccessByWebsite = $usersAccessByWebsite; - $websites = Piwik_SitesManager_API::getInstance()->getSitesWithAdminAccess(); - uasort($websites, array('Piwik_UsersManager_Controller', 'orderByName')); - $view->websites = $websites; - $this->setBasicVariablesView($view); - $view->menu = Piwik_GetAdminMenu(); - echo $view->render(); - } - - private function hasAnonymousUserViewAccess($usersAccessByWebsite) - { - $anonymousHasViewAccess = false; - foreach ($usersAccessByWebsite as $login => $access) { - if ($login == 'anonymous' - && $access != 'noaccess' - ) { - $anonymousHasViewAccess = true; - } - } - return $anonymousHasViewAccess; - } - - /** - * Returns default date for Piwik reports - * - * @param string $user - * @return string today, yesterday, week, month, year - */ - protected function getDefaultDateForUser($user) - { - $userSettingsDate = Piwik_UsersManager_API::getInstance()->getUserPreference($user, Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT_DATE); - if($userSettingsDate === false) - { - return Piwik_Config::getInstance()->General['default_day']; - } - return $userSettingsDate; - } - - /** - * The "User Settings" admin UI screen view - */ - public function userSettings() - { - Piwik::checkUserIsNotAnonymous(); - - $view = Piwik_View::factory('userSettings'); - - $userLogin = Piwik::getCurrentUserLogin(); - if(Piwik::isUserIsSuperUser()) - { - $view->userAlias = $userLogin; - $view->userEmail = Piwik::getSuperUserEmail(); - if(!Piwik_Config::getInstance()->isFileWritable()) - { - $view->configFileNotWritable = true; - } - } - else - { - $user = Piwik_UsersManager_API::getInstance()->getUser($userLogin); - $view->userAlias = $user['alias']; - $view->userEmail = $user['email']; - } - - $defaultReport = Piwik_UsersManager_API::getInstance()->getUserPreference($userLogin, Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT); - if($defaultReport === false) - { - $defaultReport = $this->getDefaultWebsiteId(); - } - $view->defaultReport = $defaultReport; - - if ($defaultReport == 'MultiSites') - { - $view->defaultReportSiteName = Piwik_Site::getNameFor($this->getDefaultWebsiteId()); - } - else - { - $view->defaultReportSiteName = Piwik_Site::getNameFor($defaultReport); - } - - $view->defaultDate = $this->getDefaultDateForUser($userLogin); - $view->availableDefaultDates = array( - 'today' => Piwik_Translate('General_Today'), - 'yesterday' => Piwik_Translate('General_Yesterday'), - 'previous7' => Piwik_Translate('General_PreviousDays', 7), - 'previous30' => Piwik_Translate('General_PreviousDays', 30), - 'last7' => Piwik_Translate('General_LastDays', 7), - 'last30' => Piwik_Translate('General_LastDays', 30), - 'week' => Piwik_Translate('General_CurrentWeek'), - 'month' => Piwik_Translate('General_CurrentMonth'), - 'year' => Piwik_Translate('General_CurrentYear'), - ); - - $view->ignoreCookieSet = Piwik_Tracker_IgnoreCookie::isIgnoreCookieFound(); - $this->initViewAnonymousUserSettings($view); - $view->piwikHost = Piwik_Url::getCurrentHost(); - $this->setBasicVariablesView($view); - $view->menu = Piwik_GetAdminMenu(); - echo $view->render(); - } - - public function setIgnoreCookie() - { - Piwik::checkUserHasSomeViewAccess(); - Piwik::checkUserIsNotAnonymous(); - $this->checkTokenInUrl(); - - Piwik_Tracker_IgnoreCookie::setIgnoreCookie(); - Piwik::redirectToModule('UsersManager', 'userSettings', array('token_auth'=> false)); - } - - /** - * The Super User can modify Anonymous user settings - * @param Piwik_View $view - */ - protected function initViewAnonymousUserSettings($view) - { - if(!Piwik::isUserIsSuperUser()) - { - return; - } - $userLogin = 'anonymous'; - - // Which websites are available to the anonymous users? - $anonymousSitesAccess = Piwik_UsersManager_API::getInstance()->getSitesAccessFromUser($userLogin); - $anonymousSites = array(); - foreach($anonymousSitesAccess as $info) - { - $idSite = $info['site']; - $site = Piwik_SitesManager_API::getInstance()->getSiteFromId($idSite); - // Work around manual website deletion - if(!empty($site)) - { - $anonymousSites[$idSite] = $site; - } - } - $view->anonymousSites = $anonymousSites; - - // Which report is displayed by default to the anonymous user? - $anonymousDefaultReport = Piwik_UsersManager_API::getInstance()->getUserPreference($userLogin, Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT); - if($anonymousDefaultReport === false) - { - if(empty($anonymousSites)) - { - $anonymousDefaultReport = Piwik::getLoginPluginName(); - } - else - { - // we manually imitate what would happen, in case the anonymous user logs in - // and is redirected to the first website available to him in the list - // @see getDefaultWebsiteId() - reset($anonymousSites); - $anonymousDefaultReport = key($anonymousSites); - } - } - $view->anonymousDefaultReport = $anonymousDefaultReport; - - $view->anonymousDefaultDate = $this->getDefaultDateForUser($userLogin); - } - - /** - * Records settings for the anonymous users (default report, default date) - */ - public function recordAnonymousUserSettings() - { - $response = new Piwik_API_ResponseBuilder(Piwik_Common::getRequestVar('format')); - try { - Piwik::checkUserIsSuperUser(); - $this->checkTokenInUrl(); - - $anonymousDefaultReport = Piwik_Common::getRequestVar('anonymousDefaultReport'); - $anonymousDefaultDate = Piwik_Common::getRequestVar('anonymousDefaultDate'); - $userLogin = 'anonymous'; - Piwik_UsersManager_API::getInstance()->setUserPreference($userLogin, - Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT, - $anonymousDefaultReport); - Piwik_UsersManager_API::getInstance()->setUserPreference($userLogin, - Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT_DATE, - $anonymousDefaultDate); - $toReturn = $response->getResponse(); - } catch(Exception $e ) { - $toReturn = $response->getResponseException( $e ); - } - echo $toReturn; - } - - /** - * Records settings from the "User Settings" page - * @throws Exception - */ - public function recordUserSettings() - { - $response = new Piwik_API_ResponseBuilder(Piwik_Common::getRequestVar('format')); - try { - $this->checkTokenInUrl(); - - $alias = Piwik_Common::getRequestVar('alias'); - $email = Piwik_Common::getRequestVar('email'); - $defaultReport = Piwik_Common::getRequestVar('defaultReport'); - $defaultDate = Piwik_Common::getRequestVar('defaultDate'); - - $newPassword = false; - $password = Piwik_Common::getRequestvar('password', false); - $passwordBis = Piwik_Common::getRequestvar('passwordBis', false); - if(!empty($password) - || !empty($passwordBis)) - { - if($password != $passwordBis) - { - throw new Exception(Piwik_Translate('Login_PasswordsDoNotMatch')); - } - $newPassword = $password; - } - - // UI disables password change on invalid host, but check here anyway - if (!Piwik_Url::isValidHost() - && $newPassword !== false) - { - throw new Exception("Cannot change password with untrusted hostname!"); - } - - $userLogin = Piwik::getCurrentUserLogin(); - if(Piwik::isUserIsSuperUser()) - { - $superUser = Piwik_Config::getInstance()->superuser; - $updatedSuperUser = false; - - if($newPassword !== false) - { - $newPassword = Piwik_Common::unsanitizeInputValue($newPassword); - $md5PasswordSuperUser = md5($newPassword); - $superUser['password'] = $md5PasswordSuperUser; - $updatedSuperUser = true; - } - if($superUser['email'] != $email) - { - $superUser['email'] = $email; - $updatedSuperUser = true; - } - if($updatedSuperUser) - { - Piwik_Config::getInstance()->superuser = $superUser; - Piwik_Config::getInstance()->forceSave(); - } - } - else - { - Piwik_UsersManager_API::getInstance()->updateUser($userLogin, $newPassword, $email, $alias); - if($newPassword !== false) - { - $newPassword = Piwik_Common::unsanitizeInputValue($newPassword); - } - } - - // logs the user in with the new password - if($newPassword !== false) - { - $info = array( - 'login' => $userLogin, - 'md5Password' => md5($newPassword), - 'rememberMe' => false, - ); - Piwik_PostEvent('Login.initSession', $info); - } - - Piwik_UsersManager_API::getInstance()->setUserPreference($userLogin, - Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT, - $defaultReport); - Piwik_UsersManager_API::getInstance()->setUserPreference($userLogin, - Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT_DATE, - $defaultDate); - $toReturn = $response->getResponse(); - } catch(Exception $e ) { - $toReturn = $response->getResponseException( $e ); - } - echo $toReturn; - } + static function orderByName($a, $b) + { + return strcmp($a['name'], $b['name']); + } + + /** + * The "Manage Users and Permissions" Admin UI screen + */ + function index() + { + Piwik::checkUserIsNotAnonymous(); + + $view = Piwik_View::factory('UsersManager'); + + $IdSitesAdmin = Piwik_SitesManager_API::getInstance()->getSitesIdWithAdminAccess(); + $idSiteSelected = 1; + + if (count($IdSitesAdmin) > 0) { + $defaultWebsiteId = $IdSitesAdmin[0]; + $idSiteSelected = Piwik_Common::getRequestVar('idSite', $defaultWebsiteId); + } + + if ($idSiteSelected === 'all') { + $usersAccessByWebsite = array(); + $defaultReportSiteName = Piwik_Translate('UsersManager_ApplyToAllWebsites'); + } else { + $usersAccessByWebsite = Piwik_UsersManager_API::getInstance()->getUsersAccessFromSite($idSiteSelected); + $defaultReportSiteName = Piwik_Site::getNameFor($idSiteSelected); + } + + // we dont want to display the user currently logged so that the user can't change his settings from admin to view... + $currentlyLogged = Piwik::getCurrentUserLogin(); + $usersLogin = Piwik_UsersManager_API::getInstance()->getUsersLogin(); + foreach ($usersLogin as $login) { + if (!isset($usersAccessByWebsite[$login])) { + $usersAccessByWebsite[$login] = 'noaccess'; + } + } + unset($usersAccessByWebsite[$currentlyLogged]); + + + // $usersAccessByWebsite is not supposed to contain unexistant logins, but it does when upgrading from some old Piwik version + foreach ($usersAccessByWebsite as $login => $access) { + if (!in_array($login, $usersLogin)) { + unset($usersAccessByWebsite[$login]); + continue; + } + } + + ksort($usersAccessByWebsite); + + $users = array(); + $usersAliasByLogin = array(); + if (Piwik::isUserHasSomeAdminAccess()) { + $users = Piwik_UsersManager_API::getInstance()->getUsers(); + foreach ($users as $user) { + $usersAliasByLogin[$user['login']] = $user['alias']; + } + } + $view->anonymousHasViewAccess = $this->hasAnonymousUserViewAccess($usersAccessByWebsite); + $view->idSiteSelected = $idSiteSelected; + $view->defaultReportSiteName = $defaultReportSiteName; + $view->users = $users; + $view->usersAliasByLogin = $usersAliasByLogin; + $view->usersCount = count($users) - 1; + $view->usersAccessByWebsite = $usersAccessByWebsite; + $websites = Piwik_SitesManager_API::getInstance()->getSitesWithAdminAccess(); + uasort($websites, array('Piwik_UsersManager_Controller', 'orderByName')); + $view->websites = $websites; + $this->setBasicVariablesView($view); + $view->menu = Piwik_GetAdminMenu(); + echo $view->render(); + } + + private function hasAnonymousUserViewAccess($usersAccessByWebsite) + { + $anonymousHasViewAccess = false; + foreach ($usersAccessByWebsite as $login => $access) { + if ($login == 'anonymous' + && $access != 'noaccess' + ) { + $anonymousHasViewAccess = true; + } + } + return $anonymousHasViewAccess; + } + + /** + * Returns default date for Piwik reports + * + * @param string $user + * @return string today, yesterday, week, month, year + */ + protected function getDefaultDateForUser($user) + { + $userSettingsDate = Piwik_UsersManager_API::getInstance()->getUserPreference($user, Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT_DATE); + if ($userSettingsDate === false) { + return Piwik_Config::getInstance()->General['default_day']; + } + return $userSettingsDate; + } + + /** + * The "User Settings" admin UI screen view + */ + public function userSettings() + { + Piwik::checkUserIsNotAnonymous(); + + $view = Piwik_View::factory('userSettings'); + + $userLogin = Piwik::getCurrentUserLogin(); + if (Piwik::isUserIsSuperUser()) { + $view->userAlias = $userLogin; + $view->userEmail = Piwik::getSuperUserEmail(); + if (!Piwik_Config::getInstance()->isFileWritable()) { + $view->configFileNotWritable = true; + } + } else { + $user = Piwik_UsersManager_API::getInstance()->getUser($userLogin); + $view->userAlias = $user['alias']; + $view->userEmail = $user['email']; + } + + $defaultReport = Piwik_UsersManager_API::getInstance()->getUserPreference($userLogin, Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT); + if ($defaultReport === false) { + $defaultReport = $this->getDefaultWebsiteId(); + } + $view->defaultReport = $defaultReport; + + if ($defaultReport == 'MultiSites') { + $view->defaultReportSiteName = Piwik_Site::getNameFor($this->getDefaultWebsiteId()); + } else { + $view->defaultReportSiteName = Piwik_Site::getNameFor($defaultReport); + } + + $view->defaultDate = $this->getDefaultDateForUser($userLogin); + $view->availableDefaultDates = array( + 'today' => Piwik_Translate('General_Today'), + 'yesterday' => Piwik_Translate('General_Yesterday'), + 'previous7' => Piwik_Translate('General_PreviousDays', 7), + 'previous30' => Piwik_Translate('General_PreviousDays', 30), + 'last7' => Piwik_Translate('General_LastDays', 7), + 'last30' => Piwik_Translate('General_LastDays', 30), + 'week' => Piwik_Translate('General_CurrentWeek'), + 'month' => Piwik_Translate('General_CurrentMonth'), + 'year' => Piwik_Translate('General_CurrentYear'), + ); + + $view->ignoreCookieSet = Piwik_Tracker_IgnoreCookie::isIgnoreCookieFound(); + $this->initViewAnonymousUserSettings($view); + $view->piwikHost = Piwik_Url::getCurrentHost(); + $this->setBasicVariablesView($view); + $view->menu = Piwik_GetAdminMenu(); + echo $view->render(); + } + + public function setIgnoreCookie() + { + Piwik::checkUserHasSomeViewAccess(); + Piwik::checkUserIsNotAnonymous(); + $this->checkTokenInUrl(); + + Piwik_Tracker_IgnoreCookie::setIgnoreCookie(); + Piwik::redirectToModule('UsersManager', 'userSettings', array('token_auth' => false)); + } + + /** + * The Super User can modify Anonymous user settings + * @param Piwik_View $view + */ + protected function initViewAnonymousUserSettings($view) + { + if (!Piwik::isUserIsSuperUser()) { + return; + } + $userLogin = 'anonymous'; + + // Which websites are available to the anonymous users? + $anonymousSitesAccess = Piwik_UsersManager_API::getInstance()->getSitesAccessFromUser($userLogin); + $anonymousSites = array(); + foreach ($anonymousSitesAccess as $info) { + $idSite = $info['site']; + $site = Piwik_SitesManager_API::getInstance()->getSiteFromId($idSite); + // Work around manual website deletion + if (!empty($site)) { + $anonymousSites[$idSite] = $site; + } + } + $view->anonymousSites = $anonymousSites; + + // Which report is displayed by default to the anonymous user? + $anonymousDefaultReport = Piwik_UsersManager_API::getInstance()->getUserPreference($userLogin, Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT); + if ($anonymousDefaultReport === false) { + if (empty($anonymousSites)) { + $anonymousDefaultReport = Piwik::getLoginPluginName(); + } else { + // we manually imitate what would happen, in case the anonymous user logs in + // and is redirected to the first website available to him in the list + // @see getDefaultWebsiteId() + reset($anonymousSites); + $anonymousDefaultReport = key($anonymousSites); + } + } + $view->anonymousDefaultReport = $anonymousDefaultReport; + + $view->anonymousDefaultDate = $this->getDefaultDateForUser($userLogin); + } + + /** + * Records settings for the anonymous users (default report, default date) + */ + public function recordAnonymousUserSettings() + { + $response = new Piwik_API_ResponseBuilder(Piwik_Common::getRequestVar('format')); + try { + Piwik::checkUserIsSuperUser(); + $this->checkTokenInUrl(); + + $anonymousDefaultReport = Piwik_Common::getRequestVar('anonymousDefaultReport'); + $anonymousDefaultDate = Piwik_Common::getRequestVar('anonymousDefaultDate'); + $userLogin = 'anonymous'; + Piwik_UsersManager_API::getInstance()->setUserPreference($userLogin, + Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT, + $anonymousDefaultReport); + Piwik_UsersManager_API::getInstance()->setUserPreference($userLogin, + Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT_DATE, + $anonymousDefaultDate); + $toReturn = $response->getResponse(); + } catch (Exception $e) { + $toReturn = $response->getResponseException($e); + } + echo $toReturn; + } + + /** + * Records settings from the "User Settings" page + * @throws Exception + */ + public function recordUserSettings() + { + $response = new Piwik_API_ResponseBuilder(Piwik_Common::getRequestVar('format')); + try { + $this->checkTokenInUrl(); + + $alias = Piwik_Common::getRequestVar('alias'); + $email = Piwik_Common::getRequestVar('email'); + $defaultReport = Piwik_Common::getRequestVar('defaultReport'); + $defaultDate = Piwik_Common::getRequestVar('defaultDate'); + + $newPassword = false; + $password = Piwik_Common::getRequestvar('password', false); + $passwordBis = Piwik_Common::getRequestvar('passwordBis', false); + if (!empty($password) + || !empty($passwordBis) + ) { + if ($password != $passwordBis) { + throw new Exception(Piwik_Translate('Login_PasswordsDoNotMatch')); + } + $newPassword = $password; + } + + // UI disables password change on invalid host, but check here anyway + if (!Piwik_Url::isValidHost() + && $newPassword !== false + ) { + throw new Exception("Cannot change password with untrusted hostname!"); + } + + $userLogin = Piwik::getCurrentUserLogin(); + if (Piwik::isUserIsSuperUser()) { + $superUser = Piwik_Config::getInstance()->superuser; + $updatedSuperUser = false; + + if ($newPassword !== false) { + $newPassword = Piwik_Common::unsanitizeInputValue($newPassword); + $md5PasswordSuperUser = md5($newPassword); + $superUser['password'] = $md5PasswordSuperUser; + $updatedSuperUser = true; + } + if ($superUser['email'] != $email) { + $superUser['email'] = $email; + $updatedSuperUser = true; + } + if ($updatedSuperUser) { + Piwik_Config::getInstance()->superuser = $superUser; + Piwik_Config::getInstance()->forceSave(); + } + } else { + Piwik_UsersManager_API::getInstance()->updateUser($userLogin, $newPassword, $email, $alias); + if ($newPassword !== false) { + $newPassword = Piwik_Common::unsanitizeInputValue($newPassword); + } + } + + // logs the user in with the new password + if ($newPassword !== false) { + $info = array( + 'login' => $userLogin, + 'md5Password' => md5($newPassword), + 'rememberMe' => false, + ); + Piwik_PostEvent('Login.initSession', $info); + } + + Piwik_UsersManager_API::getInstance()->setUserPreference($userLogin, + Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT, + $defaultReport); + Piwik_UsersManager_API::getInstance()->setUserPreference($userLogin, + Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT_DATE, + $defaultDate); + $toReturn = $response->getResponse(); + } catch (Exception $e) { + $toReturn = $response->getResponseException($e); + } + echo $toReturn; + } } diff --git a/plugins/UsersManager/UsersManager.php b/plugins/UsersManager/UsersManager.php index 57e4d42a7e..41334931c2 100644 --- a/plugins/UsersManager/UsersManager.php +++ b/plugins/UsersManager/UsersManager.php @@ -16,142 +16,139 @@ */ class Piwik_UsersManager extends Piwik_Plugin { - const PASSWORD_MIN_LENGTH = 6; - const PASSWORD_MAX_LENGTH = 26; + const PASSWORD_MIN_LENGTH = 6; + const PASSWORD_MAX_LENGTH = 26; - /** - * Plugin information - * - * @see Piwik_Plugin - * - * @return array - */ - public function getInformation() - { - $info = array( - 'description' => Piwik_Translate('UsersManager_PluginDescription'), - 'author' => 'Piwik', - 'author_homepage' => 'http://piwik.org/', - 'version' => Piwik_Version::VERSION, - ); + /** + * Plugin information + * + * @see Piwik_Plugin + * + * @return array + */ + public function getInformation() + { + $info = array( + 'description' => Piwik_Translate('UsersManager_PluginDescription'), + 'author' => 'Piwik', + 'author_homepage' => 'http://piwik.org/', + 'version' => Piwik_Version::VERSION, + ); - return $info; - } + return $info; + } - /** - * Get list of hooks to register. - * - * @see Piwik_PluginsManager.loadPlugin() - * - * @return array - */ - function getListHooksRegistered() - { - return array( - 'AdminMenu.add' => 'addMenu', - 'AssetManager.getJsFiles' => 'getJsFiles', - 'SitesManager.deleteSite' => 'deleteSite', - 'Common.fetchWebsiteAttributes' => 'recordAdminUsersInCache', - ); - } + /** + * Get list of hooks to register. + * + * @see Piwik_PluginsManager.loadPlugin() + * + * @return array + */ + function getListHooksRegistered() + { + return array( + 'AdminMenu.add' => 'addMenu', + 'AssetManager.getJsFiles' => 'getJsFiles', + 'SitesManager.deleteSite' => 'deleteSite', + 'Common.fetchWebsiteAttributes' => 'recordAdminUsersInCache', + ); + } - /** - * Hooks when a website tracker cache is flushed (website/user updated, cache deleted, or empty cache) - * Will record in the tracker config file the list of Admin token_auth for this website. This - * will be used when the Tracking API is used with setIp(), setForceDateTime(), setVisitorId(), etc. - * - * @param Piwik_Event_Notification $notification notification object - * @return void - */ - function recordAdminUsersInCache($notification) - { - $idSite = $notification->getNotificationInfo(); - // add the 'hosts' entry in the website array - $users = Piwik_UsersManager_API::getInstance()->getUsersWithSiteAccess($idSite, 'admin'); + /** + * Hooks when a website tracker cache is flushed (website/user updated, cache deleted, or empty cache) + * Will record in the tracker config file the list of Admin token_auth for this website. This + * will be used when the Tracking API is used with setIp(), setForceDateTime(), setVisitorId(), etc. + * + * @param Piwik_Event_Notification $notification notification object + * @return void + */ + function recordAdminUsersInCache($notification) + { + $idSite = $notification->getNotificationInfo(); + // add the 'hosts' entry in the website array + $users = Piwik_UsersManager_API::getInstance()->getUsersWithSiteAccess($idSite, 'admin'); - $tokens = array(); - foreach($users as $user) - { - $tokens[] = $user['token_auth']; - } - $array =& $notification->getNotificationObject(); - $array['admin_token_auth'] = $tokens; - } + $tokens = array(); + foreach ($users as $user) { + $tokens[] = $user['token_auth']; + } + $array =& $notification->getNotificationObject(); + $array['admin_token_auth'] = $tokens; + } - /** - * Delete user preferences associated with a particular site - * - * @param Piwik_Event_Notification $notification notification object - */ - function deleteSite($notification) - { - $idSite = &$notification->getNotificationObject(); + /** + * Delete user preferences associated with a particular site + * + * @param Piwik_Event_Notification $notification notification object + */ + function deleteSite($notification) + { + $idSite = & $notification->getNotificationObject(); - Piwik_Option::getInstance()->deleteLike('%\_' . Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT, $idSite); - } + Piwik_Option::getInstance()->deleteLike('%\_' . Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT, $idSite); + } - /** - * Return list of plug-in specific JavaScript files to be imported by the asset manager - * - * @see Piwik_AssetManager - * - * @param Piwik_Event_Notification $notification notification object - */ - function getJsFiles($notification) - { - $jsFiles = &$notification->getNotificationObject(); + /** + * Return list of plug-in specific JavaScript files to be imported by the asset manager + * + * @see Piwik_AssetManager + * + * @param Piwik_Event_Notification $notification notification object + */ + function getJsFiles($notification) + { + $jsFiles = & $notification->getNotificationObject(); - $jsFiles[] = "plugins/UsersManager/templates/UsersManager.js"; - $jsFiles[] = "plugins/UsersManager/templates/userSettings.js"; - } + $jsFiles[] = "plugins/UsersManager/templates/UsersManager.js"; + $jsFiles[] = "plugins/UsersManager/templates/userSettings.js"; + } - /** - * Add admin menu items - */ - function addMenu() - { - Piwik_AddAdminSubMenu('CoreAdminHome_MenuManage', 'UsersManager_MenuUsers', - array('module' => 'UsersManager', 'action' => 'index'), - Piwik::isUserHasSomeAdminAccess(), - $order = 2); - Piwik_AddAdminSubMenu('CoreAdminHome_MenuManage', 'UsersManager_MenuUserSettings', - array('module' => 'UsersManager', 'action' => 'userSettings'), - Piwik::isUserHasSomeViewAccess(), - $order = 3); - } + /** + * Add admin menu items + */ + function addMenu() + { + Piwik_AddAdminSubMenu('CoreAdminHome_MenuManage', 'UsersManager_MenuUsers', + array('module' => 'UsersManager', 'action' => 'index'), + Piwik::isUserHasSomeAdminAccess(), + $order = 2); + Piwik_AddAdminSubMenu('CoreAdminHome_MenuManage', 'UsersManager_MenuUserSettings', + array('module' => 'UsersManager', 'action' => 'userSettings'), + Piwik::isUserHasSomeViewAccess(), + $order = 3); + } - /** - * Returns true if the password is complex enough (at least 6 characters and max 26 characters) - * - * @param string email - * @return bool - */ - public static function isValidPasswordString($input) - { - if(!Piwik::isChecksEnabled() - && !empty($input) - ) - { - return true; - } - $l = strlen($input); - return $l >= self::PASSWORD_MIN_LENGTH && $l <= self::PASSWORD_MAX_LENGTH; - } + /** + * Returns true if the password is complex enough (at least 6 characters and max 26 characters) + * + * @param string email + * @return bool + */ + public static function isValidPasswordString($input) + { + if (!Piwik::isChecksEnabled() + && !empty($input) + ) { + return true; + } + $l = strlen($input); + return $l >= self::PASSWORD_MIN_LENGTH && $l <= self::PASSWORD_MAX_LENGTH; + } - public static function checkPassword($password) - { - if(!self::isValidPasswordString($password)) - { - throw new Exception(Piwik_TranslateException('UsersManager_ExceptionInvalidPassword', array(self::PASSWORD_MIN_LENGTH, - self::PASSWORD_MAX_LENGTH))); - } - } + public static function checkPassword($password) + { + if (!self::isValidPasswordString($password)) { + throw new Exception(Piwik_TranslateException('UsersManager_ExceptionInvalidPassword', array(self::PASSWORD_MIN_LENGTH, + self::PASSWORD_MAX_LENGTH))); + } + } - public static function getPasswordHash($password) - { - // if change here, should also edit the installation process - // to change how the root pwd is saved in the config file - return md5($password); - } + public static function getPasswordHash($password) + { + // if change here, should also edit the installation process + // to change how the root pwd is saved in the config file + return md5($password); + } } diff --git a/plugins/UsersManager/templates/UsersManager.js b/plugins/UsersManager/templates/UsersManager.js index 505e400f44..1da9a43943 100644 --- a/plugins/UsersManager/templates/UsersManager.js +++ b/plugins/UsersManager/templates/UsersManager.js @@ -5,14 +5,13 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */ -function sendUpdateUserAJAX( row ) -{ - var parameters = {}; - parameters.userLogin = $(row).children('#userLogin').html(); - var password = $(row).find('input#password').val(); - if(password != '-') parameters.password = password; - parameters.email = $(row).find('input#email').val(); - parameters.alias = $(row).find('input#alias').val(); +function sendUpdateUserAJAX(row) { + var parameters = {}; + parameters.userLogin = $(row).children('#userLogin').html(); + var password = $(row).find('input#password').val(); + if (password != '-') parameters.password = password; + parameters.email = $(row).find('input#email').val(); + parameters.alias = $(row).find('input#alias').val(); var ajaxHandler = new ajaxHelper(); ajaxHandler.addParams({ @@ -26,8 +25,7 @@ function sendUpdateUserAJAX( row ) ajaxHandler.send(true); } -function sendDeleteUserAJAX( login ) -{ +function sendDeleteUserAJAX(login) { var ajaxHandler = new ajaxHelper(); ajaxHandler.addParams({ module: 'API', @@ -41,13 +39,12 @@ function sendDeleteUserAJAX( login ) ajaxHandler.send(true); } -function sendAddUserAJAX( row ) -{ - var parameters = {}; - parameters.userLogin = $(row).find('input#useradd_login').val(); - parameters.password = $(row).find('input#useradd_password').val(); - parameters.email = $(row).find('input#useradd_email').val(); - parameters.alias = $(row).find('input#useradd_alias').val(); +function sendAddUserAJAX(row) { + var parameters = {}; + parameters.userLogin = $(row).find('input#useradd_login').val(); + parameters.password = $(row).find('input#useradd_password').val(); + parameters.email = $(row).find('input#useradd_email').val(); + parameters.alias = $(row).find('input#useradd_alias').val(); var ajaxHandler = new ajaxHelper(); ajaxHandler.addParams({ @@ -62,17 +59,15 @@ function sendAddUserAJAX( row ) ajaxHandler.send(true); } -function getIdSites() -{ - return $('.custom_select_main_link').attr('siteid'); +function getIdSites() { + return $('.custom_select_main_link').attr('siteid'); } -function sendUpdateUserAccess(login, access, successCallback) -{ - var parameters = {}; - parameters.userLogin = login; - parameters.access = access; - parameters.idSites = getIdSites(); +function sendUpdateUserAccess(login, access, successCallback) { + var parameters = {}; + parameters.userLogin = login; + parameters.access = access; + parameters.idSites = getIdSites(); var ajaxHandler = new ajaxHelper(); ajaxHandler.addParams({ @@ -87,171 +82,165 @@ function sendUpdateUserAccess(login, access, successCallback) ajaxHandler.send(true); } -function submitOnEnter(e) -{ - var key=e.keyCode || e.which; - if (key==13) - { - $(this).find('.adduser').click(); - $(this).find('.updateuser').click(); - } +function submitOnEnter(e) { + var key = e.keyCode || e.which; + if (key == 13) { + $(this).find('.adduser').click(); + $(this).find('.updateuser').click(); + } } -function launchAjaxRequest(self, successCallback) -{ +function launchAjaxRequest(self, successCallback) { sendUpdateUserAccess( $(self).parent().parent().find('#login').html(), //if changed change also the modal $(self).parent().attr('id'), successCallback ); } -function hideAccessUpdated() -{ - setTimeout(function(){ - $('#accessUpdated').fadeOut(500); - }, 2000); +function hideAccessUpdated() { + setTimeout(function () { + $('#accessUpdated').fadeOut(500); + }, 2000); } -function bindUpdateAccess() -{ - var self = this; - hideAccessUpdated(1); - // callback called when the ajax request Update the user permissions is successful - function successCallback (response) - { +function bindUpdateAccess() { + var self = this; + hideAccessUpdated(1); + // callback called when the ajax request Update the user permissions is successful + function successCallback(response) { var mainDiv = $(self).parent().parent(); var login = $('#login', mainDiv).text(); mainDiv.find('.accessGranted') - .attr("src","plugins/UsersManager/images/no-access.png" ) - .attr("class","updateAccess" ) + .attr("src", "plugins/UsersManager/images/no-access.png") + .attr("class", "updateAccess") .click(bindUpdateAccess) - ; + ; $(self) - .attr('src',"plugins/UsersManager/images/ok.png" ) - .attr('class',"accessGranted" ) - ; + .attr('src', "plugins/UsersManager/images/ok.png") + .attr('class', "accessGranted") + ; $('#accessUpdated').css('display', 'inline-block'); hideAccessUpdated(); // reload if user anonymous was updated, since we display a Notice message when anon has view access - if(login == 'anonymous') { + if (login == 'anonymous') { window.location.reload(); } - } - - var idSite = getIdSites(); - if(idSite == 'all') - { - var target = this; - - //ask confirmation - var userLogin = $(this).parent().parent().find('#login').text(); - $('#confirm').find('#login').text( userLogin ); // if changed here change also the launchAjaxRequest + } - function onValidate() - { - launchAjaxRequest(target, successCallback); - } - piwikHelper.modalConfirm( '#confirm', {yes: onValidate}) - } - else - { - launchAjaxRequest(this, successCallback); - } + var idSite = getIdSites(); + if (idSite == 'all') { + var target = this; + + //ask confirmation + var userLogin = $(this).parent().parent().find('#login').text(); + $('#confirm').find('#login').text(userLogin); // if changed here change also the launchAjaxRequest + + function onValidate() { + launchAjaxRequest(target, successCallback); + } + + piwikHelper.modalConfirm('#confirm', {yes: onValidate}) + } + else { + launchAjaxRequest(this, successCallback); + } } -$(document).ready( function() { - var alreadyEdited = new Array; - // when click on edituser, the cells become editable - $('.edituser') - .click( function() { - piwikHelper.hideAjaxError(); - var idRow = $(this).attr('id'); - if(alreadyEdited[idRow]==1) return; - alreadyEdited[idRow] = 1; - $('tr#'+idRow+' .editable').each( - // make the fields editable - // change the EDIT button to VALID button - function (i,n) { - var contentBefore = $(n).text(); - var idName = $(n).attr('id'); - if(idName != 'userLogin') - { - var contentAfter = ''; - $(n).html(contentAfter); - } - } - ); - - $(this) - .toggle() - .parent() - .prepend( $('') - .click( function(){ - var onValidate = function() { - sendUpdateUserAJAX($('tr#'+idRow)); - }; - if($('tr#'+idRow).find('input#password').val() != '-') { - piwikHelper.modalConfirm( '#confirmPasswordChange', {yes: onValidate}); - } else { - onValidate(); - } - } ) - ); - }); - - $('.editable').keypress( submitOnEnter ); - - $('td.editable') - .click( function(){ $(this).parent().find('.edituser').click(); } ); - - // when click on deleteuser, the we ask for confirmation and then delete the user - $('.deleteuser') - .click( function() { - piwikHelper.hideAjaxError(); - var idRow = $(this).attr('id'); - var loginToDelete = $(this).parent().parent().find('#userLogin').html(); - $('#confirmUserRemove h2').text(sprintf(_pk_translate('UsersManager_DeleteConfirm_js'),'"'+loginToDelete+'"')); - piwikHelper.modalConfirm( '#confirmUserRemove', {yes: function(){ sendDeleteUserAJAX( loginToDelete ); }}); - } - ); - - $('.addrow').click( function() { - piwikHelper.hideAjaxError(); - $(this).toggle(); - - var numberOfRows = $('table#users')[0].rows.length; - var newRowId = numberOfRows + 1; - newRowId = 'row' + newRowId; - - $(' \ +$(document).ready(function () { + var alreadyEdited = new Array; + // when click on edituser, the cells become editable + $('.edituser') + .click(function () { + piwikHelper.hideAjaxError(); + var idRow = $(this).attr('id'); + if (alreadyEdited[idRow] == 1) return; + alreadyEdited[idRow] = 1; + $('tr#' + idRow + ' .editable').each( + // make the fields editable + // change the EDIT button to VALID button + function (i, n) { + var contentBefore = $(n).text(); + var idName = $(n).attr('id'); + if (idName != 'userLogin') { + var contentAfter = ''; + $(n).html(contentAfter); + } + } + ); + + $(this) + .toggle() + .parent() + .prepend($('') + .click(function () { + var onValidate = function () { + sendUpdateUserAJAX($('tr#' + idRow)); + }; + if ($('tr#' + idRow).find('input#password').val() != '-') { + piwikHelper.modalConfirm('#confirmPasswordChange', {yes: onValidate}); + } else { + onValidate(); + } + }) + ); + }); + + $('.editable').keypress(submitOnEnter); + + $('td.editable') + .click(function () { $(this).parent().find('.edituser').click(); }); + + // when click on deleteuser, the we ask for confirmation and then delete the user + $('.deleteuser') + .click(function () { + piwikHelper.hideAjaxError(); + var idRow = $(this).attr('id'); + var loginToDelete = $(this).parent().parent().find('#userLogin').html(); + $('#confirmUserRemove h2').text(sprintf(_pk_translate('UsersManager_DeleteConfirm_js'), '"' + loginToDelete + '"')); + piwikHelper.modalConfirm('#confirmUserRemove', {yes: function () { sendDeleteUserAJAX(loginToDelete); }}); + } + ); + + $('.addrow').click(function () { + piwikHelper.hideAjaxError(); + $(this).toggle(); + + var numberOfRows = $('table#users')[0].rows.length; + var newRowId = numberOfRows + 1; + newRowId = 'row' + newRowId; + + $(' \ \ \ \ \ -\ - \ - '+sprintf(_pk_translate('General_OrCancel_js'),"","")+'\ + \ + ' + sprintf(_pk_translate('General_OrCancel_js'), "", "") + '\ ') - .appendTo('#users') - ; - $('#'+newRowId).keypress( submitOnEnter ); - $('.adduser').click( function(){ sendAddUserAJAX($('tr#'+newRowId)); } ); - $('.cancel').click(function() { piwikHelper.hideAjaxError(); $(this).parents('tr').remove(); $('.addrow').toggle(); }); - }); + .appendTo('#users') + ; + $('#' + newRowId).keypress(submitOnEnter); + $('.adduser').click(function () { sendAddUserAJAX($('tr#' + newRowId)); }); + $('.cancel').click(function () { + piwikHelper.hideAjaxError(); + $(this).parents('tr').remove(); + $('.addrow').toggle(); + }); + }); + + $('.updateAccess') + .click(bindUpdateAccess); - $('.updateAccess') - .click( bindUpdateAccess ); - - // when a site is selected, reload the page w/o showing the ajax loading element - $('#usersManagerSiteSelect').bind('piwik:siteSelected', function(e, site) { - if (site.id != piwik.idSite) - { - switchSite( - site.id, - site.name, - false /* do not show main ajax loading animation */, - true /* do not go to all websites dash */ - ); - } - }); + // when a site is selected, reload the page w/o showing the ajax loading element + $('#usersManagerSiteSelect').bind('piwik:siteSelected', function (e, site) { + if (site.id != piwik.idSite) { + switchSite( + site.id, + site.name, + false /* do not show main ajax loading animation */, + true /* do not go to all websites dash */ + ); + } + }); }); diff --git a/plugins/UsersManager/templates/UsersManager.tpl b/plugins/UsersManager/templates/UsersManager.tpl index ae2c7bd814..c73e3bc182 100644 --- a/plugins/UsersManager/templates/UsersManager.tpl +++ b/plugins/UsersManager/templates/UsersManager.tpl @@ -2,149 +2,154 @@ {loadJavascriptTranslations plugins='UsersManager'} {literal} - + {/literal}

{'UsersManager_ManageAccess'|translate}

-
-

{'UsersManager_MainDescription'|translate}

-
{'UsersManager_Sites'|translate}:
- - {capture name=applyAllSitesText assign=applyAllSitesText} - {'UsersManager_ApplyToAllWebsites'|translate} - {/capture} - {include file="CoreHome/templates/sites_selection.tpl" - siteName=$defaultReportSiteName idSite=$idSiteSelected allSitesItemText=$applyAllSitesText - allWebsitesLinkLocation=top siteSelectorId="usersManagerSiteSelect" switchSiteOnSelect=false} -
+
+

{'UsersManager_MainDescription'|translate}

+ +
{'UsersManager_Sites'|translate}:
+ + {capture name=applyAllSitesText assign=applyAllSitesText} + {'UsersManager_ApplyToAllWebsites'|translate} + {/capture} + {include file="CoreHome/templates/sites_selection.tpl" + siteName=$defaultReportSiteName idSite=$idSiteSelected allSitesItemText=$applyAllSitesText + allWebsitesLinkLocation=top siteSelectorId="usersManagerSiteSelect" switchSiteOnSelect=false} +
{ajaxErrorDiv} {ajaxLoadingDiv}
- {if $anonymousHasViewAccess} -
- {'UsersManager_AnonymousUserHasViewAccess'|translate:"'anonymous'":"'view'"}
- {'UsersManager_AnonymousUserHasViewAccess2'|translate} -
- {/if} - - - - - - - - - - - - - {assign var=accesValid value=""} - {assign var=accesInvalid value=""} - {foreach from=$usersAccessByWebsite key=login item=access} - - - - - - - - {/foreach} - -
{'UsersManager_User'|translate}{'UsersManager_Alias'|translate}{'UsersManager_PrivNone'|translate}{'UsersManager_PrivView'|translate}{'UsersManager_PrivAdmin'|translate}
{$login}{$usersAliasByLogin[$login]}{if $access=='noaccess' and $idSiteSelected!='all'}{$accesValid}{else}{$accesInvalid}{/if} {if $access=='view' and $idSiteSelected!='all'}{$accesValid}{else}{$accesInvalid}{/if}  - {if $login=='anonymous'} - N/A - {else} - {if $access=='admin' and $idSiteSelected!='all'}{$accesValid}{else}{$accesInvalid}{/if}  - {/if} -
- + {if $anonymousHasViewAccess} +
+ {'UsersManager_AnonymousUserHasViewAccess'|translate:"'anonymous'":"'view'"}
+ {'UsersManager_AnonymousUserHasViewAccess2'|translate} +
+ {/if} + + + + + + + + + + + + + {assign var=accesValid value=""} + {assign var=accesInvalid value=""} + {foreach from=$usersAccessByWebsite key=login item=access} + + + + + + + + {/foreach} + +
{'UsersManager_User'|translate}{'UsersManager_Alias'|translate}{'UsersManager_PrivNone'|translate}{'UsersManager_PrivView'|translate}{'UsersManager_PrivAdmin'|translate}
{$login}{$usersAliasByLogin[$login]}{if $access=='noaccess' and $idSiteSelected!='all'}{$accesValid}{else}{$accesInvalid}{/if} {if $access=='view' and $idSiteSelected!='all'}{$accesValid}{else}{$accesInvalid}{/if}  + {if $login=='anonymous'} + N/A + {else} + {if $access=='admin' and $idSiteSelected!='all'}{$accesValid}{else}{$accesInvalid}{/if}  + {/if} +
+
-

{'UsersManager_ChangeAllConfirm'|translate:""}

- - -
+

{'UsersManager_ChangeAllConfirm'|translate:""}

+ + + {if $userIsSuperUser}

- - -
+ + +

{'UsersManager_ChangePasswordConfirm'|translate}

- - -
- -
-

{'UsersManager_UsersManagement'|translate}

-

{'UsersManager_UsersManagementMainDescription'|translate} - {'UsersManager_ThereAreCurrentlyNRegisteredUsers'|translate:"$usersCount"}

- - {ajaxErrorDiv id=ajaxErrorUsersManagement} - {ajaxLoadingDiv id=ajaxLoadingUsersManagement} + + + +
+

{'UsersManager_UsersManagement'|translate}

+

{'UsersManager_UsersManagementMainDescription'|translate} + {'UsersManager_ThereAreCurrentlyNRegisteredUsers'|translate:"$usersCount"}

+ {ajaxErrorDiv id=ajaxErrorUsersManagement} + {ajaxLoadingDiv id=ajaxLoadingUsersManagement} +
+ + + + + + + + + + + + -
-
{'General_Username'|translate}{'UsersManager_Password'|translate}{'UsersManager_Email'|translate}{'UsersManager_Alias'|translate}token_auth{'General_Edit'|translate}{'General_Delete'|translate}
- - - - - - - - - - - - - - {foreach from=$users item=user key=i} - {if $user.login != 'anonymous'} - - - - - - - - - - {/if} - {/foreach} - -
{'General_Username'|translate}{'UsersManager_Password'|translate}{'UsersManager_Email'|translate}{'UsersManager_Alias'|translate}token_auth{'General_Edit'|translate}{'General_Delete'|translate}
{$user.login}-{$user.email}{$user.alias}{$user.token_auth} {'General_Edit'|translate} {'General_Delete'|translate}
-
{'UsersManager_AddUser'|translate}
-
+ + {foreach from=$users item=user key=i} + {if $user.login != 'anonymous'} + + {$user.login} + - + {$user.email} + {$user.alias} + {$user.token_auth} + {'General_Edit'|translate} + {'General_Delete'|translate} + + + {/if} + {/foreach} + + +
{'UsersManager_AddUser'|translate}
+ {/if} {include file="CoreAdminHome/templates/footer.tpl"} diff --git a/plugins/UsersManager/templates/userSettings.js b/plugins/UsersManager/templates/userSettings.js index abb00cc68b..0bfdf3d8bb 100644 --- a/plugins/UsersManager/templates/userSettings.js +++ b/plugins/UsersManager/templates/userSettings.js @@ -5,38 +5,35 @@ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */ -function sendUserSettingsAJAX() -{ - var params; - var defaultDate = $('input[name=defaultDate]:checked').val(); - if (defaultDate == 'today' || defaultDate == 'yesterday') { - params = 'period=day&date='+defaultDate; - } else if(defaultDate.indexOf('last') >= 0 - || defaultDate.indexOf('previous') >= 0) { - params = 'period=range&date='+defaultDate; - } else { - params = 'date=today&period='+defaultDate; - } +function sendUserSettingsAJAX() { + var params; + var defaultDate = $('input[name=defaultDate]:checked').val(); + if (defaultDate == 'today' || defaultDate == 'yesterday') { + params = 'period=day&date=' + defaultDate; + } else if (defaultDate.indexOf('last') >= 0 + || defaultDate.indexOf('previous') >= 0) { + params = 'period=range&date=' + defaultDate; + } else { + params = 'date=today&period=' + defaultDate; + } - var alias = $('#alias').val(); - var email = $('#email').val(); - var password = $('#password').val(); - var passwordBis = $('#passwordBis').val(); - var defaultReport = $('input[name=defaultReport]:checked').val(); - if (defaultReport == 1) { - defaultReport = $('#defaultReportSiteSelector .custom_select_main_link').attr('siteid'); - } - var postParams = {}; + var alias = $('#alias').val(); + var email = $('#email').val(); + var password = $('#password').val(); + var passwordBis = $('#passwordBis').val(); + var defaultReport = $('input[name=defaultReport]:checked').val(); + if (defaultReport == 1) { + defaultReport = $('#defaultReportSiteSelector .custom_select_main_link').attr('siteid'); + } + var postParams = {}; postParams.alias = alias; postParams.email = email; - if (password) - { + if (password) { postParams.password = password; - } - if (passwordBis) - { + } + if (passwordBis) { postParams.passwordBis = passwordBis; - } + } postParams.defaultReport = defaultReport; postParams.defaultDate = defaultDate; @@ -52,13 +49,12 @@ function sendUserSettingsAJAX() ajaxHandler.setErrorElement('#ajaxErrorUserSettings'); ajaxHandler.send(true); } -function sendAnonymousUserSettingsAJAX() -{ - var anonymousDefaultReport = $('input[name=anonymousDefaultReport]:checked').val(); - if (anonymousDefaultReport == 1) { - anonymousDefaultReport = $('#anonymousDefaultReportWebsite option:selected').val(); - } - var anonymousDefaultDate = $('input[name=anonymousDefaultDate]:checked').val(); +function sendAnonymousUserSettingsAJAX() { + var anonymousDefaultReport = $('input[name=anonymousDefaultReport]:checked').val(); + if (anonymousDefaultReport == 1) { + anonymousDefaultReport = $('#anonymousDefaultReportWebsite option:selected').val(); + } + var anonymousDefaultDate = $('input[name=anonymousDefaultDate]:checked').val(); var ajaxHandler = new ajaxHelper(); ajaxHandler.addParams({ @@ -76,22 +72,23 @@ function sendAnonymousUserSettingsAJAX() ajaxHandler.send(true); } -$(document).ready( function() { - $('#userSettingsSubmit').click( function() { - if($('#password').length > 0 && $('#password').val() != '') { - piwikHelper.modalConfirm( '#confirmPasswordChange', {yes: sendUserSettingsAJAX}); - } else { +$(document).ready(function () { + $('#userSettingsSubmit').click(function () { + if ($('#password').length > 0 && $('#password').val() != '') { + piwikHelper.modalConfirm('#confirmPasswordChange', {yes: sendUserSettingsAJAX}); + } else { sendUserSettingsAJAX(); - } - - }); - $('#userSettingsTable input').keypress( function(e) { - var key=e.keyCode || e.which; - if (key==13) { - $('#userSettingsSubmit').click(); - }}); - - $('#anonymousUserSettingsSubmit').click( function() { - sendAnonymousUserSettingsAJAX(); - }); + } + + }); + $('#userSettingsTable input').keypress(function (e) { + var key = e.keyCode || e.which; + if (key == 13) { + $('#userSettingsSubmit').click(); + } + }); + + $('#anonymousUserSettingsSubmit').click(function () { + sendAnonymousUserSettingsAJAX(); + }); }); diff --git a/plugins/UsersManager/templates/userSettings.tpl b/plugins/UsersManager/templates/userSettings.tpl index 72449625dd..3219d1f561 100644 --- a/plugins/UsersManager/templates/userSettings.tpl +++ b/plugins/UsersManager/templates/userSettings.tpl @@ -2,138 +2,149 @@ {loadJavascriptTranslations plugins='UsersManager'}

{'UsersManager_MenuUserSettings'|translate}

-
+

{'UsersManager_ChangePasswordConfirm'|translate}

- - -
+ + + - - - - + + + + - - - + + - - - - - - - - - - - - - + {/if} + + + + + + + + + + + + + + -{if isset($isValidHost) && $isValidHost} - - - - -{/if} + {if isset($isValidHost) && $isValidHost} + + + + + {/if}
- - {'UsersManager_YourUsernameCannotBeChanged'|translate} -
+ + {'UsersManager_YourUsernameCannotBeChanged'|translate} +
- {if $isSuperUser} - +
+ {if $isSuperUser} + {'UsersManager_TheSuperUserAliasCannotBeChanged'|translate} - {/if} -
{'UsersManager_ReportToLoadByDefault'|translate} -
-
- - {if $defaultReport=='MultiSites'}{assign var=defaultReportIdSite value=1}{else}{assign var=defaultReportIdSite value=$defaultReport}{/if} - {include file="CoreHome/templates/sites_selection.tpl" - siteName=$defaultReportSiteName idSite=$defaultReportIdSite switchSiteOnSelect=false showAllSitesItem=false - showSelectedSite=false siteSelectorId='defaultReportSiteSelector'} -
-
{'UsersManager_ReportDateToLoadByDefault'|translate} -
- {foreach from=$availableDefaultDates key=value item=description} -
- {/foreach} -
-
{'UsersManager_ReportToLoadByDefault'|translate} +
+
+ + {if $defaultReport=='MultiSites'}{assign var=defaultReportIdSite value=1}{else}{assign var=defaultReportIdSite value=$defaultReport}{/if} + {include file="CoreHome/templates/sites_selection.tpl" + siteName=$defaultReportSiteName idSite=$defaultReportIdSite switchSiteOnSelect=false showAllSitesItem=false + showSelectedSite=false siteSelectorId='defaultReportSiteSelector'} +
+
{'UsersManager_ReportDateToLoadByDefault'|translate} +
+ {foreach from=$availableDefaultDates key=value item=description} + +
+ {/foreach} +
+
- {'UsersManager_IfYouWouldLikeToChangeThePasswordTypeANewOne'|translate} -

- {'UsersManager_TypeYourPasswordAgain'|translate} -
+ {'UsersManager_IfYouWouldLikeToChangeThePasswordTypeANewOne'|translate} +

+ {'UsersManager_TypeYourPasswordAgain'|translate} +
{if !isset($isValidHost) || !$isValidHost} -
- {'UsersManager_InjectedHostCannotChangePwd'|translate:$invalidHost} {if !$isSuperUser}{'UsersManager_EmailYourAdministrator'|translate:$invalidHostMailLinkStart:''}{/if} -
-
+
+ {'UsersManager_InjectedHostCannotChangePwd'|translate:$invalidHost} +  {if !$isSuperUser}{'UsersManager_EmailYourAdministrator'|translate:$invalidHostMailLinkStart:''}{/if} +
+
{/if} {ajaxErrorDiv id=ajaxErrorUserSettings} {ajaxLoadingDiv id=ajaxLoadingUserSettings} - +

{'UsersManager_ExcludeVisitsViaCookie'|translate}

{if $ignoreCookieSet}{'UsersManager_YourVisitsAreIgnoredOnDomain'|translate:"":$piwikHost:""} -{else}{'UsersManager_YourVisitsAreNotIgnored'|translate:"":""}{/if}

+ {else}{'UsersManager_YourVisitsAreNotIgnored'|translate:"":""}{/if}

› {if $ignoreCookieSet}{'UsersManager_ClickHereToDeleteTheCookie'|translate} -{else}{'UsersManager_ClickHereToSetTheCookieOnDomain'|translate:$piwikHost}{/if} -
+ {else}{'UsersManager_ClickHereToSetTheCookieOnDomain'|translate:$piwikHost}{/if} +


{if $isSuperUser} -

{'UsersManager_MenuAnonymousUserSettings'|translate}

- {if count($anonymousSites) == 0} -

{'UsersManager_NoteNoAnonymousUserAccessSettingsWontBeUsed2'|translate}


- {else} -
- - {ajaxErrorDiv id=ajaxErrorAnonymousUserSettings} - {ajaxLoadingDiv id=ajaxLoadingAnonymousUserSettings} - - - - - - - - - - - -
{'UsersManager_WhenUsersAreNotLoggedInAndVisitPiwikTheyShouldAccess'|translate} -
-
-
- - - {if !empty($anonymousSites)} - - {/if} -
-
{'UsersManager_ForAnonymousUsersReportDateToLoadByDefault'|translate} -
- {foreach from=$availableDefaultDates key=value item=description} -
- {/foreach} -
-
- - - {/if} +

{'UsersManager_MenuAnonymousUserSettings'|translate}

+ {if count($anonymousSites) == 0} +

{'UsersManager_NoteNoAnonymousUserAccessSettingsWontBeUsed2'|translate}

+
+ {else} +
+ {ajaxErrorDiv id=ajaxErrorAnonymousUserSettings} + {ajaxLoadingDiv id=ajaxLoadingAnonymousUserSettings} + + + + + + + + + + +
{'UsersManager_WhenUsersAreNotLoggedInAndVisitPiwikTheyShouldAccess'|translate} +
+
+
+ + + {if !empty($anonymousSites)} + + {/if} +
+
{'UsersManager_ForAnonymousUsersReportDateToLoadByDefault'|translate} +
+ {foreach from=$availableDefaultDates key=value item=description} + +
+ {/foreach} +
+
+ + {/if} {/if} -- cgit v1.2.3