Exports one instance of custom field data

@param data_controller $data
@param array $subcontext subcontext to pass to content_writer::export_data
125
public static function export_customfield_data(data_controller $data, array $subcontext) {
        $context = $data->get_context();

        $exportdata = $data->to_record();
        $exportdata->fieldtype = $data->get_field()->get('type');
        $exportdata->fieldshortname = $data->get_field()->get('shortname');
        $exportdata->fieldname = $data->get_field()->get_formatted_name();
        $exportdata->timecreated = \core_privacy\local\request\transform::datetime($exportdata->timecreated);
        $exportdata->timemodified = \core_privacy\local\request\transform::datetime($exportdata->timemodified);
        unset($exportdata->contextid);
        // Use the "export_value" by default for the 'value' attribute, however the plugins may override it in their callback.
        $exportdata->value = $data->export_value();

        $classname = manager::get_provider_classname_for_component('customfield_' . $data->get_field()->get('type'));
        if (class_exists($classname) && is_subclass_of($classname, customfield_provider::class)) {
            component_class_callback($classname, 'export_customfield_data', [$data, $exportdata, $subcontext]);
        } else {
            // Custom field plugin does not implement customfield_provider, just export default value.
            writer::with_context($context)->export_data($subcontext, $exportdata);
        }
    }
956136
public static function setContextData(array $contextData = [])
    {
        $coroutineId = self::getcoroutine();
        self::$coroutineLocal[$coroutineId][self::COROUTINE_DATA] = $contextData;
    }
290166
public static function export_customfield_data(data_controller $data, \stdClass $exportdata, array $subcontext) {
        $context = $data->get_context();
        // For text fields we want to apply format_string even to raw value to avoid CSS.
        $exportdata->{$data->datafield()} = $data->export_value();
        writer::with_context($context)
            ->export_data($subcontext, $exportdata);
    }
52440
public static function dump($data, $type = self::DUMP_VAR_DUMP){

            switch($type){

                case self::DUMP_JSON:
                    return json_encode($data);
                case self::DUMP_JSON_PRETTY:
                    return json_encode($data, JSON_PRETTY_PRINT);
                case self::DUMP_VAR_EXPORT:
                    return var_export($data);
                case self::DUMP_VAR_DUMP:
                    return var_dump($data);
                case self::DUMP_XML:
                    return self::arrayToXML($data);
                case self::DUMP_SERIALIZE:
                    return serialize($data);

            }

        }
724574
public function export($dataSetConfig = null)
    {
        $export = [
            'label' => $this->getLabel(),
            'data'  => [],
        ];

        foreach ($this->getData() as $data) {
            $export['data'][] = $data->export();
        }

        if (null !== $dataSetConfig) {
            $export = array_merge($export, $dataSetConfig->export());
        }

        return $export;
    }
1360451
public static function export_submission_user_data(assign_plugin_request_data $exportdata) {
        // We currently don't show submissions to teachers when exporting their data.
        if ($exportdata->get_user() != null) {
            return null;
        }
        // Retrieve text for this submission.
        $assign = $exportdata->get_assign();
        $plugin = $assign->get_plugin_by_type('assignsubmission', 'onlinetext');
        $submission = $exportdata->get_pluginobject();
        $editortext = $plugin->get_editor_text('onlinetext', $submission->id);
        $context = $exportdata->get_context();
        if (!empty($editortext)) {
            $submissiontext = new \stdClass();
            $currentpath = $exportdata->get_subcontext();
            $currentpath[] = get_string('privacy:path', 'assignsubmission_onlinetext');
            $submissiontext->text = writer::with_context($context)->rewrite_pluginfile_urls($currentpath,
                    'assignsubmission_onlinetext', 'submissions_onlinetext', $submission->id, $editortext);
            writer::with_context($context)
                    ->export_area_files($currentpath, 'assignsubmission_onlinetext', 'submissions_onlinetext', $submission->id)
                    // Add the text to the exporter.
                    ->export_data($currentpath, $submissiontext);

            // Handle plagiarism data.
            $coursecontext = $context->get_course_context();
            $userid = $submission->userid;
            \core_plagiarism\privacy\provider::export_plagiarism_user_data($userid, $context, $currentpath, [
                'cmid' => $context->instanceid,
                'course' => $coursecontext->instanceid,
                'userid' => $userid,
                'content' => $editortext,
                'assignment' => $submission->assignment
            ]);
        }
    }
