public static function sendEmail($args) { $isEncrypted = OC_App::isEnabled('files_encryption'); if (!$isEncrypted || isset($_POST['continue'])) { $continue = true; } else { $continue = false; } if (OC_User::userExists($_POST['user']) && $continue) { $token = hash('sha256', OC_Util::generate_random_bytes(30) . OC_Config::getValue('passwordsalt', '')); OC_Preferences::setValue($_POST['user'], 'owncloud', 'lostpassword', hash('sha256', $token)); // Hash the token again to prevent timing attacks $email = OC_Preferences::getValue($_POST['user'], 'settings', 'email', ''); if (!empty($email)) { $link = OC_Helper::linkToRoute('core_lostpassword_reset', array('user' => $_POST['user'], 'token' => $token)); $link = OC_Helper::makeURLAbsolute($link); $tmpl = new OC_Template('core/lostpassword', 'email'); $tmpl->assign('link', $link, false); $msg = $tmpl->fetchPage(); $l = OC_L10N::get('core'); $from = OCP\Util::getDefaultEmailAddress('lostpassword-noreply'); try { OC_Mail::send($email, $_POST['user'], $l->t('ownCloud password reset'), $msg, $from, 'ownCloud'); } catch (Exception $e) { OC_Template::printErrorPage('A problem occurs during sending the e-mail please contact your administrator.'); } self::displayLostPasswordPage(false, true); } else { self::displayLostPasswordPage(true, false); } } else { self::displayLostPasswordPage(true, false); } }
public static function sendEmail($args) { if (OC_User::userExists($_POST['user'])) { $token = hash('sha256', OC_Util::generate_random_bytes(30) . OC_Config::getValue('passwordsalt', '')); OC_Preferences::setValue($_POST['user'], 'owncloud', 'lostpassword', hash('sha256', $token)); // Hash the token again to prevent timing attacks $email = OC_Preferences::getValue($_POST['user'], 'settings', 'email', ''); if (!empty($email)) { $link = OC_Helper::linkToRoute('core_lostpassword_reset', array('user' => $_POST['user'], 'token' => $token)); $link = OC_Helper::makeURLAbsolute($link); $tmpl = new OC_Template('core/lostpassword', 'email'); $tmpl->assign('link', $link, false); $msg = $tmpl->fetchPage(); $l = OC_L10N::get('core'); $from = 'lostpassword-noreply@' . OCP\Util::getServerHost(); OC_Mail::send($email, $_POST['user'], $l->t('ownCloud password reset'), $msg, $from, 'ownCloud'); echo 'Mailsent'; self::displayLostPasswordPage(false, true); } else { self::displayLostPasswordPage(true, false); } } else { self::displayLostPasswordPage(true, false); } }
public function setUp() { $dbfile = OC::$SERVERROOT . '/tests/data/db_structure.xml'; $r = '_' . OC_Util::generate_random_bytes('4') . '_'; $content = file_get_contents($dbfile); $content = str_replace('*dbprefix*', '*dbprefix*' . $r, $content); file_put_contents(self::$schema_file, $content); OC_DB::createDbFromStructure(self::$schema_file); $this->test_prefix = $r; $this->table1 = $this->test_prefix . 'contacts_addressbooks'; $this->table2 = $this->test_prefix . 'contacts_cards'; $this->table3 = $this->test_prefix . 'vcategory'; }
protected static function tryFormLogin() { if (!isset($_POST["user"]) || !isset($_POST['password'])) { return false; } OC_App::loadApps(); //setup extra user backends OC_User::setupBackends(); if (OC_User::login($_POST["user"], $_POST["password"])) { // setting up the time zone if (isset($_POST['timezone-offset'])) { $_SESSION['timezone'] = $_POST['timezone-offset']; } self::cleanupLoginTokens($_POST['user']); if (!empty($_POST["remember_login"])) { if (defined("DEBUG") && DEBUG) { OC_Log::write('core', 'Setting remember login to cookie', OC_Log::DEBUG); } $token = OC_Util::generate_random_bytes(32); OC_Preferences::setValue($_POST['user'], 'login_token', $token, time()); OC_User::setMagicInCookie($_POST["user"], $token); } else { OC_User::unsetMagicInCookie(); } OC_Util::redirectToDefaultPage(); exit; } return true; }
public static function install($options) { $error = array(); $dbtype = $options['dbtype']; if (empty($options['adminlogin'])) { $error[] = 'Set an admin username.'; } if (empty($options['adminpass'])) { $error[] = 'Set an admin password.'; } if (empty($options['directory'])) { $error[] = 'Specify a data folder.'; } if ($dbtype == 'mysql' or $dbtype == 'pgsql') { //mysql and postgresql needs more config options if ($dbtype == 'mysql') { $dbprettyname = 'MySQL'; } else { $dbprettyname = 'PostgreSQL'; } if (empty($options['dbuser'])) { $error[] = "{$dbprettyname} enter the database username."; } if (empty($options['dbname'])) { $error[] = "{$dbprettyname} enter the database name."; } if (empty($options['dbhost'])) { $error[] = "{$dbprettyname} set the database host."; } } if (count($error) == 0) { //no errors, good $username = htmlspecialchars_decode($options['adminlogin']); $password = htmlspecialchars_decode($options['adminpass']); $datadir = htmlspecialchars_decode($options['directory']); //use sqlite3 when available, otherise sqlite2 will be used. if ($dbtype == 'sqlite' and class_exists('SQLite3')) { $dbtype = 'sqlite3'; } //generate a random salt that is used to salt the local user passwords $salt = OC_Util::generate_random_bytes(30); OC_Config::setValue('passwordsalt', $salt); //write the config file OC_Config::setValue('datadirectory', $datadir); OC_Config::setValue('dbtype', $dbtype); OC_Config::setValue('version', implode('.', OC_Util::getVersion())); if ($dbtype == 'mysql') { $dbuser = $options['dbuser']; $dbpass = $options['dbpass']; $dbname = $options['dbname']; $dbhost = $options['dbhost']; $dbtableprefix = isset($options['dbtableprefix']) ? $options['dbtableprefix'] : 'oc_'; OC_Config::setValue('dbname', $dbname); OC_Config::setValue('dbhost', $dbhost); OC_Config::setValue('dbtableprefix', $dbtableprefix); //check if the database user has admin right $connection = @mysql_connect($dbhost, $dbuser, $dbpass); if (!$connection) { $error[] = array('error' => 'MySQL username and/or password not valid', 'hint' => 'You need to enter either an existing account or the administrator.'); return $error; } else { $oldUser = OC_Config::getValue('dbuser', false); $oldPassword = OC_Config::getValue('dbpassword', false); $query = "SELECT user FROM mysql.user WHERE user='******'"; //this should be enough to check for admin rights in mysql if (mysql_query($query, $connection)) { //use the admin login data for the new database user //add prefix to the mysql user name to prevent collissions $dbusername = substr('oc_' . $username, 0, 16); if ($dbusername != $oldUser) { //hash the password so we don't need to store the admin config in the config file $dbpassword = md5(time() . $password); self::createDBUser($dbusername, $dbpassword, $connection); OC_Config::setValue('dbuser', $dbusername); OC_Config::setValue('dbpassword', $dbpassword); } //create the database self::createDatabase($dbname, $dbusername, $connection); } else { if ($dbuser != $oldUser) { OC_Config::setValue('dbuser', $dbuser); OC_Config::setValue('dbpassword', $dbpass); } //create the database self::createDatabase($dbname, $dbuser, $connection); } //fill the database if needed $query = "select count(*) from information_schema.tables where table_schema='{$dbname}' AND table_name = '{$dbtableprefix}users';"; $result = mysql_query($query, $connection); if ($result) { $row = mysql_fetch_row($result); } if (!$result or $row[0] == 0) { OC_DB::createDbFromStructure('db_structure.xml'); } mysql_close($connection); } } elseif ($dbtype == 'pgsql') { $dbuser = $options['dbuser']; $dbpass = $options['dbpass']; $dbname = $options['dbname']; $dbhost = $options['dbhost']; $dbtableprefix = isset($options['dbtableprefix']) ? $options['dbtableprefix'] : 'oc_'; OC_CONFIG::setValue('dbname', $dbname); OC_CONFIG::setValue('dbhost', $dbhost); OC_CONFIG::setValue('dbtableprefix', $dbtableprefix); //check if the database user has admin right $connection_string = "host={$dbhost} dbname=postgres user={$dbuser} password={$dbpass}"; $connection = @pg_connect($connection_string); if (!$connection) { $error[] = array('error' => 'PostgreSQL username and/or password not valid', 'hint' => 'You need to enter either an existing account or the administrator.'); return $error; } else { //check for roles creation rights in postgresql $query = "SELECT 1 FROM pg_roles WHERE rolcreaterole=TRUE AND rolname='{$dbuser}'"; $result = pg_query($connection, $query); if ($result and pg_num_rows($result) > 0) { //use the admin login data for the new database user //add prefix to the postgresql user name to prevent collissions $dbusername = '******' . $username; //create a new password so we don't need to store the admin config in the config file $dbpassword = md5(time()); self::pg_createDBUser($dbusername, $dbpassword, $connection); OC_CONFIG::setValue('dbuser', $dbusername); OC_CONFIG::setValue('dbpassword', $dbpassword); //create the database self::pg_createDatabase($dbname, $dbusername, $connection); } else { OC_CONFIG::setValue('dbuser', $dbuser); OC_CONFIG::setValue('dbpassword', $dbpass); //create the database self::pg_createDatabase($dbname, $dbuser, $connection); } // the connection to dbname=postgres is not needed anymore pg_close($connection); // connect to the ownCloud database (dbname=$dbname) an check if it needs to be filled $dbuser = OC_CONFIG::getValue('dbuser'); $dbpass = OC_CONFIG::getValue('dbpassword'); $connection_string = "host={$dbhost} dbname={$dbname} user={$dbuser} password={$dbpass}"; $connection = @pg_connect($connection_string); if (!$connection) { $error[] = array('error' => 'PostgreSQL username and/or password not valid', 'hint' => 'You need to enter either an existing account or the administrator.'); } else { $query = "select count(*) FROM pg_class WHERE relname='{$dbtableprefix}users' limit 1"; $result = pg_query($connection, $query); if ($result) { $row = pg_fetch_row($result); } if (!$result or $row[0] == 0) { OC_DB::createDbFromStructure('db_structure.xml'); } } } } else { //delete the old sqlite database first, might cause infinte loops otherwise if (file_exists("{$datadir}/owncloud.db")) { unlink("{$datadir}/owncloud.db"); } //in case of sqlite, we can always fill the database OC_DB::createDbFromStructure('db_structure.xml'); } //create the user and group try { OC_User::createUser($username, $password); } catch (Exception $exception) { $error[] = $exception->getMessage(); } if (count($error) == 0) { OC_Appconfig::setValue('core', 'installedat', microtime(true)); OC_Appconfig::setValue('core', 'lastupdatedat', microtime(true)); OC_Group::createGroup('admin'); OC_Group::addToGroup($username, 'admin'); OC_User::login($username, $password); //guess what this does OC_Installer::installShippedApps(); //create htaccess files for apache hosts if (strstr($_SERVER['SERVER_SOFTWARE'], 'Apache')) { self::createHtaccess(); } //and we are done OC_Config::setValue('installed', true); } } return $error; }
public static function post_login($parameters) { $userid = $parameters['uid']; $samlBackend = new OC_USER_SAML(); if ($samlBackend->auth->isAuthenticated()) { $attributes = $samlBackend->auth->getAttributes(); $usernameFound = false; foreach ($samlBackend->usernameMapping as $usernameMapping) { if (array_key_exists($usernameMapping, $attributes) && !empty($attributes[$usernameMapping][0])) { $usernameFound = true; $uid = $attributes[$usernameMapping][0]; OC_Log::write('saml', 'Authenticated user ' . $uid, OC_Log::DEBUG); break; } } if ($usernameFound && $uid == $userid) { $attributes = $samlBackend->auth->getAttributes(); $saml_email = ''; foreach ($samlBackend->mailMapping as $mailMapping) { if (array_key_exists($mailMapping, $attributes) && !empty($attributes[$mailMapping][0])) { $saml_email = $attributes[$mailMapping][0]; break; } } $saml_display_name = ''; foreach ($samlBackend->displayNameMapping as $displayNameMapping) { if (array_key_exists($displayNameMapping, $attributes) && !empty($attributes[$displayNameMapping][0])) { $saml_display_name = $attributes[$displayNameMapping][0]; break; } } $saml_groups = array(); foreach ($samlBackend->groupMapping as $groupMapping) { if (array_key_exists($groupMapping, $attributes) && !empty($attributes[$groupMapping])) { $saml_groups = array_merge($saml_groups, $attributes[$groupMapping]); } } if (empty($saml_groups) && !empty($samlBackend->defaultGroup)) { $saml_groups = array($samlBackend->defaultGroup); OC_Log::write('saml', 'Using default group "' . $samlBackend->defaultGroup . '" for the user: '******'/[^a-zA-Z0-9 _\\.@\\-]/', $uid)) { OC_Log::write('saml', 'Invalid username "' . $uid . '", allowed chars "a-zA-Z0-9" and "_.@-" ', OC_Log::DEBUG); return false; } else { $random_password = OC_Util::generate_random_bytes(20); OC_Log::write('saml', 'Creating new user: '******'saml', 'Updating data of the user: ' . $uid, OC_Log::DEBUG); if (isset($saml_email)) { update_mail($uid, $saml_email); } if (isset($saml_groups)) { update_groups($uid, $saml_groups, $samlBackend->protectedGroups, false); } if (isset($saml_display_name)) { update_display_name($uid, $saml_display_name); } } } return true; } } return false; }
<?php /** * Copyright (c) 2012 Frank Karlitschek frank@owncloud.org * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ $RUNTIME_NOAPPS = TRUE; //no apps require_once '../../lib/base.php'; // Someone lost their password: if (isset($_POST['user'])) { if (OC_User::userExists($_POST['user'])) { $token = hash("sha256", $_POST['user'] . OC_Util::generate_random_bytes(10)); OC_Preferences::setValue($_POST['user'], 'owncloud', 'lostpassword', $token); $email = OC_Preferences::getValue($_POST['user'], 'settings', 'email', ''); if (!empty($email)) { $link = OC_Helper::linkToAbsolute('core/lostpassword', 'resetpassword.php', array('user' => $_POST['user'], 'token' => $token)); $tmpl = new OC_Template('core/lostpassword', 'email'); $tmpl->assign('link', $link, false); $msg = $tmpl->fetchPage(); $l = OC_L10N::get('core'); $from = 'lostpassword-noreply@' . OCP\Util::getServerHost(); OC_MAIL::send($email, $_POST['user'], $l->t('ownCloud password reset'), $msg, $from, 'ownCloud'); echo 'sent'; } OC_Template::printGuestPage('core/lostpassword', 'lostpassword', array('error' => false, 'requested' => true)); } else { OC_Template::printGuestPage('core/lostpassword', 'lostpassword', array('error' => true, 'requested' => false)); }
/** * @brief Share an item with a user, group, or via private link * @param string Item type * @param string Item source * @param int SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK * @param string User or group the item is being shared with * @param int CRUDS permissions * @return bool|string Returns true on success or false on failure, Returns token on success for links */ public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions) { $uidOwner = \OC_User::getUser(); $sharingPolicy = \OC_Appconfig::getValue('core', 'shareapi_share_policy', 'global'); // Verify share type and sharing conditions are met if ($shareType === self::SHARE_TYPE_USER) { if ($shareWith == $uidOwner) { $message = 'Sharing ' . $itemSource . ' failed, because the user ' . $shareWith . ' is the item owner'; \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR); throw new \Exception($message); } if (!\OC_User::userExists($shareWith)) { $message = 'Sharing ' . $itemSource . ' failed, because the user ' . $shareWith . ' does not exist'; \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR); throw new \Exception($message); } if ($sharingPolicy == 'groups_only') { $inGroup = array_intersect(\OC_Group::getUserGroups($uidOwner), \OC_Group::getUserGroups($shareWith)); if (empty($inGroup)) { $message = 'Sharing ' . $itemSource . ' failed, because the user ' . $shareWith . ' is not a member of any groups that ' . $uidOwner . ' is a member of'; \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR); throw new \Exception($message); } } // Check if the item source is already shared with the user, either from the same owner or a different user if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) { // Only allow the same share to occur again if it is the same owner and is not a user share, this use case is for increasing permissions for a specific user if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) { $message = 'Sharing ' . $itemSource . ' failed, because this item is already shared with ' . $shareWith; \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR); throw new \Exception($message); } } } else { if ($shareType === self::SHARE_TYPE_GROUP) { if (!\OC_Group::groupExists($shareWith)) { $message = 'Sharing ' . $itemSource . ' failed, because the group ' . $shareWith . ' does not exist'; \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR); throw new \Exception($message); } if ($sharingPolicy == 'groups_only' && !\OC_Group::inGroup($uidOwner, $shareWith)) { $message = 'Sharing ' . $itemSource . ' failed, because ' . $uidOwner . ' is not a member of the group ' . $shareWith; \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR); throw new \Exception($message); } // Check if the item source is already shared with the group, either from the same owner or a different user // The check for each user in the group is done inside the put() function if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) { // Only allow the same share to occur again if it is the same owner and is not a group share, this use case is for increasing permissions for a specific user if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) { $message = 'Sharing ' . $itemSource . ' failed, because this item is already shared with ' . $shareWith; \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR); throw new \Exception($message); } } // Convert share with into an array with the keys group and users $group = $shareWith; $shareWith = array(); $shareWith['group'] = $group; $shareWith['users'] = array_diff(\OC_Group::usersInGroup($group), array($uidOwner)); } else { if ($shareType === self::SHARE_TYPE_LINK) { if (\OC_Appconfig::getValue('core', 'shareapi_allow_links', 'yes') == 'yes') { // when updating a link share if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null, $uidOwner, self::FORMAT_NONE, null, 1)) { // remember old token $oldToken = $checkExists['token']; //delete the old share self::delete($checkExists['id']); } // Generate hash of password - same method as user passwords if (isset($shareWith)) { $forcePortable = CRYPT_BLOWFISH != 1; $hasher = new \PasswordHash(8, $forcePortable); $shareWith = $hasher->HashPassword($shareWith . \OC_Config::getValue('passwordsalt', '')); } // Generate token if (isset($oldToken)) { $token = $oldToken; } else { $token = \OC_Util::generate_random_bytes(self::TOKEN_LENGTH); } $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token); if ($result) { return $token; } else { return false; } } $message = 'Sharing ' . $itemSource . ' failed, because sharing with links is not allowed'; \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR); throw new \Exception($message); return false; // } else if ($shareType === self::SHARE_TYPE_CONTACT) { // if (!\OC_App::isEnabled('contacts')) { // $message = 'Sharing '.$itemSource.' failed, because the contacts app is not enabled'; // \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR); // return false; // } // $vcard = \OC_Contacts_App::getContactVCard($shareWith); // if (!isset($vcard)) { // $message = 'Sharing '.$itemSource.' failed, because the contact does not exist'; // \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR); // throw new \Exception($message); // } // $details = \OC_Contacts_VCard::structureContact($vcard); // // TODO Add ownCloud user to contacts vcard // if (!isset($details['EMAIL'])) { // $message = 'Sharing '.$itemSource.' failed, because no email address is associated with the contact'; // \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR); // throw new \Exception($message); // } // return self::shareItem($itemType, $itemSource, self::SHARE_TYPE_EMAIL, $details['EMAIL'], $permissions); } else { // Future share types need to include their own conditions $message = 'Share type ' . $shareType . ' is not valid for ' . $itemSource; \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR); throw new \Exception($message); } } } // If the item is a folder, scan through the folder looking for equivalent item types if ($itemType == 'folder') { $parentFolder = self::put('folder', $itemSource, $shareType, $shareWith, $uidOwner, $permissions, true); if ($parentFolder && ($files = \OC_Files::getDirectoryContent($itemSource))) { for ($i = 0; $i < count($files); $i++) { $name = substr($files[$i]['name'], strpos($files[$i]['name'], $itemSource) - strlen($itemSource)); if ($files[$i]['mimetype'] == 'httpd/unix-directory' && ($children = \OC_Files::getDirectoryContent($name, '/'))) { // Continue scanning into child folders array_push($files, $children); } else { // Check file extension for an equivalent item type to convert to $extension = strtolower(substr($itemSource, strrpos($itemSource, '.') + 1)); foreach (self::$backends as $type => $backend) { if (isset($backend->dependsOn) && $backend->dependsOn == 'file' && isset($backend->supportedFileExtensions) && in_array($extension, $backend->supportedFileExtensions)) { $itemType = $type; break; } } // Pass on to put() to check if this item should be converted, the item won't be inserted into the database unless it can be converted self::put($itemType, $name, $shareType, $shareWith, $uidOwner, $permissions, $parentFolder); } } return true; } return false; } else { // Put the item into the database return self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions); } }
protected static function tryFormLogin() { if (!isset($_POST["user"]) || !isset($_POST['password'])) { return false; } OC_App::loadApps(); //setup extra user backends OC_User::setupBackends(); if (OC_User::login($_POST["user"], $_POST["password"])) { self::cleanupLoginTokens($_POST['user']); if (!empty($_POST["remember_login"])) { if (defined("DEBUG") && DEBUG) { OC_Log::write('core', 'Setting remember login to cookie', OC_Log::DEBUG); } $token = OC_Util::generate_random_bytes(32); OC_Preferences::setValue($_POST['user'], 'login_token', $token, time()); OC_User::setMagicInCookie($_POST["user"], $token); } else { OC_User::unsetMagicInCookie(); } header('Location: ' . $_SERVER['REQUEST_URI']); exit; } return true; }
function testGenerate_random_bytes() { $result = strlen(OC_Util::generate_random_bytes(59)); $this->assertEquals(59, $result); }
public static function install($options) { $error = array(); $dbtype = $options['dbtype']; if (empty($options['adminlogin'])) { $error[] = 'Set an admin username.'; } if (empty($options['adminpass'])) { $error[] = 'Set an admin password.'; } if (empty($options['directory'])) { $error[] = 'Specify a data folder.'; } if ($dbtype == 'mysql' or $dbtype == 'pgsql' or $dbtype == 'oci') { //mysql and postgresql needs more config options if ($dbtype == 'mysql') { $dbprettyname = 'MySQL'; } else { if ($dbtype == 'pgsql') { $dbprettyname = 'PostgreSQL'; } else { $dbprettyname = 'Oracle'; } } if (empty($options['dbuser'])) { $error[] = "{$dbprettyname} enter the database username."; } if (empty($options['dbname'])) { $error[] = "{$dbprettyname} enter the database name."; } if (substr_count($options['dbname'], '.') >= 1) { $error[] = "{$dbprettyname} you may not use dots in the database name"; } if ($dbtype != 'oci' && empty($options['dbhost'])) { $error[] = "{$dbprettyname} set the database host."; } } if (count($error) == 0) { //no errors, good $username = htmlspecialchars_decode($options['adminlogin']); $password = htmlspecialchars_decode($options['adminpass']); $datadir = htmlspecialchars_decode($options['directory']); //use sqlite3 when available, otherise sqlite2 will be used. if ($dbtype == 'sqlite' and class_exists('SQLite3')) { $dbtype = 'sqlite3'; } //generate a random salt that is used to salt the local user passwords $salt = OC_Util::generate_random_bytes(30); OC_Config::setValue('passwordsalt', $salt); //write the config file OC_Config::setValue('datadirectory', $datadir); OC_Config::setValue('dbtype', $dbtype); OC_Config::setValue('version', implode('.', OC_Util::getVersion())); if ($dbtype == 'mysql') { $dbuser = $options['dbuser']; $dbpass = $options['dbpass']; $dbname = $options['dbname']; $dbhost = $options['dbhost']; $dbtableprefix = isset($options['dbtableprefix']) ? $options['dbtableprefix'] : 'oc_'; OC_Config::setValue('dbname', $dbname); OC_Config::setValue('dbhost', $dbhost); OC_Config::setValue('dbtableprefix', $dbtableprefix); try { self::setupMySQLDatabase($dbhost, $dbuser, $dbpass, $dbname, $dbtableprefix, $username); } catch (Exception $e) { $error[] = array('error' => 'MySQL username and/or password not valid', 'hint' => 'You need to enter either an existing account or the administrator.'); return $error; } } elseif ($dbtype == 'pgsql') { $dbuser = $options['dbuser']; $dbpass = $options['dbpass']; $dbname = $options['dbname']; $dbhost = $options['dbhost']; $dbtableprefix = isset($options['dbtableprefix']) ? $options['dbtableprefix'] : 'oc_'; OC_Config::setValue('dbname', $dbname); OC_Config::setValue('dbhost', $dbhost); OC_Config::setValue('dbtableprefix', $dbtableprefix); try { self::setupPostgreSQLDatabase($dbhost, $dbuser, $dbpass, $dbname, $dbtableprefix, $username); } catch (Exception $e) { $error[] = array('error' => 'PostgreSQL username and/or password not valid', 'hint' => 'You need to enter either an existing account or the administrator.'); return $error; } } elseif ($dbtype == 'oci') { $dbuser = $options['dbuser']; $dbpass = $options['dbpass']; $dbname = $options['dbname']; $dbtablespace = $options['dbtablespace']; $dbhost = isset($options['dbhost']) ? $options['dbhost'] : ''; $dbtableprefix = isset($options['dbtableprefix']) ? $options['dbtableprefix'] : 'oc_'; OC_Config::setValue('dbname', $dbname); OC_Config::setValue('dbtablespace', $dbtablespace); OC_Config::setValue('dbhost', $dbhost); OC_Config::setValue('dbtableprefix', $dbtableprefix); try { self::setupOCIDatabase($dbhost, $dbuser, $dbpass, $dbname, $dbtableprefix, $dbtablespace, $username); } catch (Exception $e) { $error[] = array('error' => 'Oracle username and/or password not valid', 'hint' => 'You need to enter either an existing account or the administrator.'); return $error; } } else { //delete the old sqlite database first, might cause infinte loops otherwise if (file_exists("{$datadir}/owncloud.db")) { unlink("{$datadir}/owncloud.db"); } //in case of sqlite, we can always fill the database OC_DB::createDbFromStructure('db_structure.xml'); } //create the user and group try { OC_User::createUser($username, $password); } catch (Exception $exception) { $error[] = $exception->getMessage(); } if (count($error) == 0) { OC_Appconfig::setValue('core', 'installedat', microtime(true)); OC_Appconfig::setValue('core', 'lastupdatedat', microtime(true)); OC_Group::createGroup('admin'); OC_Group::addToGroup($username, 'admin'); OC_User::login($username, $password); //guess what this does OC_Installer::installShippedApps(); //create htaccess files for apache hosts if (isset($_SERVER['SERVER_SOFTWARE']) && strstr($_SERVER['SERVER_SOFTWARE'], 'Apache')) { self::createHtaccess(); } //and we are done OC_Config::setValue('installed', true); } } return $error; }
protected function getUniqueSessionId() { $testSession = new Db_Session(); do { // this prevents branching for stable5 for now: // OC_Util::generate_random_bytes was camelCased if (method_exists('\\OC_Util', 'generate_random_bytes')) { $id = \OC_Util::generate_random_bytes(30); } else { $id = \OC_Util::generateRandomBytes(30); } } while ($testSession->load($id)->hasData()); return $id; }
private static function setupPostgreSQLDatabase($dbhost, $dbuser, $dbpass, $dbname, $dbtableprefix, $username) { $e_host = addslashes($dbhost); $e_user = addslashes($dbuser); $e_password = addslashes($dbpass); $l = self::getTrans(); //check if the database user has admin rights $connection_string = "host='{$e_host}' dbname=postgres user='******' password='******'"; $connection = @pg_connect($connection_string); if (!$connection) { throw new Exception($l->t('PostgreSQL username and/or password not valid')); } $e_user = pg_escape_string($dbuser); //check for roles creation rights in postgresql $query = "SELECT 1 FROM pg_roles WHERE rolcreaterole=TRUE AND rolname='{$e_user}'"; $result = pg_query($connection, $query); if ($result and pg_num_rows($result) > 0) { //use the admin login data for the new database user //add prefix to the postgresql user name to prevent collisions $dbusername = '******' . $username; //create a new password so we don't need to store the admin config in the config file $dbpassword = md5(OC_Util::generate_random_bytes(30)); self::pg_createDBUser($dbusername, $dbpassword, $connection); OC_Config::setValue('dbuser', $dbusername); OC_Config::setValue('dbpassword', $dbpassword); //create the database self::pg_createDatabase($dbname, $dbusername, $connection); } else { OC_Config::setValue('dbuser', $dbuser); OC_Config::setValue('dbpassword', $dbpass); //create the database self::pg_createDatabase($dbname, $dbuser, $connection); } // the connection to dbname=postgres is not needed anymore pg_close($connection); // connect to the ownCloud database (dbname=$dbname) and check if it needs to be filled $dbuser = OC_Config::getValue('dbuser'); $dbpass = OC_Config::getValue('dbpassword'); $e_host = addslashes($dbhost); $e_dbname = addslashes($dbname); $e_user = addslashes($dbuser); $e_password = addslashes($dbpass); $connection_string = "host='{$e_host}' dbname='{$e_dbname}' user='******' password='******'"; $connection = @pg_connect($connection_string); if (!$connection) { throw new Exception($l->t('PostgreSQL username and/or password not valid')); } $query = "select count(*) FROM pg_class WHERE relname='{$dbtableprefix}users' limit 1"; $result = pg_query($connection, $query); if ($result) { $row = pg_fetch_row($result); } if (!$result or $row[0] == 0) { OC_DB::createDbFromStructure('db_structure.xml'); } }
public static function install($options) { $error = array(); $dbtype = $options['dbtype']; if (empty($options['adminlogin'])) { $error[] = 'Set an admin username.'; } if (empty($options['adminpass'])) { $error[] = 'Set an admin password.'; } if (empty($options['directory'])) { $error[] = 'Specify a data folder.'; } if ($dbtype == 'mysql' or $dbtype == 'pgsql' or $dbtype == 'oci') { //mysql and postgresql needs more config options if ($dbtype == 'mysql') { $dbprettyname = 'MySQL'; } else { if ($dbtype == 'pgsql') { $dbprettyname = 'PostgreSQL'; } else { $dbprettyname = 'Oracle'; } } if (empty($options['dbuser'])) { $error[] = "{$dbprettyname} enter the database username."; } if (empty($options['dbname'])) { $error[] = "{$dbprettyname} enter the database name."; } if ($dbtype != 'oci' && empty($options['dbhost'])) { $error[] = "{$dbprettyname} set the database host."; } } if (count($error) == 0) { //no errors, good $username = htmlspecialchars_decode($options['adminlogin']); $password = htmlspecialchars_decode($options['adminpass']); $datadir = htmlspecialchars_decode($options['directory']); //use sqlite3 when available, otherise sqlite2 will be used. if ($dbtype == 'sqlite' and class_exists('SQLite3')) { $dbtype = 'sqlite3'; } //generate a random salt that is used to salt the local user passwords $salt = OC_Util::generate_random_bytes(30); OC_Config::setValue('passwordsalt', $salt); //write the config file OC_Config::setValue('datadirectory', $datadir); OC_Config::setValue('dbtype', $dbtype); OC_Config::setValue('version', implode('.', OC_Util::getVersion())); if ($dbtype == 'mysql') { $dbuser = $options['dbuser']; $dbpass = $options['dbpass']; $dbname = $options['dbname']; $dbhost = $options['dbhost']; $dbtableprefix = isset($options['dbtableprefix']) ? $options['dbtableprefix'] : 'oc_'; OC_Config::setValue('dbname', $dbname); OC_Config::setValue('dbhost', $dbhost); OC_Config::setValue('dbtableprefix', $dbtableprefix); //check if the database user has admin right $connection = @mysql_connect($dbhost, $dbuser, $dbpass); if (!$connection) { $error[] = array('error' => 'MySQL username and/or password not valid', 'hint' => 'You need to enter either an existing account or the administrator.'); return $error; } else { $oldUser = OC_Config::getValue('dbuser', false); $query = "SELECT user FROM mysql.user WHERE user='******'"; //this should be enough to check for admin rights in mysql if (mysql_query($query, $connection)) { //use the admin login data for the new database user //add prefix to the mysql user name to prevent collisions $dbusername = substr('oc_' . $username, 0, 16); if ($dbusername != $oldUser) { //hash the password so we don't need to store the admin config in the config file $dbpassword = md5(time() . $password); self::createDBUser($dbusername, $dbpassword, $connection); OC_Config::setValue('dbuser', $dbusername); OC_Config::setValue('dbpassword', $dbpassword); } //create the database self::createDatabase($dbname, $dbusername, $connection); } else { if ($dbuser != $oldUser) { OC_Config::setValue('dbuser', $dbuser); OC_Config::setValue('dbpassword', $dbpass); } //create the database self::createDatabase($dbname, $dbuser, $connection); } //fill the database if needed $query = "select count(*) from information_schema.tables where table_schema='{$dbname}' AND table_name = '{$dbtableprefix}users';"; $result = mysql_query($query, $connection); if ($result) { $row = mysql_fetch_row($result); } if (!$result or $row[0] == 0) { OC_DB::createDbFromStructure('db_structure.xml'); } mysql_close($connection); } } elseif ($dbtype == 'pgsql') { $dbuser = $options['dbuser']; $dbpass = $options['dbpass']; $dbname = $options['dbname']; $dbhost = $options['dbhost']; $dbtableprefix = isset($options['dbtableprefix']) ? $options['dbtableprefix'] : 'oc_'; OC_CONFIG::setValue('dbname', $dbname); OC_CONFIG::setValue('dbhost', $dbhost); OC_CONFIG::setValue('dbtableprefix', $dbtableprefix); $e_host = addslashes($dbhost); $e_user = addslashes($dbuser); $e_password = addslashes($dbpass); //check if the database user has admin right $connection_string = "host='{$e_host}' dbname=postgres user='******' password='******'"; $connection = @pg_connect($connection_string); if (!$connection) { $error[] = array('error' => 'PostgreSQL username and/or password not valid', 'hint' => 'You need to enter either an existing account or the administrator.'); return $error; } else { $e_user = pg_escape_string($dbuser); //check for roles creation rights in postgresql $query = "SELECT 1 FROM pg_roles WHERE rolcreaterole=TRUE AND rolname='{$e_user}'"; $result = pg_query($connection, $query); if ($result and pg_num_rows($result) > 0) { //use the admin login data for the new database user //add prefix to the postgresql user name to prevent collisions $dbusername = '******' . $username; //create a new password so we don't need to store the admin config in the config file $dbpassword = md5(time()); self::pg_createDBUser($dbusername, $dbpassword, $connection); OC_CONFIG::setValue('dbuser', $dbusername); OC_CONFIG::setValue('dbpassword', $dbpassword); //create the database self::pg_createDatabase($dbname, $dbusername, $connection); } else { OC_CONFIG::setValue('dbuser', $dbuser); OC_CONFIG::setValue('dbpassword', $dbpass); //create the database self::pg_createDatabase($dbname, $dbuser, $connection); } // the connection to dbname=postgres is not needed anymore pg_close($connection); // connect to the ownCloud database (dbname=$dbname) an check if it needs to be filled $dbuser = OC_CONFIG::getValue('dbuser'); $dbpass = OC_CONFIG::getValue('dbpassword'); $e_host = addslashes($dbhost); $e_dbname = addslashes($dbname); $e_user = addslashes($dbuser); $e_password = addslashes($dbpass); $connection_string = "host='{$e_host}' dbname='{$e_dbname}' user='******' password='******'"; $connection = @pg_connect($connection_string); if (!$connection) { $error[] = array('error' => 'PostgreSQL username and/or password not valid', 'hint' => 'You need to enter either an existing account or the administrator.'); } else { $query = "select count(*) FROM pg_class WHERE relname='{$dbtableprefix}users' limit 1"; $result = pg_query($connection, $query); if ($result) { $row = pg_fetch_row($result); } if (!$result or $row[0] == 0) { OC_DB::createDbFromStructure('db_structure.xml'); } } } } elseif ($dbtype == 'oci') { $dbuser = $options['dbuser']; $dbpass = $options['dbpass']; $dbname = $options['dbname']; $dbtablespace = $options['dbtablespace']; $dbhost = isset($options['dbhost']) ? $options['dbhost'] : ''; $dbtableprefix = isset($options['dbtableprefix']) ? $options['dbtableprefix'] : 'oc_'; OC_CONFIG::setValue('dbname', $dbname); OC_CONFIG::setValue('dbtablespace', $dbtablespace); OC_CONFIG::setValue('dbhost', $dbhost); OC_CONFIG::setValue('dbtableprefix', $dbtableprefix); $e_host = addslashes($dbhost); $e_dbname = addslashes($dbname); //check if the database user has admin right if ($e_host == '') { $easy_connect_string = $e_dbname; // use dbname as easy connect name } else { $easy_connect_string = '//' . $e_host . '/' . $e_dbname; } $connection = @oci_connect($dbuser, $dbpass, $easy_connect_string); if (!$connection) { $e = oci_error(); $error[] = array('error' => 'Oracle username and/or password not valid', 'hint' => 'You need to enter either an existing account or the administrator.'); return $error; } else { //check for roles creation rights in oracle $query = "SELECT count(*) FROM user_role_privs, role_sys_privs WHERE user_role_privs.granted_role = role_sys_privs.role AND privilege = 'CREATE ROLE'"; $stmt = oci_parse($connection, $query); if (!$stmt) { $entry = 'DB Error: "' . oci_last_error($connection) . '"<br />'; $entry .= 'Offending command was: ' . $query . '<br />'; echo $entry; } $result = oci_execute($stmt); if ($result) { $row = oci_fetch_row($stmt); } if ($result and $row[0] > 0) { //use the admin login data for the new database user //add prefix to the oracle user name to prevent collisions $dbusername = '******' . $username; //create a new password so we don't need to store the admin config in the config file $dbpassword = md5(time() . $dbpass); //oracle passwords are treated as identifiers: // must start with aphanumeric char // needs to be shortened to 30 bytes, as the two " needed to escape the identifier count towards the identifier length. $dbpassword = substr($dbpassword, 0, 30); self::oci_createDBUser($dbusername, $dbpassword, $dbtablespace, $connection); OC_CONFIG::setValue('dbuser', $dbusername); OC_CONFIG::setValue('dbname', $dbusername); OC_CONFIG::setValue('dbpassword', $dbpassword); //create the database not neccessary, oracle implies user = schema //self::oci_createDatabase($dbname, $dbusername, $connection); } else { OC_CONFIG::setValue('dbuser', $dbuser); OC_CONFIG::setValue('dbname', $dbname); OC_CONFIG::setValue('dbpassword', $dbpass); //create the database not neccessary, oracle implies user = schema //self::oci_createDatabase($dbname, $dbuser, $connection); } //FIXME check tablespace exists: select * from user_tablespaces // the connection to dbname=oracle is not needed anymore oci_close($connection); // connect to the oracle database (schema=$dbuser) an check if the schema needs to be filled $dbuser = OC_CONFIG::getValue('dbuser'); //$dbname = OC_CONFIG::getValue('dbname'); $dbpass = OC_CONFIG::getValue('dbpassword'); $e_host = addslashes($dbhost); $e_dbname = addslashes($dbname); if ($e_host == '') { $easy_connect_string = $e_dbname; // use dbname as easy connect name } else { $easy_connect_string = '//' . $e_host . '/' . $e_dbname; } $connection = @oci_connect($dbuser, $dbpass, $easy_connect_string); if (!$connection) { $error[] = array('error' => 'Oracle username and/or password not valid', 'hint' => 'You need to enter either an existing account or the administrator.'); return $error; } else { $query = "SELECT count(*) FROM user_tables WHERE table_name = :un"; $stmt = oci_parse($connection, $query); $un = $dbtableprefix . 'users'; oci_bind_by_name($stmt, ':un', $un); if (!$stmt) { $entry = 'DB Error: "' . oci_last_error($connection) . '"<br />'; $entry .= 'Offending command was: ' . $query . '<br />'; echo $entry; } $result = oci_execute($stmt); if ($result) { $row = oci_fetch_row($stmt); } if (!$result or $row[0] == 0) { OC_DB::createDbFromStructure('db_structure.xml'); } } } } else { //delete the old sqlite database first, might cause infinte loops otherwise if (file_exists("{$datadir}/owncloud.db")) { unlink("{$datadir}/owncloud.db"); } //in case of sqlite, we can always fill the database OC_DB::createDbFromStructure('db_structure.xml'); } //create the user and group try { OC_User::createUser($username, $password); } catch (Exception $exception) { $error[] = $exception->getMessage(); } if (count($error) == 0) { OC_Appconfig::setValue('core', 'installedat', microtime(true)); OC_Appconfig::setValue('core', 'lastupdatedat', microtime(true)); OC_Group::createGroup('admin'); OC_Group::addToGroup($username, 'admin'); OC_User::login($username, $password); //guess what this does OC_Installer::installShippedApps(); //create htaccess files for apache hosts if (isset($_SERVER['SERVER_SOFTWARE']) && strstr($_SERVER['SERVER_SOFTWARE'], 'Apache')) { self::createHtaccess(); } //and we are done OC_Config::setValue('installed', true); } } return $error; }