Download a zip file of all assignment submissions.

@param array $userids Array of user ids to download assignment submissions in a zip file
@return string - If an error occurs, this will contain the error page.
485217
protected function download_submissions($userids = false) {
        global $CFG, $DB;

        // More efficient to load this here.
        require_once($CFG->libdir.'/filelib.php');

        // Increase the server timeout to handle the creation and sending of large zip files.
        core_php_time_limit::raise();

        $this->require_view_grades();

        // Load all users with submit.
        $students = get_enrolled_users($this->context, "mod/assign:submit", null, 'u.*', null, null, null,
                        $this->show_only_active_users());

        // Build a list of files to zip.
        $filesforzipping = array();
        $fs = get_file_storage();

        $groupmode = groups_get_activity_groupmode($this->get_course_module());
        // All users.
        $groupid = 0;
        $groupname = '';
        if ($groupmode) {
            $groupid = groups_get_activity_group($this->get_course_module(), true);
            if (!empty($groupid)) {
                $groupname = groups_get_group_name($groupid) . '-';
            }
        }

        // Construct the zip file name.
        $filename = clean_filename($this->get_course()->shortname . '-' .
                                   $this->get_instance()->name . '-' .
                                   $groupname.$this->get_course_module()->id . '.zip');

        // Get all the files for each student.
        foreach ($students as $student) {
            $userid = $student->id;
            // Download all assigments submission or only selected users.
            if ($userids and !in_array($userid, $userids)) {
                continue;
            }

            if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
                // Get the plugins to add their own files to the zip.

                $submissiongroup = false;
                $groupname = '';
                if ($this->get_instance()->teamsubmission) {
                    $submission = $this->get_group_submission($userid, 0, false);
                    $submissiongroup = $this->get_submission_group($userid);
                    if ($submissiongroup) {
                        $groupname = $submissiongroup->name . '-';
                    } else {
                        $groupname = get_string('defaultteam', 'assign') . '-';
                    }
                } else {
                    $submission = $this->get_user_submission($userid, false);
                }

                if ($this->is_blind_marking()) {
                    $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
                    $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid));
                } else {
                    $prefix = str_replace('_', ' ', $groupname . fullname($student));
                    $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid));
                }

                if ($submission) {
                    $downloadasfolders = get_user_preferences('assign_downloadasfolders', 1);
                    foreach ($this->submissionplugins as $plugin) {
                        if ($plugin->is_enabled() && $plugin->is_visible()) {
                            if ($downloadasfolders) {
                                // Create a folder for each user for each assignment plugin.
                                // This is the default behavior for version of Moodle >= 3.1.
                                $submission->exportfullpath = true;
                                $pluginfiles = $plugin->get_files($submission, $student);
                                foreach ($pluginfiles as $zipfilepath => $file) {
                                    $subtype = $plugin->get_subtype();
                                    $type = $plugin->get_type();
                                    $zipfilename = basename($zipfilepath);
                                    $prefixedfilename = clean_filename($prefix .
                                                                       '_' .
                                                                       $subtype .
                                                                       '_' .
                                                                       $type .
                                                                       '_');
                                    if ($type == 'file') {
                                        $pathfilename = $prefixedfilename . $file->get_filepath() . $zipfilename;
                                    } else if ($type == 'onlinetext') {
                                        $pathfilename = $prefixedfilename . '/' . $zipfilename;
                                    } else {
                                        $pathfilename = $prefixedfilename . '/' . $zipfilename;
                                    }
                                    $pathfilename = clean_param($pathfilename, PARAM_PATH);
                                    $filesforzipping[$pathfilename] = $file;
                                }
                            } else {
                                // Create a single folder for all users of all assignment plugins.
                                // This was the default behavior for version of Moodle < 3.1.
                                $submission->exportfullpath = false;
                                $pluginfiles = $plugin->get_files($submission, $student);
                                foreach ($pluginfiles as $zipfilename => $file) {
                                    $subtype = $plugin->get_subtype();
                                    $type = $plugin->get_type();
                                    $prefixedfilename = clean_filename($prefix .
                                                                       '_' .
                                                                       $subtype .
                                                                       '_' .
                                                                       $type .
                                                                       '_' .
                                                                       $zipfilename);
                                    $filesforzipping[$prefixedfilename] = $file;
                                }
                            }
                        }
                    }
                }
            }
        }
        $result = '';
        if (count($filesforzipping) == 0) {
            $header = new assign_header($this->get_instance(),
                                        $this->get_context(),
                                        '',
                                        $this->get_course_module()->id,
                                        get_string('downloadall', 'assign'));
            $result .= $this->get_renderer()->render($header);
            $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
            $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
                                                                    'action'=>'grading'));
            $result .= $this->get_renderer()->continue_button($url);
            $result .= $this->view_footer();
        } else if ($zipfile = $this->pack_files($filesforzipping)) {
            \mod_assign\event\all_submissions_downloaded::create_from_assign($this)->trigger();
            // Send file and delete after sending.
            send_temp_file($zipfile, $filename);
            // We will not get here - send_temp_file calls exit.
        }
        return $result;
    }