284039
public static function export_user_data(approved_contextlist $contextlist) {
        global $DB;

        $user = $contextlist->get_user();
        $userid = $user->id;
        $cmids = array_reduce($contextlist->get_contexts(), function($carry, $context) {
            if ($context->contextlevel == CONTEXT_MODULE) {
                $carry[] = $context->instanceid;
            }
            return $carry;
        }, []);
        if (empty($cmids)) {
            return;
        }

        // If the context export was requested, then let's at least describe the lesson.
        foreach ($cmids as $cmid) {
            $context = context_module::instance($cmid);
            $contextdata = helper::get_context_data($context, $user);
            helper::export_context_files($context, $user);
            writer::with_context($context)->export_data([], $contextdata);
        }

        // Find the lesson IDs.
        $lessonidstocmids = static::get_lesson_ids_to_cmids_from_cmids($cmids);

        // Prepare the common SQL fragments.
        list($inlessonsql, $inlessonparams) = $DB->get_in_or_equal(array_keys($lessonidstocmids), SQL_PARAMS_NAMED);
        $sqluserlesson = "userid = :userid AND lessonid $inlessonsql";
        $paramsuserlesson = array_merge($inlessonparams, ['userid' => $userid]);

        // Export the overrides.
        $recordset = $DB->get_recordset_select('lesson_overrides', $sqluserlesson, $paramsuserlesson);
        static::recordset_loop_and_export($recordset, 'lessonid', null, function($carry, $record) {
            // We know that there is only one row per lesson, so no need to use $carry.
            return (object) [
                'available' => $record->available !== null ? transform::datetime($record->available) : null,
                'deadline' => $record->deadline !== null ? transform::datetime($record->deadline) : null,
                'timelimit' => $record->timelimit !== null ? format_time($record->timelimit) : null,
                'review' => $record->review !== null ? transform::yesno($record->review) : null,
                'maxattempts' => $record->maxattempts,
                'retake' => $record->retake !== null ? transform::yesno($record->retake) : null,
                'password' => $record->password,
            ];
        }, function($lessonid, $data) use ($lessonidstocmids) {
            $context = context_module::instance($lessonidstocmids[$lessonid]);
            writer::with_context($context)->export_related_data([], 'overrides', $data);
        });

        // Export the grades.
        $recordset = $DB->get_recordset_select('lesson_grades', $sqluserlesson, $paramsuserlesson, 'lessonid, completed');
        static::recordset_loop_and_export($recordset, 'lessonid', [], function($carry, $record) {
            $carry[] = (object) [
                'grade' => $record->grade,
                'completed' => transform::datetime($record->completed),
            ];
            return $carry;
        }, function($lessonid, $data) use ($lessonidstocmids) {
            $context = context_module::instance($lessonidstocmids[$lessonid]);
            writer::with_context($context)->export_related_data([], 'grades', (object) ['grades' => $data]);
        });

        // Export the timers.
        $recordset = $DB->get_recordset_select('lesson_timer', $sqluserlesson, $paramsuserlesson, 'lessonid, starttime');
        static::recordset_loop_and_export($recordset, 'lessonid', [], function($carry, $record) {
            $carry[] = (object) [
                'starttime' => transform::datetime($record->starttime),
                'lastactivity' => transform::datetime($record->lessontime),
                'completed' => transform::yesno($record->completed),
                'timemodifiedoffline' => $record->timemodifiedoffline ? transform::datetime($record->timemodifiedoffline) : null,
            ];
            return $carry;
        }, function($lessonid, $data) use ($lessonidstocmids) {
            $context = context_module::instance($lessonidstocmids[$lessonid]);
            writer::with_context($context)->export_related_data([], 'timers', (object) ['timers' => $data]);
        });

        // Export the attempts and branches.
        $sql = "
            SELECT " . $DB->sql_concat('lp.id', "':'", 'COALESCE(la.id, 0)', "':'", 'COALESCE(lb.id, 0)') . " AS uniqid,
                   lp.lessonid,

                   lp.id AS page_id,
                   lp.qtype AS page_qtype,
                   lp.qoption AS page_qoption,
                   lp.title AS page_title,
                   lp.contents AS page_contents,
                   lp.contentsformat AS page_contentsformat,

                   la.id AS attempt_id,
                   la.retry AS attempt_retry,
                   la.correct AS attempt_correct,
                   la.useranswer AS attempt_useranswer,
                   la.timeseen AS attempt_timeseen,

                   lb.id AS branch_id,
                   lb.retry AS branch_retry,
                   lb.timeseen AS branch_timeseen,

                   lpb.id AS nextpage_id,
                   lpb.title AS nextpage_title

              FROM {lesson_pages} lp
         LEFT JOIN {lesson_attempts} la
                ON la.pageid = lp.id
               AND la.userid = :userid1
         LEFT JOIN {lesson_branch} lb
                ON lb.pageid = lp.id
               AND lb.userid = :userid2
         LEFT JOIN {lesson_pages} lpb
                ON lpb.id = lb.nextpageid
             WHERE lp.lessonid $inlessonsql
               AND (la.id IS NOT NULL OR lb.id IS NOT NULL)
          ORDER BY lp.lessonid, lp.id, la.retry, lb.retry, la.id, lb.id";
        $params = array_merge($inlessonparams, ['userid1' => $userid, 'userid2' => $userid]);

        $recordset = $DB->get_recordset_sql($sql, $params);
        static::recordset_loop_and_export($recordset, 'lessonid', [], function($carry, $record) use ($lessonidstocmids) {
            $context = context_module::instance($lessonidstocmids[$record->lessonid]);
            $options = ['context' => $context];

            $take = isset($record->attempt_retry) ? $record->attempt_retry : $record->branch_retry;
            if (!isset($carry[$take])) {
                $carry[$take] = (object) [
                    'number' => $take + 1,
                    'answers' => [],
                    'jumps' => []
                ];
            }

            $pagefilespath = [get_string('privacy:path:pages', 'mod_lesson'), $record->page_id];
            writer::with_context($context)->export_area_files($pagefilespath, 'mod_lesson', 'page_contents', $record->page_id);
            $pagecontents = format_text(
                writer::with_context($context)->rewrite_pluginfile_urls(
                    $pagefilespath,
                    'mod_lesson',
                    'page_contents',
                    $record->page_id,
                    $record->page_contents
                ),
                $record->page_contentsformat,
                $options
            );

            $pagebase = [
                'id' => $record->page_id,
                'page' => $record->page_title,
                'contents' => $pagecontents,
                'contents_files_folder' => implode('/', $pagefilespath)
            ];

            if (isset($record->attempt_id)) {
                $carry[$take]->answers[] = array_merge($pagebase, static::transform_attempt($record, $context));

            } else if (isset($record->branch_id)) {
                if (!empty($record->nextpage_id)) {
                    $wentto = $record->nextpage_title . " (id: {$record->nextpage_id})";
                } else {
                    $wentto = get_string('endoflesson', 'mod_lesson');
                }
                $carry[$take]->jumps[] = array_merge($pagebase, [
                    'went_to' => $wentto,
                    'timeseen' => transform::datetime($record->attempt_timeseen)
                ]);
            }

            return $carry;

        }, function($lessonid, $data) use ($lessonidstocmids) {
            $context = context_module::instance($lessonidstocmids[$lessonid]);
            writer::with_context($context)->export_related_data([], 'attempts', (object) [
                'attempts' => array_values($data)
            ]);
        });
    }
