Insert platform-owner user

@return  int
768284
protected function insertPlatformOwner()
    {
        $data  = $this->getPatchData();
        $email = $data->get(
            'gridguyz-core',
            'platformOwner-email',
            'Type the platform owner\'s email (must be valid email)',
            null,
            '/^[A-Z0-9\._%\+-]+@[A-Z0-9\.-]+\.[A-Z]{2,4}$/i',
            3
        );

        $displayName = $data->get(
            'gridguyz-core',
            'platformOwner-displayName',
            'Type the platform owner\'s display name',
            strstr( $email, '@', true )
        );

        $password = $data->get(
            'gridguyz-core',
            'platformOwner-password',
            'Type the platform owner\'s password',
            $this->createPasswordSalt( 6 ),
            true
        );

        return $this->insertIntoTable(
            'user',
            array(
                'email'         => $email,
                'displayName'   => $displayName,
                'passwordHash'  => $this->createPasswordHash( $password ),
                'groupId'       => static::SITE_OWNER_GROUP,
                'state'         => 'active',
                'confirmed'     => 't',
                'locale'        => 'en',
            ),
            true
        );
    }
282018
public function add()
    {
        if (!$this->request->is(['get', 'post'])) {
            throw new MethodNotAllowedException();
        }

        /** @var User $user */
        $user = $this->Users->newEntity(null, ['associated' => 'Groups']);

        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->data, ['associated' => 'Groups']);
            $user->set('password', Text::uuid());

            if ($this->Users->save($user, ['associated' => 'Groups'])) {
                $this->Users->Tokens->invalidateExistingTokens($user->id, TokensTable::TYPE_EMAIL_VERIFICATION);
                $token = $this->Users->Tokens->generateToken($user, TokensTable::TYPE_EMAIL_VERIFICATION);
                $this->getMailer('Wasabi/Core.User')->send('verifyAndResetPasswordEmail', [$user, $token]);
                $this->Flash->success(__d('pb', 'The user <strong>{0}</strong> has been created.', $user->fullName()));
                $this->redirect(['action' => 'index']);
                return;
            } else {
                $this->Flash->error($this->formErrorMessage);
            }
        }

        $groups = $this->Users->Groups->find('list')->order('id ASC');

        // users that are no admin, may not select the super admin group
        if (Wasabi::user()->hasAccessLevel(Permission::OWN)) {
            $groups->where(['id <>' => 1]);
        }

        $this->set([
            'user' => $user,
            'groups' => $groups,
            'languages' => Hash::map(Configure::read('languages.backend'), '{n}', function ($language) {
                return [
                    'value' => $language->id,
                    'text' => $language->name
                ];
            })
        ]);
    }
374541
public static function guest(): user {
		self::check();
		$userdbname = setup::getValidation("username");

		return new self("", R::findOne('user', ' ' . $userdbname . ' = ? ', ["guest"]));
	}
1007810
protected function _insert()
    {
        // set oxcreate
        $sNow = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime());
        $this->oxremark__oxcreate = new \OxidEsales\Eshop\Core\Field($sNow, \OxidEsales\Eshop\Core\Field::T_RAW);
        $this->oxremark__oxheader = new \OxidEsales\Eshop\Core\Field($sNow, \OxidEsales\Eshop\Core\Field::T_RAW);

        return parent::_insert();
    }
537838
protected function runInsertSudoerProcess() 
    {
        if (!$this->input->getOption('user_name') || !$this->input->getOption('user_password') || !$this->input->getOption('user_email')) {
            $this->output->writeln('<info>You have to specify all option in order to insert a new superadmin user (--user_name, --user_password, --user_email)</info>');
            return $this;
        }

        # Check if user already exists in db
        if (null === $adminUser = $this->entyMgr
                        ->getRepository('BackBee\Security\User')
                        ->findOneBy(array('_login' => $this->input->getOption('user_name')))) {
            $adminUser = $this->createUser(
                            $this->input->getOption('user_name'),
                            $this->input->getOption('user_password'),
                            $this->input->getOption('user_email')
                        );
            $this->output->writeln('<info>New user created.</info>');
        }

        # Recreate security.yml
        $securityConf = $this->bbapp->getConfig()->getSecurityConfig();
        if (!array_key_exists($adminUser->getLogin(), $securityConf['sudoers'])) {
            $securityConf['sudoers'][$adminUser->getLogin()] = $adminUser->getId();

            file_put_contents(
                $this->bbapp->getBaseDir().DIRECTORY_SEPARATOR.'repository/Config/security.yml',
                Yaml::dump($securityConf)
            );

            $this->output->writeln('<info>User added in security.yml file.</info>');
        }

        return $this;
    }
