Converts from current format to backup::MOODLE format
189831
public function convert() {
        global $CFG;
        require_once($CFG->dirroot . '/backup/util/helper/convert_helper.class.php');

        // Basic/initial prevention against time/memory limits
        core_php_time_limit::raise(1 * 60 * 60); // 1 hour for 1 course initially granted
        raise_memory_limit(MEMORY_EXTRA);
        $this->progress->start_progress('Backup format conversion');

        if ($this->status != backup::STATUS_REQUIRE_CONV) {
            throw new restore_controller_exception('cannot_convert_not_required_status');
        }

        $this->log('backup format conversion required', backup::LOG_INFO);

        // Run conversion to the proper format
        if (!convert_helper::to_moodle2_format($this->get_tempdir(), $this->format, $this->get_logger())) {
            // todo - unable to find the conversion path, what to do now?
            // throwing the exception as a temporary solution
            throw new restore_controller_exception('unable_to_find_conversion_path');
        }

        $this->log('backup format conversion successful', backup::LOG_INFO);

        // If no exceptions were thrown, then we are in the proper format
        $this->format = backup::FORMAT_MOODLE;

        // Load plan, apply security and set status based on interactivity
        $this->load_plan();

        // Perform all initial security checks and apply (2nd param) them to settings automatically
        restore_check::check_security($this, true);

        if ($this->interactive == backup::INTERACTIVE_YES) {
            $this->set_status(backup::STATUS_SETTING_UI);
        } else {
            $this->set_status(backup::STATUS_NEED_PRECHECK);
        }
        $this->progress->end_progress();
    }
293620
private function getFileTemplate()
    {
        $content = FormatFileContent::createObject();
        $content->addItem('<?php');
        $content->addItem(
            sprintf(
                '/**Migration file generated at %s on %s by PowerOrm(%s)*/',
                date('h:m:i'),
                date('D, jS F Y'),
                POWERORM_VERSION
            ).PHP_EOL
        );

        $content->addItem('namespace %s;'.PHP_EOL);

        $content->addItem('use Eddmash\\PowerOrm\\Migration\\Migration;');
        $content->addItem('%s');

        $content->addItem('class %s extends Migration{'.PHP_EOL);

        $content->addIndent();
        $content->addItem('public function getDependency(){');

        $content->addIndent();
        $content->addItem('return [');

        $content->addItem('%s');

        $content->addItem('];');
        $content->reduceIndent();

        $content->addItem('}'.PHP_EOL);

        $content->addItem('public function getOperations(){');

        $content->addIndent();
        $content->addItem('return %s ;');
        $content->reduceIndent();

        $content->addItem('}'.PHP_EOL);
        $content->reduceIndent();

        $content->addItem('}');

        return $content;
    }
125092
public function convert() {

		// Get HTMLBook

		$output = $this->transform( true );

		if ( ! $output ) {
			return false;
		}

		// Save HTMLBook as file in exports folder

		$filename = $this->timestampedFileName( '-htmlbook.html' );
		\Pressbooks\Utility\put_contents( $filename, $output );
		$this->outputPath = $filename;

		return true;
	}
1156886
public function download() {
        $filename = 'logs_' . userdate(time(), get_string('backupnameformat', 'langconfig'), 99, false);
        if ($this->course->id !== SITEID) {
            $courseshortname = format_string($this->course->shortname, true,
                    array('context' => context_course::instance($this->course->id)));
            $filename = clean_filename('logs_' . $courseshortname . '_' . userdate(time(),
                    get_string('backupnameformat', 'langconfig'), 99, false));
        }
        $this->tablelog->is_downloading($this->logformat, $filename);
        $this->tablelog->out($this->perpage, false);
    }
556366
public function backup_details_unknown(moodle_url $nextstageurl) {

        $html  = html_writer::start_div('unknownformat');
        $html .= $this->output->heading(get_string('errorinvalidformat', 'backup'), 2);
        $html .= $this->output->notification(get_string('errorinvalidformatinfo', 'backup'), 'notifyproblem');
        $html .= $this->output->single_button($nextstageurl, get_string('continue'), 'post');
        $html .= html_writer::end_div();

        return $html;
    }
1111391
public function to_bin()
   {
         $out = "";
      for ($i=0; $i<$this->dataLength($this->data); $i++)
         $out = sprintf("%08b",$this->data[$i]).$out;
      return $out;      
   }
1311527
public function convert() {

        try {
            $this->log('creating the target directory', backup::LOG_DEBUG);
            $this->create_workdir();

            $this->log('executing the conversion', backup::LOG_DEBUG);
            $this->execute();

            $this->log('replacing the source directory with the converted version', backup::LOG_DEBUG);
            $this->replace_tempdir();
        } catch (Exception $e) {
        }

        // clean-up stuff if needed
        $this->destroy();

        // eventually re-throw the execution exception
        if (isset($e) and ($e instanceof Exception)) {
            throw $e;
        }
    }