284105
public function addExportData($key, $data = null): PrepareOrderExportEvent
    {
        if (is_array($key)) {
            $this->exportData = array_merge($this->exportData, $key);
        } else {
            $this->exportData[$key] = $data;
        }

        return $this;
    }
1296315
protected static function export_submission_data(\stdClass $submission, \context $context, array $currentpath) {
        $submissiondata = (object)[
            'timecreated' => transform::datetime($submission->timecreated),
            'timemodified' => transform::datetime($submission->timemodified),
            'status' => get_string('submissionstatus_' . $submission->status, 'mod_assign'),
            'groupid' => $submission->groupid,
            'attemptnumber' => ($submission->attemptnumber + 1),
            'latest' => transform::yesno($submission->latest)
        ];
        writer::with_context($context)
                ->export_data(array_merge($currentpath, [get_string('privacy:submissionpath', 'mod_assign')]), $submissiondata);
    }
1230209
public static function export_user_data(approved_contextlist $contextlist) {
        global $DB;

        $userid = $contextlist->get_user()->id;
        $contexts = array_reduce($contextlist->get_contexts(), function($carry, $context) use ($userid) {
            if ($context->contextlevel == CONTEXT_USER) {
                if ($context->instanceid == $userid) {
                    $carry['has_mine'] = true;
                } else {
                    $carry['others'][] = $context->instanceid;
                }
            }
            return $carry;
        }, [
            'has_mine' => false,
            'others' => []
        ]);

        $path = [get_string('webservices', 'core_webservice')];

        // Exporting my stuff.
        if ($contexts['has_mine']) {

            $data = [];

            // Exporting my tokens.
            $sql = "
                SELECT t.*, s.name as externalservicename
                  FROM {external_tokens} t
                  JOIN {external_services} s
                    ON s.id = t.externalserviceid
                 WHERE t.userid = :userid
              ORDER BY t.id";
            $recordset = $DB->get_recordset_sql($sql, ['userid' => $userid]);
            foreach ($recordset as $record) {
                if (!isset($data['tokens'])) {
                    $data['tokens'] = [];
                }
                $data['tokens'][] = static::transform_token($record);
            }
            $recordset->close();

            // Exporting the services I have access to.
            $sql = "
                SELECT su.*, s.name as externalservicename
                  FROM {external_services_users} su
                  JOIN {external_services} s
                    ON s.id = su.externalserviceid
                 WHERE su.userid = :userid
              ORDER BY su.id";
            $recordset = $DB->get_recordset_sql($sql, ['userid' => $userid]);
            foreach ($recordset as $record) {
                if (!isset($data['services_user'])) {
                    $data['services_user'] = [];
                }
                $data['services_user'][] = [
                    'external_service' => $record->externalservicename,
                    'ip_restriction' => $record->iprestriction,
                    'valid_until' => $record->validuntil ? transform::datetime($record->validuntil) : null,
                    'created_on' => transform::datetime($record->timecreated),
                ];
            }
            $recordset->close();

            if (!empty($data)) {
                writer::with_context(context_user::instance($userid))->export_data($path, (object) $data);
            };
        }

        // Exporting the tokens I created.
        if (!empty($contexts['others'])) {
            list($insql, $inparams) = $DB->get_in_or_equal($contexts['others'], SQL_PARAMS_NAMED);
            $sql = "
                SELECT t.*, s.name as externalservicename
                  FROM {external_tokens} t
                  JOIN {external_services} s
                    ON s.id = t.externalserviceid
                 WHERE t.userid $insql
                   AND t.creatorid = :userid1
                   AND t.userid <> :userid2
              ORDER BY t.userid, t.id";
            $params = array_merge($inparams, ['userid1' => $userid, 'userid2' => $userid]);
            $recordset = $DB->get_recordset_sql($sql, $params);
            static::recordset_loop_and_export($recordset, 'userid', [], function($carry, $record) {
                $carry[] = static::transform_token($record);
                return $carry;
            }, function($userid, $data) use ($path) {
                writer::with_context(context_user::instance($userid))->export_related_data($path, 'created_by_you', (object) [
                    'tokens' => $data
                ]);
            });
        }
    }
