uploadcsv.php 13.3 KB
Newer Older
1 2 3 4 5 6
<?php
/**
 *
 * @package    mahara
 * @subpackage admin
 * @author     Catalyst IT Ltd
7 8
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
 *
 */

define('INTERNAL', 1);
define('INSTITUTIONALADMIN', 1);
define('MENUITEM', 'managegroups/uploadcsv');
require(dirname(dirname(dirname(__FILE__))) . '/init.php');
define('TITLE', get_string('uploadgroupcsv', 'admin'));
require_once('pieforms/pieform.php');
require_once(get_config('libroot') . 'group.php');
require_once(get_config('libroot') . 'institution.php');
safe_require('artefact', 'internal');

// Turn on autodetecting of line endings, so mac newlines (\r) will work
ini_set('auto_detect_line_endings', 1);

$FORMAT = array();
$ALLOWEDKEYS = array(
    'shortname',
    'displayname',
    'description',
30 31 32 33
    'open',
    'controlled',
    'request',
    'roles',
34
    'public',
35
    'submitpages',
36
    'allowarchives',
37
    'editroles',
38
    'hidden',
39
    'hidemembers',
40
    'hidemembersfrommembers',
41 42
    'invitefriends',
    'suggestfriends',
43 44 45 46 47 48 49 50
);
if ($USER->get('admin')) {
    $ALLOWEDKEYS[] = 'usersautoadded';
    $ALLOWEDKEYS[] = 'quota';
}
$MANDATORYFIELDS = array(
    'shortname',
    'displayname',
51
    'roles',
52 53
);
$UPDATES         = array(); // During validation, remember which group already exist
54
$GROUPTYPES = group_get_grouptype_options();
55
$EDITROLES  = group_get_editroles_options();
56 57 58 59 60 61 62 63 64

$form = array(
    'name' => 'uploadcsv',
    'elements' => array(
        'institution' => get_institution_selector(),
        'file' => array(
            'type' => 'file',
            'title' => get_string('csvfile', 'admin'),
            'description' => get_string('groupcsvfiledescription', 'admin'),
65
            'accept' => '.csv, text/csv, application/csv, text/comma-separated-values',
66 67 68 69 70
            'rules' => array(
                'required' => true
            )
        ),
        'updategroups' => array(
71
            'type' => 'switchbox',
72
            'title' => get_string('updategroups', 'admin'),
73
            'description' => get_string('updategroupsdescription1', 'admin'),
74 75
            'defaultvalue' => false,
        ),
76 77 78 79 80
        'progress_meter_token' => array(
            'type' => 'hidden',
            'value' => 'uploadgroupscsv',
            'readonly' => TRUE,
        ),
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
        'submit' => array(
            'type' => 'submit',
            'value' => get_string('uploadgroupcsv', 'admin')
        )
    )
);


/**
 * The CSV file is parsed here so validation errors can be returned to the
 * user. The data from a successful parsing is stored in the <var>$CVSDATA</var>
 * array so it can be accessed by the submit function
 *
 * @param Pieform  $form   The form to validate
 * @param array    $values The values submitted
 */
