MDL-15249 error status codes for exceptions and notices
[moodle.git] / mod / glossary / lib.php
CommitLineData
41905731 1<?php // $Id$
07842023 2
3/// Library of functions and constants for module glossary
4/// (replace glossary with the name of your module and delete this line)
5
214b1cf7 6require_once($CFG->libdir.'/portfoliolib.php');
7
7dd88447 8define("GLOSSARY_SHOW_ALL_CATEGORIES", 0);
9define("GLOSSARY_SHOW_NOT_CATEGORISED", -1);
c76e673a 10
1ac87c73 11define("GLOSSARY_NO_VIEW", -1);
7dd88447 12define("GLOSSARY_STANDARD_VIEW", 0);
13define("GLOSSARY_CATEGORY_VIEW", 1);
c197e607 14define("GLOSSARY_DATE_VIEW", 2);
1ac87c73 15define("GLOSSARY_AUTHOR_VIEW", 3);
16define("GLOSSARY_ADDENTRY_VIEW", 4);
17define("GLOSSARY_IMPORT_VIEW", 5);
18define("GLOSSARY_EXPORT_VIEW", 6);
19define("GLOSSARY_APPROVAL_VIEW", 7);
fb443f1a 20
da9c60ec 21/// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
22
07842023 23function glossary_add_instance($glossary) {
c18269c7 24 global $DB;
07842023 25/// Given an object containing all the necessary data,
7cac0c4b 26/// (defined by the form in mod_form.php) this function
07842023 27/// will create a new instance and return the id number
28/// of the new instance.
29
63e21b9b 30 if (empty($glossary->userating)) {
63dd5fb2 31 $glossary->assessed = 0;
32 }
33
e6d45048 34 if (empty($glossary->ratingtime) or empty($glossary->assessed)) {
63dd5fb2 35 $glossary->assesstimestart = 0;
36 $glossary->assesstimefinish = 0;
37 }
38
63e21b9b 39 if (empty($glossary->globalglossary) ) {
0de786f7 40 $glossary->globalglossary = 0;
63e21b9b 41 }
42
957f6fc9 43 if (!has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_SYSTEM))) {
0de786f7 44 $glossary->globalglossary = 0;
45 }
46
e6d45048 47 $glossary->timecreated = time();
07842023 48 $glossary->timemodified = $glossary->timecreated;
49
ff424012 50 //Check displayformat is a valid one
51 $formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
52 if (!in_array($glossary->displayformat, $formats)) {
5973a4c4 53 print_error('unknowformat', '', '', $glossary->displayformat);
a02c77dc 54 }
24c1be88 55
c18269c7 56 if ($returnid = $DB->insert_record("glossary", $glossary)) {
e6d45048 57 $glossary->id = $returnid;
612607bd 58 glossary_grade_item_update($glossary);
e6d45048 59 }
60
61 return $returnid;
07842023 62}
63
64
65function glossary_update_instance($glossary) {
66/// Given an object containing all the necessary data,
7cac0c4b 67/// (defined by the form in mod_form.php) this function
07842023 68/// will update an existing instance with new data.
c18269c7 69 global $CFG, $DB;
a02c77dc 70
da5754f8 71 if (empty($glossary->globalglossary)) {
72 $glossary->globalglossary = 0;
73 }
0de786f7 74
957f6fc9 75 if (!has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_SYSTEM))) {
63e21b9b 76 // keep previous
77 unset($glossary->globalglossary);
78 }
79
07842023 80 $glossary->timemodified = time();
e6d45048 81 $glossary->id = $glossary->instance;
07842023 82
63e21b9b 83 if (empty($glossary->userating)) {
63dd5fb2 84 $glossary->assessed = 0;
85 }
86
e6d45048 87 if (empty($glossary->ratingtime) or empty($glossary->assessed)) {
63dd5fb2 88 $glossary->assesstimestart = 0;
89 $glossary->assesstimefinish = 0;
90 }
91
ff424012 92 //Check displayformat is a valid one
93 $formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
94 if (!in_array($glossary->displayformat, $formats)) {
5973a4c4 95 print_error('unknowformat', '', '', $glossary->displayformat);
ff424012 96 }
97
c18269c7 98 if ($return = $DB->update_record("glossary", $glossary)) {
e6d45048 99 if ($glossary->defaultapproval) {
c18269c7 100 $DB->execute("UPDATE {glossary_entries} SET approved = 1 where approved <> 1 and glossaryid = ?", array($glossary->id));
e6d45048 101 }
102 glossary_grade_item_update($glossary);
5eaa2d34 103 }
07842023 104
5eaa2d34 105 return $return;
07842023 106}
107
49bcd737 108/**
109 * Given an ID of an instance of this module,
110 * this function will permanently delete the instance
111 * and any data that depends on it.
112 * @param int $id glossary id
113 * @return bool success
114 */
07842023 115function glossary_delete_instance($id) {
c18269c7 116 global $DB;
07842023 117
49bcd737 118 if (!$glossary = $DB->get_record('glossary', array('id'=>$id))) {
07842023 119 return false;
120 }
121
49bcd737 122 if (!$cm = get_coursemodule_from_instance('glossary', $id)) {
123 return false;
124 }
07842023 125
49bcd737 126 if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) {
127 return false;
128 }
07842023 129
49bcd737 130 $fs = get_file_storage();
131
132 if ($glossary->mainglossary) {
133 // unexport entries
134 $sql = "SELECT ge.id, ge.sourceglossaryid, cm.id AS sourcecmid
135 FROM {glossary_entries} ge
136 JOIN {modules} m ON m.name = 'glossary'
137 JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = ge.sourceglossaryid)
138 WHERE ge.glossaryid = ? AND ge.sourceglossaryid > 0";
139
140 if ($exported = $DB->get_records_sql($sql, array($id))) {
141 foreach ($exported as $entry) {
142 $entry->glossaryid = $entry->sourceglossaryid;
143 $entry->sourceglossaryid = 0;
144 $newcontext = get_context_instance(CONTEXT_MODULE, $entry->sourcecmid);
145 if ($oldfiles = $fs->get_area_files($context->id, 'glossary_attachment', $entry->id)) {
146 foreach ($oldfiles as $oldfile) {
147 $file_record = new object();
148 $file_record->contextid = $newcontext->id;
149 $fs->create_file_from_storedfile($file_record, $oldfile);
150 }
151 $fs->delete_area_files($context->id, 'glossary_attachment', $entry->id);
152 $entry->attachment = '1';
072f7533 153 } else {
49bcd737 154 $entry->attachment = '0';
072f7533 155 }
49bcd737 156 $DB->update_record('glossary_entries', $entry);
49210b90 157 }
158 }
49bcd737 159 } else {
160 // move exported entries to main glossary
161 $sql = "UPDATE {glossary_entries}
162 SET sourceglossaryid = 0
163 WHERE sourceglossaryid = ?";
164 $DB->execute($sql, array($id));
07842023 165 }
49bcd737 166
167 // Delete any dependent records
168 $entry_select = "SELECT id FROM {glossary_entries} WHERE glossaryid = ?";
169 $DB->delete_records_select('glossary_comments', "entryid IN ($entry_select)", array($id));
170 $DB->delete_records_select('glossary_alias', "entryid IN ($entry_select)", array($id));
171 $DB->delete_records_select('glossary_ratings', "entryid IN ($entry_select)", array($id));
172
173 $category_select = "SELECT id FROM {glossary_categories} WHERE glossaryid = ?";
174 $DB->delete_records_select('glossary_entries_categories', "categoryid IN ($category_select)", array($id));
175 $DB->delete_records('glossary_categories', array('glossaryid'=>$id));
176
fa686bc4 177 // delete all files
178 $fs->delete_area_files($context->id);
49bcd737 179
e6d45048 180 glossary_grade_item_delete($glossary);
07842023 181
49bcd737 182 return $DB->delete_records('glossary', array('id'=>$id));
07842023 183}
184
185function glossary_user_outline($course, $user, $mod, $glossary) {
186/// Return a small object with summary information about what a
187/// user has done with a given particular instance of this module
188/// Used for user activity reports.
189/// $return->time = the time they did it
190/// $return->info = a short text description
191
1ac87c73 192 if ($entries = glossary_get_user_entries($glossary->id, $user->id)) {
e6d45048 193 $result = new object();
1ac87c73 194 $result->info = count($entries) . ' ' . get_string("entries", "glossary");
195
63dd5fb2 196 $lastentry = array_pop($entries);
197 $result->time = $lastentry->timemodified;
1ac87c73 198 return $result;
199 }
200 return NULL;
201}
202
203function glossary_get_user_entries($glossaryid, $userid) {
204/// Get all the entries for a user in a glossary
ae8c3566 205 global $DB;
1ac87c73 206
ae8c3566 207 return $DB->get_records_sql("SELECT e.*, u.firstname, u.lastname, u.email, u.picture
208 FROM {glossary} g, {glossary_entries} e, {user} u
209 WHERE g.id = ?
a02c77dc 210 AND e.glossaryid = g.id
ae8c3566 211 AND e.userid = ?
1ac87c73 212 AND e.userid = u.id
ae8c3566 213 ORDER BY e.timemodified ASC", array($glossaryid, $userid));
07842023 214}
215
216function glossary_user_complete($course, $user, $mod, $glossary) {
217/// Print a detailed representation of what a user has done with
218/// a given particular instance of this module, for user activity reports.
1ac87c73 219 global $CFG;
07842023 220
1ac87c73 221 if ($entries = glossary_get_user_entries($glossary->id, $user->id)) {
a359c29b 222 echo '<table width="95%" border="0"><tr><td>';
1ac87c73 223 foreach ($entries as $entry) {
224 $cm = get_coursemodule_from_instance("glossary", $glossary->id, $course->id);
225 glossary_print_entry($course, $cm, $glossary, $entry,"","",0);
226 echo '<p>';
227 }
a359c29b 228 echo '</td></tr></table>';
1ac87c73 229 }
07842023 230}
231
dd97c328 232function glossary_print_recent_activity($course, $viewfullnames, $timestart) {
07842023 233/// Given a course and a time, this module should find recent activity
234/// that has occurred in glossary activities and print it out.
235/// Return true if there was output, or false is there was none.
236
ae8c3566 237 global $CFG, $USER, $DB;
dd97c328 238
239 //TODO: use timestamp in approved field instead of changing timemodified when approving in 2.0
240
241 $modinfo = get_fast_modinfo($course);
242 $ids = array();
243 foreach ($modinfo->cms as $cm) {
244 if ($cm->modname != 'glossary') {
245 continue;
246 }
247 if (!$cm->uservisible) {
248 continue;
249 }
250 $ids[$cm->instance] = $cm->instance;
251 }
252
253 if (!$ids) {
254 return false;
255 }
256
257 $glist = implode(',', $ids); // there should not be hundreds of glossaries in one course, right?
07842023 258
ae8c3566 259 if (!$entries = $DB->get_records_sql("SELECT ge.id, ge.concept, ge.approved, ge.timemodified, ge.glossaryid,
260 ge.userid, u.firstname, u.lastname, u.email, u.picture
261 FROM {glossary_entries} ge
262 JOIN {user} u ON u.id = ge.userid
263 WHERE ge.glossaryid IN ($glist) AND ge.timemodified > ?
264 ORDER BY ge.timemodified ASC", array($timestart))) {
07842023 265 return false;
266 }
267
dd97c328 268 $editor = array();
a359c29b 269
dd97c328 270 foreach ($entries as $entryid=>$entry) {
271 if ($entry->approved) {
cf8eaebb 272 continue;
273 }
dd97c328 274
275 if (!isset($editor[$entry->glossaryid])) {
276 $editor[$entry->glossaryid] = has_capability('mod/glossary:approve', get_context_instance(CONTEXT_MODULE, $modinfo->instances['glossary'][$entry->glossaryid]->id));
07842023 277 }
07842023 278
dd97c328 279 if (!$editor[$entry->glossaryid]) {
280 unset($entries[$entryid]);
281 }
282 }
8f7dc7f1 283
dd97c328 284 if (!$entries) {
285 return false;
286 }
287 print_headline(get_string('newentries', 'glossary').':');
288
289 $strftimerecent = get_string('strftimerecent');
290 foreach ($entries as $entry) {
291 $link = $CFG->wwwroot.'/mod/glossary/view.php?g='.$entry->glossaryid.'&amp;mode=entry&amp;hook='.$entry->id;
292 if ($entry->approved) {
293 $dimmed = '';
294 } else {
295 $dimmed = ' dimmed_text';
07842023 296 }
dd97c328 297 echo '<div class="head'.$dimmed.'">';
298 echo '<div class="date">'.userdate($entry->timemodified, $strftimerecent).'</div>';
299 echo '<div class="name">'.fullname($entry, $viewfullnames).'</div>';
300 echo '</div>';
301 echo '<div class="info"><a href="'.$link.'">'.format_text($entry->concept, true).'</a></div>';
07842023 302 }
303
dd97c328 304 return true;
07842023 305}
306
8f7dc7f1 307
1ac87c73 308function glossary_log_info($log) {
ae8c3566 309 global $DB;
1ac87c73 310
ae8c3566 311 return $DB->get_record_sql("SELECT e.*, u.firstname, u.lastname
312 FROM {glossary_entries} e, {user} u
313 WHERE e.id = ? AND u.id = ?", array($log->info, $log->userid));
1ac87c73 314}
315
07842023 316function glossary_cron () {
317/// Function to be run periodically according to the moodle cron
318/// This function searches for things that need to be done, such
319/// as sending out mail, toggling flags etc ...
07842023 320 return true;
321}
322
d31bae70 323/**
324 * Return grade for given user or all users.
325 *
326 * @param int $glossaryid id of glossary
327 * @param int $userid optional user id, 0 means all users
328 * @return array array of grades, false if none
329 */
612607bd 330function glossary_get_user_grades($glossary, $userid=0) {
ae8c3566 331 global $DB;
63dd5fb2 332
ae8c3566 333 $params = array('userid'=>$userid, 'gid'=>$glossary->id);
334
335 $user = $userid ? "AND u.id = :userid" : "";
63dd5fb2 336
ac9b0805 337 $sql = "SELECT u.id, u.id AS userid, avg(gr.rating) AS rawgrade
ae8c3566 338 FROM {user} u, {glossary_entries} ge, {glossary_ratings} gr
e6d45048 339 WHERE u.id = ge.userid AND ge.id = gr.entryid
ae8c3566 340 AND gr.userid != u.id AND ge.glossaryid = :gid
e6d45048 341 $user
342 GROUP BY u.id";
343
ae8c3566 344 return $DB->get_records_sql($sql, $params);
e6d45048 345}
346
d31bae70 347/**
775f811a 348 * Update activity grades
d31bae70 349 *
7f46236f 350 * @param object $glossary null means all glossaries (with extra cmidnumber property)
775f811a 351 * @param int $userid specific user only, 0 means all
d31bae70 352 */
612607bd 353function glossary_update_grades($glossary=null, $userid=0, $nullifnone=true) {
ae8c3566 354 global $CFG, $DB;
adcbb43a 355 require_once($CFG->libdir.'/gradelib.php');
e6d45048 356
775f811a 357 if (!$glossary->assessed) {
358 glossary_grade_item_update($glossary);
3e6303b7 359
775f811a 360 } else if ($grades = glossary_get_user_grades($glossary, $userid)) {
361 glossary_grade_item_update($glossary, $grades);
eafb9d9e 362
775f811a 363 } else if ($userid and $nullifnone) {
364 $grade = new object();
365 $grade->userid = $userid;
366 $grade->rawgrade = NULL;
367 glossary_grade_item_update($glossary, $grade);
a02c77dc 368
e6d45048 369 } else {
775f811a 370 glossary_grade_item_update($glossary);
371 }
372}
373
374/**
375 * Update all grades in gradebook.
376 */
377function glossary_upgrade_grades() {
378 global $DB;
379
380 $sql = "SELECT COUNT('x')
381 FROM {glossary} g, {course_modules} cm, {modules} m
382 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id";
383 $count = $DB->count_records_sql($sql);
384
385 $sql = "SELECT g.*, cm.idnumber AS cmidnumber, g.course AS courseid
386 FROM {glossary} g, {course_modules} cm, {modules} m
387 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id";
388 if ($rs = $DB->get_recordset_sql($sql)) {
775f811a 389 $pbar = new progress_bar('glossaryupgradegrades', 500, true);
390 $i=0;
391 foreach ($rs as $glossary) {
392 $i++;
393 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
394 glossary_update_grades($glossary, 0, false);
395 $pbar->update($i, $count, "Updating Glossary grades ($i/$count).");
e6d45048 396 }
775f811a 397 $rs->close();
e6d45048 398 }
399}
400
d31bae70 401/**
612607bd 402 * Create/update grade item for given glossary
d31bae70 403 *
dd232d01 404 * @param object $glossary object with extra cmidnumber
0b5a80a1 405 * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
612607bd 406 * @return int, 0 if ok, error code otherwise
d31bae70 407 */
0b5a80a1 408function glossary_grade_item_update($glossary, $grades=NULL) {
612607bd 409 global $CFG;
ae8c3566 410 require_once($CFG->libdir.'/gradelib.php');
411
7f46236f 412 $params = array('itemname'=>$glossary->name, 'idnumber'=>$glossary->cmidnumber);
e6d45048 413
5980d52f 414 if (!$glossary->assessed or $glossary->scale == 0) {
612607bd 415 $params['gradetype'] = GRADE_TYPE_NONE;
34601114 416
417 } else if ($glossary->scale > 0) {
e8586b5f 418 $params['gradetype'] = GRADE_TYPE_VALUE;
e6d45048 419 $params['grademax'] = $glossary->scale;
420 $params['grademin'] = 0;
421
422 } else if ($glossary->scale < 0) {
e8586b5f 423 $params['gradetype'] = GRADE_TYPE_SCALE;
e6d45048 424 $params['scaleid'] = -$glossary->scale;
e6d45048 425 }
426
0b5a80a1 427 if ($grades === 'reset') {
428 $params['reset'] = true;
429 $grades = NULL;
430 }
431
432 return grade_update('mod/glossary', $glossary->course, 'mod', 'glossary', $glossary->id, 0, $grades, $params);
e6d45048 433}
434
d31bae70 435/**
436 * Delete grade item for given glossary
437 *
dd232d01 438 * @param object $glossary object
d31bae70 439 */
e6d45048 440function glossary_grade_item_delete($glossary) {
612607bd 441 global $CFG;
442 require_once($CFG->libdir.'/gradelib.php');
443
b67ec72f 444 return grade_update('mod/glossary', $glossary->course, 'mod', 'glossary', $glossary->id, 0, NULL, array('deleted'=>1));
07842023 445}
446
05855091 447function glossary_get_participants($glossaryid) {
448//Returns the users with data in one glossary
449//(users with records in glossary_entries, students)
ae8c3566 450 global $DB;
05855091 451
452 //Get students
ae8c3566 453 $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
454 FROM {user} u, {glossary_entries} g
585fb1f4 455 WHERE g.glossaryid = ? AND u.id = g.userid", array($glossaryid));
05855091 456
457 //Return students array (it contains an array of unique users)
ae8c3566 458 return $students;
05855091 459}
07842023 460
0f1a97c2 461function glossary_scale_used ($glossaryid,$scaleid) {
462//This function returns if a scale is being used by one glossary
ae8c3566 463 global $DB;
a02c77dc 464
0f1a97c2 465 $return = false;
466
ae8c3566 467 $rec = $DB->get_record("glossary", array("id"=>$glossaryid, "scale"=>-$scaleid));
0f1a97c2 468
2127fedd 469 if (!empty($rec) && !empty($scaleid)) {
a02c77dc 470 $return = true;
471 }
472
0f1a97c2 473 return $return;
474}
475
85c9ebb9 476/**
477 * Checks if scale is being used by any instance of glossary
478 *
479 * This is used to find out if scale used anywhere
480 * @param $scaleid int
481 * @return boolean True if the scale is used by any glossary
482 */
483function glossary_scale_used_anywhere($scaleid) {
ae8c3566 484 global $DB;
485
486 if ($scaleid and $DB->record_exists('glossary', array('scale'=>-$scaleid))) {
85c9ebb9 487 return true;
488 } else {
489 return false;
490 }
491}
492
07842023 493//////////////////////////////////////////////////////////////////////////////////////
494/// Any other glossary functions go here. Each of them must have a name that
495/// starts with glossary_
496
a359c29b 497//This function return an array of valid glossary_formats records
498//Everytime it's called, every existing format is checked, new formats
499//are included if detected and old formats are deleted and any glossary
500//using an invalid format is updated to the default (dictionary).
501function glossary_get_available_formats() {
ae8c3566 502 global $CFG, $DB;
a359c29b 503
504 //Get available formats (plugin) and insert (if necessary) them into glossary_formats
77495793 505 $formats = get_list_of_plugins('mod/glossary/formats', 'TEMPLATE');
506 $pluginformats = array();
a359c29b 507 foreach ($formats as $format) {
508 //If the format file exists
509 if (file_exists($CFG->dirroot.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php')) {
510 include_once($CFG->dirroot.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php');
511 //If the function exists
512 if (function_exists('glossary_show_entry_'.$format)) {
77495793 513 //Acummulate it as a valid format
514 $pluginformats[] = $format;
a359c29b 515 //If the format doesn't exist in the table
ae8c3566 516 if (!$rec = $DB->get_record('glossary_formats', array('name'=>$format))) {
a359c29b 517 //Insert the record in glossary_formats
e6d45048 518 $gf = new object();
a359c29b 519 $gf->name = $format;
520 $gf->popupformatname = $format;
521 $gf->visible = 1;
ae8c3566 522 $DB->insert_record("glossary_formats",$gf);
a359c29b 523 }
524 }
525 }
526 }
527
528 //Delete non_existent formats from glossary_formats table
ae8c3566 529 $formats = $DB->get_records("glossary_formats");
a359c29b 530 foreach ($formats as $format) {
531 $todelete = false;
77495793 532 //If the format in DB isn't a valid previously detected format then delete the record
533 if (!in_array($format->name,$pluginformats)) {
a359c29b 534 $todelete = true;
a359c29b 535 }
536
537 if ($todelete) {
538 //Delete the format
ae8c3566 539 $DB->delete_records('glossary_formats', array('name'=>$format->name));
a359c29b 540 //Reasign existing glossaries to default (dictionary) format
ae8c3566 541 if ($glossaries = $DB->get_records('glossary', array('displayformat'=>$format->name))) {
a359c29b 542 foreach($glossaries as $glossary) {
ae8c3566 543 $DB->set_field('glossary','displayformat','dictionary', array('id'=>$glossary->id));
a359c29b 544 }
545 }
546 }
547 }
548
549 //Now everything is ready in glossary_formats table
ae8c3566 550 $formats = $DB->get_records("glossary_formats");
a359c29b 551
552 return $formats;
553}
554
1ac87c73 555function glossary_debug($debug,$text,$br=1) {
556 if ( $debug ) {
41905731 557 echo '<font color="red">' . $text . '</font>';
1ac87c73 558 if ( $br ) {
a9ef4a63 559 echo '<br />';
1ac87c73 560 }
561 }
07842023 562}
563
ea14e783 564function glossary_get_entries($glossaryid, $entrylist, $pivot = "") {
ae8c3566 565 global $DB;
ea14e783 566 if ($pivot) {
567 $pivot .= ",";
568 }
07842023 569
ae8c3566 570 return $DB->get_records_sql("SELECT $pivot id,userid,concept,definition,format
571 FROM {glossary_entries}
572 WHERE glossaryid = ?
573 AND id IN ($entrylist)", array($glossaryid));
07842023 574}
359f2758 575
576function glossary_get_entries_search($concept, $courseid) {
ae8c3566 577 global $CFG, $DB;
359f2758 578
a02c77dc 579 //Check if the user is an admin
6c351232 580 $bypassadmin = 1; //This means NO (by default)
957f6fc9 581 if (has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_SYSTEM))) {
6c351232 582 $bypassadmin = 0; //This means YES
a02c77dc 583 }
6c351232 584
a02c77dc 585 //Check if the user is a teacher
6c351232 586 $bypassteacher = 1; //This means NO (by default)
81e956b9 587 if (has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_COURSE, $courseid))) {
6c351232 588 $bypassteacher = 0; //This means YES
a02c77dc 589 }
6c351232 590
95d56829 591 $conceptlower = moodle_strtolower(trim($concept));
359f2758 592
ae8c3566 593 $params = array('courseid1'=>$courseid, 'courseid2'=>$courseid, 'conceptlower'=>$conceptlower, 'concept'=>$concept);
c76e673a 594
ae8c3566 595 return $DB->get_records_sql("SELECT e.*, g.name as glossaryname, cm.id as cmid, cm.course as courseid
596 FROM {glossary_entries} e, {glossary} g,
597 {course_modules} cm, {modules} m
598 WHERE m.name = 'glossary' AND
599 cm.module = m.id AND
600 (cm.visible = 1 OR cm.visible = $bypassadmin OR
601 (cm.course = :courseid1 AND cm.visible = $bypassteacher)) AND
602 g.id = cm.instance AND
603 e.glossaryid = g.id AND
604 ( (e.casesensitive != 0 AND LOWER(concept) = :conceptlower) OR
605 (e.casesensitive = 0 and concept = :concept)) AND
606 (g.course = courseid2 OR g.globalglossary = 1) AND
607 e.usedynalink != 0 AND
608 g.usedynalink != 0", $params);
c76e673a 609}
07842023 610
b8340d19 611function glossary_print_entry($course, $cm, $glossary, $entry, $mode='',$hook='',$printicons = 1, $displayformat = -1, $ratings = NULL, $printview = false) {
612 global $USER, $CFG;
37d543b5 613 $return = false;
b1918034 614 if ( $displayformat < 0 ) {
615 $displayformat = $glossary->displayformat;
616 }
b620a995 617 if ($entry->approved or ($USER->id == $entry->userid) or ($mode == 'approval' and !$entry->approved) ) {
a359c29b 618 $formatfile = $CFG->dirroot.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
ae06e00e 619 if ($printview) {
620 $functionname = 'glossary_print_entry_'.$displayformat;
621 } else {
622 $functionname = 'glossary_show_entry_'.$displayformat;
623 }
a359c29b 624
625 if (file_exists($formatfile)) {
626 include_once($formatfile);
627 if (function_exists($functionname)) {
628 $return = $functionname($course, $cm, $glossary, $entry,$mode,$hook,$printicons,$ratings);
ae06e00e 629 } else if ($printview) {
630 //If the glossary_print_entry_XXXX function doesn't exist, print default (old) print format
ccde17c3 631 $return = glossary_print_entry_default($entry, $glossary, $cm);
c76e673a 632 }
767a31c3 633 }
07842023 634 }
a359c29b 635 return $return;
07842023 636}
b8340d19 637
ae06e00e 638 //Default (old) print format used if custom function doesn't exist in format
ccde17c3 639function glossary_print_entry_default ($entry, $glossary, $cm) {
097d705e 640 echo '<h3>'. strip_tags($entry->concept) . ': </h3>';
7d8a3cb0 641
642 $definition = $entry->definition;
643
7d8a3cb0 644 $definition = '<span class="nolink">' . strip_tags($definition) . '</span>';
645
ccde17c3 646 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
647 $definition = file_rewrite_pluginfile_urls($definition, 'pluginfile.php', $context->id, 'glossary_entry', $entry->id);
cbc2b5df 648
7d8a3cb0 649 $options = new object();
ae06e00e 650 $options->para = false;
cbc2b5df 651 $options->trusted = $entry->definitiontrust;
652 $definition = format_text($definition, $entry->definitionformat, $options);
ae06e00e 653 echo ($definition);
654 echo '<br /><br />';
655}
a359c29b 656
120a18f0 657/**
658 * Print glossary concept/term as a heading &lt;h3>
659 */
81bdc9e9 660function glossary_print_entry_concept($entry) {
7d8a3cb0 661 $options = new object();
d34b9c5f 662 $options->para = false;
46712419 663 $text = format_text(print_heading('<span class="nolink">' . $entry->concept . '</span>', '', 3, 'nolink', true), FORMAT_MOODLE, $options);
ff8352de 664 if (!empty($entry->highlight)) {
665 $text = highlight($entry->highlight, $text);
666 }
667 echo $text;
81bdc9e9 668}
1d9ddaaf 669
ccde17c3 670function glossary_print_entry_definition($entry, $glossary, $cm) {
ae8c3566 671 global $DB;
701fff21 672
f287e69c 673 $definition = $entry->definition;
674
4e489ae9 675 global $GLOSSARY_EXCLUDECONCEPTS;
676
701fff21 677 //Calculate all the strings to be no-linked
678 //First, the concept
4e489ae9 679 $GLOSSARY_EXCLUDECONCEPTS=array($entry->concept);
701fff21 680 //Now the aliases
ae8c3566 681 if ( $aliases = $DB->get_records('glossary_alias', array('entryid'=>$entry->id))) {
701fff21 682 foreach ($aliases as $alias) {
4e489ae9 683 $GLOSSARY_EXCLUDECONCEPTS[]=trim($alias->alias);
701fff21 684 }
f287e69c 685 }
686
7d8a3cb0 687 $options = new object();
3eb2f7ec 688 $options->para = false;
cbc2b5df 689 $options->trusted = $entry->definitiontrust;
0f9a668f 690
ccde17c3 691 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
692 $definition = file_rewrite_pluginfile_urls($definition, 'pluginfile.php', $context->id, 'glossary_entry', $entry->id);
cbc2b5df 693
694 $text = format_text($definition, $entry->definitionformat, $options);
695
4e489ae9 696 // Stop excluding concepts from autolinking
697 unset($GLOSSARY_EXCLUDECONCEPTS);
cbc2b5df 698
ff8352de 699 if (!empty($entry->highlight)) {
700 $text = highlight($entry->highlight, $text);
701 }
359f2758 702 if (isset($entry->footer)) { // Unparsed footer info
703 $text .= $entry->footer;
704 }
ff8352de 705 echo $text;
1d9ddaaf 706}
707
b8340d19 708function glossary_print_entry_aliases($course, $cm, $glossary, $entry,$mode='',$hook='', $type = 'print') {
ae8c3566 709 global $DB;
710
81bdc9e9 711 $return = '';
ae8c3566 712 if ( $aliases = $DB->get_records('glossary_alias', array('entryid'=>$entry->id))) {
81bdc9e9 713 foreach ($aliases as $alias) {
33cc423e 714 if (trim($alias->alias)) {
81bdc9e9 715 if ($return == '') {
716 $return = '<select style="font-size:8pt">';
717 }
718 $return .= "<option>$alias->alias</option>";
719 }
720 }
721 if ($return != '') {
722 $return .= '</select>';
81bdc9e9 723 }
a02c77dc 724 }
1ac87c73 725 if ($type == 'print') {
81bdc9e9 726 echo $return;
727 } else {
728 return $return;
729 }
730}
731
b8340d19 732function glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode='',$hook='', $type = 'print') {
ae8c3566 733 global $USER, $CFG, $DB;
a02c77dc 734
dabfd0ed 735 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
81bdc9e9 736
36ce6ea2 737 $output = false; //To decide if we must really return text in "return". Activate when needed only!
81bdc9e9 738 $importedentry = ($entry->sourceglossaryid == $glossary->id);
81bdc9e9 739 $ismainglossary = $glossary->mainglossary;
b8340d19 740
741
9362b9b6 742 $return = '<span class="commands">';
097d705e 743 // Differentiate links for each entry.
2d1e0971 744 $altsuffix = ': '.strip_tags(format_text($entry->concept));
745
81bdc9e9 746 if (!$entry->approved) {
36ce6ea2 747 $output = true;
b8340d19 748 $return .= get_string('entryishidden','glossary');
81bdc9e9 749 }
66d7ae88 750 $return .= glossary_print_entry_commentslink($course, $cm, $glossary, $entry,$mode,$hook,'html');
a02c77dc 751
ea16f9b2 752 if (has_capability('mod/glossary:comment', $context) and $glossary->allowcomments) {
dabfd0ed 753 $output = true;
989c16ee 754 $return .= ' <a title="' . get_string('addcomment','glossary') . '" href="comment.php?action=add&amp;entryid='.$entry->id.'"><img src="comment.gif" class="iconsmall" alt="'.get_string('addcomment','glossary').$altsuffix.'" /></a>';
81bdc9e9 755 }
756
b8340d19 757
6cb34d44 758 if (has_capability('mod/glossary:manageentries', $context) or (!empty($USER->id) and has_capability('mod/glossary:write', $context) and $entry->userid == $USER->id)) {
81bdc9e9 759 // only teachers can export entries so check it out
0468976c 760 if (has_capability('mod/glossary:export', $context) and !$ismainglossary and !$importedentry) {
ae8c3566 761 $mainglossary = $DB->get_record('glossary', array('mainglossary'=>1,'course'=>$course->id));
81bdc9e9 762 if ( $mainglossary ) { // if there is a main glossary defined, allow to export the current entry
36ce6ea2 763 $output = true;
49bcd737 764 $return .= ' <a title="'.get_string('exporttomainglossary','glossary') . '" href="exportentry.php?id='.$entry->id.'&amp;prevmode='.$mode.'&amp;hook='.urlencode($hook).'"><img src="export.gif" class="iconsmall" alt="'.get_string('exporttomainglossary','glossary').$altsuffix.'" /></a>';
81bdc9e9 765 }
766 }
767
768 if ( $entry->sourceglossaryid ) {
769 $icon = "minus.gif"; // graphical metaphor (minus) for deleting an imported entry
770 } else {
096b5432 771 $icon = "$CFG->pixpath/t/delete.gif";
81bdc9e9 772 }
773
ff1e2621 774 //Decide if an entry is editable:
775 // -It isn't a imported entry (so nobody can edit a imported (from secondary to main) entry)) and
776 // -The user is teacher or he is a student with time permissions (edit period or editalways defined).
516c7276 777 $ineditperiod = ((time() - $entry->timecreated < $CFG->maxeditingtime) || $glossary->editalways);
6cb34d44 778 if ( !$importedentry and (has_capability('mod/glossary:manageentries', $context) or ($entry->userid == $USER->id and ($ineditperiod and has_capability('mod/glossary:write', $context))))) {
36ce6ea2 779 $output = true;
49bcd737 780 $return .= " <a title=\"" . get_string("delete") . "\" href=\"deleteentry.php?id=$cm->id&amp;mode=delete&amp;entry=$entry->id&amp;prevmode=$mode&amp;hook=".urlencode($hook)."\"><img src=\"";
81bdc9e9 781 $return .= $icon;
097d705e 782 $return .= "\" class=\"iconsmall\" alt=\"" . get_string("delete") .$altsuffix."\" /></a> ";
a02c77dc 783
49bcd737 784 $return .= " <a title=\"" . get_string("edit") . "\" href=\"edit.php?cmid=$cm->id&amp;id=$entry->id&amp;mode=$mode&amp;hook=".urlencode($hook)."\"><img src=\"$CFG->pixpath/t/edit.gif\" class=\"iconsmall\" alt=\"" . get_string("edit") .$altsuffix. "\" /></a>";
81bdc9e9 785 } elseif ( $importedentry ) {
41905731 786 $return .= " <font size=\"-1\">" . get_string("exportedentry","glossary") . "</font>";
81bdc9e9 787 }
788 }
86a3996d 789 if (has_capability('mod/glossary:exportentry', $context)
790 || ($entry->userid == $USER->id
791 && has_capability('mod/glossary:exportownentry', $context))) {
0d06b6fd 792 $button = new portfolio_add_button();
793 $button->set_callback_options('glossary_entry_portfolio_caller', array('id' => $cm->id, 'entryid' => $entry->id));
794 $return .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
49a12552 795 }
81bdc9e9 796 $return .= "&nbsp;&nbsp;"; // just to make up a little the output in Mozilla ;)
36ce6ea2 797
9362b9b6 798 $return .= '</span>';
a02c77dc 799
36ce6ea2 800 //If we haven't calculated any REAL thing, delete result ($return)
801 if (!$output) {
802 $return = '';
803 }
804 //Print or get
1ac87c73 805 if ($type == 'print') {
81bdc9e9 806 echo $return;
807 } else {
808 return $return;
a0d1e2bb 809 }
810}
811
812function glossary_print_entry_commentslink($course, $cm, $glossary, $entry,$mode,$hook, $type = 'print') {
ae8c3566 813 global $DB;
814
a0d1e2bb 815 $return = '';
816
ae8c3566 817 $count = $DB->count_records('glossary_comments', array('entryid'=>$entry->id));
a0d1e2bb 818 if ($count) {
b8340d19 819 $return = '';
839f2456 820 $return .= "<a href=\"comments.php?id=$cm->id&amp;eid=$entry->id\">$count ";
a0d1e2bb 821 if ($count == 1) {
b8340d19 822 $return .= get_string('comment', 'glossary');
a0d1e2bb 823 } else {
b8340d19 824 $return .= get_string('comments', 'glossary');
a0d1e2bb 825 }
b8340d19 826 $return .= '</a>';
a0d1e2bb 827 }
828
829 if ($type == 'print') {
830 echo $return;
831 } else {
832 return $return;
81bdc9e9 833 }
834}
835
cbc2b5df 836function glossary_print_entry_lower_section($course, $cm, $glossary, $entry, $mode, $hook, $printicons, $ratings, $aliases=true) {
81bdc9e9 837
26983d03 838 if ($aliases) {
9362b9b6 839 $aliases = glossary_print_entry_aliases($course, $cm, $glossary, $entry, $mode, $hook,'html');
26983d03 840 }
9362b9b6 841 $icons = '';
842 $return = '';
cbc2b5df 843 if ($printicons) {
9362b9b6 844 $icons = glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode, $hook,'html');
1ac87c73 845 }
36ce6ea2 846 if ($aliases || $icons || $ratings) {
9362b9b6 847 echo '<table>';
a359c29b 848 if ( $aliases ) {
9362b9b6 849 echo '<tr valign="top"><td class="aliases">' .
850 get_string('aliases','glossary').': '.$aliases . '</td></tr>';
a359c29b 851 }
852 if ($icons) {
9362b9b6 853 echo '<tr valign="top"><td class="icons">'.$icons.'</td></tr>';
a359c29b 854 }
855 if ($ratings) {
9362b9b6 856 echo '<tr valign="top"><td class="ratings">';
a359c29b 857 $return = glossary_print_entry_ratings($course, $entry, $ratings);
858 echo '</td></tr>';
859 }
860 echo '</table>';
81bdc9e9 861 }
a359c29b 862 return $return;
81bdc9e9 863}
864
49bcd737 865function glossary_print_entry_attachment($entry, $cm, $format=NULL, $align="right", $insidetable=true) {
1d9ddaaf 866/// valid format values: html : Return the HTML link for the attachment as an icon
867/// text : Return the HTML link for tha attachment as text
868/// blank : Print the output to the screen
869 if ($entry->attachment) {
77495793 870 if ($insidetable) {
41905731 871 echo "<table border=\"0\" width=\"100%\" align=\"$align\"><tr><td align=\"$align\" nowrap=\"nowrap\">\n";
77495793 872 }
49bcd737 873 echo glossary_print_attachments($entry, $cm, $format, $align);
77495793 874 if ($insidetable) {
875 echo "</td></tr></table>\n";
876 }
1d9ddaaf 877 }
878}
879
cbc2b5df 880function glossary_print_entry_approval($cm, $entry, $mode, $align="right", $insidetable=true) {
cff611fc 881 global $CFG;
882
cbc2b5df 883 if ($mode == 'approval' and !$entry->approved) {
77495793 884 if ($insidetable) {
a8466100 885 echo '<table class="glossaryapproval" align="'.$align.'"><tr><td align="'.$align.'">';
77495793 886 }
e32d5506 887 echo '<a title="'.get_string('approve','glossary').'" href="approve.php?id='.$cm->id.'&amp;eid='.$entry->id.'&amp;mode='.$mode.'"><img align="'.$align.'" src="'.$CFG->pixpath.'/i/approve.gif" style="border:0px; width:34px; height:34px" alt="'.get_string('approve','glossary').'" /></a>';
77495793 888 if ($insidetable) {
a8466100 889 echo '</td></tr></table>';
77495793 890 }
1d9ddaaf 891 }
892}
07842023 893
c80828fe 894function glossary_search($course, $searchterms, $extended = 0, $glossary = NULL) {
a02c77dc 895// It returns all entries from all glossaries that matches the specified criteria
c80828fe 896// within a given $course. It performs an $extended search if necessary.
897// It restrict the search to only one $glossary if the $glossary parameter is set.
ae8c3566 898 global $CFG, $DB;
07842023 899
c80828fe 900 if ( !$glossary ) {
ae8c3566 901 if ( $glossaries = $DB->get_records("glossary", array("course"=>$course->id)) ) {
c80828fe 902 $glos = "";
903 foreach ( $glossaries as $glossary ) {
904 $glos .= "$glossary->id,";
905 }
9cae3799 906 $glos = substr($glos,0,-1);
c80828fe 907 }
908 } else {
909 $glos = $glossary->id;
910 }
a02c77dc 911
81e956b9 912 if (!has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_COURSE, $glossary->course))) {
ae8c3566 913 $glossarymodule = $DB->get_record("modules", array("name"=>"glossary"));
6a22879b 914 $onlyvisible = " AND g.id = cm.instance AND cm.visible = 1 AND cm.module = $glossarymodule->id";
ae8c3566 915 $onlyvisibletable = ", {course_modules} cm";
07842023 916 } else {
917
918 $onlyvisible = "";
919 $onlyvisibletable = "";
920 }
921
ae8c3566 922 if ($DB->sql_regex_supported()) {
923 $REGEXP = $DB->sql_regex(true);
924 $NOTREGEXP = $DB->sql_regex(false);
a02c77dc 925 }
ae8c3566 926 $LIKE = $DB->sql_ilike(); // case-insensitive
07842023 927
ae8c3566 928 $searchcond = array();
929 $params = array();
930 $i = 0;
931
932 $concat = $DB->sql_concat('e.concept', "' '", 'e.definition');
07842023 933
934
935 foreach ($searchterms as $searchterm) {
ae8c3566 936 $i++;
937
938 $NOT = ''; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
939 /// will use it to simulate the "-" operator with LIKE clause
07842023 940
6f4bdb9c 941 /// Under Oracle and MSSQL, trim the + and - operators and perform
ae8c3566 942 /// simpler LIKE (or NOT LIKE) queries
943 if (!$DB->sql_regex_supported()) {
944 if (substr($searchterm, 0, 1) == '-') {
945 $NOT = ' NOT ';
946 }
6f4bdb9c 947 $searchterm = trim($searchterm, '+-');
948 }
949
ae8c3566 950 // TODO: +- may not work for non latin languages
951
952 if (substr($searchterm,0,1) == '+') {
953 $searchterm = trim($searchterm, '+-');
954 $searchterm = preg_quote($searchterm, '|');
955 $searchcond[] = "$concat $REGEXP :ss$i";
956 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
957
07842023 958 } else if (substr($searchterm,0,1) == "-") {
ae8c3566 959 $searchterm = trim($searchterm, '+-');
960 $searchterm = preg_quote($searchterm, '|');
961 $searchcond[] = "$concat $NOTREGEXP :ss$i";
962 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
963
07842023 964 } else {
ae8c3566 965 $searchcond[] = "$concat $NOT $LIKE :ss$i";
966 $params['ss'.$i] = "%$searchterm%";
07842023 967 }
968 }
969
ae8c3566 970 if (empty($searchcond)) {
971 $totalcount = 0;
972 return array();
973 }
974
975 $searchcond = implode(" AND ", $searchcond);
07842023 976
ae8c3566 977 $sql = "SELECT e.*
978 FROM {glossary_entries} e, {glossary} g $onlyvisibletable
979 WHERE $searchcond
ad58adac 980 AND (e.glossaryid = g.id or e.sourceglossaryid = g.id) $onlyvisible
ae8c3566 981 AND g.id IN ($glos) AND e.approved <> 0";
07842023 982
ae8c3566 983 return $DB->get_records_sql($sql, $params);
07842023 984}
985
c80828fe 986function glossary_search_entries($searchterms, $glossary, $extended) {
ae8c3566 987 global $DB;
988
989 $course = $DB->get_record("course", array("id"=>$glossary->course));
c80828fe 990 return glossary_search($course,$searchterms,$extended,$glossary);
991}
992
49bcd737 993/**
994 * if return=html, then return a html string.
995 * if return=text, then return a text-only string.
996 * otherwise, print HTML for non-images, and return image HTML
997 * if attachment is an image, $align set its aligment.
998 * @param object $entry
999 * @param object $cm
1000 * @param string $type html, txt, empty
1001 * @param string $align left or right
1002 * @return image string or nothing depending on $type param
1003 */
1004function glossary_print_attachments($entry, $cm, $type=NULL, $align="left") {
ae8c3566 1005 global $CFG, $DB;
e179048e 1006
49bcd737 1007 if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) {
1008 return '';
e179048e 1009 }
a02c77dc 1010
49bcd737 1011 if ($entry->sourceglossaryid == $cm->instance) {
1012 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
1013 return '';
a02c77dc 1014 }
49bcd737 1015 $filecontext = get_context_instance(CONTEXT_MODULE, $maincm->id);
e179048e 1016
49bcd737 1017 } else {
1018 $filecontext = $context;
1019 }
e179048e 1020
49bcd737 1021 $strattachment = get_string('attachment', 'glossary');
e179048e 1022
49bcd737 1023 $fs = get_file_storage();
1024 $browser = get_file_browser();
e179048e 1025
49bcd737 1026 $imagereturn = '';
1027 $output = '';
e179048e 1028
49bcd737 1029 if ($files = $fs->get_area_files($filecontext->id, 'glossary_attachment', $entry->id, "timemodified", false)) {
1030 foreach ($files as $file) {
1031 $filename = $file->get_filename();
1032 $mimetype = $file->get_mimetype();
1033 $icon = mimeinfo_from_type('icon', $mimetype);
1034 $iconimage = '<img src="'.$CFG->pixpath.'/f/'.$icon.'" class="icon" alt="'.$icon.'" />';
4eef1399 1035 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$context->id.'/glossary_attachment/'.$entry->id.'/'.$filename);
e179048e 1036
49bcd737 1037 if ($type == 'html') {
1038 $output .= "<a href=\"$path\">$iconimage</a> ";
1039 $output .= "<a href=\"$path\">".s($filename)."</a>";
1040 $output .= "<br />";
18b8fbfa 1041
49bcd737 1042 } else if ($type == 'text') {
1043 $output .= "$strattachment ".s($filename).":\n$path\n";
e179048e 1044
49bcd737 1045 } else {
1046 if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) {
1047 // Image attachments don't get printed as links
1048 $imagereturn .= "<br /><img src=\"$path\" alt=\"\" />";
1049 } else {
1050 $output .= "<a href=\"$path\">$iconimage</a> ";
1051 $output .= filter_text("<a href=\"$path\">".s($filename)."</a>");
1052 $output .= '<br />';
18b8fbfa 1053 }
e179048e 1054 }
1055 }
1056 }
49bcd737 1057
1058 if ($type) {
1059 return $output;
1060 } else {
1061 echo $output;
1062 return $imagereturn;
1063 }
e179048e 1064}
1065
aa9bcfcd 1066/**
1067 * Lists all browsable file areas
1068 */
1069function glossary_get_file_areas($course, $cm, $context) {
1070 $areas = array();
aa9bcfcd 1071 return $areas;
1072}
1073
49bcd737 1074/**
1075 * Serves the glossary attachments. Implements needed access control ;-)
1076 */
1077function glossary_pluginfile($course, $cminfo, $context, $filearea, $args) {
1078 global $CFG, $DB;
a02c77dc 1079
49bcd737 1080 if (!$cminfo->uservisible) {
1081 return false;
1082 }
e179048e 1083
dc5c2bd9 1084 if ($filearea === 'glossary_attachment' or $filearea === 'glossary_entry') {
aa9bcfcd 1085 $entryid = (int)array_shift($args);
49bcd737 1086
aa9bcfcd 1087 if (!$entry = $DB->get_record('glossary_entries', array('id'=>$entryid))) {
1088 return false;
e179048e 1089 }
49bcd737 1090
aa9bcfcd 1091 if (!$glossary = $DB->get_record('glossary', array('id'=>$cminfo->instance))) {
1092 return false;
1093 }
e179048e 1094
aa9bcfcd 1095 if ($glossary->defaultapproval and !$entry->approved and !has_capability('mod/glossary:approve', $context)) {
1096 return false;
1097 }
1098
1099 if ($entry->glossaryid == $cminfo->instance) {
1100 $filecontext = $context;
1101
1102 } else if ($entry->sourceglossaryid == $cminfo->instance) {
1103 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
1104 print_error('invalidcoursemodule');
1105 }
1106 $filecontext = get_context_instance(CONTEXT_MODULE, $maincm->id);
1107
1108 } else {
1109 return false;
1110 }
1111
1112 $relativepath = '/'.implode('/', $args);
1113 $fullpath = $filecontext->id.$filearea.$entryid.$relativepath;
1114
1115 $fs = get_file_storage();
1116 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1117 return false;
1118 }
1119
1120 // finally send the file
1121 send_stored_file($file, 0, 0, true); // download MUST be forced - security!
e179048e 1122 }
1123
aa9bcfcd 1124 return false;
e179048e 1125}
1126
ad58adac 1127function glossary_print_tabbed_table_end() {
9ca8cc08 1128 echo "</div></div>";
06d94a52 1129}
1130
1ac87c73 1131function glossary_print_approval_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
a359c29b 1132 if ($glossary->showalphabet) {
7a3ec1af 1133 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
677038ee 1134 }
1ac87c73 1135 glossary_print_special_links($cm, $glossary, $mode, $hook);
c76e673a 1136
c4a35419 1137 glossary_print_alphabet_links($cm, $glossary, $mode, $hook,$sortkey, $sortorder);
c76e673a 1138
1ac87c73 1139 glossary_print_all_links($cm, $glossary, $mode, $hook);
894ff63f 1140
db87439a 1141 glossary_print_sorting_links($cm, $mode, 'CREATION', 'asc');
c76e673a 1142}
1143
1ac87c73 1144function glossary_print_import_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
7a3ec1af 1145 echo '<div class="glossaryexplain">' . get_string("explainimport","glossary") . '</div>';
748b1932 1146}
1147
1ac87c73 1148function glossary_print_export_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
7a3ec1af 1149 echo '<div class="glossaryexplain">' . get_string("explainexport","glossary") . '</div>';
748b1932 1150}
1151
1ac87c73 1152function glossary_print_alphabet_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1153 if ( $mode != 'date' ) {
a359c29b 1154 if ($glossary->showalphabet) {
7a3ec1af 1155 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
c197e607 1156 }
c76e673a 1157
1ac87c73 1158 glossary_print_special_links($cm, $glossary, $mode, $hook);
c76e673a 1159
c4a35419 1160 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
c197e607 1161
1ac87c73 1162 glossary_print_all_links($cm, $glossary, $mode, $hook);
c197e607 1163 } else {
1ac87c73 1164 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
1165 }
1166}
1167
1168function glossary_print_author_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
a359c29b 1169 if ($glossary->showalphabet) {
7a3ec1af 1170 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
c197e607 1171 }
1ac87c73 1172
c4a35419 1173 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
1ac87c73 1174 glossary_print_all_links($cm, $glossary, $mode, $hook);
7a3ec1af 1175 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
c76e673a 1176}
1177
1ac87c73 1178function glossary_print_categories_menu($cm, $glossary, $hook, $category) {
ae8c3566 1179 global $CFG, $DB;
a02c77dc 1180
dabfd0ed 1181 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
3a26f0ea 1182
41905731 1183 echo '<table border="0" width="100%">';
c197e607 1184 echo '<tr>';
c76e673a 1185
5bd76d7f 1186 echo '<td align="center" style="width:20%">';
0468976c 1187 if (has_capability('mod/glossary:managecategories', $context)) {
c76e673a 1188 $options['id'] = $cm->id;
1ac87c73 1189 $options['mode'] = 'cat';
1190 $options['hook'] = $hook;
c76e673a 1191 echo print_single_button("editcategories.php", $options, get_string("editcategories","glossary"), "get");
1192 }
c197e607 1193 echo '</td>';
c76e673a 1194
5bd76d7f 1195 echo '<td align="center" style="width:60%">';
c197e607 1196 echo '<b>';
c76e673a 1197
1198 $menu[GLOSSARY_SHOW_ALL_CATEGORIES] = get_string("allcategories","glossary");
1199 $menu[GLOSSARY_SHOW_NOT_CATEGORISED] = get_string("notcategorised","glossary");
677038ee 1200
ae8c3566 1201 $categories = $DB->get_records("glossary_categories", array("glossaryid"=>$glossary->id), "name ASC");
c197e607 1202 $selected = '';
c76e673a 1203 if ( $categories ) {
1204 foreach ($categories as $currentcategory) {
1205 $url = $currentcategory->id;
1206 if ( $category ) {
1207 if ($currentcategory->id == $category->id) {
1208 $selected = $url;
1209 }
1210 }
ae06e00e 1211 $menu[$url] = clean_text($currentcategory->name); //Only clean, not filters
c76e673a 1212 }
1213 }
1214 if ( !$selected ) {
1215 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1216 }
1217
1218 if ( $category ) {
5bd76d7f 1219 echo format_text($category->name, FORMAT_PLAIN);
c76e673a 1220 } else {
1ac87c73 1221 if ( $hook == GLOSSARY_SHOW_NOT_CATEGORISED ) {
c76e673a 1222
1223 echo get_string("entrieswithoutcategory","glossary");
1224 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1225
1ac87c73 1226 } elseif ( $hook == GLOSSARY_SHOW_ALL_CATEGORIES ) {
c76e673a 1227
1228 echo get_string("allcategories","glossary");
1229 $selected = GLOSSARY_SHOW_ALL_CATEGORIES;
1230
1231 }
1232 }
c197e607 1233 echo '</b></td>';
5bd76d7f 1234 echo '<td align="center" style="width:20%">';
c76e673a 1235
839f2456 1236 echo popup_form("$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=cat&amp;hook=", $menu, "catmenu", $selected, "",
c76e673a 1237 "", "", false);
677038ee 1238
c197e607 1239 echo '</td>';
1240 echo '</tr>';
c76e673a 1241
c197e607 1242 echo '</table>';
c76e673a 1243}
1244
1ac87c73 1245function glossary_print_all_links($cm, $glossary, $mode, $hook) {
a02c77dc 1246global $CFG;
a359c29b 1247 if ( $glossary->showall) {
c76e673a 1248 $strallentries = get_string("allentries", "glossary");
1ac87c73 1249 if ( $hook == 'ALL' ) {
c76e673a 1250 echo "<b>$strallentries</b>";
1251 } else {
1252 $strexplainall = strip_tags(get_string("explainall","glossary"));
839f2456 1253 echo "<a title=\"$strexplainall\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=ALL\">$strallentries</a>";
c76e673a 1254 }
1255 }
1256}
1257
1ac87c73 1258function glossary_print_special_links($cm, $glossary, $mode, $hook) {
c76e673a 1259global $CFG;
a359c29b 1260 if ( $glossary->showspecial) {
c76e673a 1261 $strspecial = get_string("special", "glossary");
1ac87c73 1262 if ( $hook == 'SPECIAL' ) {
677038ee 1263 echo "<b>$strspecial</b> | ";
1264 } else {
1265 $strexplainspecial = strip_tags(get_string("explainspecial","glossary"));
839f2456 1266 echo "<a title=\"$strexplainspecial\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=SPECIAL\">$strspecial</a> | ";
677038ee 1267 }
914cb260 1268 }
c76e673a 1269}
677038ee 1270
c4a35419 1271function glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder) {
c76e673a 1272global $CFG;
a359c29b 1273 if ( $glossary->showalphabet) {
c4274149 1274 $alphabet = explode(",", get_string("alphabet"));
677038ee 1275 $letters_by_line = 14;
1276 for ($i = 0; $i < count($alphabet); $i++) {
1ac87c73 1277 if ( $hook == $alphabet[$i] and $hook) {
677038ee 1278 echo "<b>$alphabet[$i]</b>";
1279 } else {
82015ed2 1280 echo "<a href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=".urlencode($alphabet[$i])."&amp;sortkey=$sortkey&amp;sortorder=$sortorder\">$alphabet[$i]</a>";
677038ee 1281 }
1282 if ((int) ($i % $letters_by_line) != 0 or $i == 0) {
c197e607 1283 echo ' | ';
677038ee 1284 } else {
a9ef4a63 1285 echo '<br />';
677038ee 1286 }
767a31c3 1287 }
677038ee 1288 }
c76e673a 1289}
1290
1ac87c73 1291function glossary_print_sorting_links($cm, $mode, $sortkey = '',$sortorder = '') {
c76e673a 1292global $CFG;
677038ee 1293
c4a35419 1294 $asc = get_string("ascending","glossary");
1295 $desc = get_string("descending","glossary");
1296 $bopen = '<b>';
1297 $bclose = '</b>';
a02c77dc 1298
c197e607 1299 $neworder = '';
468c120a 1300 $currentorder = '';
1301 $currentsort = '';
677038ee 1302 if ( $sortorder ) {
c197e607 1303 if ( $sortorder == 'asc' ) {
468c120a 1304 $currentorder = $asc;
839f2456 1305 $neworder = '&amp;sortorder=desc';
468c120a 1306 $newordertitle = get_string('changeto', 'glossary', $desc);
677038ee 1307 } else {
468c120a 1308 $currentorder = $desc;
839f2456 1309 $neworder = '&amp;sortorder=asc';
468c120a 1310 $newordertitle = get_string('changeto', 'glossary', $asc);
677038ee 1311 }
468c120a 1312 $icon = " <img src=\"$sortorder.gif\" class=\"icon\" alt=\"$newordertitle\" />";
677038ee 1313 } else {
c4a35419 1314 if ( $sortkey != 'CREATION' and $sortkey != 'UPDATE' and
1315 $sortkey != 'FIRSTNAME' and $sortkey != 'LASTNAME' ) {
677038ee 1316 $icon = "";
c4a35419 1317 $newordertitle = $asc;
677038ee 1318 } else {
c4a35419 1319 $newordertitle = $desc;
839f2456 1320 $neworder = '&amp;sortorder=desc';
468c120a 1321 $icon = ' <img src="asc.gif" class="icon" alt="'.$newordertitle.'" />';
677038ee 1322 }
1323 }
c4a35419 1324 $ficon = '';
1325 $fneworder = '';
1326 $fbtag = '';
1327 $fendbtag = '';
1328
1329 $sicon = '';
1330 $sneworder = '';
ae078733 1331
1332 $sbtag = '';
1333 $fbtag = '';
1334 $fendbtag = '';
1335 $sendbtag = '';
1336
c4a35419 1337 $sendbtag = '';
1338
1339 if ( $sortkey == 'CREATION' or $sortkey == 'FIRSTNAME' ) {
1340 $ficon = $icon;
1341 $fneworder = $neworder;
1342 $fordertitle = $newordertitle;
1343 $sordertitle = $asc;
1344 $fbtag = $bopen;
1345 $fendbtag = $bclose;
1346 } elseif ($sortkey == 'UPDATE' or $sortkey == 'LASTNAME') {
1347 $sicon = $icon;
1348 $sneworder = $neworder;
1349 $fordertitle = $asc;
1350 $sordertitle = $newordertitle;
1351 $sbtag = $bopen;
1352 $sendbtag = $bclose;
677038ee 1353 } else {
c4a35419 1354 $fordertitle = $asc;
1355 $sordertitle = $asc;
677038ee 1356 }
c4a35419 1357
1358 if ( $sortkey == 'CREATION' or $sortkey == 'UPDATE' ) {
1359 $forder = 'CREATION';
1360 $sorder = 'UPDATE';
1361 $fsort = get_string("sortbycreation", "glossary");
1362 $ssort = get_string("sortbylastupdate", "glossary");
1363
468c120a 1364 $currentsort = $fsort;
1365 if ($sortkey == 'UPDATE') {
1366 $currentsort = $ssort;
1367 }
c4a35419 1368 $sort = get_string("sortchronogically", "glossary");
1369 } elseif ( $sortkey == 'FIRSTNAME' or $sortkey == 'LASTNAME') {
1370 $forder = 'FIRSTNAME';
1371 $sorder = 'LASTNAME';
1372 $fsort = get_string("firstname");
1373 $ssort = get_string("lastname");
1374
468c120a 1375 $currentsort = $fsort;
1376 if ($sortkey == 'LASTNAME') {
1377 $currentsort = $ssort;
1378 }
c4a35419 1379 $sort = get_string("sortby", "glossary");
1380 }
468c120a 1381 $current = '<span class="accesshide">'.get_string('current', 'glossary', "$currentsort $currentorder").'</span>';
1382 echo "<br />$current $sort: $sbtag<a title=\"$ssort $sordertitle\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;sortkey=$sorder$sneworder&amp;mode=$mode\">$ssort$sicon</a>$sendbtag | ".
839f2456 1383 "$fbtag<a title=\"$fsort $fordertitle\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;sortkey=$forder$fneworder&amp;mode=$mode\">$fsort$ficon</a>$fendbtag<br />";
fb443f1a 1384}
ad58adac 1385
1386function glossary_sort_entries ( $entry0, $entry1 ) {
a02c77dc 1387
95d56829 1388 if ( moodle_strtolower(ltrim($entry0->concept)) < moodle_strtolower(ltrim($entry1->concept)) ) {
ad58adac 1389 return -1;
95d56829 1390 } elseif ( moodle_strtolower(ltrim($entry0->concept)) > moodle_strtolower(ltrim($entry1->concept)) ) {
ad58adac 1391 return 1;
1392 } else {
1393 return 0;
1394 }
1395}
1396
ed0201dd 1397function glossary_print_comment($course, $cm, $glossary, $entry, $comment) {
ae8c3566 1398 global $CFG, $USER, $DB;
a02c77dc 1399
bbbf2d40 1400 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
ed0201dd 1401
ae8c3566 1402 $user = $DB->get_record('user', array('id'=>$comment->userid));
3a26f0ea 1403 $strby = get_string('writtenby','glossary');
26663a23 1404 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
ed0201dd 1405
36a2b6bd 1406 echo '<div class="boxaligncenter">';
3a26f0ea 1407 echo '<table class="glossarycomment" cellspacing="0">';
1408 echo '<tr valign="top">';
eee75231 1409 echo '<td class="left picture">';
65bcf17b 1410 print_user_picture($user, $course->id, $user->picture);
3a26f0ea 1411 echo '</td>';
1412 echo '<td class="entryheader">';
c07ca217 1413
26663a23 1414 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
e6d45048 1415 $by = new object();
c07ca217 1416 $by->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$user->id.'&amp;course='.$course->id.'">'.$fullname.'</a>';
1417 $by->date = userdate($comment->timemodified);
1418 echo '<span class="author">'.get_string('bynameondate', 'forum', $by).'</span>';
1419
3a26f0ea 1420 echo '</td></tr>';
ed0201dd 1421
3a26f0ea 1422 echo '<tr valign="top"><td class="left side">';
1423 echo '&nbsp;';
1424 echo '</td><td class="entry">';
072f7533 1425
7d8a3cb0 1426 $options = new object();
cbc2b5df 1427 $options->trusted = $comment->entrycommenttrust;
1428 echo format_text($comment->entrycomment, $comment->entrycommentformat, $options);
072f7533 1429
3a26f0ea 1430 echo '<div class="icons commands">';
1431
3a512f86 1432 $ineditperiod = ((time() - $comment->timemodified < $CFG->maxeditingtime) || $glossary->editalways);
0468976c 1433 if ( ($glossary->allowcomments && $ineditperiod && $USER->id == $comment->userid) || has_capability('mod/glossary:managecomments', $context)) {
989c16ee 1434 echo "<a href=\"comment.php?id=$comment->id&amp;action=edit\"><img
0d905d9f 1435 alt=\"" . get_string("edit") . "\" src=\"$CFG->pixpath/t/edit.gif\" class=\"iconsmall\" /></a> ";
c197e607 1436 }
0468976c 1437 if ( ($glossary->allowcomments && $USER->id == $comment->userid) || has_capability('mod/glossary:managecomments', $context) ) {
989c16ee 1438 echo "<a href=\"comment.php?id=$comment->id&amp;action=delete\"><img
0d905d9f 1439 alt=\"" . get_string("delete") . "\" src=\"$CFG->pixpath/t/delete.gif\" class=\"iconsmall\" /></a>";
c197e607 1440 }
a02c77dc 1441
3a26f0ea 1442 echo '</div></td></tr>';
36a2b6bd 1443 echo '</table></div>';
ed0201dd 1444
ed0201dd 1445}
1446
63dd5fb2 1447function glossary_print_entry_ratings($course, $entry, $ratings = NULL) {
ae8c3566 1448 global $USER, $CFG, $DB;
a02c77dc 1449
ae8c3566 1450 $glossary = $DB->get_record('glossary', array('id'=>$entry->glossaryid));
1451 $glossarymod = $DB->get_record('modules', array('name'=>'glossary'));
1452 $cm = $DB->get_record_sql("SELECT *
1453 FROM {course_modules}
1454 WHERE course = ? AND module = ? and instance = ?", array($course->id, $glossarymod->id, $glossary->id));
a02c77dc 1455
bbbf2d40 1456 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
a359c29b 1457
63dd5fb2 1458 $ratingsmenuused = false;
1459 if (!empty($ratings) and !empty($USER->id)) {
1460 $useratings = true;
1461 if ($ratings->assesstimestart and $ratings->assesstimefinish) {
1462 if ($entry->timecreated < $ratings->assesstimestart or $entry->timecreated > $ratings->assesstimefinish) {
1463 $useratings = false;
1464 }
1465 }
1466 if ($useratings) {
0468976c 1467 if (has_capability('mod/glossary:viewrating', $context)) {
63dd5fb2 1468 glossary_print_ratings_mean($entry->id, $ratings->scale);
1469 if ($USER->id != $entry->userid) {
1470 glossary_print_rating_menu($entry->id, $USER->id, $ratings->scale);
1471 $ratingsmenuused = true;
1472 }
1473 } else if ($USER->id == $entry->userid) {
1474 glossary_print_ratings_mean($entry->id, $ratings->scale);
1475 } else if (!empty($ratings->allow) ) {
1476 glossary_print_rating_menu($entry->id, $USER->id, $ratings->scale);
1477 $ratingsmenuused = true;
1478 }
1479 }
1480 }
1481 return $ratingsmenuused;
1482}
1483
b1918034 1484function glossary_print_dynaentry($courseid, $entries, $displayformat = -1) {
ae8c3566 1485 global $USER,$CFG, $DB;
cca6f7f1 1486
36a2b6bd 1487 echo '<div class="boxaligncenter">';
a8466100 1488 echo '<table class="glossarypopup" cellspacing="0"><tr>';
1489 echo '<td>';
1d9ddaaf 1490 if ( $entries ) {
1491 foreach ( $entries as $entry ) {
ae8c3566 1492 if (! $glossary = $DB->get_record('glossary', array('id'=>$entry->glossaryid))) {
5973a4c4 1493 print_error('invalidid', 'glossary');
cca6f7f1 1494 }
ae8c3566 1495 if (! $course = $DB->get_record('course', array('id'=>$glossary->course))) {
5973a4c4 1496 print_error('coursemisconf');
1d9ddaaf 1497 }
a8466100 1498 if (!$cm = get_coursemodule_from_instance('glossary', $entry->glossaryid, $glossary->course) ) {
5973a4c4 1499 print_error('invalidid', 'glossary');
1d9ddaaf 1500 }
1f63b7c6 1501
1502 //If displayformat is present, override glossary->displayformat
a359c29b 1503 if ($displayformat < 0) {
1f63b7c6 1504 $dp = $glossary->displayformat;
a359c29b 1505 } else {
1f63b7c6 1506 $dp = $displayformat;
1507 }
1508
a359c29b 1509 //Get popupformatname
ae8c3566 1510 $format = $DB->get_record('glossary_formats', array('name'=>$dp));
a359c29b 1511 $displayformat = $format->popupformatname;
1512
1513 //Check displayformat variable and set to default if necessary
1514 if (!$displayformat) {
1515 $displayformat = 'dictionary';
584dcac9 1516 }
1f63b7c6 1517
a359c29b 1518 $formatfile = $CFG->dirroot.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
1519 $functionname = 'glossary_show_entry_'.$displayformat;
1520
1521 if (file_exists($formatfile)) {
1522 include_once($formatfile);
1523 if (function_exists($functionname)) {
1524 $functionname($course, $cm, $glossary, $entry,'','','','');
1525 }
1526 }
cca6f7f1 1527 }
cca6f7f1 1528 }
a8466100 1529 echo '</td>';
36a2b6bd 1530 echo '</tr></table></div>';
1d9ddaaf 1531}
4f4ca7b5 1532
6c0a9413 1533function glossary_generate_export_csv($entries, $aliases, $categories) {
1534 global $CFG;
1535 $csv = '';
1536 $delimiter = '';
1537 require_once($CFG->libdir . '/csvlib.class.php');
1538 $delimiter = csv_import_reader::get_delimiter('comma');
1539 $csventries = array(0 => array(get_string('concept', 'glossary'), get_string('definition', 'glossary')));
1540 $csvaliases = array(0 => array());
1541 $csvcategories = array(0 => array());
1542 $aliascount = 0;
1543 $categorycount = 0;
1544
1545 foreach ($entries as $entry) {
1546 $thisaliasesentry = array();
1547 $thiscategoriesentry = array();
cbc2b5df 1548 $thiscsventry = array($entry->concept, nl2br($entry->definition));
6c0a9413 1549
1550 if (array_key_exists($entry->id, $aliases) && is_array($aliases[$entry->id])) {
1551 $thiscount = count($aliases[$entry->id]);
1552 if ($thiscount > $aliascount) {
1553 $aliascount = $thiscount;
1554 }
1555 foreach ($aliases[$entry->id] as $alias) {
1556 $thisaliasesentry[] = trim($alias);
1557 }
1558 }
1559 if (array_key_exists($entry->id, $categories) && is_array($categories[$entry->id])) {
1560 $thiscount = count($categories[$entry->id]);
1561 if ($thiscount > $categorycount) {
1562 $categorycount = $thiscount;
1563 }
1564 foreach ($categories[$entry->id] as $catentry) {
1565 $thiscategoriesentry[] = trim($catentry);
1566 }
1567 }
1568 $csventries[$entry->id] = $thiscsventry;
1569 $csvaliases[$entry->id] = $thisaliasesentry;
1570 $csvcategories[$entry->id] = $thiscategoriesentry;
1571
1572 }
1573 $returnstr = '';
1574 foreach ($csventries as $id => $row) {
1575 $aliasstr = '';
1576 $categorystr = '';
1577 if ($id == 0) {
1578 $aliasstr = get_string('alias', 'glossary');
1579 $categorystr = get_string('category', 'glossary');
1580 }
1581 $row = array_merge($row, array_pad($csvaliases[$id], $aliascount, $aliasstr), array_pad($csvcategories[$id], $categorycount, $categorystr));
1582 $returnstr .= '"' . implode('"' . $delimiter . '"', $row) . '"' . "\n";
1583 }
1584 return $returnstr;
1585}
1586
1ac87c73 1587function glossary_generate_export_file($glossary, $hook = "", $hook = 0) {
ae8c3566 1588 global $CFG, $DB;
212039c0 1589
1590 $co = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1591
1592 $co .= glossary_start_tag("GLOSSARY",0,true);
1593 $co .= glossary_start_tag("INFO",1,true);
1594 $co .= glossary_full_tag("NAME",2,false,$glossary->name);
1595 $co .= glossary_full_tag("INTRO",2,false,$glossary->intro);
212039c0 1596 $co .= glossary_full_tag("ALLOWDUPLICATEDENTRIES",2,false,$glossary->allowduplicatedentries);
1597 $co .= glossary_full_tag("DISPLAYFORMAT",2,false,$glossary->displayformat);
1598 $co .= glossary_full_tag("SHOWSPECIAL",2,false,$glossary->showspecial);
1599 $co .= glossary_full_tag("SHOWALPHABET",2,false,$glossary->showalphabet);
1600 $co .= glossary_full_tag("SHOWALL",2,false,$glossary->showall);
1601 $co .= glossary_full_tag("ALLOWCOMMENTS",2,false,$glossary->allowcomments);
1602 $co .= glossary_full_tag("USEDYNALINK",2,false,$glossary->usedynalink);
1603 $co .= glossary_full_tag("DEFAULTAPPROVAL",2,false,$glossary->defaultapproval);
1604 $co .= glossary_full_tag("GLOBALGLOSSARY",2,false,$glossary->globalglossary);
1605 $co .= glossary_full_tag("ENTBYPAGE",2,false,$glossary->entbypage);
4f4ca7b5 1606
ae8c3566 1607 if ( $entries = $DB->get_records("glossary_entries", array("glossaryid"=>$glossary->id))) {
212039c0 1608 $co .= glossary_start_tag("ENTRIES",2,true);
748b1932 1609 foreach ($entries as $entry) {
046a797c 1610 $permissiongranted = 1;
1ac87c73 1611 if ( $hook ) {
1612 switch ( $hook ) {
046a797c 1613 case "ALL":
1614 case "SPECIAL":
1615 break;
1616 default:
1ac87c73 1617 $permissiongranted = ($entry->concept[ strlen($hook)-1 ] == $hook);
046a797c 1618 break;
1619 }
1620 }
1ac87c73 1621 if ( $hook ) {
1622 switch ( $hook ) {
046a797c 1623 case GLOSSARY_SHOW_ALL_CATEGORIES:
1624 break;
1625 case GLOSSARY_SHOW_NOT_CATEGORISED:
ae8c3566 1626 $permissiongranted = !$DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id));
046a797c 1627 break;
1628 default:
ae8c3566 1629 $permissiongranted = $DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id, "categoryid"=>$hook));
046a797c 1630 break;
1631 }
1632 }
1633 if ( $entry->approved and $permissiongranted ) {
212039c0 1634 $co .= glossary_start_tag("ENTRY",3,true);
1635 $co .= glossary_full_tag("CONCEPT",4,false,trim($entry->concept));
cbc2b5df 1636 $co .= glossary_full_tag("DEFINITION",4,false,$entry->definition);
1637 $co .= glossary_full_tag("FORMAT",4,false,$entry->definitionformat);
212039c0 1638 $co .= glossary_full_tag("USEDYNALINK",4,false,$entry->usedynalink);
1639 $co .= glossary_full_tag("CASESENSITIVE",4,false,$entry->casesensitive);
1640 $co .= glossary_full_tag("FULLMATCH",4,false,$entry->fullmatch);
1641 $co .= glossary_full_tag("TEACHERENTRY",4,false,$entry->teacherentry);
748b1932 1642
ae8c3566 1643 if ( $aliases = $DB->get_records("glossary_alias", array("entryid"=>$entry->id))) {
212039c0 1644 $co .= glossary_start_tag("ALIASES",4,true);
7965be79 1645 foreach ($aliases as $alias) {
212039c0 1646 $co .= glossary_start_tag("ALIAS",5,true);
1647 $co .= glossary_full_tag("NAME",6,false,trim($alias->alias));
1648 $co .= glossary_end_tag("ALIAS",5,true);
7965be79 1649 }
212039c0 1650 $co .= glossary_end_tag("ALIASES",4,true);
7965be79 1651 }
ae8c3566 1652 if ( $catentries = $DB->get_records("glossary_entries_categories", array("entryid"=>$entry->id))) {
212039c0 1653 $co .= glossary_start_tag("CATEGORIES",4,true);
748b1932 1654 foreach ($catentries as $catentry) {
ae8c3566 1655 $category = $DB->get_record("glossary_categories", array("id"=>$catentry->categoryid));
748b1932 1656
212039c0 1657 $co .= glossary_start_tag("CATEGORY",5,true);
1658 $co .= glossary_full_tag("NAME",6,false,$category->name);
1659 $co .= glossary_full_tag("USEDYNALINK",6,false,$category->usedynalink);
1660 $co .= glossary_end_tag("CATEGORY",5,true);
748b1932 1661 }
212039c0 1662 $co .= glossary_end_tag("CATEGORIES",4,true);
748b1932 1663 }
4f4ca7b5 1664
212039c0 1665 $co .= glossary_end_tag("ENTRY",3,true);
4f4ca7b5 1666 }
1667 }
212039c0 1668 $co .= glossary_end_tag("ENTRIES",2,true);
748b1932 1669
4f4ca7b5 1670 }
748b1932 1671
1672
212039c0 1673 $co .= glossary_end_tag("INFO",1,true);
1674 $co .= glossary_end_tag("GLOSSARY",0,true);
4f4ca7b5 1675
212039c0 1676 return $co;
4f4ca7b5 1677}
212039c0 1678/// Functions designed by Eloy Lafuente
1679/// Functions to create, open and write header of the xml file
4f4ca7b5 1680
212039c0 1681// Read import file and convert to current charset
748b1932 1682function glossary_read_imported_file($file) {
9f79b50f 1683 require_once "../../lib/xmlize.php";
1684 global $CFG;
1685
748b1932 1686 $h = fopen($file,"r");
1687 $line = '';
1688 if ($h) {
1689 while ( !feof($h) ) {
b9656030 1690 $char = fread($h,1024);
748b1932 1691 $line .= $char;
1692 }
1693 fclose($h);
894ff63f 1694 }
792a76d8 1695 return xmlize($line, 0);
748b1932 1696}
4f4ca7b5 1697
a02c77dc 1698//Return the xml start tag
4f4ca7b5 1699function glossary_start_tag($tag,$level=0,$endline=false) {
1700 if ($endline) {
1701 $endchar = "\n";
1702 } else {
1703 $endchar = "";
1704 }
1705 return str_repeat(" ",$level*2)."<".strtoupper($tag).">".$endchar;
1706}
a02c77dc 1707
1708//Return the xml end tag
4f4ca7b5 1709function glossary_end_tag($tag,$level=0,$endline=true) {
1710 if ($endline) {
1711 $endchar = "\n";
1712 } else {
1713 $endchar = "";
1714 }
1715 return str_repeat(" ",$level*2)."</".strtoupper($tag).">".$endchar;
1716}
a02c77dc 1717
4f4ca7b5 1718//Return the start tag, the contents and the end tag
212039c0 1719function glossary_full_tag($tag,$level=0,$endline=true,$content) {
9f79b50f 1720 global $CFG;
a02c77dc 1721
4f4ca7b5 1722 $st = glossary_start_tag($tag,$level,$endline);
212039c0 1723 $co = preg_replace("/\r\n|\r/", "\n", s($content));
4f4ca7b5 1724 $et = glossary_end_tag($tag,0,true);
1725 return $st.$co.$et;
1726}
1727
63dd5fb2 1728/*
a02c77dc 1729* Adding grading functions
63dd5fb2 1730*/
1731
1732function glossary_get_ratings($entryid, $sort="u.firstname ASC") {
1733/// Returns a list of ratings for a particular entry - sorted.
ae8c3566 1734 global $DB;
1735 return $DB->get_records_sql("SELECT u.*, r.rating, r.time
1736 FROM {glossary_ratings} r, {user} u
1737 WHERE r.entryid = ? AND r.userid = u.id
1738 ORDER BY $sort", array($entryid));
63dd5fb2 1739}
1740
63dd5fb2 1741function glossary_count_unrated_entries($glossaryid, $userid) {
1742// How many unrated entries are in the given glossary for a given user?
ae8c3566 1743 global $DB;
1744 if ($entries = $DB->get_record_sql("SELECT count('x') as num
1745 FROM {glossary_entries}
1746 WHERE glossaryid = ? AND userid <> ?", array($glossaryid, $userid))) {
1747
1748 if ($rated = $DB->get_record_sql("SELECT count(*) as num
1749 FROM {glossary_entries} e, {glossary_ratings} r
1750 WHERE e.glossaryid = ? AND e.id = r.entryid
1751 AND r.userid = ?", array($glossaryid, $userid))) {
63dd5fb2 1752 $difference = $entries->num - $rated->num;
1753 if ($difference > 0) {
1754 return $difference;
1755 } else {
1756 return 0; // Just in case there was a counting error
1757 }
1758 } else {
1759 return $entries->num;
1760 }
1761 } else {
1762 return 0;
1763 }
1764}
1765
1766function glossary_print_ratings_mean($entryid, $scale) {
1767/// Print the multiple ratings on a entry given to the current user by others.
1768/// Scale is an array of ratings
1769
1770 static $strrate;
1771
1772 $mean = glossary_get_ratings_mean($entryid, $scale);
a02c77dc 1773
63dd5fb2 1774 if ($mean !== "") {
1775
1776 if (empty($strratings)) {
1777 $strratings = get_string("ratings", "glossary");
1778 }
1779
91b4cb68 1780 echo "$strratings: ";
63dd5fb2 1781 link_to_popup_window ("/mod/glossary/report.php?id=$entryid", "ratings", $mean, 400, 600);
1782 }
1783}
1784
1785
1786function glossary_get_ratings_mean($entryid, $scale, $ratings=NULL) {
1787/// Return the mean rating of a entry given to the current user by others.
1788/// Scale is an array of possible ratings in the scale
1789/// Ratings is an optional simple array of actual ratings (just integers)
ae8c3566 1790 global $DB;
63dd5fb2 1791
1792 if (!$ratings) {
1793 $ratings = array();
ae8c3566 1794 if ($rates = $DB->get_records("glossary_ratings", array("entryid"=>$entryid))) {
63dd5fb2 1795 foreach ($rates as $rate) {
1796 $ratings[] = $rate->rating;
1797 }
1798 }
1799 }
1800
1801 $count = count($ratings);
1802
1803 if ($count == 0) {
1804 return "";
1805
1806 } else if ($count == 1) {
1807 return $scale[$ratings[0]];
1808
1809 } else {
1810 $total = 0;
1811 foreach ($ratings as $rating) {
1812 $total += $rating;
1813 }
1814 $mean = round( ((float)$total/(float)$count) + 0.001); // Little fudge factor so that 0.5 goes UP
a02c77dc 1815
63dd5fb2 1816 if (isset($scale[$mean])) {
1817 return $scale[$mean]." ($count)";
1818 } else {
1819 return "$mean ($count)"; // Should never happen, hopefully
1820 }
1821 }
1822}
1823
1824function glossary_get_ratings_summary($entryid, $scale, $ratings=NULL) {
1825/// Return a summary of entry ratings given to the current user by others.
1826/// Scale is an array of possible ratings in the scale
1827/// Ratings is an optional simple array of actual ratings (just integers)
ae8c3566 1828 global $DB;
63dd5fb2 1829
1830 if (!$ratings) {
1831 $ratings = array();
ae8c3566 1832 if ($rates = $DB->get_records("glossary_ratings", array("entryid"=>$entryid))) {
63dd5fb2 1833 foreach ($rates as $rate) {
1834 $rating[] = $rate->rating;
1835 }
1836 }
1837 }
1838
1839
1840 if (!$count = count($ratings)) {
1841 return "";
1842 }
1843
1844
1845 foreach ($scale as $key => $scaleitem) {
1846 $sumrating[$key] = 0;
1847 }
1848
1849 foreach ($ratings as $rating) {
1850 $sumrating[$rating]++;
1851 }
1852
1853 $summary = "";
1854 foreach ($scale as $key => $scaleitem) {
1855 $summary = $sumrating[$key].$summary;
1856 if ($key > 1) {
1857 $summary = "/$summary";
1858 }
1859 }
1860 return $summary;
1861}
1862
1863function glossary_print_rating_menu($entryid, $userid, $scale) {
a02c77dc 1864/// Print the menu of ratings as part of a larger form.
63dd5fb2 1865/// If the entry has already been - set that value.
1866/// Scale is an array of ratings
ae8c3566 1867 global $DB;
63dd5fb2 1868
1869 static $strrate;
1870
ae8c3566 1871 if (!$rating = $DB->get_record("glossary_ratings", array("userid"=>$userid, "entryid"=>$entryid))) {
92fac4b2 1872 $rating->rating = -999;
63dd5fb2 1873 }
1874
1875 if (empty($strrate)) {
1876 $strrate = get_string("rate", "glossary");
1877 }
1878
92fac4b2 1879 choose_from_menu($scale, $entryid, $rating->rating, "$strrate...",'',-999);
63dd5fb2 1880}
1881
e2cf5316 1882
1883function glossary_get_paging_bar($totalcount, $page, $perpage, $baseurl, $maxpageallowed=99999, $maxdisplay=20, $separator="&nbsp;", $specialtext="", $specialvalue=-1, $previousandnext = true) {
1884// Returns the html code to represent any pagging bar. Paramenters are:
1885//
1886// Mandatory:
1887// $totalcount: total number of records to be displayed
1888// $page: page currently selected (0 based)
1889// $perpage: number of records per page
1890// $baseurl: url to link in each page, the string 'page=XX' will be added automatically.
1891// Optional:
1892// $maxpageallowed: maximum number of page allowed.
1893// $maxdisplay: maximum number of page links to show in the bar
1894// $separator: string to be used between pages in the bar
1895// $specialtext: string to be showed as an special link
1896// $specialvalue: value (page) to be used in the special link
1897// $previousandnext: to decide if we want the previous and next links
1898//
1899// The function dinamically show the first and last pages, and "scroll" over pages.
1900// Fully compatible with Moodle's print_paging_bar() function. Perhaps some day this
1901// could replace the general one. ;-)
1902
1903 $code = '';
1904
1905 $showspecial = false;
1906 $specialselected = false;
1907
1908 //Check if we have to show the special link
1909 if (!empty($specialtext)) {
1910 $showspecial = true;
1911 }
1912 //Check if we are with the special link selected
1913 if ($showspecial && $page == $specialvalue) {
1914 $specialselected = true;
a02c77dc 1915 }
e2cf5316 1916
1917 //If there are results (more than 1 page)
1918 if ($totalcount > $perpage) {
36a2b6bd 1919 $code .= "<div style=\"text-align:center\">";
e2cf5316 1920 $code .= "<p>".get_string("page").":";
1921
1922 $maxpage = (int)(($totalcount-1)/$perpage);
1923
1924 //Lower and upper limit of page
1925 if ($page < 0) {
1926 $page = 0;
1927 }
1928 if ($page > $maxpageallowed) {
1929 $page = $maxpageallowed;
1930 }
1931 if ($page > $maxpage) {
1932 $page = $maxpage;
1933 }
1934
1935 //Calculate the window of pages
1936 $pagefrom = $page - ((int)($maxdisplay / 2));
1937 if ($pagefrom < 0) {
1938 $pagefrom = 0;
1939 }
1940 $pageto = $pagefrom + $maxdisplay - 1;
1941 if ($pageto > $maxpageallowed) {
1942 $pageto = $maxpageallowed;
1943 }
1944 if ($pageto > $maxpage) {
1945 $pageto = $maxpage;
1946 }
1947
1948 //Some movements can be necessary if don't see enought pages
1949 if ($pageto - $pagefrom < $maxdisplay - 1) {
1950 if ($pageto - $maxdisplay + 1 > 0) {
1951 $pagefrom = $pageto - $maxdisplay + 1;
1952 }
1953 }
1954
1955 //Calculate first and last if necessary
1956 $firstpagecode = '';
1957 $lastpagecode = '';
1958 if ($pagefrom > 0) {
1959 $firstpagecode = "$separator<a href=\"{$baseurl}page=0\">1</a>";
1960 if ($pagefrom > 1) {
1961 $firstpagecode .= "$separator...";
1962 }
1963 }
1964 if ($pageto < $maxpage) {
1965 if ($pageto < $maxpage -1) {
1966 $lastpagecode = "$separator...";
1967 }
1968 $lastpagecode .= "$separator<a href=\"{$baseurl}page=$maxpage\">".($maxpage+1)."</a>";
1969 }
1970
1971 //Previous
1972 if ($page > 0 && $previousandnext) {
1973 $pagenum = $page - 1;
1974 $code .= "&nbsp;(<a href=\"{$baseurl}page=$pagenum\">".get_string("previous")."</a>)&nbsp;";
1975 }
1976
1977 //Add first
1978 $code .= $firstpagecode;
1979
1980 $pagenum = $pagefrom;
1981
1982 //List of maxdisplay pages
1983 while ($pagenum <= $pageto) {
1984 $pagetoshow = $pagenum +1;
1985 if ($pagenum == $page && !$specialselected) {
08ec7ec6 1986 $code .= "$separator<b>$pagetoshow</b>";
e2cf5316 1987 } else {
1988 $code .= "$separator<a href=\"{$baseurl}page=$pagenum\">$pagetoshow</a>";
1989 }
1990 $pagenum++;
1991 }
1992
1993 //Add last
1994 $code .= $lastpagecode;
1995
1996 //Next
1997 if ($page < $maxpage && $page < $maxpageallowed && $previousandnext) {
1998 $pagenum = $page + 1;
1999 $code .= "$separator(<a href=\"{$baseurl}page=$pagenum\">".get_string("next")."</a>)";
2000 }
2001
2002 //Add special
2003 if ($showspecial) {
2004 $code .= '<br />';
2005 if ($specialselected) {
08ec7ec6 2006 $code .= "<b>$specialtext</b>";
e2cf5316 2007 } else {
2008 $code .= "$separator<a href=\"{$baseurl}page=$specialvalue\">$specialtext</a>";
2009 }
2010 }
2011
2012 //End html
2013 $code .= "</p>";
36a2b6bd 2014 $code .= "</div>";
e2cf5316 2015 }
2016
2017 return $code;
2018}
2019
f3221af9 2020function glossary_get_view_actions() {
2021 return array('view','view all','view entry');
2022}
2023
2024function glossary_get_post_actions() {
2025 return array('add category','add comment','add entry','approve entry','delete category','delete comment','delete entry','edit category','update comment','update entry');
2026}
2027
0b5a80a1 2028
2029/**
2030 * Implementation of the function for printing the form elements that control
2031 * whether the course reset functionality affects the glossary.
2032 * @param $mform form passed by reference
2033 */
2034function glossary_reset_course_form_definition(&$mform) {
2035 $mform->addElement('header', 'glossaryheader', get_string('modulenameplural', 'glossary'));
2036 $mform->addElement('checkbox', 'reset_glossary_all', get_string('resetglossariesall','glossary'));
2037
2038 $mform->addElement('select', 'reset_glossary_types', get_string('resetglossaries', 'glossary'),
2039 array('main'=>get_string('mainglossary', 'glossary'), 'secondary'=>get_string('secondaryglossary', 'glossary')), array('multiple' => 'multiple'));
2040 $mform->setAdvanced('reset_glossary_types');
2041 $mform->disabledIf('reset_glossary_types', 'reset_glossary_all', 'checked');
2042
2043 $mform->addElement('checkbox', 'reset_glossary_notenrolled', get_string('deletenotenrolled', 'glossary'));
2044 $mform->disabledIf('reset_glossary_notenrolled', 'reset_glossary_all', 'checked');
2045
2046 $mform->addElement('checkbox', 'reset_glossary_ratings', get_string('deleteallratings'));
2047 $mform->disabledIf('reset_glossary_ratings', 'reset_glossary_all', 'checked');
2048
2049 $mform->addElement('checkbox', 'reset_glossary_comments', get_string('deleteallcomments'));
2050 $mform->disabledIf('reset_glossary_comments', 'reset_glossary_all', 'checked');
2051}
2052
2053/**
2054 * Course reset form defaults.
2055 */
2056function glossary_reset_course_form_defaults($course) {
2057 return array('reset_glossary_all'=>0, 'reset_glossary_ratings'=>1, 'reset_glossary_comments'=>1, 'reset_glossary_notenrolled'=>0);
2058}
2059
2060/**
2061 * Removes all grades from gradebook
2062 * @param int $courseid
2063 * @param string optional type
2064 */
2065function glossary_reset_gradebook($courseid, $type='') {
ae8c3566 2066 global $DB;
0b5a80a1 2067
2068 switch ($type) {
2069 case 'main' : $type = "AND g.mainglossary=1"; break;
2070 case 'secondary' : $type = "AND g.mainglossary=0"; break;
2071 default : $type = ""; //all
2072 }
2073
2074 $sql = "SELECT g.*, cm.idnumber as cmidnumber, g.course as courseid
ae8c3566 2075 FROM {glossary} g, {course_modules} cm, {modules} m
2076 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id AND g.course=? $type";
0b5a80a1 2077
ae8c3566 2078 if ($glossarys = $DB->get_records_sql($sql, array($courseid))) {
0b5a80a1 2079 foreach ($glossarys as $glossary) {
2080 glossary_grade_item_update($glossary, 'reset');
2081 }
2082 }
2083}
2084/**
2085 * Actual implementation of the rest coures functionality, delete all the
2086 * glossary responses for course $data->courseid.
2087 * @param $data the data submitted from the reset course.
2088 * @return array status array
2089 */
2090function glossary_reset_userdata($data) {
ae8c3566 2091 global $CFG, $DB;
0b5a80a1 2092
2093 $componentstr = get_string('modulenameplural', 'glossary');
2094 $status = array();
2095
2096 $allentriessql = "SELECT e.id
ae8c3566 2097 FROM {glossary_entries} e
2098 JOIN {glossary} g ON e.glossaryid = g.id
2099 WHERE g.course = ?";
0b5a80a1 2100
2101 $allglossariessql = "SELECT g.id
ae8c3566 2102 FROM {glossary} g
2103 WHERE g.course = ?";
2104
2105 $params = array($data->courseid);
0b5a80a1 2106
49bcd737 2107 $fs = get_file_storage();
2108
0b5a80a1 2109 // delete entries if requested
2110 if (!empty($data->reset_glossary_all)
2111 or (!empty($data->reset_glossary_types) and in_array('main', $data->reset_glossary_types) and in_array('secondary', $data->reset_glossary_types))) {
2112
ae8c3566 2113 $DB->delete_records_select('glossary_ratings', "entryid IN ($allentriessql)", $params);
2114 $DB->delete_records_select('glossary_comments', "entryid IN ($allentriessql)", $params);
2115 $DB->delete_records_select('glossary_entries', "glossaryid IN ($allglossariessql)", $params);
0b5a80a1 2116
49bcd737 2117 // now get rid of all attachments
ae8c3566 2118 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
0b5a80a1 2119 foreach ($glossaries as $glossaryid=>$unused) {
49bcd737 2120 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2121 continue;
2122 }
2123 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2124 $fs->delete_area_files($context->id, 'glossary_attachment');
0b5a80a1 2125 }
2126 }
2127
2128 // remove all grades from gradebook
2129 if (empty($data->reset_gradebook_grades)) {
2130 glossary_reset_gradebook($data->courseid);
2131 }
2132
2133 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossariesall', 'glossary'), 'error'=>false);
2134
2135 } else if (!empty($data->reset_glossary_types)) {
2136 $mainentriessql = "$allentries AND g.mainglossary=1";
2137 $secondaryentriessql = "$allentries AND g.mainglossary=0";
2138
2139 $mainglossariessql = "$allglossariessql AND g.mainglossary=1";
2140 $secondaryglossariessql = "$allglossariessql AND g.mainglossary=0";
2141
2142 if (in_array('main', $data->reset_glossary_types)) {
ae8c3566 2143 $DB->delete_records_select('glossary_ratings', "entryid IN ($mainentriessql)", $params);
2144 $DB->delete_records_select('glossary_comments', "entryid IN ($mainentriessql)", $params);
2145 $DB->delete_records_select('glossary_entries', "glossaryid IN ($mainglossariessql)", $params);
0b5a80a1 2146
ae8c3566 2147 if ($glossaries = $DB->get_records_sql($mainglossariessql, $params)) {
0b5a80a1 2148 foreach ($glossaries as $glossaryid=>$unused) {
49bcd737 2149 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2150 continue;
2151 }
2152 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2153 $fs->delete_area_files($context->id, 'glossary_attachment');
0b5a80a1 2154 }
2155 }
2156
2157 // remove all grades from gradebook
2158 if (empty($data->reset_gradebook_grades)) {
2159 glossary_reset_gradebook($data->courseid, 'main');
2160 }
2161
2162 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary'), 'error'=>false);
2163
2164 } else if (in_array('secondary', $data->reset_glossary_types)) {
ae8c3566 2165 $DB->delete_records_select('glossary_ratings', "entryid IN ($secondaryentriessql)", $params);
2166 $DB->delete_records_select('glossary_comments', "entryid IN ($secondaryentriessql)", $params);
2167 $DB->delete_records_select('glossary_entries', "glossaryid IN ($secondaryglossariessql)", $params);
0b5a80a1 2168 // remove exported source flag from entries in main glossary
ae8c3566 2169 $DB->execute("UPDATE {glossary_entries
2170 SET sourceglossaryid=0
2171 WHERE glossaryid IN ($mainglossariessql)", $params);
0b5a80a1 2172
ae8c3566 2173 if ($glossaries = $DB->get_records_sql($secondaryglossariessql, $params)) {
0b5a80a1 2174 foreach ($glossaries as $glossaryid=>$unused) {
49bcd737 2175 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2176 continue;
2177 }
2178 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2179 $fs->delete_area_files($context->id, 'glossary_attachment');
0b5a80a1 2180 }
2181 }
2182
2183 // remove all grades from gradebook
2184 if (empty($data->reset_gradebook_grades)) {
2185 glossary_reset_gradebook($data->courseid, 'secondary');
2186 }
2187
2188 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('secondaryglossary', 'glossary'), 'error'=>false);
2189 }
2190 }
2191
2192 // remove entries by users not enrolled into course
2193 if (!empty($data->reset_glossary_notenrolled)) {
2194 $entriessql = "SELECT e.id, e.userid, e.glossaryid, u.id AS userexists, u.deleted AS userdeleted
ae8c3566 2195 FROM {glossary_entries} e
2196 JOIN {glossary} g ON e.glossaryid = g.id
2197 LEFT JOIN {user} u ON e.userid = u.id
2198 WHERE g.course = ? AND e.userid > 0";
0b5a80a1 2199
2200 $course_context = get_context_instance(CONTEXT_COURSE, $data->courseid);
2201 $notenrolled = array();
ae8c3566 2202 if ($rs = $DB->get_recordset_sql($entriessql, $params)) {
2203 foreach ($rs as $entry) {
0b5a80a1 2204 if (array_key_exists($entry->userid, $notenrolled) or !$entry->userexists or $entry->userdeleted
2205 or !has_capability('moodle/course:view', $course_context , $entry->userid)) {
ae8c3566 2206 $DB->delete_records('glossary_ratings', array('entryid'=>$entry->id));
2207 $DB->delete_records('glossary_comments', array('entryid'=>$entry->id));
2208 $DB->delete_records('glossary_entries', array('id'=>$entry->id));
49bcd737 2209
2210 if ($cm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
2211 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2212 $fs->delete_area_files($context->id, 'glossary_attachment', $entry->id);
2213 }
0b5a80a1 2214 }
2215 }
ae8c3566 2216 $rs->close();
0b5a80a1 2217 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'glossary'), 'error'=>false);
2218 }
2219 }
2220
2221 // remove all ratings
2222 if (!empty($data->reset_glossary_ratings)) {
ae8c3566 2223 $DB->delete_records_select('glossary_ratings', "entryid IN ($allentriessql)", $params);
0b5a80a1 2224 // remove all grades from gradebook
2225 if (empty($data->reset_gradebook_grades)) {
2226 glossary_reset_gradebook($data->courseid);
2227 }
2228 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2229 }
2230
2231 // remove all comments
2232 if (!empty($data->reset_glossary_comments)) {
ae8c3566 2233 $DB->delete_records_select('glossary_comments', "entryid IN ($allentriessql)", $params);
0b5a80a1 2234 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2235 }
2236
2237 /// updating dates - shift may be negative too
2238 if ($data->timeshift) {
2239 shift_course_mod_dates('glossary', array('assesstimestart', 'assesstimefinish'), $data->timeshift, $data->courseid);
2240 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2241 }
2242
2243 return $status;
2244}
2245
f432bebf 2246/**
2247 * Returns all other caps used in module
2248 */
2249function glossary_get_extra_capabilities() {
2250 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames', 'moodle/site:trustcontent');
2251}
2252
18a2a0cb 2253/**
2254 * @param string $feature FEATURE_xx constant for requested feature
2255 * @return mixed True if module supports feature, null if doesn't know
2256 */
2257function glossary_supports($feature) {
2258 switch($feature) {
42f103be 2259 case FEATURE_GROUPS: return false;
2260 case FEATURE_GROUPINGS: return false;
2261 case FEATURE_GROUPMEMBERSONLY: return true;
dc5c2bd9 2262 case FEATURE_MOD_INTRO: return true;
18a2a0cb 2263 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
42f103be 2264 case FEATURE_GRADE_HAS_GRADE: return true;
2265 case FEATURE_GRADE_OUTCOMES: return true;
2266
18a2a0cb 2267 default: return null;
2268 }
2269}
2270
6c0a9413 2271class glossary_csv_portfolio_caller extends portfolio_module_caller_base {
2272
2273 private $glossary;
84a44985 2274 private $exportdata;
6c0a9413 2275
0d06b6fd 2276 public static function expected_callbackargs() {
2277 return array(
2278 'id' => true,
2279 );
2280 }
2281
2282 public function load_data() {
6c0a9413 2283 global $DB;
0d06b6fd 2284 if (!$this->cm = get_coursemodule_from_id('glossary', $this->id)) {
34035201 2285 throw new portfolio_caller_exception('invalidid', 'glossary');
6c0a9413 2286 }
2287 if (!$this->glossary = $DB->get_record('glossary', array('id' => $this->cm->instance))) {
34035201 2288 throw new portfolio_caller_exception('invalidid', 'glossary');
6c0a9413 2289 }
2290 $entries = $DB->get_records('glossary_entries', array('glossaryid' => $this->glossary->id));
2291 list($where, $params) = $DB->get_in_or_equal(array_keys($entries));
2292
77ac22a5 2293 $aliases = $DB->get_records_select('glossary_alias', 'entryid ' . $where, $params);
6c0a9413 2294 $categoryentries = $DB->get_records_sql('SELECT ec.entryid, c.name FROM {glossary_entries_categories} ec
2295 JOIN {glossary_categories} c
2296 ON c.id = ec.categoryid
2297 WHERE ec.entryid ' . $where, $params);
2298
84a44985 2299 $this->exportdata = array('entries' => $entries, 'aliases' => $aliases, 'categoryentries' => $categoryentries);
6c0a9413 2300 }
2301
2302 public function expected_time() {
d8606b20 2303 return portfolio_expected_time_db(count($this->exportdata['entries']));
6c0a9413 2304 }
2305
2306 public function get_sha1() {
84a44985 2307 return sha1(serialize($this->exportdata));
6c0a9413 2308 }
2309
d67bfc32 2310 public function prepare_package() {
84a44985 2311 $entries = $this->exportdata['entries'];
6c0a9413 2312 $aliases = array();
2313 $categories = array();
84a44985 2314 if (is_array($this->exportdata['aliases'])) {
2315 foreach ($this->exportdata['aliases'] as $alias) {
6c0a9413 2316 if (!array_key_exists($alias->entryid, $aliases)) {
2317 $aliases[$alias->entryid] = array();
2318 }
2319 $aliases[$alias->entryid][] = $alias->alias;
2320 }
2321 }
84a44985 2322 if (is_array($this->exportdata['categoryentries'])) {
2323 foreach ($this->exportdata['categoryentries'] as $cat) {
6c0a9413 2324 if (!array_key_exists($cat->entryid, $categories)) {
2325 $categories[$cat->entryid] = array();
2326 }
2327 $categories[$cat->entryid][] = $cat->name;
2328 }
2329 }
2330 $csv = glossary_generate_export_csv($entries, $aliases, $categories);
6be1dcae 2331 return $this->exporter->write_new_file($csv, clean_filename($this->cm->name) . '.csv', false);
6c0a9413 2332 }
2333
2334 public function check_permissions() {
86a3996d 2335 return has_capability('mod/glossary:export', get_context_instance(CONTEXT_MODULE, $this->cm->id));
6c0a9413 2336 }
2337
2338 public static function display_name() {
2339 return get_string('modulename', 'glossary');
2340 }
2341}
49a12552 2342
2343class glossary_entry_portfolio_caller extends portfolio_module_caller_base {
2344
2345 private $glossary;
2346 private $entry;
0d06b6fd 2347 protected $entryid;
49a12552 2348
0d06b6fd 2349 public static function expected_callbackargs() {
2350 return array(
2351 'entryid' => true,
2352 'id' => true,
2353 );
2354 }
2355
2356 public function load_data() {
49a12552 2357 global $DB;
0d06b6fd 2358 if (!$this->cm = get_coursemodule_from_id('glossary', $this->id)) {
34035201 2359 throw new portfolio_caller_exception('invalidid', 'glossary');
49a12552 2360 }
2361 if (!$this->glossary = $DB->get_record('glossary', array('id' => $this->cm->instance))) {
34035201 2362 throw new portfolio_caller_exception('invalidid', 'glossary');
49a12552 2363 }
0d06b6fd 2364 if ($this->entryid) {
2365 if (!$this->entry = $DB->get_record('glossary_entries', array('id' => $this->entryid))) {
2366 throw new portfolio_caller_exception('noentry', 'glossary');
2367 }
2368 // in case we don't have USER this will make the entry be printed
2369 $this->entry->approved = true;
49a12552 2370 }
6be1dcae 2371 $this->supportedformats = array(PORTFOLIO_FORMAT_PLAINHTML);
49a12552 2372 }
2373
2374 public function expected_time() {
2375 return PORTFOLIO_TIME_LOW;
2376 }
2377
2378 public function check_permissions() {
86a3996d 2379 $context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
2380 return has_capability('mod/glossary:exportentry', $context)
2381 || ($this->entry->userid == $this->user->id && has_capability('mod/glossary:exportownentry', $context));
49a12552 2382 }
2383
2384 public static function display_name() {
ad1cfbb1 2385 return get_string('modulename', 'glossary');
49a12552 2386 }
2387
d67bfc32 2388 public function prepare_package() {
84a44985 2389 define('PORTFOLIO_INTERNAL', true);
49a12552 2390 ob_start();
0d06b6fd 2391 $entry = clone $this->entry;
2392 glossary_print_entry($this->get('course'), $this->cm, $this->glossary, $entry, null, null, false);
49a12552 2393 $content = ob_get_clean();
6be1dcae 2394 return $this->exporter->write_new_file($content, clean_filename($this->entry->concept) . '.html', false);
49a12552 2395 }
2396
2397 public function get_sha1() {
84a44985 2398 return sha1(serialize($this->entry));
49a12552 2399 }
2400}