691551
protected function exportFieldData(array $data)
    {
        $replacements = array("\n" => '\\n', "\r" => '\\r', "\t" => '\\t');

        foreach ($data as &$item) {
            $item = strtr((string) $item, $replacements);
        }
        fwrite($this->_file, implode("\t", $data) . "\r\n");
    }
914184
protected static function export_user_data_frameworks_in_context($userid, context $context) {
        global $DB;

        $ffields = competency_framework::get_sql_fields('f', 'f_');
        $cfields = competency::get_sql_fields('c', 'c_');
        $c2fields = competency::get_sql_fields('c2', 'c2_');
        $rcfields = related_competency::get_sql_fields('rc', 'rc_');

        $frameworks = [];
        $initframework = function($record) use (&$frameworks, $userid) {
            $framework = new competency_framework(null, competency_framework::extract_record($record, 'f_'));
            $frameworks[$framework->get('id')] = array_merge(static::transform_framework_brief($framework), [
                'timemodified' => transform::datetime($framework->get('timemodified')),
                'created_or_modified_by_you' => transform::yesno($framework->get('usermodified') == $userid),
                'competencies' => []
            ]);
        };
        $initcompetency = function($record, $prefix) use (&$frameworks, $userid) {
            $competency = new competency(null, competency::extract_record($record, $prefix));
            $frameworks[$competency->get('competencyframeworkid')]['competencies'][$competency->get('id')] = array_merge(
                static::transform_competency_brief($competency),
                [
                    'timemodified' => transform::datetime($competency->get('timemodified')),
                    'created_or_modified_by_you' => transform::yesno($competency->get('usermodified') == $userid),
                    'related_competencies' => []
                ]
            );
        };

        // Start by looking for related competencies.
        $sql = "
            SELECT $ffields, $cfields, $c2fields, $rcfields
              FROM {" . related_competency::TABLE . "} rc
              JOIN {" . competency::TABLE . "} c
                ON c.id = rc.competencyid
              JOIN {" . competency::TABLE . "} c2
                ON c2.id = rc.relatedcompetencyid
              JOIN {" . competency_framework::TABLE . "} f
                ON f.id = c.competencyframeworkid
             WHERE rc.usermodified = :userid
               AND f.contextid = :contextid
          ORDER BY rc.id, c.id";
        $params = ['userid' => $userid, 'contextid' => $context->id];

        $recordset = $DB->get_recordset_sql($sql, $params);
        foreach ($recordset as $record) {
            $frameworkid = $record->f_id;
            $comp1id = $record->c_id;
            $comp2id = $record->c2_id;

            if (!isset($frameworks[$frameworkid])) {
                $initframework($record);
            }

            foreach (['c_', 'c2_'] as $key) {
                $competencyid = $record->{$key . 'id'};
                if (!isset($frameworks[$frameworkid]['competencies'][$competencyid])) {
                    $initcompetency($record, $key);
                }
            }

            $relcomp = new related_competency(null, related_competency::extract_record($record, 'rc_'));
            foreach (['c_' => 'c2_', 'c2_' => 'c_'] as $key => $relatedkey) {
                $competencyid = $record->{$key . 'id'};
                $competency = new competency(null, competency::extract_record($record, $relatedkey));
                $frameworks[$frameworkid]['competencies'][$competencyid]['related_competencies'][] = [
                    'name' => $competency->get('shortname'),
                    'idnumber' => $competency->get('idnumber'),
                    'timemodified' => transform::datetime($relcomp->get('timemodified')),
                    'created_or_modified_by_you' => transform::yesno($relcomp->get('usermodified') == $userid),
                ];
            }
        }
        $recordset->close();

        // Now look for competencies, but skip the ones we've already seen.
        $competencyids = array_reduce($frameworks, function($carry, $framework) {
            return array_merge($carry, array_keys($framework['competencies']));
        }, []);
        $insql = ' IS NOT NULL';
        $inparams = [];
        if (!empty($competencyids)) {
            list($insql, $inparams) = $DB->get_in_or_equal($competencyids, SQL_PARAMS_NAMED, 'param', false);
        }
        $sql = "
            SELECT $ffields, $cfields
              FROM {" . competency::TABLE . "} c
              JOIN {" . competency_framework::TABLE . "} f
                ON f.id = c.competencyframeworkid
             WHERE c.usermodified = :userid
               AND f.contextid = :contextid
               AND c.id $insql
          ORDER BY c.id";
        $params = array_merge($inparams, ['userid' => $userid, 'contextid' => $context->id]);
        $recordset = $DB->get_recordset_sql($sql, $params);
        foreach ($recordset as $record) {
            $frameworkid = $record->f_id;
            if (!isset($frameworks[$frameworkid])) {
                $initframework($record);
            }
            $initcompetency($record, 'c_');
        }
        $recordset->close();

        // Now look for frameworks, but skip the ones we've already seen.
        $frameworkids = array_keys($frameworks);
        $insql = ' IS NOT NULL';
        $inparams = [];
        if (!empty($frameworkids)) {
            list($insql, $inparams) = $DB->get_in_or_equal($frameworkids, SQL_PARAMS_NAMED, 'param', false);
        }
        $sql = "
            SELECT $ffields
              FROM {" . competency_framework::TABLE . "} f
             WHERE f.usermodified = :userid
               AND f.contextid = :contextid
               AND f.id $insql
          ORDER BY f.id";
        $params = array_merge($inparams, ['userid' => $userid, 'contextid' => $context->id]);
        $recordset = $DB->get_recordset_sql($sql, $params);
        foreach ($recordset as $record) {
            context_helper::preload_from_record($record);
            $initframework($record);
        }
        $recordset->close();

        // Export all the things!
        writer::with_context($context)->export_related_data(
            [get_string('competencies', 'core_competency')],
            'frameworks',
            (object) [
                // Drop the temporary IDs.
                'frameworks' => array_reduce($frameworks, function($carry, $item) {
                    $item['competencies'] = array_values($item['competencies']);
                    $carry[] = $item;
                    return $carry;
                }, [])
            ]
        );
    }
