Load the needed users.xml file to backup_ids table for future reference

@param string $restoreid Restore id
@param string $usersfile File path
@param \core\progress\base $progress Progress tracker
342360
public static function load_users_to_tempids($restoreid, $usersfile,
            \core\progress\base $progress = null) {

        if (!file_exists($usersfile)) { // Shouldn't happen ever, but...
            throw new backup_helper_exception('missing_users_xml_file', $usersfile);
        }

        // Set up progress tracking (indeterminate).
        if (!$progress) {
            $progress = new \core\progress\none();
        }
        $progress->start_progress('Loading users into temporary table');

        // Let's parse, custom processor will do its work, sending info to DB
        $xmlparser = new progressive_parser();
        $xmlparser->set_file($usersfile);
        $xmlprocessor = new restore_users_parser_processor($restoreid);
        $xmlparser->set_processor($xmlprocessor);
        $xmlparser->set_progress($progress);
        $xmlparser->process();

        // Finish progress.
        $progress->end_progress();
    }
857734
public static function initData($syncid, $action)
	{
		if ($syncid) {
			//clear sync in progress catch in case we manually stopped the sync so that the sync will continue
			self::changeStatus($syncid, 0);
		}

		$syncdata = new Registry();

		$syncdata->set('completed', false);
		$syncdata->set('sync_errors', 0);
		$syncdata->set('total_to_sync', 0);
		$syncdata->set('synced_users', 0);
		$syncdata->set('userbatch', 1);
		$syncdata->set('user_offset', 0);
		$syncdata->set('syncid', $syncid);
		$syncdata->set('action', $action);

		return $syncdata;
	}
687620
public function resolveFor(UserIdInterface $donorId)
    {
        $donor = $this->donorRepository->findOneById($donorId);

        $donee = $this->getResolverHandlerChain()->resolve($donor);

        $this->eventContext->dispatch(FoundDonee::fromPair($donor, $donee));

        return $donee;
    }
