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