760972
protected static function export_user_calendar_subscription_data(approved_contextlist $contextlist) {
        // Calendar Subscriptions can exist at Site, Course Category, Course, Course Group, or User contexts.
        $subscriptiondetails = self::get_calendar_subscription_details_by_contextlist($contextlist);

        // Multiple Calendar Subscriptions of the same eventtype can exist for a context, so collate them for export.
        $subscriptionrecords = [];
        foreach ($subscriptiondetails as $subscriptiondetail) {
            // Create an array key based on the contextid and eventtype.
            $key = $subscriptiondetail->contextid . $subscriptiondetail->eventtype;

            if (array_key_exists($key, $subscriptionrecords) === false) {
                $subscriptionrecords[$key] = [ $subscriptiondetail ];
            } else {
                $subscriptionrecords[$key] = array_merge($subscriptionrecords[$key], [$subscriptiondetail]);
            }
        }
        $subscriptiondetails->close();

        // Export Calendar Subscription data.
        foreach ($subscriptionrecords as $subscriptionrecord) {
            $index = (count($subscriptionrecord) > 1) ? 1 : 0;

            foreach ($subscriptionrecord as $subscription) {
                // Export the events using the structure Calendar/Subscriptions/{eventtype}-subscription.json.
                $subcontexts = [
                    get_string('calendar', 'calendar'),
                    get_string('subscriptions', 'calendar')
                ];
                $name = $subscription->eventtype . '-subscription';

                // Use name {eventtype}-subscription-{index}.json if multiple eventtypes exists at the same context.
                if ($index != 0) {
                    $name .= '-' . $index;
                    $index++;
                }

                $context = \context::instance_by_id($subscription->contextid);
                writer::with_context($context)->export_related_data($subcontexts, $name, $subscription);
            }
        }
    }
