public function newUserSession()
 {
     /* @var $identity LSUserIdentity */
     $sUser = $this->getUserName();
     $oUser = $this->api->getUserByName($sUser);
     if (is_null($oUser)) {
         if (function_exists("hook_get_auth_webserver_profile")) {
             // If defined this function returns an array
             // describing the default profile for this user
             $aUserProfile = hook_get_auth_webserver_profile($sUser);
         } elseif ($this->api->getConfigKey('auth_webserver_autocreate_user')) {
             $aUserProfile = $this->api->getConfigKey('auth_webserver_autocreate_profile');
         }
     } else {
         $this->setAuthSuccess($oUser);
         return;
     }
     if ($this->api->getConfigKey('auth_webserver_autocreate_user') && isset($aUserProfile) && is_null($oUser)) {
         // user doesn't exist but auto-create user is set
         $oUser = new User();
         $oUser->users_name = $sUser;
         $oUser->password = hash('sha256', createPassword());
         $oUser->full_name = $aUserProfile['full_name'];
         $oUser->parent_id = 1;
         $oUser->lang = $aUserProfile['lang'];
         $oUser->email = $aUserProfile['email'];
         if ($oUser->save()) {
             $permission = new Permission();
             $permission->setPermissions($oUser->uid, 0, 'global', $this->api->getConfigKey('auth_webserver_autocreate_permissions'), true);
             // read again user from newly created entry
             $this->setAuthSuccess($oUser);
             return;
         } else {
             $this->setAuthFailure(self::ERROR_USERNAME_INVALID);
         }
     }
 }
Exemple #2
0
 /**
  * Create a DB user
  *
  * @return unknown_type
  */
 public function createNewUser()
 {
     // Do nothing if the user to be added is not DB type
     if (flattenText(Yii::app()->request->getPost('user_type')) != 'DB') {
         return;
     }
     $oEvent = $this->getEvent();
     $new_user = flattenText(Yii::app()->request->getPost('new_user'), false, true);
     $new_email = flattenText(Yii::app()->request->getPost('new_email'), false, true);
     if (!validateEmailAddress($new_email)) {
         $oEvent->set('errorCode', self::ERROR_INVALID_EMAIL);
         $oEvent->set('errorMessageTitle', gT("Failed to add user"));
         $oEvent->set('errorMessageBody', gT("The email address is not valid."));
         return;
     }
     $new_full_name = flattenText(Yii::app()->request->getPost('new_full_name'), false, true);
     $new_pass = createPassword();
     $iNewUID = User::model()->insertUser($new_user, $new_pass, $new_full_name, Yii::app()->session['loginID'], $new_email);
     if (!$iNewUID) {
         $oEvent->set('errorCode', self::ERROR_ALREADY_EXISTING_USER);
         $oEvent->set('errorMessageTitle', '');
         $oEvent->set('errorMessageBody', gT("Failed to add user"));
         return;
     }
     Permission::model()->setGlobalPermission($iNewUID, 'auth_db');
     $oEvent->set('newUserID', $iNewUID);
     $oEvent->set('newPassword', $new_pass);
     $oEvent->set('newEmail', $new_email);
     $oEvent->set('newFullName', $new_full_name);
     $oEvent->set('errorCode', self::ERROR_NONE);
 }
 public function newUserSession()
 {
     // Do nothing if this user is not Authwebserver type
     $identity = $this->getEvent()->get('identity');
     if ($identity->plugin != 'Authwebserver') {
         return;
     }
     /* @var $identity LSUserIdentity */
     $sUser = $this->getUserName();
     $oUser = $this->api->getUserByName($sUser);
     if (is_null($oUser)) {
         if (function_exists("hook_get_auth_webserver_profile")) {
             // If defined this function returns an array
             // describing the default profile for this user
             $aUserProfile = hook_get_auth_webserver_profile($sUser);
         } elseif ($this->api->getConfigKey('auth_webserver_autocreate_user')) {
             $aUserProfile = $this->api->getConfigKey('auth_webserver_autocreate_profile');
         }
     } else {
         if (Permission::model()->hasGlobalPermission('auth_webserver', 'read', $oUser->uid)) {
             $this->setAuthSuccess($oUser);
             return;
         } else {
             $this->setAuthFailure(self::ERROR_AUTH_METHOD_INVALID, gT('Web server authentication method is not allowed for this user'));
             return;
         }
     }
     if ($this->api->getConfigKey('auth_webserver_autocreate_user') && isset($aUserProfile) && is_null($oUser)) {
         // user doesn't exist but auto-create user is set
         $oUser = new User();
         $oUser->users_name = $sUser;
         $oUser->password = hash('sha256', createPassword());
         $oUser->full_name = $aUserProfile['full_name'];
         $oUser->parent_id = 1;
         $oUser->lang = $aUserProfile['lang'];
         $oUser->email = $aUserProfile['email'];
         if ($oUser->save()) {
             $permission = new Permission();
             $permission->setPermissions($oUser->uid, 0, 'global', $this->api->getConfigKey('auth_webserver_autocreate_permissions'), true);
             Permission::model()->setGlobalPermission($oUser->uid, 'auth_webserver');
             // read again user from newly created entry
             $this->setAuthSuccess($oUser);
             return;
         } else {
             $this->setAuthFailure(self::ERROR_USERNAME_INVALID);
         }
     }
 }
 /**
  * Send the forgot password email
  *
  * @param string $sEmailAddr
  * @param array $aFields
  */
 private function _sendPasswordEmail($sEmailAddr, $aFields)
 {
     $clang = $this->getController()->lang;
     $sFrom = Yii::app()->getConfig("siteadminname") . " <" . Yii::app()->getConfig("siteadminemail") . ">";
     $sTo = $sEmailAddr;
     $sSubject = $clang->gT('User data');
     $sNewPass = createPassword();
     $sSiteName = Yii::app()->getConfig('sitename');
     $sSiteAdminBounce = Yii::app()->getConfig('siteadminbounce');
     $username = sprintf($clang->gT('Username: %s'), $aFields[0]['users_name']);
     $email = sprintf($clang->gT('Email: %s'), $sEmailAddr);
     $password = sprintf($clang->gT('New password: %s'), $sNewPass);
     $body = array();
     $body[] = sprintf($clang->gT('Your user data for accessing %s'), Yii::app()->getConfig('sitename'));
     $body[] = $username;
     $body[] = $password;
     $body = implode("\n", $body);
     if (SendEmailMessage($body, $sSubject, $sTo, $sFrom, $sSiteName, false, $sSiteAdminBounce)) {
         User::model()->updatePassword($aFields[0]['uid'], $sNewPass);
         $sMessage = $username . '<br />' . $email . '<br /><br />' . $clang->gT('An email with your login data was sent to you.');
     } else {
         $sTmp = str_replace("{NAME}", '<strong>' . $aFields[0]['users_name'] . '</strong>', $clang->gT("Email to {NAME} ({EMAIL}) failed."));
         $sMessage = str_replace("{EMAIL}", $sEmailAddr, $sTmp) . '<br />';
     }
     return $sMessage;
 }