1154597
private function complete_change_owner() {
            $this->_logger->entrance();

            $site_result = $this->get_api_site_scope( true )->get();
            $site        = new FS_Site( $site_result );
            $this->_site = $site;

            $user     = new FS_User();
            $user->id = fs_request_get( 'user_id' );

            // Validate install's user and given user.
            if ( $user->id != $this->_site->user_id ) {
                return false;
            }

            $user->public_key = fs_request_get( 'user_public_key' );
            $user->secret_key = fs_request_get( 'user_secret_key' );

            // Fetch new user information.
            $this->_user = $user;
            $user_result = $this->get_api_user_scope( true )->get();
            $user        = new FS_User( $user_result );
            $this->_user = $user;

            $this->_set_account( $user, $site );

            return true;
        }
301396
function insert()
    {
        $item = array();
        $item['owner'] = arg('owner', 'int');
        $item['name'] = arg('name', '/[^a-z0-9_]/i');
        $item['title'] = arg('title', 'dbsafe');
        $item['caption'] = arg('caption', 'dbsafe');
        $item['description'] = arg('description', 'dbsafe');
        $item['hint'] = arg('hint', 'dbsafe');
        $item['keywords'] = arg('keywords', 'dbsafe');
        $item['template'] = arg('template', 'dbsafe');
        $item['type'] = arg('type', 'dbsafe');
        $item['active'] = arg('active', 'int');
        $item['visible'] = arg('visible', 'int');
        $item['access'] = arg('access', 'int');
        $item['position'] = arg('position', 'int');
        $item['options'] = arg('options');
        $item['created'] = $item['updated'] = gettime('Y-m-d H:i:s');

        $temp = Eresus_CMS::getLegacyKernel()->sections->get("(`name`='" . $item['name'] .
        "') AND (`owner`='" . $item['owner'] . "')");
        if (count($temp) == 0)
        {
            Eresus_CMS::getLegacyKernel()->sections->add($item);
            dbReorderItems('pages', "`owner`='".arg('owner', 'int')."'");
            HTTP::redirect(Eresus_Kernel::app()->getPage()->url(array('id'=>'')));
        }
        else
        {
            Eresus_Kernel::app()->getPage()->addErrorMessage(
                sprintf(errItemWithSameName, $item['name']));
            saveRequest();
            HTTP::redirect(Eresus_CMS::getLegacyKernel()->request['referer']);
        }
    }
39274
protected function _insert()
    {

        // set oxcreate date
        $this->oxuser__oxcreate = new \OxidEsales\Eshop\Core\Field(date('Y-m-d H:i:s'), \OxidEsales\Eshop\Core\Field::T_RAW);

        if (!isset($this->oxuser__oxboni->value)) {
            $this->oxuser__oxboni = new \OxidEsales\Eshop\Core\Field($this->getBoni(), \OxidEsales\Eshop\Core\Field::T_RAW);
        }

        return parent::_insert();
    }