900633
public function backupStructure(): string
	{
		$string = [];

		// Get databases
		$dbs = $this->getDriver()->getDbs();

		foreach($dbs as &$d)
		{
			// Skip built-in dbs
			// @codeCoverageIgnoreStart
			if ($d === 'mysql')
			{
				continue;
			}
			// @codeCoverageIgnoreEnd

			// Get the list of tables
			$tables = $this->getDriver()->driverQuery("SHOW TABLES FROM `{$d}`", TRUE);

			foreach($tables as $table)
			{
				$array = $this->getDriver()->driverQuery("SHOW CREATE TABLE `{$d}`.`{$table}`", FALSE);
				$row = current($array);

				if ( ! isset($row['Create Table']))
				{
					continue;
				}


				$string[] = $row['Create Table'];
			}
		}

		return implode("\n\n", $string);
	}
470092
protected function dumpCurrentDB()
    {
        date_default_timezone_set("Etc/UTC");
        $relativeFilename = sprintf("export_%s_%s.sql", date('Y-m-d'), time());
        $command = sprintf("%s db export %s%s --add-drop-table", $this->getWpCliPath(), Strata::getDbPath(), $relativeFilename);
        $this->output->writeLn("Generating MySQL export dump to ./$relativeFilename");
        system($command);
    }
392083
public function restore_item($item) {
        global $CFG, $OUTPUT, $PAGE;

        require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
        require_once($CFG->dirroot . '/course/lib.php');

        $user = get_admin();

        // Grab the course category context.
        $context = \context_coursecat::instance($this->_categoryid);

        // Get the backup file.
        $fs = get_file_storage();
        $files = $fs->get_area_files($context->id, 'tool_recyclebin', TOOL_RECYCLEBIN_COURSECAT_BIN_FILEAREA, $item->id,
            'itemid, filepath, filename', false);

        if (empty($files)) {
            throw new \moodle_exception('Invalid recycle bin item!');
        }

        if (count($files) > 1) {
            throw new \moodle_exception('Too many files found!');
        }

        // Get the backup file.
        $file = reset($files);

        // Get a backup temp directory name and create it.
        $tempdir = \restore_controller::get_tempdir_name($context->id, $user->id);
        $fulltempdir = make_backup_temp_directory($tempdir);

        // Extract the backup to tmpdir.
        $fb = get_file_packer('application/vnd.moodle.backup');
        $fb->extract_to_pathname($file, $fulltempdir);

        // Build a course.
        $course = new \stdClass();
        $course->category = $this->_categoryid;
        $course->shortname = $item->shortname;
        $course->fullname = $item->fullname;
        $course->summary = '';

        // Create a new course.
        $course = create_course($course);
        if (!$course) {
            throw new \moodle_exception("Could not create course to restore into.");
        }

        // Define the import.
        $controller = new \restore_controller(
            $tempdir,
            $course->id,
            \backup::INTERACTIVE_NO,
            \backup::MODE_AUTOMATED,
            $user->id,
            \backup::TARGET_NEW_COURSE
        );

        // Prechecks.
        if (!$controller->execute_precheck()) {
            $results = $controller->get_precheck_results();

            // Check if errors have been found.
            if (!empty($results['errors'])) {
                // Delete the temporary file we created.
                fulldelete($fulltempdir);

                // Delete the course we created.
                delete_course($course, false);

                echo $OUTPUT->header();
                $backuprenderer = $PAGE->get_renderer('core', 'backup');
                echo $backuprenderer->precheck_notices($results);
                echo $OUTPUT->continue_button(new \moodle_url('/course/index.php', array('categoryid' => $this->_categoryid)));
                echo $OUTPUT->footer();
                exit();
            }
        }

        // Run the import.
        $controller->execute_plan();

        // Have finished with the controller, let's destroy it, freeing mem and resources.
        $controller->destroy();

        // Fire event.
        $event = \tool_recyclebin\event\category_bin_item_restored::create(array(
            'objectid' => $item->id,
            'context' => $context
        ));
        $event->add_record_snapshot('tool_recyclebin_category', $item);
        $event->trigger();

        // Cleanup.
        fulldelete($fulltempdir);
        $this->delete_item($item);
    }
89203
protected function backupComposer()
    {
        $composerDir = $this->composer->getVendorDirectory() . '/composer';
        $composerBak = $composerDir . '.bak';

        // Remove old backup folder.
        if (is_dir($composerBak)) {
            $process = new Process('rm -rf "' . $composerBak . '"');
            $process->run();
            $isSuccessful = $process->isSuccessful();

            unset($process);

            if (!$isSuccessful) {
                return false;
            }
        }

        // Backup
        $process = new Process('cp -R "' . $composerDir . '" "' . $composerBak . '"');
        $process->run();
        $isSuccessful = $process->isSuccessful();

        unset($process);

        return $isSuccessful;
    }