Exemple #5
0
 isset($_POST['lastname']) ? $lastname = $_POST['lastname'] : ($lastname = "");
 isset($_POST['email']) ? $email = $_POST['email'] : ($email = "");
 $captchaKey = substr($_SESSION['key'], 0, 5);
 $formKey = $_POST['formKey'];
 if ($formKey == $captchaKey) {
     if ($firstname && $lastname) {
         include 'library/opendb.php';
         include 'include/common/common.php';
         $firstname = $dbSocket->escapeSimple($firstname);
         $lastname = $dbSocket->escapeSimple($lastname);
         $email = $dbSocket->escapeSimple($email);
         /* let's generate a random username and password
            of length 4 and with username prefix 'guest' */
         $rand = createPassword($configValues['CONFIG_USERNAME_LENGTH'], $configValues['CONFIG_USER_ALLOWEDRANDOMCHARS']);
         $username = $configValues['CONFIG_USERNAME_PREFIX'] . $rand;
         $password = createPassword($configValues['CONFIG_PASSWORD_LENGTH'], $configValues['CONFIG_USER_ALLOWEDRANDOMCHARS']);
         /* adding the user to the radcheck table */
         $sql = "INSERT INTO " . $configValues['CONFIG_DB_TBL_RADCHECK'] . " (id, Username, Attribute, op, Value) " . " VALUES (0, '{$username}', 'User-Password', '==', '{$password}')";
         $res = $dbSocket->query($sql);
         /* adding user information to the userinfo table */
         $sql = "INSERT INTO " . $configValues['CONFIG_DB_TBL_DALOUSERINFO'] . " (username, firstname, lastname, email) " . " VALUES ('{$username}', '{$firstname}', '{$lastname}', '{$email}')";
         $res = $dbSocket->query($sql);
         /* adding the user to the default group defined */
         if (isset($configValues['CONFIG_GROUP_NAME']) && $configValues['CONFIG_GROUP_NAME'] != "") {
             $sql = "INSERT INTO " . $configValues['CONFIG_DB_TBL_RADUSERGROUP'] . " (UserName, GroupName, priority) " . " VALUES ('{$username}', '" . $configValues['CONFIG_GROUP_NAME'] . "', '" . $configValues['CONFIG_GROUP_PRIORITY'] . "')";
             $res = $dbSocket->query($sql);
         }
         include 'library/closedb.php';
         $status = "success";
     } else {
         $status = "fieldsFailure";
 // we do not create users and continue with the batch loop process
 // if batch_history creation failed.
 if ($sql_batch_id == 0) {
     break;
 }
 switch ($createBatchUsersType) {
     case "createRandomUsers":
         $username = createPassword($length_user, $configValues['CONFIG_USER_ALLOWEDRANDOMCHARS']);
         break;
     case "createIncrementUsers":
         $username = $startingIndex + $i;
         break;
 }
 // append the prefix to the username
 $username = $username_prefix . $username;
 $password = createPassword($length_pass, $configValues['CONFIG_USER_ALLOWEDRANDOMCHARS']);
 $sql = "SELECT * FROM " . $configValues['CONFIG_DB_TBL_RADCHECK'] . " WHERE UserName='******'";
 $res = $dbSocket->query($sql);
 $logDebugSQL .= $sql . "\n";
 if ($res->numRows() > 0) {
     $actionMsgBadUsernames = $actionMsgBadUsernames . $username . ", ";
     $failureMsg = "skipping matching entry: <b> {$actionMsgBadUsernames} </b>";
 } else {
     // insert username/password
     $actionMsgGoodUsernames .= $username;
     if ($i + 1 != $number) {
         $actionMsgGoodUsernames .= ", ";
     }
     $sql = "INSERT INTO " . $configValues['CONFIG_DB_TBL_RADCHECK'] . " VALUES (0, '" . $dbSocket->escapeSimple($username) . "',  'User-Password', ':=', '" . $dbSocket->escapeSimple($password) . "')";
     $res = $dbSocket->query($sql);
     $logDebugSQL .= $sql . "\n";
Exemple #7
0
 * First check if user exist
 */
$query = "SELECT userid FROM users WHERE email='" . pg_escape_string(strtolower($_POST['email'])) . "'";
$result = pg_query($dbh, $query) or die('{"error":{"message":"Error : registering is currently unavailable"}}');
$userid = -1;
while ($user = pg_fetch_row($result)) {
    $userid = $user[0];
}
/**
 * User does not exist => generate a password and insert new user within database
 */
if ($userid == -1) {
    /*
     * Create a new password
     */
    $password = createPassword(6);
    $email = pg_escape_string($dbh, strtolower($_POST['email']));
    $username = pg_escape_string($dbh, strtolower($_POST['username']));
    $query = "INSERT INTO users (username,password,email,registrationdate) VALUES ('" . $username . "','" . md5($password) . "','" . $email . "', now())";
    $result = pg_query($dbh, $query) or die('{"error":{"message":"Error : registering is currently unavailable"}}');
} else {
    pg_close($dbh);
    die('{"error":{"message":"Error : email adress is already registered"}}');
}
/*
 * Prepare message
 */
$to = $email;
$subject = "[mapshup] Requested password for user " . $email;
$message = "Hi,\r\n\r\n" . "You have requested a password for mapshup application at " . MSP_DOMAIN . "\r\n\r\n" . "Your password is " . $password . "\r\n\r\n" . "Regards" . "\r\n\r\n" . "The mapshup team";
$headers = "From: " . MSP_ADMIN_EMAIL . "\r\n" . "Reply-To: " . MSP_ADMIN_EMAIL . "\r\n" . "X-Mailer: PHP/" . phpversion();
Exemple #8
0
/**
 * This script returns GeoJSON
 */
header("Pragma: no-cache");
header("Expires: 0");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Content-type: application/json; charset=utf-8");
/**
 * TODO : allow only ws.geonames.net to idenfied user ?
 * $url = 'http://ws.geonames.org/wikipediaSearch?';
 */
$url = 'http://ws.geonames.net/wikipediaSearch?username=jrom&';
/*
 * Search terms
 */
$q = isset($_REQUEST["q"]) ? $_REQUEST["q"] : "";
/*
 * Lang
 */
$lang = isset($_REQUEST["lang"]) ? $_REQUEST["lang"] : "en";
/*
 * Number of results
 */
$maxRows = isset($_REQUEST["maxRows"]) ? $_REQUEST["maxRows"] : MSP_RESULTS_PER_PAGE;
/**
 * NB: tags are comma separated
 */
$url = $url . "q=" . $q . "&maxRows=" . $maxRows . "&lang=" . $lang;
echo toGeoJSON(saveFile(getRemoteData($url, null, false), MSP_UPLOAD_DIR . "wikipedia_" . createPassword(10) . ".xml"));
Exemple #9
0
 /**
  * Create the autoconf.php file.
  */
 case "write_config":
     include "../includes/func.php";
     // special characters " and $ are escaped
     $database = $_REQUEST['database'];
     $hostname = $_REQUEST['hostname'];
     $username = $_REQUEST['username'];
     $password = $_REQUEST['password'];
     $timezone = $_REQUEST['timezone'];
     $db_layer = $_REQUEST['db_layer'];
     $db_type = $_REQUEST['db_type'];
     $prefix = addcslashes($_REQUEST['prefix'], '"$');
     $lang = $_REQUEST['lang'];
     $salt = createPassword(20);
     write_config_file($database, $hostname, $username, $password, $db_layer, $db_type, $prefix, $lang, $salt, $timezone);
     break;
     /**
      * Create the database.
      */
 /**
  * Create the database.
  */
 case "make_database":
     $databaseName = $_REQUEST['database'];
     $hostname = $_REQUEST['hostname'];
     $username = $_REQUEST['username'];
     $password = $_REQUEST['password'];
     $server_type = $_REQUEST['db_type'];
     $db_layer = $_REQUEST['db_layer'];
Exemple #10
0
      die($kga['lang']['updater'][130]);
      


  /*
   *  Reset all passwords
   */
  $new_passwords = array();

  $users = $database->queryAll("SELECT * FROM ${p}usr");

  foreach ($users as $user) {
    if ($user['usr_name'] == 'admin')
      $new_password = '******';
    else
      $new_password = createPassword(8);
    exec_query("UPDATE ${p}usr SET pw = '".
        md5($kga['password_salt'].$new_password.$kga['password_salt']).
        "' WHERE usr_ID = $user[usr_ID]");
    if ($result)    
      $new_passwords[$user['usr_name']] = $new_password;
  }

}

if ((int)$revisionDB < 1068) {
    Logger::logfile("-- update to r1068");
    exec_query("ALTER TABLE `${p}usr` CHANGE `autoselection` `autoselection` TINYINT( 1 ) NOT NULL default '0';");
}

if ((int)$revisionDB < 1077) {
Exemple #11
0
    public function newUserSession() {
        if ($this->ssp->isAuthenticated()) {

            $sUser = $this->getUserName();
            $_SERVER['REMOTE_USER'] = $sUser;

            $password = createPassword();
            $this->setPassword($password);

            $name = $this->getUserCommonName();
            $mail = $this->getUserMail();

            $oUser = $this->api->getUserByName($sUser);
            if (is_null($oUser)) {
                // Create user
                $auto_create_users = $this->get('auto_create_users', null, null, true);
                if ($auto_create_users) {

                    $iNewUID = User::model()->insertUser($sUser, $password, $name, 1, $mail);

                    if ($iNewUID) {
                        Permission::model()->insertSomeRecords(array('uid' => $iNewUID, 'permission' => Yii::app()->getConfig("defaulttemplate"), 'entity' => 'template', 'read_p' => 1));

                        // Set permissions: Label Sets 
                        $auto_create_labelsets = $this->get('auto_create_labelsets', null, null, true);
                        if ($auto_create_labelsets) {

                            Permission::model()->insertSomeRecords(array('uid' => $iNewUID, 'permission' => 'labelsets', 'entity' => 'global', 'create_p' => 1, 'read_p' => 1, 'update_p' => 1, 'delete_p' => 1, 'import_p' => 1, 'export_p' => 1));
                        }

                        // Set permissions: Particiapnt Panel 
                        $auto_create_participant_panel = $this->get('auto_create_participant_panel', null, null, true);
                        if ($auto_create_participant_panel) {

                            Permission::model()->insertSomeRecords(array('uid' => $iNewUID, 'permission' => 'participantpanel', 'entity' => 'global', 'create_p' => 1, 'read_p' => 0, 'update_p' => 0, 'delete_p' => 0, 'export_p' => 0));
                        }

                        // Set permissions: Settings & Plugins 
                        $auto_create_settings_plugins = $this->get('auto_create_settings_plugins', null, null, true);
                        if ($auto_create_settings_plugins) {

                            Permission::model()->insertSomeRecords(array('uid' => $iNewUID, 'permission' => 'settings', 'entity' => 'global', 'create_p' => 0, 'read_p' => 1, 'update_p' => 1, 'delete_p' => 0, 'import_p' => 1, 'export_p' => 0));
                        }

                        // Set permissions: surveys 
                        $auto_create_surveys = $this->get('auto_create_surveys', null, null, true);
                        if ($auto_create_surveys) {

                            Permission::model()->insertSomeRecords(array('uid' => $iNewUID, 'permission' => 'surveys', 'entity' => 'global', 'create_p' => 1, 'read_p' => 0, 'update_p' => 0, 'delete_p' => 0, 'export_p' => 0));
                        }

                        // Set permissions: Templates 
                        $auto_create_templates = $this->get('auto_create_templates', null, null, true);
                        if ($auto_create_templates) {

                            Permission::model()->insertSomeRecords(array('uid' => $iNewUID, 'permission' => 'templates', 'entity' => 'global', 'create_p' => 1, 'read_p' => 1, 'update_p' => 1, 'delete_p' => 1, 'import_p' => 1, 'export_p' => 1));
                        }

                        // Set permissions: User Groups 
                        $auto_create_user_groups = $this->get('auto_create_user_groups', null, null, true);
                        if ($auto_create_user_groups) {

                            Permission::model()->insertSomeRecords(array('uid' => $iNewUID, 'permission' => 'usergroups', 'entity' => 'global', 'create_p' => 1, 'read_p' => 1, 'update_p' => 1, 'delete_p' => 1, 'export_p' => 0));
                        }

                        // read again user from newly created entry
                        $oUser = $this->api->getUserByName($sUser);

                        $this->setAuthSuccess($oUser);
                    } else {
                        $this->setAuthFailure(self::ERROR_USERNAME_INVALID);
                    }
                } else {
                    $this->setAuthFailure(self::ERROR_USERNAME_INVALID);
                }
            } else {
                // Update user?
                $auto_update_users = $this->get('auto_update_users', null, null, true);
                if ($auto_update_users) {
                    $changes = array(
                        'full_name' => $name,
                        'email' => $mail,
                    );

                    User::model()->updateByPk($oUser->uid, $changes);


                    $oUser = $this->api->getUserByName($sUser);
                }

                $this->setAuthSuccess($oUser);
            }
        }
    }
 } else {
     $checkEmail = UserPeer::loadUserByEmailAddress($emailAddress);
     if ($checkEmail) {
         // username exists
         setError(t("email_address_already_exists", "Email address already exists on another account"));
     } else {
         $checkUser = UserPeer::loadUserByUsername($username);
         if ($checkUser) {
             // username exists
             setError(t("username_already_exists", "Username already exists on another account"));
         }
     }
 }
 // create the account
 if (!isErrors()) {
     $newPassword = createPassword();
     $newUser = UserPeer::create($username, $newPassword, $emailAddress, $title, $firstname, $lastname);
     if ($newUser) {
         $subject = "Account details for " . SITE_CONFIG_SITE_NAME;
         $plainMsg = "Dear " . $firstname . ",\n\n";
         $plainMsg .= "Your account on " . SITE_CONFIG_SITE_NAME . " has be created. Use the details below to login to your new account:\n\n";
         $plainMsg .= "<strong>Url:</strong> <a href='" . WEB_ROOT . "'>" . WEB_ROOT . "</a>\n";
         $plainMsg .= "<strong>Username:</strong> " . $username . "\n";
         $plainMsg .= "<strong>Password:</strong> " . $newPassword . "\n\n";
         $plainMsg .= "Feel free to contact us if you need any support with your account.\n\n";
         $plainMsg .= "Regards,\n";
         $plainMsg .= SITE_CONFIG_SITE_NAME . " Admin\n";
         send_html_mail($emailAddress, $subject, str_replace("\n", "<br/>", $plainMsg), SITE_CONFIG_DEFAULT_EMAIL_ADDRESS_FROM, strip_tags($plainMsg));
         redirect(WEB_ROOT . "/register_complete." . SITE_CONFIG_PAGE_EXTENSION);
     } else {
         setError(t("problem_creating_your_account_try_again_later", "There was a problem creating your account, please try again later"));
Exemple #13
0
// for later retreiving of the transaction details
$status = "firstload";
$errorMissingFields = false;
$userPIN = "";
if (isset($_POST['submit'])) {
    isset($_POST['firstName']) ? $firstName = $_POST['firstName'] : ($firstName = "");
    isset($_POST['lastName']) ? $lastName = $_POST['lastName'] : ($lastName = "");
    isset($_POST['address']) ? $address = $_POST['address'] : ($address = "");
    isset($_POST['city']) ? $city = $_POST['city'] : ($city = "");
    isset($_POST['state']) ? $state = $_POST['state'] : ($state = "");
    isset($_POST['planId']) ? $planId = $_POST['planId'] : ($planId = "");
    if ($firstName != "" && $lastName != "" && $address != "" && $city != "" && $state != "" && $planId != "") {
        // all paramteres have been set, save it in the database
        $currDate = date('Y-m-d H:i:s');
        $currBy = "2Checkout-webinterface";
        $userPIN = createPassword($configValues['CONFIG_USERNAME_LENGTH'], $configValues['CONFIG_USER_ALLOWEDRANDOMCHARS']);
        // lets create some random data for user pin
        $planId = $dbSocket->escapeSimple($planId);
        // grab information about a plan from the table
        $sql = "SELECT planId,planName,planCost,planTax,planCurrency FROM " . $configValues['CONFIG_DB_TBL_DALOBILLINGPLANS'] . " WHERE (planType='2Checkout') AND (planId='{$planId}') ";
        $res = $dbSocket->query($sql);
        $row = $res->fetchRow();
        $planId = $row[0];
        $planName = $row[1];
        $planCost = $row[2];
        $planTax = $row[3];
        $planCurrency = $row[4];
        // lets add user information to the database
        $sql = "INSERT INTO " . $configValues['CONFIG_DB_TBL_DALOUSERINFO'] . " (id, username, firstname, lastname, creationdate, creationby)" . " VALUES (0,'{$userPIN}','" . $dbSocket->escapeSimple($firstName) . "','" . $dbSocket->escapeSimple($lastName) . "'," . "'{$currDate}','{$currBy}'" . ")";
        $res = $dbSocket->query($sql);
        // lets add user billing information to the database
      </Constraint>
   </csw:Query>
</GetRecords>';
/**
 * Send a post $request at $url
 * 
 * If headers is set to false, do not force headers
 * during POST request
 */
if (isset($_REQUEST["headers"]) && $_REQUEST["headers"] == "false") {
    $theData = postRemoteData($url, $request, false);
} else {
    $theData = postRemoteData($url, $request, true);
}
/**
 * Store request and response
 */
if (MSP_DEBUG) {
    $tmp = createPassword(10);
    saveFile($request, MSP_UPLOAD_DIR . "csw_" . $tmp . "_request.xml");
    $resultFileURI = saveFile($theData, MSP_UPLOAD_DIR . "csw_" . $tmp . "_response.xml");
}
/**
 *  Check if a SOAP Fault occured
 */
$error = OWSExceptionToJSON($theData);
if ($error) {
    echo $error;
} else {
    echo outputToGeoJSON($theData);
}
Exemple #15
0
function changePassword($userid, $token, $email)
{
    $tokenSQL = "SELECT EXISTS (\n    SELECT * FROM pwReset where user_id = {$userid} AND token='{$token}' AND ts + INTERVAL 20 MINUTE > NOW())";
    $tokenData = db::executeSqlColumn($tokenSQL);
    if ($tokenData[0] === 0) {
        resetForm($email);
    }
    if (!isset($_POST['pass1']) || !isset($_POST['pass2'])) {
        changePwForm($userid, $token, $email, 'Passwords not set, it must be at least 8 characters');
    }
    if ($_POST['pass1'] !== $_POST['pass2'] && strlen($_POST['pass1']) < 8) {
        changePwForm($userid, $token, $email, 'Passwords do not match or is less than 8 characters');
    }
    $uPass = createPassword($_POST['pass1']);
    $sql = "UPDATE `users` set " . "`password`= '" . $uPass['pass'] . "', " . " `salt` = '" . $uPass['salt'] . "' " . " WHERE " . " id = " . $userid;
    //~ db::executeISql();
    $pwChanged = db::executeISql($sql);
    if ($pwChanged) {
        echo '<p>Password has been reset.</p>';
    } else {
        die('Unknown Error Occured please contact support');
    }
    exit;
    die;
}
Exemple #16
0
function encrypt(&$session, $value, $salt)
{
    return createPassword($session, 6) . strrev($value) . 'jfi9';
}
Exemple #17
0
 }
 if (isset($_POST['city'])) {
     $city = $_POST['city'];
 }
 if (isset($_POST['state'])) {
     $state = $_POST['state'];
 }
 if (isset($_POST['planId'])) {
     $planId = $_POST['planId'];
 }
 if (isset($firstName) && isset($lastName) && isset($address) && isset($city) && isset($state) && isset($planId)) {
     // all paramteres have been set, save it in the database
     $currDate = date('Y-m-d H:i:s');
     $currBy = "paypal-webinterface";
     // lets create some random data for user pin
     $userPIN = createPassword(8, $configValues['CONFIG_USER_ALLOWEDRANDOMCHARS']);
     $planId = $dbSocket->escapeSimple($planId);
     // grab information about a plan from the table
     $sql = "SELECT planId,planName,planCost,planTax,planCurrency FROM " . $configValues['CONFIG_DB_TBL_DALOBILLINGPLANS'] . " WHERE (planType='PayPal') AND (planId='{$planId}') ";
     $res = $dbSocket->query($sql);
     $row = $res->fetchRow();
     $planId = $row[0];
     $planName = $row[1];
     $planCost = $row[2];
     $planTax = $row[3];
     $planCurrency = $row[4];
     // lets add user information to the database
     $sql = "INSERT INTO " . $configValues['CONFIG_DB_TBL_DALOUSERINFO'] . " (id, username, firstname, lastname, creationdate, creationby)" . " VALUES (0,'{$userPIN}','" . $dbSocket->escapeSimple($firstName) . "','" . $dbSocket->escapeSimple($lastName) . "'," . "'{$currDate}','{$currBy}'" . ")";
     $res = $dbSocket->query($sql);
     // lets add user billing information to the database
     $sql = "INSERT INTO " . $configValues['CONFIG_DB_TBL_DALOBILLINGPAYPAL'] . " (id, username, txnId, planName, planId)" . " VALUES (0,'{$userPIN}','{$txnId}','{$planName}','{$planId}'" . ")";
// verify the email address passes a sniff test
if (!empty($error)) {
    header("Location: http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/createaccount.php?username={$username}&fullname={$fullname}&email={$email}&email2={$email2}&error=" . urlencode($error));
    exit;
}
//create an activation code
/* there may be a better way to do this.  My thought is that md5 gives me a
string that is pretty random and long enough that it is essentially impossible
to guess.  By seeding it with microtime and username the key should be different
for each user it would take a couple of thousand guesses to get a match if you
tried to brute force create every possible activationKey for the time around
when the attackers account was created.
*/
$activationCode = md5(microtime() . $username);
// create the actual account
$encryptedPassword = createPassword($username, $password);
if (!createAccount($username, $encryptedPassword, $fullname, $domain, $email, $activationCode)) {
    // oops ... got an error creating the account
    $error = $error . "Error while creating account.";
    header("Location: http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/createaccount.php?username={$username}&fullname={$fullname}&email={$email}&email2={$email2}&error=" . urlencode($error));
    exit;
}
// create a default resource
$defaultAOR = $username . '@' . $domain;
if (!createResource($username, $defaultAOR, 'N', '', '')) {
    // oops ... got an error creating the default resource
    $error = $error . "Error while creating account (default resource).";
    header("Location: http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/createaccount.php?username={$username}&fullname={$fullname}&email={$email}&email2={$email2}&error=" . urlencode($error));
    exit;
}
// email the activation notice
Exemple #19
0
 /**
  * Checks whether this user has correctly entered password or not
  *
  * @access public
  * @return bool
  */
 public function authenticate($sOneTimePassword = '')
 {
     if (Yii::app()->getConfig("auth_webserver") == false || $this->username != "") {
         $user = User::model()->findByAttributes(array('users_name' => $this->username));
         if ($user !== null) {
             if (gettype($user->password) == 'resource') {
                 $sStoredPassword = stream_get_contents($user->password, -1, 0);
                 // Postgres delivers bytea fields as streams :-o
             } else {
                 $sStoredPassword = $user->password;
             }
         } else {
             $this->errorCode = self::ERROR_USERNAME_INVALID;
             return !$this->errorCode;
         }
         if ($sOneTimePassword != '' && Yii::app()->getConfig("use_one_time_passwords") && md5($sOneTimePassword) == $user->one_time_pw) {
             $user->one_time_pw = '';
             $user->save();
             $this->id = $user->uid;
             $this->user = $user;
             $this->errorCode = self::ERROR_NONE;
         } elseif ($sStoredPassword !== hash('sha256', $this->password)) {
             $this->errorCode = self::ERROR_PASSWORD_INVALID;
         } else {
             $this->id = $user->uid;
             $this->user = $user;
             $this->errorCode = self::ERROR_NONE;
         }
     } elseif (Yii::app()->getConfig("auth_webserver") === true && (isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER['LOGON_USER']))) {
         if (isset($_SERVER['PHP_AUTH_USER'])) {
             $sUser = $_SERVER['PHP_AUTH_USER'];
         } else {
             $sUser = $_SERVER['LOGON_USER'];
             $sUser = substr($sUser, strrpos($sUser, "\\") + 1);
         }
         $aUserMappings = Yii::app()->getConfig("auth_webserver_user_map");
         if (isset($aUserMappings[$sUser])) {
             $sUser = $aUserMappings[$sUser];
         }
         $oUser = User::model()->findByAttributes(array('users_name' => $sUser));
         if (is_null($oUser)) {
             if (function_exists("hook_get_auth_webserver_profile")) {
                 // If defined this function returns an array
                 // describing the defaukt profile for this user
                 $aUserProfile = hook_get_autouserprofile($sUser);
             } elseif (Yii::app()->getConfig("auth_webserver_autocreate_user")) {
                 $aUserProfile = Yii::app()->getConfig("auth_webserver_autocreate_profile");
             }
         } else {
             $this->id = $oUser->uid;
             $this->user = $oUser;
             $this->errorCode = self::ERROR_NONE;
         }
         if (Yii::app()->getConfig("auth_webserver_autocreate_user") && isset($aUserProfile) && is_null($oUser)) {
             // user doesn't exist but auto-create user is set
             $oUser = new User();
             $oUser->users_name = $sUser;
             $oUser->password = hash('sha256', createPassword());
             $oUser->full_name = $aUserProfile['full_name'];
             $oUser->parent_id = 1;
             $oUser->lang = $aUserProfile['lang'];
             $oUser->email = $aUserProfile['email'];
             $oUser->create_survey = $aUserProfile['create_survey'];
             $oUser->create_user = $aUserProfile['create_user'];
             $oUser->delete_user = $aUserProfile['delete_user'];
             $oUser->superadmin = $aUserProfile['superadmin'];
             $oUser->configurator = $aUserProfile['configurator'];
             $oUser->manage_template = $aUserProfile['manage_template'];
             $oUser->manage_label = $aUserProfile['manage_label'];
             if ($oUser->save()) {
                 $aTemplates = explode(",", $aUserProfile['templatelist']);
                 foreach ($aTemplates as $sTemplateName) {
                     $oRecord = new Templates_rights();
                     $oRecord->uid = $oUser->uid;
                     $oRecord->folder = trim($sTemplateName);
                     $oRecord->use = 1;
                     $oRecord->save();
                 }
                 // read again user from newly created entry
                 $this->id = $oUser->uid;
                 $this->user = $oUser;
                 $this->errorCode = self::ERROR_NONE;
             } else {
                 $this->errorCode = self::ERROR_USERNAME_INVALID;
             }
         }
     } else {
         $this->errorCode = self::ERROR_USERNAME_INVALID;
     }
     return !$this->errorCode;
 }
Exemple #20
0
 /**
  * Create a LDAP user
  *
  * @param string $new_user
  * @return null|string New user ID
  */
 private function _createNewUser($new_user)
 {
     $oEvent = $this->getEvent();
     // Get configuration settings:
     $ldapserver = $this->get('server');
     $ldapport = $this->get('ldapport');
     $ldapmode = $this->get('ldapmode');
     $searchuserattribute = $this->get('searchuserattribute');
     $extrauserfilter = $this->get('extrauserfilter');
     $usersearchbase = $this->get('usersearchbase');
     $binddn = $this->get('binddn');
     $bindpwd = $this->get('bindpwd');
     $mailattribute = $this->get('mailattribute');
     $fullnameattribute = $this->get('fullnameattribute');
     // Try to connect
     $ldapconn = $this->createConnection();
     if (!is_resource($ldapconn)) {
         $oEvent->set('errorCode', self::ERROR_LDAP_CONNECTION);
         $oEvent->set('errorMessageTitle', '');
         $oEvent->set('errorMessageBody', $ldapconn['errorMessage']);
         return null;
     }
     if (empty($ldapmode) || $ldapmode == 'simplebind') {
         $oEvent->set('errorCode', self::ERROR_LDAP_MODE);
         $oEvent->set('errorMessageTitle', gT("Failed to add user"));
         $oEvent->set('errorMessageBody', gT("Simple bind LDAP configuration doesn't allow LDAP user creation"));
         return null;
     }
     // Search email address and full name
     if (empty($binddn)) {
         // There is no account defined to do the LDAP search,
         // let's use anonymous bind instead
         $ldapbindsearch = @ldap_bind($ldapconn);
     } else {
         // An account is defined to do the LDAP search, let's use it
         $ldapbindsearch = @ldap_bind($ldapconn, $binddn, $bindpwd);
     }
     if (!$ldapbindsearch) {
         $oEvent->set('errorCode', self::ERROR_LDAP_NO_BIND);
         $oEvent->set('errorMessageTitle', gT('Could not connect to LDAP server.'));
         $oEvent->set('errorMessageBody', gT(ldap_error($ldapconn)));
         ldap_close($ldapconn);
         // all done? close connection
         return null;
     }
     // Now prepare the search fitler
     if ($extrauserfilter != "") {
         $usersearchfilter = "(&({$searchuserattribute}={$new_user}){$extrauserfilter})";
     } else {
         $usersearchfilter = "({$searchuserattribute}={$new_user})";
     }
     // Search for the user
     $dnsearchres = ldap_search($ldapconn, $usersearchbase, $usersearchfilter, array($mailattribute, $fullnameattribute));
     $rescount = ldap_count_entries($ldapconn, $dnsearchres);
     if ($rescount == 1) {
         $userentry = ldap_get_entries($ldapconn, $dnsearchres);
         $new_email = flattenText($userentry[0][$mailattribute][0]);
         $new_full_name = flattenText($userentry[0][strtolower($fullnameattribute)][0]);
     } else {
         $oEvent->set('errorCode', self::ERROR_LDAP_NO_SEARCH_RESULT);
         $oEvent->set('errorMessageTitle', gT('Username not found in LDAP server'));
         $oEvent->set('errorMessageBody', gT('Verify username and try again'));
         ldap_close($ldapconn);
         // all done? close connection
         return null;
     }
     if (!validateEmailAddress($new_email)) {
         $oEvent->set('errorCode', self::ERROR_INVALID_EMAIL);
         $oEvent->set('errorMessageTitle', gT("Failed to add user"));
         $oEvent->set('errorMessageBody', gT("The email address is not valid."));
         return null;
     }
     $new_pass = createPassword();
     // If user is being auto created we set parent ID to 1 (admin user)
     if (isset(Yii::app()->session['loginID'])) {
         $parentID = Yii::app()->session['loginID'];
     } else {
         $parentID = 1;
     }
     $iNewUID = User::model()->insertUser($new_user, $new_pass, $new_full_name, $parentID, $new_email);
     if (!$iNewUID) {
         $oEvent->set('errorCode', self::ERROR_ALREADY_EXISTING_USER);
         $oEvent->set('errorMessageTitle', '');
         $oEvent->set('errorMessageBody', gT("Failed to add user"));
         return null;
     }
     Permission::model()->setGlobalPermission($iNewUID, 'auth_ldap');
     $oEvent->set('newUserID', $iNewUID);
     $oEvent->set('newPassword', $new_pass);
     $oEvent->set('newEmail', $new_email);
     $oEvent->set('newFullName', $new_full_name);
     $oEvent->set('errorCode', self::ERROR_NONE);
     return $iNewUID;
 }
 /**
  * Send the forgot password email
  *
  * @param string $sEmailAddr
  * @param array $aFields
  */
 private function _sendPasswordEmail($sEmailAddr, $aFields)
 {
     $sFrom = Yii::app()->getConfig("siteadminname") . " <" . Yii::app()->getConfig("siteadminemail") . ">";
     $sTo = $sEmailAddr;
     $sSubject = gT('User data');
     $sNewPass = createPassword();
     $sSiteName = Yii::app()->getConfig('sitename');
     $sSiteAdminBounce = Yii::app()->getConfig('siteadminbounce');
     $username = sprintf(gT('Username: %s'), $aFields[0]['users_name']);
     $email = sprintf(gT('Email: %s'), $sEmailAddr);
     $password = sprintf(gT('New password: %s'), $sNewPass);
     $body = array();
     $body[] = sprintf(gT('Your user data for accessing %s'), Yii::app()->getConfig('sitename'));
     $body[] = $username;
     $body[] = $password;
     $body = implode("\n", $body);
     if (SendEmailMessage($body, $sSubject, $sTo, $sFrom, $sSiteName, false, $sSiteAdminBounce)) {
         User::model()->updatePassword($aFields[0]['uid'], $sNewPass);
         // For security reasons, we don't show a successful message
         $sMessage = gT($this->sent_email_message);
     } else {
         $sMessage = gT('Email failed');
     }
     return $sMessage;
 }
Exemple #22
0
 public function newUserSession()
 {
     // Do nothing if this user is not AuthCAS type
     $identity = $this->getEvent()->get('identity');
     if ($identity->plugin != 'AuthCAS') {
         return;
     }
     $sUser = $this->getUserName();
     $oUser = $this->api->getUserByName($sUser);
     if (is_null($oUser)) {
         if ((bool) $this->get('autoCreate') === true) {
             // auto-create
             // Get configuration settings:
             $ldapserver = $this->get('server');
             $ldapport = $this->get('ldapport');
             $ldapver = $this->get('ldapversion');
             $ldaptls = $this->get('ldaptls');
             $ldapoptreferrals = $this->get('ldapoptreferrals');
             $searchuserattribute = $this->get('searchuserattribute');
             $extrauserfilter = $this->get('extrauserfilter');
             $usersearchbase = $this->get('usersearchbase');
             $binddn = $this->get('binddn');
             $bindpwd = $this->get('bindpwd');
             $username = $sUser;
             if (empty($ldapport)) {
                 $ldapport = 389;
             }
             // Try to connect
             $ldapconn = ldap_connect($ldapserver, (int) $ldapport);
             if (false == $ldapconn) {
                 $this->setAuthFailure(1, gT('Could not connect to LDAP server.'));
                 return;
             }
             // using LDAP version
             if ($ldapver === null) {
                 // If the version hasn't been set, default = 2
                 $ldapver = 2;
             }
             ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, $ldapver);
             ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, $ldapoptreferrals);
             if (!empty($ldaptls) && $ldaptls == '1' && $ldapver == 3 && preg_match("/^ldaps:\\/\\//", $ldapserver) == 0) {
                 // starting TLS secure layer
                 if (!ldap_start_tls($ldapconn)) {
                     $this->setAuthFailure(100, ldap_error($ldapconn));
                     ldap_close($ldapconn);
                     // all done? close connection
                     return;
                 }
             }
             // We first do a LDAP search from the username given
             // to find the userDN and then we procced to the bind operation
             if (empty($binddn)) {
                 // There is no account defined to do the LDAP search,
                 // let's use anonymous bind instead
                 $ldapbindsearch = @ldap_bind($ldapconn);
             } else {
                 // An account is defined to do the LDAP search, let's use it
                 $ldapbindsearch = @ldap_bind($ldapconn, $binddn, $bindpwd);
             }
             if (!$ldapbindsearch) {
                 $this->setAuthFailure(100, ldap_error($ldapconn));
                 ldap_close($ldapconn);
                 // all done? close connection
                 return;
             }
             // Now prepare the search filter
             if ($extrauserfilter != "") {
                 $usersearchfilter = "(&({$searchuserattribute}={$username}){$extrauserfilter})";
             } else {
                 $usersearchfilter = "({$searchuserattribute}={$username})";
             }
             // Search for the user
             $dnsearchres = ldap_search($ldapconn, $usersearchbase, $usersearchfilter, array($searchuserattribute, "displayname", "mail"));
             $rescount = ldap_count_entries($ldapconn, $dnsearchres);
             if ($rescount == 1) {
                 $userentry = ldap_get_entries($ldapconn, $dnsearchres);
                 $userdn = $userentry[0]["dn"];
                 $oUser = new User();
                 $oUser->users_name = $username;
                 $oUser->password = hash('sha256', createPassword());
                 $oUser->full_name = $userentry[0]["displayname"][0];
                 $oUser->parent_id = 1;
                 $oUser->email = $userentry[0]["mail"][0];
                 if ($oUser->save()) {
                     $permission = new Permission();
                     $permission->setPermissions($oUser->uid, 0, 'global', $this->api->getConfigKey('auth_cas_autocreate_permissions'), true);
                     // read again user from newly created entry
                     $this->setAuthSuccess($oUser);
                     return;
                 } else {
                     $this->setAuthFailure(self::ERROR_USERNAME_INVALID);
                     throw new CHttpException(401, 'User not saved : ' . $userentry[0]["mail"][0] . " / " . $userentry[0]["displayName"]);
                     return;
                 }
             } else {
                 // if no entry or more than one entry returned
                 // then deny authentication
                 $this->setAuthFailure(100, ldap_error($ldapconn));
                 ldap_close($ldapconn);
                 // all done? close connection
                 throw new CHttpException(401, 'No authorized user found for login "' . $username . '"');
                 return;
             }
         }
     } else {
         $this->setAuthSuccess($oUser);
         return;
     }
 }
Exemple #23
0
 /**
  * Send the forgot password email
  *
  * @param string $sEmailAddr
  * @param array $aFields
  */
 private function _sendPasswordEmail($sEmailAddr, $aFields)
 {
     $clang = $this->getController()->lang;
     $sFrom = Yii::app()->getConfig("siteadminname") . " <" . Yii::app()->getConfig("siteadminemail") . ">";
     $sTo = $sEmailAddr;
     $sSubject = $clang->gT('User data');
     $sNewPass = createPassword();
     $sSiteName = Yii::app()->getConfig('sitename');
     $sSiteAdminBounce = Yii::app()->getConfig('siteadminbounce');
     $username = sprintf($clang->gT('Username: %s'), $aFields[0]['users_name']);
     $email = sprintf($clang->gT('Email: %s'), $sEmailAddr);
     $password = sprintf($clang->gT('New password: %s'), $sNewPass);
     $body = array();
     $body[] = sprintf($clang->gT('Your user data for accessing %s'), Yii::app()->getConfig('sitename'));
     $body[] = $username;
     $body[] = $password;
     $body = implode("\n", $body);
     if (SendEmailMessage($body, $sSubject, $sTo, $sFrom, $sSiteName, false, $sSiteAdminBounce)) {
         User::model()->updatePassword($aFields[0]['uid'], $sNewPass);
         $sMessage = gT('If username and email that you specified are valid, a new password has been sent to you');
     } else {
         $sMessage = gT("Email failed.");
     }
     return $sMessage;
 }
Exemple #24
0
/**
 *
 * Return a random session id
 *
 */
function getSessionId()
{
    return md5(createPassword(5) . date("Y-m-d H:i:s"));
}
Exemple #25
0
include_once '../functions/magicutils.php';
include_once '../functions/ExifReader.class.php';
/*
 * This script returns json
 */
header("Pragma: no-cache");
header("Expires: 0");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Content-type: application/json; charset=utf-8");
/*
 * Success if $bool is true
 */
$bool = false;
$error = "Unknown problem with upload";
$random = createPassword(10);
/**
 * Upload allowed extension
 * Should be identical to mapshup client msp.Config["upload"].allowedExtensions
 */
$validExtensions = array("gml", "gpx", "kml", "xml", "rss", "jpeg", "jpg", "gif", "png", "shp", "shx", "dbf", "json");
/*
 * Process only valid requests
 *
 * This script accepts POST requests with multipart
 */
if (abcCheck($_REQUEST)) {
    /*
     * Set the error messages
     */
    $error_message[0] = "Error : Unknown problem with upload.";
Exemple #26
0
 * same conditions as regards security.
 *
 * The fact that you are presently reading this means that you have had
 * knowledge of the CeCILL-B license and that you accept its terms.
 */
include_once '../config.php';
include_once '../functions/general.php';
/*
 * Geonames rssToGeoRSS service
 */
$rssToGeoRSS = 'http://ws.geonames.net/rssToGeoRSS?username=jrom&feedUrl=';
/*
 * Process only valid requests
 */
if (abcCheck($_REQUEST)) {
    $fileName = MSP_UPLOAD_DIR . createPassword(8) . '.rss';
    /*
     * First get RSS stream
     */
    if (saveFile(getRemoteData($_REQUEST["url"], null, false), $fileName)) {
        /*
         * If input RSS is true GeoRSS, then it should contain
         * a xmlns:georss attribute with value = "http://www.georss.org/georss"
         *
         */
        $doc = new DOMDocument();
        $doc->load($fileName);
        if ($doc->documentElement->getAttribute("xmlns:georss") != "http://www.georss.org/georss") {
            unlink($fileName);
            saveFile(getRemoteData($rssToGeoRSS . rawurlencode($_REQUEST["url"]), null, false), $fileName);
        }
Exemple #27
0
 $addsummary = "<div class='header ui-widget-header'>" . $clang->gT("Add user") . "</div>\n";
 $new_user = FlattenText($postnew_user, true);
 $new_email = FlattenText($postnew_email, true);
 $new_full_name = FlattenText($postnew_full_name, true);
 $valid_email = true;
 if (!validate_email($new_email)) {
     $valid_email = false;
     $addsummary .= "<div class='messagebox ui-corner-all'><div class='warningheader'>" . $clang->gT("Failed to add user") . "</div><br />\n" . " " . $clang->gT("The email address is not valid.") . "<br />\n";
 }
 if (empty($new_user)) {
     if ($valid_email) {
         $addsummary .= "<br /><strong>" . $clang->gT("Failed to add user") . "</strong><br />\n" . " ";
     }
     $addsummary .= $clang->gT("A username was not supplied or the username is invalid.") . "<br />\n";
 } elseif ($valid_email) {
     $new_pass = createPassword();
     $uquery = "INSERT INTO {$dbprefix}users (users_name, password,full_name,parent_id,lang,email,create_survey,create_user,delete_user,superadmin,configurator,manage_template,manage_label)\n                   VALUES ('" . db_quote($new_user) . "', '" . SHA256::hashing($new_pass) . "', '" . db_quote($new_full_name) . "', {$_SESSION['loginID']}, 'auto', '" . db_quote($new_email) . "',0,0,0,0,0,0,0)";
     $uresult = $connect->Execute($uquery);
     //Checked
     if ($uresult) {
         $newqid = $connect->Insert_ID("{$dbprefix}users", "uid");
         // add default template to template rights for user
         $template_query = "INSERT INTO {$dbprefix}templates_rights VALUES('{$newqid}','default','1')";
         $connect->Execute($template_query);
         //Checked
         // add new user to userlist
         $squery = "SELECT uid, users_name, password, parent_id, email, create_survey, configurator, create_user, delete_user, superadmin, manage_template, manage_label FROM " . db_table_name('users') . " WHERE uid='{$newqid}'";
         //added by Dennis
         $sresult = db_execute_assoc($squery);
         //Checked
         $srow = $sresult->FetchRow();
Exemple #28
0
 function adduser()
 {
     if (!Yii::app()->session['USER_RIGHT_CREATE_USER']) {
         die(accessDenied('adduser'));
     }
     $clang = Yii::app()->lang;
     $new_user = flattenText(Yii::app()->request->getPost('new_user'), false, true);
     $new_email = flattenText(Yii::app()->request->getPost('new_email'), false, true);
     $new_full_name = flattenText(Yii::app()->request->getPost('new_full_name'), false, true);
     $aViewUrls = array();
     $valid_email = true;
     if (!validateEmailAddress($new_email)) {
         $valid_email = false;
         $aViewUrls['message'] = array('title' => $clang->gT("Failed to add user"), 'message' => $clang->gT("The email address is not valid."), 'class' => 'warningheader');
     }
     if (empty($new_user)) {
         $aViewUrls['message'] = array('title' => $clang->gT("Failed to add user"), 'message' => $clang->gT("A username was not supplied or the username is invalid."), 'class' => 'warningheader');
     } elseif (User::model()->find("users_name='{$new_user}'")) {
         $aViewUrls['message'] = array('title' => $clang->gT("Failed to add user"), 'message' => $clang->gT("The username already exists."), 'class' => 'warningheader');
     } elseif ($valid_email) {
         $new_pass = createPassword();
         $iNewUID = User::model()->insertUser($new_user, $new_pass, $new_full_name, Yii::app()->session['loginID'], $new_email);
         if ($iNewUID) {
             // add default template to template rights for user
             Templates_rights::model()->insertRecords(array('uid' => $iNewUID, 'folder' => 'default', 'use' => '1'));
             // add new user to userlist
             $sresult = User::model()->getAllRecords(array('uid' => $iNewUID));
             $srow = count($sresult);
             $userlist = getUserList();
             array_push($userlist, array("user" => $srow['users_name'], "uid" => $srow['uid'], "email" => $srow['email'], "password" => $srow["password"], "parent_id" => $srow['parent_id'], "create_survey" => $srow['create_survey'], "participant_panel" => $srow['participant_panel'], "configurator" => $srow['configurator'], "create_user" => $srow['create_user'], "delete_user" => $srow['delete_user'], "superadmin" => $srow['superadmin'], "manage_template" => $srow['manage_template'], "manage_label" => $srow['manage_label']));
             // send Mail
             $body = sprintf($clang->gT("Hello %s,"), $new_full_name) . "<br /><br />\n";
             $body .= sprintf($clang->gT("this is an automated email to notify that a user has been created for you on the site '%s'."), Yii::app()->getConfig("sitename")) . "<br /><br />\n";
             $body .= $clang->gT("You can use now the following credentials to log into the site:") . "<br />\n";
             $body .= $clang->gT("Username") . ": " . $new_user . "<br />\n";
             if (Yii::app()->getConfig("useWebserverAuth") === false) {
                 // authent is not delegated to web server
                 // send password (if authorized by config)
                 if (Yii::app()->getConfig("display_user_password_in_email") === true) {
                     $body .= $clang->gT("Password") . ": " . $new_pass . "<br />\n";
                 } else {
                     $body .= $clang->gT("Password") . ": " . $clang->gT("Please ask your password to your LimeSurvey administrator") . "<br />\n";
                 }
             }
             $body .= "<a href='" . $this->getController()->createAbsoluteUrl("/admin") . "'>" . $clang->gT("Click here to log in.") . "</a><br /><br />\n";
             $body .= sprintf($clang->gT('If you have any questions regarding this mail please do not hesitate to contact the site administrator at %s. Thank you!'), Yii::app()->getConfig("siteadminemail")) . "<br />\n";
             $subject = sprintf($clang->gT("User registration at '%s'", "unescaped"), Yii::app()->getConfig("sitename"));
             $to = $new_user . " <{$new_email}>";
             $from = Yii::app()->getConfig("siteadminname") . " <" . Yii::app()->getConfig("siteadminemail") . ">";
             $extra = '';
             $classMsg = '';
             if (SendEmailMessage($body, $subject, $to, $from, Yii::app()->getConfig("sitename"), true, Yii::app()->getConfig("siteadminbounce"))) {
                 $extra .= "<br />" . $clang->gT("Username") . ": {$new_user}<br />" . $clang->gT("Email") . ": {$new_email}<br />";
                 $extra .= "<br />" . $clang->gT("An email with a generated password was sent to the user.");
                 $classMsg = 'successheader';
                 $sHeader = $clang->gT("Success");
             } else {
                 // has to be sent again or no other way
                 $tmp = str_replace("{NAME}", "<strong>" . $new_user . "</strong>", $clang->gT("Email to {NAME} ({EMAIL}) failed."));
                 $extra .= "<br />" . str_replace("{EMAIL}", $new_email, $tmp) . "<br />";
                 $classMsg = 'warningheader';
                 $sHeader = $clang->gT("Warning");
             }
             $aViewUrls['mboxwithredirect'][] = $this->_messageBoxWithRedirect($clang->gT("Add user"), $sHeader, $classMsg, $extra, $this->getController()->createUrl("admin/user/setUserRights"), $clang->gT("Set user permissions"), array('action' => 'setUserRights', 'user' => $new_user, 'uid' => $iNewUID));
         } else {
             $aViewUrls['mboxwithredirect'][] = $this->_messageBoxWithRedirect($clang->gT("Failed to add user"), $clang->gT("The user name already exists."), 'warningheader');
         }
     }
     $this->_renderWrappedTemplate('user', $aViewUrls);
 }
     $errors[] = "Unable to request data from LDAP server.";
     $ldap_error = ldap_error($ad);
     $ldap_errno = ldap_errno($ad);
     @ldap_unbind($ad);
 } else {
     $le = @ldap_get_entries($ad, $ls);
     if (!$le) {
         $errors[] = "Unable to retrieve data from LDAP server.";
         $ldap_error = ldap_error($ad);
         $ldap_errno = ldap_errno($ad);
         @ldap_unbind($ad);
     } else {
         $dn = $le[0]["dn"];
         $displayName = $le[0]["displayname"][0];
         $email = $le[0]["mail"][0];
         $npw = createPassword();
         // Active Directory is more likely to support unicodePwd than than userPassword
         $npw_encoded = mb_convert_encoding('"' . $npw . '"', "UTF-16LE");
         $attributes = array("unicodePwd" => $npw_encoded);
         if (@ldap_mod_replace($ad, $dn, $attributes)) {
             $feedback .= "<p style='color:#090'>Password successfully reset for {$displayName}. New password:</p>";
             $feedback .= "<h3 style='color:#090'>{$npw}</h3>";
             if ($email) {
                 mail("{$displayName} <{$email}>", "Your account password was just reset", "Hi {$displayName},\n\nThe new password for your account is: {$npw}\n\nIt was reset by: {$un}\n\nThank you!", "From: " . LDAP_EMAIL_FROM);
             }
             $tun = "";
         } else {
             $errors[] = "Unable to reset password for {$displayName}. You may not be authorised for this operation.";
             $ldap_error = ldap_error($ad);
             $ldap_errno = ldap_errno($ad);
         }