function uploadcsv_validate(Pieform $form, $values) {
98
    global $CSVDATA, $ALLOWEDKEYS, $MANDATORYFIELDS, $GROUPTYPES, $FORMAT, $USER, $UPDATES, $EDITROLES;
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122

    // Don't even start attempting to parse if there are previous errors
    if ($form->has_errors()) {
        return;
    }

    if ($values['file']['size'] == 0) {
        $form->set_error('file', $form->i18n('rule', 'required', 'required', array()));
        return;
    }

    $institution = $values['institution'];
    if (!$USER->can_edit_institution($institution)) {
        $form->set_error('institution', get_string('notadminforinstitution', 'admin'));
        return;
    }

    require_once('csvfile.php');

    $csvgroups = new CsvFile($values['file']['tmp_name']);
    $csvgroups->set('allowedkeys', $ALLOWEDKEYS);

    $csvgroups->set('mandatoryfields', $MANDATORYFIELDS);
    $csvdata = $csvgroups->get_data();
123
    $num_lines = count($csvdata->data);
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140

    if (!empty($csvdata->errors['file'])) {
        $form->set_error('file', $csvdata->errors['file']);
        return;
    }

    $csverrors = new CSVErrors();

    $formatkeylookup = array_flip($csvdata->format);

    $shortnames = array();
    $displaynames = array();

    foreach ($csvdata->data as $key => $line) {
        // If headers exists, increment i = key + 2 for actual line number
        $i = ($csvgroups->get('headerExists')) ? ($key + 2) : ($key + 1);

141 142 143 144 145
        // In adding 5000 groups, this part was approx 10% of the wall time.
        if (!($key % 25)) {
            set_progress_info('uploadgroupscsv', $key, $num_lines * 10, get_string('validating', 'admin'));
        }

146 147 148 149 150 151 152 153 154 155 156 157
        // Trim non-breaking spaces -- they get left in place by File_CSV
        foreach ($line as &$field) {
            $field = preg_replace('/^(\s|\xc2\xa0)*(.*?)(\s|\xc2\xa0)*$/', '$2', $field);
        }

        if (count($line) != count($csvdata->format)) {
            $csverrors->add($i, get_string('uploadcsverrorwrongnumberoffields', 'admin', $i));
            continue;
        }

        $shortname = $line[$formatkeylookup['shortname']];
        $displayname = $line[$formatkeylookup['displayname']];
158 159 160 161
        $grouptype = $line[$formatkeylookup['roles']];
        $open = isset($formatkeylookup['open']) && !empty($line[$formatkeylookup['open']]);
        $controlled = isset($formatkeylookup['controlled']) && !empty($line[$formatkeylookup['controlled']]);
        $request = isset($formatkeylookup['request']) && !empty($line[$formatkeylookup['request']]);
162
        $submitpages = isset($formatkeylookup['submitpages']) && !empty($line[$formatkeylookup['submitpages']]);
163 164 165
        if (isset($formatkeylookup['editroles'])) {
            $editroles = $line[$formatkeylookup['editroles']];
        }
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180

        if (!preg_match('/^[a-zA-Z0-9_.-]{2,255}$/', $shortname)) {
            $csverrors->add($i, get_string('uploadgroupcsverrorinvalidshortname', 'admin', $i, $shortname));
        }

        if (isset($shortnames[$shortname])) {
            // Duplicate shortname within this file.
            $csverrors->add($i, get_string('uploadgroupcsverrorshortnamealreadytaken', 'admin', $i, $shortname));
        }
        else if (!$values['updategroups']) {
            // The groupname must be new
            if (record_exists('group', 'shortname', $shortname, 'institution', $institution)) {
                $csverrors->add($i, get_string('uploadgroupcsverrorshortnamealreadytaken', 'admin', $i, $shortname));
            }
        }
181 182 183 184 185 186
        else if ($values['updategroups']) {
            // The groupname needs to exist
            if (!record_exists('group', 'shortname', $shortname, 'institution', $institution)) {
                $csverrors->add($i, get_string('uploadgroupcsverrorshortnamemissing', 'admin', $i, $shortname));
            }
        }
187 188 189
        $shortnames[$shortname] = array(
                'shortname'   => $shortname,
                'displayname' => $displayname,
190
                'roles'       => $grouptype,
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
                'lineno'      => $i,
                'raw'         => $line,
        );

        if (isset($displaynames[strtolower($displayname)])) {
            // Duplicate displayname within this file
            $csverrors->add($i, get_string('uploadgroupcsverrorsgroupnamealreadyexists', 'admin', $i, $displayname));
        }
        else if (!$values['updategroups']) {
            // The displayname must be new
            if (get_records_sql_array('SELECT id FROM {group} WHERE LOWER(TRIM(name)) = ?', array(strtolower(trim($displayname))))) {
                $csverrors->add($i, get_string('uploadgroupcsverrorgroupnamealreadyexists', 'admin', $i, $displayname));
            }
        }
        else {
            // This displayname must be new if not our shortname/institution
            if (get_records_sql_array('
                    SELECT id FROM {group}
                    WHERE LOWER(TRIM(name)) = ?
                        AND NOT (shortname = ? AND institution = ?)',
                    array(
                        strtolower(trim($displayname)),
                        $shortname,
                        $institution
                    ))) {
                $csverrors->add($i, get_string('uploadgroupcsverrorgroupnamealreadyexists', 'admin', $i, $displayname));
            }
        }
        $displaynames[strtolower($displayname)] = 1;

221
        if (!isset($GROUPTYPES[$grouptype])) {
222 223 224
            $csverrors->add($i, get_string('uploadgroupcsverrorinvalidgrouptype', 'admin', $i, $grouptype));
        }

225 226 227 228
        if (isset($editroles) && !isset($EDITROLES[$editroles])) {
            $csverrors->add($i, get_string('uploadgroupcsverrorinvalideditroles', 'admin', $i, $editroles));
        }

229 230 231 232 233 234
        if ($open && $controlled) {
            $csverrors->add($i, get_string('uploadgroupcsverroropencontrolled', 'admin', $i));
        }
        if ($open && $request) {
            $csverrors->add($i, get_string('uploadgroupcsverroropenrequest', 'admin', $i));
        }
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278

        if ($values['updategroups']) {

            foreach ($shortnames as $shortname => $data) {

                // TODO: Any other checks we have to do for updated groups

                $UPDATES[$shortname] = 1;

            }

        }
    }

    if ($errors = $csverrors->process()) {
        $form->set_error('file', clean_html($errors));
        return;
    }

    $FORMAT = $csvdata->format;
    $CSVDATA = $csvdata->data;
}