799443
protected static function export_user_data_in_user_contexts($userid, array $contexts) {
        global $DB;

        $mycontext = context_user::instance($userid);
        $contextids = array_map(function($context) {
            return $context->id;
        }, $contexts);
        $exportowncontext = in_array($mycontext->id, $contextids);
        $othercontexts = array_filter($contextids, function($contextid) use ($mycontext) {
            return $contextid != $mycontext->id;
        });

        if ($exportowncontext) {
            static::export_user_data_learning_plans($mycontext);
            static::export_user_data_competencies($mycontext);
            static::export_user_data_user_evidence($mycontext);
        }

        foreach ($othercontexts as $contextid) {
            static::export_user_data_learning_plans_related_to_me($userid, context::instance_by_id($contextid));
            static::export_user_data_competencies_related_to_me($userid, context::instance_by_id($contextid));
            static::export_user_data_user_evidence_related_to_me($userid, context::instance_by_id($contextid));
        }
    }
753645
public static function find_ongoing_request_types_for_users(array $userids) : array {
        global $DB;

        if (empty($userids)) {
            return [];
        }

        // Check if the user already has an incomplete data request of the same type.
        $nonpendingstatuses = [
            self::DATAREQUEST_STATUS_COMPLETE,
            self::DATAREQUEST_STATUS_CANCELLED,
            self::DATAREQUEST_STATUS_REJECTED,
            self::DATAREQUEST_STATUS_DOWNLOAD_READY,
            self::DATAREQUEST_STATUS_EXPIRED,
            self::DATAREQUEST_STATUS_DELETED,
        ];
        list($statusinsql, $statusparams) = $DB->get_in_or_equal($nonpendingstatuses, SQL_PARAMS_NAMED, 'st', false);
        list($userinsql, $userparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'us');

        $select = "userid {$userinsql} AND status {$statusinsql}";
        $params = array_merge($statusparams, $userparams);

        $requests = $DB->get_records_select(data_request::TABLE, $select, $params, 'userid', 'id, userid, type');

        $returnval = [];
        foreach ($userids as $userid) {
            $returnval[$userid] = (object) [];
        }

        foreach ($requests as $request) {
            $returnval[$request->userid]->{$request->type} = true;
        }

        return $returnval;
    }
1093979
protected function _getToken($userId = null) {
        if ($userId
            && $this->_getAuthVars()
            && array_get($this->_getAuthVars()->toArray(), 'reuse_existing_token')
        ) {
            return $this->_fetchExistingToken($userId) ?: $this->_getToken();
        }
        if (function_exists('openssl_random_pseudo_bytes')) {
            return bin2hex(openssl_random_pseudo_bytes(32));
        }
        return mt_rand();
    }