66017
public function createUser()
    {
        $oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();
        $sShopID = \OxidEsales\Eshop\Core\Registry::getConfig()->getShopId();

        // check if user exists AND there is no password - in this case we update otherwise we try to insert
        $sSelect = "select oxid from oxuser where oxusername = " . $oDb->quote($this->oxuser__oxusername->value) . " and oxpassword = '' ";
        if (!$this->_blMallUsers) {
            $sSelect .= " and oxshopid = '{$sShopID}' ";
        }
        // We force reading from master to prevent issues with slow replications or open transactions (see ESDEV-3804).
        $masterDb = \OxidEsales\Eshop\Core\DatabaseProvider::getMaster();
        $oldUserId = $masterDb->getOne($sSelect);

        if ($oldUserId) {
            $this->delete($oldUserId);
        } elseif ($this->_blMallUsers) {
            // must be sure if there is no duplicate user
            $sQ = "select oxid from oxuser where oxusername = " . $oDb->quote($this->oxuser__oxusername->value) . " and oxusername != '' ";
            // We force reading from master to prevent issues with slow replications or open transactions (see ESDEV-3804).
            if ($masterDb->getOne($sQ)) {
                /** @var UserException $oEx */
                $oEx = oxNew(UserException::class);
                $oLang = Registry::getLang();
                $oEx->setMessage(sprintf($oLang->translateString('ERROR_MESSAGE_USER_USEREXISTS', $oLang->getTplLanguage()), $this->oxuser__oxusername->value));
                throw $oEx;
            }
        }

        $this->oxuser__oxshopid = new Field($sShopID, Field::T_RAW);

        $newUserId = $this->save();
        if ($newUserId === false) {
            throw oxNew(UserException::class, 'ERROR_MESSAGE_USER_USERCREATIONFAILED');
        } else {
            // @TODO the following statements make no sense and should be removed: oxuser__oxid is freshly created and the conditions will never match
            // dropping/cleaning old delivery address/payment info
            $oDb->execute("delete from oxaddress where oxaddress.oxuserid = " . $oDb->quote($this->oxuser__oxid->value));
            $oDb->execute("update oxuserpayments set oxuserpayments.oxuserid = " . $oDb->quote($this->oxuser__oxusername->value) . " where oxuserpayments.oxuserid = " . $oDb->quote($this->oxuser__oxid->value));
        }

        return $newUserId;
    }
272850
public function getNumLoggedIn()
     {

        // Snag command line of every process in system
        $procs = glob('/proc/*/cmdline', GLOB_NOSORT);

        // Store unqiue users here
        $users = [];

        // Each process
        foreach ($procs as $proc) {

            // Does the process match a popular shell, such as bash, csh, etc?
            if (preg_match('/(?:bash|csh|zsh|ksh)$/', Common::getContents($proc, ''))) {

                // Who owns it, anyway?
                $owner = fileowner(dirname($proc));

                // Careful..
                if (!is_numeric($owner)) {
                    continue;
                }

                // Have we not seen this user before?
                if (!in_array($owner, $users)) {
                    $users[] = $owner;
                }
            }
        }

        // Give number of unique users with shells running
        return count($users);
     }
1155214
protected function insert()
    {
        $aggregate = $this->aggregate;

        $attributes = $aggregate->getRawAttributes();

        $keyName = $aggregate->getEntityMap()->getKeyName();

        // Check if the primary key is defined in the attributes
        if (array_key_exists($keyName, $attributes) && $attributes[$keyName] != null) {
            $this->query->insert($attributes);
        } else {
            // Prevent inserting with a null ID
            if (array_key_exists($keyName, $attributes)) {
                unset($attributes[$keyName]);
            }

            if (isset($attributes['attributes'])) {
                unset($attributes['attributes']);
            }

            $id = $this->query->insertGetId($attributes, $keyName);

            $aggregate->setEntityAttribute($keyName, $id);
        }
    }
239300
public function execute() {
        global $DB;

        $userid = $this->get_custom_data()->userid;

        // Get the user's preference.
        $hasbeenmigrated = get_user_preferences('core_message_migrate_data', false, $userid);

        if (!$hasbeenmigrated) {
            // To determine if we should update the preference.
            $updatepreference = true;

            // Get all the users the current user has received a message from.
            $sql = "SELECT DISTINCT(useridfrom)
                      FROM {message} m
                     WHERE useridto = ?
                     UNION
                    SELECT DISTINCT(useridfrom)
                      FROM {message_read} m
                     WHERE useridto = ?";
            $users = $DB->get_records_sql($sql, [$userid, $userid]);

            // Get all the users the current user has messaged.
            $sql = "SELECT DISTINCT(useridto)
                      FROM {message} m
                     WHERE useridfrom = ?
                     UNION
                    SELECT DISTINCT(useridto)
                      FROM {message_read} m
                     WHERE useridfrom = ?";
            $users = $users + $DB->get_records_sql($sql, [$userid, $userid]);
            if (!empty($users)) {
                // Loop through each user and migrate the data.
                foreach ($users as $otheruserid => $user) {
                    $ids = [$userid, $otheruserid];
                    sort($ids);
                    $key = implode('_', $ids);

                    // Set the lock data.
                    $timeout = 5; // In seconds.
                    $locktype = 'core_message_migrate_data';

                    // Get an instance of the currently configured lock factory.
                    $lockfactory = \core\lock\lock_config::get_lock_factory($locktype);

                    // See if we can grab this lock.
                    if ($lock = $lockfactory->get_lock($key, $timeout)) {
                        try {
                            $transaction = $DB->start_delegated_transaction();
                            $this->migrate_data($userid, $otheruserid);
                            $transaction->allow_commit();
                        } catch (\Throwable $e) {
                            throw $e;
                        } finally {
                            $lock->release();
                        }
                    } else {
                        // Couldn't get a lock, move on to next user but make sure we don't update user preference so
                        // we still try again.
                        $updatepreference = false;
                        continue;
                    }
                }
            }

            if ($updatepreference) {
                set_user_preference('core_message_migrate_data', true, $userid);
            } else {
                // Throwing an exception in the task will mean that it isn't removed from the queue and is tried again.
                throw new \moodle_exception('Task failed.');
            }
        }
    }
