Survey source synchronization check function

@param string $sourceSurveyId
@param int $surveyId
@param int $userId
@return mixed message string or array of messages
1922
public function checkSurvey($sourceSurveyId, $surveyId, $userId)
    {
        $changed     = 0;
        $created     = false;
        $deleted     = false;
        $deletedFile = false;
        $survey      = $this->tracker->getSurvey($surveyId);

        // Get OpenRosa data
        if ($sourceSurveyId) {
            // Surveys in OpenRose
            $db = $this->getSourceDatabase();

            $select = $db->select();
            $select->from('gems__openrosaforms')
                    ->where('gof_id = ?', $sourceSurveyId);

            $openRosaSurvey = $db->fetchRow($select);
        } else {
            $openRosaSurvey = false;
        }

        if ($openRosaSurvey) {
            // Exists
            $values['gsu_survey_name']     = sprintf(
                    '%s [%s]',
                    $openRosaSurvey['gof_form_title'],
                    $openRosaSurvey['gof_form_version']
                    );
            $values['gsu_status']          = 'OK';
            $values['gsu_surveyor_active'] = $openRosaSurvey['gof_form_active'];

            if (!$surveyId) {
                // New
                $values['gsu_active']      = 0;
                $values['gsu_id_source']   = $this->getId();
                $values['gsu_surveyor_id'] = $sourceSurveyId;
                $created = true;
            }

            if (!$this->sourceFileExists($openRosaSurvey['gof_form_xml'])) {
                // No longer exists
                $values['gsu_surveyor_active'] = 0;
                $values['gsu_status']          = 'Survey form XML was removed from directory.';
                $deletedFile = true;
            }


        } else {
            // No longer exists
            $values['gsu_surveyor_active'] = 0;
            $values['gsu_status']          = 'Survey was removed from source.';

            $deleted = true;
        }

        $changed = $survey->saveSurvey($values, $userId);

        if (! $changed) {
            return;
        }

        if ($deleted) {
            $message = $this->_('The \'%s\' survey is no longer active. The survey was removed from OpenRosa!');

        } elseif ($deletedFile) {
            $message = $this->_('The \'%s\' survey is no longer active. The survey XML file was removed from its directory!');

        } elseif ($created) {
            $message = $this->_('Imported the \'%s\' survey.');

        } else {
            $message = $this->_('Updated the \'%s\' survey.');
        }

        return sprintf($message, $survey->getName());;
    }
690442
public function execute($respTrackData = null, $userId = null)
    {
        $batch     = $this->getBatch();
        $tracker   = $this->loader->getTracker();
        $respTrack = $tracker->getRespondentTrack($respTrackData);

        $i = $batch->addToCounter('checkedRespondentTracks');

        if ($result = $respTrack->checkTrackTokens($userId)) {
            $a = $batch->addToCounter('tokenDateCauses');
            $b = $batch->addToCounter('tokenDateChanges', $result);
            $batch->setMessage('tokenDateChanges',
                    sprintf($this->_('%2$d token date changes in %1$d tracks.'), $a, $b)
                    );
        }

        $batch->setMessage('checkedRespondentTracks', sprintf($this->_('Checked %d tracks.'), $i));
    }
695769
public static function confirm_contact_request(int $userid, int $requesteduserid) {
        global $DB;

        if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
                'requesteduserid' => $requesteduserid])) {
            self::add_contact($userid, $requesteduserid);

            $DB->delete_records('message_contact_requests', ['id' => $request->id]);
        }
    }
330852
public function getSurveyPages($surveyId, array $filters = [])
	{
		return $this->sendRequest(
			$this->createRequest('GET', sprintf('surveys/%d/pages', $surveyId), [ 
				'query' => $filters 
			])
		);
	}
129454
public static function user_competency_plan_viewed($competencyid, $userid, $planid) {
        $params = self::validate_parameters(self::user_competency_viewed_in_plan_parameters(), array(
            'competencyid' => $competencyid,
            'userid' => $userid,
            'planid' => $planid
        ));
        $pl = api::get_plan_competency($params['planid'], $params['competencyid']);
        $result = api::user_competency_plan_viewed($pl->usercompetencyplan);

        return $result;
    }
1241817
protected function process_outcomes($userid, $formdata, $sourceuserid = null) {
        global $CFG, $USER;

        if (empty($CFG->enableoutcomes)) {
            return;
        }
        if ($this->grading_disabled($userid)) {
            return;
        }

        require_once($CFG->libdir.'/gradelib.php');

        $data = array();
        $gradinginfo = grade_get_grades($this->get_course()->id,
                                        'mod',
                                        'assign',
                                        $this->get_instance()->id,
                                        $userid);

        if (!empty($gradinginfo->outcomes)) {
            foreach ($gradinginfo->outcomes as $index => $oldoutcome) {
                $name = 'outcome_'.$index;
                $sourceuserid = $sourceuserid !== null ? $sourceuserid : $userid;
                if (isset($formdata->{$name}[$sourceuserid]) &&
                        $oldoutcome->grades[$userid]->grade != $formdata->{$name}[$sourceuserid]) {
                    $data[$index] = $formdata->{$name}[$sourceuserid];
                }
            }
        }
        if (count($data) > 0) {
            grade_update_outcomes('mod/assign',
                                  $this->course->id,
                                  'mod',
                                  'assign',
                                  $this->get_instance()->id,
                                  $userid,
                                  $data);
        }
    }
