<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * @package moodlecore
 * @subpackage backup-tests
 * @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
    die('Direct access to this script is forbidden.');
}

// Include all the needed stuff
require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');

/*
 * check tests (all)
 */
class backup_check_test extends UnitTestCase {

    public static $includecoverage = array('backup/util/checks');
    public static $excludecoverage = array('backup/util/checks/simpletest');

    protected $moduleid;  // course_modules id used for testing
    protected $sectionid; // course_sections id used for testing
    protected $courseid;  // course id used for testing
    protected $userid;    // user record id

    protected $errorlogloggerlevel; // To store $CFG->backup_error_log_logger_level
    protected $fileloggerlevel; // To store level $CFG->backup_file_logger_level
    protected $databaseloggerlevel; // To store $CFG->backup_database_logger_level
    protected $outputindentedloggerlevel; // To store $CFG->backup_output_indented_logger_level
    protected $fileloggerextra; // To store $CFG->backup_file_logger_extra
    protected $fileloggerlevelextra; // To store level $CFG->backup_file_logger_level_extra
    protected $debugging; // To store $CFG->debug
    protected $debugdisplay; // To store $CFG->debugdisplay

    function __construct() {
        global $DB, $USER, $CFG;

        $this->moduleid  = 0;
        $this->sectionid = 0;
        $this->courseid  = 0;
        $this->userid = $USER->id;

        // Check we have (at least) one course_module
        if ($coursemodule = $DB->get_record('course_modules', array(), '*', IGNORE_MULTIPLE)) {
            $this->moduleid  = $coursemodule->id;
            $this->sectionid = $coursemodule->section;
            $this->courseid  = $coursemodule->course;
        }
        parent::__construct();
    }

    function skip() {
        $this->skipIf(empty($this->moduleid), 'backup_check_test require at least one course module to exist');
        $this->skipIf(empty($this->sectionid),'backup_check_test require at least one course section to exist');
        $this->skipIf(empty($this->courseid), 'backup_check_test require at least one course to exist');
        $this->skipIf(empty($this->userid),'backup_check_test require one valid user to exist');
    }

    function setUp() {
        global $CFG;
        parent::setUp();
        // Avoid any file logger to be created, we'll restore original settings on tearDown()
        // Fetch the rest of CFG variables to be able to restore them after tests
        // and normalize default values
        $this->errorlogloggerlevel = isset($CFG->backup_error_log_logger_level) ? $CFG->backup_error_log_logger_level : null;
        $CFG->backup_error_log_logger_level = backup::LOG_NONE;

        $this->outputindentedloggerlevel = isset($CFG->backup_output_indented_logger_level) ? $CFG->backup_output_indented_logger_level : null;
        $CFG->backup_output_indented_logger_level = backup::LOG_NONE;

        $this->fileloggerlevel = isset($CFG->backup_file_logger_level) ? $CFG->backup_file_logger_level : null;
        $CFG->backup_file_logger_level = backup::LOG_NONE;

        $this->databaseloggerlevel = isset($CFG->backup_database_logger_level) ? $CFG->backup_database_logger_level : null;
        $CFG->backup_database_logger_level = backup::LOG_NONE;

        $this->fileloggerextra = isset($CFG->backup_file_logger_extra) ? $CFG->backup_file_logger_extra : null;
        unset($CFG->backup_file_logger_extra);
        $this->fileloggerlevelextra = isset($CFG->backup_file_logger_level_extra) ? $CFG->backup_file_logger_level_extra : null;
        $CFG->backup_file_logger_level_extra = backup::LOG_NONE;

        $this->debugging = isset($CFG->debug) ? $CFG->debug : null;
        $this->debugdisplay = isset($CFG->debugdisplay) ? $CFG->debugdisplay : null;
    }

