当前位置: 首页>>代码示例>>PHP>>正文


PHP csv_import_reader::next方法代码示例

本文整理汇总了PHP中csv_import_reader::next方法的典型用法代码示例。如果您正苦于以下问题:PHP csv_import_reader::next方法的具体用法?PHP csv_import_reader::next怎么用?PHP csv_import_reader::next使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在csv_import_reader的用法示例。


在下文中一共展示了csv_import_reader::next方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: next

 /**
  * Get the next row of data from the csv file (only the columns we care about)
  *
  * @return stdClass or false The stdClass is an object containing user, grade and lastmodified
  */
 public function next()
 {
     global $DB;
     $result = new stdClass();
     while ($record = $this->csvreader->next()) {
         $idstr = $record[$this->idindex];
         // Strip the integer from the end of the participant string.
         $id = substr($idstr, strlen(get_string('hiddenuser', 'assign')));
         if ($userid = $this->assignment->get_user_id_for_uniqueid($id)) {
             if (array_key_exists($userid, $this->validusers)) {
                 $result->grade = $record[$this->gradeindex];
                 $result->modified = strtotime($record[$this->modifiedindex]);
                 $result->user = $this->validusers[$userid];
                 $result->feedback = array();
                 foreach ($this->feedbackcolumnindexes as $description => $details) {
                     if (!empty($details['index'])) {
                         $details['value'] = $record[$details['index']];
                         $result->feedback[] = $details;
                     }
                 }
                 return $result;
             }
         }
     }
     // If we got here the csvreader had no more rows.
     return false;
 }
开发者ID:alanaipe2015,项目名称:moodle,代码行数:32,代码来源:importgradeslib.php

示例2: preview

 /**
  * Return a preview of the import.
  *
  * This only returns passed data, along with the errors.
  *
  * @param integer $rows number of rows to preview.
  * @param object $tracker the output tracker to use.
  * @return array of preview data.
  */
 public function preview($rows = 10, $tracker = null)
 {
     if ($this->processstarted) {
         throw new coding_exception('Process has already been started');
     }
     $this->processstarted = true;
     if (empty($tracker)) {
         $tracker = new tool_uploadcourse_tracker(tool_uploadcourse_tracker::NO_OUTPUT);
     }
     $tracker->start();
     // We might need extra time and memory depending on the number of rows to preview.
     core_php_time_limit::raise();
     raise_memory_limit(MEMORY_EXTRA);
     // Loop over the CSV lines.
     $preview = array();
     while (($line = $this->cir->next()) && $rows > $this->linenb) {
         $this->linenb++;
         $data = $this->parse_line($line);
         $course = $this->get_course($data);
         $result = $course->prepare();
         if (!$result) {
             $tracker->output($this->linenb, $result, $course->get_errors(), $data);
         } else {
             $tracker->output($this->linenb, $result, $course->get_statuses(), $data);
         }
         $row = $data;
         $preview[$this->linenb] = $row;
     }
     $tracker->finish();
     return $preview;
 }
开发者ID:evltuma,项目名称:moodle,代码行数:40,代码来源:processor.php

示例3: execute

 public function execute()
 {
     global $CFG, $DB;
     require_once $CFG->libdir . '/csvlib.class.php';
     require_once $CFG->libdir . '/moodlelib.php';
     $csvfilepath = $this->arguments[0];
     if ($csvfilepath[0] != '/') {
         $csvfilepath = $this->cwd . DIRECTORY_SEPARATOR . $csvfilepath;
     }
     $iid = \csv_import_reader::get_new_iid('userprofile');
     $type = 'userprofile';
     $csvreader = new \csv_import_reader($iid, $type);
     if (false === ($csvfile = file_get_contents($csvfilepath))) {
         cli_error('Unable to load csv file. ' . error_get_last()['message']);
     }
     if (!$csvreader->load_csv_content($csvfile, 'utf-8', 'comma')) {
         cli_error('Unalbe to parse csv file. ' . $csvreader->get_error());
     }
     if (!$csvreader->init()) {
         cli_error('Unable to initialise csv reading');
     }
     $columns = $csvreader->get_columns();
     $columnsids = array_flip($columns);
     while (false !== ($row = $csvreader->next())) {
         $category = $this->get_or_create_category($row[$columnsids['categoryname']], $row[$columnsids['categorysortorder']]);
         $userfield = new \stdClass();
         $userfield->shortname = $row[$columnsids['shortname']];
         $userfield->name = $row[$columnsids['name']];
         $userfield->datatype = $row[$columnsids['datatype']];
         $userfield->description = $row[$columnsids['description']];
         $userfield->descriptionformat = $row[$columnsids['descriptionformat']];
         $userfield->categoryid = $category->id;
         $userfield->sortorder = $row[$columnsids['sortorder']];
         $userfield->required = $row[$columnsids['required']];
         $userfield->locked = $row[$columnsids['locked']];
         $userfield->visible = $row[$columnsids['visible']];
         $userfield->forceunique = $row[$columnsids['forceunique']];
         $userfield->signup = $row[$columnsids['signup']];
         $userfield->defaultdata = $row[$columnsids['defaultdata']];
         $userfield->defaultdataformat = $row[$columnsids['defaultdataformat']];
         $userfield->param1 = $row[$columnsids['param1']];
         $userfield->param2 = $row[$columnsids['param2']];
         $userfield->param3 = $row[$columnsids['param3']];
         $userfield->param4 = $row[$columnsids['param4']];
         $userfield->param5 = $row[$columnsids['param5']];
         $this->get_or_create_userfield($userfield);
     }
 }
