acced0f97bf0b3883692c6adae8495b2db1b2347
[moodle.git] / mod / glossary / import.php
1 <?php
3 require_once("../../config.php");
4 require_once("lib.php");
5 require_once("$CFG->dirroot/course/lib.php");
7 $id = required_param('id', PARAM_INT);    // Course Module ID
9 $step     = optional_param('step', 0, PARAM_INT);
10 $dest     = optional_param('dest', 'current', PARAM_ALPHA);   // current | new
11 $file     = optional_param('file', '', PARAM_FILE);         // file to import
12 $catsincl = optional_param('catsincl', 0, PARAM_INT);         // Import Categories too?
14 $mode     = optional_param('mode', 'letter', PARAM_ALPHA );
15 $hook     = optional_param('hook', 'ALL', PARAM_ALPHANUM);
17 $url = new moodle_url('/mod/glossary/import.php', array('id'=>$id));
18 if ($step !== 0) {
19     $url->param('step', $step);
20 }
21 if ($dest !== 'current') {
22     $url->param('dest', $dest);
23 }
24 if ($file !== '') {
25     $url->param('file', $file);
26 }
27 if ($catsincl !== 0) {
28     $url->param('catsincl', $catsincl);
29 }
30 if ($mode !== 'letter') {
31     $url->param('mode', $mode);
32 }
33 if ($hook !== 'ALL') {
34     $url->param('hook', $hook);
35 }
36 $PAGE->set_url($url);
38 if (! $cm = get_coursemodule_from_id('glossary', $id)) {
39     print_error('invalidcoursemodule');
40 }
42 if (! $course = $DB->get_record("course", array("id"=>$cm->course))) {
43     print_error('coursemisconf');
44 }
46 if (! $glossary = $DB->get_record("glossary", array("id"=>$cm->instance))) {
47     print_error('invalidid', 'glossary');
48 }
50 require_login($course->id, false, $cm);
52 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
53 require_capability('mod/glossary:import', $context);
55 if ($dest != 'new' and $dest != 'current') {
56     $dest = 'current';
57 }
58 $strglossaries = get_string("modulenameplural", "glossary");
59 $strglossary = get_string("modulename", "glossary");
60 $strallcategories = get_string("allcategories", "glossary");
61 $straddentry = get_string("addentry", "glossary");
62 $strnoentries = get_string("noentries", "glossary");
63 $strsearchconcept = get_string("searchconcept", "glossary");
64 $strsearchindefinition = get_string("searchindefinition", "glossary");
65 $strsearch = get_string("search");
66 $strimportentries = get_string('importentriesfromxml', 'glossary');
68 $PAGE->set_url('/mod/glossary/import.php', array('id'=>$cm->id, 'mode'=>$mode, 'hook'=>$hook));
69 $PAGE->navbar->add($strimportentries);
70 $PAGE->set_title(format_string($glossary->name));
71 $PAGE->set_heading($course->fullname);
73 echo $OUTPUT->header();
74 echo $OUTPUT->heading($strimportentries);
76 if ( !$step ) {
77     echo $OUTPUT->box_start('glossarydisplay generalbox');
78     include("import.html");
79     echo $OUTPUT->box_end();
81     echo $OUTPUT->footer();
82     exit;
83 }
85 require_sesskey();
86 $form = data_submitted();
87 $file = $_FILES["file"];
89 require_once($CFG->dirroot.'/lib/uploadlib.php');
90 $um = new upload_manager('file',false,false,$course,false,0);
92 if (!$um->preprocess_files()) {
93     echo $OUTPUT->box_start('glossarydisplay generalbox');
94     echo $OUTPUT->continue_button('import.php?id='.$id);
95     echo $OUTPUT->box_end();
97     echo $OUTPUT->footer();
98     die();
99 }
101 if ($xml = glossary_read_imported_file($file['tmp_name']) ) {
103     $importedentries = 0;
104     $importedcats    = 0;
105     $entriesrejected = 0;
106     $rejections      = '';
107     if ($dest == 'new') {
108         // If the user chose to create a new glossary
109         $xmlglossary = $xml['GLOSSARY']['#']['INFO'][0]['#'];
111         if ( $xmlglossary['NAME'][0]['#'] ) {
112             unset($glossary);
113             $glossary->name = ($xmlglossary['NAME'][0]['#']);
114             $glossary->course = $course->id;
115             $glossary->globalglossary = ($xmlglossary['GLOBALGLOSSARY'][0]['#']);
116             $glossary->intro = ($xmlglossary['INTRO'][0]['#']);
117             $glossary->showspecial = ($xmlglossary['SHOWSPECIAL'][0]['#']);
118             $glossary->showalphabet = ($xmlglossary['SHOWALPHABET'][0]['#']);
119             $glossary->showall = ($xmlglossary['SHOWALL'][0]['#']);
120             $glossary->timecreated = time();
121             $glossary->timemodified = time();
123             // Setting the default values if no values were passed
124             if ( isset($xmlglossary['ENTBYPAGE'][0]['#']) ) {
125                 $glossary->entbypage = ($xmlglossary['ENTBYPAGE'][0]['#']);
126             } else {
127                 $glossary->entbypage = $CFG->glossary_entbypage;
128             }
129             if ( isset($xmlglossary['ALLOWDUPLICATEDENTRIES'][0]['#']) ) {
130                 $glossary->allowduplicatedentries = ($xmlglossary['ALLOWDUPLICATEDENTRIES'][0]['#']);
131             } else {
132                 $glossary->allowduplicatedentries = $CFG->glossary_dupentries;
133             }
134             if ( isset($xmlglossary['DISPLAYFORMAT'][0]['#']) ) {
135                 $glossary->displayformat = ($xmlglossary['DISPLAYFORMAT'][0]['#']);
136             } else {
137                 $glossary->displayformat = 2;
138             }
139             if ( isset($xmlglossary['ALLOWCOMMENTS'][0]['#']) ) {
140                 $glossary->allowcomments = ($xmlglossary['ALLOWCOMMENTS'][0]['#']);
141             } else {
142                 $glossary->allowcomments = $CFG->glossary_allowcomments;
143             }
144             if ( isset($xmlglossary['USEDYNALINK'][0]['#']) ) {
145                 $glossary->usedynalink = ($xmlglossary['USEDYNALINK'][0]['#']);
146             } else {
147                 $glossary->usedynalink = $CFG->glossary_linkentries;
148             }
149             if ( isset($xmlglossary['DEFAULTAPPROVAL'][0]['#']) ) {
150                 $glossary->defaultapproval = ($xmlglossary['DEFAULTAPPROVAL'][0]['#']);
151             } else {
152                 $glossary->defaultapproval = $CFG->glossary_defaultapproval;
153             }
155             // Include new glossary and return the new ID
156             if ( !$glossary->id = glossary_add_instance($glossary) ) {
157                 echo $OUTPUT->notification("Error while trying to create the new glossary.");
158                 echo '</center>';
159                 glossary_print_tabbed_table_end();
160                 echo $OUTPUT->footer();
161                 exit;
162             } else {
163                 //The instance has been created, so lets do course_modules
164                 //and course_sections
165                 $mod->groupmode = $course->groupmode;  /// Default groupmode the same as course
167                 $mod->instance = $glossary->id;
168                 // course_modules and course_sections each contain a reference
169                 // to each other, so we have to update one of them twice.
171                 if (! $currmodule = $DB->get_record("modules", array("name"=>'glossary'))) {
172                     print_error('modulenotexist', 'debug', '', 'Glossary');
173                 }
174                 $mod->module = $currmodule->id;
175                 $mod->course = $course->id;
176                 $mod->modulename = 'glossary';
177                 $mod->section = 0;
179                 if (! $mod->coursemodule = add_course_module($mod) ) {
180                     print_error('cannotaddcoursemodule');
181                 }
183                 if (! $sectionid = add_mod_to_section($mod) ) {
184                     print_error('cannotaddcoursemoduletosection');
185                 }
186                 //We get the section's visible field status
187                 $visible = $DB->get_field("course_sections", "visible", array("id"=>$sectionid));
189                 $DB->set_field("course_modules", "visible", $visible, array("id"=>$mod->coursemodule));
190                 $DB->set_field("course_modules", "section", $sectionid, array("id"=>$mod->coursemodule));
192                 add_to_log($course->id, "course", "add mod",
193                            "../mod/$mod->modulename/view.php?id=$mod->coursemodule",
194                            "$mod->modulename $mod->instance");
195                 add_to_log($course->id, $mod->modulename, "add",
196                            "view.php?id=$mod->coursemodule",
197                            "$mod->instance", $mod->coursemodule);
199                 rebuild_course_cache($course->id);
201                 echo $OUTPUT->box(get_string("newglossarycreated","glossary"),'generalbox boxaligncenter boxwidthnormal');
202                 echo '<p>';
203             }
204         } else {
205             echo $OUTPUT->notification("Error while trying to create the new glossary.");
206             echo $OUTPUT->footer();
207             exit;
208         }
209     }
211     $xmlentries = $xml['GLOSSARY']['#']['INFO'][0]['#']['ENTRIES'][0]['#']['ENTRY'];
212     for($i = 0; $i < sizeof($xmlentries); $i++) {
213         // Inserting the entries
214         $xmlentry = $xmlentries[$i];
215         unset($newentry);
216         $newentry->concept = trim($xmlentry['#']['CONCEPT'][0]['#']);
217         $newentry->definition = trusttext_strip($xmlentry['#']['DEFINITION'][0]['#']);
218         if ( isset($xmlentry['#']['CASESENSITIVE'][0]['#']) ) {
219             $newentry->casesensitive = $xmlentry['#']['CASESENSITIVE'][0]['#'];
220         } else {
221             $newentry->casesensitive = $CFG->glossary_casesensitive;
222         }
224         $permissiongranted = 1;
225         if ( $newentry->concept and $newentry->definition ) {
226             if ( !$glossary->allowduplicatedentries ) {
227                 // checking if the entry is valid (checking if it is duplicated when should not be)
228                 if ( $newentry->casesensitive ) {
229                     $dupentry = $DB->get_record("glossary_entries", array("concept"=>$newentry->concept, "glossaryid"=>$glossary->id));
230                 } else {
231                     $dupentry = $DB->get_record("glossary_entries", array("lower(concept)"=>moodle_strtolower($newentry->concept), "glossaryid"=>$glossary->id));
232                 }
233                 if ($dupentry) {
234                     $permissiongranted = 0;
235                 }
236             }
237         } else {
238             $permissiongranted = 0;
240         if ($permissiongranted) {
241             $newentry->glossaryid       = $glossary->id;
242             $newentry->sourceglossaryid = 0;
243             $newentry->approved         = 1;
244             $newentry->userid           = $USER->id;
245             $newentry->teacherentry     = 1;
246             $newentry->format           = $xmlentry['#']['FORMAT'][0]['#'];
247             $newentry->timecreated      = time();
248             $newentry->timemodified     = time();
250             // Setting the default values if no values were passed
251             if ( isset($xmlentry['#']['USEDYNALINK'][0]['#']) ) {
252                 $newentry->usedynalink      = $xmlentry['#']['USEDYNALINK'][0]['#'];
253             } else {
254                 $newentry->usedynalink      = $CFG->glossary_linkentries;
255             }
256             if ( isset($xmlentry['#']['FULLMATCH'][0]['#']) ) {
257                 $newentry->fullmatch        = $xmlentry['#']['FULLMATCH'][0]['#'];
258             } else {
259                 $newentry->fullmatch      = $CFG->glossary_fullmatch;
260             }
262             if ( $newentry->id = $DB->insert_record("glossary_entries",$newentry) )  {
263                 $importedentries++;
265                 $xmlaliases = @$xmlentry['#']['ALIASES'][0]['#']['ALIAS']; // ignore missing ALIASES
266                 for($k = 0; $k < sizeof($xmlaliases); $k++) {
267                 /// Importing aliases
268                     $xmlalias = $xmlaliases[$k];
269                     $aliasname = $xmlalias['#']['NAME'][0]['#'];
271                     if (!empty($aliasname)) {
272                         $newalias = new object();
273                         $newalias->entryid = $newentry->id;
274                         $newalias->alias = trim($aliasname);
275                         $newalias->id = $DB->insert_record("glossary_alias",$newalias);
276                     }
277                 }
279                 if ( $catsincl ) {
280                     // If the categories must be imported...
281                     $xmlcats = @$xmlentry['#']['CATEGORIES'][0]['#']['CATEGORY']; // ignore missing CATEGORIES
282                     for($k = 0; $k < sizeof($xmlcats); $k++) {
283                         $xmlcat = $xmlcats[$k];
285                         $newcat = new object();
286                         $newcat->name = $xmlcat['#']['NAME'][0]['#'];
287                         $newcat->usedynalink = $xmlcat['#']['USEDYNALINK'][0]['#'];
288                         if ( !$category = $DB->get_record("glossary_categories", array("glossaryid"=>$glossary->id,"name"=>$newcat->name))) {
289                             // Create the category if it does not exist
290                             $category = new object();
291                             $category->name = $newcat->name;
292                             $category->glossaryid = $glossary->id;
293                             $category->id = $DB->insert_record("glossary_categories",$category);
294                             $importedcats++;
295                         }
296                         if ( $category ) {
297                             // inserting the new relation
298                             $entrycat = new object();
299                             $entrycat->entryid    = $newentry->id;
300                             $entrycat->categoryid = $category->id;
301                             $DB->insert_record("glossary_entries_categories",$entrycat);
302                         }
303                     }
304                 }
305             } else {
306                 $entriesrejected++;
307                 // add to exception report (can't insert new record)
308                 $rejections .= "<tr><td>$newentry->concept</td>" .
309                                "<td>" . get_string("cantinsertrec","glossary"). "</td></tr>";
310             }
311         } else {
312             $entriesrejected++;
313             if ( $newentry->concept and $newentry->definition ) {
314                 // add to exception report (duplicated entry))
315                 $rejections .= "<tr><td>$newentry->concept</td>" .
316                                "<td>" . get_string("duplicateentry","glossary"). "</td></tr>";
317             } else {
318                 // add to exception report (no concept or definition found))
319                 $rejections .= "<tr><td>---</td>" .
320                                "<td>" . get_string("noconceptfound","glossary"). "</td></tr>";
321             }
322         }
323     }
324     // processed entries
325     echo $OUTPUT->box_start('glossarydisplay generalbox');
326     echo '<table class="glossaryimportexport">';
327     echo '<tr>';
328     echo '<td width="50%" align="right">';
329     echo get_string("totalentries","glossary");
330     echo ':</td>';
331     echo '<td width="50%" align="left">';
332     echo $importedentries + $entriesrejected;
333     echo '</td>';
334     echo '</tr>';
335     echo '<tr>';
336     echo '<td width="50%" align="right">';
337     echo get_string("importedentries","glossary");
338     echo ':</td>';
339     echo '<td width="50%" align="left">';
340     echo $importedentries;
341     if ( $entriesrejected ) {
342         echo ' <small>(' . get_string("rejectedentries","glossary") . ": $entriesrejected)</small>";
343     }
344     echo '</td>';
345     echo '</tr>';
346     if ( $catsincl ) {
347         echo '<tr>';
348         echo '<td width="50%" align="right">';
349         echo get_string("importedcategories","glossary");
350         echo ':</td>';
351         echo '<td width="50%">';
352         echo $importedcats;
353         echo '</td>';
354         echo '</tr>';
355     }
356     echo '</table><hr />';
358     // rejected entries
359     if ($rejections) {
360         echo '<table class="glossaryimportexport">';
361         echo '<tr><td align="center" colspan="2" width="100%"><strong>' . get_string("rejectionrpt","glossary") . '</strong></tr>';
362         echo $rejections;
363         echo '</table><hr />';
364     }
365 /// Print continue button, based on results
366     if ($importedentries) {
367         echo $OUTPUT->continue_button('view.php?id='.$id);
368     } else {
369         echo $OUTPUT->continue_button('import.php?id='.$id);
370     }
371     echo $OUTPUT->box_end();
372 } else {
373     notice(get_string('errorparsingxml', 'glossary'));
376 /// Finish the page
377 echo $OUTPUT->footer();