[ Index ]

PHP Cross Reference of Unnamed Project

title

Body

[close]

/admin/tool/monitor/classes/ -> subscription_manager.php (source)

   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  /**
  18   * Class to manage subscriptions.
  19   *
  20   * @package    tool_monitor
  21   * @copyright  2014 onwards Ankit Agarwal <ankit.agrr@gmail.com>
  22   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  namespace tool_monitor;
  26  
  27  defined('MOODLE_INTERNAL') || die();
  28  
  29  /**
  30   * Class to manage subscriptions.
  31   *
  32   * @since      Moodle 2.8
  33   * @package    tool_monitor
  34   * @copyright  2014 onwards Ankit Agarwal <ankit.agrr@gmail.com>
  35   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  36   */
  37  class subscription_manager {
  38  
  39      /** @const Period of time, in days, after which an inactive subscription will be removed completely.*/
  40      const INACTIVE_SUBSCRIPTION_LIFESPAN_IN_DAYS = 30;
  41  
  42      /**
  43       * Subscribe a user to a given rule.
  44       *
  45       * @param int $ruleid  Rule id.
  46       * @param int $courseid Course id.
  47       * @param int $cmid Course module id.
  48       * @param int $userid User who is subscribing, defaults to $USER.
  49       *
  50       * @return bool|int returns id of the created subscription.
  51       */
  52      public static function create_subscription($ruleid, $courseid, $cmid, $userid = 0) {
  53          global $DB, $USER;
  54  
  55          $subscription = new \stdClass();
  56          $subscription->ruleid = $ruleid;
  57          $subscription->courseid = $courseid;
  58          $subscription->cmid = $cmid;
  59          $subscription->userid = empty($userid) ? $USER->id : $userid;
  60          if ($DB->record_exists('tool_monitor_subscriptions', (array)$subscription)) {
  61              // Subscription already exists.
  62              return false;
  63          }
  64  
  65          $subscription->timecreated = time();
  66          $subscription->id = $DB->insert_record('tool_monitor_subscriptions', $subscription);
  67  
  68          // Trigger a subscription created event.
  69          if ($subscription->id) {
  70              if (!empty($subscription->courseid)) {
  71                  $courseid = $subscription->courseid;
  72                  $context = \context_course::instance($subscription->courseid);
  73              } else {
  74                  $courseid = 0;
  75                  $context = \context_system::instance();
  76              }
  77  
  78              $params = array(
  79                  'objectid' => $subscription->id,
  80                  'courseid' => $courseid,
  81                  'context' => $context
  82              );
  83              $event = \tool_monitor\event\subscription_created::create($params);
  84              $event->trigger();
  85  
  86              // Let's invalidate the cache.
  87              $cache = \cache::make('tool_monitor', 'eventsubscriptions');
  88              $cache->delete($courseid);
  89          }
  90  
  91          return $subscription->id;
  92      }
  93  
  94      /**
  95       * Delete a subscription.
  96       *
  97       * @param subscription|int $subscriptionorid an instance of subscription class or id.
  98       * @param bool $checkuser Check if the subscription belongs to current user before deleting.
  99       *
 100       * @return bool
 101       * @throws \coding_exception if $checkuser is true and the subscription doesn't belong to the current user.
 102       */
 103      public static function delete_subscription($subscriptionorid, $checkuser = true) {
 104          global $DB, $USER;
 105          if (is_object($subscriptionorid)) {
 106              $subscription = $subscriptionorid;
 107          } else {
 108              $subscription = self::get_subscription($subscriptionorid);
 109          }
 110          if ($checkuser && $subscription->userid != $USER->id) {
 111              throw new \coding_exception('Invalid subscription supplied');
 112          }
 113  
 114          // Store the subscription before we delete it.
 115          $subscription = $DB->get_record('tool_monitor_subscriptions', array('id' => $subscription->id));
 116  
 117          $success = $DB->delete_records('tool_monitor_subscriptions', array('id' => $subscription->id));
 118  
 119          // If successful trigger a subscription_deleted event.
 120          if ($success) {
 121              if (!empty($subscription->courseid)) {
 122                  $courseid = $subscription->courseid;
 123                  $context = \context_course::instance($subscription->courseid);
 124              } else {
 125                  $courseid = 0;
 126                  $context = \context_system::instance();
 127              }
 128  
 129              $params = array(
 130                  'objectid' => $subscription->id,
 131                  'courseid' => $courseid,
 132                  'context' => $context
 133              );
 134              $event = \tool_monitor\event\subscription_deleted::create($params);
 135              $event->add_record_snapshot('tool_monitor_subscriptions', $subscription);
 136              $event->trigger();
 137  
 138              // Let's invalidate the cache.
 139              $cache = \cache::make('tool_monitor', 'eventsubscriptions');
 140              $cache->delete($courseid);
 141          }
 142  
 143          return $success;
 144      }
 145  
 146      /**
 147       * Delete all subscriptions for a user.
 148       *
 149       * @param int $userid user id.
 150       *
 151       * @return mixed
 152       */
 153      public static function delete_user_subscriptions($userid) {
 154          global $DB;
 155          return $DB->delete_records('tool_monitor_subscriptions', array('userid' => $userid));
 156      }
 157  
 158      /**
 159       * Delete all subscriptions for a course module.
 160       *
 161       * @param int $cmid cm id.
 162       *
 163       * @return mixed
 164       */
 165      public static function delete_cm_subscriptions($cmid) {
 166          global $DB;
 167          return $DB->delete_records('tool_monitor_subscriptions', array('cmid' => $cmid));
 168      }
 169  
 170      /**
 171       * Delete all subscribers for a given rule.
 172       *
 173       * @param int $ruleid rule id.
 174       * @param \context|null $coursecontext the context of the course - this is passed when we
 175       *      can not get the context via \context_course as the course has been deleted.
 176       *
 177       * @return bool
 178       */
 179      public static function remove_all_subscriptions_for_rule($ruleid, $coursecontext = null) {
 180          global $DB;
 181  
 182          // Store all the subscriptions we have to delete.
 183          $subscriptions = $DB->get_recordset('tool_monitor_subscriptions', array('ruleid' => $ruleid));
 184  
 185          // Now delete them.
 186          $success = $DB->delete_records('tool_monitor_subscriptions', array('ruleid' => $ruleid));
 187  
 188          // If successful and there were subscriptions that were deleted trigger a subscription deleted event.
 189          if ($success && $subscriptions) {
 190              foreach ($subscriptions as $subscription) {
 191                  // It is possible that we are deleting rules associated with a deleted course, so we should be
 192                  // passing the context as the second parameter.
 193                  if (!is_null($coursecontext)) {
 194                      $context = $coursecontext;
 195                      $courseid = $subscription->courseid;
 196                  } else if (!empty($subscription->courseid) && ($coursecontext =
 197                          \context_course::instance($subscription->courseid, IGNORE_MISSING))) {
 198                      $courseid = $subscription->courseid;
 199                      $context = $coursecontext;
 200                  } else {
 201                      $courseid = 0;
 202                      $context = \context_system::instance();
 203                  }
 204  
 205                  $params = array(
 206                      'objectid' => $subscription->id,
 207                      'courseid' => $courseid,
 208                      'context' => $context
 209                  );
 210                  $event = \tool_monitor\event\subscription_deleted::create($params);
 211                  $event->add_record_snapshot('tool_monitor_subscriptions', $subscription);
 212                  $event->trigger();
 213  
 214                  // Let's invalidate the cache.
 215                  $cache = \cache::make('tool_monitor', 'eventsubscriptions');
 216                  $cache->delete($courseid);
 217              }
 218          }
 219  
 220          $subscriptions->close();
 221  
 222          return $success;
 223      }
 224  
 225      /**
 226       * Get a subscription instance for an given subscription id.
 227       *
 228       * @param subscription|int $subscriptionorid an instance of subscription class or id.
 229       *
 230       * @return subscription returns a instance of subscription class.
 231       */
 232      public static function get_subscription($subscriptionorid) {
 233          global $DB;
 234  
 235          if (is_object($subscriptionorid)) {
 236              return new subscription($subscriptionorid);
 237          }
 238  
 239          $sql = self::get_subscription_join_rule_sql();
 240          $sql .= "WHERE s.id = :id";
 241          $sub = $DB->get_record_sql($sql, array('id' => $subscriptionorid), MUST_EXIST);
 242          return new subscription($sub);
 243      }
 244  
 245      /**
 246       * Get an array of subscriptions for a given user in a given course.
 247       *
 248       * @param int $courseid course id.
 249       * @param int $limitfrom Limit from which to fetch rules.
 250       * @param int $limitto  Limit to which rules need to be fetched.
 251       * @param int $userid Id of the user for which the subscription needs to be fetched. Defaults to $USER;
 252       * @param string $order Order to sort the subscriptions.
 253       *
 254       * @return array list of subscriptions
 255       */
 256      public static function get_user_subscriptions_for_course($courseid, $limitfrom = 0, $limitto = 0, $userid = 0,
 257              $order = 's.timecreated DESC' ) {
 258          global $DB, $USER;
 259          if ($userid == 0) {
 260              $userid = $USER->id;
 261          }
 262          $sql = self::get_subscription_join_rule_sql();
 263          $sql .= "WHERE s.courseid = :courseid AND s.userid = :userid ORDER BY $order";
 264  
 265          return self::get_instances($DB->get_records_sql($sql, array('courseid' => $courseid, 'userid' => $userid), $limitfrom,
 266                  $limitto));
 267      }
 268  
 269      /**
 270       * Get count of subscriptions for a given user in a given course.
 271       *
 272       * @param int $courseid course id.
 273       * @param int $userid Id of the user for which the subscription needs to be fetched. Defaults to $USER;
 274       *
 275       * @return int number of subscriptions
 276       */
 277      public static function count_user_subscriptions_for_course($courseid, $userid = 0) {
 278          global $DB, $USER;
 279          if ($userid == 0) {
 280              $userid = $USER->id;
 281          }
 282          $sql = self::get_subscription_join_rule_sql(true);
 283          $sql .= "WHERE s.courseid = :courseid AND s.userid = :userid";
 284  
 285          return $DB->count_records_sql($sql, array('courseid' => $courseid, 'userid' => $userid));
 286      }
 287  
 288      /**
 289       * Get an array of subscriptions for a given user.
 290       *
 291       * @param int $limitfrom Limit from which to fetch rules.
 292       * @param int $limitto  Limit to which rules need to be fetched.
 293       * @param int $userid Id of the user for which the subscription needs to be fetched. Defaults to $USER;
 294       * @param string $order Order to sort the subscriptions.
 295       *
 296       * @return array list of subscriptions
 297       */
 298      public static function get_user_subscriptions($limitfrom = 0, $limitto = 0, $userid = 0,
 299                                                               $order = 's.courseid ASC, r.name' ) {
 300          global $DB, $USER;
 301          if ($userid == 0) {
 302              $userid = $USER->id;
 303          }
 304          $sql = self::get_subscription_join_rule_sql();
 305          $sql .= "WHERE s.userid = :userid ORDER BY $order";
 306  
 307          return self::get_instances($DB->get_records_sql($sql, array('userid' => $userid), $limitfrom, $limitto));
 308      }
 309  
 310      /**
 311       * Get count of subscriptions for a given user.
 312       *
 313       * @param int $userid Id of the user for which the subscription needs to be fetched. Defaults to $USER;
 314       *
 315       * @return int number of subscriptions
 316       */
 317      public static function count_user_subscriptions($userid = 0) {
 318          global $DB, $USER;;
 319          if ($userid == 0) {
 320              $userid = $USER->id;
 321          }
 322          $sql = self::get_subscription_join_rule_sql(true);
 323          $sql .= "WHERE s.userid = :userid";
 324  
 325          return $DB->count_records_sql($sql, array('userid' => $userid));
 326      }
 327  
 328      /**
 329       * Return a list of subscriptions for a given event.
 330       *
 331       * @param \stdClass $event the event object.
 332       *
 333       * @return array
 334       */
 335      public static function get_subscriptions_by_event(\stdClass $event) {
 336          global $DB;
 337  
 338          $sql = self::get_subscription_join_rule_sql();
 339          if ($event->contextlevel == CONTEXT_MODULE && $event->contextinstanceid != 0) {
 340              $sql .= "WHERE r.eventname = :eventname AND s.courseid = :courseid AND (s.cmid = :cmid OR s.cmid = 0)";
 341              $params = array('eventname' => $event->eventname, 'courseid' => $event->courseid, 'cmid' => $event->contextinstanceid);
 342          } else {
 343              $sql .= "WHERE r.eventname = :eventname AND (s.courseid = :courseid OR s.courseid = 0)";
 344              $params = array('eventname' => $event->eventname, 'courseid' => $event->courseid);
 345          }
 346          return self::get_instances($DB->get_records_sql($sql, $params));
 347      }
 348  
 349      /**
 350       * Return sql to join rule and subscription table.
 351       *
 352       * @param bool $count Weather if this is a count query or not.
 353       *
 354       * @return string the sql.
 355       */
 356      protected static function get_subscription_join_rule_sql($count = false) {
 357          if ($count) {
 358              $select = "SELECT COUNT(s.id) ";
 359          } else {
 360              $select = "SELECT s.*, r.description, r.descriptionformat, r.name, r.userid as ruleuserid, r.courseid as rulecourseid,
 361              r.plugin, r.eventname, r.template, r.templateformat, r.frequency, r.timewindow";
 362          }
 363          $sql = $select . "
 364                    FROM {tool_monitor_rules} r
 365                    JOIN {tool_monitor_subscriptions} s
 366                          ON r.id = s.ruleid ";
 367          return $sql;
 368      }
 369  
 370      /**
 371       * Helper method to convert db records to instances.
 372       *
 373       * @param array $arr of subscriptions.
 374       *
 375       * @return array of subscriptions as instances.
 376       */
 377      protected static function get_instances($arr) {
 378          $result = array();
 379          foreach ($arr as $key => $sub) {
 380              $result[$key] = new subscription($sub);
 381          }
 382          return $result;
 383      }
 384  
 385      /**
 386       * Get count of subscriptions for a given rule.
 387       *
 388       * @param int $ruleid rule id of the subscription.
 389       *
 390       * @return int number of subscriptions
 391       */
 392      public static function count_rule_subscriptions($ruleid) {
 393          global $DB;
 394          $sql = self::get_subscription_join_rule_sql(true);
 395          $sql .= "WHERE s.ruleid = :ruleid";
 396  
 397          return $DB->count_records_sql($sql, array('ruleid' => $ruleid));
 398      }
 399  
 400      /**
 401       * Returns true if an event in a particular course has a subscription.
 402       *
 403       * @param string $eventname the name of the event
 404       * @param int $courseid the course id
 405       * @return bool returns true if the event has subscriptions in a given course, false otherwise.
 406       */
 407      public static function event_has_subscriptions($eventname, $courseid) {
 408          global $DB;
 409  
 410          // Check if we can return these from cache.
 411          $cache = \cache::make('tool_monitor', 'eventsubscriptions');
 412  
 413          // The SQL we will be using to fill the cache if it is empty.
 414          $sql = "SELECT DISTINCT(r.eventname)
 415                    FROM {tool_monitor_subscriptions} s
 416              INNER JOIN {tool_monitor_rules} r
 417                      ON s.ruleid = r.id
 418                   WHERE s.courseid = :courseid";
 419  
 420          $sitesubscriptions = $cache->get(0);
 421          // If we do not have the site subscriptions in the cache then return them from the DB.
 422          if ($sitesubscriptions === false) {
 423              // Set the array for the cache.
 424              $sitesubscriptions = array();
 425              if ($subscriptions = $DB->get_records_sql($sql, array('courseid' => 0))) {
 426                  foreach ($subscriptions as $subscription) {
 427                      $sitesubscriptions[$subscription->eventname] = true;
 428                  }
 429              }
 430              $cache->set(0, $sitesubscriptions);
 431          }
 432  
 433          // Check if a subscription exists for this event site wide.
 434          if (isset($sitesubscriptions[$eventname])) {
 435              return true;
 436          }
 437  
 438          // If the course id is for the site, and we reached here then there is no site wide subscription for this event.
 439          if (empty($courseid)) {
 440              return false;
 441          }
 442  
 443          $coursesubscriptions = $cache->get($courseid);
 444          // If we do not have the course subscriptions in the cache then return them from the DB.
 445          if ($coursesubscriptions === false) {
 446              // Set the array for the cache.
 447              $coursesubscriptions = array();
 448              if ($subscriptions = $DB->get_records_sql($sql, array('courseid' => $courseid))) {
 449                  foreach ($subscriptions as $subscription) {
 450                      $coursesubscriptions[$subscription->eventname] = true;
 451                  }
 452              }
 453              $cache->set($courseid, $coursesubscriptions);
 454          }
 455  
 456          // Check if a subscription exists for this event in this course.
 457          if (isset($coursesubscriptions[$eventname])) {
 458              return true;
 459          }
 460  
 461          return false;
 462      }
 463  
 464      /**
 465       * Activates a group of subscriptions based on an input array of ids.
 466       *
 467       * @since 3.2.0
 468       * @param array $ids of subscription ids.
 469       * @return bool true if the operation was successful, false otherwise.
 470       */
 471      public static function activate_subscriptions(array $ids) {
 472          global $DB;
 473          if (!empty($ids)) {
 474              list($sql, $params) = $DB->get_in_or_equal($ids);
 475              $success = $DB->set_field_select('tool_monitor_subscriptions', 'inactivedate', '0', 'id ' . $sql, $params);
 476              return $success;
 477          }
 478          return false;
 479      }
 480  
 481      /**
 482       * Deactivates a group of subscriptions based on an input array of ids.
 483       *
 484       * @since 3.2.0
 485       * @param array $ids of subscription ids.
 486       * @return bool true if the operation was successful, false otherwise.
 487       */
 488      public static function deactivate_subscriptions(array $ids) {
 489          global $DB;
 490          if (!empty($ids)) {
 491              $inactivedate = time();
 492              list($sql, $params) = $DB->get_in_or_equal($ids);
 493              $success = $DB->set_field_select('tool_monitor_subscriptions', 'inactivedate', $inactivedate, 'id ' . $sql,
 494                                               $params);
 495              return $success;
 496          }
 497          return false;
 498      }
 499  
 500      /**
 501       * Deletes subscriptions which have been inactive for a period of time.
 502       *
 503       * @since 3.2.0
 504       * @param int $userid if provided, only this user's stale subscriptions will be deleted.
 505       * @return bool true if the operation was successful, false otherwise.
 506       */
 507      public static function delete_stale_subscriptions($userid = 0) {
 508          global $DB;
 509          // Get the expiry duration, in days.
 510          $cutofftime = strtotime("-" . self::INACTIVE_SUBSCRIPTION_LIFESPAN_IN_DAYS . " days", time());
 511  
 512          if (!empty($userid)) {
 513              // Remove any stale subscriptions for the desired user only.
 514              $success = $DB->delete_records_select('tool_monitor_subscriptions',
 515                                                    'userid = ? AND inactivedate < ? AND inactivedate <> 0',
 516                                                    array($userid, $cutofftime));
 517  
 518          } else {
 519              // Remove all stale subscriptions.
 520              $success = $DB->delete_records_select('tool_monitor_subscriptions',
 521                                                    'inactivedate < ? AND inactivedate <> 0',
 522                                                    array($cutofftime));
 523          }
 524          return $success;
 525      }
 526  
 527      /**
 528       * Check whether a subscription is active.
 529       *
 530       * @since 3.2.0
 531       * @param \tool_monitor\subscription $subscription instance.
 532       * @return bool true if the subscription is active, false otherwise.
 533       */
 534      public static function subscription_is_active(subscription $subscription) {
 535          return empty($subscription->inactivedate);
 536      }
 537  }


Generated: Thu Aug 11 10:00:09 2016 Cross-referenced by PHPXref 0.7.1