    function tearDown() {
        global $CFG;
        // Restore original file_logger levels
        if ($this->errorlogloggerlevel !== null) {
            $CFG->backup_error_log_logger_level = $this->errorlogloggerlevel;
        } else {
            unset($CFG->backup_error_log_logger_level);
        }

        if ($this->outputindentedloggerlevel !== null) {
            $CFG->backup_output_indented_logger_level = $this->outputindentedloggerlevel;
        } else {
            unset($CFG->backup_output_indented_logger_level);
        }

        if ($this->fileloggerlevel !== null) {
            $CFG->backup_file_logger_level = $this->fileloggerlevel;
        } else {
            unset($CFG->backup_file_logger_level);
        }

        if ($this->databaseloggerlevel !== null) {
            $CFG->backup_database_logger_level = $this->databaseloggerlevel;
        } else {
            unset($CFG->backup_database_logger_level);
        }

        if ($this->fileloggerextra !== null) {
            $CFG->backup_file_logger_extra = $this->fileloggerextra;
        } else {
            unset($CFG->backup_file_logger_extra);
        }
        if ($this->fileloggerlevelextra !== null) {
            $CFG->backup_file_logger_level_extra = $this->fileloggerlevelextra;
        } else {
            unset($CFG->backup_file_logger_level_extra);
        }
        // Restore the rest of $CFG settings
        if ($this->debugging !== null) {
            $CFG->debug = $this->debugging;
        } else {
            unset($CFG->debug);
        }
        if ($this->debugdisplay !== null) {
            $CFG->debugdisplay = $this->debugdisplay;
        } else {
            unset($CFG->debugdisplay);
        }
        parent::tearDown();
    }

    /*
     * test backup_check class
     */
    function test_backup_check() {

        // Check against existing course module/section course or fail
        $this->assertTrue(backup_check::check_id(backup::TYPE_1ACTIVITY, $this->moduleid));
        $this->assertTrue(backup_check::check_id(backup::TYPE_1SECTION, $this->sectionid));
        $this->assertTrue(backup_check::check_id(backup::TYPE_1COURSE, $this->courseid));
        $this->assertTrue(backup_check::check_user($this->userid));

        // Check agains non-existing course module/section/course (0)
        try {
            backup_check::check_id(backup::TYPE_1ACTIVITY, 0);
            $this->assertTrue(false, 'backup_controller_exception expected');
        } catch (exception $e) {
            $this->assertTrue($e instanceof backup_controller_exception);
            $this->assertEqual($e->errorcode, 'backup_check_module_not_exists');
        }
        try {
            backup_check::check_id(backup::TYPE_1SECTION, 0);
            $this->assertTrue(false, 'backup_controller_exception expected');
        } catch (exception $e) {
            $this->assertTrue($e instanceof backup_controller_exception);
            $this->assertEqual($e->errorcode, 'backup_check_section_not_exists');
        }
        try {
            backup_check::check_id(backup::TYPE_1COURSE, 0);
            $this->assertTrue(false, 'backup_controller_exception expected');
        } catch (exception $e) {
            $this->assertTrue($e instanceof backup_controller_exception);
            $this->assertEqual($e->errorcode, 'backup_check_course_not_exists');
        }

        // Try wrong type
        try {
            backup_check::check_id(12345678,0);
            $this->assertTrue(false, 'backup_controller_exception expected');
        } catch (exception $e) {
            $this->assertTrue($e instanceof backup_controller_exception);
            $this->assertEqual($e->errorcode, 'backup_check_incorrect_type');
        }

        // Test non-existing user
        $userid = 0;
        try {
            backup_check::check_user($userid);
            $this->assertTrue(false, 'backup_controller_exception expected');
        } catch (exception $e) {
            $this->assertTrue($e instanceof backup_controller_exception);
            $this->assertEqual($e->errorcode, 'backup_check_user_not_exists');
        }

        // Security check tests
        // Try to pass wrong controller
        try {
            backup_check::check_security(new stdclass(), true);
            $this->assertTrue(false, 'backup_controller_exception expected');
        } catch (exception $e) {
            $this->assertTrue($e instanceof backup_controller_exception);
            $this->assertEqual($e->errorcode, 'backup_check_security_requires_backup_controller');
        }

        // Pass correct controller, check must return true in any case with $apply enabled
        // and $bc must continue being mock_backup_controller
        $bc = new backup_controller(backup::TYPE_1ACTIVITY, $this->moduleid, backup::FORMAT_MOODLE,
                                    backup::INTERACTIVE_NO, backup::MODE_GENERAL, $this->userid);
        $this->assertTrue(backup_check::check_security($bc, true));
        $this->assertTrue($bc instanceof backup_controller);

    }
}
