Uploads a course backup

@param int $hubcourseid id of the published course on moodle.net, it must be published from this site
@param \stored_file $backupfile
497552
public static function upload_course_backup($hubcourseid, \stored_file $backupfile) {
        $curl = new \curl();
        $params = array();
        $params['filetype'] = self::HUB_BACKUP_FILE_TYPE;
        $params['courseid'] = $hubcourseid;
        $params['file'] = $backupfile;
        $params['token'] = registration::get_token();
        $curl->post(HUB_MOODLEORGHUBURL . '/local/hub/webservice/upload.php', $params);
    }
1365142
protected function backupConfigFile($configFile)
    {
        if ($this->fs->exists($configFile)) {
            $this->fs->copy($configFile, $configFile . '-' . date('Y-m-d_H-i-s'));
        }
    }
499342
public function define_course_plugin_structure() {
        global $DB;

        // Since this method is executed before the restore we can do some pre-checks here.
        // In case of merging backup into existing course find the current number of sections.
        $target = $this->step->get_task()->get_target();
        if (($target == backup::TARGET_CURRENT_ADDING || $target == backup::TARGET_EXISTING_ADDING) &&
                $this->is_pre_33_backup()) {
            $maxsection = $DB->get_field_sql(
                'SELECT max(section) FROM {course_sections} WHERE course = ?',
                [$this->step->get_task()->get_courseid()]);
            $this->originalnumsections = (int)$maxsection;
        }

        // Dummy path element is needed in order for after_restore_course() to be called.
        return [new restore_path_element('dummy_course', $this->get_pathfor('/dummycourse'))];
    }
399165
public static function get_courseid_from_type_id($type, $id) {
        global $DB;
        if ($type == backup::TYPE_1COURSE) {
            return $id; // id is the course id

        } else if ($type == backup::TYPE_1SECTION) {
            if (! $courseid = $DB->get_field('course_sections', 'course', array('id' => $id))) {
                throw new backup_dbops_exception('course_not_found_for_section', $id);
            }
            return $courseid;
        } else if ($type == backup::TYPE_1ACTIVITY) {
            if (! $courseid = $DB->get_field('course_modules', 'course', array('id' => $id))) {
                throw new backup_dbops_exception('course_not_found_for_moduleid', $id);
            }
            return $courseid;
        }
    }
558817
public static function save_site_info($formdata) {
        $cleanhuburl = clean_param(HUB_MOODLEORGHUBURL, PARAM_ALPHANUMEXT);
        foreach (self::FORM_FIELDS as $field) {
            set_config('site_' . $field . '_' . $cleanhuburl, $formdata->$field, 'hub');
        }
        // Even if the the connection with moodle.net fails, admin has manually submitted the form which means they don't need
        // to be redirected to the site registration page any more.
        set_config('site_regupdateversion_' . $cleanhuburl, max(array_keys(self::CONFIRM_NEW_FIELDS)), 'hub');
    }
1013492
public static function backup_includes_file_references($backupid) {
        global $CFG, $DB;

        $sql = "SELECT count(r.repositoryid)
                  FROM {files} f
                  LEFT JOIN {files_reference} r
                       ON r.id = f.referencefileid
                  JOIN {backup_ids_temp} bi
                       ON f.id = bi.itemid
                 WHERE bi.backupid = ?
                       AND bi.itemname = 'filefinal'";
        $count = $DB->count_records_sql($sql, array($backupid));
        return (int)(bool)$count;
    }
786655
public function display(core_backup_renderer $renderer) {

        $format = backup_general_helper::detect_backup_format($this->filepath);

        if ($format === backup::FORMAT_MOODLE) {
            // Standard Moodle 2 format, let use get the type of the backup.
            $details = backup_general_helper::get_backup_information($this->filepath);
            if ($details->type === backup::TYPE_1COURSE) {
                $wholecourse = true;
            } else {
                $wholecourse = false;
            }

        } else {
            // Non-standard format to be converted. We assume it contains the
            // whole course for now. However, in the future there might be a callback
            // to the installed converters.
            $wholecourse = true;
        }

        $nextstageurl = new moodle_url('/backup/restore.php', array(
            'contextid' => $this->contextid,
            'filepath'  => $this->filepath,
            'stage'     => restore_ui::STAGE_SETTINGS));
        $context = context::instance_by_id($this->contextid);

        if ($context->contextlevel == CONTEXT_COURSE and has_capability('moodle/restore:restorecourse', $context)) {
            $currentcourse = $context->instanceid;
        } else {
            $currentcourse = false;
        }

        return $renderer->course_selector($nextstageurl, $wholecourse, $this->categorysearch, $this->coursesearch, $currentcourse);
    }