开发者ID:dariogs,项目名称:moosh,代码行数:48,代码来源:UserProfileFieldsImport.php

示例4: execute

 /**
  * Execute the process.
  *
  * @param object $tracker the output tracker to use.
  * @return void
  */
 public function execute($tracker = null)
 {
     global $DB;
     if ($this->processstarted) {
         throw new moodle_exception('process_already_started', 'error');
     }
     $this->processstarted = true;
     if (is_null($tracker)) {
         $tracker = new tool_uploadcoursecategory_tracker(tool_uploadcoursecategory_tracker::OUTPUT_PLAIN);
     }
     $tracker->start();
     // Statistics for tracker.
     $total = 0;
     $created = 0;
     $updated = 0;
     $deleted = 0;
     $errors = 0;
     core_php_time_limit::raise();
     raise_memory_limit(MEMORY_HUGE);
     // Loop over CSV lines.
     while ($line = $this->cir->next()) {
         $this->linenum++;
         $total++;
         $data = $this->parse_line($line);
         $category = $this->get_coursecategory($data);
         if ($category->prepare()) {
             $category->proceed();
             $status = $category->get_status();
             if (array_key_exists('coursecategoriescreated', $status)) {
                 $created++;
             } else {
                 if (array_key_exists('coursecategoryupdated', $status)) {
                     $updated++;
                 } else {
                     if (array_key_exists('coursecategorydeleted', $status)) {
                         $deleted++;
                     }
                 }
             }
             $data = array_merge($data, $category->get_finaldata(), array('id' => $category->get_id()));
             $tracker->output($this->linenum, true, $status, $data);
         } else {
             $errors++;
             $tracker->output($this->linenum, false, $category->get_errors(), $data);
         }
     }
     $tracker->results($total, $created, $updated, $deleted, $errors);
 }
开发者ID:alexandru-elisei,项目名称:moodle-tool_uploadcoursecategory,代码行数:54,代码来源:processor.php

示例5: load_csv_content

 /**
  * Load CSV content for previewing.
  *
  * @param string $text The grade data being imported.
  * @param string $encoding The type of encoding the file uses.
  * @param string $separator The separator being used to define each field.
  * @param int $previewrows How many rows are being previewed.
  */
 public function load_csv_content($text, $encoding, $separator, $previewrows)
 {
     $this->raise_limits();
     $this->iid = csv_import_reader::get_new_iid('grade');
     $csvimport = new csv_import_reader($this->iid, 'grade');
     $csvimport->load_csv_content($text, $encoding, $separator);
     $this->error = $csvimport->get_error();
     // Get header (field names).
     $this->headers = $csvimport->get_columns();
     $this->trim_headers();
     $csvimport->init();
     $this->previewdata = array();
     for ($numlines = 0; $numlines <= $previewrows; $numlines++) {
         $lines = $csvimport->next();
         if ($lines) {
             $this->previewdata[] = $lines;
         }
     }
 }
开发者ID:jtibbetts,项目名称:moodle,代码行数:27,代码来源:load_data.php

示例6: validation

 function validation($data, $files)
 {
     global $CFG;
     $errors = array();
     // Use csv importer from Moodle
     $iid = csv_import_reader::get_new_iid('emarking-predefined-comments');
     $reader = new csv_import_reader($iid, 'emarking-predefined-comments');
     $content = $data['comments'];
     $reader->load_csv_content($content, 'utf8', "tab");
     // Validate columns, minimum number and first two to be userid and attemptid
     if (count($reader->get_columns()) < 0) {
         $errors['comments'] = get_string('onecolumnrequired', 'mod_emarking');
     }
     $reader->init();
     $current = 0;
     while ($line = $reader->next()) {
         $current++;
     }
     if ($current < 1) {
         $errors['comments'] = get_string('twolinesrequired', 'mod_emarking');
     }
     return $errors;
 }