83140
public function deleteReview($userId, $reviewId)
    {
        $review = $this->getReviewById($reviewId);

        $this->validateUserPermissionsToManageReview($review, $userId);

        $review->delete();
    }
260541
public static function user_competency_stop_review($userid, $competencyid) {
        $params = self::validate_parameters(self::user_competency_stop_review_parameters(), array(
            'userid' => $userid,
            'competencyid' => $competencyid
        ));

        $context = context_user::instance($params['userid']);
        self::validate_context($context);

        return api::user_competency_stop_review($userid, $competencyid);
    }
1188020
public function getSurveyPageQuestion($surveyId, $pageId, $questionId)
	{
		return $this->sendRequest(
			$this->createRequest('GET', sprintf('surveys/%d/pages/%d/questions/%d', $surveyId, $pageId, $questionId))
		);	
	}
448215
public function getSurveyAnswerModel(\Gems_Tracker_Survey $survey, $language = null, $sourceSurveyId = null)
    {
        if (null === $sourceSurveyId) {
            $sourceSurveyId = $this->_getSid($survey->getSurveyId());
        }

        $model         = $this->createModel($survey);
        $model->set('gto_id_token', 'label', $this->_('Token'), 'elementClass', 'Exhibitor');

        $surveyForm  = $this->getSurvey($survey->getSurveyId(), $sourceSurveyId);
        $surveyModel   = $this->getSurvey($survey->getSurveyId(), $sourceSurveyId)->getModel();

        $model->setMeta('openroseTableName', $surveyForm->getTableName());
        $model->setMeta('internalAttributes', true);

        /*$questionsList = $this->getQuestionList($language, $survey->getSurveyId(), $sourceSurveyId);
        foreach($questionsList as $item => $question) {
            $allOptions = $surveyModel->get($item);
            $allowed = array_fill_keys(array('storageFormat', 'dateFormat', 'label', 'multiOptions', 'maxlength', 'type', 'itemDisplay', 'formatFunction'),1);
            $options = array_intersect_key($allOptions, $allowed);

            $options['label']           = strip_tags($question);
            $options['survey_question'] = true;

            //Should also do something to get the better titles...
            $model->set($item, $options);
        }

        return $model;
        */

        foreach($surveyModel->getItemsOrdered() as $name) {
            $label = $surveyModel->get($name, 'label');
            if ($label) {
                $options = $surveyModel->get($name);
                unset($options['table']);

                $options['label']           = strip_tags($label);
                $options['label_raw']       = $label;
                $options['survey_question'] = true;

                //Should also do something to get the better titles...
                $model->set($name, $options);
            }
        }

        if ($tableIdField = $model->getTableIdField()) {
            if ($surveyModel->has($tableIdField) && !$surveyModel->get($tableIdField, 'label')) {
                $options = $surveyModel->get($name);
                unset($options['table']);
                $model->set($tableIdField, $options);
            }
        }

        if ($surveyModel->getMeta('nested', false)) {
            $model->setMeta('nested', true);
            // We have a nested model, add the nested questions
            $nestedNames = $surveyModel->getMeta('nestedNames');
            $model->setMeta('nestedNames', $nestedNames);
            foreach($nestedNames as $nestedName) {

                $nestedModel = $surveyModel->get($nestedName, 'model');
                if ($nestedModel instanceof \MUtil_Model_ModelAbstract) {
                    $model->addListModel($nestedModel, array('orf_id' => 'orfr_response_id'));
                    $model->set($nestedName, 'label', $surveyModel->get($nestedName, 'label'),
                        'elementClass', 'FormTable'
                    );
                    $model->setMeta('nestedNames', $nestedNames);
                }
            }
        }
        $model->del('token');

        return $model;
    }
1262215
public function updateSurveyResponse($surveyId, $responseId, array $data = [])
	{
		return $this->sendRequest(
			$this->createRequest('PATCH', sprintf('surveys/%s/responses/%s', $surveyId, $responseId), [], $data)
		);
	}
710852
public function checkSourceActive($userId)
    {
        // The only method to check if it is active is by getting all the tables,
        // since the surveys table may be empty so we just check for existence.
        $sourceDb  = $this->getSourceDatabase();
        $tables    = array_map('strtolower', $sourceDb->listTables());
        $tableName = $this->addDatabasePrefix(self::SURVEYS_TABLE, false); // Get name without database prefix.

        $active = strtolower(in_array($tableName, $tables));

        $values['gso_active'] = $active ? 1 : 0;
        $values['gso_status'] = $active ? 'Active' : 'Inactive';

        $this->_updateSource($values, $userId);

        return $active;
    }