1008591
public static function copy_file_moodle2backup($backupid, $filerecorid) {
        global $DB;

        if (!backup_controller_dbops::backup_includes_files($backupid)) {
            // Only include the files if required by the controller.
            return;
        }

        // Normalise param
        if (!is_object($filerecorid)) {
            $filerecorid = $DB->get_record('files', array('id' => $filerecorid));
        }

        // Directory, nothing to do
        if ($filerecorid->filename === '.') {
            return;
        }

        $fs = get_file_storage();
        $file = $fs->get_file_instance($filerecorid);
        // If the file is external file, skip copying.
        if ($file->is_external_file()) {
            return;
        }

        // Calculate source and target paths (use same subdirs strategy for both)
        $targetfilepath = self::get_backup_storage_base_dir($backupid) . '/' .
                          self::get_backup_content_file_location($filerecorid->contenthash);

        // Create target dir if necessary
        if (!file_exists(dirname($targetfilepath))) {
            if (!check_dir_exists(dirname($targetfilepath), true, true)) {
                throw new backup_helper_exception('cannot_create_directory', dirname($targetfilepath));
            }
        }

        // And copy the file (if doesn't exist already)
        if (!file_exists($targetfilepath)) {
            $file->copy_content_to($targetfilepath);
        }
    }
808094
public function after_restore_course() {
        if (!$this->is_pre_33_backup()) {
            // Backup file was made in Moodle 3.3 or later, we don't need to process it.
            return;
        }

        $backupinfo = $this->step->get_task()->get_info();
        if ($backupinfo->original_course_format !== 'weeks') {
            // Backup from another course format.
            return;
        }

        $data = $this->connectionpoint->get_data();

        // Backup may not include the end date, so set it to 0.
        $enddate = isset($data['tags']['enddate']) ? $data['tags']['enddate'] : 0;

        // Set the automatic end date setting and the course end date (if applicable).
        $this->update_automatic_end_date($enddate);

        if (isset($data['tags']['numsections'])) {
            // Update course sections visibility.
            $numsections = (int)$data['tags']['numsections'];
            $this->update_course_sections_visibility($numsections);
        }
    }
213146
public function execute() {
        if ($this->controller->get_status() != backup::STATUS_AWAITING) {
            throw new backup_controller_exception('backup_not_executable_awaiting_required', $this->controller->get_status());
        }
        $this->controller->set_status(backup::STATUS_EXECUTING);
        parent::execute();
        $this->controller->set_status(backup::STATUS_FINISHED_OK);

        if ($this->controller->get_type() === backup::TYPE_1COURSE) {
            // Trigger a course_backup_created event.
            $otherarray = array('format' => $this->controller->get_format(),
                                'mode' => $this->controller->get_mode(),
                                'interactive' => $this->controller->get_interactive(),
                                'type' => $this->controller->get_type(),
            );
            $event = \core\event\course_backup_created::create(array(
                'objectid' => $this->get_courseid(),
                'context' => context_course::instance($this->get_courseid()),
                'other' => $otherarray
            ));
            $event->trigger();
        }
    }
672521
public function store(UploadedFileSource $file, $folderId, $userId, $originalFileId, $useWizard)
    {
        $tempId = uniqid();
        $tempDir = $this->tempDir.'/'.$tempId.'/';
        $tempName = $tempDir.basename($file->getPath());

        if (!file_exists($tempDir) && !mkdir($tempDir, 0777, true)) {
            throw new StoreUploadedFileException('Error occured while creating temp upload folder.');
        }

        if (!move_uploaded_file($file->getPath(), $tempName)) {
            throw new StoreUploadedFileException('Error occured during uploaded file move.');
        }

        $tempFile = new TempFile(
            $tempId,
            $file->getName(),
            $tempName,
            $file->getMimeType(),
            $file->getSize(),
            $this->hasher->fromPath($tempName),
            $originalFileId,
            $folderId,
            $userId,
            $useWizard
        );

        /*
        $event = new BeforeStoreUploadEvent($this, $tempFile);
        if ($this->dispatcher->dispatch(MediaSiteEvents::BEFORE_STORE_UPLOAD, $event)->isPropagationStopped()) {
            return null;
        }
        */

        $tempFiles = $this->session->get('mediamanager.temp_files');
        $tempFiles[$tempId] = $tempFile;
        $this->session->set('mediamanager.temp_files', $tempFiles);

        /*
        $event = new StoreUploadEvent($this, $tempFile);
        $this->dispatcher->dispatch(MediaSiteEvents::STORE_UPLOAD, $event);
        */

        return $tempFile;
    }