969472
def update_migration_issue_users(self, id, user_id, workflow_state, content_migration_id):
        
        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - user_id
        """ID"""
        path["user_id"] = user_id

        # REQUIRED - PATH - content_migration_id
        """ID"""
        path["content_migration_id"] = content_migration_id

        # REQUIRED - PATH - id
        """ID"""
        path["id"] = id

        # REQUIRED - workflow_state
        """Set the workflow_state of the issue."""
        self._validate_enum(workflow_state, ["active", "resolved"])
        data["workflow_state"] = workflow_state

        self.logger.debug("PUT /api/v1/users/{user_id}/content_migrations/{content_migration_id}/migration_issues/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("PUT", "/api/v1/users/{user_id}/content_migrations/{content_migration_id}/migration_issues/{id}".format(**path), data=data, params=params, single_item=True)
1166398
public function execute($userId = 0)
    {
        $batch = $this->getBatch();
        if ($batch->getCounter('movestarted') === 0) {
            $batch->addToCounter('movestarted');
            $select = $this->loader->getTracker()->getTokenSelect(['total' => new \Zend_Db_Expr('count(*)')])->andReceptionCodes([])->onlyCompleted()->onlySucces()->forSurveyId($this->sourceSurveyId)->getSelect();
            $count = $this->db->fetchOne($select);
            $batch->addStepCount($count - 1);   // For progressbar
            $batch->resetCounter('movesteps');
            $batch->addToCounter('movesteps', $count);
        }
        $this->executeIteration($userId);
    }
629644
public function get_user_completion($user_id, $criteria) {
        $params = array(
            'course'        => $this->course_id,
            'userid'        => $user_id,
            'criteriaid'    => $criteria->id,
        );

        $completion = new completion_criteria_completion($params);
        return $completion;
    }
898027
public function getUserProfilePhotos($userId, $offset = 0, $limit = 100)
    {
        return UserProfilePhotos::fromResponse($this->call('getUserProfilePhotos', [
            'user_id' => (int)$userId,
            'offset' => (int)$offset,
            'limit' => (int)$limit,
        ]));
    }
1358285
protected function processRetrievedData($userId, $data = []): array
    {
        $items = [];

        foreach ($data as $meta) {
            if (! $value = @\unserialize($meta->getAttribute('value'))) {
                $value = $meta->getAttribute('value');
            }

            $key = $meta->getAttribute('name');

            $this->addKey("{$key}/user-{$userId}", [
                'id' => $meta->getAttribute('id'),
                'value' => $value,
            ]);

            $items[$key] = $value;
        }

        return $items;
    }
521767
public function listVersionsForUser($userId, $status = VersionInfo::STATUS_DRAFT)
    {
        try {
            return $this->innerGateway->listVersionsForUser($userId, $status);
        } catch (DBALException $e) {
            throw new RuntimeException('Database error', 0, $e);
        } catch (PDOException $e) {
            throw new RuntimeException('Database error', 0, $e);
        }
    }
876720
public static function getUploadProgress($uniqueId) {
		
		$upload = apc_fetch('upload_' . $uniqueId);
		if ($upload['done']) {
			$percent = 100;
		} else if (0 == $upload['total']) {
			$percent = 0;
		} else {
			$percent = round(($upload['current'] / $upload['total'] * 100), 0);
		}
		return $percent;
		
	}
90442
public static function get_async_backup_progress($backupids, $contextid) {
        global $CFG;
        require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
        require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');

        // Parameter validation.
        self::validate_parameters(
                self::get_async_backup_progress_parameters(),
                array(
                    'backupids' => $backupids,
                    'contextid' => $contextid
                )
        );

        // Context validation.
        list($context, $course, $cm) = get_context_info_array($contextid);
        self::validate_context($context);

        if ($cm) {
            require_capability('moodle/backup:backupactivity', $context);
        } else {
            require_capability('moodle/backup:backupcourse', $context);
            $instanceid = $course->id;
        }

        $results = array();
        foreach ($backupids as $backupid) {
            $results[] = backup_controller_dbops::get_progress($backupid);
        }

        return $results;
    }
1180001
static function retrieveUserCacheFromFile( $filePath, $mtime, $userId )
    {
        $userCache = include( $filePath );

        // check that the returned array is not corrupted
        if ( is_array( $userCache )
          && isset( $userCache['info'] )
          && isset( $userCache['info'][$userId] )
          && is_numeric( $userCache['info'][$userId]['contentobject_id'] )
          && isset( $userCache['groups'] )
          && isset( $userCache['roles'] )
          && isset( $userCache['role_limitations'] )
          && isset( $userCache['access_array'] )
          && isset( $userCache['discount_rules'] ) )
        {
            return $userCache;
        }

        eZDebug::writeError( 'Cache file ' . $filePath . ' is corrupted, forcing generation.', __METHOD__ );
        return new eZClusterFileFailure( 1, 'Cache file ' . $filePath . ' is corrupted, forcing generation.' );
    }
552531
public function parseSourceFile($packageHandle, $packageVersion, $path, $relDirectory = '')
    {
        if (!$this->filesystem->isFile($path)) {
            throw new UserMessageException(t('Unable to find the file %s', $path));
        }
        $tmp = $this->app->make(VolatileDirectory::class);
        $workDir = $tmp->getPath();
        if (!@$this->filesystem->copy($path, $workDir . '/' . basename($path))) {
            unset($tmp);
            throw new UserMessageException(t('Failed to copy a temporary file'));
        }
        $result = $this->parseDirectory($packageHandle, $packageVersion, $workDir, $relDirectory, '');
        unset($tmp);

        return $result;
    }
1110696
public function restore(
        Filesystem $source,
        Filesystem $destination,
        ReadonlyDatabase $database,
        array $parameter
    ) {
        // TODO make it smoother
        $files = $source->listFiles('', true);

        $progressBar = new ProgressBar($this->output, count($files));
        $progressBar->setOverwrite(true);
        $progressBar->setFormat(' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%');
        $progressBar->start();

        $metadata = $database->getWithDefault('metadata', []);

        foreach ($files as $file) {
            $path = $file['path'];
            $fullPath = $parameter['directory'] . '/' . $path;
            $fileMetadata = array_key_exists($path, $metadata) ? $metadata[$path] : ['hash' => null];
            if ($destination->has($fullPath)) {
                if ($fileMetadata['hash'] !== null && $destination->hash($fullPath) === $fileMetadata['hash']) {
                    $progressBar->advance();

                    continue;
                }

                $destination->delete($fullPath);
            }

            $stream = $source->readStream($path);
            if (!$stream) {
                continue;
            }

            $destination->writeStream($fullPath, $stream);
            fclose($stream);

            $progressBar->advance();
        }

        $progressBar->finish();
    }
140794
public function sync(progress_trace $trace, $courseid = null) {
        global $DB;

        if (!enrol_is_enabled('self')) {
            $trace->finished();
            return 2;
        }

        // Unfortunately this may take a long time, execution can be interrupted safely here.
        core_php_time_limit::raise();
        raise_memory_limit(MEMORY_HUGE);

        $trace->output('Verifying self-enrolments...');

        $params = array('now'=>time(), 'useractive'=>ENROL_USER_ACTIVE, 'courselevel'=>CONTEXT_COURSE);
        $coursesql = "";
        if ($courseid) {
            $coursesql = "AND e.courseid = :courseid";
            $params['courseid'] = $courseid;
        }

        // Note: the logic of self enrolment guarantees that user logged in at least once (=== u.lastaccess set)
        //       and that user accessed course at least once too (=== user_lastaccess record exists).

        // First deal with users that did not log in for a really long time - they do not have user_lastaccess records.
        $sql = "SELECT e.*, ue.userid
                  FROM {user_enrolments} ue
                  JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'self' AND e.customint2 > 0)
                  JOIN {user} u ON u.id = ue.userid
                 WHERE :now - u.lastaccess > e.customint2
                       $coursesql";
        $rs = $DB->get_recordset_sql($sql, $params);
        foreach ($rs as $instance) {
            $userid = $instance->userid;
            unset($instance->userid);
            $this->unenrol_user($instance, $userid);
            $days = $instance->customint2 / 60*60*24;
            $trace->output("unenrolling user $userid from course $instance->courseid as they have did not log in for at least $days days", 1);
        }
        $rs->close();

        // Now unenrol from course user did not visit for a long time.
        $sql = "SELECT e.*, ue.userid
                  FROM {user_enrolments} ue
                  JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'self' AND e.customint2 > 0)
                  JOIN {user_lastaccess} ul ON (ul.userid = ue.userid AND ul.courseid = e.courseid)
                 WHERE :now - ul.timeaccess > e.customint2
                       $coursesql";
        $rs = $DB->get_recordset_sql($sql, $params);
        foreach ($rs as $instance) {
            $userid = $instance->userid;
            unset($instance->userid);
            $this->unenrol_user($instance, $userid);
                $days = $instance->customint2 / 60*60*24;
            $trace->output("unenrolling user $userid from course $instance->courseid as they have did not access course for at least $days days", 1);
        }
        $rs->close();

        $trace->output('...user self-enrolment updates finished.');
        $trace->finished();

        $this->process_expirations($trace, $courseid);

        return 0;
    }
