Update notes about users.

@param array $notes An array of ids for the notes to update.
@return array fail infos.
@since Moodle 2.2
548587
public static function update_notes($notes = array()) {
        global $CFG, $DB;

        $params = self::validate_parameters(self::update_notes_parameters(), array('notes' => $notes));

        // Check if note system is enabled.
        if (!$CFG->enablenotes) {
            throw new moodle_exception('notesdisabled', 'notes');
        }

        $warnings = array();
        foreach ($params['notes'] as $note) {
            $notedetails = note_load($note['id']);
            if (isset($notedetails->id)) {
                // Ensure the current user is allowed to run this function.
                $context = context_course::instance($notedetails->courseid);
                self::validate_context($context);
                require_capability('moodle/notes:manage', $context);

                $dbnote = new stdClass;
                $dbnote->id = $note['id'];
                $dbnote->content = $note['text'];
                $dbnote->format = external_validate_format($note['format']);
                // Get the state ('personal', 'course', 'site').
                switch ($note['publishstate']) {
                    case 'personal':
                        $dbnote->publishstate = NOTES_STATE_DRAFT;
                        break;
                    case 'course':
                        $dbnote->publishstate = NOTES_STATE_PUBLIC;
                        break;
                    case 'site':
                        $dbnote->publishstate = NOTES_STATE_SITE;
                        $dbnote->courseid = SITEID;
                        break;
                    default:
                        $warnings[] = array('item' => 'note',
                                            'itemid' => $note["id"],
                                            'warningcode' => 'badparam',
                                            'message' => 'Provided publishstate incorrect');
                        break;
                }
                if (!note_save($dbnote)) {
                    $warnings[] = array('item' => 'note',
                                        'itemid' => $note["id"],
                                        'warningcode' => 'savedfailed',
                                        'message' => 'Note could not be modified');
                }
            } else {
                $warnings[] = array('item' => 'note',
                                    'itemid' => $note["id"],
                                    'warningcode' => 'badid',
                                    'message' => 'Note does not exist');
            }
        }
        return $warnings;
    }
307567
public function setNotes($value)
    {
        $this->values['notes'] = [];

        if ($value instanceof Note) {
            $value = [$value];
        }

        foreach ($value as $note) {
            if ($note instanceof Note) {
                $note = $note->getValues();
            }

            $this->values['notes'][] = $note;
        }

        return $this;
    }
453543
public function multiUpdate($records)
    {
        $ids = [];

        foreach ($records as $record) {
            try {
                $updatedRecord = $this->update($record);
                $ids[] = $updatedRecord[$this->getIdentifier()];
            } catch (\Throwable $e) {
                // TODO: need to log record that was not updated
                continue;
            }
        }

        return $ids;
    }
1332270
public function update(array $fields = []) {
        $query = new UpdateQuery($this->getTable());
        $query->fields(!empty($fields)? $fields : $this->getFields());
        $query->whereConditionGroup($this->getWhereConditionGroup());
        return $this->connection->exec($query);
    }
1103007
public static function get_course_notes($courseid, $userid = 0) {
        global $CFG, $USER;

        if (empty($CFG->enablenotes)) {
            throw new moodle_exception('notesdisabled', 'notes');
        }

        $warnings = array();
        $arrayparams = array(
            'courseid' => $courseid,
            'userid'   => $userid,
        );
        $params = self::validate_parameters(self::get_course_notes_parameters(), $arrayparams);

        if (empty($params['courseid'])) {
            $params['courseid'] = SITEID;
        }
        $user = null;
        if (!empty($params['userid'])) {
            $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
            core_user::require_active_user($user);
        }

        $course = get_course($params['courseid']);

        $systemcontext = context_system::instance();
        $canmanagesystemnotes = has_capability('moodle/notes:manage', $systemcontext);

        if ($course->id == SITEID) {
            $context = $systemcontext;
            $canmanagecoursenotes = $canmanagesystemnotes;
        } else {
            $context = context_course::instance($course->id);
            $canmanagecoursenotes = has_capability('moodle/notes:manage', $context);
        }
        self::validate_context($context);

        $sitenotes = array();
        $coursenotes = array();
        $personalnotes = array();

        if ($course->id != SITEID) {

            require_capability('moodle/notes:view', $context);
            $sitenotes = self::create_note_list(0, $systemcontext, $params['userid'], NOTES_STATE_SITE);
            $coursenotes = self::create_note_list($course->id, $context, $params['userid'], NOTES_STATE_PUBLIC);
            $personalnotes = self::create_note_list($course->id, $context, $params['userid'], NOTES_STATE_DRAFT,
                                                        $USER->id);
        } else {
            if (has_capability('moodle/notes:view', $context)) {
                $sitenotes = self::create_note_list(0, $context, $params['userid'], NOTES_STATE_SITE);
            }
            // It returns notes only for a specific user!
            if (!empty($user)) {
                $usercourses = enrol_get_users_courses($user->id, true);
                foreach ($usercourses as $c) {
                    // All notes at course level, only if we have capability on every course.
                    if (has_capability('moodle/notes:view', context_course::instance($c->id))) {
                        $coursenotes += self::create_note_list($c->id, $context, $params['userid'], NOTES_STATE_PUBLIC);
                    }
                }
            }
        }

        $results = array(
            'sitenotes'     => $sitenotes,
            'coursenotes'   => $coursenotes,
            'personalnotes' => $personalnotes,
            'canmanagesystemnotes' => $canmanagesystemnotes,
            'canmanagecoursenotes' => $canmanagecoursenotes,
            'warnings'      => $warnings
        );
        return $results;

    }
