/**
  * Send one backup controller to DB
  *
  * @param backup_controller $controller controller to send to DB
  * @param string $checksum hash of the controller to be checked
  * @param bool $includeobj to decide if the object itself must be updated (true) or no (false)
  * @param bool $cleanobj to decide if the object itself must be cleaned (true) or no (false)
  * @return int id of the controller record in the DB
  * @throws backup_controller_exception|backup_dbops_exception
  */
 public static function save_controller($controller, $checksum, $includeobj = true, $cleanobj = false)
 {
     global $DB;
     // Check we are going to save one backup_controller
     if (!$controller instanceof backup_controller) {
         throw new backup_controller_exception('backup_controller_expected');
     }
     // Check checksum is ok. Only if we are including object info. Sounds silly but it isn't ;-).
     if ($includeobj and !$controller->is_checksum_correct($checksum)) {
         throw new backup_dbops_exception('backup_controller_dbops_saving_checksum_mismatch');
     }
     // Cannot request to $includeobj and $cleanobj at the same time.
     if ($includeobj and $cleanobj) {
         throw new backup_dbops_exception('backup_controller_dbops_saving_cannot_include_and_delete');
     }
     // Get all the columns
     $rec = new stdclass();
     $rec->backupid = $controller->get_backupid();
     $rec->operation = $controller->get_operation();
     $rec->type = $controller->get_type();
     $rec->itemid = $controller->get_id();
     $rec->format = $controller->get_format();
     $rec->interactive = $controller->get_interactive();
     $rec->purpose = $controller->get_mode();
     $rec->userid = $controller->get_userid();
     $rec->status = $controller->get_status();
     $rec->execution = $controller->get_execution();
     $rec->executiontime = $controller->get_executiontime();
     $rec->checksum = $checksum;
     // Serialize information
     if ($includeobj) {
         $rec->controller = base64_encode(serialize($controller));
     } else {
         if ($cleanobj) {
             $rec->controller = '';
         }
     }
     // Send it to DB
     if ($recexists = $DB->get_record('backup_controllers', array('backupid' => $rec->backupid))) {
         $rec->id = $recexists->id;
         $rec->timemodified = time();
         $DB->update_record('backup_controllers', $rec);
     } else {
         $rec->timecreated = time();
         $rec->timemodified = 0;
         $rec->id = $DB->insert_record('backup_controllers', $rec);
     }
     return $rec->id;
 }