1096046
public static function create_contact_request(int $userid, int $requesteduserid) : \stdClass {
        global $DB, $PAGE;

        $request = new \stdClass();
        $request->userid = $userid;
        $request->requesteduserid = $requesteduserid;
        $request->timecreated = time();

        $request->id = $DB->insert_record('message_contact_requests', $request);

        // Send a notification.
        $userfrom = \core_user::get_user($userid);
        $userfromfullname = fullname($userfrom);
        $userto = \core_user::get_user($requesteduserid);
        $url = new \moodle_url('/message/pendingcontactrequests.php');

        $subject = get_string('messagecontactrequestsnotificationsubject', 'core_message', $userfromfullname);
        $fullmessage = get_string('messagecontactrequestsnotification', 'core_message', $userfromfullname);

        $message = new \core\message\message();
        $message->courseid = SITEID;
        $message->component = 'moodle';
        $message->name = 'messagecontactrequests';
        $message->notification = 1;
        $message->userfrom = $userfrom;
        $message->userto = $userto;
        $message->subject = $subject;
        $message->fullmessage = text_to_html($fullmessage);
        $message->fullmessageformat = FORMAT_HTML;
        $message->fullmessagehtml = $fullmessage;
        $message->smallmessage = '';
        $message->contexturl = $url->out(false);
        $userpicture = new \user_picture($userfrom);
        $userpicture->includetoken = $userto->id; // Generate an out-of-session token for the user receiving the message.
        $message->customdata = [
            'notificationiconurl' => $userpicture->get_url($PAGE)->out(false),
            'actionbuttons' => [
                'accept' => get_string_manager()->get_string('accept', 'moodle', null, $userto->lang),
                'reject' => get_string_manager()->get_string('reject', 'moodle', null, $userto->lang),
            ],
        ];

        message_send($message);

        return $request;
    }
1297941
public static function user_competency_request_review($userid, $competencyid) {
        $params = self::validate_parameters(self::user_competency_request_review_parameters(), array(
            'userid' => $userid,
            'competencyid' => $competencyid,
        ));

        $context = context_user::instance($params['userid']);
        self::validate_context($context);

        return api::user_competency_request_review($userid, $competencyid);
    }
537990
public function get_contexts_for_userid(int $userid) : contextlist_collection {
        $progress = static::get_log_tracer();

        $components = $this->get_component_list();
        $a = (object) [
            'total' => count($components),
            'progress' => 0,
            'component' => '',
            'datetime' => userdate(time()),
        ];
        $clcollection = new contextlist_collection($userid);

        $progress->output(get_string('trace:fetchcomponents', 'core_privacy', $a), 1);
        foreach ($components as $component) {
            $a->component = $component;
            $a->progress++;
            $a->datetime = userdate(time());
            $progress->output(get_string('trace:processingcomponent', 'core_privacy', $a), 2);
            $contextlist = $this->handled_component_class_callback($component, core_user_data_provider::class,
                'get_contexts_for_userid', [$userid]);
            if ($contextlist === null) {
                $contextlist = new local\request\contextlist();
            }

            // Each contextlist is tied to its respective component.
            $contextlist->set_component($component);

            // Add contexts that the component may not know about.
            // Example of these include activity completion which modules do not know about themselves.
            $contextlist = local\request\helper::add_shared_contexts_to_contextlist_for($userid, $contextlist);

            if (count($contextlist)) {
                $clcollection->add_contextlist($contextlist);
            }
        }
        $progress->output(get_string('trace:done', 'core_privacy'), 1);

        return $clcollection;
    }
1063137
public function setHasRespondents($userId)
    {
        if (! $this->_get('gor_has_respondents')) {
            $values['gor_has_respondents'] = 1;
            $values['gor_changed']         = new \MUtil_Db_Expr_CurrentTimestamp();
            $values['gor_changed_by']      = $userId;

            $where = $this->db->quoteInto('gor_id_organization = ?', $this->_id);

            $this->db->update('gems__organizations', $values, $where);

            // Invalidate cache / change value
            $this->_set('gor_has_respondents', 1);
        }

        return $this;
    }
54777
public function check_examples_assessed_before_submission($userid) {

        if ($this->useexamples and $this->examplesmode == self::EXAMPLES_BEFORE_SUBMISSION
            and !has_capability('mod/workshop:manageexamples', $this->context)) {

            // Check that all required examples have been assessed by the user.
            $examples = $this->get_examples_for_reviewer($userid);
            foreach ($examples as $exampleid => $example) {
                if (is_null($example->assessmentid)) {
                    $examples[$exampleid]->assessmentid = $this->add_allocation($example, $userid, 0);
                }
                if (is_null($example->grade)) {
                    return false;
                }
            }
        }
        return true;
    }