[ Index ]

PHP Cross Reference of Moodle 1.9.3 [Build 15-Oct-2008]

title

Body

[close]

/lib/ -> deprecatedlib.php (source)

   1  <?php // $Id: deprecatedlib.php,v 1.41.2.8 2008/06/01 13:21:17 skodak Exp $
   2  
   3  ///////////////////////////////////////////////////////////////////////////
   4  //                                                                       //
   5  // NOTICE OF COPYRIGHT                                                   //
   6  //                                                                       //
   7  // Moodle - Modular Object-Oriented Dynamic Learning Environment         //
   8  //          http://moodle.org                                            //
   9  //                                                                       //
  10  // Copyright (C) 1999 onwards Martin Dougiamas, Moodle  http://moodle.com  //
  11  //                                                                       //
  12  // This program is free software; you can redistribute it and/or modify  //
  13  // it under the terms of the GNU General Public License as published by  //
  14  // the Free Software Foundation; either version 2 of the License, or     //
  15  // (at your option) any later version.                                   //
  16  //                                                                       //
  17  // This program is distributed in the hope that it will be useful,       //
  18  // but WITHOUT ANY WARRANTY; without even the implied warranty of        //
  19  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         //
  20  // GNU General Public License for more details:                          //
  21  //                                                                       //
  22  //          http://www.gnu.org/copyleft/gpl.html                         //
  23  //                                                                       //
  24  ///////////////////////////////////////////////////////////////////////////
  25  
  26  /**
  27   * deprecatedlib.php - Old functions retained only for backward compatibility
  28   *
  29   * Old functions retained only for backward compatibility.  New code should not
  30   * use any of these functions.
  31   *
  32   * @author Martin Dougiamas
  33   * @version $Id: deprecatedlib.php,v 1.41.2.8 2008/06/01 13:21:17 skodak Exp $
  34   * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
  35   * @package moodlecore
  36   */
  37  
  38  
  39  
  40  
  41  /**
  42   * Ensure that a variable is set
  43   *
  44   * If $var is undefined throw an error, otherwise return $var.
  45   *
  46   * @param mixed $var the variable which may be unset
  47   * @param mixed $default the value to return if $var is unset
  48   */
  49  function require_variable($var) {
  50      global $CFG;
  51      if (!empty($CFG->disableglobalshack)) {
  52          error( 'The require_variable() function is deprecated.' );
  53      }
  54      if (! isset($var)) {
  55          error('A required parameter was missing');
  56      }
  57  }
  58  
  59  /**
  60   * Ensure that a variable is set
  61   *
  62   * If $var is undefined set it (by reference), otherwise return $var.
  63   *
  64   * @param mixed $var the variable which may be unset
  65   * @param mixed $default the value to return if $var is unset
  66   */
  67  function optional_variable(&$var, $default=0) {
  68      global $CFG;
  69      if (!empty($CFG->disableglobalshack)) {
  70          error( "The optional_variable() function is deprecated ($var, $default)." );
  71      }
  72      if (! isset($var)) {
  73          $var = $default;
  74      }
  75  }
  76  
  77  /**
  78   * Ensure that a variable is set
  79   *
  80   * Return $var if it is defined, otherwise return $default,
  81   * This function is very similar to {@link optional_variable()}
  82   *
  83   * @param    mixed $var the variable which may be unset
  84   * @param    mixed $default the value to return if $var is unset
  85   * @return   mixed
  86   */
  87  function nvl(&$var, $default='') {
  88      global $CFG;
  89  
  90      if (!empty($CFG->disableglobalshack)) {
  91        error( "The nvl() function is deprecated ($var, $default)." );
  92      }
  93      return isset($var) ? $var : $default;
  94  }
  95  
  96  /**
  97   * Determines if a user an admin
  98   *
  99   * @uses $USER
 100   * @param int $userid The id of the user as is found in the 'user' table
 101   * @staticvar array $admins List of users who have been found to be admins by user id
 102   * @staticvar array $nonadmins List of users who have been found not to be admins by user id
 103   * @return bool
 104   */
 105  function isadmin($userid=0) {
 106      global $USER, $CFG;
 107  
 108      if (empty($CFG->rolesactive)) {    // Then the user is likely to be upgrading NOW
 109          if (!$userid) {
 110              if (empty($USER->id)) {
 111                  return false;
 112              }
 113              if (!empty($USER->admin)) {
 114                  return true;
 115              }
 116              $userid = $USER->id;
 117          }
 118  
 119          return record_exists('user_admins', 'userid', $userid);
 120      }
 121  
 122      $context = get_context_instance(CONTEXT_SYSTEM);
 123  
 124      return has_capability('moodle/legacy:admin', $context, $userid, false);
 125  }
 126  
 127  /**
 128   * Determines if a user is a teacher (or better)
 129   *
 130   * @uses $CFG
 131   * @param int $courseid The id of the course that is being viewed, if any
 132   * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
 133   * @param bool $obsolete_includeadmin Not used any more
 134   * @return bool
 135   */
 136  
 137  function isteacher($courseid=0, $userid=0, $obsolete_includeadmin=true) {
 138  /// Is the user able to access this course as a teacher?
 139      global $CFG;
 140  
 141      if (empty($CFG->rolesactive)) {     // Teachers are locked out during an upgrade to 1.7
 142          return false;
 143      }
 144  
 145      if ($courseid) {
 146          $context = get_context_instance(CONTEXT_COURSE, $courseid);
 147      } else {
 148          $context = get_context_instance(CONTEXT_SYSTEM);
 149      }
 150  
 151      return (has_capability('moodle/legacy:teacher', $context, $userid, false)
 152           or has_capability('moodle/legacy:editingteacher', $context, $userid, false)
 153           or has_capability('moodle/legacy:admin', $context, $userid, false));
 154  }
 155  
 156  /**
 157   * Determines if a user is a teacher in any course, or an admin
 158   *
 159   * @uses $USER
 160   * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
 161   * @param bool $includeadmin Include anyone wo is an admin as well
 162   * @return bool
 163   */
 164  function isteacherinanycourse($userid=0, $includeadmin=true) {
 165      global $USER, $CFG;
 166  
 167      if (empty($CFG->rolesactive)) {     // Teachers are locked out during an upgrade to 1.7
 168          return false;
 169      }
 170  
 171      if (!$userid) {
 172          if (empty($USER->id)) {
 173              return false;
 174          }
 175          $userid = $USER->id;
 176      }
 177  
 178      if (!record_exists('role_assignments', 'userid', $userid)) {    // Has no roles anywhere
 179          return false;
 180      }
 181  
 182  /// If this user is assigned as an editing teacher anywhere then return true
 183      if ($roles = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW)) {
 184          foreach ($roles as $role) {
 185              if (record_exists('role_assignments', 'roleid', $role->id, 'userid', $userid)) {
 186                  return true;
 187              }
 188          }
 189      }
 190  
 191  /// If this user is assigned as a non-editing teacher anywhere then return true
 192      if ($roles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW)) {
 193          foreach ($roles as $role) {
 194              if (record_exists('role_assignments', 'roleid', $role->id, 'userid', $userid)) {
 195                  return true;
 196              }
 197          }
 198      }
 199  
 200  /// Include admins if required
 201      if ($includeadmin) {
 202          $context = get_context_instance(CONTEXT_SYSTEM);
 203          if (has_capability('moodle/legacy:admin', $context, $userid, false)) {
 204              return true;
 205          }
 206      }
 207  
 208      return false;
 209  }
 210  
 211  /**
 212   * Determines if a user is allowed to edit a given course
 213   *
 214   * @param int $courseid The id of the course that is being edited
 215   * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
 216   * @return bool
 217   */
 218  function isteacheredit($courseid, $userid=0, $obsolete_ignorestudentview=false) {
 219      global $CFG;
 220  
 221      if (empty($CFG->rolesactive)) {
 222          return false;
 223      }
 224  
 225      if (empty($courseid)) {
 226          $context = get_context_instance(CONTEXT_SYSTEM);
 227      } else {
 228          $context = get_context_instance(CONTEXT_COURSE, $courseid);
 229      }
 230  
 231      return (has_capability('moodle/legacy:editingteacher', $context, $userid, false)
 232           or has_capability('moodle/legacy:admin', $context, $userid, false));
 233  }
 234  
 235  /**
 236   * Determines if a user can create new courses
 237   *
 238   * @param int $userid The user being tested. You can set this to 0 or leave it blank to test the currently logged in user.
 239   * @return bool
 240   */
 241  function iscreator ($userid=0) {
 242      global $CFG;
 243  
 244      if (empty($CFG->rolesactive)) {
 245          return false;
 246      }
 247  
 248      $context = get_context_instance(CONTEXT_SYSTEM);
 249  
 250      return (has_capability('moodle/legacy:coursecreator', $context, $userid, false)
 251           or has_capability('moodle/legacy:admin', $context, $userid, false));
 252  }
 253  
 254  /**
 255   * Determines if a user is a student in the specified course
 256   *
 257   * If the course id specifies the site then this determines
 258   * if the user is a confirmed and valid user of this site.
 259   *
 260   * @uses $CFG
 261   * @uses SITEID
 262   * @param int $courseid The id of the course being tested
 263   * @param int $userid The user being tested. You can set this to 0 or leave it blank to test the currently logged in user.
 264   * @return bool
 265   */
 266  function isstudent($courseid=0, $userid=0) {
 267      global $CFG;
 268  
 269      if (empty($CFG->rolesactive)) {
 270          return false;
 271      }
 272  
 273      if ($courseid == 0) {
 274          $context = get_context_instance(CONTEXT_SYSTEM);
 275      } else {
 276          $context = get_context_instance(CONTEXT_COURSE, $courseid);
 277      }
 278  
 279      return has_capability('moodle/legacy:student', $context, $userid, false);
 280  }
 281  
 282  /**
 283   * Determines if the specified user is logged in as guest.
 284   *
 285   * @param int $userid The user being tested. You can set this to 0 or leave it blank to test the currently logged in user.
 286   * @return bool
 287   */
 288  function isguest($userid=0) {
 289      global $CFG;
 290  
 291      if (empty($CFG->rolesactive)) {
 292          return false;
 293      }
 294  
 295      $context = get_context_instance(CONTEXT_SYSTEM);
 296  
 297      return has_capability('moodle/legacy:guest', $context, $userid, false);
 298  }
 299  
 300  /**
 301   * Enrols (or re-enrols) a student in a given course
 302   *
 303   * NOTE: Defaults to 'manual' enrolment - enrolment plugins
 304   * must set it explicitly.
 305   *
 306   * @uses $CFG
 307   * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
 308   * @param int $courseid The id of the course that is being viewed
 309   * @param int $timestart ?
 310   * @param int $timeend ?
 311   * @param string $enrol ?
 312   * @return bool
 313   */
 314  function enrol_student($userid, $courseid, $timestart=0, $timeend=0, $enrol='manual') {
 315  
 316      global $CFG;
 317  
 318      if (!$user = get_record('user', 'id', $userid)) {        // Check user
 319          return false;
 320      }
 321  
 322      if (!$roles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
 323          return false;
 324      }
 325  
 326      $role = array_shift($roles);      // We can only use one, let's use the first one
 327  
 328      if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
 329          return false;
 330      }
 331  
 332      $res = role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol);
 333  
 334      return $res;
 335  }
 336  
 337  /**
 338   * Unenrols a student from a given course
 339   *
 340   * @param int $courseid The id of the course that is being viewed, if any
 341   * @param int $userid The id of the user that is being tested against.
 342   * @return bool
 343   */
 344  function unenrol_student($userid, $courseid=0) {
 345      global $CFG;
 346  
 347      $status = true;
 348  
 349      if ($courseid) {
 350          /// First delete any crucial stuff that might still send mail
 351          if ($forums = get_records('forum', 'course', $courseid)) {
 352              foreach ($forums as $forum) {
 353                  delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
 354              }
 355          }
 356          /// remove from all legacy student roles
 357          if ($courseid == SITEID) {
 358              $context = get_context_instance(CONTEXT_SYSTEM);
 359          } else if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
 360              return false;
 361          }
 362          if (!$roles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
 363              return false;
 364          }
 365          foreach($roles as $role) {
 366              $status = role_unassign($role->id, $userid, 0, $context->id) and $status;
 367          }
 368      } else {
 369          // recursivelly unenroll student from all courses
 370          if ($courses = get_records('course')) {
 371              foreach($courses as $course) {
 372                  $status = unenrol_student($userid, $course->id) and $status;
 373              }
 374          }
 375      }
 376  
 377      return $status;
 378  }
 379  
 380  /**
 381   * Add a teacher to a given course
 382   *
 383   * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
 384   * @param int $courseid The id of the course that is being viewed, if any
 385   * @param int $editall Can edit the course
 386   * @param string $role Obsolete
 387   * @param int $timestart The time they start
 388   * @param int $timeend The time they end in this role
 389   * @param string $enrol The type of enrolment this is
 390   * @return bool
 391   */
 392  function add_teacher($userid, $courseid, $editall=1, $role='', $timestart=0, $timeend=0, $enrol='manual') {
 393      global $CFG;
 394  
 395      if (!$user = get_record('user', 'id', $userid)) {        // Check user
 396          return false;
 397      }
 398  
 399      $capability = $editall ? 'moodle/legacy:editingteacher' : 'moodle/legacy:teacher';
 400  
 401      if (!$roles = get_roles_with_capability($capability, CAP_ALLOW)) {
 402          return false;
 403      }
 404  
 405      $role = array_shift($roles);      // We can only use one, let's use the first one
 406  
 407      if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
 408          return false;
 409      }
 410  
 411      $res = role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol);
 412  
 413      return $res;
 414  }
 415  
 416  /**
 417   * Removes a teacher from a given course (or ALL courses)
 418   * Does not delete the user account
 419   *
 420   * @param int $courseid The id of the course that is being viewed, if any
 421   * @param int $userid The id of the user that is being tested against.
 422   * @return bool
 423   */
 424  function remove_teacher($userid, $courseid=0) {
 425      global $CFG;
 426  
 427      $roles = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW);
 428  
 429      if ($roles) {
 430          $roles += get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW);
 431      } else {
 432          $roles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW);
 433      }
 434  
 435      if (empty($roles)) {
 436          return true;
 437      }
 438  
 439      $return = true;
 440  
 441      if ($courseid) {
 442  
 443          if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
 444              return false;
 445          }
 446  
 447          /// First delete any crucial stuff that might still send mail
 448          if ($forums = get_records('forum', 'course', $courseid)) {
 449              foreach ($forums as $forum) {
 450                  delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
 451              }
 452          }
 453  
 454          /// No need to remove from groups now
 455  
 456          foreach ($roles as $role) {    // Unassign them from all the teacher roles
 457              $newreturn = role_unassign($role->id, $userid, 0, $context->id);
 458              if (empty($newreturn)) {
 459                  $return = false;
 460              }
 461          }
 462  
 463      } else {
 464          delete_records('forum_subscriptions', 'userid', $userid);
 465          $return = true;
 466          foreach ($roles as $role) {    // Unassign them from all the teacher roles
 467              $newreturn = role_unassign($role->id, $userid, 0, 0);
 468              if (empty($newreturn)) {
 469                  $return = false;
 470              }
 471          }
 472      }
 473  
 474      return $return;
 475  }
 476  
 477  /**
 478   * Add an admin to a site
 479   *
 480   * @uses SITEID
 481   * @param int $userid The id of the user that is being tested against.
 482   * @return bool
 483   * @TODO: remove from cvs
 484   */
 485  function add_admin($userid) {
 486      return true;
 487  }
 488  
 489  function get_user_info_from_db($field, $value) {  // For backward compatibility
 490      return get_complete_user_data($field, $value);
 491  }
 492  
 493  
 494  /**
 495   * Get the guest user information from the database
 496   *
 497   * @return object(user) An associative array with the details of the guest user account.
 498   * @todo Is object(user) a correct return type? Or is array the proper return type with a note that the contents include all details for a user.
 499   */
 500  function get_guest() {
 501      return get_complete_user_data('username', 'guest');
 502  }
 503  
 504  /**
 505   * Returns $user object of the main teacher for a course
 506   *
 507   * @uses $CFG
 508   * @param int $courseid The course in question.
 509   * @return user|false  A {@link $USER} record of the main teacher for the specified course or false if error.
 510   * @todo Finish documenting this function
 511   */
 512  function get_teacher($courseid) {
 513  
 514      global $CFG;
 515  
 516      $context = get_context_instance(CONTEXT_COURSE, $courseid);
 517  
 518      // Pass $view=true to filter hidden caps if the user cannot see them
 519      if ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*', 'u.id ASC',
 520                                           '', '', '', '', false, true)) {
 521          $users = sort_by_roleassignment_authority($users, $context);
 522          return array_shift($users);
 523      }
 524  
 525      return false;
 526  }
 527  
 528  /**
 529   * Searches logs to find all enrolments since a certain date
 530   *
 531   * used to print recent activity
 532   *
 533   * @uses $CFG
 534   * @param int $courseid The course in question.
 535   * @return object|false  {@link $USER} records or false if error.
 536   * @todo Finish documenting this function
 537   */
 538  function get_recent_enrolments($courseid, $timestart) {
 539  
 540      global $CFG;
 541  
 542      $context = get_context_instance(CONTEXT_COURSE, $courseid);
 543  
 544      return get_records_sql("SELECT DISTINCT u.id, u.firstname, u.lastname, l.time
 545                              FROM {$CFG->prefix}user u,
 546                                   {$CFG->prefix}role_assignments ra,
 547                                   {$CFG->prefix}log l
 548                              WHERE l.time > '$timestart'
 549                                AND l.course = '$courseid'
 550                                AND l.module = 'course'
 551                                AND l.action = 'enrol'
 552                                AND ".sql_cast_char2int('l.info')." = u.id
 553                                AND u.id = ra.userid
 554                                AND ra.contextid ".get_related_contexts_string($context)."
 555                                ORDER BY l.time ASC");
 556  }
 557  
 558  /**
 559   * Returns array of userinfo of all students in this course
 560   * or on this site if courseid is id of site
 561   *
 562   * @uses $CFG
 563   * @uses SITEID
 564   * @param int $courseid The course in question.
 565   * @param string $sort ?
 566   * @param string $dir ?
 567   * @param int $page ?
 568   * @param int $recordsperpage ?
 569   * @param string $firstinitial ?
 570   * @param string $lastinitial ?
 571   * @param ? $group ?
 572   * @param string $search ?
 573   * @param string $fields A comma separated list of fields to be returned from the chosen table.
 574   * @param string $exceptions ?
 575   * @return object
 576   * @todo Finish documenting this function
 577   */
 578  function get_course_students($courseid, $sort='ul.timeaccess', $dir='', $page='', $recordsperpage='',
 579                               $firstinitial='', $lastinitial='', $group=NULL, $search='', $fields='', $exceptions='') {
 580  
 581      global $CFG;
 582  
 583      // make sure it works on the site course
 584      $context = get_context_instance(CONTEXT_COURSE, $courseid);
 585  
 586      /// For the site course, old way was to check if $CFG->allusersaresitestudents was set to true.
 587      /// The closest comparible method using roles is if the $CFG->defaultuserroleid is set to the legacy
 588      /// student role. This function should be replaced where it is used with something more meaningful.
 589      if (($courseid == SITEID) && !empty($CFG->defaultuserroleid) && empty($CFG->nodefaultuserrolelists)) {
 590          if ($roles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW, $context)) {
 591              $hascap = false;
 592              foreach ($roles as $role) {
 593                  if ($role->id == $CFG->defaultuserroleid) {
 594                      $hascap = true;
 595                      break;
 596                  }
 597              }
 598              if ($hascap) {
 599                  // return users with confirmed, undeleted accounts who are not site teachers
 600                  // the following is a mess because of different conventions in the different user functions
 601                  $sort = str_replace('s.timeaccess', 'lastaccess', $sort); // site users can't be sorted by timeaccess
 602                  $sort = str_replace('timeaccess', 'lastaccess', $sort); // site users can't be sorted by timeaccess
 603                  $sort = str_replace('u.', '', $sort); // the get_user function doesn't use the u. prefix to fields
 604                  $fields = str_replace('u.', '', $fields);
 605                  if ($sort) {
 606                      $sort = $sort .' '. $dir;
 607                  }
 608                  // Now we have to make sure site teachers are excluded
 609  
 610                  if ($teachers = get_course_teachers(SITEID)) {
 611                      foreach ($teachers as $teacher) {
 612                          $exceptions .= ','. $teacher->userid;
 613                      }
 614                      $exceptions = ltrim($exceptions, ',');
 615  
 616                  }
 617  
 618                  return get_users(true, $search, true, $exceptions, $sort, $firstinitial, $lastinitial,
 619                                    $page, $recordsperpage, $fields ? $fields : '*');
 620              }
 621          }
 622      }
 623  
 624      $LIKE      = sql_ilike();
 625      $fullname  = sql_fullname('u.firstname','u.lastname');
 626  
 627      $groupmembers = '';
 628  
 629      $select = "c.contextlevel=".CONTEXT_COURSE." AND "; // Must be on a course
 630      if ($courseid != SITEID) {
 631          // If not site, require specific course
 632          $select.= "c.instanceid=$courseid AND ";
 633      }
 634      $select.="rc.capability='moodle/legacy:student' AND rc.permission=".CAP_ALLOW." AND ";
 635  
 636      $select .= ' u.deleted = \'0\' ';
 637  
 638      if (!$fields) {
 639          $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
 640                    'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
 641                    'u.country, u.picture, u.idnumber, u.department, u.institution, '.
 642                    'u.emailstop, u.lang, u.timezone, ul.timeaccess as lastaccess';
 643      }
 644  
 645      if ($search) {
 646          $search = ' AND ('. $fullname .' '. $LIKE .'\'%'. $search .'%\' OR email '. $LIKE .'\'%'. $search .'%\') ';
 647      }
 648  
 649      if ($firstinitial) {
 650          $select .= ' AND u.firstname '. $LIKE .'\''. $firstinitial .'%\' ';
 651      }
 652  
 653      if ($lastinitial) {
 654          $select .= ' AND u.lastname '. $LIKE .'\''. $lastinitial .'%\' ';
 655      }
 656  
 657      if ($group === 0) {   /// Need something here to get all students not in a group
 658          return array();
 659  
 660      } else if ($group !== NULL) {
 661          $groupmembers = "INNER JOIN {$CFG->prefix}groups_members gm on u.id=gm.userid";
 662          $select .= ' AND gm.groupid = \''. $group .'\'';
 663      }
 664  
 665      if (!empty($exceptions)) {
 666          $select .= ' AND u.id NOT IN ('. $exceptions .')';
 667      }
 668  
 669      if ($sort) {
 670          $sort = ' ORDER BY '. $sort .' ';
 671      }
 672  
 673      $students = get_records_sql("SELECT $fields
 674                                  FROM {$CFG->prefix}user u INNER JOIN
 675                                       {$CFG->prefix}role_assignments ra on u.id=ra.userid INNER JOIN
 676                                       {$CFG->prefix}role_capabilities rc ON ra.roleid=rc.roleid INNER JOIN
 677                                       {$CFG->prefix}context c ON c.id=ra.contextid LEFT OUTER JOIN
 678                                       {$CFG->prefix}user_lastaccess ul on ul.userid=ra.userid
 679                                       $groupmembers
 680                                  WHERE $select $search $sort $dir", $page, $recordsperpage);
 681  
 682      return $students;
 683  }
 684  
 685  /**
 686   * Counts the students in a given course (or site), or a subset of them
 687   *
 688   * @param object $course The course in question as a course object.
 689   * @param string $search ?
 690   * @param string $firstinitial ?
 691   * @param string $lastinitial ?
 692   * @param ? $group ?
 693   * @param string $exceptions ?
 694   * @return int
 695   * @todo Finish documenting this function
 696   */
 697  function count_course_students($course, $search='', $firstinitial='', $lastinitial='', $group=NULL, $exceptions='') {
 698  
 699      if ($students = get_course_students($course->id, '', '', 0, 999999, $firstinitial, $lastinitial, $group, $search, '', $exceptions)) {
 700          return count($students);
 701      }
 702      return 0;
 703  }
 704  
 705  /**
 706   * Returns list of all teachers in this course
 707   *
 708   * If $courseid matches the site id then this function
 709   * returns a list of all teachers for the site.
 710   *
 711   * @uses $CFG
 712   * @param int $courseid The course in question.
 713   * @param string $sort ?
 714   * @param string $exceptions ?
 715   * @return object
 716   * @todo Finish documenting this function
 717   */
 718  function get_course_teachers($courseid, $sort='t.authority ASC', $exceptions='') {
 719  
 720      global $CFG;
 721  
 722      $sort = 'ul.timeaccess DESC';
 723  
 724      $context = get_context_instance(CONTEXT_COURSE, $courseid);
 725  
 726      /// For the site course, if the $CFG->defaultuserroleid is set to the legacy teacher role, then all
 727      /// users are teachers. This function should be replaced where it is used with something more
 728      /// meaningful.
 729      if (($courseid == SITEID) && !empty($CFG->defaultuserroleid) && empty($CFG->nodefaultuserrolelists)) {
 730          if ($roles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW, $context)) {
 731              $hascap = false;
 732              foreach ($roles as $role) {
 733                  if ($role->id == $CFG->defaultuserroleid) {
 734                      $hascap = true;
 735                      break;
 736                  }
 737              }
 738              if ($hascap) {
 739                  if (empty($fields)) {
 740                      $fields = '*';
 741                  }
 742                  return get_users(true, '', true, $exceptions, 'lastname ASC', '', '', '', '', $fields);
 743              }
 744          }
 745      }
 746  
 747      $users = get_users_by_capability($context, 'moodle/course:update',
 748                                       'u.*, ul.timeaccess as lastaccess',
 749                                       $sort, '','','',$exceptions, false);
 750      return sort_by_roleassignment_authority($users, $context);
 751  
 752      /// some fields will be missing, like authority, editall
 753      /*
 754      return get_records_sql("SELECT u.id, u.username, u.firstname, u.lastname, u.maildisplay, u.mailformat, u.maildigest,
 755                                     u.email, u.city, u.country, u.lastlogin, u.picture, u.lang, u.timezone,
 756                                     u.emailstop, t.authority,t.role,t.editall,t.timeaccess as lastaccess
 757                              FROM {$CFG->prefix}user u,
 758                                   {$CFG->prefix}user_teachers t
 759                              WHERE t.course = '$courseid' AND t.userid = u.id
 760                                AND u.deleted = '0' AND u.confirmed = '1' $exceptions $sort");
 761      */
 762  }
 763  
 764  /**
 765   * Returns all the users of a course: students and teachers
 766   *
 767   * @param int $courseid The course in question.
 768   * @param string $sort ?
 769   * @param string $exceptions ?
 770   * @param string $fields A comma separated list of fields to be returned from the chosen table.
 771   * @return object
 772   * @todo Finish documenting this function
 773   */
 774  function get_course_users($courseid, $sort='ul.timeaccess DESC', $exceptions='', $fields='u.*, ul.timeaccess as lastaccess') {
 775      global $CFG;
 776  
 777      $context = get_context_instance(CONTEXT_COURSE, $courseid);
 778  
 779      /// If the course id is the SITEID, we need to return all the users if the "defaultuserroleid"
 780      /// has the capbility of accessing the site course. $CFG->nodefaultuserrolelists set to true can
 781      /// over-rule using this.
 782      if (($courseid == SITEID) && !empty($CFG->defaultuserroleid) && empty($CFG->nodefaultuserrolelists)) {
 783          if ($roles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $context)) {
 784              $hascap = false;
 785              foreach ($roles as $role) {
 786                  if ($role->id == $CFG->defaultuserroleid) {
 787                      $hascap = true;
 788                      break;
 789                  }
 790              }
 791              if ($hascap) {
 792                  if (empty($fields)) {
 793                      $fields = '*';
 794                  }
 795                  return get_users(true, '', true, $exceptions, 'lastname ASC', '', '', '', '', $fields);
 796              }
 797          }
 798      }
 799      return get_users_by_capability($context, 'moodle/course:view', $fields, $sort, '','','',$exceptions, false);
 800  
 801  }
 802  
 803  /**
 804   * Returns an array of user objects
 805   *
 806   * @uses $CFG
 807   * @param int $groupid The group(s) in question.
 808   * @param string $sort How to sort the results
 809   * @return object (changed to groupids)
 810   */
 811  function get_group_students($groupids, $sort='ul.timeaccess DESC') {
 812  
 813      if (is_array($groupids)){
 814          $groups = $groupids;
 815          // all groups must be from one course anyway...
 816          $group = groups_get_group(array_shift($groups));
 817      } else {
 818          $group = groups_get_group($groupids);
 819      }
 820      if (!$group) {
 821          return NULL;
 822      }
 823  
 824      $context = get_context_instance(CONTEXT_COURSE, $group->courseid);
 825      return get_users_by_capability($context, 'moodle/legacy:student', 'u.*, ul.timeaccess as lastaccess', $sort, '','',$groupids, '', false);
 826  }
 827  
 828  /**
 829   * Returns list of all the teachers who can access a group
 830   *
 831   * @uses $CFG
 832   * @param int $courseid The course in question.
 833   * @param int $groupid The group in question.
 834   * @return object
 835   */
 836  function get_group_teachers($courseid, $groupid) {
 837  /// Returns a list of all the teachers who can access a group
 838      if ($teachers = get_course_teachers($courseid)) {
 839          foreach ($teachers as $key => $teacher) {
 840              if ($teacher->editall) {             // These can access anything
 841                  continue;
 842              }
 843              if (($teacher->authority > 0) and groups_is_member($groupid, $teacher->id)) {  // Specific group teachers
 844                  continue;
 845              }
 846              unset($teachers[$key]);
 847          }
 848      }
 849      return $teachers;
 850  }
 851  
 852  
 853  
 854  ########### FROM weblib.php ##########################################################################
 855  
 856  /**
 857   * Creates a nicely formatted table and returns it.
 858   *
 859   * @param array $table is an object with several properties.
 860   *     <ul<li>$table->head - An array of heading names.
 861   *     <li>$table->align - An array of column alignments
 862   *     <li>$table->size  - An array of column sizes
 863   *     <li>$table->wrap - An array of "nowrap"s or nothing
 864   *     <li>$table->data[] - An array of arrays containing the data.
 865   *     <li>$table->class -  A css class name
 866   *     <li>$table->fontsize - Is the size of all the text
 867   *     <li>$table->tablealign  - Align the whole table
 868   *     <li>$table->width  - A percentage of the page
 869   *     <li>$table->cellpadding  - Padding on each cell
 870   *     <li>$table->cellspacing  - Spacing between cells
 871   * </ul>
 872   * @return string
 873   * @todo Finish documenting this function
 874   */
 875  function make_table($table) {
 876      return print_table($table, true);
 877  }
 878  
 879  
 880  /**
 881   * Print a message in a standard themed box.
 882   * This old function used to implement boxes using tables.  Now it uses a DIV, but the old
 883   * parameters remain.  If possible, $align, $width and $color should not be defined at all.
 884   * Preferably just use print_box() in weblib.php
 885   *
 886   * @param string $align, alignment of the box, not the text (default center, left, right).
 887   * @param string $width, width of the box, including units %, for example '100%'.
 888   * @param string $color, background colour of the box, for example '#eee'.
 889   * @param int $padding, padding in pixels, specified without units.
 890   * @param string $class, space-separated class names.
 891   * @param string $id, space-separated id names.
 892   * @param boolean $return, return as string or just print it
 893   */
 894  function print_simple_box($message, $align='', $width='', $color='', $padding=5, $class='generalbox', $id='', $return=false) {
 895      $output = '';
 896      $output .= print_simple_box_start($align, $width, $color, $padding, $class, $id, true);
 897      $output .= stripslashes_safe($message);
 898      $output .= print_simple_box_end(true);
 899  
 900      if ($return) {
 901          return $output;
 902      } else {
 903          echo $output;
 904      }
 905  }
 906  
 907  
 908  
 909  /**
 910   * This old function used to implement boxes using tables.  Now it uses a DIV, but the old
 911   * parameters remain.  If possible, $align, $width and $color should not be defined at all.
 912   * Even better, please use print_box_start() in weblib.php
 913   *
 914   * @param string $align, alignment of the box, not the text (default center, left, right).   DEPRECATED
 915   * @param string $width, width of the box, including % units, for example '100%'.            DEPRECATED
 916   * @param string $color, background colour of the box, for example '#eee'.                   DEPRECATED
 917   * @param int $padding, padding in pixels, specified without units.                          OBSOLETE
 918   * @param string $class, space-separated class names.
 919   * @param string $id, space-separated id names.
 920   * @param boolean $return, return as string or just print it
 921   */
 922  function print_simple_box_start($align='', $width='', $color='', $padding=5, $class='generalbox', $id='', $return=false) {
 923  
 924      $output = '';
 925  
 926      $divclasses = 'box '.$class.' '.$class.'content';
 927      $divstyles  = '';
 928  
 929      if ($align) {
 930          $divclasses .= ' boxalign'.$align;    // Implement alignment using a class
 931      }
 932      if ($width) {    // Hopefully we can eliminate these in calls to this function (inline styles are bad)
 933          if (substr($width, -1, 1) == '%') {    // Width is a % value
 934              $width = (int) substr($width, 0, -1);    // Extract just the number
 935              if ($width < 40) {
 936                  $divclasses .= ' boxwidthnarrow';    // Approx 30% depending on theme
 937              } else if ($width > 60) {
 938                  $divclasses .= ' boxwidthwide';      // Approx 80% depending on theme
 939              } else {
 940                  $divclasses .= ' boxwidthnormal';    // Approx 50% depending on theme
 941              }
 942          } else {
 943              $divstyles  .= ' width:'.$width.';';     // Last resort
 944          }
 945      }
 946      if ($color) {    // Hopefully we can eliminate these in calls to this function (inline styles are bad)
 947          $divstyles  .= ' background:'.$color.';';
 948      }
 949      if ($divstyles) {
 950          $divstyles = ' style="'.$divstyles.'"';
 951      }
 952  
 953      if ($id) {
 954          $id = ' id="'.$id.'"';
 955      }
 956  
 957      $output .= '<div'.$id.$divstyles.' class="'.$divclasses.'">';
 958  
 959      if ($return) {
 960          return $output;
 961      } else {
 962          echo $output;
 963      }
 964  }
 965  
 966  
 967  /**
 968   * Print the end portion of a standard themed box.
 969   * Preferably just use print_box_end() in weblib.php
 970   */
 971  function print_simple_box_end($return=false) {
 972      $output = '</div>';
 973      if ($return) {
 974          return $output;
 975      } else {
 976          echo $output;
 977      }
 978  }
 979  
 980  /**
 981   * deprecated - use clean_param($string, PARAM_FILE); instead
 982   * Check for bad characters ?
 983   *
 984   * @param string $string ?
 985   * @param int $allowdots ?
 986   * @todo Finish documenting this function - more detail needed in description as well as details on arguments
 987   */
 988  function detect_munged_arguments($string, $allowdots=1) {
 989      if (substr_count($string, '..') > $allowdots) {   // Sometimes we allow dots in references
 990          return true;
 991      }
 992      if (ereg('[\|\`]', $string)) {  // check for other bad characters
 993          return true;
 994      }
 995      if (empty($string) or $string == '/') {
 996          return true;
 997      }
 998  
 999      return false;
1000  }
1001  
1002  /** Deprecated function - returns the code of the current charset - originally depended on the selected language pack.
1003   *
1004   * @param $ignorecache not used anymore
1005   * @return string always returns 'UTF-8'
1006   */
1007  function current_charset($ignorecache = false) {
1008      return 'UTF-8';
1009  }
1010  
1011  
1012  /////////////////////////////////////////////////////////////
1013  /// Old functions not used anymore - candidates for removal
1014  /////////////////////////////////////////////////////////////
1015  
1016  /**
1017   * Load a template from file - this function dates back to Moodle 1 :-) not used anymore
1018   *
1019   * Returns a (big) string containing the contents of a template file with all
1020   * the variables interpolated.  all the variables must be in the $var[] array or
1021   * object (whatever you decide to use).
1022   *
1023   * <b>WARNING: do not use this on big files!!</b>
1024   *
1025   * @param string $filename Location on the server's filesystem where template can be found.
1026   * @param mixed $var Passed in by reference. An array or object which will be loaded with data from the template file.
1027   *
1028   */
1029  function read_template($filename, &$var) {
1030  
1031      $temp = str_replace("\\", "\\\\", implode(file($filename), ''));
1032      $temp = str_replace('"', '\"', $temp);
1033      eval("\$template = \"$temp\";");
1034      return $template;
1035  }
1036  
1037  
1038  /**
1039   * deprecated - relies on register globals; use new formslib instead
1040   *
1041   * Set a variable's value depending on whether or not it already has a value.
1042   *
1043   * If variable is set, set it to the set_value otherwise set it to the
1044   * unset_value.  used to handle checkboxes when you are expecting them from
1045   * a form
1046   *
1047   * @param mixed $var Passed in by reference. The variable to check.
1048   * @param mixed $set_value The value to set $var to if $var already has a value.
1049   * @param mixed $unset_value The value to set $var to if $var does not already have a value.
1050   */
1051  function checked(&$var, $set_value = 1, $unset_value = 0) {
1052  
1053      if (empty($var)) {
1054          $var = $unset_value;
1055      } else {
1056          $var = $set_value;
1057      }
1058  }
1059  
1060  /**
1061   * deprecated - use new formslib instead
1062   *
1063   * Prints the word "checked" if a variable is true, otherwise prints nothing,
1064   * used for printing the word "checked" in a checkbox form element.
1065   *
1066   * @param boolean $var Variable to be checked for true value
1067   * @param string $true_value Value to be printed if $var is true
1068   * @param string $false_value Value to be printed if $var is false
1069   */
1070  function frmchecked(&$var, $true_value = 'checked', $false_value = '') {
1071  
1072      if ($var) {
1073          echo $true_value;
1074      } else {
1075          echo $false_value;
1076      }
1077  }
1078  
1079  /**
1080   * Legacy function, provided for backward compatability.
1081   * This method now simply calls {@link use_html_editor()}
1082   *
1083   * @deprecated Use {@link use_html_editor()} instead.
1084   * @param string $name Form element to replace with HTMl editor by name
1085   * @todo Finish documenting this function
1086   */
1087  function print_richedit_javascript($form, $name, $source='no') {
1088      use_html_editor($name);
1089  }
1090  
1091  /** various deprecated groups function **/
1092  
1093  
1094  /**
1095   * Returns the table in which group members are stored, with a prefix 'gm'.
1096   * @return SQL string.
1097   */
1098  function groups_members_from_sql() {
1099      global $CFG;
1100      return " {$CFG->prefix}groups_members gm ";
1101  }
1102  
1103  /**
1104   * Returns a join testing user.id against member's user ID.
1105   * Relies on 'user' table being included as 'user u'.
1106   * Used in Quiz module reports.
1107   * @param group ID, optional to include a test for this in the SQL.
1108   * @return SQL string.
1109   */
1110  function groups_members_join_sql($groupid=false) {
1111      $sql = ' JOIN '.groups_members_from_sql().' ON u.id = gm.userid ';
1112      if ($groupid) {
1113          $sql = "AND gm.groupid = '$groupid' ";
1114      }
1115      return $sql;
1116      //return ' INNER JOIN '.$CFG->prefix.'role_assignments ra ON u.id=ra.userid'.
1117      //       ' INNER JOIN '.$CFG->prefix.'context c ON ra.contextid=c.id AND c.contextlevel='.CONTEXT_GROUP.' AND c.instanceid='.$groupid;
1118  }
1119  
1120  /**
1121   * Returns SQL for a WHERE clause testing the group ID.
1122   * Optionally test the member's ID against another table's user ID column.
1123   * @param groupid
1124   * @param userid_sql Optional user ID column selector, example "mdl_user.id", or false.
1125   * @return SQL string.
1126   */
1127  function groups_members_where_sql($groupid, $userid_sql=false) {
1128      $sql = " gm.groupid = '$groupid' ";
1129      if ($userid_sql) {
1130          $sql .= "AND $userid_sql = gm.userid ";
1131      }
1132      return $sql;
1133  }
1134  
1135  
1136  /**
1137   * Returns an array of group objects that the user is a member of
1138   * in the given course.  If userid isn't specified, then return a
1139   * list of all groups in the course.
1140   *
1141   * @uses $CFG
1142   * @param int $courseid The id of the course in question.
1143   * @param int $userid The id of the user in question as found in the 'user' table 'id' field.
1144   * @return object
1145   */
1146  function get_groups($courseid, $userid=0) {
1147      return groups_get_all_groups($courseid, $userid);
1148  }
1149  
1150  /**
1151   * Returns the user's groups in a particular course
1152   * note: this function originally returned only one group
1153   *
1154   * @uses $CFG
1155   * @param int $courseid The course in question.
1156   * @param int $userid The id of the user as found in the 'user' table.
1157   * @param int $groupid The id of the group the user is in.
1158   * @return aray of groups
1159   */
1160  function user_group($courseid, $userid) {
1161      return groups_get_all_groups($courseid, $userid);
1162  }
1163  
1164  
1165  /**
1166   * Determines if the user is a member of the given group.
1167   *
1168   * @param int $groupid The group to check for membership.
1169   * @param int $userid The user to check against the group.
1170   * @return boolean True if the user is a member, false otherwise.
1171   */
1172  function ismember($groupid, $userid = null) {
1173      return groups_is_member($groupid, $userid);
1174  }
1175  
1176  /**
1177   * Get the IDs for the user's groups in the given course.
1178   *
1179   * @uses $USER
1180   * @param int $courseid The course being examined - the 'course' table id field.
1181   * @return array An _array_ of groupids.
1182   * (Was return $groupids[0] - consequences!)
1183   */
1184  function mygroupid($courseid) {
1185      global $USER;
1186      if ($groups = groups_get_all_groups($courseid, $USER->id)) {
1187          return array_keys($groups);
1188      } else {
1189          return false;
1190      }
1191  }
1192  
1193  /**
1194   * Add a user to a group, return true upon success or if user already a group
1195   * member
1196   *
1197   * @param int $groupid  The group id to add user to
1198   * @param int $userid   The user id to add to the group
1199   * @return bool
1200   */
1201  function add_user_to_group($groupid, $userid) {
1202      global $CFG;
1203      require_once($CFG->dirroot.'/group/lib.php');
1204  
1205      return groups_add_member($groupid, $userid);
1206  }
1207  
1208  
1209  /**
1210   * Returns an array of user objects
1211   *
1212   * @uses $CFG
1213   * @param int $groupid The group in question.
1214   * @param string $sort ?
1215   * @param string $exceptions ?
1216   * @return object
1217   * @todo Finish documenting this function
1218   */
1219  function get_group_users($groupid, $sort='u.lastaccess DESC', $exceptions='',
1220                           $fields='u.*') {
1221      global $CFG;
1222      if (!empty($exceptions)) {
1223          $except = ' AND u.id NOT IN ('. $exceptions .') ';
1224      } else {
1225          $except = '';
1226      }
1227      // in postgres, you can't have things in sort that aren't in the select, so...
1228      $extrafield = str_replace('ASC','',$sort);
1229      $extrafield = str_replace('DESC','',$extrafield);
1230      $extrafield = trim($extrafield);
1231      if (!empty($extrafield)) {
1232          $extrafield = ','.$extrafield;
1233      }
1234      return get_records_sql("SELECT DISTINCT $fields $extrafield
1235                                FROM {$CFG->prefix}user u,
1236                                     {$CFG->prefix}groups_members m
1237                               WHERE m.groupid = '$groupid'
1238                                 AND m.userid = u.id $except
1239                            ORDER BY $sort");
1240  }
1241  
1242  /**
1243   * Returns the current group mode for a given course or activity module
1244   *
1245   * Could be false, SEPARATEGROUPS or VISIBLEGROUPS    (<-- Martin)
1246   */
1247  function groupmode($course, $cm=null) {
1248  
1249      if (isset($cm->groupmode) && empty($course->groupmodeforce)) {
1250          return $cm->groupmode;
1251      }
1252      return $course->groupmode;
1253  }
1254  
1255  
1256  /**
1257   * Sets the current group in the session variable
1258   * When $SESSION->currentgroup[$courseid] is set to 0 it means, show all groups.
1259   * Sets currentgroup[$courseid] in the session variable appropriately.
1260   * Does not do any permission checking.
1261   * @uses $SESSION
1262   * @param int $courseid The course being examined - relates to id field in
1263   * 'course' table.
1264   * @param int $groupid The group being examined.
1265   * @return int Current group id which was set by this function
1266   */
1267  function set_current_group($courseid, $groupid) {
1268      global $SESSION;
1269      return $SESSION->currentgroup[$courseid] = $groupid;
1270  }
1271  
1272  
1273  /**
1274   * Gets the current group - either from the session variable or from the database.
1275   *
1276   * @uses $USER
1277   * @uses $SESSION
1278   * @param int $courseid The course being examined - relates to id field in
1279   * 'course' table.
1280   * @param bool $full If true, the return value is a full record object.
1281   * If false, just the id of the record.
1282   */
1283  function get_current_group($courseid, $full = false) {
1284      global $SESSION;
1285  
1286      if (isset($SESSION->currentgroup[$courseid])) {
1287          if ($full) {
1288              return groups_get_group($SESSION->currentgroup[$courseid]);
1289          } else {
1290              return $SESSION->currentgroup[$courseid];
1291          }
1292      }
1293  
1294      $mygroupid = mygroupid($courseid);
1295      if (is_array($mygroupid)) {
1296          $mygroupid = array_shift($mygroupid);
1297          set_current_group($courseid, $mygroupid);
1298          if ($full) {
1299              return groups_get_group($mygroupid);
1300          } else {
1301              return $mygroupid;
1302          }
1303      }
1304  
1305      if ($full) {
1306          return false;
1307      } else {
1308          return 0;
1309      }
1310  }
1311  
1312  
1313  /**
1314   * A combination function to make it easier for modules
1315   * to set up groups.
1316   *
1317   * It will use a given "groupid" parameter and try to use
1318   * that to reset the current group for the user.
1319   *
1320   * @uses VISIBLEGROUPS
1321   * @param course $course A {@link $COURSE} object
1322   * @param int $groupmode Either NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
1323   * @param int $groupid Will try to use this optional parameter to
1324   *            reset the current group for the user
1325   * @return int|false Returns the current group id or false if error.
1326   */
1327  function get_and_set_current_group($course, $groupmode, $groupid=-1) {
1328  
1329      // Sets to the specified group, provided the current user has view permission
1330      if (!$groupmode) {   // Groups don't even apply
1331          return false;
1332      }
1333  
1334      $currentgroupid = get_current_group($course->id);
1335  
1336      if ($groupid < 0) {  // No change was specified
1337          return $currentgroupid;
1338      }
1339  
1340      $context = get_context_instance(CONTEXT_COURSE, $course->id);
1341      if ($groupid and $group = get_record('groups', 'id', $groupid)) {      // Try to change the current group to this groupid
1342          if ($group->courseid == $course->id) {
1343              if (has_capability('moodle/site:accessallgroups', $context)) {  // Sets current default group
1344                  $currentgroupid = set_current_group($course->id, $groupid);
1345  
1346              } elseif ($groupmode == VISIBLEGROUPS) {
1347                    // All groups are visible
1348                  //if (groups_is_member($group->id)){
1349                      $currentgroupid = set_current_group($course->id, $groupid); //set this since he might post
1350                  /*)}else {
1351                      $currentgroupid = $group->id;*/
1352              } elseif ($groupmode == SEPARATEGROUPS) { // student in separate groups switching
1353                  if (groups_is_member($groupid)) { //check if is a member
1354                      $currentgroupid = set_current_group($course->id, $groupid); //might need to set_current_group?
1355                  }
1356                  else {
1357                      notify('You do not belong to this group! ('.$groupid.')', 'error');
1358                  }
1359              }
1360          }
1361      } else { // When groupid = 0 it means show ALL groups
1362          // this is changed, non editting teacher needs access to group 0 as well,
1363          // for viewing work in visible groups (need to set current group for multiple pages)
1364          if (has_capability('moodle/site:accessallgroups', $context)) { // Sets current default group
1365              $currentgroupid = set_current_group($course->id, 0);
1366  
1367          } else if ($groupmode == VISIBLEGROUPS) {  // All groups are visible
1368              $currentgroupid = set_current_group($course->id, 0);
1369          }
1370      }
1371  
1372      return $currentgroupid;
1373  }
1374  
1375  
1376  /**
1377   * A big combination function to make it easier for modules
1378   * to set up groups.
1379   *
1380   * Terminates if the current user shouldn't be looking at this group
1381   * Otherwise returns the current group if there is one
1382   * Otherwise returns false if groups aren't relevant
1383   *
1384   * @uses SEPARATEGROUPS
1385   * @uses VISIBLEGROUPS
1386   * @param course $course A {@link $COURSE} object
1387   * @param int $groupmode Either NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
1388   * @param string $urlroot ?
1389   * @return int|false
1390   */
1391  function setup_and_print_groups($course, $groupmode, $urlroot) {
1392  
1393      global $USER, $SESSION; //needs his id, need to hack his groups in session
1394  
1395      $changegroup = optional_param('group', -1, PARAM_INT);
1396  
1397      $currentgroup = get_and_set_current_group($course, $groupmode, $changegroup);
1398      if ($currentgroup === false) {
1399          return false;
1400      }
1401  
1402      $context = get_context_instance(CONTEXT_COURSE, $course->id);
1403  
1404      if ($groupmode == SEPARATEGROUPS and !$currentgroup and !has_capability('moodle/site:accessallgroups', $context)) {
1405          //we are in separate groups and the current group is group 0, as last set.
1406          //this can mean that either, this guy has no group
1407          //or, this guy just came from a visible all forum, and he left when he set his current group to 0 (show all)
1408  
1409          if ($usergroups = groups_get_all_groups($course->id, $USER->id)){
1410              //for the second situation, we need to perform the trick and get him a group.
1411              $first = reset($usergroups);
1412              $currentgroup = get_and_set_current_group($course, $groupmode, $first->id);
1413  
1414          } else {
1415              //else he has no group in this course
1416              print_heading(get_string('notingroup'));
1417              print_footer($course);
1418              exit;
1419          }
1420      }
1421  
1422      if ($groupmode == VISIBLEGROUPS or ($groupmode and has_capability('moodle/site:accessallgroups', $context))) {
1423  
1424          if ($groups = groups_get_all_groups($course->id)) {
1425  
1426              echo '<div class="groupselector">';
1427              print_group_menu($groups, $groupmode, $currentgroup, $urlroot, 1);
1428              echo '</div>';
1429          }
1430  
1431      } else if ($groupmode == SEPARATEGROUPS and has_capability('moodle/course:view', $context)) {
1432          //get all the groups this guy is in in this course
1433          if ($usergroups = groups_get_all_groups($course->id, $USER->id)){
1434              echo '<div class="groupselector">';
1435              //print them in the menu
1436              print_group_menu($usergroups, $groupmode, $currentgroup, $urlroot, 0);
1437              echo '</div>';
1438          }
1439      }
1440  
1441      return $currentgroup;
1442  }
1443  
1444  /**
1445   * Prints an appropriate group selection menu
1446   *
1447   * @uses VISIBLEGROUPS
1448   * @param array $groups ?
1449   * @param int $groupmode ?
1450   * @param string $currentgroup ?
1451   * @param string $urlroot ?
1452   * @param boolean $showall: if set to 0, it is a student in separate groups, do not display all participants
1453   * @todo Finish documenting this function
1454   */
1455  function print_group_menu($groups, $groupmode, $currentgroup, $urlroot, $showall=1, $return=false) {
1456  
1457      $output = '';
1458      $groupsmenu = array();
1459  
1460  /// Add an "All groups" to the start of the menu
1461      if ($showall){
1462          $groupsmenu[0] = get_string('allparticipants');
1463      }
1464      foreach ($groups as $key => $group) {
1465          $groupsmenu[$key] = format_string($group->name);
1466      }
1467  
1468      if ($groupmode == VISIBLEGROUPS) {
1469          $grouplabel = get_string('groupsvisible');
1470      } else {
1471          $grouplabel = get_string('groupsseparate');
1472      }
1473  
1474      if (count($groupsmenu) == 1) {
1475          $groupname = reset($groupsmenu);
1476          $output .= $grouplabel.': '.$groupname;
1477      } else {
1478          $output .= popup_form($urlroot.'&amp;group=', $groupsmenu, 'selectgroup', $currentgroup, '', '', '', true, 'self', $grouplabel);
1479      }
1480  
1481      if ($return) {
1482          return $output;
1483      } else {
1484          echo $output;
1485      }
1486  
1487  }
1488  
1489  /**
1490   * All users that we have not seen for a really long time (ie dead accounts)
1491   * TODO: Delete this for Moodle 2.0
1492   *
1493   * @uses $CFG
1494   * @deprecated The query is executed directly within admin/cron.php (MDL-11571)
1495   * @param string $cutofftime ?
1496   * @return object  {@link $USER} records
1497   */
1498  function get_users_longtimenosee($cutofftime) {
1499      global $CFG;
1500      return get_records_sql("SELECT id, userid, courseid
1501                               FROM {$CFG->prefix}user_lastaccess
1502                              WHERE courseid != ".SITEID."
1503                                AND timeaccess < $cutofftime ");
1504  }
1505  
1506  /**
1507   * Full list of users that have not yet confirmed their accounts.
1508   * TODO: Delete this for Moodle 2.0
1509   *
1510   * @uses $CFG
1511   * @deprecated The query is executed directly within admin/cron.php (MDL-11487)
1512   * @param string $cutofftime ?
1513   * @return object  {@link $USER} records
1514   */
1515  function get_users_unconfirmed($cutofftime=2000000000) {
1516      global $CFG;
1517      return get_records_sql("SELECT *
1518                                FROM {$CFG->prefix}user
1519                               WHERE confirmed = 0
1520                                 AND firstaccess > 0
1521                                 AND firstaccess < $cutofftime");
1522  }
1523  
1524  /**
1525   * Full list of bogus accounts that are probably not ever going to be used
1526   * TODO: Delete this for Moodle 2.0
1527   *
1528   * @uses $CFG
1529   * @deprecated The query is executed directly within admin/cron.php (MDL-11487)
1530   * @param string $cutofftime ?
1531   * @return object  {@link $USER} records
1532   */
1533  function get_users_not_fully_set_up($cutofftime=2000000000) {
1534      global $CFG;
1535      return get_records_sql("SELECT *
1536                                FROM {$CFG->prefix}user
1537                               WHERE confirmed = 1
1538                                 AND lastaccess > 0
1539                                 AND lastaccess < $cutofftime
1540                                 AND deleted = 0
1541                                 AND (lastname = '' OR firstname = '' OR email = '')");
1542  }
1543  
1544  /**
1545   * Returns SQL to be used as a subselect to find the primary role of users.
1546   * Geoff Cant <geoff@catalyst.net.nz> (the author) is very keen for this to
1547   * be implemented as a view in future versions.
1548   *
1549   * eg if this function returns a string called $primaryroles, then you could:
1550   * $sql = 'SELECT COUNT(DISTINCT prs.userid) FROM ('.$primary_roles.') prs
1551   *          WHERE prs.primary_roleid='.$role->id.' AND prs.courseid='.$course->id.
1552   *          ' AND prs.contextlevel = '.CONTEXT_COURSE;
1553   *
1554   * @return string the piece of SQL code to be used in your FROM( ) statement.
1555   */
1556  function sql_primary_role_subselect() {
1557      global $CFG;
1558      return 'SELECT ra.userid,
1559                  ra.roleid AS primary_roleid,
1560                  ra.contextid,
1561                  r.sortorder,
1562                  r.name,
1563                  r.description,
1564                  r.shortname,
1565                  c.instanceid AS courseid,
1566                  c.contextlevel
1567              FROM '.$CFG->prefix.'role_assignments ra
1568              INNER JOIN '.$CFG->prefix.'role r ON ra.roleid = r.id
1569              INNER JOIN '.$CFG->prefix.'context c ON ra.contextid = c.id
1570              WHERE NOT EXISTS (
1571                                SELECT 1
1572                                FROM '.$CFG->prefix.'role_assignments i_ra
1573                                INNER JOIN '.$CFG->prefix.'role i_r ON i_ra.roleid = i_r.id
1574                                WHERE ra.userid = i_ra.userid AND
1575                                       ra.contextid = i_ra.contextid AND
1576                                       i_r.sortorder < r.sortorder
1577                                ) ';
1578  }
1579  
1580  /**
1581   * Can include a given document file (depends on second
1582   * parameter) or just return info about it.
1583   *
1584   * @uses $CFG
1585   * @param string $file ?
1586   * @param bool $include ?
1587   * @return ?
1588   * @todo Finish documenting this function
1589   */
1590  function document_file($file, $include=true) {
1591      global $CFG;
1592  
1593      debugging('The document_file() function is deprecated.', DEBUG_DEVELOPER);
1594  
1595      $file = clean_filename($file);
1596  
1597      if (empty($file)) {
1598          return false;
1599      }
1600  
1601      $langs = array(current_language(), get_string('parentlanguage'), 'en');
1602  
1603      foreach ($langs as $lang) {
1604          $info = new object();
1605          $info->filepath = $CFG->dirroot .'/lang/'. $lang .'/docs/'. $file;
1606          $info->urlpath  = $CFG->wwwroot .'/lang/'. $lang .'/docs/'. $file;
1607  
1608          if (file_exists($info->filepath)) {
1609              if ($include) {
1610                  include($info->filepath);
1611              }
1612              return $info;
1613          }
1614      }
1615  
1616      return false;
1617  }
1618  
1619  /**
1620   * Print an error page displaying an error message.
1621   * Old method, don't call directly in new code - use print_error instead.
1622   *
1623   *
1624   * @uses $SESSION
1625   * @uses $CFG
1626   * @param string $message The message to display to the user about the error.
1627   * @param string $link The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
1628   */
1629  function error ($message, $link='') {
1630  
1631      global $CFG, $SESSION, $THEME;
1632      $message = clean_text($message);   // In case nasties are in here
1633  
1634      if (defined('FULLME') && FULLME == 'cron') {
1635          // Errors in cron should be mtrace'd.
1636          mtrace($message);
1637          die;
1638      }
1639  
1640      if (! defined('HEADER_PRINTED')) {
1641          //header not yet printed
1642          @header('HTTP/1.0 404 Not Found');
1643          print_header(get_string('error'));
1644      } else {
1645          print_container_end_all(false, $THEME->open_header_containers);
1646      }
1647  
1648      echo '<br />';
1649      print_simple_box($message, '', '', '', '', 'errorbox');
1650  
1651      debugging('Stack trace:', DEBUG_DEVELOPER);
1652  
1653      // in case we are logging upgrade in admin/index.php stop it
1654      if (function_exists('upgrade_log_finish')) {
1655          upgrade_log_finish();
1656      }
1657  
1658      if (empty($link) and !defined('ADMIN_EXT_HEADER_PRINTED')) {
1659          if ( !empty($SESSION->fromurl) ) {
1660              $link = $SESSION->fromurl;
1661              unset($SESSION->fromurl);
1662          } else {
1663              $link = $CFG->wwwroot .'/';
1664          }
1665      }
1666  
1667      if (!empty($link)) {
1668          print_continue($link);
1669      }
1670  
1671      print_footer();
1672  
1673      for ($i=0;$i<512;$i++) {  // Padding to help IE work with 404
1674          echo ' ';
1675      }
1676  
1677      die;
1678  }
1679  ?>


Generated: Wed Jan 14 11:33:29 2009 Cross-referenced by PHPXref 0.7