106139
public function execute() {
        if ($this->progress >= self::PROGRESS_EXECUTED) {
            throw new restore_ui_exception('restoreuialreadyexecuted');
        }
        if ($this->stage->get_stage() < self::STAGE_PROCESS) {
            throw new restore_ui_exception('restoreuifinalisedbeforeexecute');
        }
        if ($this->controller->get_target() == backup::TARGET_CURRENT_DELETING || $this->controller->get_target() == backup::TARGET_EXISTING_DELETING) {
            $options = array();
            $options['keep_roles_and_enrolments'] = $this->get_setting_value('keep_roles_and_enrolments');
            $options['keep_groups_and_groupings'] = $this->get_setting_value('keep_groups_and_groupings');
            restore_dbops::delete_course_content($this->controller->get_courseid(), $options);
        }
        $this->controller->execute_plan();
        $this->progress = self::PROGRESS_EXECUTED;
        $this->stage = new restore_ui_stage_complete($this, $this->stage->get_params(), $this->controller->get_results());
        return true;
    }
588319
private void updateReplicaLayerStatusUpdateDeletion(final Node user,
			final Node statusUpdate) {
		final Node lastUpdate = NeoUtils.getNextSingleNode(user,
				SocialGraphRelationshipType.UPDATE);

		// update the ego network if the removal targets the last recent status
		// update
		if (statusUpdate.equals(lastUpdate)) {
			// get timestamp of the last recent status update in future
			long newTimestamp = 0;
			final Node nextStatusUpdate = NeoUtils.getNextSingleNode(
					statusUpdate, SocialGraphRelationshipType.UPDATE);
			if (nextStatusUpdate != null) {
				newTimestamp = (long) nextStatusUpdate
						.getProperty(Properties.StatusUpdate.TIMESTAMP);
			}

			// loop through followers
			Node replicaNode, following;
			for (Relationship replicated : user.getRelationships(
					SocialGraphRelationshipType.REPLICA, Direction.INCOMING)) {
				replicaNode = replicated.getEndNode();
				following = NeoUtils.getPrevSingleNode(replicaNode,
						SocialGraphRelationshipType.FOLLOW);

				// search for insertion index within following replica layer
				long crrTimestamp;
				Node prevReplica = following;
				Node nextReplica = null;
				while (true) {
					// get next user
					nextReplica = NeoUtils.getNextSingleNode(prevReplica,
							SocialGraphRelationshipType.GRAPHITY);
					if (nextReplica != null) {
						// ignore replica of the status update owner
						if (nextReplica.equals(replicaNode)) {
							prevReplica = nextReplica;
							continue;
						}

						crrTimestamp = getLastUpdateByReplica(nextReplica);

						// step on if current user has newer status updates
						if (crrTimestamp > newTimestamp) {
							prevReplica = nextReplica;
							continue;
						}
					}

					// insertion position has been found
					break;
				}

				// insert the replica
				if (nextReplica != null) {
					// bride the replica node
					final Node oldPrevReplica = NeoUtils.getNextSingleNode(
							replicaNode, SocialGraphRelationshipType.GRAPHITY);
					final Node oldNextReplica = NeoUtils.getNextSingleNode(
							replicaNode, SocialGraphRelationshipType.GRAPHITY);
					replicaNode.getSingleRelationship(
							SocialGraphRelationshipType.GRAPHITY,
							Direction.INCOMING).delete();

					if (oldNextReplica != null) {
						oldNextReplica.getSingleRelationship(
								SocialGraphRelationshipType.GRAPHITY,
								Direction.INCOMING).delete();
						oldPrevReplica.createRelationshipTo(oldNextReplica,
								SocialGraphRelationshipType.GRAPHITY);
					}

					// link to new neighbored nodes
					if (nextReplica != null) {
						replicaNode.createRelationshipTo(nextReplica,
								SocialGraphRelationshipType.GRAPHITY);
						prevReplica.getSingleRelationship(
								SocialGraphRelationshipType.GRAPHITY,
								Direction.OUTGOING);
					}
					prevReplica.createRelationshipTo(replicaNode,
							SocialGraphRelationshipType.GRAPHITY);
				}
			}

		}
	}