/**
 * Add the users to the system. Make sure that they have to change their
 * password on next login also.
 */
function uploadcsv_submit(Pieform $form, $values) {
    global $SESSION, $CSVDATA, $FORMAT, $UPDATES, $USER;

    $formatkeylookup = array_flip($FORMAT);

    $institution = $values['institution'];

    if ($values['updategroups']) {
        log_info('Updating groups from the CSV file');
    }
    else {
        log_info('Inserting groups from the CSV file');
    }
    db_begin();

    $addedgroups = array();

279 280 281
    $key = 0;
    $num_lines = count($CSVDATA);

282 283
    foreach ($CSVDATA as $record) {

284 285 286 287 288
        if (!($key % 25)) {
            set_progress_info('uploadgroupscsv', $num_lines + $key * 9, $num_lines * 10, get_string('committingchanges', 'admin'));
        }
        $key++;

289 290 291 292
        $group = new StdClass;
        $group->name        = $record[$formatkeylookup['displayname']];
        $group->shortname   = $record[$formatkeylookup['shortname']];
        $group->institution = $institution;
293
        $group->grouptype   = $record[$formatkeylookup['roles']];
294 295

        foreach ($FORMAT as $field) {
296
            if ($field == 'displayname' || $field == 'shortname' || $field == 'roles') {
297 298
                continue;
            }
299 300 301 302
            if ($field == 'submitpages') {
                $group->submittableto = $record[$formatkeylookup[$field]];
                continue;
            }
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
            $group->{$field} = $record[$formatkeylookup[$field]];
        }

        if (!$values['updategroups'] || !isset($UPDATES[$group->shortname])) {
            $group->members = array($USER->id => 'admin');
            $group->id = group_create((array)$group);

            $addedgroups[] = $group;
            log_debug('added group ' . $group->name);
        }
        else if (isset($UPDATES[$group->shortname])) {
            $shortname = $group->shortname;
            $updates = group_update($group);

            if (empty($updates)) {
                unset($UPDATES[$shortname]);
            }
            else {
                if (isset($updates['name'])) {
                    $updates['displayname'] = $updates['name'];
                    unset($updates['name']);
                }
                $UPDATES[$shortname] = $updates;
                log_debug('updated group ' . $group->name . ' (' . implode(', ', array_keys((array)$updates)) . ')');
            }
        }

    }

    db_commit();

    $SESSION->add_ok_msg(get_string('csvfileprocessedsuccessfully', 'admin'));
    if ($UPDATES) {
        $updatemsg = smarty_core();
        $updatemsg->assign('added', count($addedgroups));
        $updatemsg->assign('updates', $UPDATES);
        $SESSION->add_info_msg($updatemsg->fetch('admin/groups/csvupdatemessage.tpl'), false);
    }
    else {
        $SESSION->add_ok_msg(get_string('numbernewgroupsadded', 'admin', count($addedgroups)));
    }
344 345 346

    set_progress_done('uploadgroupscsv');

347 348 349 350
    redirect('/admin/groups/uploadcsv.php');
}

$grouptypes = "<ul class=fieldslist>\n";
351 352
foreach (array_keys($GROUPTYPES) as $grouptype) {
    $grouptypes .= '<li>' . hsc($grouptype) . "</li>\n";
353 354 355
}
$grouptypes .= "<div class=cl></div></ul>\n";

356 357 358 359 360 361 362 363
$editroles = "<ul class=fieldslist>\n";
foreach (array_keys($EDITROLES) as $editrole) {
    $editroles .= '<li>' . hsc($editrole) . "</li>\n";
}
$editroles .= "<div class=cl></div></ul>\n";

$grouptypes .= get_string('uploadgroupcsveditrolesdescription', 'admin', get_help_icon('core', 'groups', 'editgroup', 'editroles'), $editroles);

364 365 366
$fields = "<ul class=fieldslist>\n";
foreach ($ALLOWEDKEYS as $type) {
    $helplink = '';
367 368
    if ($type == 'public' || $type == 'usersautoadded') {
        $helplink = get_help_icon('core', 'groups', 'editgroup', $type);
369 370 371 372
    }
    $fields .= '<li>' . hsc($type) . $helplink . "</li>\n";
}
$fields .= "<div class=cl></div></ul>\n";
373
$uploadcsvpagedescription = get_string('uploadgroupcsvpagedescription2', 'admin', get_help_icon('core', 'groups', 'editgroup', 'grouptype'), $grouptypes, $fields);
374 375 376

$form = pieform($form);

377 378
set_progress_done('uploadgroupscsv');

379 380 381 382 383
$smarty = smarty(array('adminuploadcsv'));
$smarty->assign('uploadcsvpagedescription', $uploadcsvpagedescription);
$smarty->assign('uploadcsvform', $form);
$smarty->assign('PAGEHEADING', TITLE);
$smarty->display('admin/groups/uploadcsv.tpl');