Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.0.x will end 8 May 2023 (12 months).
  • Bug fixes for security issues in 4.0.x will end 13 November 2023 (18 months).
  • PHP version: minimum PHP 7.3.0 Note: the minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is also supported.

Differences Between: [Versions 400 and 401] [Versions 400 and 402] [Versions 400 and 403]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  declare(strict_types=1);
  18  
  19  namespace core_reportbuilder\local\helpers;
  20  
  21  use context_user;
  22  use core_plugin_manager;
  23  use core_user;
  24  use invalid_parameter_exception;
  25  use stdClass;
  26  use stored_file;
  27  use table_dataformat_export_format;
  28  use core\message\message;
  29  use core\plugininfo\dataformat;
  30  use core_reportbuilder\local\models\audience as audience_model;
  31  use core_reportbuilder\local\models\schedule as model;
  32  use core_reportbuilder\table\custom_report_table_view;
  33  
  34  /**
  35   * Helper class for report schedule related methods
  36   *
  37   * @package     core_reportbuilder
  38   * @copyright   2021 Paul Holden <paulh@moodle.com>
  39   * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  40   */
  41  class schedule {
  42  
  43      /**
  44       * Create report schedule, calculate when it should be next sent
  45       *
  46       * @param stdClass $data
  47       * @param int|null $timenow Time to use as comparison against current date (defaults to current time)
  48       * @return model
  49       */
  50      public static function create_schedule(stdClass $data, ?int $timenow = null): model {
  51          $data->name = trim($data->name);
  52  
  53          $schedule = (new model(0, $data));
  54          $schedule->set('timenextsend', self::calculate_next_send_time($schedule, $timenow));
  55  
  56          return $schedule->create();
  57      }
  58  
  59      /**
  60       * Update report schedule
  61       *
  62       * @param stdClass $data
  63       * @return model
  64       * @throws invalid_parameter_exception
  65       */
  66      public static function update_schedule(stdClass $data): model {
  67          $schedule = model::get_record(['id' => $data->id, 'reportid' => $data->reportid]);
  68          if ($schedule === false) {
  69              throw new invalid_parameter_exception('Invalid schedule');
  70          }
  71  
  72          // Normalize model properties.
  73          $data = array_intersect_key((array) $data, model::properties_definition());
  74          if (array_key_exists('name', $data)) {
  75              $data['name'] = trim($data['name']);
  76          }
  77  
  78          $schedule->set_many($data);
  79          $schedule->set('timenextsend', self::calculate_next_send_time($schedule))
  80              ->update();
  81  
  82          return $schedule;
  83      }
  84  
  85      /**
  86       * Toggle report schedule enabled
  87       *
  88       * @param int $reportid
  89       * @param int $scheduleid
  90       * @param bool $enabled
  91       * @return bool
  92       * @throws invalid_parameter_exception
  93       */
  94      public static function toggle_schedule(int $reportid, int $scheduleid, bool $enabled): bool {
  95          $schedule = model::get_record(['id' => $scheduleid, 'reportid' => $reportid]);
  96          if ($schedule === false) {
  97              throw new invalid_parameter_exception('Invalid schedule');
  98          }
  99  
 100          return $schedule->set('enabled', $enabled)->update();
 101      }
 102  
 103      /**
 104       * Return array of users who match the audience records added to the given schedule
 105       *
 106       * @param model $schedule
 107       * @return stdClass[]
 108       */
 109      public static function get_schedule_report_users(model $schedule): array {
 110          global $DB;
 111  
 112          $audienceids = (array) json_decode($schedule->get('audiences'));
 113  
 114          // Retrieve all selected audience records for the schedule.
 115          [$audienceselect, $audienceparams] = $DB->get_in_or_equal($audienceids, SQL_PARAMS_NAMED, 'aid', true, true);
 116          $audiences = audience_model::get_records_select("id {$audienceselect}", $audienceparams);
 117          if (count($audiences) === 0) {
 118              return [];
 119          }
 120  
 121          // Now convert audiences to SQL for user retrieval.
 122          [$wheres, $params] = audience::user_audience_sql($audiences);
 123          [$userorder] = users_order_by_sql('u');
 124  
 125          $sql = 'SELECT u.*
 126                    FROM {user} u
 127                   WHERE ' . implode(' OR ', $wheres) . '
 128                ORDER BY ' . $userorder;
 129  
 130          return $DB->get_records_sql($sql, $params);
 131      }
 132  
 133      /**
 134       * Return count of schedule report rows
 135       *
 136       * @param model $schedule
 137       * @return int
 138       */
 139      public static function get_schedule_report_count(model $schedule): int {
 140          global $DB;
 141  
 142          $table = custom_report_table_view::create($schedule->get('reportid'));
 143          $table->setup();
 144  
 145          return $DB->count_records_sql($table->countsql, $table->countparams);
 146      }
 147  
 148      /**
 149       * Generate stored file instance for given schedule, in user draft
 150       *
 151       * @param model $schedule
 152       * @return stored_file
 153       */
 154      public static function get_schedule_report_file(model $schedule): stored_file {
 155          global $CFG;
 156          require_once("{$CFG->libdir}/filelib.php");
 157  
 158          $table = custom_report_table_view::create($schedule->get('reportid'));
 159  
 160          $table->setup();
 161          $table->query_db(0, false);
 162  
 163          // Set up table as if it were being downloaded, retrieve appropriate export class (ensure output buffer is
 164          // cleaned in order to instantiate export class without exception).
 165          ob_start();
 166          $table->download = $schedule->get('format');
 167          $exportclass = new table_dataformat_export_format($table, $table->download);
 168          ob_end_clean();
 169  
 170          // Create our schedule report stored file.
 171          $context = context_user::instance($schedule->get('usercreated'));
 172          $filerecord = [
 173              'contextid' => $context->id,
 174              'component' => 'user',
 175              'filearea' => 'draft',
 176              'itemid' => file_get_unused_draft_itemid(),
 177              'filepath' => '/',
 178              'filename' => clean_filename($schedule->get_formatted_name()),
 179          ];
 180  
 181          $storedfile = \core\dataformat::write_data_to_filearea(
 182              $filerecord,
 183              $table->download,
 184              $exportclass->format_data($table->headers),
 185              $table->rawdata,
 186              static function(stdClass $record, bool $supportshtml) use ($table, $exportclass): array {
 187                  $record = $table->format_row($record);
 188                  if (!$supportshtml) {
 189                      $record = $exportclass->format_data($record);
 190                  }
 191                  return $record;
 192              }
 193          );
 194  
 195          $table->close_recordset();
 196  
 197          return $storedfile;
 198      }
 199  
 200      /**
 201       * Check whether given schedule needs to be sent
 202       *
 203       * @param model $schedule
 204       * @return bool
 205       */
 206      public static function should_send_schedule(model $schedule): bool {
 207          if (!$schedule->get('enabled')) {
 208              return false;
 209          }
 210  
 211          $timenow = time();
 212  
 213          // Ensure we've reached the initial scheduled start time.
 214          $timescheduled = $schedule->get('timescheduled');
 215          if ($timescheduled > $timenow) {
 216              return false;
 217          }
 218  
 219          // If there's no recurrence, check whether it's been sent since initial scheduled start time. This ensures that even if
 220          // the schedule was manually sent beforehand, it'll still be automatically sent once the start time is first reached.
 221          if ($schedule->get('recurrence') === model::RECURRENCE_NONE) {
 222              return $schedule->get('timelastsent') < $timescheduled;
 223          }
 224  
 225          return $schedule->get('timenextsend') <= $timenow;
 226      }
 227  
 228      /**
 229       * Calculate the next time a schedule should be sent, based on it's recurrence and when it was initially scheduled. Ensures
 230       * returned value is after the current date
 231       *
 232       * @param model $schedule
 233       * @param int|null $timenow Time to use as comparison against current date (defaults to current time)
 234       * @return int
 235       */
 236      public static function calculate_next_send_time(model $schedule, ?int $timenow = null): int {
 237          global $CFG;
 238  
 239          $timenow = $timenow ?? time();
 240  
 241          $recurrence = $schedule->get('recurrence');
 242          $timescheduled = $schedule->get('timescheduled');
 243  
 244          // If no recurrence is set or we haven't reached last sent date, return early.
 245          if ($recurrence === model::RECURRENCE_NONE || $timescheduled > $timenow) {
 246              return $timescheduled;
 247          }
 248  
 249          // Extract attributes from date (year, month, day, hours, minutes).
 250          [
 251              'year' => $year,
 252              'mon' => $month,
 253              'mday' => $day,
 254              'wday' => $dayofweek,
 255              'hours' => $hour,
 256              'minutes' => $minute,
 257          ] = usergetdate($timescheduled, $CFG->timezone);
 258  
 259          switch ($recurrence) {
 260              case model::RECURRENCE_DAILY:
 261                  $day += 1;
 262              break;
 263              case model::RECURRENCE_WEEKDAYS:
 264                  $day += 1;
 265  
 266                  $calendar = \core_calendar\type_factory::get_calendar_instance();
 267                  $weekend = get_config('core', 'calendar_weekend');
 268  
 269                  // Increment day until day of week falls on a weekday.
 270                  while ((bool) ($weekend & (1 << (++$dayofweek % $calendar->get_num_weekdays())))) {
 271                      $day++;
 272                  }
 273              break;
 274              case model::RECURRENCE_WEEKLY:
 275                  $day += 7;
 276              break;
 277              case model::RECURRENCE_MONTHLY:
 278                  $month += 1;
 279              break;
 280              case model::RECURRENCE_ANNUALLY:
 281                  $year += 1;
 282              break;
 283          }
 284  
 285          // We need to recursively increment the timestamp until we get one after the current time.
 286          $timestamp = make_timestamp($year, $month, $day, $hour, $minute, 0, $CFG->timezone);
 287          if ($timestamp < $timenow) {
 288              // Ensure we don't modify anything in the original model.
 289              $scheduleclone = new model(0, $schedule->to_record());
 290  
 291              return self::calculate_next_send_time(
 292                  $scheduleclone->set('timescheduled', $timestamp), $timenow);
 293          } else {
 294              return $timestamp;
 295          }
 296      }
 297  
 298      /**
 299       * Send schedule message to user
 300       *
 301       * @param model $schedule
 302       * @param stdClass $user
 303       * @param stored_file $attachment
 304       * @return bool
 305       */
 306      public static function send_schedule_message(model $schedule, stdClass $user, stored_file $attachment): bool {
 307          $message = new message();
 308          $message->component = 'moodle';
 309          $message->name = 'reportbuilderschedule';
 310          $message->courseid = SITEID;
 311          $message->userfrom = core_user::get_noreply_user();
 312          $message->userto = $user;
 313          $message->subject = $schedule->get('subject');
 314          $message->fullmessage = $schedule->get('message');
 315          $message->fullmessageformat = $schedule->get('messageformat');
 316          $message->fullmessagehtml = $message->fullmessage;
 317          $message->smallmessage = $message->fullmessage;
 318  
 319          // Attach report to outgoing message.
 320          $message->attachment = $attachment;
 321          $message->attachname = $attachment->get_filename();
 322  
 323          return (bool) message_send($message);
 324      }
 325  
 326      /**
 327       * Delete report schedule
 328       *
 329       * @param int $reportid
 330       * @param int $scheduleid
 331       * @return bool
 332       * @throws invalid_parameter_exception
 333       */
 334      public static function delete_schedule(int $reportid, int $scheduleid): bool {
 335          $schedule = model::get_record(['id' => $scheduleid, 'reportid' => $reportid]);
 336          if ($schedule === false) {
 337              throw new invalid_parameter_exception('Invalid schedule');
 338          }
 339  
 340          return $schedule->delete();
 341      }
 342  
 343      /**
 344       * Return list of available data formats
 345       *
 346       * @return string[]
 347       */
 348      public static function get_format_options(): array {
 349          $dataformats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
 350  
 351          return array_map(static function(dataformat $dataformat): string {
 352              return $dataformat->displayname;
 353          }, $dataformats);
 354      }
 355  
 356      /**
 357       * Return list of available view as user options
 358       *
 359       * @return string[]
 360       */
 361      public static function get_viewas_options(): array {
 362          return [
 363              model::REPORT_VIEWAS_CREATOR => get_string('scheduleviewascreator', 'core_reportbuilder'),
 364              model::REPORT_VIEWAS_RECIPIENT => get_string('scheduleviewasrecipient', 'core_reportbuilder'),
 365              model::REPORT_VIEWAS_USER => get_string('userselect', 'core_reportbuilder'),
 366          ];
 367      }
 368  
 369      /**
 370       * Return list of recurrence options
 371       *
 372       * @return string[]
 373       */
 374      public static function get_recurrence_options(): array {
 375          return [
 376              model::RECURRENCE_NONE => get_string('none'),
 377              model::RECURRENCE_DAILY => get_string('recurrencedaily', 'core_reportbuilder'),
 378              model::RECURRENCE_WEEKDAYS => get_string('recurrenceweekdays', 'core_reportbuilder'),
 379              model::RECURRENCE_WEEKLY => get_string('recurrenceweekly', 'core_reportbuilder'),
 380              model::RECURRENCE_MONTHLY => get_string('recurrencemonthly', 'core_reportbuilder'),
 381              model::RECURRENCE_ANNUALLY => get_string('recurrenceannually', 'core_reportbuilder'),
 382          ];
 383      }
 384  
 385      /**
 386       * Return list of options for when report is empty
 387       *
 388       * @return string[]
 389       */
 390      public static function get_report_empty_options(): array {
 391          return [
 392              model::REPORT_EMPTY_SEND_EMPTY => get_string('scheduleemptysendwithattachment', 'core_reportbuilder'),
 393              model::REPORT_EMPTY_SEND_WITHOUT => get_string('scheduleemptysendwithoutattachment', 'core_reportbuilder'),
 394              model::REPORT_EMPTY_DONT_SEND => get_string('scheduleemptydontsend', 'core_reportbuilder'),
 395          ];
 396      }
 397  }