开发者ID:eduagdo,项目名称:emarking,代码行数:23,代码来源:predefined_comments_form.php

示例7: bulk_costcenter_enroll

/**
 * process the mass enrolment
 * @param csv_import_reader $cir  an import reader created by caller
 * @param Object $course  a course record from table mdl_course
 * @param Object $context  course context instance
 * @param Object $data    data from a moodleform 
 * @return string  log of operations 
 */
function bulk_costcenter_enroll($cir,   $data) {
    global $CFG,$DB,$USER;
    require_once ($CFG->dirroot . '/group/lib.php');

    $result = '';
    
    $roleid = $data->roleassign;
    $useridfield = $data->firstcolumn;

    $enrollablecount = 0;
    $createdgroupscount = 0;
    $createdgroupingscount = 0;
    $createdgroups = '';
    $createdgroupings = '';
    
    $plugin = enrol_get_plugin('manual');
    // init csv import helper
    $cir->init();
    while ($fields = $cir->next()) {
        $a = new StdClass();
        if (empty ($fields))
            continue;
        
        // 1rst column = id Moodle (idnumber,username or email)    
        // get rid on eventual double quotes unfortunately not done by Moodle CSV importer 
            //$fields[0]= str_replace('"', '', trim($fields[0]));
            //$fields[1]= str_replace('"', '', trim($fields[1]));
        if (!$costcenter = $DB->get_record_sql('select * from {local_costcenter} where shortname="'.$fields[1].'"')) {
            $result .= '<div class="alert alert-error">'.get_string('im:costcenter_unknown', 'local_users', $fields[0] ). '</div>';
            continue;
        }
        if (!$user = $DB->get_record_sql('select * from {user} where '.$useridfield.' = "'.$fields[0].'"')) {
            $result .= '<div class="alert alert-error">'.get_string('im:user_unknown', 'local_users', $fields[1] ). '</div>';
            continue;
        }

        if(!is_siteadmin() && !$DB->record_exists_sql("select id from {local_costcenter_permissions} where costcenterid=$costcenter->id AND userid=$USER->id")){
            $costcentername = $DB->get_field('local_costcenter','fullname',array('id'=>$costcenter->id));
            $cs_object = new stdClass();
            $cs_object->csname = $costcentername;
            $cs_object->user   = fullname($user);
            $result .= '<div class="alert alert-error">'.get_string('im:user_notcostcenter', 'local_userdata',$cs_object ). '</div>';
            continue; 
        }
        //already enroled ?
        if ($DB->record_exists_sql('select * from {local_userdata} where userid='.$user->id.' and costcenterid>0')) {
            $result .= '<div class="alert alert-error">'.get_string('im:already_in', 'local_users', fullname($user)). '</div>';
        } else {
        $userdata = new stdClass();
        $userdata->userid = $user->id;
        $userdata->costcenterid = $costcenter->id;
        $userdata->supervisorid = 0;
        $userdata->reportingmanagerid = 0;
        $userdata->usermodified = $USER->id;
        $userdata->timecreated = time();
        $userdata->timemodified = time();
        $DB->insert_record('local_userdata',$userdata);     
                $result .= '<div class="alert alert-success">'.get_string('im:assigned_ok', 'local_userdata', fullname($user)).'</div>';
            $enrollablecount++;
        }
    }
    $result .= '<br />';

    //$result .= get_string('im:stats_i', 'local_userdata', $enrollablecount) . "";
 
    return $result;
}
开发者ID:narasimhaeabyas,项目名称:tataaiapro,代码行数:75,代码来源:bulk_assignlib.php