782591
public static function fix_revision_values(array $versions) {

        $byrev = [];

        foreach ($versions as $version) {
            if ($version->revision === '') {
                $version->revision = userdate($version->timecreated, get_string('strftimedate', 'core_langconfig'));
            }
            $byrev[$version->revision][$version->id] = true;
        }

        foreach ($byrev as $origrevision => $versionids) {
            $cnt = count($byrev[$origrevision]);
            if ($cnt > 1) {
                foreach ($versionids as $versionid => $unused) {
                    foreach ($versions as $version) {
                        if ($version->id == $versionid) {
                            $version->revision = $version->revision.' - v'.$cnt;
                            $cnt--;
                            break;
                        }
                    }
                }
            }
        }
    }
136888
public ResponseWrapper updateFriendsNote(String username, FriendNote[] array)
            throws APIConnectionException, APIRequestException {
        StringUtils.checkUsername(username);
        FriendNotePayload payload = new FriendNotePayload.Builder()
                .setFriendNotes(array)
                .build();
        Preconditions.checkArgument(null != payload, "FriendNotePayload should not be null");
        return _httpClient.sendPut(_baseUrl + userPath + "/" + username + "/friends", payload.toString());
    }
1054153
public function notes($notes = null)
    {
        if (is_null($notes)) {
            return $this->notes;
        }

        $this->notes = $notes;

        return $this;
    }
521184
protected static function create_note_list($courseid, $context, $userid, $state, $author = 0) {
        $results = array();
        $notes = note_list($courseid, $userid, $state, $author);
        foreach ($notes as $key => $note) {
            $note = (array)$note;
            list($note['content'], $note['format']) = external_format_text($note['content'],
                                                                           $note['format'],
                                                                           $context->id,
                                                                           '',
                                                                           '',
                                                                           0);
            $results[$key] = $note;
        }
        return $results;
    }
453976
public function updateMany(array $settings)
    {
        // TODO Use DB::beginTransaction(), DB::rollback(), DB::commit() ?
        foreach ($settings as $k => $v) {
            if ($this->update($k, $v) === false) {
                return false;
            }
        }

        return true;
    }
395729
public function processNotes($contact, $notes)
    {
        $get = function($note) {
            return $note->getId();
        };

        $delete = function($note) use ($contact) {
            $contact->removeNote($note);

            return true;
        };

        $update = function($note, $matchedEntry) {
            return $this->updateNote($note, $matchedEntry);
        };

        $add = function($note) use ($contact) {
            return $this->addNote($contact, $note);
        };

        $entities = $contact->getNotes();

        $result = $this->processSubEntities(
            $entities,
            $notes,
            $get,
            $add,
            $update,
            $delete
        );

        $this->resetIndexOfSubentites($entities);

        return $result;
    }
949396
public function update(array $credentials)
    {
        if (array_key_exists('email', $credentials))
        {
            $this->email = new ValueObjects\Email(strtolower($credentials['email']));
        }

        if (array_key_exists('username', $credentials))
        {
            $this->changeUsername($credentials['username']);
        }

        if (array_key_exists('password', $credentials) && !empty($credentials['password']))
        {
            $this->password = new ValueObjects\Password($credentials['password']);
        }

        if (array_key_exists('firstName', $credentials) || array_key_exists('lastName', $credentials))
        {
            $firstName = array_get($credentials, 'firstName', $this->name->getFirstName());
            $lastName  = array_get($credentials, 'lastName',  $this->name->getLastName());

            $this->changeName($firstName, $lastName);
        }

        if (array_key_exists('permissions', $credentials))
        {
            $this->syncPermissions((array) $credentials['permissions']);
        }
    }
477480
public void setNote(String note) {
       try {
           staticTableHistory.updateNote(historyId, note);
           httpMessageCachedData.setNote(note != null && note.length() > 0);
           notifyEvent(HistoryReferenceEventPublisher.EVENT_NOTE_SET);
       } catch (DatabaseException e) {
           log.error(e.getMessage(), e);
       }
       
   }
533492
static public function updateOrCreateRecords(array $records) {
        $table = static::getInstance();
        $alreadyInTransaction = $table::inTransaction();
        if (!$alreadyInTransaction) {
            $table::beginTransaction();
        }
        try {
            foreach ($records as $record) {
                $success = $table::updateOrCreateRecord($record);
                if (!$success) {
                    if (!$alreadyInTransaction) {
                        $table::rollBackTransaction();
                    }
                    return false;
                }
            }
            if (!$alreadyInTransaction) {
                $table::commitTransaction();
            }
            return true;
        } catch (\Exception $exc) {
            if (!$alreadyInTransaction && $table::inTransaction()) {
                $table::rollBackTransaction();
            }
            /** @noinspection ExceptionsAnnotatingAndHandlingInspection */
            throw $exc;
        }
    }