166567
private function insert()
    {
        $insert = $this->dsql();

        // Performs the actual database changes. Throw exception if problem occurs
        foreach ($this->elements as $name => $f) {
            if ($f instanceof Field) {
                if (!$f->editable() && !$f->system()) {
                    continue;
                }
                if (!isset($this->dirty[$name]) && $f->defaultValue() === null) {
                    continue;
                }

                $f->updateInsertQuery($insert);
            }
        }
        $this->hook('beforeInsert', array(&$insert));
        //delayed is not supported by INNODB, but what's worse - it shows error.
        //if($this->_save_as===false)$insert->option_insert('delayed');
        $id = $insert->insert();
        if ($id == 0) {
            // no auto-increment column present
            $id = $this->get($this->id_field);

            if ($id === null && $this->_save_as !== false) {
                throw $this->exception('Please add auto-increment ID column to your table or specify ID manually');
            }
        }
        $res = $this->hook('afterInsert', array($id));
        if ($res === false) {
            return $this;
        }

        if ($this->_save_as === false) {
            return $this->unload();
        }
        if ($this->_save_as) {
            $this->unload();
        }
        $o = $this->_save_as ?: $this;

        if ($this->fast && !$this->_save_as) {
            $this[$this->id_field] = $this->id = $id;

            return $this;
        }
        $res = $o->tryLoad($id);
        if (!$res->loaded()) {
            throw $this->exception('Saved model did not match conditions. Save aborted.');
        }

        return $res;
    }
773430
public function getAdminCount()
    {
        $oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();

        $sQuery = "SELECT COUNT(1) FROM oxuser WHERE oxrights != 'user'";

        return (int) $oDb->getOne($sQuery);
    }