458044
private function makeBackup ()
    {
        $this->createDirectory($this->backupDirectory);
        $this->createDirectory($this->backupDirectory . '/config');

        File::copyDirectory('app', $this->backupDirectory . '/app');
        File::copyDirectory('bootstrap', $this->backupDirectory . '/bootstrap');
        File::copyDirectory('routes', $this->backupDirectory . '/routes');

        File::copy('composer.json', $this->backupDirectory . '/composer.json');
        File::copy('config/auth.php', $this->backupDirectory . '/config/auth.php');
        File::copy('config/database.php', $this->backupDirectory . '/config/database.php');
    }
717982
def file_write(filepath, newcontent, backup=false)
      if self.file_exists?(filepath)
        self.cp filepath, "#{filepath}-previous" if backup
      end
      
      content = StringIO.new
      content.puts newcontent
      self.file_upload content, filepath
    end
1091068
func (be *BuiltinBackupEngine) backupFile(ctx context.Context, cnf *Mycnf, mysqld MysqlDaemon, logger logutil.Logger, bh backupstorage.BackupHandle, fe *FileEntry, name string, hookExtraEnv map[string]string) (err error) {
	// Open the source file for reading.
	var source *os.File
	source, err = fe.open(cnf, true)
	if err != nil {
		return err
	}
	defer source.Close()

	fi, err := source.Stat()
	if err != nil {
		return err
	}

	logger.Infof("Backing up file: %v", fe.Name)
	// Open the destination file for writing, and a buffer.
	wc, err := bh.AddFile(ctx, name, fi.Size())
	if err != nil {
		return vterrors.Wrapf(err, "cannot add file: %v,%v", name, fe.Name)
	}
	defer func(name, fileName string) {
		if rerr := wc.Close(); rerr != nil {
			if err != nil {
				// We already have an error, just log this one.
				logger.Errorf2(rerr, "failed to close file %v,%v", name, fe.Name)
			} else {
				err = rerr
			}
		}
	}(name, fe.Name)
	dst := bufio.NewWriterSize(wc, writerBufferSize)

	// Create the hasher and the tee on top.
	hasher := newHasher()
	writer := io.MultiWriter(dst, hasher)

	// Create the external write pipe, if any.
	var pipe io.WriteCloser
	var wait hook.WaitFunc
	if *backupStorageHook != "" {
		h := hook.NewHook(*backupStorageHook, []string{"-operation", "write"})
		h.ExtraEnv = hookExtraEnv
		pipe, wait, _, err = h.ExecuteAsWritePipe(writer)
		if err != nil {
			return vterrors.Wrapf(err, "'%v' hook returned error", *backupStorageHook)
		}
		writer = pipe
	}

	// Create the gzip compression pipe, if necessary.
	var gzip *pgzip.Writer
	if *backupStorageCompress {
		gzip, err = pgzip.NewWriterLevel(writer, pgzip.BestSpeed)
		if err != nil {
			return vterrors.Wrap(err, "cannot create gziper")
		}
		gzip.SetConcurrency(*backupCompressBlockSize, *backupCompressBlocks)
		writer = gzip
	}

	// Copy from the source file to writer (optional gzip,
	// optional pipe, tee, output file and hasher).
	_, err = io.Copy(writer, source)
	if err != nil {
		return vterrors.Wrap(err, "cannot copy data")
	}

	// Close gzip to flush it, after that all data is sent to writer.
	if gzip != nil {
		if err = gzip.Close(); err != nil {
			return vterrors.Wrap(err, "cannot close gzip")
		}
	}

	// Close the hook pipe if necessary.
	if pipe != nil {
		if err := pipe.Close(); err != nil {
			return vterrors.Wrap(err, "cannot close hook pipe")
		}
		stderr, err := wait()
		if stderr != "" {
			logger.Infof("'%v' hook returned stderr: %v", *backupStorageHook, stderr)
		}
		if err != nil {
			return vterrors.Wrapf(err, "'%v' returned error", *backupStorageHook)
		}
	}

	// Flush the buffer to finish writing on destination.
	if err = dst.Flush(); err != nil {
		return vterrors.Wrapf(err, "cannot flush destination: %v", name)
	}

	// Save the hash.
	fe.Hash = hasher.HashString()
	return nil
}
691714
protected function add_html_formatting(backup_setting $setting) {
        $mform = $this->_form;
        $isincludesetting = (strpos($setting->get_name(), '_include') !== false);
        if ($isincludesetting && $setting->get_level() != backup_setting::ROOT_LEVEL) {
            switch ($setting->get_level()) {
                case backup_setting::COURSE_LEVEL:
                    if ($this->activitydiv) {
                        $this->_form->addElement('html', html_writer::end_tag('div'));
                        $this->activitydiv = false;
                    }
                    if ($this->sectiondiv) {
                        $this->_form->addElement('html', html_writer::end_tag('div'));
                        $this->sectiondiv = false;
                    }
                    if ($this->coursediv) {
                        $this->_form->addElement('html', html_writer::end_tag('div'));
                    }
                    $mform->addElement('html', html_writer::start_tag('div', array('class' => 'grouped_settings course_level')));
                    $mform->addElement('html', html_writer::start_tag('div', array('class' => 'include_setting course_level')));
                    $this->coursediv = true;
                    break;
                case backup_setting::SECTION_LEVEL:
                    if ($this->activitydiv) {
                        $this->_form->addElement('html', html_writer::end_tag('div'));
                        $this->activitydiv = false;
                    }
                    if ($this->sectiondiv) {
                        $this->_form->addElement('html', html_writer::end_tag('div'));
                    }
                    $mform->addElement('html', html_writer::start_tag('div', array('class' => 'grouped_settings section_level')));
                    $mform->addElement('html', html_writer::start_tag('div', array('class' => 'include_setting section_level')));
                    $this->sectiondiv = true;
                    break;
                case backup_setting::ACTIVITY_LEVEL:
                    if ($this->activitydiv) {
                        $this->_form->addElement('html', html_writer::end_tag('div'));
                    }
                    $mform->addElement('html', html_writer::start_tag('div', array('class' => 'grouped_settings activity_level')));
                    $mform->addElement('html', html_writer::start_tag('div', array('class' => 'include_setting activity_level')));
                    $this->activitydiv = true;
                    break;
                default:
                    $mform->addElement('html', html_writer::start_tag('div', array('class' => 'normal_setting')));
                    break;
            }
        } else if ($setting->get_level() == backup_setting::ROOT_LEVEL) {
            $mform->addElement('html', html_writer::start_tag('div', array('class' => 'root_setting')));
        } else {
            $mform->addElement('html', html_writer::start_tag('div', array('class' => 'normal_setting')));
        }
    }
