//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
/**
 * @package block_mhaairs
 * @category admin
 * @copyright 2014 Itamar Tzadok
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
require_once '../../../config.php';
require_once "{$CFG->libdir}/adminlib.php";
require_once "{$CFG->dirroot}/blocks/mhaairs/block_mhaairs_util.php";
$delete = optional_param('delete', 0, PARAM_INT);
admin_externalpage_setup('blockmhaairs_gradelogs');
$baseurl = '/blocks/mhaairs/admin/gradelogs.php';
$logger = MHLog::instance();
// DATA PROCESSING.
if ($delete) {
    $logger->delete_all();
    redirect(new \moodle_url($baseurl));
}
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('gradelogs', 'block_mhaairs'));
if ($logs = $logger->logs) {
    // Print delete option.
    $url = new \moodle_url($baseurl, array('delete' => 1));
    $link = html_writer::link($url, get_string('deleteall'));
    echo html_writer::tag('div', $link);
    // Print summary.
    foreach ($logs as $logfile) {
        echo html_writer::tag('div', $logfile);
 /**
  * Tests deleting logs.
  *
  * @return void
  */
 public function test_delete_logs()
 {
     $this->resetAfterTest();
     // Enable logs.
     set_config('block_mhaairs_gradelog', 1);
     // Add 3 loggers.
     $log1 = MHLog::instance();
     $log2 = MHLog::instance();
     $log3 = MHLog::instance();
     // Add 3 loggers.
     $log1->log('Hello world');
     $log2->log('Hello universe');
     $log3->log('Big bang');
     // Verify we have 3 log files.
     $result = count(MHLog::instance()->logs);
     $this->assertEquals(3, $result);
     // Delete one.
     $log1->delete();
     // Verify we have 2 log files.
     $result = count(MHLog::instance()->logs);
     $this->assertEquals(2, $result);
     // Delete all.
     MHLog::instance()->delete_all();
     // Verify we have no log files.
     $result = count(MHLog::instance()->logs);
     $this->assertEquals(0, $result);
 }
 /**
  * Allows external systems to push grade items and scores into the course gradebook. The service as to be
  * activated by the site admin.
  * A typical usage requires two calls, the first to create/update the grade item and the second to update
  * the user grade. The create/update grade item call should not pass null for the grades. The update user
  * grade call may require the identity_type flag which can be passed either in the grades parameter or in
  * the itemdetails paramter. The latter is otherwise not required.
  *
  * @param string $source - Any string or empty.
  * @param string $courseid - Expected idnumber or Moodle id; requires identity_type in itemdetails.
  * @param string $itemtype - Ignored; all mhaairs items should be manual.
  * @param string $itemmodule - Ignored; all mhaairs items should be identified as mhaairs.
  * @param string $iteminstance - The mhaairs assignment id.
  * @param string $itemnumber - Any integer.
  * @param string $grades - Url encoded, json encoded, array of the following user grade details:
  *      userid - The user username or internal id (depends on identity_type). Required. PARAM_TEXT.
  *      rawgrade - The user grade. Optional. PARAM_FLOAT.
  *      identity_type - Whether to treat the userid as username or internal id. Optional. PARAM_ALPHA.
  * @param string $itemdetails - Url encoded, json encoded, array of the following item details and flags:
  *      itemname - The item name. Required. PARAM_TEXT.
  *      idnumber - The item idnumber. Optional. PARAM_TEXT.
  *      gradetype - The item grade type. Optional. PARAM_INT. Defaults to point.
  *      grademax - The item grade max. Optional. PARAM_FLOAT. Defaults to 100.
  *      hidden - Whether the item is hidden. Optional. PARAM_INT.
  *      deleted - Whether to delete the item. Optional. PARAM_INT.
  *      categoryid - The name of the target category for the item. Optional. PARAM_TEXT.
  *      identity_type - Whether to treat the courseid as idnumber or internal id. Optional. PARAM_ALPHA.
  *      needsupdate - Optional. PARAM_INT.
  *      useexisting - Whether to use an existing item by name. Optional. PARAM_INT.
  *
  * @return mixed
  * @throws invalid_parameter_exception
  * @throws moodle_exception
  */
 public static function update_grade($source = 'mhaairs', $courseid = '', $itemtype = self::ITEM_DEFAULT_TYPE, $itemmodule = self::ITEM_DEFAULT_MODULE, $iteminstance = '0', $itemnumber = '0', $grades = null, $itemdetails = null)
 {
     global $USER, $DB;
     $logger = MHLog::instance();
     $logger->log('==================================');
     $logger->log('New webservice request started on ' . $logger->time_stamp);
     $logger->log('Entry parameters:');
     $logger->log("source = {$source}");
     $logger->log("courseid = {$courseid}");
     $logger->log("itemtype = {$itemtype}");
     $logger->log("itemmodule = {$itemmodule}");
     $logger->log("iteminstance = {$iteminstance}");
     $logger->log("itemnumber = {$itemnumber}");
     $logger->log("grades = {$grades}");
     $logger->log("itemdetails = {$itemdetails}");
     // Gradebook sync must be enabled by admin in the block's site configuration.
     if (!($syncgrades = get_config('core', 'block_mhaairs_sync_gradebook'))) {
         $logger->log('Grade sync is not enabled in global settings. Returning 1.');
         return GRADE_UPDATE_FAILED;
     }
     // Parameters validation.
     $params = self::validate_parameters(self::update_grade_parameters(), array('source' => $source, 'courseid' => $courseid, 'itemtype' => $itemtype, 'itemmodule' => $itemmodule, 'iteminstance' => $iteminstance, 'itemnumber' => $itemnumber, 'grades' => $grades, 'itemdetails' => $itemdetails));
     $logger->log('Parameters validated.');
     // Extract the validated parameters to their respective variables.
     foreach ($params as $var => $value) {
         ${$var} = $value;
     }
     // Context validation.
     // OPTIONAL but in most web service it should be present.
     $context = context_user::instance($USER->id);
     self::validate_context($context);
     $logger->log('Context validated.');
     // Capability checking.
     // OPTIONAL but in most web service it should be present.
     require_capability('moodle/user:viewdetails', $context, null, true, 'cannotviewprofile');
     $logger->log('Capability validated.');
     // Validate item details.
     $logger->log("Checking if any item details were sent.");
     $itemdetails = json_decode(urldecode($itemdetails), true);
     $itemdetails = self::validate_item_details($itemdetails);
     $logger->log('Item details validated: ' . var_export($itemdetails, true));
     // Get the item details identity type variable.
     $identitytype = self::get_details_itentity_type($itemdetails);
     // Validate grades.
     $logger->log("Checking if any grades were sent.");
     $grades = json_decode(urldecode($grades), true);
     $grades = self::validate_grades($grades);
     // HACK Make sure grades has identity type; take from item details if must.
     if ($grades and !isset($grades['identity_type'])) {
         $grades['identity_type'] = null;
         if ($identitytype) {
             $grades['identity_type'] = $identitytype;
         }
     }
     $logger->log('Grades validated: ' . var_export($grades, true));
     // Get the course.
     if (!($course = self::get_course($courseid, $identitytype))) {
         // No valid course specified.
         $logger->log("Course id received was not correct. courseid = {$courseid}.");
         $logger->log('Returning ' . GRADE_UPDATE_FAILED . '.');
         return GRADE_UPDATE_FAILED;
     }
     $courseid = $course->id;
     $logger->log('Course validated.');
     if (!$grades) {
         // A request without grades is for creating/updating/deleting a grade item.
         $result = self::update_grade_item($source, $courseid, $iteminstance, $itemnumber, $itemdetails);
         $resultverbose = $result == GRADE_UPDATE_OK ? 'completed successfully' : 'failed';
         $logger->log("Grade item update {$resultverbose}");
     } else {
         $result = self::update_user_grade($source, $courseid, $iteminstance, $itemnumber, $grades);
         $resultverbose = $result == GRADE_UPDATE_OK ? 'completed successfully' : 'failed';
         $logger->log("User grade update {$resultverbose}");
     }
     return $result;
 }