function setupsecondary_main() { global $gbl, $sgbl, $login, $ghtml; global $argv; $dbf = $sgbl->__var_dbf; $prgm = $sgbl->__var_program_name; $list = parse_opt($argv); if (!isset($list['primary-master'])) { print "need --primary-master=\n"; exit; } if (!isset($list['sshport'])) { print "need --sshport=\n"; exit; } $master = $list['primary-master']; $sshport = $list['sshport']; print "Taking backup of the current database anyway...\n"; lxshell_php("../bin/common/mebackup.php"); $slavepass = randomString(7); print "Setting up mysql to receive data from master\n"; add_line_to_secondary_mycnf($master, $slavepass); $pass = slave_get_db_pass(); // TODO: REPLACE MYSQL_CONNECT $dblink = mysqli_connect("localhost", "root", $pass, $dbf); mysqli_query($dblink, "STOP SLAVE"); print "Getting initial data from the master\n"; system("ssh -p {$sshport} {$master} \"(cd /usr/local/lxlabs/{$prgm}/httpdocs ; lphp.exe ../bin/common/setupprimarymaster.php --slavepass={$slavepass})\" | mysql -u root -p{$pass} {$dbf}"); print "starting mysql data getting process\n"; mysqli_query($dblink, "CHANGE MASTER TO master_host='{$master}', master_password='******'"); mysqli_query($dblink, "START SLAVE"); lxfile_touch("../etc/secondary_master"); lxfile_touch("../etc/running_secondary"); }
protected function uploadFile($value) { $uploadPressed = http_request::getString('upload'); $fileExists = false; if ($value == "4d988458b51093c7ee3a4e1582b5fd9b" && $uploadPressed == 'Ladda upp') { $value = $imgStr = randomString(); file::tempName($imgStr); $fileExists = true; } $uploadState = file::append($this->name, $this->mimes, $this->max, $this->dir, $value); if ($uploadPressed !== false && $uploadPressed == 'Ladda upp' && $uploadState === false) { $this->error = 'Filuppladdningen misslyckades: för stor fil eller bild av ej tillåtet format.'; $this->value = sprintf('%s/%d.%s', $this->dir, 0, 'png'); return false; } $removePressed = http_request::getString('remove'); $doRemove = $removePressed !== false && in_array($removePressed, array('Ta bort Avatar', 'Ta bort Bild')); if ($uploadState !== false) { $bajs = fe($uploadState); $fileExists = true; $this->value = str_replace(ROOT . '/public/', '/', $uploadState); $this->uploaded = true; if (isset($_SESSION['fileTempName'])) { $_SESSION['fileTempName'] = basename($this->value); } foreach ($this->mimes as $fe) { $f = sprintf('%s/%s.%s', $this->dir, $value, $fe); if (file_exists($f) && $fe != $bajs) { file::remove($f); } } if ($doRemove === true) { file::remove($uploadState); } } else { foreach ($this->mimes as $fe) { $f = sprintf('%s/%s.%s', $this->dir, $value, $fe); if (file_exists($f)) { if ($doRemove === true) { file::remove($f); } $fileExists = true; $this->value = str_replace(ROOT . '/public/', '/', $f); if (isset($_SESSION['fileTempName'])) { $_SESSION['fileTempName'] = $this->value; } $this->uploaded = true; break; } } } if ($fileExists === false) { $this->value = sprintf('%s/%d.%s', $this->dir, 0, 'png'); } return $fileExists ? true : false; }
function runTask($task, $source) { $hash = randomString(); while (file_exists("sandbox/run_{$hash}/")) { $hash = randomString(); } $hash = 'run_' . $hash; $sandboxDir = "sandbox/{$hash}/"; mkdir($sandboxDir); $task_dir = "tasks/{$task}/"; $source_file = $sandboxDir . 'user.sql'; file_put_contents($source_file, $source); $output_file = $sandboxDir . 'output'; $error_file = $sandboxDir . 'error'; $diff_file = $sandboxDir . 'diff'; $db_init_file = $sandboxDir . 'db_init.sql'; $db_destroy_file = $sandboxDir . 'db_destroy.sql'; $answer_file = $task_dir . $task . '.ans'; $init_file = $task_dir . $task . '.sql'; $config = getTaskConfig(); foreach ($config as $pattern => $def) { $matched = @preg_match($pattern, $task); if ($matched) { if (array_key_exists('init', $def)) { $init_file = 'tasks/' . $def['init']; } } else { if ($matched === false) { abort('invalid regex pattern in task config: ' . $pattern); } } } $sql_admin = "mysql --user=task_runner --password=task_runner --local-infile=1"; $sql_jail = "mysql --user={$hash} --password={$hash}"; file_put_contents($db_init_file, join(";\n", array("create database {$hash}", "create user '{$hash}'@'localhost' identified by '{$hash}'", "grant all privileges on {$hash}.* to '{$hash}'@'localhost'", "flush privileges")) . ';'); exec("{$sql_admin} < {$db_init_file} 2> {$error_file}"); parseError($error_file, true); exec("{$sql_admin} {$hash} < {$init_file} 2> {$error_file}"); parseError($error_file, true); exec("{$sql_jail} {$hash} < {$source_file} > {$output_file} 2> {$error_file}"); exec("diff -q --strip-trailing-cr {$output_file} {$answer_file} > {$diff_file}"); $output = file_get_contents($output_file); $error = parseError($error_file, false); $diff = file_get_contents($diff_file); if (!empty($diff)) { exec("diff -y --strip-trailing-cr {$output_file} {$answer_file} > {$diff_file}"); $diff = file_get_contents($diff_file); } file_put_contents($db_destroy_file, join(";\n", array("revoke all privileges on {$hash}.* from '{$hash}'@'localhost'", "drop user '{$hash}'@'localhost'", "drop database {$hash}")) . ';'); exec("{$sql_admin} < {$db_destroy_file} 2> {$error_file}"); parseError($error_file, true); // Do not remove $sandboxDir if history is wanted. //exec("rm -r $sandboxDir"); $result = array('error' => $error, 'diff' => $diff, 'output' => $output); return $result; }
function apiKey() { $key = randomString(24); // Make sure it doesn't already exist $sql = "SELECT * \n\t\t\tFROM user \n\t\t\tWHERE apikey = '" . nice($key) . "'"; $results = mysql_query($sql); $row = mysql_fetch_assoc($results); if ($row) { return apiKey(); } else { return $key; } }
/** * login user, either by a temporary session or a stored cookie. * * @param int $id * @param bool[optional] $rememberMe * @return void */ public function login($id, $name, $groups, $rememberMe = false) { session_destroy(); $sessid = randomString(); session_id($sessid); session_start(); $_SESSION['online'] = TRUE; $_SESSION['ip'] = getIp(); $_SESSION['proxy'] = getProxy(); if ($rememberMe) { setcookie('userid', serialize(array($id, $name, $groups)), time() + 60 * 60 * 24 * 999, '/', '.madr.se', false, true); } $_SESSION['userid'] = serialize(array($id, $name, $groups)); }
/** * login user, either by a temporary session or a stored cookie. * * @param int $id * @param bool[optional] $rememberMe * @return void */ public function setOnline($id, $name, $groups, $rememberMe = false) { // if success: session_destroy(); $sessid = randomString(); session_id($sessid); session_start(); $_SESSION['online'] = TRUE; $_SESSION['ip'] = getIp(); $_SESSION['proxy'] = getProxy(); if ($rememberMe) { setcookie('userid', serialize(array($id, $name, $groups)), time() + 60 * 60 * 24 * 999, '/', COOKIE_DOMAIN, false, true); } $_SESSION['userid'] = serialize(array($id, $name, $groups)); $this->groups = $groups; }
function dbactionAdd() { global $gbl, $sgbl, $login, $ghtml; $dir = $this->main->__var_full_directory; $dir = expand_real_root($dir); $pass = $this->main->realpass; if (!$pass) { $pass = randomString(8); } lxshell_input("{$pass}\n{$pass}\n", "pure-pw", "useradd", $this->main->nname, "-u", $this->main->__var_username, "-d", $dir, "-m"); if (!lxfile_exists($dir)) { lxfile_mkdir($dir); lxfile_unix_chown($dir, $this->main->__var_username); } $this->setQuota(); // If the user is added is fully formed, this makes sure that all his properties are synced. $this->toggleStatus(); }
function create_mysql_db($type, $opt, $admin_pass) { global $gbl, $sgbl, $login, $ghtml; $progname = $sgbl->__var_program_name; $db = $sgbl->__var_dbf; if (!isset($opt['db-rootuser']) || !isset($opt['db-rootpassword'])) { print "Need db Root User and password --db-rootuser, --db-rootpassword \n"; exit; } if ($sgbl->__var_database_type === 'mysql') { // TODO: REPLACE MYSQL_CONNECT // TUT TUT naughty programmer... We are creating the db now XD $req = mysqli_connect('localhost', $opt['db-rootuser'], $opt['db-rootpassword']); } else { if ($sgbl->__var_database_type === 'mssql') { $req = mssql_connect("localhost,{$sgbl->__var_mssqlport}"); } else { $req = new PDO("sqlite:{$db}"); } } if (!$req) { print "Could not Connect to Database on localhost using root user: "******"\n"; } //$sqlcm = lfile_get_contents("__path_program_root/httpdocs/sql/init/$type.sql"); $dp = randomString(9); $dbadminpass = client::createDbPass($dp); $dbname = $sgbl->__var_dbf; $pguser = $sgbl->__var_admin_user; if ($sgbl->__var_database_type === 'mysql') { @mysqli_query($req, "CREATE DATABASE {$dbname}"); mysqli_query($req, "GRANT ALL ON {$dbname}.* TO '{$pguser}'@'localhost' IDENTIFIED BY '{$dbadminpass}';"); } else { if ($sgbl->__var_database_type === 'mssql') { mssql_query("create database {$dbname};"); mssql_query("use master "); mssql_query("sp_addlogin '{$pguser}', '{$dbadminpass}', '{$dbname}';"); mssql_query("use {$dbname} "); mssql_query("grant all to {$pguser}"); } else { } } lfile_put_contents("__path_admin_pass", $dbadminpass); lxfile_generic_chown("__path_admin_pass", "lxlabs"); }
/** * * * @param $SourcePath * @param $DestPath * @return mixed * @throws Exception */ public function copyDefinitions($SourcePath, $DestPath) { // Load the definitions from the source path. $Definitions = $this->loadDefinitions($SourcePath); $TmpPath = dirname($DestPath) . '/tmp_' . randomString(10); $Key = trim(strchr($SourcePath, '/'), '/'); $fp = fopen($TmpPath, 'wb'); if (!$fp) { throw new Exception(sprintf(t('Could not open %s.'), $TmpPath)); } fwrite($fp, $this->getFileHeader()); fwrite($fp, "/** Definitions copied from {$Key}. **/\n\n"); $this->writeDefinitions($fp, $Definitions); fclose($fp); $Result = rename($TmpPath, $DestPath); if (!$Result) { throw new Exception(sprintf(t('Could not open %s.'), $DestPath)); } return $DestPath; }
function create_mysql_db($type, $opt, $admin_pass) { global $gbl, $sgbl, $login, $ghtml; $progname = $sgbl->__var_program_name; if (!isset($opt['db-rootuser']) || !isset($opt['db-rootpassword'])) { print "Need db Root User and password --db-rootuser, --db-rootpassword \n"; exit; } if ($sgbl->__var_database_type === 'mysql') { $req = mysql_connect('localhost', $opt['db-rootuser'], $opt['db-rootpassword']); } else { if ($sgbl->__var_database_type === 'mssql') { $req = mssql_connect("localhost,{$sgbl->__var_mssqlport}"); } else { $req = new PDO("sqlite:{$sgbl->__var_dbf}"); } } if (!$req) { print "Could not Connect to Database on localhost using root user\n"; } //$sqlcm = lfile_get_contents("__path_program_root/httpdocs/sql/init/$type.sql"); $dp = randomString(9); $dbadminpass = client::createDbPass($dp); $dbname = $sgbl->__var_dbf; $pguser = $sgbl->__var_admin_user; if ($sgbl->__var_database_type === 'mysql') { @mysql_query("create database {$dbname}"); mysql_query("grant all on {$dbname}.* to '{$pguser}'@'localhost' identified by '{$dbadminpass}';"); } else { if ($sgbl->__var_database_type === 'mssql') { mssql_query("create database {$dbname};"); mssql_query("use master "); mssql_query("sp_addlogin '{$pguser}', '{$dbadminpass}', '{$dbname}';"); mssql_query("use {$dbname} "); mssql_query("grant all to {$pguser}"); } else { } } lfile_put_contents("__path_admin_pass", $dbadminpass); lxfile_generic_chown("__path_admin_pass", "lxlabs"); }
public function actionIndex() { if (!user()->isGuest) { // Если авторизирован $this->redirect(array('/cabinet/default/index')); } $model = new ForgottenPasswordForm(); if (isset($_POST['ForgottenPasswordForm'])) { $model->attributes = $_POST['ForgottenPasswordForm']; if ($model->validate()) { $cache = new CFileCache(); $cache->init(); $cacheData = array('hash' => md5(randomString(rand(10, 30)) . userIp() . time()), 'login' => $model->login, 'ls_id' => $model->gs_list[$model->gs_id]['login_id'], 'email' => $model->email); $cache->set($this->_cacheName . $cacheData['hash'], $cacheData, (int) config('forgotten_password.cache_time') * 60); notify()->forgottenPasswordStep1($model->email, array('hash' => $cacheData['hash'])); user()->setFlash(FlashConst::MESSAGE_SUCCESS, Yii::t('main', 'На Email <b>:email</b> отправлены инструкции по восстановлению пароля.', array(':email' => $model->email))); $this->refresh(); } } $this->render('//forgotten-password', array('model' => $model)); }
public function reset_password() { if (!$this->id == 0) { $newpass = randomString(10); $encedpass = md5($newpass); $userdata = array(); $userdata['id'] = $this->id; $userdata['password'] = $encedpass; $this->password = $encedpass; $db = Database::obtain(); $this->id = $db->insert("users", $userdata); $subject = translate('Your new password for', $this->language) . ' ' . sz_config('name'); $message = translate('Below is the new password for your user account on', $this->language) . ' ' . sz_config('name') . "\r\n" . translate('You can access your account on', $this->language) . ' ' . sz_config('url') . "\r\n" . translate('Your new password is', $this->language) . ': ' . $this->password; $headers = 'From: ' . sz_config('email') . "\r\n" . 'Bcc: ' . sz_config('cron_email') . "\r\n"; if (send_email($email_address, $subject, $message, $headers)) { return true; } else { return false; } } else { return false; } }
static function imageVerify($length = 4, $mode = 1, $width = 48, $height = 22, $verifyName = 'verify') { $verifyName = C('SESSION_PRE') . $verifyName; $randval = randomString($length, $mode); session($verifyName, md5($randval)); $width = $length * 10 + 10 > $width ? $length * 10 + 10 : $width; $im = @imagecreatetruecolor($width, $height); $r = array(225, 255, 255, 223); $g = array(225, 236, 237, 255); $b = array(225, 236, 166, 125); $key = mt_rand(0, 3); //随机背景色 $backColor = imagecolorallocate($im, $r[$key], $g[$key], $b[$key]); //边框色 $borderColor = imagecolorallocate($im, 100, 100, 100); //点颜色 $pointColor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); @imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor); @imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor); $stringColor = imagecolorallocate($im, mt_rand(0, 200), mt_rand(0, 120), mt_rand(0, 120)); //干扰 for ($i = 0; $i < 10; $i++) { $fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $fontcolor); } for ($i = 0; $i < 25; $i++) { $fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $pointColor); } for ($i = 0; $i < $length; $i++) { imagestring($im, 5, $i * 10 + 5, mt_rand(1, 8), $randval[$i], $stringColor); } header('Content-type: image/png'); imagepng($im); imagedestroy($im); exit; }
function add($data) { if (is_array($data)) { if (array_key_exists('u_username', $data)) { if ($this->user->_checkUsername($data['u_username'], $data['u_email'], true, false)) { include_once PATH_CLASS . '/CIdat.php'; // need for Idat include_once PATH_INCLUDE . '/functions.php'; // need for randomString() $idat =& CIdat::getInstance(); $_randId = $idat->nextID('fotoflix.user_id'); $data['u_key'] = substr($_randId . randomString(), 0, 32); $status = $data['u_status']; //$data['u_password'] = md5($data['u_password']); $data = $this->dbh->asql_safe($data); $keys = array_keys($data); $sql = 'INSERT INTO users(' . implode(', ', $keys) . ', u_dateCreated, u_dateModified) ' . 'VALUES(' . implode(', ', $data) . ', NOW(), NOW())'; $this->dbh->execute($sql); $return = $this->dbh->insert_id(); $sql = 'DELETE FROM user_incompletes WHERE u_key = ' . $data['u_key'] . ' '; $this->dbh->execute($sql); if ($status == 'Pending') { $key = $this->dbh->sql_safe(md5(uniqid(rand(), true))); $this->dbh->execute($sql = 'INSERT INTO user_activation(ua_u_id, ua_key) VALUES(' . $return . ', ' . $key . ')'); } return $return; } else { array_push($this->error, 'Username / Email (' . $data['u_username'] . ' / ' . $data['u_email'] . ') contained invalid characters.'); } } else { array_push($this->error, 'No username was specified.'); } } else { array_push($this->error, 'Malformed data sent to update user.'); return false; } }
if (is_dir($tempDirectory)) { recursiveRemoveDirectory($tempDirectory); } $logger->log(sprintf('Making temporary directory %s.', $tempDirectory), Logger::INFO); mkdir($tempDirectory); // ----------------------------------------------------------------------------- // Generate temporary documents $tempFilenames = array(); $mailMerge = new MailMerge(); $mailMerge->setUsername(DEMOS_ZEND_SERVICE_LIVEDOCX_USERNAME)->setPassword(DEMOS_ZEND_SERVICE_LIVEDOCX_PASSWORD); $mailMerge->setLocalTemplate('template.docx'); $date = new DateTime(); for ($iteration = 1; $iteration <= $iterations; $iteration++) { $tempFilename = sprintf('%s%s%010s.pdf', $tempDirectory, DIRECTORY_SEPARATOR, $iteration); $tempFilenames[] = $tempFilename; $mailMerge->assign('software', randomString())->assign('licensee', randomString())->assign('company', randomString())->assign('date', $date->format('Y-m-d'))->assign('time', $date->format('H:i:s'))->assign('city', randomString())->assign('country', randomString()); $mailMerge->createDocument(); file_put_contents($tempFilename, $mailMerge->retrieveDocument('pdf')); $logger->log(sprintf('Generating temporary document %s.', $tempFilename), Logger::INFO); } unset($mailMerge); // ----------------------------------------------------------------------------- // Concatenate temporary documents and write output document $outputFilename = __DIR__ . DIRECTORY_SEPARATOR . 'document-concat.pdf'; $logger->log('Concatenating temporary documents...', Logger::INFO); if (true === concatenatePdfFilenames($tempFilenames, $outputFilename, $processor)) { $logger->log(sprintf('...DONE. Saved output document as %s.', basename($outputFilename)), Logger::INFO); } else { $logger->log(sprintf('...ERROR.'), Logger::ERR); } // -----------------------------------------------------------------------------
} //Make sure the user exists $user = $db->select("SELECT id FROM " . $DATABASE . ".users \n\t\t WHERE email = " . $db->quote($_POST["email"]) . " \n\t\t AND password_reset = " . $db->quote($_POST["reset"])); if (empty($user)) { error("Unknown User", "We were unable to find or complete your password reset request"); } //at this point we can change the password. A user is verified. $pass = password_hash($_POST["pass"], PASSWORD_BCRYPT); $db->query("UPDATE " . $DATABASE . ".users \n\t\t SET activation = '1',\n\t\t password_reset = NULL,\n\t\t password = "******" \n\t\t WHERE email = " . $db->quote($_POST["email"])); resetCompletePage(); //user has submitted an email to change their password } else { if (!empty($_POST["email"])) { $email = $db->select("SELECT users.email \n\t\t FROM " . $DATABASE . ".users \n\t\t WHERE email = " . $db->quote($_POST["email"])); if (!empty($email)) { $pass = randomString(40); $db->query("UPDATE " . $DATABASE . ".users \n\t\t\t SET password_reset = " . $db->quote($pass) . " WHERE email = " . $db->quote($email[0]["email"])); sendEmail($email, $pass); } showVerify($_POST["email"]); } else { page(); } } } //The regular page, displays the button to reset a password function page() { head(); ?>
/** * Генерация бонус кода */ public function actionGenerateCode($parts = 4, $length = 4, $divider = '-') { $code = ''; for ($i = 0; $i < $parts; $i++) { $code .= strtoupper(randomString($length)) . $divider; } echo substr($code, 0, -1); }
/** * Generic save procedure. * * $Settings controls certain save functionality * * SaveRoles - Save 'RoleID' field as user's roles. Default false. * HashPassword - Hash the provided password on update. Default true. * FixUnique - Try to resolve conflicts with unique constraints on Name and Email. Default false. * ValidateEmail - Make sure the provided email addresses is formattted properly. Default true. * NoConfirmEmail - Disable email confirmation. Default false. * */ public function save($FormPostValues, $Settings = false) { // See if the user's related roles should be saved or not. $SaveRoles = val('SaveRoles', $Settings); // Define the primary key in this model's table. $this->defineSchema(); // Custom Rule: This will make sure that at least one role was selected if saving roles for this user. if ($SaveRoles) { $this->Validation->addRule('OneOrMoreArrayItemRequired', 'function:ValidateOneOrMoreArrayItemRequired'); // $this->Validation->AddValidationField('RoleID', $FormPostValues); $this->Validation->applyRule('RoleID', 'OneOrMoreArrayItemRequired'); } else { $this->Validation->unapplyRule('RoleID', 'OneOrMoreArrayItemRequired'); } // Make sure that checkbox vals are saved as the appropriate value if (array_key_exists('ShowEmail', $FormPostValues)) { $FormPostValues['ShowEmail'] = forceBool($FormPostValues['ShowEmail'], '0', '1', '0'); } if (array_key_exists('Banned', $FormPostValues)) { $FormPostValues['Banned'] = forceBool($FormPostValues['Banned'], '0', '1', '0'); } if (array_key_exists('Confirmed', $FormPostValues)) { $FormPostValues['Confirmed'] = forceBool($FormPostValues['Confirmed'], '0', '1', '0'); } if (array_key_exists('Verified', $FormPostValues)) { $FormPostValues['Verified'] = forceBool($FormPostValues['Verified'], '0', '1', '0'); } unset($FormPostValues['Admin']); // Validate the form posted values if (array_key_exists('Gender', $FormPostValues)) { $FormPostValues['Gender'] = self::fixGender($FormPostValues['Gender']); } if (array_key_exists('DateOfBirth', $FormPostValues) && $FormPostValues['DateOfBirth'] == '0-00-00') { $FormPostValues['DateOfBirth'] = null; } $UserID = val('UserID', $FormPostValues); $User = array(); $Insert = $UserID > 0 ? false : true; if ($Insert) { $this->addInsertFields($FormPostValues); } else { $this->addUpdateFields($FormPostValues); $User = $this->getID($UserID, DATASET_TYPE_ARRAY); if (!$User) { $User = array(); } // Block banning the superadmin or System accounts if (val('Admin', $User) == 2 && val('Banned', $FormPostValues)) { $this->Validation->addValidationResult('Banned', 'You may not ban a System user.'); } elseif (val('Admin', $User) && val('Banned', $FormPostValues)) { $this->Validation->addValidationResult('Banned', 'You may not ban a user with the Admin flag set.'); } } $this->EventArguments['FormPostValues'] = $FormPostValues; $this->fireEvent('BeforeSaveValidation'); $RecordRoleChange = true; if ($UserID && val('FixUnique', $Settings)) { $UniqueValid = $this->validateUniqueFields(val('Name', $FormPostValues), val('Email', $FormPostValues), $UserID, true); if (!$UniqueValid['Name']) { unset($FormPostValues['Name']); } if (!$UniqueValid['Email']) { unset($FormPostValues['Email']); } $UniqueValid = true; } else { $UniqueValid = $this->validateUniqueFields(val('Name', $FormPostValues), val('Email', $FormPostValues), $UserID); } // Add & apply any extra validation rules: if (array_key_exists('Email', $FormPostValues) && val('ValidateEmail', $Settings, true)) { $this->Validation->applyRule('Email', 'Email'); } // AllIPAdresses is stored as a CSV, so handle the case where an array is submitted. if (array_key_exists('AllIPAddresses', $FormPostValues) && is_array($FormPostValues['AllIPAddresses'])) { $FormPostValues['AllIPAddresses'] = implode(',', $FormPostValues['AllIPAddresses']); } if ($this->validate($FormPostValues, $Insert) && $UniqueValid) { // All fields on the form that need to be validated (including non-schema field rules defined above) $Fields = $this->Validation->validationFields(); $RoleIDs = val('RoleID', $Fields, 0); $Username = val('Name', $Fields); $Email = val('Email', $Fields); // Only fields that are present in the schema $Fields = $this->Validation->schemaValidationFields(); // Remove the primary key from the fields collection before saving $Fields = removeKeyFromArray($Fields, $this->PrimaryKey); if (!$Insert && array_key_exists('Password', $Fields) && val('HashPassword', $Settings, true)) { // Encrypt the password for saving only if it won't be hashed in _Insert() $PasswordHash = new Gdn_PasswordHash(); $Fields['Password'] = $PasswordHash->hashPassword($Fields['Password']); $Fields['HashMethod'] = 'Vanilla'; } // Check for email confirmation. if (self::requireConfirmEmail() && !val('NoConfirmEmail', $Settings)) { // Email address has changed if (isset($Fields['Email']) && (array_key_exists('Confirmed', $Fields) && $Fields['Confirmed'] == 0 || $UserID == Gdn::session()->UserID && $Fields['Email'] != Gdn::session()->User->Email && !Gdn::session()->checkPermission('Garden.Users.Edit'))) { $Attributes = val('Attributes', Gdn::session()->User); if (is_string($Attributes)) { $Attributes = @unserialize($Attributes); } $ConfirmEmailRoleID = RoleModel::getDefaultRoles(RoleModel::TYPE_UNCONFIRMED); if (!empty($ConfirmEmailRoleID)) { // The confirm email role is set and it exists so go ahead with the email confirmation. $NewKey = randomString(8); $EmailKey = touchValue('EmailKey', $Attributes, $NewKey); $Fields['Attributes'] = serialize($Attributes); $Fields['Confirmed'] = 0; } } } $this->EventArguments['SaveRoles'] =& $SaveRoles; $this->EventArguments['RoleIDs'] =& $RoleIDs; $this->EventArguments['Fields'] =& $Fields; $this->fireEvent('BeforeSave'); $User = array_merge($User, $Fields); // Check the validation results again in case something was added during the BeforeSave event. if (count($this->Validation->results()) == 0) { // If the primary key exists in the validated fields and it is a // numeric value greater than zero, update the related database row. if ($UserID > 0) { // If they are changing the username & email, make sure they aren't // already being used (by someone other than this user) if (val('Name', $Fields, '') != '' || val('Email', $Fields, '') != '') { if (!$this->validateUniqueFields($Username, $Email, $UserID)) { return false; } } if (array_key_exists('Attributes', $Fields) && !is_string($Fields['Attributes'])) { $Fields['Attributes'] = serialize($Fields['Attributes']); } // Perform save DB operation $this->SQL->put($this->Name, $Fields, array($this->PrimaryKey => $UserID)); // Record activity if the person changed his/her photo. $Photo = val('Photo', $FormPostValues); if ($Photo !== false) { if (val('CheckExisting', $Settings)) { $User = $this->getID($UserID); $OldPhoto = val('Photo', $User); } if (isset($OldPhoto) && $OldPhoto != $Photo) { if (IsUrl($Photo)) { $PhotoUrl = $Photo; } else { $PhotoUrl = Gdn_Upload::url(changeBasename($Photo, 'n%s')); } $ActivityModel = new ActivityModel(); if ($UserID == Gdn::session()->UserID) { $HeadlineFormat = t('HeadlineFormat.PictureChange', '{RegardingUserID,You} changed {ActivityUserID,your} profile picture.'); } else { $HeadlineFormat = t('HeadlineFormat.PictureChange.ForUser', '{RegardingUserID,You} changed the profile picture for {ActivityUserID,user}.'); } $ActivityModel->save(array('ActivityUserID' => $UserID, 'RegardingUserID' => Gdn::session()->UserID, 'ActivityType' => 'PictureChange', 'HeadlineFormat' => $HeadlineFormat, 'Story' => img($PhotoUrl, array('alt' => t('Thumbnail'))))); } } } else { $RecordRoleChange = false; if (!$this->validateUniqueFields($Username, $Email)) { return false; } // Define the other required fields: $Fields['Email'] = $Email; $Fields['Roles'] = $RoleIDs; // Make sure that the user is assigned to one or more roles: $SaveRoles = false; // And insert the new user. $UserID = $this->_insert($Fields, $Settings); if ($UserID) { // Report that the user was created. $ActivityModel = new ActivityModel(); $ActivityModel->save(array('ActivityType' => 'Registration', 'ActivityUserID' => $UserID, 'HeadlineFormat' => t('HeadlineFormat.Registration', '{ActivityUserID,You} joined.'), 'Story' => t('Welcome Aboard!')), false, array('GroupBy' => 'ActivityTypeID')); // Report the creation for mods. $ActivityModel->save(array('ActivityType' => 'Registration', 'ActivityUserID' => Gdn::session()->UserID, 'RegardingUserID' => $UserID, 'NotifyUserID' => ActivityModel::NOTIFY_MODS, 'HeadlineFormat' => t('HeadlineFormat.AddUser', '{ActivityUserID,user} added an account for {RegardingUserID,user}.'))); } } // Now update the role settings if necessary. if ($SaveRoles) { // If no RoleIDs were provided, use the system defaults if (!is_array($RoleIDs)) { $RoleIDs = RoleModel::getDefaultRoles(RoleModel::TYPE_MEMBER); } $this->saveRoles($UserID, $RoleIDs, $RecordRoleChange); } // Send the confirmation email. if (isset($EmailKey)) { if (!is_array($User)) { $User = $this->getID($UserID, DATASET_TYPE_ARRAY); } $this->sendEmailConfirmationEmail($User, true); } $this->EventArguments['UserID'] = $UserID; $this->fireEvent('AfterSave'); } else { $UserID = false; } } else { $UserID = false; } // Clear cached user data if (!$Insert && $UserID) { $this->clearCache($UserID, array('user')); } return $UserID; }
/** * Synchronizes the user based on a given UserKey. * * @param string $UserKey A string that uniquely identifies this user. * @param array $Data Information to put in the user table. * @return int The ID of the user. */ public function synchronize($UserKey, $Data) { $UserID = 0; $Attributes = val('Attributes', $Data); if (is_string($Attributes)) { $Attributes = dbdecode($Attributes); } if (!is_array($Attributes)) { $Attributes = []; } // If the user didnt log in, they won't have a UserID yet. That means they want a new // account. So create one for them. if (!isset($Data['UserID']) || $Data['UserID'] <= 0) { // Prepare the user data. $UserData = []; $UserData['Name'] = $Data['Name']; $UserData['Password'] = randomString(16); $UserData['Email'] = val('Email', $Data, '*****@*****.**'); $UserData['Gender'] = strtolower(substr(val('Gender', $Data, 'u'), 0, 1)); $UserData['HourOffset'] = val('HourOffset', $Data, 0); $UserData['DateOfBirth'] = val('DateOfBirth', $Data, ''); $UserData['CountNotifications'] = 0; $UserData['Attributes'] = $Attributes; $UserData['InsertIPAddress'] = ipEncode(Gdn::request()->ipAddress()); if ($UserData['DateOfBirth'] == '') { $UserData['DateOfBirth'] = '1975-09-16'; } // Make sure there isn't another user with this username. if ($this->validateUniqueFields($UserData['Name'], $UserData['Email'])) { if (!BanModel::checkUser($UserData, $this->Validation, true)) { throw permissionException('Banned'); } // Insert the new user. $this->addInsertFields($UserData); $UserID = $this->insertInternal($UserData); } if ($UserID > 0) { $NewUserRoleIDs = $this->newUserRoleIDs(); // Save the roles. $Roles = val('Roles', $Data, false); if (empty($Roles)) { $Roles = $NewUserRoleIDs; } $this->saveRoles($UserID, $Roles, false); } } else { $UserID = $Data['UserID']; } // Synchronize the transientkey from the external user data source if it is present (eg. WordPress' wpnonce). if (array_key_exists('TransientKey', $Attributes) && $Attributes['TransientKey'] != '' && $UserID > 0) { $this->setTransientKey($UserID, $Attributes['TransientKey']); } return $UserID; }
/** * Request password * * @param string $username * @param string $email * @return bool */ public function passwordRequest($username, $email) { if (!empty($username) && !empty($email) && filter_var($email, FILTER_VALIDATE_EMAIL)) { if (($check = $GLOBALS['db']->select('CubeCart_admin_users', array('admin_id', 'email', 'language', 'name'), array('username' => $username, 'email' => $email, 'status' => '1'))) !== false) { // Generate validation key $validation = randomString($this->_validate_key_len); if ($GLOBALS['db']->update('CubeCart_admin_users', array('verify' => $validation), array('admin_id' => (int) $check[0]['admin_id']))) { // Send email $mailer = Mailer::getInstance(); $data['link'] = $GLOBALS['storeURL'] . '/' . $GLOBALS['config']->get('config', 'adminFile') . '?_g=recovery&email=' . $check[0]['email'] . '&validate=' . $validation; $data['name'] = $check[0]['name']; $content = $mailer->loadContent('admin.password_recovery', $check[0]['language'], $data); if ($content) { $GLOBALS['smarty']->assign('DATA', $data); $GLOBALS['session']->set('recover_login', true); return $mailer->sendEmail($check[0]['email'], $content); } } } } return false; }
$nta = explode("\n", str_replace("\r\n", "\n", $b)); $diffs = new Diff($ota, $nta); $formatter = new TableDiffFormatter(); $funky = $formatter->format($diffs); preg_match_all('/<span class="diffchange">(.*?)<\\/span>/', $funky, $matches); foreach ($matches[1] as $bit) { $hex = bin2hex($bit); echo "\t{$hex}\n"; } } $size = 16; $n = 0; while (true) { $n++; echo "{$n}\n"; $str = randomString($size, true); $clean = UtfNormal::cleanUp($str); $norm = donorm($str); echo strlen($clean) . ", " . strlen($norm); if ($clean == $norm) { echo " (match)\n"; } else { echo " (FAIL)\n"; echo "\traw: " . bin2hex($str) . "\n" . "\tphp: " . bin2hex($clean) . "\n" . "\ticu: " . bin2hex($norm) . "\n"; echo "\n\tdiffs:\n"; showDiffs($clean, $norm); die; } $str = ''; $clean = ''; $norm = '';
/** * Connect the user with an external source. * * This controller method is meant to be used with plugins that set its data array to work. * Events: ConnectData * * @since 2.0.0 * @access public * * @param string $Method Used to register multiple providers on ConnectData event. */ public function connect($Method) { $this->addJsFile('entry.js'); $this->View = 'connect'; $IsPostBack = $this->Form->isPostBack() && $this->Form->getFormValue('Connect', null) !== null; $UserSelect = $this->Form->getFormValue('UserSelect'); if (!$IsPostBack) { // Here are the initial data array values. that can be set by a plugin. $Data = array('Provider' => '', 'ProviderName' => '', 'UniqueID' => '', 'FullName' => '', 'Name' => '', 'Email' => '', 'Photo' => '', 'Target' => $this->target()); $this->Form->setData($Data); $this->Form->addHidden('Target', $this->Request->get('Target', '/')); } // The different providers can check to see if they are being used and modify the data array accordingly. $this->EventArguments = array($Method); // Fire ConnectData event & error handling. $currentData = $this->Form->formValues(); // Filter the form data for users here. SSO plugins must reset validated data each postback. $filteredData = Gdn::userModel()->filterForm($currentData, true); $filteredData = array_replace($filteredData, arrayTranslate($currentData, ['TransientKey', 'hpt'])); unset($filteredData['Roles'], $filteredData['RoleID']); $this->Form->formValues($filteredData); try { $this->EventArguments['Form'] = $this->Form; $this->fireEvent('ConnectData'); $this->fireEvent('AfterConnectData'); } catch (Gdn_UserException $Ex) { $this->Form->addError($Ex); return $this->render('ConnectError'); } catch (Exception $Ex) { if (Debug()) { $this->Form->addError($Ex); } else { $this->Form->addError('There was an error fetching the connection data.'); } return $this->render('ConnectError'); } if (!UserModel::noEmail()) { if (!$this->Form->getFormValue('Email') || $this->Form->getFormValue('EmailVisible')) { $this->Form->setFormValue('EmailVisible', true); $this->Form->addHidden('EmailVisible', true); if ($IsPostBack) { $this->Form->setFormValue('Email', val('Email', $currentData)); } } } $FormData = $this->Form->formValues(); // debug // Make sure the minimum required data has been provided to the connect. if (!$this->Form->getFormValue('Provider')) { $this->Form->addError('ValidateRequired', t('Provider')); } if (!$this->Form->getFormValue('UniqueID')) { $this->Form->addError('ValidateRequired', t('UniqueID')); } if (!$this->data('Verified')) { // Whatever event handler catches this must Set the data 'Verified' to true to prevent a random site from connecting without credentials. // This must be done EVERY postback and is VERY important. $this->Form->addError('The connection data has not been verified.'); } if ($this->Form->errorCount() > 0) { return $this->render(); } $UserModel = Gdn::userModel(); // Check to see if there is an existing user associated with the information above. $Auth = $UserModel->getAuthentication($this->Form->getFormValue('UniqueID'), $this->Form->getFormValue('Provider')); $UserID = val('UserID', $Auth); // Check to synchronise roles upon connecting. if (($this->data('Trusted') || c('Garden.SSO.SyncRoles')) && $this->Form->getFormValue('Roles', null) !== null) { $SaveRoles = $SaveRolesRegister = true; // Translate the role names to IDs. $Roles = $this->Form->getFormValue('Roles', null); $Roles = RoleModel::getByName($Roles); $RoleIDs = array_keys($Roles); if (empty($RoleIDs)) { // The user must have at least one role. This protects that. $RoleIDs = $this->UserModel->newUserRoleIDs(); } if (c('Garden.SSO.SyncRolesBehavior') === 'register') { $SaveRoles = false; } $this->Form->setFormValue('RoleID', $RoleIDs); } else { $SaveRoles = false; $SaveRolesRegister = false; } if ($UserID) { // The user is already connected. $this->Form->setFormValue('UserID', $UserID); if (c('Garden.Registration.ConnectSynchronize', true)) { $User = Gdn::userModel()->getID($UserID, DATASET_TYPE_ARRAY); $Data = $this->Form->formValues(); // Don't overwrite the user photo if the user uploaded a new one. $Photo = val('Photo', $User); if (!val('Photo', $Data) || $Photo && !isUrl($Photo)) { unset($Data['Photo']); } // Synchronize the user's data. $UserModel->save($Data, array('NoConfirmEmail' => true, 'FixUnique' => true, 'SaveRoles' => $SaveRoles)); } // Always save the attributes because they may contain authorization information. if ($Attributes = $this->Form->getFormValue('Attributes')) { $UserModel->saveAttribute($UserID, $Attributes); } // Sign the user in. Gdn::session()->start($UserID, true, (bool) $this->Form->getFormValue('RememberMe', true)); Gdn::userModel()->fireEvent('AfterSignIn'); // $this->_setRedirect(TRUE); $this->_setRedirect($this->Request->get('display') == 'popup'); } elseif ($this->Form->getFormValue('Name') || $this->Form->getFormValue('Email')) { $NameUnique = c('Garden.Registration.NameUnique', true); $EmailUnique = c('Garden.Registration.EmailUnique', true); $AutoConnect = c('Garden.Registration.AutoConnect'); if ($IsPostBack && $this->Form->getFormValue('ConnectName')) { $searchName = $this->Form->getFormValue('ConnectName'); } else { $searchName = $this->Form->getFormValue('Name'); } // Get the existing users that match the name or email of the connection. $Search = false; if ($searchName && $NameUnique) { $UserModel->SQL->orWhere('Name', $searchName); $Search = true; } if ($this->Form->getFormValue('Email') && ($EmailUnique || $AutoConnect)) { $UserModel->SQL->orWhere('Email', $this->Form->getFormValue('Email')); $Search = true; } if (is_numeric($UserSelect)) { $UserModel->SQL->orWhere('UserID', $UserSelect); $Search = true; } if ($Search) { $ExistingUsers = $UserModel->getWhere()->resultArray(); } else { $ExistingUsers = array(); } // Check to automatically link the user. if ($AutoConnect && count($ExistingUsers) > 0) { if ($IsPostBack && $this->Form->getFormValue('ConnectName')) { $this->Form->setFormValue('Name', $this->Form->getFormValue('ConnectName')); } foreach ($ExistingUsers as $Row) { if (strcasecmp($this->Form->getFormValue('Email'), $Row['Email']) === 0) { $UserID = $Row['UserID']; $this->Form->setFormValue('UserID', $UserID); $Data = $this->Form->formValues(); if (c('Garden.Registration.ConnectSynchronize', true)) { // Don't overwrite a photo if the user has already uploaded one. $Photo = val('Photo', $Row); if (!val('Photo', $Data) || $Photo && !stringBeginsWith($Photo, 'http')) { unset($Data['Photo']); } $UserModel->save($Data, array('NoConfirmEmail' => true, 'FixUnique' => true, 'SaveRoles' => $SaveRoles)); } if ($Attributes = $this->Form->getFormValue('Attributes')) { $UserModel->saveAttribute($UserID, $Attributes); } // Save the userauthentication link. $UserModel->saveAuthentication(array('UserID' => $UserID, 'Provider' => $this->Form->getFormValue('Provider'), 'UniqueID' => $this->Form->getFormValue('UniqueID'))); // Sign the user in. Gdn::session()->start($UserID, true, (bool) $this->Form->getFormValue('RememberMe', true)); Gdn::userModel()->fireEvent('AfterSignIn'); // $this->_setRedirect(TRUE); $this->_setRedirect($this->Request->get('display') == 'popup'); $this->render(); return; } } } $CurrentUserID = Gdn::session()->UserID; // Massage the existing users. foreach ($ExistingUsers as $Index => $UserRow) { if ($EmailUnique && $UserRow['Email'] == $this->Form->getFormValue('Email')) { $EmailFound = $UserRow; break; } if ($UserRow['Name'] == $this->Form->getFormValue('Name')) { $NameFound = $UserRow; } if ($CurrentUserID > 0 && $UserRow['UserID'] == $CurrentUserID) { unset($ExistingUsers[$Index]); $CurrentUserFound = true; } } if (isset($EmailFound)) { // The email address was found and can be the only user option. $ExistingUsers = array($UserRow); $this->setData('NoConnectName', true); } elseif (isset($CurrentUserFound)) { $ExistingUsers = array_merge(array('UserID' => 'current', 'Name' => sprintf(t('%s (Current)'), Gdn::session()->User->Name)), $ExistingUsers); } if (!isset($NameFound) && !$IsPostBack) { $this->Form->setFormValue('ConnectName', $this->Form->getFormValue('Name')); } $this->setData('ExistingUsers', $ExistingUsers); if (UserModel::noEmail()) { $EmailValid = true; } else { $EmailValid = validateRequired($this->Form->getFormValue('Email')); } if ((!$UserSelect || $UserSelect == 'other') && $this->Form->getFormValue('Name') && $EmailValid && (!is_array($ExistingUsers) || count($ExistingUsers) == 0)) { // There is no existing user with the suggested name so we can just create the user. $User = $this->Form->formValues(); $User['Password'] = randomString(50); // some password is required $User['HashMethod'] = 'Random'; $User['Source'] = $this->Form->getFormValue('Provider'); $User['SourceID'] = $this->Form->getFormValue('UniqueID'); $User['Attributes'] = $this->Form->getFormValue('Attributes', null); $User['Email'] = $this->Form->getFormValue('ConnectEmail', $this->Form->getFormValue('Email', null)); $UserID = $UserModel->register($User, array('CheckCaptcha' => false, 'ValidateEmail' => false, 'NoConfirmEmail' => true, 'SaveRoles' => $SaveRolesRegister)); $User['UserID'] = $UserID; $this->Form->setValidationResults($UserModel->validationResults()); if ($UserID) { $UserModel->saveAuthentication(array('UserID' => $UserID, 'Provider' => $this->Form->getFormValue('Provider'), 'UniqueID' => $this->Form->getFormValue('UniqueID'))); $this->Form->setFormValue('UserID', $UserID); $this->Form->setFormValue('UserSelect', false); Gdn::session()->start($UserID, true, (bool) $this->Form->getFormValue('RememberMe', true)); Gdn::userModel()->fireEvent('AfterSignIn'); // Send the welcome email. if (c('Garden.Registration.SendConnectEmail', false)) { try { $UserModel->sendWelcomeEmail($UserID, '', 'Connect', array('ProviderName' => $this->Form->getFormValue('ProviderName', $this->Form->getFormValue('Provider', 'Unknown')))); } catch (Exception $Ex) { // Do nothing if emailing doesn't work. } } $this->_setRedirect(true); } } } // Save the user's choice. if ($IsPostBack) { // The user has made their decision. $PasswordHash = new Gdn_PasswordHash(); if (!$UserSelect || $UserSelect == 'other') { // The user entered a username. $ConnectNameEntered = true; if ($this->Form->validateRule('ConnectName', 'ValidateRequired')) { $ConnectName = $this->Form->getFormValue('ConnectName'); $User = false; if (c('Garden.Registration.NameUnique')) { // Check to see if there is already a user with the given name. $User = $UserModel->getWhere(array('Name' => $ConnectName))->firstRow(DATASET_TYPE_ARRAY); } if (!$User) { $this->Form->validateRule('ConnectName', 'ValidateUsername'); } } } else { // The user selected an existing user. $ConnectNameEntered = false; if ($UserSelect == 'current') { if (Gdn::session()->UserID == 0) { // This shouldn't happen, but a use could sign out in another browser and click submit on this form. $this->Form->addError('@You were unexpectedly signed out.'); } else { $UserSelect = Gdn::session()->UserID; } } $User = $UserModel->getID($UserSelect, DATASET_TYPE_ARRAY); } if (isset($User) && $User) { // Make sure the user authenticates. if (!$User['UserID'] == Gdn::session()->UserID) { if ($this->Form->validateRule('ConnectPassword', 'ValidateRequired', sprintf(t('ValidateRequired'), t('Password')))) { try { if (!$PasswordHash->checkPassword($this->Form->getFormValue('ConnectPassword'), $User['Password'], $User['HashMethod'], $this->Form->getFormValue('ConnectName'))) { if ($ConnectNameEntered) { $this->Form->addError('The username you entered has already been taken.'); } else { $this->Form->addError('The password you entered is incorrect.'); } } } catch (Gdn_UserException $Ex) { $this->Form->addError($Ex); } } } } elseif ($this->Form->errorCount() == 0) { // The user doesn't exist so we need to add another user. $User = $this->Form->formValues(); $User['Name'] = $User['ConnectName']; $User['Password'] = randomString(50); // some password is required $User['HashMethod'] = 'Random'; $UserID = $UserModel->register($User, array('CheckCaptcha' => false, 'NoConfirmEmail' => true, 'SaveRoles' => $SaveRolesRegister)); $User['UserID'] = $UserID; $this->Form->setValidationResults($UserModel->validationResults()); if ($UserID && c('Garden.Registration.SendConnectEmail', false)) { // Send the welcome email. $UserModel->sendWelcomeEmail($UserID, '', 'Connect', array('ProviderName' => $this->Form->getFormValue('ProviderName', $this->Form->getFormValue('Provider', 'Unknown')))); } } if ($this->Form->errorCount() == 0) { // Save the authentication. if (isset($User) && val('UserID', $User)) { $UserModel->saveAuthentication(array('UserID' => $User['UserID'], 'Provider' => $this->Form->getFormValue('Provider'), 'UniqueID' => $this->Form->getFormValue('UniqueID'))); $this->Form->setFormValue('UserID', $User['UserID']); } // Sign the appropriate user in. Gdn::session()->start($this->Form->getFormValue('UserID'), true, (bool) $this->Form->getFormValue('RememberMe', true)); Gdn::userModel()->fireEvent('AfterSignIn'); $this->_setRedirect(true); } } $this->render(); }
$color = substr($color, 1); } if (strlen($color) == 6) { list($r, $g, $b) = array($color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5]); } elseif (strlen($color) == 3) { list($r, $g, $b) = array($color[0], $color[1], $color[2]); } else { return false; } $r = hexdec($r); $g = hexdec($g); $b = hexdec($b); return array($r, $g, $b); } $rgb = html2rgb($_REQUEST['var_captcha_color']); $text = randomString(5); // how many figures will be display $abspath = getcwd(); $abspath = str_replace("\\", "/", $abspath); //header('Content-type: image/png'); //error_reporting(E_ALL); $img = ImageCreateFromPNG('captcha.png'); // background image $color = ImageColorAllocate($img, $rgb[0], $rgb[1], $rgb[2]); // color $ttf = "{$abspath}/xfiles.ttf"; //font type $ttfsize = 24; // font size $angle = rand(0, 5); $t_x = rand(5, 30);
$tablename = $classname; $database = new Sqlite(null, $tablename); $data = $database->rawQuery("select contactemail from {$tablename} where nname = '{$cgi_clientname}';"); if (empty($data)) { $ghtml->print_redirect("/login/?frm_emessage=nouser_email"); //throw lxException('Contact email is not set on Kloxo, it could not be send to a empty address.'); } elseif (!isset($data[0]['contactemail'])) { $ghtml->print_redirect("/login/?frm_emessage=nouser_email"); //throw lxException('Contact email is not set on Kloxo, it could not be send to a empty address.'); } else { $contact_email = $data[0]['contactemail']; if (empty($contact_email)) { //throw lxException('Contact email is not set on Kloxo, it could not be send to a empty address.'); $ghtml->print_redirect("/login/?frm_emessage=nouser_email"); } } if ($cgi_email == $contact_email) { $rndstring = randomString(8); $pass = crypt($rndstring); $database->rawQuery("update {$tablename} set password = '******' where nname = '{$cgi_clientname}'"); $subject = "{$cprogname} Password Reset Request"; $message = "\n\n\nYour password has been reset to the one below for your {$cprogname} login.\n" . "The Client IP address which requested the Reset: {$_SERVER['REMOTE_ADDR']}\n" . 'Username: '******'New Password: ' . $rndstring; $from = NULL; //Setting NULL gets the program@hostname.com lx_mail($from, $contact_email, $subject, $message); $ghtml->print_redirect("/login/?frm_smessage=password_sent"); } else { $ghtml->print_redirect("/login/?frm_emessage=nouser_email"); } } }
if (intval($_GET['id']) != 0) { $user = new user($sql, "id", intval($_GET['id'])); } elseif (isMail($_GET['id']) == TRUE) { $user = new user($sql, "email", e($_GET['id'])); } else { $user = new user($sql, "username", e($_GET['id'])); } if ($user->load()) { $redmsg = ""; $greenmsg = ""; if (isset($_POST['save'])) { $changed = FALSE; $redmsg = ""; $greenmsg = ""; if (isset($_POST['password'])) { $password = randomString(25); $user->changePW($password); $greenmsg = '<p>New user password: '******'</p> <p>Give it to the user.</p>'; $changed = TRUE; } if (isset($_POST['verified'])) { $user->verified = TRUE; $changed = TRUE; } else { $user->verified = FALSE; $changed = TRUE; } if (isset($_POST['division'])) { $user->division = intval($_POST['division']); $changed = TRUE;
<?php // To send HTML mail, the Content-type header must be set $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n"; // Additional headers $headers .= 'From: mySeat Team <*****@*****.**>' . "\r\n"; //$headers .= 'Bcc: support@myseat.us \r\n'; //get a random 8 character string $_SESSION['confHash'] = randomString(); //confirmation hash to database $rows = querySQL('user_confirm_code'); // Get property details $property = querySQL('property_info'); // Subject of email $subject = "Welcome to mySeat"; // prepate logo file $logo = $property['logo_filename'] == '' ? 'logo.png' : $property['logo_filename']; $logo = $global_basedir . 'uploads/logo/' . $logo; // prepate welcome text of email //$text = _user_email_confirmation; // prepate confirmation text of email $text = _user_activation_email; $message = sprintf($text, $_POST['username'], $global_basedir, $_SESSION['confHash'], $global_basedir, $_SESSION['confHash']); // =============== // Email template // =============== $html_text = ' <html> <head>
require 'includes/classes/crypto.php'; $crypto = new phpFreaksCrypto(); include 'includes/classes/class.phpmailer.php'; if ($_GET['reset'] == 'true') { $display = '<div class="responseOk">Your password has been reset, and has been sent to you.</div><br/>'; } if (isset($_POST['submit'])) { //create new user, disabled $sql = "SELECT * FROM " . $db_prefix . "users WHERE firstname='" . $_POST['firstname'] . "' and email = '" . $_POST['email'] . "';"; $query = mysql_query($sql); if (mysql_numrows($query) == 0) { $display = '<div class="responseError">No account matched, please try again.</div><br/>'; } else { $result = mysql_fetch_array($query); //generate random password and update the db $password = randomString(10); $salt = substr($crypto->encrypt(uniqid(mt_rand(), true)), 0, 10); $secure_password = $crypto->encrypt($salt . $crypto->encrypt($password)); $sql = "update " . $db_prefix . "users set salt = '" . $salt . "', password = '******' where firstname='" . $_POST['firstname'] . "' and email = '" . $_POST['email'] . "';"; mysql_query($sql) or die(mysql_error()); //send confirmation email $mail = new PHPMailer(); $mail->IsHTML(true); $mail->From = $adminUser->email; // the email field of the form $mail->FromName = 'NFL Pick \'Em Admin'; // the name field of the form $mail->AddAddress($_POST['email']); // the form will be sent to this address $mail->Subject = 'NFL Pick \'Em Password'; // the subject of email
/** * Set encryption key * * @return string */ public function setEncryptKey() { // Older stores used the software license key so lets keep using that if it exists $key = $GLOBALS['config']->get('config', 'license_key'); // If license_key isn't set and we don't have an "enc_key".. make one if ((!$key || empty($key)) && !$GLOBALS['config']->has('config', 'enc_key')) { $key = randomString(); $GLOBALS['config']->set('config', 'enc_key', $key); } else { // Get enc_key $key = $GLOBALS['config']->get('config', 'enc_key'); if (!$key || empty($key)) { $key = randomString(); $GLOBALS['config']->set('config', 'enc_key', $key); } } return $key; }
/** * Instead of using Gdn_Upload->GenerateTargetName, create one that * depends on SHA1s, to reduce space for duplicates, and use smarter * folder sorting based off the SHA1s. * * @param type $file */ public function getAbsoluteDestinationFilePath($tmpFilePath, $fileExtension, $uploadDestinationDir = '') { $absolutePath = ''; $basePath = $this->editorBaseUploadDestinationDir; if ($basePath != '') { $basePath = $this->getBaseUploadDestinationDir(); } if ($uploadDestinationDir) { $basePath = $uploadDestinationDir; } // SHA1 of the tmp file // $fileSHA1 = sha1_file($tmpFilePath); // Instead just use the RandomString function that Gdn_Upload->GenerateTargetName is using. $fileRandomString = strtolower(randomString(14)); // Use first two characters from fileMD5 as subdirectory, // and use the rest as the file name. $dirlen = 2; $subdir = substr($fileRandomString, 0, $dirlen); $filename = substr($fileRandomString, $dirlen); $fileExtension = strtolower($fileExtension); $fileDirPath = $basePath . '/' . $subdir; if ($this->validateUploadDestinationPath($fileDirPath)) { $absolutePath = $fileDirPath . '/' . $filename; if ($fileExtension) { $absolutePath .= '.' . $fileExtension; } } return $absolutePath; }
/** * @param $dataSourceName * @param $bypassAuth * @return bool */ public function newToDB($dataSourceName, $bypassAuth) { $this->fieldInfo = null; $tableInfo = $this->dbSettings->getDataSourceTargetArray(); $tableName = $this->dbSettings->getEntityForUpdate(); if (!$bypassAuth && isset($tableInfo['authentication'])) { $signedUser = $this->authSupportUnifyUsernameAndEmail($this->dbSettings->getCurrentUser()); } $setColumnNames = array(); $setValues = array(); if (!$this->setupConnection()) { //Establish the connection return false; } if (isset($tableInfo['script'])) { foreach ($tableInfo['script'] as $condition) { if ($condition['db-operation'] == 'new' && $condition['situation'] == 'pre') { $sql = $condition['definition']; $this->logger->setDebugMessage($sql); $result = $this->link->query($sql); if (!$result) { $this->errorMessageStore('Pre-script:' . $sql); return false; } } } } $requiredFields = $this->dbSettings->getFieldsRequired(); $countFields = count($requiredFields); $fieldValues = $this->dbSettings->getValue(); for ($i = 0; $i < $countFields; $i++) { $field = $requiredFields[$i]; $value = $fieldValues[$i]; $filedInForm = "{$tableName}{$this->dbSettings->getSeparator()}{$field}"; $convertedValue = is_array($value) ? implode("\n", $value) : $value; $setValues[] = $this->link->quote($this->formatter->formatterToDB($filedInForm, $convertedValue)); $setColumnNames[] = $field; } if (isset($tableInfo['default-values'])) { foreach ($tableInfo['default-values'] as $itemDef) { $field = $itemDef['field']; $value = $itemDef['value']; $filedInForm = "{$tableName}{$this->dbSettings->getSeparator()}{$field}"; $convertedValue = is_array($value) ? implode("\n", $value) : $value; $setValues[] = $this->link->quote($this->formatter->formatterToDB($filedInForm, $convertedValue)); $setColumnNames[] = $field; } } if (!$bypassAuth && isset($tableInfo['authentication'])) { $authInfoField = $this->getFieldForAuthorization("new"); $authInfoTarget = $this->getTargetForAuthorization("new"); if ($authInfoTarget == 'field-user') { $setColumnNames[] = $authInfoField; $setValues[] = $this->link->quote(strlen($signedUser) == 0 ? randomString(10) : $signedUser); } else { if ($authInfoTarget == 'field-group') { $belongGroups = $this->authSupportGetGroupsOfUser($signedUser); $setColumnNames[] = $authInfoField; $setValues[] = $this->link->quote(strlen($belongGroups[0]) == 0 ? randomString(10) : $belongGroups[0]); } } } $keyField = isset($tableInfo['key']) ? $tableInfo['key'] : 'id'; if (strpos($this->dbSettings->getDbSpecDSN(), 'mysql:') === 0) { /**/ $setClause = count($setColumnNames) == 0 ? "SET {$keyField}=DEFAULT" : '(' . implode(',', $setColumnNames) . ') VALUES(' . implode(',', $setValues) . ')'; } else { // sqlite, pgsql $setClause = count($setColumnNames) == 0 ? "DEFAULT VALUES" : '(' . implode(',', $setColumnNames) . ') VALUES(' . implode(',', $setValues) . ')'; } $sql = "INSERT INTO {$tableName} {$setClause}"; $this->logger->setDebugMessage($sql); $result = $this->link->query($sql); if ($result === false) { $this->errorMessageStore('Insert:' . $sql); return false; } $seqObject = isset($tableInfo['sequence']) ? $tableInfo['sequence'] : $tableName; $lastKeyValue = $this->link->lastInsertId($seqObject); $this->queriedPrimaryKeys = array($lastKeyValue); $this->queriedEntity = $tableName; if ($this->isRequiredUpdated) { $sql = "SELECT * FROM " . $tableName . " WHERE " . $keyField . "=" . $this->link->quote($lastKeyValue); $result = $this->link->query($sql); $this->logger->setDebugMessage($sql); if ($result === false) { $this->errorMessageStore('Select:' . $sql); } else { $sqlResult = array(); $isFirstRow = true; foreach ($result->fetchAll(PDO::FETCH_ASSOC) as $row) { $rowArray = array(); foreach ($row as $field => $val) { if ($isFirstRow) { $this->fieldInfo[] = $field; } $filedInForm = "{$tableName}{$this->dbSettings->getSeparator()}{$field}"; $rowArray[$field] = $this->formatter->formatterFromDB($filedInForm, $val); } $sqlResult[] = $rowArray; $isFirstRow = false; } $this->updatedRecord = $sqlResult; } } if (isset($tableInfo['script'])) { foreach ($tableInfo['script'] as $condition) { if ($condition['db-operation'] == 'new' && $condition['situation'] == 'post') { $sql = $condition['definition']; $this->logger->setDebugMessage($sql); $result = $this->link->query($sql); if (!$result) { $this->errorMessageStore('Post-script:' . $sql); return false; } } } } return $lastKeyValue; }