MDL-18910 moving modedit features to modname_supports()
[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;
097d705e 754 $return .= ' <a title="' . get_string('addcomment','glossary') . '" href="comment.php?action=add&amp;eid='.$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.'" />';
1035 $path = $browser->encodepath($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();
1071 if (has_capability('moodle/course:managefiles', $context)) {
1072 $areas['glossary_intro'] = get_string('areaintro', 'glossary');
1073 }
1074 return $areas;
1075}
1076
49bcd737 1077/**
1078 * Serves the glossary attachments. Implements needed access control ;-)
1079 */
1080function glossary_pluginfile($course, $cminfo, $context, $filearea, $args) {
1081 global $CFG, $DB;
a02c77dc 1082
49bcd737 1083 if (!$cminfo->uservisible) {
1084 return false;
1085 }
e179048e 1086
aa9bcfcd 1087 if ($filearea === 'glossary_intro') {
1088 // all users may access it
1089 $relativepath = '/'.implode('/', $args);
1090 $fullpath = $context->id.'glossary_intro0'.$relativepath;
e179048e 1091
aa9bcfcd 1092 $fs = get_file_storage();
1093 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1094 return false;
1095 }
e179048e 1096
aa9bcfcd 1097 $lifetime = isset($CFG->filelifetime) ? $CFG->filelifetime : 86400;
24fb69e1 1098
aa9bcfcd 1099 // finally send the file
1100 send_stored_file($file, $lifetime, 0);
e179048e 1101
ccde17c3 1102 } else if ($filearea === 'glossary_attachment' or $filearea === 'glossary_entry') {
aa9bcfcd 1103 $entryid = (int)array_shift($args);
49bcd737 1104
aa9bcfcd 1105 if (!$entry = $DB->get_record('glossary_entries', array('id'=>$entryid))) {
1106 return false;
e179048e 1107 }
49bcd737 1108
aa9bcfcd 1109 if (!$glossary = $DB->get_record('glossary', array('id'=>$cminfo->instance))) {
1110 return false;
1111 }
e179048e 1112
aa9bcfcd 1113 if ($glossary->defaultapproval and !$entry->approved and !has_capability('mod/glossary:approve', $context)) {
1114 return false;
1115 }
1116
1117 if ($entry->glossaryid == $cminfo->instance) {
1118 $filecontext = $context;
1119
1120 } else if ($entry->sourceglossaryid == $cminfo->instance) {
1121 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
1122 print_error('invalidcoursemodule');
1123 }
1124 $filecontext = get_context_instance(CONTEXT_MODULE, $maincm->id);
1125
1126 } else {
1127 return false;
1128 }
1129
1130 $relativepath = '/'.implode('/', $args);
1131 $fullpath = $filecontext->id.$filearea.$entryid.$relativepath;
1132
1133 $fs = get_file_storage();
1134 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1135 return false;
1136 }
1137
1138 // finally send the file
1139 send_stored_file($file, 0, 0, true); // download MUST be forced - security!
e179048e 1140 }
1141
aa9bcfcd 1142 return false;
e179048e 1143}
1144
ad58adac 1145function glossary_print_tabbed_table_end() {
9ca8cc08 1146 echo "</div></div>";
06d94a52 1147}
1148
1ac87c73 1149function glossary_print_approval_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
a359c29b 1150 if ($glossary->showalphabet) {
7a3ec1af 1151 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
677038ee 1152 }
1ac87c73 1153 glossary_print_special_links($cm, $glossary, $mode, $hook);
c76e673a 1154
c4a35419 1155 glossary_print_alphabet_links($cm, $glossary, $mode, $hook,$sortkey, $sortorder);
c76e673a 1156
1ac87c73 1157 glossary_print_all_links($cm, $glossary, $mode, $hook);
894ff63f 1158
db87439a 1159 glossary_print_sorting_links($cm, $mode, 'CREATION', 'asc');
c76e673a 1160}
1161
1ac87c73 1162function glossary_print_import_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
7a3ec1af 1163 echo '<div class="glossaryexplain">' . get_string("explainimport","glossary") . '</div>';
748b1932 1164}
1165
1ac87c73 1166function glossary_print_export_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
7a3ec1af 1167 echo '<div class="glossaryexplain">' . get_string("explainexport","glossary") . '</div>';
748b1932 1168}
1169
1ac87c73 1170function glossary_print_alphabet_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1171 if ( $mode != 'date' ) {
a359c29b 1172 if ($glossary->showalphabet) {
7a3ec1af 1173 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
c197e607 1174 }
c76e673a 1175
1ac87c73 1176 glossary_print_special_links($cm, $glossary, $mode, $hook);
c76e673a 1177
c4a35419 1178 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
c197e607 1179
1ac87c73 1180 glossary_print_all_links($cm, $glossary, $mode, $hook);
c197e607 1181 } else {
1ac87c73 1182 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
1183 }
1184}
1185
1186function glossary_print_author_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
a359c29b 1187 if ($glossary->showalphabet) {
7a3ec1af 1188 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
c197e607 1189 }
1ac87c73 1190
c4a35419 1191 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
1ac87c73 1192 glossary_print_all_links($cm, $glossary, $mode, $hook);
7a3ec1af 1193 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
c76e673a 1194}
1195
1ac87c73 1196function glossary_print_categories_menu($cm, $glossary, $hook, $category) {
ae8c3566 1197 global $CFG, $DB;
a02c77dc 1198
dabfd0ed 1199 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
3a26f0ea 1200
41905731 1201 echo '<table border="0" width="100%">';
c197e607 1202 echo '<tr>';
c76e673a 1203
5bd76d7f 1204 echo '<td align="center" style="width:20%">';
0468976c 1205 if (has_capability('mod/glossary:managecategories', $context)) {
c76e673a 1206 $options['id'] = $cm->id;
1ac87c73 1207 $options['mode'] = 'cat';
1208 $options['hook'] = $hook;
c76e673a 1209 echo print_single_button("editcategories.php", $options, get_string("editcategories","glossary"), "get");
1210 }
c197e607 1211 echo '</td>';
c76e673a 1212
5bd76d7f 1213 echo '<td align="center" style="width:60%">';
c197e607 1214 echo '<b>';
c76e673a 1215
1216 $menu[GLOSSARY_SHOW_ALL_CATEGORIES] = get_string("allcategories","glossary");
1217 $menu[GLOSSARY_SHOW_NOT_CATEGORISED] = get_string("notcategorised","glossary");
677038ee 1218
ae8c3566 1219 $categories = $DB->get_records("glossary_categories", array("glossaryid"=>$glossary->id), "name ASC");
c197e607 1220 $selected = '';
c76e673a 1221 if ( $categories ) {
1222 foreach ($categories as $currentcategory) {
1223 $url = $currentcategory->id;
1224 if ( $category ) {
1225 if ($currentcategory->id == $category->id) {
1226 $selected = $url;
1227 }
1228 }
ae06e00e 1229 $menu[$url] = clean_text($currentcategory->name); //Only clean, not filters
c76e673a 1230 }
1231 }
1232 if ( !$selected ) {
1233 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1234 }
1235
1236 if ( $category ) {
5bd76d7f 1237 echo format_text($category->name, FORMAT_PLAIN);
c76e673a 1238 } else {
1ac87c73 1239 if ( $hook == GLOSSARY_SHOW_NOT_CATEGORISED ) {
c76e673a 1240
1241 echo get_string("entrieswithoutcategory","glossary");
1242 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1243
1ac87c73 1244 } elseif ( $hook == GLOSSARY_SHOW_ALL_CATEGORIES ) {
c76e673a 1245
1246 echo get_string("allcategories","glossary");
1247 $selected = GLOSSARY_SHOW_ALL_CATEGORIES;
1248
1249 }
1250 }
c197e607 1251 echo '</b></td>';
5bd76d7f 1252 echo '<td align="center" style="width:20%">';
c76e673a 1253
839f2456 1254 echo popup_form("$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=cat&amp;hook=", $menu, "catmenu", $selected, "",
c76e673a 1255 "", "", false);
677038ee 1256
c197e607 1257 echo '</td>';
1258 echo '</tr>';
c76e673a 1259
c197e607 1260 echo '</table>';
c76e673a 1261}
1262
1ac87c73 1263function glossary_print_all_links($cm, $glossary, $mode, $hook) {
a02c77dc 1264global $CFG;
a359c29b 1265 if ( $glossary->showall) {
c76e673a 1266 $strallentries = get_string("allentries", "glossary");
1ac87c73 1267 if ( $hook == 'ALL' ) {
c76e673a 1268 echo "<b>$strallentries</b>";
1269 } else {
1270 $strexplainall = strip_tags(get_string("explainall","glossary"));
839f2456 1271 echo "<a title=\"$strexplainall\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=ALL\">$strallentries</a>";
c76e673a 1272 }
1273 }
1274}
1275
1ac87c73 1276function glossary_print_special_links($cm, $glossary, $mode, $hook) {
c76e673a 1277global $CFG;
a359c29b 1278 if ( $glossary->showspecial) {
c76e673a 1279 $strspecial = get_string("special", "glossary");
1ac87c73 1280 if ( $hook == 'SPECIAL' ) {
677038ee 1281 echo "<b>$strspecial</b> | ";
1282 } else {
1283 $strexplainspecial = strip_tags(get_string("explainspecial","glossary"));
839f2456 1284 echo "<a title=\"$strexplainspecial\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=SPECIAL\">$strspecial</a> | ";
677038ee 1285 }
914cb260 1286 }
c76e673a 1287}
677038ee 1288
c4a35419 1289function glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder) {
c76e673a 1290global $CFG;
a359c29b 1291 if ( $glossary->showalphabet) {
c4274149 1292 $alphabet = explode(",", get_string("alphabet"));
677038ee 1293 $letters_by_line = 14;
1294 for ($i = 0; $i < count($alphabet); $i++) {
1ac87c73 1295 if ( $hook == $alphabet[$i] and $hook) {
677038ee 1296 echo "<b>$alphabet[$i]</b>";
1297 } else {
82015ed2 1298 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 1299 }
1300 if ((int) ($i % $letters_by_line) != 0 or $i == 0) {
c197e607 1301 echo ' | ';
677038ee 1302 } else {
a9ef4a63 1303 echo '<br />';
677038ee 1304 }
767a31c3 1305 }
677038ee 1306 }
c76e673a 1307}
1308
1ac87c73 1309function glossary_print_sorting_links($cm, $mode, $sortkey = '',$sortorder = '') {
c76e673a 1310global $CFG;
677038ee 1311
c4a35419 1312 $asc = get_string("ascending","glossary");
1313 $desc = get_string("descending","glossary");
1314 $bopen = '<b>';
1315 $bclose = '</b>';
a02c77dc 1316
c197e607 1317 $neworder = '';
468c120a 1318 $currentorder = '';
1319 $currentsort = '';
677038ee 1320 if ( $sortorder ) {
c197e607 1321 if ( $sortorder == 'asc' ) {
468c120a 1322 $currentorder = $asc;
839f2456 1323 $neworder = '&amp;sortorder=desc';
468c120a 1324 $newordertitle = get_string('changeto', 'glossary', $desc);
677038ee 1325 } else {
468c120a 1326 $currentorder = $desc;
839f2456 1327 $neworder = '&amp;sortorder=asc';
468c120a 1328 $newordertitle = get_string('changeto', 'glossary', $asc);
677038ee 1329 }
468c120a 1330 $icon = " <img src=\"$sortorder.gif\" class=\"icon\" alt=\"$newordertitle\" />";
677038ee 1331 } else {
c4a35419 1332 if ( $sortkey != 'CREATION' and $sortkey != 'UPDATE' and
1333 $sortkey != 'FIRSTNAME' and $sortkey != 'LASTNAME' ) {
677038ee 1334 $icon = "";
c4a35419 1335 $newordertitle = $asc;
677038ee 1336 } else {
c4a35419 1337 $newordertitle = $desc;
839f2456 1338 $neworder = '&amp;sortorder=desc';
468c120a 1339 $icon = ' <img src="asc.gif" class="icon" alt="'.$newordertitle.'" />';
677038ee 1340 }
1341 }
c4a35419 1342 $ficon = '';
1343 $fneworder = '';
1344 $fbtag = '';
1345 $fendbtag = '';
1346
1347 $sicon = '';
1348 $sneworder = '';
ae078733 1349
1350 $sbtag = '';
1351 $fbtag = '';
1352 $fendbtag = '';
1353 $sendbtag = '';
1354
c4a35419 1355 $sendbtag = '';
1356
1357 if ( $sortkey == 'CREATION' or $sortkey == 'FIRSTNAME' ) {
1358 $ficon = $icon;
1359 $fneworder = $neworder;
1360 $fordertitle = $newordertitle;
1361 $sordertitle = $asc;
1362 $fbtag = $bopen;
1363 $fendbtag = $bclose;
1364 } elseif ($sortkey == 'UPDATE' or $sortkey == 'LASTNAME') {
1365 $sicon = $icon;
1366 $sneworder = $neworder;
1367 $fordertitle = $asc;
1368 $sordertitle = $newordertitle;
1369 $sbtag = $bopen;
1370 $sendbtag = $bclose;
677038ee 1371 } else {
c4a35419 1372 $fordertitle = $asc;
1373 $sordertitle = $asc;
677038ee 1374 }
c4a35419 1375
1376 if ( $sortkey == 'CREATION' or $sortkey == 'UPDATE' ) {
1377 $forder = 'CREATION';
1378 $sorder = 'UPDATE';
1379 $fsort = get_string("sortbycreation", "glossary");
1380 $ssort = get_string("sortbylastupdate", "glossary");
1381
468c120a 1382 $currentsort = $fsort;
1383 if ($sortkey == 'UPDATE') {
1384 $currentsort = $ssort;
1385 }
c4a35419 1386 $sort = get_string("sortchronogically", "glossary");
1387 } elseif ( $sortkey == 'FIRSTNAME' or $sortkey == 'LASTNAME') {
1388 $forder = 'FIRSTNAME';
1389 $sorder = 'LASTNAME';
1390 $fsort = get_string("firstname");
1391 $ssort = get_string("lastname");
1392
468c120a 1393 $currentsort = $fsort;
1394 if ($sortkey == 'LASTNAME') {
1395 $currentsort = $ssort;
1396 }
c4a35419 1397 $sort = get_string("sortby", "glossary");
1398 }
468c120a 1399 $current = '<span class="accesshide">'.get_string('current', 'glossary', "$currentsort $currentorder").'</span>';
1400 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 1401 "$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 1402}
ad58adac 1403
1404function glossary_sort_entries ( $entry0, $entry1 ) {
a02c77dc 1405
95d56829 1406 if ( moodle_strtolower(ltrim($entry0->concept)) < moodle_strtolower(ltrim($entry1->concept)) ) {
ad58adac 1407 return -1;
95d56829 1408 } elseif ( moodle_strtolower(ltrim($entry0->concept)) > moodle_strtolower(ltrim($entry1->concept)) ) {
ad58adac 1409 return 1;
1410 } else {
1411 return 0;
1412 }
1413}
1414
ed0201dd 1415function glossary_print_comment($course, $cm, $glossary, $entry, $comment) {
ae8c3566 1416 global $CFG, $USER, $DB;
a02c77dc 1417
bbbf2d40 1418 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
ed0201dd 1419
ae8c3566 1420 $user = $DB->get_record('user', array('id'=>$comment->userid));
3a26f0ea 1421 $strby = get_string('writtenby','glossary');
26663a23 1422 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
ed0201dd 1423
36a2b6bd 1424 echo '<div class="boxaligncenter">';
3a26f0ea 1425 echo '<table class="glossarycomment" cellspacing="0">';
1426 echo '<tr valign="top">';
eee75231 1427 echo '<td class="left picture">';
65bcf17b 1428 print_user_picture($user, $course->id, $user->picture);
3a26f0ea 1429 echo '</td>';
1430 echo '<td class="entryheader">';
c07ca217 1431
26663a23 1432 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
e6d45048 1433 $by = new object();
c07ca217 1434 $by->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$user->id.'&amp;course='.$course->id.'">'.$fullname.'</a>';
1435 $by->date = userdate($comment->timemodified);
1436 echo '<span class="author">'.get_string('bynameondate', 'forum', $by).'</span>';
1437
3a26f0ea 1438 echo '</td></tr>';
ed0201dd 1439
3a26f0ea 1440 echo '<tr valign="top"><td class="left side">';
1441 echo '&nbsp;';
1442 echo '</td><td class="entry">';
072f7533 1443
7d8a3cb0 1444 $options = new object();
cbc2b5df 1445 $options->trusted = $comment->entrycommenttrust;
1446 echo format_text($comment->entrycomment, $comment->entrycommentformat, $options);
072f7533 1447
3a26f0ea 1448 echo '<div class="icons commands">';
1449
3a512f86 1450 $ineditperiod = ((time() - $comment->timemodified < $CFG->maxeditingtime) || $glossary->editalways);
0468976c 1451 if ( ($glossary->allowcomments && $ineditperiod && $USER->id == $comment->userid) || has_capability('mod/glossary:managecomments', $context)) {
a02c77dc 1452 echo "<a href=\"comment.php?cid=$comment->id&amp;action=edit\"><img
0d905d9f 1453 alt=\"" . get_string("edit") . "\" src=\"$CFG->pixpath/t/edit.gif\" class=\"iconsmall\" /></a> ";
c197e607 1454 }
0468976c 1455 if ( ($glossary->allowcomments && $USER->id == $comment->userid) || has_capability('mod/glossary:managecomments', $context) ) {
a02c77dc 1456 echo "<a href=\"comment.php?cid=$comment->id&amp;action=delete\"><img
0d905d9f 1457 alt=\"" . get_string("delete") . "\" src=\"$CFG->pixpath/t/delete.gif\" class=\"iconsmall\" /></a>";
c197e607 1458 }
a02c77dc 1459
3a26f0ea 1460 echo '</div></td></tr>';
36a2b6bd 1461 echo '</table></div>';
ed0201dd 1462
ed0201dd 1463}
1464
63dd5fb2 1465function glossary_print_entry_ratings($course, $entry, $ratings = NULL) {
ae8c3566 1466 global $USER, $CFG, $DB;
a02c77dc 1467
ae8c3566 1468 $glossary = $DB->get_record('glossary', array('id'=>$entry->glossaryid));
1469 $glossarymod = $DB->get_record('modules', array('name'=>'glossary'));
1470 $cm = $DB->get_record_sql("SELECT *
1471 FROM {course_modules}
1472 WHERE course = ? AND module = ? and instance = ?", array($course->id, $glossarymod->id, $glossary->id));
a02c77dc 1473
bbbf2d40 1474 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
a359c29b 1475
63dd5fb2 1476 $ratingsmenuused = false;
1477 if (!empty($ratings) and !empty($USER->id)) {
1478 $useratings = true;
1479 if ($ratings->assesstimestart and $ratings->assesstimefinish) {
1480 if ($entry->timecreated < $ratings->assesstimestart or $entry->timecreated > $ratings->assesstimefinish) {
1481 $useratings = false;
1482 }
1483 }
1484 if ($useratings) {
0468976c 1485 if (has_capability('mod/glossary:viewrating', $context)) {
63dd5fb2 1486 glossary_print_ratings_mean($entry->id, $ratings->scale);
1487 if ($USER->id != $entry->userid) {
1488 glossary_print_rating_menu($entry->id, $USER->id, $ratings->scale);
1489 $ratingsmenuused = true;
1490 }
1491 } else if ($USER->id == $entry->userid) {
1492 glossary_print_ratings_mean($entry->id, $ratings->scale);
1493 } else if (!empty($ratings->allow) ) {
1494 glossary_print_rating_menu($entry->id, $USER->id, $ratings->scale);
1495 $ratingsmenuused = true;
1496 }
1497 }
1498 }
1499 return $ratingsmenuused;
1500}
1501
b1918034 1502function glossary_print_dynaentry($courseid, $entries, $displayformat = -1) {
ae8c3566 1503 global $USER,$CFG, $DB;
cca6f7f1 1504
36a2b6bd 1505 echo '<div class="boxaligncenter">';
a8466100 1506 echo '<table class="glossarypopup" cellspacing="0"><tr>';
1507 echo '<td>';
1d9ddaaf 1508 if ( $entries ) {
1509 foreach ( $entries as $entry ) {
ae8c3566 1510 if (! $glossary = $DB->get_record('glossary', array('id'=>$entry->glossaryid))) {
5973a4c4 1511 print_error('invalidid', 'glossary');
cca6f7f1 1512 }
ae8c3566 1513 if (! $course = $DB->get_record('course', array('id'=>$glossary->course))) {
5973a4c4 1514 print_error('coursemisconf');
1d9ddaaf 1515 }
a8466100 1516 if (!$cm = get_coursemodule_from_instance('glossary', $entry->glossaryid, $glossary->course) ) {
5973a4c4 1517 print_error('invalidid', 'glossary');
1d9ddaaf 1518 }
1f63b7c6 1519
1520 //If displayformat is present, override glossary->displayformat
a359c29b 1521 if ($displayformat < 0) {
1f63b7c6 1522 $dp = $glossary->displayformat;
a359c29b 1523 } else {
1f63b7c6 1524 $dp = $displayformat;
1525 }
1526
a359c29b 1527 //Get popupformatname
ae8c3566 1528 $format = $DB->get_record('glossary_formats', array('name'=>$dp));
a359c29b 1529 $displayformat = $format->popupformatname;
1530
1531 //Check displayformat variable and set to default if necessary
1532 if (!$displayformat) {
1533 $displayformat = 'dictionary';
584dcac9 1534 }
1f63b7c6 1535
a359c29b 1536 $formatfile = $CFG->dirroot.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
1537 $functionname = 'glossary_show_entry_'.$displayformat;
1538
1539 if (file_exists($formatfile)) {
1540 include_once($formatfile);
1541 if (function_exists($functionname)) {
1542 $functionname($course, $cm, $glossary, $entry,'','','','');
1543 }
1544 }
cca6f7f1 1545 }
cca6f7f1 1546 }
a8466100 1547 echo '</td>';
36a2b6bd 1548 echo '</tr></table></div>';
1d9ddaaf 1549}
4f4ca7b5 1550
6c0a9413 1551function glossary_generate_export_csv($entries, $aliases, $categories) {
1552 global $CFG;
1553 $csv = '';
1554 $delimiter = '';
1555 require_once($CFG->libdir . '/csvlib.class.php');
1556 $delimiter = csv_import_reader::get_delimiter('comma');
1557 $csventries = array(0 => array(get_string('concept', 'glossary'), get_string('definition', 'glossary')));
1558 $csvaliases = array(0 => array());
1559 $csvcategories = array(0 => array());
1560 $aliascount = 0;
1561 $categorycount = 0;
1562
1563 foreach ($entries as $entry) {
1564 $thisaliasesentry = array();
1565 $thiscategoriesentry = array();
cbc2b5df 1566 $thiscsventry = array($entry->concept, nl2br($entry->definition));
6c0a9413 1567
1568 if (array_key_exists($entry->id, $aliases) && is_array($aliases[$entry->id])) {
1569 $thiscount = count($aliases[$entry->id]);
1570 if ($thiscount > $aliascount) {
1571 $aliascount = $thiscount;
1572 }
1573 foreach ($aliases[$entry->id] as $alias) {
1574 $thisaliasesentry[] = trim($alias);
1575 }
1576 }
1577 if (array_key_exists($entry->id, $categories) && is_array($categories[$entry->id])) {
1578 $thiscount = count($categories[$entry->id]);
1579 if ($thiscount > $categorycount) {
1580 $categorycount = $thiscount;
1581 }
1582 foreach ($categories[$entry->id] as $catentry) {
1583 $thiscategoriesentry[] = trim($catentry);
1584 }
1585 }
1586 $csventries[$entry->id] = $thiscsventry;
1587 $csvaliases[$entry->id] = $thisaliasesentry;
1588 $csvcategories[$entry->id] = $thiscategoriesentry;
1589
1590 }
1591 $returnstr = '';
1592 foreach ($csventries as $id => $row) {
1593 $aliasstr = '';
1594 $categorystr = '';
1595 if ($id == 0) {
1596 $aliasstr = get_string('alias', 'glossary');
1597 $categorystr = get_string('category', 'glossary');
1598 }
1599 $row = array_merge($row, array_pad($csvaliases[$id], $aliascount, $aliasstr), array_pad($csvcategories[$id], $categorycount, $categorystr));
1600 $returnstr .= '"' . implode('"' . $delimiter . '"', $row) . '"' . "\n";
1601 }
1602 return $returnstr;
1603}
1604
1ac87c73 1605function glossary_generate_export_file($glossary, $hook = "", $hook = 0) {
ae8c3566 1606 global $CFG, $DB;
212039c0 1607
1608 $co = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1609
1610 $co .= glossary_start_tag("GLOSSARY",0,true);
1611 $co .= glossary_start_tag("INFO",1,true);
1612 $co .= glossary_full_tag("NAME",2,false,$glossary->name);
1613 $co .= glossary_full_tag("INTRO",2,false,$glossary->intro);
212039c0 1614 $co .= glossary_full_tag("ALLOWDUPLICATEDENTRIES",2,false,$glossary->allowduplicatedentries);
1615 $co .= glossary_full_tag("DISPLAYFORMAT",2,false,$glossary->displayformat);
1616 $co .= glossary_full_tag("SHOWSPECIAL",2,false,$glossary->showspecial);
1617 $co .= glossary_full_tag("SHOWALPHABET",2,false,$glossary->showalphabet);
1618 $co .= glossary_full_tag("SHOWALL",2,false,$glossary->showall);
1619 $co .= glossary_full_tag("ALLOWCOMMENTS",2,false,$glossary->allowcomments);
1620 $co .= glossary_full_tag("USEDYNALINK",2,false,$glossary->usedynalink);
1621 $co .= glossary_full_tag("DEFAULTAPPROVAL",2,false,$glossary->defaultapproval);
1622 $co .= glossary_full_tag("GLOBALGLOSSARY",2,false,$glossary->globalglossary);
1623 $co .= glossary_full_tag("ENTBYPAGE",2,false,$glossary->entbypage);
4f4ca7b5 1624
ae8c3566 1625 if ( $entries = $DB->get_records("glossary_entries", array("glossaryid"=>$glossary->id))) {
212039c0 1626 $co .= glossary_start_tag("ENTRIES",2,true);
748b1932 1627 foreach ($entries as $entry) {
046a797c 1628 $permissiongranted = 1;
1ac87c73 1629 if ( $hook ) {
1630 switch ( $hook ) {
046a797c 1631 case "ALL":
1632 case "SPECIAL":
1633 break;
1634 default:
1ac87c73 1635 $permissiongranted = ($entry->concept[ strlen($hook)-1 ] == $hook);
046a797c 1636 break;
1637 }
1638 }
1ac87c73 1639 if ( $hook ) {
1640 switch ( $hook ) {
046a797c 1641 case GLOSSARY_SHOW_ALL_CATEGORIES:
1642 break;
1643 case GLOSSARY_SHOW_NOT_CATEGORISED:
ae8c3566 1644 $permissiongranted = !$DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id));
046a797c 1645 break;
1646 default:
ae8c3566 1647 $permissiongranted = $DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id, "categoryid"=>$hook));
046a797c 1648 break;
1649 }
1650 }
1651 if ( $entry->approved and $permissiongranted ) {
212039c0 1652 $co .= glossary_start_tag("ENTRY",3,true);
1653 $co .= glossary_full_tag("CONCEPT",4,false,trim($entry->concept));
cbc2b5df 1654 $co .= glossary_full_tag("DEFINITION",4,false,$entry->definition);
1655 $co .= glossary_full_tag("FORMAT",4,false,$entry->definitionformat);
212039c0 1656 $co .= glossary_full_tag("USEDYNALINK",4,false,$entry->usedynalink);
1657 $co .= glossary_full_tag("CASESENSITIVE",4,false,$entry->casesensitive);
1658 $co .= glossary_full_tag("FULLMATCH",4,false,$entry->fullmatch);
1659 $co .= glossary_full_tag("TEACHERENTRY",4,false,$entry->teacherentry);
748b1932 1660
ae8c3566 1661 if ( $aliases = $DB->get_records("glossary_alias", array("entryid"=>$entry->id))) {
212039c0 1662 $co .= glossary_start_tag("ALIASES",4,true);
7965be79 1663 foreach ($aliases as $alias) {
212039c0 1664 $co .= glossary_start_tag("ALIAS",5,true);
1665 $co .= glossary_full_tag("NAME",6,false,trim($alias->alias));
1666 $co .= glossary_end_tag("ALIAS",5,true);
7965be79 1667 }
212039c0 1668 $co .= glossary_end_tag("ALIASES",4,true);
7965be79 1669 }
ae8c3566 1670 if ( $catentries = $DB->get_records("glossary_entries_categories", array("entryid"=>$entry->id))) {
212039c0 1671 $co .= glossary_start_tag("CATEGORIES",4,true);
748b1932 1672 foreach ($catentries as $catentry) {
ae8c3566 1673 $category = $DB->get_record("glossary_categories", array("id"=>$catentry->categoryid));
748b1932 1674
212039c0 1675 $co .= glossary_start_tag("CATEGORY",5,true);
1676 $co .= glossary_full_tag("NAME",6,false,$category->name);
1677 $co .= glossary_full_tag("USEDYNALINK",6,false,$category->usedynalink);
1678 $co .= glossary_end_tag("CATEGORY",5,true);
748b1932 1679 }
212039c0 1680 $co .= glossary_end_tag("CATEGORIES",4,true);
748b1932 1681 }
4f4ca7b5 1682
212039c0 1683 $co .= glossary_end_tag("ENTRY",3,true);
4f4ca7b5 1684 }
1685 }
212039c0 1686 $co .= glossary_end_tag("ENTRIES",2,true);
748b1932 1687
4f4ca7b5 1688 }
748b1932 1689
1690
212039c0 1691 $co .= glossary_end_tag("INFO",1,true);
1692 $co .= glossary_end_tag("GLOSSARY",0,true);
4f4ca7b5 1693
212039c0 1694 return $co;
4f4ca7b5 1695}
212039c0 1696/// Functions designed by Eloy Lafuente
1697/// Functions to create, open and write header of the xml file
4f4ca7b5 1698
212039c0 1699// Read import file and convert to current charset
748b1932 1700function glossary_read_imported_file($file) {
9f79b50f 1701 require_once "../../lib/xmlize.php";
1702 global $CFG;
1703
748b1932 1704 $h = fopen($file,"r");
1705 $line = '';
1706 if ($h) {
1707 while ( !feof($h) ) {
b9656030 1708 $char = fread($h,1024);
748b1932 1709 $line .= $char;
1710 }
1711 fclose($h);
894ff63f 1712 }
792a76d8 1713 return xmlize($line, 0);
748b1932 1714}
4f4ca7b5 1715
a02c77dc 1716//Return the xml start tag
4f4ca7b5 1717function glossary_start_tag($tag,$level=0,$endline=false) {
1718 if ($endline) {
1719 $endchar = "\n";
1720 } else {
1721 $endchar = "";
1722 }
1723 return str_repeat(" ",$level*2)."<".strtoupper($tag).">".$endchar;
1724}
a02c77dc 1725
1726//Return the xml end tag
4f4ca7b5 1727function glossary_end_tag($tag,$level=0,$endline=true) {
1728 if ($endline) {
1729 $endchar = "\n";
1730 } else {
1731 $endchar = "";
1732 }
1733 return str_repeat(" ",$level*2)."</".strtoupper($tag).">".$endchar;
1734}
a02c77dc 1735
4f4ca7b5 1736//Return the start tag, the contents and the end tag
212039c0 1737function glossary_full_tag($tag,$level=0,$endline=true,$content) {
9f79b50f 1738 global $CFG;
a02c77dc 1739
4f4ca7b5 1740 $st = glossary_start_tag($tag,$level,$endline);
212039c0 1741 $co = preg_replace("/\r\n|\r/", "\n", s($content));
4f4ca7b5 1742 $et = glossary_end_tag($tag,0,true);
1743 return $st.$co.$et;
1744}
1745
63dd5fb2 1746/*
a02c77dc 1747* Adding grading functions
63dd5fb2 1748*/
1749
1750function glossary_get_ratings($entryid, $sort="u.firstname ASC") {
1751/// Returns a list of ratings for a particular entry - sorted.
ae8c3566 1752 global $DB;
1753 return $DB->get_records_sql("SELECT u.*, r.rating, r.time
1754 FROM {glossary_ratings} r, {user} u
1755 WHERE r.entryid = ? AND r.userid = u.id
1756 ORDER BY $sort", array($entryid));
63dd5fb2 1757}
1758
63dd5fb2 1759function glossary_count_unrated_entries($glossaryid, $userid) {
1760// How many unrated entries are in the given glossary for a given user?
ae8c3566 1761 global $DB;
1762 if ($entries = $DB->get_record_sql("SELECT count('x') as num
1763 FROM {glossary_entries}
1764 WHERE glossaryid = ? AND userid <> ?", array($glossaryid, $userid))) {
1765
1766 if ($rated = $DB->get_record_sql("SELECT count(*) as num
1767 FROM {glossary_entries} e, {glossary_ratings} r
1768 WHERE e.glossaryid = ? AND e.id = r.entryid
1769 AND r.userid = ?", array($glossaryid, $userid))) {
63dd5fb2 1770 $difference = $entries->num - $rated->num;
1771 if ($difference > 0) {
1772 return $difference;
1773 } else {
1774 return 0; // Just in case there was a counting error
1775 }
1776 } else {
1777 return $entries->num;
1778 }
1779 } else {
1780 return 0;
1781 }
1782}
1783
1784function glossary_print_ratings_mean($entryid, $scale) {
1785/// Print the multiple ratings on a entry given to the current user by others.
1786/// Scale is an array of ratings
1787
1788 static $strrate;
1789
1790 $mean = glossary_get_ratings_mean($entryid, $scale);
a02c77dc 1791
63dd5fb2 1792 if ($mean !== "") {
1793
1794 if (empty($strratings)) {
1795 $strratings = get_string("ratings", "glossary");
1796 }
1797
91b4cb68 1798 echo "$strratings: ";
63dd5fb2 1799 link_to_popup_window ("/mod/glossary/report.php?id=$entryid", "ratings", $mean, 400, 600);
1800 }
1801}
1802
1803
1804function glossary_get_ratings_mean($entryid, $scale, $ratings=NULL) {
1805/// Return the mean rating of a entry given to the current user by others.
1806/// Scale is an array of possible ratings in the scale
1807/// Ratings is an optional simple array of actual ratings (just integers)
ae8c3566 1808 global $DB;
63dd5fb2 1809
1810 if (!$ratings) {
1811 $ratings = array();
ae8c3566 1812 if ($rates = $DB->get_records("glossary_ratings", array("entryid"=>$entryid))) {
63dd5fb2 1813 foreach ($rates as $rate) {
1814 $ratings[] = $rate->rating;
1815 }
1816 }
1817 }
1818
1819 $count = count($ratings);
1820
1821 if ($count == 0) {
1822 return "";
1823
1824 } else if ($count == 1) {
1825 return $scale[$ratings[0]];
1826
1827 } else {
1828 $total = 0;
1829 foreach ($ratings as $rating) {
1830 $total += $rating;
1831 }
1832 $mean = round( ((float)$total/(float)$count) + 0.001); // Little fudge factor so that 0.5 goes UP
a02c77dc 1833
63dd5fb2 1834 if (isset($scale[$mean])) {
1835 return $scale[$mean]." ($count)";
1836 } else {
1837 return "$mean ($count)"; // Should never happen, hopefully
1838 }
1839 }
1840}
1841
1842function glossary_get_ratings_summary($entryid, $scale, $ratings=NULL) {
1843/// Return a summary of entry ratings given to the current user by others.
1844/// Scale is an array of possible ratings in the scale
1845/// Ratings is an optional simple array of actual ratings (just integers)
ae8c3566 1846 global $DB;
63dd5fb2 1847
1848 if (!$ratings) {
1849 $ratings = array();
ae8c3566 1850 if ($rates = $DB->get_records("glossary_ratings", array("entryid"=>$entryid))) {
63dd5fb2 1851 foreach ($rates as $rate) {
1852 $rating[] = $rate->rating;
1853 }
1854 }
1855 }
1856
1857
1858 if (!$count = count($ratings)) {
1859 return "";
1860 }
1861
1862
1863 foreach ($scale as $key => $scaleitem) {
1864 $sumrating[$key] = 0;
1865 }
1866
1867 foreach ($ratings as $rating) {
1868 $sumrating[$rating]++;
1869 }
1870
1871 $summary = "";
1872 foreach ($scale as $key => $scaleitem) {
1873 $summary = $sumrating[$key].$summary;
1874 if ($key > 1) {
1875 $summary = "/$summary";
1876 }
1877 }
1878 return $summary;
1879}
1880
1881function glossary_print_rating_menu($entryid, $userid, $scale) {
a02c77dc 1882/// Print the menu of ratings as part of a larger form.
63dd5fb2 1883/// If the entry has already been - set that value.
1884/// Scale is an array of ratings
ae8c3566 1885 global $DB;
63dd5fb2 1886
1887 static $strrate;
1888
ae8c3566 1889 if (!$rating = $DB->get_record("glossary_ratings", array("userid"=>$userid, "entryid"=>$entryid))) {
92fac4b2 1890 $rating->rating = -999;
63dd5fb2 1891 }
1892
1893 if (empty($strrate)) {
1894 $strrate = get_string("rate", "glossary");
1895 }
1896
92fac4b2 1897 choose_from_menu($scale, $entryid, $rating->rating, "$strrate...",'',-999);
63dd5fb2 1898}
1899
e2cf5316 1900
1901function glossary_get_paging_bar($totalcount, $page, $perpage, $baseurl, $maxpageallowed=99999, $maxdisplay=20, $separator="&nbsp;", $specialtext="", $specialvalue=-1, $previousandnext = true) {
1902// Returns the html code to represent any pagging bar. Paramenters are:
1903//
1904// Mandatory:
1905// $totalcount: total number of records to be displayed
1906// $page: page currently selected (0 based)
1907// $perpage: number of records per page
1908// $baseurl: url to link in each page, the string 'page=XX' will be added automatically.
1909// Optional:
1910// $maxpageallowed: maximum number of page allowed.
1911// $maxdisplay: maximum number of page links to show in the bar
1912// $separator: string to be used between pages in the bar
1913// $specialtext: string to be showed as an special link
1914// $specialvalue: value (page) to be used in the special link
1915// $previousandnext: to decide if we want the previous and next links
1916//
1917// The function dinamically show the first and last pages, and "scroll" over pages.
1918// Fully compatible with Moodle's print_paging_bar() function. Perhaps some day this
1919// could replace the general one. ;-)
1920
1921 $code = '';
1922
1923 $showspecial = false;
1924 $specialselected = false;
1925
1926 //Check if we have to show the special link
1927 if (!empty($specialtext)) {
1928 $showspecial = true;
1929 }
1930 //Check if we are with the special link selected
1931 if ($showspecial && $page == $specialvalue) {
1932 $specialselected = true;
a02c77dc 1933 }
e2cf5316 1934
1935 //If there are results (more than 1 page)
1936 if ($totalcount > $perpage) {
36a2b6bd 1937 $code .= "<div style=\"text-align:center\">";
e2cf5316 1938 $code .= "<p>".get_string("page").":";
1939
1940 $maxpage = (int)(($totalcount-1)/$perpage);
1941
1942 //Lower and upper limit of page
1943 if ($page < 0) {
1944 $page = 0;
1945 }
1946 if ($page > $maxpageallowed) {
1947 $page = $maxpageallowed;
1948 }
1949 if ($page > $maxpage) {
1950 $page = $maxpage;
1951 }
1952
1953 //Calculate the window of pages
1954 $pagefrom = $page - ((int)($maxdisplay / 2));
1955 if ($pagefrom < 0) {
1956 $pagefrom = 0;
1957 }
1958 $pageto = $pagefrom + $maxdisplay - 1;
1959 if ($pageto > $maxpageallowed) {
1960 $pageto = $maxpageallowed;
1961 }
1962 if ($pageto > $maxpage) {
1963 $pageto = $maxpage;
1964 }
1965
1966 //Some movements can be necessary if don't see enought pages
1967 if ($pageto - $pagefrom < $maxdisplay - 1) {
1968 if ($pageto - $maxdisplay + 1 > 0) {
1969 $pagefrom = $pageto - $maxdisplay + 1;
1970 }
1971 }
1972
1973 //Calculate first and last if necessary
1974 $firstpagecode = '';
1975 $lastpagecode = '';
1976 if ($pagefrom > 0) {
1977 $firstpagecode = "$separator<a href=\"{$baseurl}page=0\">1</a>";
1978 if ($pagefrom > 1) {
1979 $firstpagecode .= "$separator...";
1980 }
1981 }
1982 if ($pageto < $maxpage) {
1983 if ($pageto < $maxpage -1) {
1984 $lastpagecode = "$separator...";
1985 }
1986 $lastpagecode .= "$separator<a href=\"{$baseurl}page=$maxpage\">".($maxpage+1)."</a>";
1987 }
1988
1989 //Previous
1990 if ($page > 0 && $previousandnext) {
1991 $pagenum = $page - 1;
1992 $code .= "&nbsp;(<a href=\"{$baseurl}page=$pagenum\">".get_string("previous")."</a>)&nbsp;";
1993 }
1994
1995 //Add first
1996 $code .= $firstpagecode;
1997
1998 $pagenum = $pagefrom;
1999
2000 //List of maxdisplay pages
2001 while ($pagenum <= $pageto) {
2002 $pagetoshow = $pagenum +1;
2003 if ($pagenum == $page && !$specialselected) {
08ec7ec6 2004 $code .= "$separator<b>$pagetoshow</b>";
e2cf5316 2005 } else {
2006 $code .= "$separator<a href=\"{$baseurl}page=$pagenum\">$pagetoshow</a>";
2007 }
2008 $pagenum++;
2009 }
2010
2011 //Add last
2012 $code .= $lastpagecode;
2013
2014 //Next
2015 if ($page < $maxpage && $page < $maxpageallowed && $previousandnext) {
2016 $pagenum = $page + 1;
2017 $code .= "$separator(<a href=\"{$baseurl}page=$pagenum\">".get_string("next")."</a>)";
2018 }
2019
2020 //Add special
2021 if ($showspecial) {
2022 $code .= '<br />';
2023 if ($specialselected) {
08ec7ec6 2024 $code .= "<b>$specialtext</b>";
e2cf5316 2025 } else {
2026 $code .= "$separator<a href=\"{$baseurl}page=$specialvalue\">$specialtext</a>";
2027 }
2028 }
2029
2030 //End html
2031 $code .= "</p>";
36a2b6bd 2032 $code .= "</div>";
e2cf5316 2033 }
2034
2035 return $code;
2036}
2037
f3221af9 2038function glossary_get_view_actions() {
2039 return array('view','view all','view entry');
2040}
2041
2042function glossary_get_post_actions() {
2043 return array('add category','add comment','add entry','approve entry','delete category','delete comment','delete entry','edit category','update comment','update entry');
2044}
2045
0b5a80a1 2046
2047/**
2048 * Implementation of the function for printing the form elements that control
2049 * whether the course reset functionality affects the glossary.
2050 * @param $mform form passed by reference
2051 */
2052function glossary_reset_course_form_definition(&$mform) {
2053 $mform->addElement('header', 'glossaryheader', get_string('modulenameplural', 'glossary'));
2054 $mform->addElement('checkbox', 'reset_glossary_all', get_string('resetglossariesall','glossary'));
2055
2056 $mform->addElement('select', 'reset_glossary_types', get_string('resetglossaries', 'glossary'),
2057 array('main'=>get_string('mainglossary', 'glossary'), 'secondary'=>get_string('secondaryglossary', 'glossary')), array('multiple' => 'multiple'));
2058 $mform->setAdvanced('reset_glossary_types');
2059 $mform->disabledIf('reset_glossary_types', 'reset_glossary_all', 'checked');
2060
2061 $mform->addElement('checkbox', 'reset_glossary_notenrolled', get_string('deletenotenrolled', 'glossary'));
2062 $mform->disabledIf('reset_glossary_notenrolled', 'reset_glossary_all', 'checked');
2063
2064 $mform->addElement('checkbox', 'reset_glossary_ratings', get_string('deleteallratings'));
2065 $mform->disabledIf('reset_glossary_ratings', 'reset_glossary_all', 'checked');
2066
2067 $mform->addElement('checkbox', 'reset_glossary_comments', get_string('deleteallcomments'));
2068 $mform->disabledIf('reset_glossary_comments', 'reset_glossary_all', 'checked');
2069}
2070
2071/**
2072 * Course reset form defaults.
2073 */
2074function glossary_reset_course_form_defaults($course) {
2075 return array('reset_glossary_all'=>0, 'reset_glossary_ratings'=>1, 'reset_glossary_comments'=>1, 'reset_glossary_notenrolled'=>0);
2076}
2077
2078/**
2079 * Removes all grades from gradebook
2080 * @param int $courseid
2081 * @param string optional type
2082 */
2083function glossary_reset_gradebook($courseid, $type='') {
ae8c3566 2084 global $DB;
0b5a80a1 2085
2086 switch ($type) {
2087 case 'main' : $type = "AND g.mainglossary=1"; break;
2088 case 'secondary' : $type = "AND g.mainglossary=0"; break;
2089 default : $type = ""; //all
2090 }
2091
2092 $sql = "SELECT g.*, cm.idnumber as cmidnumber, g.course as courseid
ae8c3566 2093 FROM {glossary} g, {course_modules} cm, {modules} m
2094 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id AND g.course=? $type";
0b5a80a1 2095
ae8c3566 2096 if ($glossarys = $DB->get_records_sql($sql, array($courseid))) {
0b5a80a1 2097 foreach ($glossarys as $glossary) {
2098 glossary_grade_item_update($glossary, 'reset');
2099 }
2100 }
2101}
2102/**
2103 * Actual implementation of the rest coures functionality, delete all the
2104 * glossary responses for course $data->courseid.
2105 * @param $data the data submitted from the reset course.
2106 * @return array status array
2107 */
2108function glossary_reset_userdata($data) {
ae8c3566 2109 global $CFG, $DB;
0b5a80a1 2110
2111 $componentstr = get_string('modulenameplural', 'glossary');
2112 $status = array();
2113
2114 $allentriessql = "SELECT e.id
ae8c3566 2115 FROM {glossary_entries} e
2116 JOIN {glossary} g ON e.glossaryid = g.id
2117 WHERE g.course = ?";
0b5a80a1 2118
2119 $allglossariessql = "SELECT g.id
ae8c3566 2120 FROM {glossary} g
2121 WHERE g.course = ?";
2122
2123 $params = array($data->courseid);
0b5a80a1 2124
49bcd737 2125 $fs = get_file_storage();
2126
0b5a80a1 2127 // delete entries if requested
2128 if (!empty($data->reset_glossary_all)
2129 or (!empty($data->reset_glossary_types) and in_array('main', $data->reset_glossary_types) and in_array('secondary', $data->reset_glossary_types))) {
2130
ae8c3566 2131 $DB->delete_records_select('glossary_ratings', "entryid IN ($allentriessql)", $params);
2132 $DB->delete_records_select('glossary_comments', "entryid IN ($allentriessql)", $params);
2133 $DB->delete_records_select('glossary_entries', "glossaryid IN ($allglossariessql)", $params);
0b5a80a1 2134
49bcd737 2135 // now get rid of all attachments
ae8c3566 2136 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
0b5a80a1 2137 foreach ($glossaries as $glossaryid=>$unused) {
49bcd737 2138 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2139 continue;
2140 }
2141 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2142 $fs->delete_area_files($context->id, 'glossary_attachment');
0b5a80a1 2143 }
2144 }
2145
2146 // remove all grades from gradebook
2147 if (empty($data->reset_gradebook_grades)) {
2148 glossary_reset_gradebook($data->courseid);
2149 }
2150
2151 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossariesall', 'glossary'), 'error'=>false);
2152
2153 } else if (!empty($data->reset_glossary_types)) {
2154 $mainentriessql = "$allentries AND g.mainglossary=1";
2155 $secondaryentriessql = "$allentries AND g.mainglossary=0";
2156
2157 $mainglossariessql = "$allglossariessql AND g.mainglossary=1";
2158 $secondaryglossariessql = "$allglossariessql AND g.mainglossary=0";
2159
2160 if (in_array('main', $data->reset_glossary_types)) {
ae8c3566 2161 $DB->delete_records_select('glossary_ratings', "entryid IN ($mainentriessql)", $params);
2162 $DB->delete_records_select('glossary_comments', "entryid IN ($mainentriessql)", $params);
2163 $DB->delete_records_select('glossary_entries', "glossaryid IN ($mainglossariessql)", $params);
0b5a80a1 2164
ae8c3566 2165 if ($glossaries = $DB->get_records_sql($mainglossariessql, $params)) {
0b5a80a1 2166 foreach ($glossaries as $glossaryid=>$unused) {
49bcd737 2167 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2168 continue;
2169 }
2170 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2171 $fs->delete_area_files($context->id, 'glossary_attachment');
0b5a80a1 2172 }
2173 }
2174
2175 // remove all grades from gradebook
2176 if (empty($data->reset_gradebook_grades)) {
2177 glossary_reset_gradebook($data->courseid, 'main');
2178 }
2179
2180 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary'), 'error'=>false);
2181
2182 } else if (in_array('secondary', $data->reset_glossary_types)) {
ae8c3566 2183 $DB->delete_records_select('glossary_ratings', "entryid IN ($secondaryentriessql)", $params);
2184 $DB->delete_records_select('glossary_comments', "entryid IN ($secondaryentriessql)", $params);
2185 $DB->delete_records_select('glossary_entries', "glossaryid IN ($secondaryglossariessql)", $params);
0b5a80a1 2186 // remove exported source flag from entries in main glossary
ae8c3566 2187 $DB->execute("UPDATE {glossary_entries
2188 SET sourceglossaryid=0
2189 WHERE glossaryid IN ($mainglossariessql)", $params);
0b5a80a1 2190
ae8c3566 2191 if ($glossaries = $DB->get_records_sql($secondaryglossariessql, $params)) {
0b5a80a1 2192 foreach ($glossaries as $glossaryid=>$unused) {
49bcd737 2193 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2194 continue;
2195 }
2196 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2197 $fs->delete_area_files($context->id, 'glossary_attachment');
0b5a80a1 2198 }
2199 }
2200
2201 // remove all grades from gradebook
2202 if (empty($data->reset_gradebook_grades)) {
2203 glossary_reset_gradebook($data->courseid, 'secondary');
2204 }
2205
2206 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('secondaryglossary', 'glossary'), 'error'=>false);
2207 }
2208 }
2209
2210 // remove entries by users not enrolled into course
2211 if (!empty($data->reset_glossary_notenrolled)) {
2212 $entriessql = "SELECT e.id, e.userid, e.glossaryid, u.id AS userexists, u.deleted AS userdeleted
ae8c3566 2213 FROM {glossary_entries} e
2214 JOIN {glossary} g ON e.glossaryid = g.id
2215 LEFT JOIN {user} u ON e.userid = u.id
2216 WHERE g.course = ? AND e.userid > 0";
0b5a80a1 2217
2218 $course_context = get_context_instance(CONTEXT_COURSE, $data->courseid);
2219 $notenrolled = array();
ae8c3566 2220 if ($rs = $DB->get_recordset_sql($entriessql, $params)) {
2221 foreach ($rs as $entry) {
0b5a80a1 2222 if (array_key_exists($entry->userid, $notenrolled) or !$entry->userexists or $entry->userdeleted
2223 or !has_capability('moodle/course:view', $course_context , $entry->userid)) {
ae8c3566 2224 $DB->delete_records('glossary_ratings', array('entryid'=>$entry->id));
2225 $DB->delete_records('glossary_comments', array('entryid'=>$entry->id));
2226 $DB->delete_records('glossary_entries', array('id'=>$entry->id));
49bcd737 2227
2228 if ($cm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
2229 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2230 $fs->delete_area_files($context->id, 'glossary_attachment', $entry->id);
2231 }
0b5a80a1 2232 }
2233 }
ae8c3566 2234 $rs->close();
0b5a80a1 2235 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'glossary'), 'error'=>false);
2236 }
2237 }
2238
2239 // remove all ratings
2240 if (!empty($data->reset_glossary_ratings)) {
ae8c3566 2241 $DB->delete_records_select('glossary_ratings', "entryid IN ($allentriessql)", $params);
0b5a80a1 2242 // remove all grades from gradebook
2243 if (empty($data->reset_gradebook_grades)) {
2244 glossary_reset_gradebook($data->courseid);
2245 }
2246 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2247 }
2248
2249 // remove all comments
2250 if (!empty($data->reset_glossary_comments)) {
ae8c3566 2251 $DB->delete_records_select('glossary_comments', "entryid IN ($allentriessql)", $params);
0b5a80a1 2252 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2253 }
2254
2255 /// updating dates - shift may be negative too
2256 if ($data->timeshift) {
2257 shift_course_mod_dates('glossary', array('assesstimestart', 'assesstimefinish'), $data->timeshift, $data->courseid);
2258 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2259 }
2260
2261 return $status;
2262}
2263
f432bebf 2264/**
2265 * Returns all other caps used in module
2266 */
2267function glossary_get_extra_capabilities() {
2268 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames', 'moodle/site:trustcontent');
2269}
2270
18a2a0cb 2271/**
2272 * @param string $feature FEATURE_xx constant for requested feature
2273 * @return mixed True if module supports feature, null if doesn't know
2274 */
2275function glossary_supports($feature) {
2276 switch($feature) {
42f103be 2277 case FEATURE_GROUPS: return false;
2278 case FEATURE_GROUPINGS: return false;
2279 case FEATURE_GROUPMEMBERSONLY: return true;
2280 case FEATURE_MODEDIT_INTRO_EDITOR: return true;
18a2a0cb 2281 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
42f103be 2282 case FEATURE_GRADE_HAS_GRADE: return true;
2283 case FEATURE_GRADE_OUTCOMES: return true;
2284
18a2a0cb 2285 default: return null;
2286 }
2287}
2288
6c0a9413 2289class glossary_csv_portfolio_caller extends portfolio_module_caller_base {
2290
2291 private $glossary;
84a44985 2292 private $exportdata;
6c0a9413 2293
0d06b6fd 2294 public static function expected_callbackargs() {
2295 return array(
2296 'id' => true,
2297 );
2298 }
2299
2300 public function load_data() {
6c0a9413 2301 global $DB;
0d06b6fd 2302 if (!$this->cm = get_coursemodule_from_id('glossary', $this->id)) {
34035201 2303 throw new portfolio_caller_exception('invalidid', 'glossary');
6c0a9413 2304 }
2305 if (!$this->glossary = $DB->get_record('glossary', array('id' => $this->cm->instance))) {
34035201 2306 throw new portfolio_caller_exception('invalidid', 'glossary');
6c0a9413 2307 }
2308 $entries = $DB->get_records('glossary_entries', array('glossaryid' => $this->glossary->id));
2309 list($where, $params) = $DB->get_in_or_equal(array_keys($entries));
2310
77ac22a5 2311 $aliases = $DB->get_records_select('glossary_alias', 'entryid ' . $where, $params);
6c0a9413 2312 $categoryentries = $DB->get_records_sql('SELECT ec.entryid, c.name FROM {glossary_entries_categories} ec
2313 JOIN {glossary_categories} c
2314 ON c.id = ec.categoryid
2315 WHERE ec.entryid ' . $where, $params);
2316
84a44985 2317 $this->exportdata = array('entries' => $entries, 'aliases' => $aliases, 'categoryentries' => $categoryentries);
6c0a9413 2318 }
2319
2320 public function expected_time() {
d8606b20 2321 return portfolio_expected_time_db(count($this->exportdata['entries']));
6c0a9413 2322 }
2323
2324 public function get_sha1() {
84a44985 2325 return sha1(serialize($this->exportdata));
6c0a9413 2326 }
2327
d67bfc32 2328 public function prepare_package() {
84a44985 2329 $entries = $this->exportdata['entries'];
6c0a9413 2330 $aliases = array();
2331 $categories = array();
84a44985 2332 if (is_array($this->exportdata['aliases'])) {
2333 foreach ($this->exportdata['aliases'] as $alias) {
6c0a9413 2334 if (!array_key_exists($alias->entryid, $aliases)) {
2335 $aliases[$alias->entryid] = array();
2336 }
2337 $aliases[$alias->entryid][] = $alias->alias;
2338 }
2339 }
84a44985 2340 if (is_array($this->exportdata['categoryentries'])) {
2341 foreach ($this->exportdata['categoryentries'] as $cat) {
6c0a9413 2342 if (!array_key_exists($cat->entryid, $categories)) {
2343 $categories[$cat->entryid] = array();
2344 }
2345 $categories[$cat->entryid][] = $cat->name;
2346 }
2347 }
2348 $csv = glossary_generate_export_csv($entries, $aliases, $categories);
6be1dcae 2349 return $this->exporter->write_new_file($csv, clean_filename($this->cm->name) . '.csv', false);
6c0a9413 2350 }
2351
2352 public function check_permissions() {
86a3996d 2353 return has_capability('mod/glossary:export', get_context_instance(CONTEXT_MODULE, $this->cm->id));
6c0a9413 2354 }
2355
2356 public static function display_name() {
2357 return get_string('modulename', 'glossary');
2358 }
2359}
49a12552 2360
2361class glossary_entry_portfolio_caller extends portfolio_module_caller_base {
2362
2363 private $glossary;
2364 private $entry;
0d06b6fd 2365 protected $entryid;
49a12552 2366
0d06b6fd 2367 public static function expected_callbackargs() {
2368 return array(
2369 'entryid' => true,
2370 'id' => true,
2371 );
2372 }
2373
2374 public function load_data() {
49a12552 2375 global $DB;
0d06b6fd 2376 if (!$this->cm = get_coursemodule_from_id('glossary', $this->id)) {
34035201 2377 throw new portfolio_caller_exception('invalidid', 'glossary');
49a12552 2378 }
2379 if (!$this->glossary = $DB->get_record('glossary', array('id' => $this->cm->instance))) {
34035201 2380 throw new portfolio_caller_exception('invalidid', 'glossary');
49a12552 2381 }
0d06b6fd 2382 if ($this->entryid) {
2383 if (!$this->entry = $DB->get_record('glossary_entries', array('id' => $this->entryid))) {
2384 throw new portfolio_caller_exception('noentry', 'glossary');
2385 }
2386 // in case we don't have USER this will make the entry be printed
2387 $this->entry->approved = true;
49a12552 2388 }
6be1dcae 2389 $this->supportedformats = array(PORTFOLIO_FORMAT_PLAINHTML);
49a12552 2390 }
2391
2392 public function expected_time() {
2393 return PORTFOLIO_TIME_LOW;
2394 }
2395
2396 public function check_permissions() {
86a3996d 2397 $context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
2398 return has_capability('mod/glossary:exportentry', $context)
2399 || ($this->entry->userid == $this->user->id && has_capability('mod/glossary:exportownentry', $context));
49a12552 2400 }
2401
2402 public static function display_name() {
ad1cfbb1 2403 return get_string('modulename', 'glossary');
49a12552 2404 }
2405
d67bfc32 2406 public function prepare_package() {
84a44985 2407 define('PORTFOLIO_INTERNAL', true);
49a12552 2408 ob_start();
0d06b6fd 2409 $entry = clone $this->entry;
2410 glossary_print_entry($this->get('course'), $this->cm, $this->glossary, $entry, null, null, false);
49a12552 2411 $content = ob_get_clean();
6be1dcae 2412 return $this->exporter->write_new_file($content, clean_filename($this->entry->concept) . '.html', false);
49a12552 2413 }
2414
2415 public function get_sha1() {
84a44985 2416 return sha1(serialize($this->entry));
49a12552 2417 }
2418}