209084
public function revert_to_draft($userid) {
        global $DB, $USER;

        // Need grade permission.
        require_capability('mod/assign:grade', $this->context);

        if ($this->get_instance()->teamsubmission) {
            $submission = $this->get_group_submission($userid, 0, false);
        } else {
            $submission = $this->get_user_submission($userid, false);
        }

        if (!$submission) {
            return false;
        }
        $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
        $this->update_submission($submission, $userid, false, $this->get_instance()->teamsubmission);

        // Give each submission plugin a chance to process the reverting to draft.
        $plugins = $this->get_submission_plugins();
        foreach ($plugins as $plugin) {
            if ($plugin->is_enabled() && $plugin->is_visible()) {
                $plugin->revert_to_draft($submission);
            }
        }
        // Update the modified time on the grade (grader modified).
        $grade = $this->get_user_grade($userid, true);
        $grade->grader = $USER->id;
        $this->update_grade($grade);

        $completion = new completion_info($this->get_course());
        if ($completion->is_enabled($this->get_course_module()) &&
                $this->get_instance()->completionsubmit) {
            $completion->update_state($this->get_course_module(), COMPLETION_INCOMPLETE, $userid);
        }
        \mod_assign\event\submission_status_updated::create_from_submission($this, $submission)->trigger();
        return true;
    }
1142776
public function toUserId($userIds)
    {
        $userIds = is_string($userIds) || is_integer($userIds) ? func_get_args() : $userIds;

        foreach ($userIds as $userId) {
            $fds = $this->room->getClients(static::USER_PREFIX . $userId);
            $this->to($fds);
        }

        return $this;
    }
430509
private static function get_files($assignment, $userid, $attemptnumber, $filearea, $filepath = '/') {
        $grade = $assignment->get_user_grade($userid, true, $attemptnumber);
        $itemid = $grade->id;
        $contextid = $assignment->get_context()->id;
        $component = self::COMPONENT;
        $fs = get_file_storage();
        $files = $fs->get_directory_files($contextid, $component, $filearea, $itemid, $filepath);
        return $files;
    }
200004
public function GetCards($userId, & $pagination = null, $sorting = null)
    {
        return $this->GetList('users_allcards', $pagination, '\MangoPay\Card', $userId, null, $sorting);
    }
1202168
private static function generateUserCacheData( $userId )
    {
        $user = eZUser::fetch( $userId );
        if ( !$user instanceof eZUser )
        {
            return null;
        }

        // user info (session: eZUserInfoCache)
        $data['info'][$userId] = array( 'contentobject_id'   => $user->attribute( 'contentobject_id' ),
                                        'login'              => $user->attribute( 'login' ),
                                        'email'              => $user->attribute( 'email' ),
                                        'is_enabled'         => $user->isEnabled( false ),
                                        'password_hash'      => $user->attribute( 'password_hash' ),
                                        'password_hash_type' => $user->attribute( 'password_hash_type' ) );

        // function groups relies on caching. The function generateUserCacheData relies on function groups.
        // To avoid an infinitive loop, the code is disabling caching in function generateUserCacheData.
        // At the end of this method flag is set to previous value again
        $previousCachingState = $user->setCachingEnabled( false );
        // user groups list (session: eZUserGroupsCache)
        $groups = $user->groups(); 
        $data['groups'] = $groups;

        // role list (session: eZRoleIDList)
        $groups[] = $userId;
        $data['roles'] = eZRole::fetchIDListByUser( $groups );

        // role limitation list (session: eZRoleLimitationValueList)
        $limitList = $user->limitList();
        foreach ( $limitList as $limit )
        {
            $data['role_limitations'][] = $limit['limit_value'];
        }

        // access array (session: AccessArray)
        $data['access_array'] = $user->generateAccessArray();

        // discount rules (session: eZUserDiscountRules<userId>)
        $data['discount_rules'] = eZUserDiscountRule::generateIDListByUserID( $userId );

        $user->setCachingEnabled( $previousCachingState );

        return $data;
    }