1157104
private function exportToSingle(array $configurations, array $overrideData)
    {
        $configurations = array_replace_recursive($configurations, $overrideData);
        FileHelper::writeToFile($this->file, Data::toYaml($configurations));
        Schematic::info('Exported schema to '.$this->file);
    }
535038
public function applyBehavioursOnSubmittedForm(ControllerContext $controllerContext)
    {
        if ($this->formObject->formWasSubmitted()) {
            $request = $controllerContext->getRequest()->getOriginalRequest();
            $formName = $this->formObject->getName();

            if ($request
                && $request->hasArgument($formName)
            ) {
                /** @var BehavioursManager $behavioursManager */
                $behavioursManager = GeneralUtility::makeInstance(BehavioursManager::class);

                /** @var array $originalForm */
                $originalForm = $request->getArgument($formName);

                $formProperties = $behavioursManager->applyBehaviourOnPropertiesArray(
                    $originalForm,
                    $this->formObject->getConfiguration()
                );

                $request->setArgument($formName, $formProperties);
            }
        }
    }
1185387
public function getDataPlainText(array $dataSubArray): string
    {
        $dataArray = [];
        foreach ($dataSubArray as $key => $value) {
            $dataArray[] = implode($this->config->getDataSubSeparator(), [$key, $value]);
        }

        return implode($this->config->getDataSeparator(), $dataArray);
    }
525631
public function serializePayload(ControllerContext $controllerContext)
    {
        return [
            'contextPath' => $this->getNode()->getContextPath(),
            'parentDomAddress' => $this->getParentDomAddress(),
            'siblingDomAddress' => $this->getSiblingDomAddress(),
            'mode' => $this->getMode(),
            'renderedContent' => $this->renderContent($controllerContext)
        ];
    }