846609
public function upload($local_path, $remote_path, $mode = 'auto', $permissions = null)
	{
		if ( ! $this->_is_conn())
		{
			return false;
		}

		if ( ! is_file($local_path))
		{
			throw new \FtpFileAccessException('No source file');
			return false;
		}

		// Set the mode if not specified
		if ($mode == 'auto')
		{
			// Get the file extension so we can set the upload type
			$ext = pathinfo($local_path, PATHINFO_EXTENSION);
			$mode = $this->_settype($ext);
		}

		$mode = ($mode == 'ascii') ? FTP_ASCII : FTP_BINARY;

		$result = @ftp_put($this->_conn_id, $remote_path, $local_path, $mode);

		if ($result === false)
		{
			if ($this->_debug == true)
			{
				throw new \FtpFileAccessException('Unable to upload');
			}
			return false;
		}

		// Set file permissions if needed
		if ($permissions !== null)
		{
			$this->chmod($remote_path, (int) $permissions);
		}

		return true;
	}
137367
public function import_course_selector(moodle_url $nextstageurl, import_course_search $courses = null) {
        $html  = html_writer::start_tag('div', array('class' => 'import-course-selector backup-restore'));
        $html .= html_writer::start_tag('form', array('method' => 'post', 'action' => $nextstageurl->out_omit_querystring()));
        foreach ($nextstageurl->params() as $key => $value) {
            $html .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $key, 'value' => $value));
        }
        // We only allow import adding for now. Enforce it here.
        $html .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'target', 'value' => backup::TARGET_CURRENT_ADDING));
        $html .= html_writer::start_tag('div', array('class' => 'ics-existing-course backup-section'));
        $html .= $this->output->heading(get_string('importdatafrom'), 2, array('class' => 'header'));
        $html .= $this->backup_detail_pair(get_string('selectacourse', 'backup'), $this->render($courses));
        $attrs = array('type' => 'submit', 'value' => get_string('continue'), 'class' => 'btn btn-primary');
        $html .= $this->backup_detail_pair('', html_writer::empty_tag('input', $attrs));
        $html .= html_writer::end_tag('div');
        $html .= html_writer::end_tag('form');
        $html .= html_writer::end_tag('div');
        return $html;
    }