244469
public function Backup_Init()
    {
        $sql = "-- -----------------------------\n";
        $sql .= "-- Think MySQL Data Transfer \n";
        $sql .= "-- \n";
        $sql .= "-- Host     : " . $this->dbconfig['hostname'] . "\n";
        $sql .= "-- Port     : " . $this->dbconfig['hostport'] . "\n";
        $sql .= "-- Database : " . $this->dbconfig['database'] . "\n";
        $sql .= "-- \n";
        $sql .= "-- Part : #{$this->file['part']}\n";
        $sql .= "-- Date : " . date("Y-m-d H:i:s") . "\n";
        $sql .= "-- -----------------------------\n\n";
        $sql .= "SET FOREIGN_KEY_CHECKS = 0;\n\n";
        return $this->write($sql);
    }
564027
def format_auto_backup_settings(result):
    '''
    
    '''
    from collections import OrderedDict
    # Only display parameters that have content
    order_dict = OrderedDict()
    if result.enable is not None:
        order_dict['enable'] = result.enable
    if result.enable_encryption is not None:
        order_dict['enableEncryption'] = result.enable_encryption
    if result.retention_period is not None:
        order_dict['retentionPeriod'] = result.retention_period
    if result.storage_account_url is not None:
        order_dict['storageAccountUrl'] = result.storage_account_url
    if result.backup_system_dbs is not None:
        order_dict['backupSystemDbs'] = result.backup_system_dbs
    if result.backup_schedule_type is not None:
        order_dict['backupScheduleType'] = result.backup_schedule_type
    if result.full_backup_frequency is not None:
        order_dict['fullBackupFrequency'] = result.full_backup_frequency
    if result.full_backup_start_time is not None:
        order_dict['fullBackupStartTime'] = result.full_backup_start_time
    if result.full_backup_window_hours is not None:
        order_dict['fullBackupWindowHours'] = result.full_backup_window_hours
    if result.log_backup_frequency is not None:
        order_dict['logBackupFrequency'] = result.log_backup_frequency

    return order_dict
868132
public function MoodleQuickForm_modgrade($elementname = null, $elementlabel = null, $options = array(), $attributes = null) {
        debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
        self::__construct($elementname, $elementlabel, $options, $attributes);
    }
269576
public function wrap_html_start() {
        echo \html_writer::start_tag('form',
            ['action' => new \moodle_url('/admin/tool/policy/accept.php')]);
        echo \html_writer::empty_tag('input', ['type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()]);
        echo \html_writer::empty_tag('input', ['type' => 'hidden', 'name' => 'returnurl',
            'value' => $this->get_return_url()]);
        foreach (array_keys($this->versionids) as $versionid) {
            echo \html_writer::empty_tag('input', ['type' => 'hidden', 'name' => 'versionids[]',
                'value' => $versionid]);
        }
    }
1141405
def to_h
      hash                        = {:churn => {:changes => @changes}}
      hash[:churn][:class_churn]  = @class_changes
      hash[:churn][:method_churn] = @method_changes
      #detail the most recent changes made this revision
      first_revision         = @revisions.first
      first_revision_changes = @revision_changes[first_revision]
      if first_revision_changes
        changes = first_revision_changes
        hash[:churn][:changed_files]   = changes[:files]
        hash[:churn][:changed_classes] = changes[:classes]
        hash[:churn][:changed_methods] = changes[:methods]
      end
      # TODO crappy place to do this but save hash to revision file but
      # while entirely under metric_fu only choice
      ChurnHistory.store_revision_history(first_revision, hash, @churn_options.data_directory)
      hash
    end
385572
def backup(schema, uuid, export_filter, export_format, filename, pretty, export_all, omit):
    """"""

    export_format = export_format.upper()

    if pretty:
        indent = 4
    else:
        indent = 0

    f = None

    if filename:
        try:
            f = open(filename, 'w')
        except (IOError, PermissionError) as e:
            backup_log('Could not open output file for writing:', exc=True, lvl=error)
            return

    def output(what, convert=False):
        """Output the backup in a specified format."""

        if convert:
            if export_format == 'JSON':
                data = json.dumps(what, indent=indent)
            else:
                data = ""
        else:
            data = what

        if not filename:
            print(data)
        else:
            f.write(data)

    if schema is None:
        if export_all is False:
            backup_log('No schema given.', lvl=warn)
            return
        else:
            schemata = objectmodels.keys()
    else:
        schemata = [schema]

    all_items = {}

    for schema_item in schemata:
        model = objectmodels[schema_item]

        if uuid:
            obj = model.find({'uuid': uuid})
        elif export_filter:
            obj = model.find(literal_eval(export_filter))
        else:
            obj = model.find()

        items = []
        for item in obj:
            fields = item.serializablefields()
            for field in omit:
                try:
                    fields.pop(field)
                except KeyError:
                    pass
            items.append(fields)

        all_items[schema_item] = items

        # if pretty is True:
        #    output('\n// Objectmodel: ' + schema_item + '\n\n')
        # output(schema_item + ' = [\n')

    output(all_items, convert=True)

    if f is not None:
        f.flush()
        f.close()