956909
public function setNotes($v)
    {
        if ($v !== null) {
            $v = (string) $v;
        }

        if ($this->notes !== $v) {
            $this->notes = $v;
            $this->modifiedColumns[] = RemoteAppPeer::NOTES;
        }


        return $this;
    }
327655
public static function update_users($users) {
        global $CFG, $DB, $USER;
        require_once($CFG->dirroot."/user/lib.php");
        require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
        require_once($CFG->dirroot.'/user/editlib.php');

        // Ensure the current user is allowed to run this function.
        $context = context_system::instance();
        require_capability('moodle/user:update', $context);
        self::validate_context($context);

        $params = self::validate_parameters(self::update_users_parameters(), array('users' => $users));

        $filemanageroptions = array('maxbytes' => $CFG->maxbytes,
                'subdirs'        => 0,
                'maxfiles'       => 1,
                'accepted_types' => 'web_image');

        $transaction = $DB->start_delegated_transaction();

        foreach ($params['users'] as $user) {
            // First check the user exists.
            if (!$existinguser = core_user::get_user($user['id'])) {
                continue;
            }
            // Check if we are trying to update an admin.
            if ($existinguser->id != $USER->id and is_siteadmin($existinguser) and !is_siteadmin($USER)) {
                continue;
            }
            // Other checks (deleted, remote or guest users).
            if ($existinguser->deleted or is_mnet_remote_user($existinguser) or isguestuser($existinguser->id)) {
                continue;
            }
            // Check duplicated emails.
            if (isset($user['email']) && $user['email'] !== $existinguser->email) {
                if (!validate_email($user['email'])) {
                    continue;
                } else if (empty($CFG->allowaccountssameemail)) {
                    // Make a case-insensitive query for the given email address and make sure to exclude the user being updated.
                    $select = $DB->sql_equal('email', ':email', false) . ' AND mnethostid = :mnethostid AND id <> :userid';
                    $params = array(
                        'email' => $user['email'],
                        'mnethostid' => $CFG->mnet_localhost_id,
                        'userid' => $user['id']
                    );
                    // Skip if there are other user(s) that already have the same email.
                    if ($DB->record_exists_select('user', $select, $params)) {
                        continue;
                    }
                }
            }

            user_update_user($user, true, false);

            $userobject = (object)$user;

            // Update user picture if it was specified for this user.
            if (empty($CFG->disableuserimages) && isset($user['userpicture'])) {
                $userobject->deletepicture = null;

                if ($user['userpicture'] == 0) {
                    $userobject->deletepicture = true;
                } else {
                    $userobject->imagefile = $user['userpicture'];
                }

                core_user::update_picture($userobject, $filemanageroptions);
            }

            // Update user interests.
            if (!empty($user['interests'])) {
                $trimmedinterests = array_map('trim', explode(',', $user['interests']));
                $interests = array_filter($trimmedinterests, function($value) {
                    return !empty($value);
                });
                useredit_update_interests($userobject, $interests);
            }

            // Update user custom fields.
            if (!empty($user['customfields'])) {

                foreach ($user['customfields'] as $customfield) {
                    // Profile_save_data() saves profile file it's expecting a user with the correct id,
                    // and custom field to be named profile_field_"shortname".
                    $user["profile_field_".$customfield['type']] = $customfield['value'];
                }
                profile_save_data((object) $user);
            }

            // Trigger event.
            \core\event\user_updated::create_from_userid($user['id'])->trigger();

            // Preferences.
            if (!empty($user['preferences'])) {
                $userpref = clone($existinguser);
                foreach ($user['preferences'] as $preference) {
                    $userpref->{'preference_'.$preference['type']} = $preference['value'];
                }
                useredit_update_user_preference($userpref);
            }
            if (isset($user['suspended']) and $user['suspended']) {
                \core\session\manager::kill_user_sessions($user['id']);
            }
        }

        $transaction->allow_commit();

        return null;
    }
85694
public function updateAverageNote()
    {
        $commentTableName = $this->em->getClassMetadata($this->commentManager->getClass())->table['name'];
        $threadTableName = $this->em->getClassMetadata($this->getClass())->table['name'];

        $this->em->getConnection()->beginTransaction();
        $this->em->getConnection()->query(sprintf('UPDATE %s t SET t.average_note = 0', $threadTableName));

        $this->em->getConnection()->query(sprintf(
            'UPDATE %s t, (SELECT c.thread_id, avg(c.note) as avg_note FROM %s as c WHERE c.private <> 1 GROUP BY c.thread_id) as comments_note
            SET t.average_note = comments_note.avg_note
            WHERE t.id = comments_note.thread_id
            AND t.is_commentable <> 0', $threadTableName, $commentTableName));

        $this->em->getConnection()->commit();
    }