969018
protected function addDoInsertBodyRaw()
    {
        $this->declareClasses('Propel', 'PDO');
        $table = $this->getTable();
        $peerClassname = $this->getPeerClassname();
        $platform = $this->getPlatform();
        $primaryKeyMethodInfo = '';
        if ($table->getIdMethodParameters()) {
            $params = $table->getIdMethodParameters();
            $imp = $params[0];
            $primaryKeyMethodInfo = $imp->getValue();
        } elseif ($table->getIdMethod() == IDMethod::NATIVE && ($platform->getNativeIdMethod() == PropelPlatformInterface::SEQUENCE || $platform->getNativeIdMethod() == PropelPlatformInterface::SERIAL)) {
            $primaryKeyMethodInfo = $platform->getSequenceName($table);
        }
        $query = 'INSERT INTO ' . $platform->quoteIdentifier($table->getName()) . ' (%s) VALUES (%s)';
        $script = "
        \$modifiedColumns = array();
        \$index = 0;
";

        foreach ($table->getPrimaryKey() as $column) {
            if (!$column->isAutoIncrement()) {
                continue;
            }
            $constantName = $this->getColumnConstant($column);
            if ($platform->supportsInsertNullPk()) {
                $script .= "
        \$this->modifiedColumns[] = $constantName;";
            }
            $columnProperty = strtolower($column->getName());
            if (!$table->isAllowPkInsert()) {
                $script .= "
        if (null !== \$this->{$columnProperty}) {
            throw new PropelException('Cannot insert a value for auto-increment primary key (' . $constantName . ')');
        }";
            } elseif (!$platform->supportsInsertNullPk()) {
                $script .= "
        // add primary key column only if it is not null since this database does not accept that
        if (null !== \$this->{$columnProperty}) {
            \$this->modifiedColumns[] = $constantName;
        }";
            }
        }

        // if non auto-increment but using sequence, get the id first
        if (!$platform->isNativeIdMethodAutoIncrement() && $table->getIdMethod() == "native") {
            $column = $table->getFirstPrimaryKeyColumn();
            $columnProperty = strtolower($column->getName());
            $script .= "
        if (null === \$this->{$columnProperty}) {
            try {";
            $script .= $platform->getIdentifierPhp('$this->' . $columnProperty, '$con', $primaryKeyMethodInfo, '				');
            $script .= "
            } catch (Exception \$e) {
                throw new PropelException('Unable to get sequence id.', \$e);
            }
        }
";
        }

        $script .= "

         // check the columns in natural order for more readable SQL queries";
        foreach ($table->getColumns() as $column) {
            $constantName = $this->getColumnConstant($column);
            $identifier = var_export($platform->quoteIdentifier($column->getName()), true);
            $script .= "
        if (\$this->isColumnModified($constantName)) {
            \$modifiedColumns[':p' . \$index++]  = $identifier;
        }";
        }

        $script .= "

        \$sql = sprintf(
            '$query',
            implode(', ', \$modifiedColumns),
            implode(', ', array_keys(\$modifiedColumns))
        );

        try {
            \$stmt = \$con->prepare(\$sql);
            foreach (\$modifiedColumns as \$identifier => \$columnName) {
                switch (\$columnName) {";
        foreach ($table->getColumns() as $column) {
            $columnNameCase = var_export($platform->quoteIdentifier($column->getName()), true);
            $script .= "
                    case $columnNameCase:";
            $script .= $platform->getColumnBindingPHP($column, "\$identifier", '$this->' . strtolower($column->getName()), '						');
            $script .= "
                        break;";
        }
        $script .= "
                }
            }
            \$stmt->execute();
        } catch (Exception \$e) {
            Propel::log(\$e->getMessage(), Propel::LOG_ERR);
            throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', \$sql), \$e);
        }
";

        // if auto-increment, get the id after
        if ($platform->isNativeIdMethodAutoIncrement() && $table->getIdMethod() == "native") {
            $column = $table->getFirstPrimaryKeyColumn();
            $columnProperty = strtolower($column->getName());
            $script .= "
        try {";
            $script .= $platform->getIdentifierPhp('$pk', '$con', $primaryKeyMethodInfo);
            $script .= "
        } catch (Exception \$e) {
            throw new PropelException('Unable to get autoincrement id.', \$e);
        }";
            if ($table->isAllowPkInsert()) {
                $script .= "
        if (\$pk !== null) {
            \$this->set" . $column->getPhpName() . "(\$pk);
        }";
            } else {
                $script .= "
        \$this->set" . $column->getPhpName() . "(\$pk);";
            }
            $script .= "
";
        }

        return $script;
    }
1065469
public function addSitePrivileges()
    {
        if ($this->addSitePrivilegeStatement == null) {
            $this->addSitePrivilegeStatement = $this->connection->prepare("
              INSERT INTO UserPrivileges (username, rootPrivileges, sitePrivileges, pageId) VALUES (?,0,1,NULL)");
        }
        $this->addSitePrivilegeStatement->execute(array($this->user->getUsername()));
        $this->sitePrivilege = 1;
    }
446394
public function add()
    {
        $user = $this->Users->newEntity();

        $user->accessible('role_id', true); // the role_id field should be accessible
        $user->accessible('active', true); // the active field should be accessible
        $user->accessible('send_mail', true); // checkbox to send an e-mail

        $roles = $this->Users->Roles->find('list');

        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->data);

            if (!$user->get('active')) {
                $user->set('activation_key', $this->Users->generateActivationKey());
            }

            if ($this->Users->save($user)) {
                // firing an event: afterRegister
                $_event = new Event('Controller.Users.afterRegister', $this, [
                    'user' => $user,
                    'sendMail' => $user->send_mail
                ]);
                $this->eventManager()->dispatch($_event);
                $this->Flash->success(__('The user has been saved.'));
                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The user could not be saved. Please, try again.'));
            }
        }

        $customFields = Hash::normalize(Configure::read('CM.UserFields'));

        $this->set(compact('user', 'roles', 'customFields'));

        $this->render(Configure::read('CM.AdminUserViews.add'));
    }