Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.3.x will end 7 October 2024 (12 months).
  • Bug fixes for security issues in 4.3.x will end 21 April 2025 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.2.x is supported too.

Differences Between: [Versions 310 and 403] [Versions 311 and 403] [Versions 39 and 403] [Versions 400 and 403] [Versions 401 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  /**
  18   * CLI Bulk course registration script from a comma separated file.
  19   *
  20   * @package    tool_uploadcourse
  21   * @copyright  2012 Piers Harding
  22   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  define('CLI_SCRIPT', true);
  26  
  27  require(__DIR__ . '/../../../../config.php');
  28  require_once($CFG->libdir . '/clilib.php');
  29  require_once($CFG->libdir . '/csvlib.class.php');
  30  
  31  $courseconfig = get_config('moodlecourse');
  32  
  33  // Now get cli options.
  34  list($options, $unrecognized) = cli_get_params(array(
  35      'help' => false,
  36      'mode' => '',
  37      'updatemode' => 'nothing',
  38      'file' => '',
  39      'delimiter' => 'comma',
  40      'encoding' => 'UTF-8',
  41      'shortnametemplate' => '',
  42      'templatecourse' => false,
  43      'restorefile' => false,
  44      'allowdeletes' => false,
  45      'allowrenames' => false,
  46      'allowresets' => false,
  47      'reset' => false,
  48      'category' => core_course_category::get_default()->id,
  49  ),
  50  array(
  51      'h' => 'help',
  52      'm' => 'mode',
  53      'u' => 'updatemode',
  54      'f' => 'file',
  55      'd' => 'delimiter',
  56      'e' => 'encoding',
  57      't' => 'templatecourse',
  58      'r' => 'restorefile',
  59      'g' => 'format',
  60  ));
  61  
  62  if ($unrecognized) {
  63      $unrecognized = implode("\n  ", $unrecognized);
  64      cli_error(get_string('cliunknowoption', 'admin', $unrecognized));
  65  }
  66  
  67  $help =
  68  "Execute Course Upload.
  69  
  70  Options:
  71  -h, --help                 Print out this help
  72  -m, --mode                 Import mode: createnew, createall, createorupdate, update
  73  -u, --updatemode           Update mode: nothing, dataonly, dataordefaults¸ missingonly
  74  -f, --file                 CSV file
  75  -d, --delimiter            CSV delimiter: colon, semicolon, tab, cfg, comma
  76  -e, --encoding             CSV file encoding: utf8, ... etc
  77  -t, --templatecourse       Shortname of the course to restore after import
  78  -r, --restorefile          Backup file to restore after import
  79  --reset                    Run the course reset after each course import
  80  --allowdeletes             Allow courses to be deleted
  81  --allowrenames             Allow courses to be renamed
  82  --allowresets              Allow courses to be reset
  83  --shortnametemplate        Template to generate the shortname from
  84  --category                 ID of default category (--updatemode dataordefaults will use this value)
  85  
  86  
  87  Example:
  88  \$sudo -u www-data /usr/bin/php admin/tool/uploadcourse/cli/uploadcourse.php --mode=createnew \\
  89         --updatemode=dataonly --file=./courses.csv --delimiter=comma
  90  ";
  91  
  92  if ($options['help']) {
  93      echo $help;
  94      die();
  95  }
  96  echo "Moodle course uploader running ...\n";
  97  
  98  $processoroptions = array(
  99      'allowdeletes' => $options['allowdeletes'],
 100      'allowrenames' => $options['allowrenames'],
 101      'allowresets' => $options['allowresets'],
 102      'reset' => $options['reset'],
 103      'shortnametemplate' => $options['shortnametemplate']
 104  );
 105  
 106  // Confirm that the mode is valid.
 107  $modes = array(
 108      'createnew' => tool_uploadcourse_processor::MODE_CREATE_NEW,
 109      'createall' => tool_uploadcourse_processor::MODE_CREATE_ALL,
 110      'createorupdate' => tool_uploadcourse_processor::MODE_CREATE_OR_UPDATE,
 111      'update' => tool_uploadcourse_processor::MODE_UPDATE_ONLY
 112  );
 113  if (!isset($options['mode']) || !isset($modes[$options['mode']])) {
 114      echo get_string('invalidmode', 'tool_uploadcourse')."\n";
 115      echo $help;
 116      die();
 117  }
 118  $processoroptions['mode'] = $modes[$options['mode']];
 119  
 120  // Check that the update mode is valid.
 121  $updatemodes = array(
 122      'nothing' => tool_uploadcourse_processor::UPDATE_NOTHING,
 123      'dataonly' => tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY,
 124      'dataordefaults' => tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_OR_DEFAUTLS,
 125      'missingonly' => tool_uploadcourse_processor::UPDATE_MISSING_WITH_DATA_OR_DEFAUTLS
 126  );
 127  if (($processoroptions['mode'] === tool_uploadcourse_processor::MODE_CREATE_OR_UPDATE ||
 128          $processoroptions['mode'] === tool_uploadcourse_processor::MODE_UPDATE_ONLY)
 129          && (!isset($options['updatemode']) || !isset($updatemodes[$options['updatemode']]))) {
 130      echo get_string('invalideupdatemode', 'tool_uploadcourse')."\n";
 131      echo $help;
 132      die();
 133  }
 134  $processoroptions['updatemode'] = $updatemodes[$options['updatemode']];
 135  
 136  // File.
 137  if (!empty($options['file'])) {
 138      $options['file'] = realpath($options['file']);
 139  }
 140  if (!file_exists($options['file'])) {
 141      echo get_string('invalidcsvfile', 'tool_uploadcourse')."\n";
 142      echo $help;
 143      die();
 144  }
 145  
 146  // Encoding.
 147  $encodings = core_text::get_encodings();
 148  if (!isset($encodings[$options['encoding']])) {
 149      echo get_string('invalidencoding', 'tool_uploadcourse')."\n";
 150      echo $help;
 151      die();
 152  }
 153  
 154  // Default values.
 155  $defaults = array();
 156  $defaults['category'] = $options['category'];
 157  $defaults['startdate'] = time() + 3600 * 24;
 158  $defaults['enddate'] = $defaults['startdate'] + intval(get_config('moodlecourse', 'courseduration'));
 159  $defaults['newsitems'] = $courseconfig->newsitems;
 160  $defaults['showgrades'] = $courseconfig->showgrades;
 161  $defaults['showreports'] = $courseconfig->showreports;
 162  $defaults['maxbytes'] = $courseconfig->maxbytes;
 163  $defaults['legacyfiles'] = $CFG->legacyfilesinnewcourses;
 164  $defaults['groupmode'] = $courseconfig->groupmode;
 165  $defaults['groupmodeforce'] = $courseconfig->groupmodeforce;
 166  $defaults['visible'] = $courseconfig->visible;
 167  $defaults['lang'] =  $courseconfig->lang;
 168  $defaults['enablecompletion'] = $courseconfig->enablecompletion;
 169  $defaults['showactivitydates'] = $courseconfig->showactivitydates;
 170  
 171  // Course template.
 172  if (isset($options['templatecourse'])) {
 173      $processoroptions['templatecourse'] = $options['templatecourse'];
 174  }
 175  
 176  // Restore file.
 177  if ($options['restorefile']) {
 178      $options['restorefile'] = realpath($options['restorefile']);
 179  }
 180  if ($options['restorefile'] && !file_exists($options['restorefile'])) {
 181      echo get_string('invalidrestorefile', 'tool_uploadcourse')."\n";
 182      echo $help;
 183      die();
 184  }
 185  $processoroptions['restorefile'] = $options['restorefile'];
 186  
 187  // Emulate normal session.
 188  \core\cron::setup_user();
 189  
 190  // Let's get started!
 191  $content = file_get_contents($options['file']);
 192  $importid = csv_import_reader::get_new_iid('uploadcourse');
 193  $cir = new csv_import_reader($importid, 'uploadcourse');
 194  $readcount = $cir->load_csv_content($content, $options['encoding'], $options['delimiter']);
 195  unset($content);
 196  if ($readcount === false) {
 197      throw new \moodle_exception('csvfileerror', 'tool_uploadcourse', '', $cir->get_error());
 198  } else if ($readcount == 0) {
 199      throw new \moodle_exception('csvemptyfile', 'error', '', $cir->get_error());
 200  }
 201  $processor = new tool_uploadcourse_processor($cir, $processoroptions, $defaults);
 202  $processor->execute(new tool_uploadcourse_tracker(tool_uploadcourse_tracker::OUTPUT_PLAIN));