953173
public function get($userId)
    {
        $endpoint = '/admin/users/'.$userId.'.json';
        $response = $this->request($endpoint);
        return $this->createObject(User::class, $response['user']);
    }
540084
protected function getBucketingId($userId, $userAttributes)
    {
        $bucketingIdKey = ControlAttributes::BUCKETING_ID;

        if (isset($userAttributes[$bucketingIdKey])) {
            if (is_string($userAttributes[$bucketingIdKey])) {
                return $userAttributes[$bucketingIdKey];
            }
            $this->_logger->log(Logger::WARNING, 'Bucketing ID attribute is not a string. Defaulted to user ID.');
        }
        return $userId;
    }
311425
public static function get_expired_requests($userid = 0) {
        global $DB;

        $expiryseconds = get_config('tool_dataprivacy', 'privacyrequestexpiry');
        $expirytime = strtotime("-{$expiryseconds} second");
        $table = self::TABLE;
        $sqlwhere = 'type = :export_type AND status = :completestatus AND timemodified <= :expirytime';
        $params = array(
            'export_type' => api::DATAREQUEST_TYPE_EXPORT,
            'completestatus' => api::DATAREQUEST_STATUS_DOWNLOAD_READY,
            'expirytime' => $expirytime,
        );
        $sort = 'id';
        $fields = 'id, userid';

        // Filter by user ID if specified.
        if ($userid > 0) {
            $sqlwhere .= ' AND (userid = :userid OR requestedby = :requestedby)';
            $params['userid'] = $userid;
            $params['requestedby'] = $userid;
        }

        return $DB->get_records_select_menu($table, $sqlwhere, $params, $sort, $fields, 0, 2000);
    }
437438
static function fetchListForUser( $userID )
    {
        return eZPersistentObject::fetchObjectList( eZContentBrowseRecent::definition(),
                                                    null, array( 'user_id' => $userID ),
                                                    array( 'created' => 'desc' ), null, true );
    }
586815
public function loadPoliciesByUserId($userId)
    {
        $groupIds = $this->fetchUserGroups($userId);
        $groupIds[] = $userId;

        return $this->loadRolesForContentObjects($groupIds);
    }
1168595
public static function getRoutesByUser($userId)
    {
        if (!isset(self::$_userRoutes[$userId])) {
            $manager = self::getAuthManager();
            if ($manager->cache && ($routes = $manager->cache->get([__METHOD__, $userId])) !== false) {
                self::$_userRoutes[$userId] = $routes;
            } else {
                $routes = static::getDefaultRoutes();
                foreach ($manager->getPermissionsByUser($userId) as $item) {
                    if ($item->name[0] === '/') {
                        $routes[$item->name] = true;
                    }
                }
                self::$_userRoutes[$userId] = $routes;
                if ($manager->cache) {
                    $manager->cache->set([__METHOD__, $userId], $routes, $manager->cacheDuration, new TagDependency([
                        'tags' => $manager->cacheTag
                    ]));
                }
            }
        }
        return self::$_userRoutes[$userId];
    }
601656
public function update($userId)
    {
        try
        {
            $permissions = Input::get('permissions', array());
            $this->users->updatePermissions($userId,$permissions);

            return Redirect::route('cpanel.users.index')
                ->with('success', Lang::get('cpanel::users.permissions_update_success'));
        }
        catch ( UserNotFoundException $e)
        {
            return Redirect::route('cpanel.users.permissions')
                ->with('error', $e->getMessage());
        }

    }
401745
public function deleteForce(array $userIds): array
    {
        $deleted = [];

        $users = $this->makeQuery()->withTrashed()->whereIn('id', $userIds)->get();

        /** @var HCUser $user */
        foreach ($users as $user) {
            if ($user->forceDelete()) {
                $deleted[] = $user;
            }
        }

        return $deleted;
    }