示例8: array

     print_error('cannotreadtmpfile', 'error');
 }
 // check the fieldnames are valid
 $fields = $DB->get_records('data_fields', array('dataid' => $data->id), '', 'name, id, type');
 $errorfield = '';
 foreach ($fieldnames as $name) {
     if (!isset($fields[$name])) {
         $errorfield .= "'{$name}' ";
     }
 }
 if (!empty($errorfield)) {
     print_error('fieldnotmatched', 'data', "{$CFG->wwwroot}/mod/data/edit.php?d={$data->id}", $errorfield);
 }
 $cir->init();
 $recordsadded = 0;
 while ($record = $cir->next()) {
     if ($recordid = data_add_record($data, 0)) {
         // add instance to data_record
         $fields = $DB->get_records('data_fields', array('dataid' => $data->id), '', 'name, id, type');
         // Insert new data_content fields with NULL contents:
         foreach ($fields as $field) {
             $content = new stdClass();
             $content->recordid = $recordid;
             $content->fieldid = $field->id;
             $DB->insert_record('data_content', $content);
         }
         // Fill data_content with the values imported from the CSV file:
         foreach ($record as $key => $value) {
             $name = $fieldnames[$key];
             $field = $fields[$name];
             $content = new stdClass();
开发者ID:vuchannguyen,项目名称:web,代码行数:31,代码来源:import.php

示例9: mass_enroll

/**
 * process the mass enrolment
 * @param csv_import_reader $cir  an import reader created by caller
 * @param Object $course  a course record from table mdl_course
 * @param Object $context  course context instance
 * @param Object $data    data from a moodleform 
 * @return string  log of operations 
 */
function mass_enroll($cir, $course, $context, $data) {
    global $CFG,$DB;
    require_once ($CFG->dirroot . '/group/lib.php');

    $result = '';
    
    $courseid=$course->id;
    $roleid = $data->roleassign;
    $useridfield = $data->firstcolumn;

    $enrollablecount = 0;
    $createdgroupscount = 0;
    $createdgroupingscount = 0;
    $createdgroups = '';
    $createdgroupings = '';


    $plugin = enrol_get_plugin('manual');
    //Moodle 2.x enrolment and role assignment are different
    // make sure couse DO have a manual enrolment plugin instance in that course
    //that we are going to use (only one instance is allowed @see enrol/manual/lib.php get_new_instance)
    // thus call to get_record is safe 
    $instance = $DB->get_record('enrol', array('courseid' => $course->id, 'enrol' => 'manual'));
    if (empty($instance)) {
        // Only add an enrol instance to the course if non-existent
        $enrolid = $plugin->add_instance($course);
        $instance = $DB->get_record('enrol', array('id' => $enrolid));
    }
    
   
    // init csv import helper
    $cir->init();
    while ($fields = $cir->next()) {
        $a = new StdClass();

        if (empty ($fields))
            continue;

        // print_r($fields);
        // $enrollablecount++;
        // continue;
        
        // 1rst column = id Moodle (idnumber,username or email)    
        // get rid on eventual double quotes unfortunately not done by Moodle CSV importer 
            $fields[0]= str_replace('"', '', trim($fields[0]));
        
        if (!$user = $DB->get_record('user', array($useridfield => $fields[0]))) {
            $result .= '<div class="alert alert-error">'.get_string('im:user_unknown', 'local_mass_enroll', $fields[0] ). '</div>';
            continue;
        }
        if(!$DB->record_exists_sql("select id from {local_userdata} where costcenterid=$course->costcenter AND userid=$user->id")){
            $costcentername = $DB->get_field('local_costcenter','fullname',array('id'=>$course->costcenter));
            $cs_object = new stdClass();
            $cs_object->csname = $costcentername;
            $cs_object->user   = fullname($user);
            $result .= '<div class="alert alert-error">'.get_string('im:user_notcostcenter', 'local_mass_enroll',$cs_object ). '</div>';
            continue; 
        }
        //already enroled ?
        if (user_has_role_assignment($user->id, $roleid, $context->id)) {
            $result .= '<div class="alert alert-error">'.get_string('im:already_in', 'local_mass_enroll', fullname($user)). '</div>';

        } else {
            //TODO take care of timestart/timeend in course settings
            // done in rev 1.1
            $timestart = time();
            // remove time part from the timestamp and keep only the date part
            $timestart = make_timestamp(date('Y', $timestart), date('m', $timestart), date('d', $timestart), 0, 0, 0);
            if ($instance->enrolperiod) {
                $timeend = $timestart + $instance->enrolperiod;
            } else {
                $timeend = 0;
            }
            // not anymore so easy in Moodle 2.x
            // if (!role_assign($roleid, $user->id, null, $context->id, $timestart, $timeend, 0, 'flatfile')) {
            //    $result .= get_string('im:error_in', 'local_mass_enroll', fullname($user)) . "";
            //    continue;
            //}
            //
            // Enrol the user with this plugin instance (unfortunately return void, no more status )
            $plugin->enrol_user($instance, $user->id,$roleid,$timestart,$timeend);
            $result .= '<div class="alert alert-success">'.get_string('im:enrolled_ok', 'local_mass_enroll', fullname($user)).'</div>';
            $enrollablecount++;
        }

        $group = str_replace('"','',trim($fields[1]));
        // 2nd column ?
        if (empty ($group)) {
            $result .= "";
            continue; // no group for this one
        }

//.........这里部分代码省略.........
开发者ID:narasimhaeabyas,项目名称:tataaiapro,代码行数:101,代码来源:lib.php

示例10: unset

     }
 }
 unset($allowedroles);
 // clear bulk selection
 if ($bulk) {
     $SESSION->bulk_users = array();
 }
 // init csv import helper
 $cir->init();
 $linenum = 1;
 //column header is first line
 // init upload progress tracker
 $upt = new uu_progress_tracker();
 $upt->init();
 // start table
 while ($line = $cir->next()) {
     $upt->flush();
     $linenum++;
     $upt->track('line', $linenum);
     $user = new object();
     // by default, use the local mnet id (this may be changed in the file)
     $user->mnethostid = $CFG->mnet_localhost_id;
     // add fields to user object
     foreach ($line as $key => $value) {
         if ($value !== '') {
             $key = $columns[$key];
             // password is special field
             if ($key == 'password') {
                 if ($value !== '') {
                     $user->password = hash_internal_user_password($value);
                     if (!empty($CFG->passwordpolicy) and !check_password_policy($value, $errmsg)) {
开发者ID:ajv,项目名称:Offline-Caching,代码行数:31,代码来源:uploaduser.php

示例11: test_csv_functions

 public function test_csv_functions()
 {
     global $CFG;
     $csvexport = new csv_export_writer();
     $csvexport->set_filename('unittest');
     foreach ($this->testdata as $data) {
         $csvexport->add_data($data);
     }
     $csvoutput = $csvexport->print_csv_data(true);
     $this->assertEquals($csvoutput, $this->teststring);
     $test_data = csv_export_writer::print_array($this->testdata, 'comma', '"', true);
     $this->assertEquals($test_data, $this->teststring);
     // Testing that the content is imported correctly.
     $iid = csv_import_reader::get_new_iid('lib');
     $csvimport = new csv_import_reader($iid, 'lib');
     $contentcount = $csvimport->load_csv_content($this->teststring, 'utf-8', 'comma');
     $csvimport->init();
     $dataset = array();
     $dataset[] = $csvimport->get_columns();
     while ($record = $csvimport->next()) {
         $dataset[] = $record;
     }
     $csvimport->cleanup();
     $csvimport->close();
     $this->assertEquals($dataset, $this->testdata);
     // Testing for the wrong count of columns.
     $errortext = get_string('csvweirdcolumns', 'error');
     $iid = csv_import_reader::get_new_iid('lib');
     $csvimport = new csv_import_reader($iid, 'lib');
     $contentcount = $csvimport->load_csv_content($this->teststring2, 'utf-8', 'comma');
     $importerror = $csvimport->get_error();
     $csvimport->cleanup();
     $csvimport->close();
     $this->assertEquals($importerror, $errortext);
     // Testing for empty content
     $errortext = get_string('csvemptyfile', 'error');
     $iid = csv_import_reader::get_new_iid('lib');
     $csvimport = new csv_import_reader($iid, 'lib');
     $contentcount = $csvimport->load_csv_content($this->teststring3, 'utf-8', 'comma');
     $importerror = $csvimport->get_error();
     $csvimport->cleanup();
     $csvimport->close();
     $this->assertEquals($importerror, $errortext);
     // Testing for a tab separated file.
     // The tab separated file has a trailing tab and extra blank lines at the end of the file.
     $filename = $CFG->dirroot . '/lib/tests/fixtures/tabfile.csv';
     $fp = fopen($filename, 'r');
     $tabdata = fread($fp, filesize($filename));
     fclose($fp);
     $iid = csv_import_reader::get_new_iid('tab');
     $csvimport = new csv_import_reader($iid, 'tab');
     $contentcount = $csvimport->load_csv_content($tabdata, 'utf-8', 'tab');
     // This should import four rows including the headings.
     $this->assertEquals($contentcount, 4);
     // Testing for empty lines.
     $iid = csv_import_reader::get_new_iid('blanklines');
     $csvimport = new csv_import_reader($iid, 'blanklines');
     $contentcount = $csvimport->load_csv_content($this->teststring4, 'utf-8', 'comma');
     // Five lines including the headings should be imported.
     $this->assertEquals($contentcount, 5);
 }
开发者ID:masaterutakeno,项目名称:MoodleMobile,代码行数:61,代码来源:csvclass_test.php

示例12: mass_unenroll

/**
 * process the mass enrolment
 * @param csv_import_reader $cir  an import reader created by caller
 * @param Object $course  a course record from table mdl_course
 * @param Object $context  course context instance
 * @param Object $data    data from a moodleform 
 * @return string  log of operations 
 */
function mass_unenroll($cir, $course, $context, $data)
{
    global $CFG, $DB;
    $result = '';
    $courseid = $course->id;
    $useridfield = $data->firstcolumn;
    $unenrollablecount = 0;
    $plugin = enrol_get_plugin('manual');
    //Moodle 2.x enrolment and role assignment are different
    // make sure couse DO have a manual enrolment plugin instance in that course
    //that we are going to use (only one instance is allowed @see enrol/manual/lib.php get_new_instance)
    // thus call to get_record is safe
    $instance = $DB->get_record('enrol', array('courseid' => $course->id, 'enrol' => 'manual'));
    if (empty($instance)) {
        // Only add an enrol instance to the course if non-existent
        $enrolid = $plugin->add_instance($course);
        $instance = $DB->get_record('enrol', array('id' => $enrolid));
    }
    // init csv import helper
    $cir->init();
    while ($fields = $cir->next()) {
        $a = new StdClass();
        if (empty($fields)) {
            continue;
        }
        // 1rst column = id Moodle (idnumber,username or email)
        // get rid on eventual double quotes unfortunately not done by Moodle CSV importer
        $fields[0] = str_replace('"', '', trim($fields[0]));
        if (!($user = $DB->get_record('user', array($useridfield => $fields[0])))) {
            $result .= get_string('im:user_unknown', 'local_mass_enroll', $fields[0]) . "\n";
            continue;
        }
        //already enroled ?
        if (!($ue = $DB->get_record('user_enrolments', array('enrolid' => $instance->id, 'userid' => $user->id)))) {
            // weird, user not enrolled
            $result .= get_string('im:not_in', 'local_mass_enroll', fullname($user)) . "\n";
        } else {
            // Enrol the user with this plugin instance (unfortunately return void, no more status )
            $plugin->unenrol_user($instance, $user->id);
            $result .= get_string('im:unenrolled_ok', 'local_mass_enroll', fullname($user)) . "\n";
            $unenrollablecount++;
        }
    }
    //recap final
    $result .= get_string('im:stats_ui', 'local_mass_enroll', $unenrollablecount) . "\n";
    return $result;
}
开发者ID:nadavkav,项目名称:moodle_local_mass_enroll,代码行数:55,代码来源:lib.php

示例13: process_csv

 /**
  * @param array  $options associative delimiter,enclosure,encoding,updateexisting,settings
  */
 public function process_csv($data, $csvcontent, $options = null)
 {
     global $CFG, $DB;
     require_once "{$CFG->libdir}/csvlib.class.php";
     @set_time_limit(0);
     raise_memory_limit(MEMORY_EXTRA);
     $iid = \csv_import_reader::get_new_iid('moddataform');
     $cir = new \csv_import_reader($iid, 'moddataform');
     $delimiter = !empty($options['delimiter']) ? $options['delimiter'] : $this->_delimiter;
     $enclosure = !empty($options['enclosure']) ? $options['enclosure'] : $this->_enclosure;
     $encoding = !empty($options['encoding']) ? $options['encoding'] : $this->_encoding;
     $fieldsettings = !empty($options['settings']) ? $options['settings'] : array();
     $readcount = $cir->load_csv_content($csvcontent, $encoding, $delimiter);
     if (empty($readcount)) {
         $data->errors[] = $cir->get_error();
         return $data;
     }
     // Csv column headers.
     if (!($fieldnames = $cir->get_columns())) {
         $data->errors[] = $cir->get_error();
         return $data;
     }
     // Are we updating existing entries?
     $existingkeys = array();
     $keyname = null;
     if ($updateexisting = !empty($options['updateexisting'])) {
         if (isset($fieldnames['entryid'])) {
             $keyname = 'entryid';
         } else {
             $keyname = reset($fieldnames);
             if ($field = $this->df->field_manager->get_field_by_name($keyname)) {
                 $params = array('fieldid' => $field->id);
                 $existingkeys = $DB->get_records_menu('dataform_contents', $params, '', 'entryid,content');
             }
         }
     }
     // Are we adding the imported entries to every participant?
     $addperparticipant = (!empty($options['addperparticipant']) and $users = $this->df->grade_manager->get_gradebook_users());
     $i = 0;
     $cir->init();
     while ($csvrecord = $cir->next()) {
         $csvrecord = array_combine($fieldnames, $csvrecord);
         // Add the entry for every participant.
         if ($addperparticipant) {
             foreach ($users as $userid => $unused) {
                 // Set the entry id.
                 $i++;
                 $entryid = -$i;
                 $data->eids[$entryid] = $entryid;
                 $data->{"entry_{$entryid}_userid"} = $userid;
                 // Iterate the fields and collate their entry content.
                 foreach ($fieldsettings as $fieldid => $importsettings) {
                     $field = $this->df->field_manager->get_field_by_id($fieldid);
                     $data = $field->prepare_import_content($data, $importsettings, $csvrecord, $entryid);
                 }
             }
             continue;
         }
         // Get the entry id.
         $entryid = 0;
         if ($updateexisting and $keyname) {
             if ($keyname == 'entryid') {
                 if (!empty($csvrecord['entryid'])) {
                     $entryid = $csvrecord['entryid'];
                 }
             } else {
                 if ($existingkeys and !empty($csvrecord[$keyname])) {
                     $entryid = array_search($csvrecord[$keyname], $existingkeys);
                 }
             }
         }
         if (!$entryid) {
             $i++;
             $entryid = -$i;
         }
         $data->eids[$entryid] = $entryid;
         // Iterate the fields and collate their entry content.
         foreach ($fieldsettings as $fieldid => $importsettings) {
             $field = $this->df->field_manager->get_field_by_id($fieldid);
             $data = $field->prepare_import_content($data, $importsettings, $csvrecord, $entryid);
         }
     }
     $cir->cleanup(true);
     $cir->close();
     return $data;
 }
开发者ID:vaenda,项目名称:moodle-mod_dataform,代码行数:89,代码来源:csv.php

示例14: bulk_enroll

/**
 * process the mass enrolment
 * @param csv_import_reader $cir  an import reader created by caller
 * @param Object $course  a course record from table mdl_course
 * @param Object $context  course context instance
 * @param Object $data    data from a moodleform 
 * @return string  log of operations 
 */
function bulk_enroll($cir,   $data) {
    global $CFG,$DB,$USER;
    require_once ($CFG->dirroot . '/group/lib.php');

    $result = '';
    
    $roleid = $data->roleassign;
    $useridfield = $data->firstcolumn;

    $enrollablecount = 0;
    $createdgroupscount = 0;
    $createdgroupingscount = 0;
    $createdgroups = '';
    $createdgroupings = '';
    
    $plugin = enrol_get_plugin('manual');
    
    // init csv import helper
    $cir->init();
    while ($fields = $cir->next()) {
        $a = new StdClass();
        if (empty ($fields))
            continue;
        
        // 1rst column = id Moodle (idnumber,username or email)    
        // get rid on eventual double quotes unfortunately not done by Moodle CSV importer 
            $fields[0]= str_replace('"', '', trim($fields[0]));
           $fields[1]= str_replace('"', '', trim($fields[1]));
        if (!$lplan = $DB->get_record('learning_learningplan', array('shortname' => $fields[0]))) {
            $result .= '<div class="alert alert-error">'.get_string('im:learningplan_unknown', 'block_learning_plan', $fields[1] ). '</div>';
            continue;
        }
        
        if (!$user = $DB->get_record('user', array($useridfield => $fields[1]))) {
            $result .= '<div class="alert alert-error">'.get_string('im:user_unknown', 'block_learning_plan', $fields[1] ). '</div>';
            continue;
        }
        if(!$DB->record_exists_sql("select id from {local_userdata} where costcenterid=$lplan->costcenter AND userid=$user->id")){
          echo  $costcentername = $DB->get_field('local_costcenter','fullname',array('id'=>$lplan->costcenter));
            $cs_object = new stdClass();
            $cs_object->csname = $costcentername;
            $cs_object->user   = fullname($user);
            $result .= '<div class="alert alert-error">'.get_string('im:user_notcostcenter', 'local_mass_enroll',$cs_object ). '</div>';
            continue; 
        }
        //already enroled ?
        if ($DB->record_exists('learning_user_learningplan',array('u_id'=>$user->id, 'lp_id'=>$lplan->id))) {
            $result .= '<div class="alert alert-error">'.get_string('im:already_in', 'local_mass_enroll', fullname($user)). '</div>';

        } else {
                $record = new stdClass();
                $record2 = new stdClass();
                $record->lp_id = $lplan->id;
                $record->assignee_id = $USER->id;
                    $record->u_id = $user->id;
                    $training = learningplan_training($lplan->id);
					if(!empty($training)){
                    foreach ($training as $train) {
                        $studentroleid = $DB->get_field('role', 'id', array('shortname' => 'student'), MUST_EXIST);
                        $manualenrol = enrol_get_plugin('manual');
                        $enrol = $DB->get_record('enrol', array('courseid'=>$train->t_id, 'enrol'=>'manual'));
                        $manualenrol->enrol_user($enrol, $user->id,$studentroleid,$lplan->startdate,$lplan->enddate);
                        $record2->lpt_id = $train->id;
                        $record2->u_id = $user->id;
						$record2->timemodified = time();
                        // Insert in learning_user_trainingplan
                        $DB->insert_record('learning_user_trainingplan', $record2);
                    }
					}
                    $record->timemodified = time();
                    // Insert in learning_user_learningplan
                    if(!$DB->record_exists('learning_user_learningplan',array('lp_id'=>$lplan->id,'u_id'=>$user->id)))
                    $DB->insert_record('learning_user_learningplan', $record);
                $result .= '<div class="alert alert-success">'.get_string('im:enrolled_ok', 'local_mass_enroll', fullname($user)).'</div>';
            $enrollablecount++;
        }
    }
    $result .= '<br />';

    $result .= get_string('im:stats_i', 'local_mass_enroll', $enrollablecount) . "";
 
    return $result;
}
开发者ID:narasimhaeabyas,项目名称:tataaiapro,代码行数:91,代码来源:bulk_enrollib.php

示例15: process_uploaded_groups

 /**
  * enrol and add user to groups in course
  * @param object $course
  * @param csv_import_reader $reader
  * @param int $roleid
  */
 public function process_uploaded_groups($course, $reader, $roleid)
 {
     global $DB, $PAGE;
     $usercol = null;
     // Index of username column.
     $groupcol = null;
     // Index of group column.
     // Find the index of the needed columns.
     $i = 0;
     foreach ($reader->get_columns() as $col) {
         $col = strtoupper(trim($col));
         switch ($col) {
             case 'USERNAME':
                 $usercol = $i;
                 break;
             case 'GROUP':
                 $groupcol = $i;
                 break;
         }
         $i++;
     }
     // Get the manual enrolment plugin.
     $enrolinstances = enrol_get_instances($course->id, true);
     $manualinstance = null;
     foreach ($enrolinstances as $instance) {
         if ($instance->enrol == 'manual') {
             $manualinstance = $instance;
             break;
         }
     }
     $manualenroler = enrol_get_plugin('manual');
     // Get the list of enrolled users for the course.
     $manager = new course_enrolment_manager($PAGE, $course);
     $totalusers = $manager->get_total_users();
     /*
      * Since the number of fields being retrieved are limited (email, id, lastaccess, and lastseen),
      * I feel comfortable retrieving the entire enrolled userbase for this course.
      */
     $users = $manager->get_users('firstname', 'ASC', 0, $totalusers);
     $groups = $manager->get_all_groups();
     $groupids = array();
     foreach ($groups as $group) {
         $groupids[$group->name] = $group->id;
     }
     // Prep the returned array.
     $output = array('group_created' => array(), 'user_enrolled' => array(), 'member_added' => array(), 'error' => array('user_not_found' => array(), 'group_failed' => array(), 'enrol_failed' => array(), 'member_failed' => array(), 'user_not_added' => array()));
     // Loop through the records.
     $reader->init();
     while ($line = $reader->next()) {
         $username = trim($line[$usercol]);
         $groupname = trim($line[$groupcol]);
         // Check if the user exists.
         $user = $DB->get_record('user', array('username' => $username));
         if ($user === false) {
             $output['error']['user_not_found'][] = $username;
             continue;
         }
         // Enroll the user as needed.
         if (!isset($users[$user->id])) {
             try {
                 $manualenroler->enrol_user($manualinstance, $user->id, $roleid);
                 $output['user_enrolled'][] = $username;
             } catch (Exception $e) {
                 $output['error']['enroll_failed'][] = $username;
             }
         }
         // Create the group as needed.
         if (!isset($groupids[$groupname])) {
             if ($groupname != '') {
                 $data = new stdClass();
                 $data->courseid = $course->id;
                 $data->name = $groupname;
                 $newgroupid = groups_create_group($data);
             } else {
                 $newgroupid = false;
             }
             if ($newgroupid === false) {
                 if ($groupname != '') {
                     $output['error']['group_failed'][] = $groupname;
                 }
             } else {
                 $groupids[$groupname] = $newgroupid;
                 $output['group_created'][] = $groupname;
             }
         }
         // Add the user to the group.
         if ($groupname != '') {
             if (groups_add_member($groupids[$groupname], $user->id)) {
                 if (!isset($output['member_added'][$groupname])) {
                     $output['member_added'][$groupname] = array();
                 }
                 $output['member_added'][$groupname][] = $username;
             } else {
                 if (!isset($output['error']['member_failed'][$groupname])) {
//.........这里部分代码省略.........
开发者ID:at-tools,项目名称:moodle-block_uploadgroups,代码行数:101,代码来源:lib.php


注:本文中的csv_import_reader::next方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。