File: import.php

package info (click to toggle)
moodle 1.6.3-2%2Betch3
  • links: PTS
  • area: main
  • in suites: etch
  • size: 37,172 kB
  • ctags: 51,688
  • sloc: php: 231,916; sql: 5,631; xml: 2,688; sh: 1,185; perl: 638; makefile: 48; pascal: 36
file content (212 lines) | stat: -rwxr-xr-x 8,367 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
<?php  // $Id: import.php,v 1.4.2.2 2006/08/14 09:01:31 moodler Exp $
///////////////////////////////////////////////////////////////////////////
//                                                                       //
// NOTICE OF COPYRIGHT                                                   //
//                                                                       //
// Moodle - Modular Object-Oriented Dynamic Learning Environment         //
//          http://moodle.org                                            //
//                                                                       //
// Copyright (C) 2005 Martin Dougiamas  http://dougiamas.com             //
//                                                                       //
// This program is free software; you can redistribute it and/or modify  //
// it under the terms of the GNU General Public License as published by  //
// the Free Software Foundation; either version 2 of the License, or     //
// (at your option) any later version.                                   //
//                                                                       //
// This program is distributed in the hope that it will be useful,       //
// but WITHOUT ANY WARRANTY; without even the implied warranty of        //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         //
// GNU General Public License for more details:                          //
//                                                                       //
//          http://www.gnu.org/copyleft/gpl.html                         //
//                                                                       //
///////////////////////////////////////////////////////////////////////////

    require_once('../../config.php');
    require_once('lib.php');
    require_once($CFG->libdir.'/uploadlib.php');

    require_login();

    $id              = optional_param('id', 0, PARAM_INT);  // course module id
    $d               = optional_param('d', 0, PARAM_INT);   // database id
    $rid             = optional_param('rid', 0, PARAM_INT); // record id
    $fielddelimiter  = optional_param('fielddelimiter', ',', PARAM_CLEANHTML); // characters used as field delimiters for csv file import
    $fieldenclosure = optional_param('fieldenclosure', '', PARAM_CLEANHTML);   // characters used as record delimiters for csv file import
        
    if ($id) {
        if (! $cm = get_coursemodule_from_id('data', $id)) {
            error('Course Module ID was incorrect');
        }
        if (! $course = get_record('course', 'id', $cm->course)) {
            error('Course is misconfigured');
        }
        if (! $data = get_record('data', 'id', $cm->instance)) {
            error('Course module is incorrect');
        }

    } else {
        if (! $data = get_record('data', 'id', $d)) {
            error('Data ID is incorrect');
        }
        if (! $course = get_record('course', 'id', $data->course)) {
            error('Course is misconfigured');
        }
        if (! $cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
            error('Course Module ID was incorrect');
        }
    }
    
    if (isteacher($course->id)) {
        if (!count_records('data_fields','dataid',$data->id)) {      // Brand new database!
            redirect($CFG->wwwroot.'/mod/data/field.php?d='.$data->id);  // Redirect to field entry
        }
    }

    ///checking for participants
    if ((!isteacher($course->id)) && $data->participants == DATA_TEACHERS_ONLY) {
        error ('students are not allowed to participate in this activity');
    }

    if ($rid){    //editting a record, do you have access to edit this?
        if (!isteacher($course->id) or !data_isowner($rid) or !confirm_sesskey()){
            error (get_string('noaccess','data'));
        }
    }
  

/// Print the page header
    $strdata = get_string('modulenameplural','data');
    print_header_simple($data->name, "", "<a href='index.php?id=$course->id'>$strdata</a> -> $data->name", "", "", true, "", navmenu($course));
    print_heading(format_string($data->name));

/// Print the tabs
    $currenttab = 'add';
    include('tabs.php');
    
    
    $um = new upload_manager('recordsfile', false, false, null, false, 0);
    
    if ($um->preprocess_files() && confirm_sesskey()) {
        $filename = $um->files['recordsfile']['tmp_name'];
        
        // Large files are likely to take their time and memory. Let PHP know
        // that we'll take longer, and that the process should be recycled soon
        // to free up memory.
        @set_time_limit(0);
        @raise_memory_limit("64M");
        if (function_exists('apache_child_terminate')) {
            @apache_child_terminate();
        }
        
        //Fix mac/dos newlines
        $text = my_file_get_contents($filename);
        $text = preg_replace('!\r\n?!',"\n",$text);
        $fp = fopen($filename, "w");
        fwrite($fp, $text);
        fclose($fp);
        
        $recordsadded = 0;
        
        if (!$records = data_get_records_csv($filename, $fielddelimiter, $fieldenclosure)) {
            error('get_records_csv failed to read data from the uploaded file. Please check file for field name typos and formatting errors.');
        } else {
            //$db->debug = true;
            $fieldnames = array_shift($records);
            
            foreach ($records as $record) {
                if ($recordid = data_add_record($data, 0)) {  // add instance to data_record
                    $fields = get_records('data_fields', 'dataid', $data->id, '', 'name, id, type');
                    
                    // do a manual round of inserting, to make sure even empty contents get stored
                    foreach ($fields as $field) {
                        $content->recordid = $recordid;
                        $content->fieldid = $field->id;
                        insert_record('data_content', $content);
                    }
                    // for each field in the add form, add it to the data_content.
                    foreach ($record as $key => $value) {
                        $name = $fieldnames[$key];
                        $field = $fields[$name];
                        require_once($CFG->dirroot.'/mod/data/field/'.$field->type.'/field.class.php');
                        $newfield = 'data_field_'.$field->type;
                        $currentfield = new $newfield($field->id);

                        $currentfield->update_content($recordid, $value, $name);
                    }
                    $recordsadded++;
                }
            } // End foreach
        } // End else
    }//sun without love motivo atillas

    if ($recordsadded > 0) {
        notify($recordsadded. ' '. get_string('recordssaved', 'data'));
    } else {
        notify(get_string('recordsnotsaved', 'data'));
    }
    echo '<p />';


/// Finish the page
    print_footer($course);




function my_file_get_contents($filename, $use_include_path = 0) {
/// Returns the file as one big long string

    $data = "";
    $file = @fopen($filename, "rb", $use_include_path);
    if ($file) {
        while (!feof($file)) {
            $data .= fread($file, 1024);
        }
        fclose($file);
    }
    return $data;
}



// Read the records from the given file.
// Perform a simple field count check for each record.
function data_get_records_csv($filename, $fielddelimiter=',', $fieldenclosure="\n") {
    global $db;
    
    if (empty($fielddelimiter)) {
        $fielddelimiter = ',';
    }
    if (empty($fieldenclosure)) {
        $fieldenclosure = "\n";
    }
    
    if (!$fp = fopen($filename, "r")) {
        error('get_records_csv failed to open '.$filename);
    }
    $fieldnames = array();
    $rows = array();

    $fieldnames = fgetcsv($fp, 4096, $fielddelimiter, $fieldenclosure);
    
    if (empty($fieldnames)) {
        fclose($fp);
        return false;
    }
    $rows[] = $fieldnames;
    
    while (($data = fgetcsv($fp, 4096, $fielddelimiter, $fieldenclosure)) !== false) {
        if (count($data) > count($fieldnames)) {
            // For any given record, we can't have more data entities than the number of fields.
            fclose($fp);
            return false;
        }
        $rows[] = $data;
    }
    
    fclose($fp);
    return $rows;
}

?>