2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
22 * @copyright 2007 j.beedell@open.ac.uk
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 require_once $CFG->dirroot
.'/tag/lib.php';
29 * Returns an ordered array of tags associated with visible courses
30 * (boosted replacement of get_all_tags() allowing association with user and tagtype).
34 * @param int $courseid A course id. Passing 0 will return all distinct tags for all visible courses
35 * @param int $userid (optional) the user id, a default of 0 will return all users tags for the course
36 * @param string $tagtype (optional) The type of tag, empty string returns all types. Currently (Moodle 2.2) there are two
37 * types of tags which are used within Moodle, they are 'official' and 'default'.
38 * @param int $numtags (optional) number of tags to display, default of 80 is set in the block, 0 returns all
39 * @param string $sort (optional) selected sorting, default is alpha sort (name) also timemodified or popularity
42 function coursetag_get_tags($courseid, $userid=0, $tagtype='', $numtags=0, $sort='name') {
46 // get visible course ids
47 $courselist = array();
48 if ($courseid === 0) {
49 if ($courses = $DB->get_records_select('course', 'visible=1 AND category>0', null, '', 'id')) {
50 foreach ($courses as $key => $value) {
56 // get tags from the db ordered by highest count first
58 $sql = "SELECT id as tkey, name, id, tagtype, rawname, f.timemodified, flag, count
60 (SELECT tagid, MAX(timemodified) as timemodified, COUNT(id) as count
62 WHERE itemtype = 'course' ";
65 $sql .= " AND itemid = :courseid ";
66 $params['courseid'] = $courseid;
68 if (!empty($courselist)) {
69 list($usql, $uparams) = $DB->get_in_or_equal($courselist, SQL_PARAMS_NAMED
);
70 $sql .= "AND itemid $usql ";
71 $params = $params +
$uparams;
76 $sql .= " AND tiuserid = :userid ";
77 $params['userid'] = $userid;
80 $sql .= " GROUP BY tagid) f
81 WHERE t.id = f.tagid ";
83 $sql .= "AND tagtype = :tagtype ";
84 $params['tagtype'] = $tagtype;
86 $sql .= "ORDER BY count DESC, name ASC";
88 // limit the number of tags for output
90 $tags = $DB->get_records_sql($sql, $params);
92 $tags = $DB->get_records_sql($sql, $params, 0, $numtags);
98 // sort the tag display order
99 if ($sort != 'popularity') {
100 $CFG->tagsort
= $sort;
101 usort($tags, "coursetag_sort");
103 // avoid print_tag_cloud()'s ksort upsetting ordering by setting the key here
104 foreach ($tags as $value) {
114 * Returns an ordered array of tags
115 * (replaces popular_tags_count() allowing sorting).
119 * @param string $sort (optional) selected sorting, default is alpha sort (name) also timemodified or popularity
120 * @param int $numtags (optional) number of tags to display, default of 20 is set in the block, 0 returns all
123 function coursetag_get_all_tags($sort='name', $numtags=0) {
127 // note that this selects all tags except for courses that are not visible
128 $sql = "SELECT id, name, tagtype, rawname, f.timemodified, flag, count
130 (SELECT tagid, MAX(timemodified) as timemodified, COUNT(id) as count
131 FROM {tag_instance} WHERE tagid NOT IN
132 (SELECT tagid FROM {tag_instance} ti, {course} c
134 AND ti.itemtype = 'course'
135 AND ti.itemid = c.id)
138 ORDER BY count DESC, name ASC";
140 $tags = $DB->get_records_sql($sql);
142 $tags = $DB->get_records_sql($sql, null, 0, $numtags);
147 if ($sort != 'popularity') {
148 $CFG->tagsort
= $sort;
149 usort($tags, "coursetag_sort");
151 foreach ($tags as $value) {
160 * Sorting callback function for coursetag_get_tags() and coursetag_get_all_tags() only
162 * This function does a comparision on a field withing two variables, $a and $b. The field used is specified by
163 * $CFG->tagsort or we just use the 'name' field if $CFG->tagsort is empty. The comparison works as follows:
164 * If $a->$tagsort is greater than $b->$tagsort, 1 is returned.
165 * If $a->$tagsort is equal to $b->$tagsort, 0 is returned.
166 * If $a->$tagsort is less than $b->$tagsort, -1 is returned.
168 * Also if $a->$tagsort is not numeric or a string, 0 is returned.
172 * @param int|string|mixed $a Variable to compare against $b
173 * @param int|string|mixed $b Variable to compare against $a
174 * @return int The result of the comparison/validation 1, 0 or -1
176 function coursetag_sort($a, $b) {
177 // originally from block_blog_tags
180 // set up the variable $tagsort as either 'name' or 'timemodified' only, 'popularity' does not need sorting
181 if (empty($CFG->tagsort
)) {
184 $tagsort = $CFG->tagsort
;
187 if (is_numeric($a->$tagsort)) {
188 return ($a->$tagsort == $b->$tagsort) ?
0 : ($a->$tagsort > $b->$tagsort) ?
1 : -1;
189 } elseif (is_string($a->$tagsort)) {
190 return strcmp($a->$tagsort, $b->$tagsort);
201 * @param array $tagcloud array of tag objects (fields: id, name, rawname, count and flag)
202 * @param mixed $return if true return html string
203 * @param int $max_size maximum text size, in percentage
204 * @param int $min_size minimum text size, in percentage
206 function coursetag_print_cloud($tagcloud, $return=false, $max_size=180, $min_size=80) {
210 if (empty($tagcloud)) {
217 foreach ($tagcloud as $key => $value) {
218 if(!empty($value->count
)) {
219 $count[$key] = log10($value->count
);
228 $spread = $max - $min;
229 if (0 == $spread) { // we don't want to divide by zero
233 $step = ($max_size - $min_size)/($spread);
235 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
236 $can_manage_tags = has_capability('moodle/tag:manage', $systemcontext);
238 //prints the tag cloud
239 $output = '<ul class="tag-cloud inline-list">';
240 foreach ($tagcloud as $key => $tag) {
242 $size = $min_size +
((log10($tag->count
) - $min) * $step);
245 $style = 'style="font-size: '.$size.'%"';
247 if ($tag->count
> 1) {
248 $title = 'title="'.s(get_string('thingstaggedwith','tag', $tag)).'"';
250 $title = 'title="'.s(get_string('thingtaggedwith','tag', $tag)).'"';
253 $href = 'href="'.$CFG->wwwroot
.'/tag/index.php?id='.$tag->id
.'"';
255 //highlight tags that have been flagged as inappropriate for those who can manage them
256 $tagname = tag_display_name($tag);
257 if ($tag->flag
> 0 && $can_manage_tags) {
258 $tagname = '<span class="flagged-tag">' . tag_display_name($tag) . '</span>';
261 $tag_link = '<li><a '.$href.' '.$title.' '. $style .'>'.$tagname.'</a></li> ';
263 $output .= $tag_link;
266 $output .= '</ul>'."\n";
276 * Returns javascript for use in tags block and supporting pages
280 * @param string $coursetagdivs comma separated divs ids
283 function coursetag_get_jscript($coursetagdivs = '') {
284 global $CFG, $DB, $PAGE;
286 $PAGE->requires
->js('/tag/tag.js');
287 $PAGE->requires
->strings_for_js(array('jserror1', 'jserror2'), 'block_tags');
289 if ($coursetagdivs) {
290 $PAGE->requires
->js_function_call('set_course_tag_divs', $coursetagdivs);
293 if ($coursetags = $DB->get_records('tag', null, 'name ASC', 'name, id')) {
294 foreach ($coursetags as $key => $value) {
295 $PAGE->requires
->js_function_call('set_course_tag', array($key));
299 $PAGE->requires
->js('/blocks/tags/coursetags.js');
305 * Returns javascript to create the links in the tag block footer.
309 * @param string $elementid the element to attach the footer to
310 * @param array $coursetagslinks links arrays each consisting of 'title', 'onclick' and 'text' elements
311 * @return string always returns a blank string
313 function coursetag_get_jscript_links($elementid, $coursetagslinks) {
316 if (!empty($coursetagslinks)) {
317 foreach ($coursetagslinks as $a) {
318 $PAGE->requires
->js_function_call('add_tag_footer_link', array($elementid, $a['title'], $a['onclick'], $a['text']), true);
326 * Returns all tags created by a user for a course
330 * @param int $courseid tags are returned for the course that has this courseid
331 * @param int $userid return tags which were created by this user
333 function coursetag_get_records($courseid, $userid) {
336 $sql = "SELECT t.id, name, rawname
337 FROM {tag} t, {tag_instance} ti
338 WHERE t.id = ti.tagid
339 AND ti.tiuserid = :userid
340 AND ti.itemid = :courseid
343 return $DB->get_records_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid));
347 * Stores a tag for a course for a user
351 * @param array $tags simple array of keywords to be stored
352 * @param int $courseid the id of the course we wish to store a tag for
353 * @param int $userid the id of the user we wish to store a tag for
354 * @param string $tagtype official or default only
355 * @param string $myurl (optional) for logging creation of course tags
357 function coursetag_store_keywords($tags, $courseid, $userid=0, $tagtype='official', $myurl='') {
361 if (is_array($tags) and !empty($tags)) {
362 foreach($tags as $tag) {
364 if (strlen($tag) > 0) {
365 //tag_set_add('course', $courseid, $tag, $userid); //deletes official tags
367 //add tag if does not exist
368 if (!$tagid = tag_get_id($tag)) {
369 $tag_id_array = tag_add(array($tag), $tagtype);
370 $tagid = $tag_id_array[textlib
::strtolower($tag)];
374 if ($current_ids = tag_get_tags_ids('course', $courseid)) {
376 $ordering = key($current_ids) +
1;
379 tag_type_set($tagid, $tagtype);
382 tag_assign('course', $courseid, $tagid, $ordering, $userid);
384 //logging - note only for user added tags
385 if ($tagtype == 'default' and $myurl != '') {
386 $url = $myurl.'?query='.urlencode($tag);
387 add_to_log($courseid, 'coursetags', 'add', $url, 'Course tagged');
396 * Deletes a personal tag for a user for a course.
400 * @param int $tagid the tag we wish to delete
401 * @param int $userid the user that the tag is associated with
402 * @param int $courseid the course that the tag is associated with
404 function coursetag_delete_keyword($tagid, $userid, $courseid) {
408 $sql = "SELECT COUNT(*)
411 AND tiuserid = $userid
412 AND itemtype = 'course'
413 AND itemid = $courseid";
414 if ($DB->count_records_sql($sql) == 1) {
415 $sql = "tagid = $tagid
416 AND tiuserid = $userid
417 AND itemtype = 'course'
418 AND itemid = $courseid";
419 $DB->delete_records_select('tag_instance', $sql);
420 // if there are no other instances of the tag then consider deleting the tag as well
421 if (!$DB->record_exists('tag_instance', array('tagid' => $tagid))) {
422 // if the tag is a personal tag then delete it - don't do official tags
423 if ($DB->record_exists('tag', array('id' => $tagid, 'tagtype' => 'default'))) {
424 $DB->delete_records('tag', array('id' => $tagid, 'tagtype' => 'default'));
428 print_error("errordeleting", 'tag', '', $tagid);
434 * Get courses tagged with a tag
439 * @return array of course objects
441 function coursetag_get_tagged_courses($tagid) {
445 if ($crs = $DB->get_records_select('tag_instance', "tagid=:tagid AND itemtype='course'", array('tagid'=>$tagid))) {
446 foreach ($crs as $c) {
447 $course = $DB->get_record('course', array('id'=>$c->itemid
));
448 // check if the course is hidden
449 if ($course->visible
== 1 ||
has_capability('moodle/course:viewhiddencourses', context_course
::instance($course->id
))) {
450 $courses[$c->itemid
] = $course;
459 * Course tagging function used only during the deletion of a course (called by lib/moodlelib.php) to clean up associated tags
462 * @param int $courseid the course we wish to delete tag instances from
463 * @param bool $showfeedback if we should output a notification of the delete to the end user
465 function coursetag_delete_course_tags($courseid, $showfeedback=false) {
468 if ($tags = $DB->get_records_select('tag_instance', "itemtype='course' AND itemid=:courseid", array('courseid'=>$courseid))) {
469 foreach ($tags as $tag) {
470 //delete the course tag instance record
471 $DB->delete_records('tag_instance', array('tagid'=>$tag->tagid
, 'itemtype'=>'course', 'itemid'=> $courseid));
472 // delete tag if there are no other tag_instance entries now
473 if (!($DB->record_exists('tag_instance', array('tagid'=>$tag->tagid
)))) {
474 $DB->delete_records('tag', array('id'=>$tag->tagid
));
476 $fs = get_file_storage();
477 $fs->delete_area_files(get_system_context()->id
, 'tag', 'description', $tag->tagid
);
483 echo $OUTPUT->notification(get_string('deletedcoursetags', 'tag'), 'notifysuccess');
488 * Function called by cron to create/update users rss feeds
493 * rsslib.php needs updating to accept Dublin Core tags (dc/cc) input before this can work.
496 function coursetag_rss_feeds() {
499 require_once($CFG->dirroot.'/lib/dmllib.php');
500 require_once($CFG->dirroot.'/lib/rsslib.php');
503 mtrace(' Preparing to update all user unit tags RSS feeds');
504 if (empty($CFG->enablerssfeeds)) {
505 mtrace(' RSS DISABLED (admin variables - enablerssfeeds)');
508 // Load all the categories for use later on
509 $categories = $DB->get_records('course_categories');
511 // get list of users who have tagged a unit
513 SELECT DISTINCT u.id as userid, u.username, u.firstname, u.lastname, u.email
514 FROM {user} u, {course} c, {tag_instance} cti, {tag} t
515 WHERE c.id = cti.itemid
516 AND u.id = cti.tiuserid
518 AND t.tagtype = 'personal'
522 if ($users = $DB->get_records_sql($sql)) {
524 $items = array(); //contains rss data items for each user
525 foreach ($users as $user) {
527 // loop through each user, getting the data (tags for courses)
529 SELECT cti.id, c.id as courseid, c.fullname, c.shortname, c.category, t.rawname, cti.timemodified
530 FROM {course} c, {tag_instance} cti, {tag} t
531 WHERE c.id = cti.itemid
532 AND cti.tiuserid = :userid{$user->userid}
534 AND t.tagtype = 'personal'
536 if ($usertags = $DB->get_records_sql($sql, array('userid' => $user->userid))) {
537 $latest_date = 0; //latest date any tag was created by a user
538 $c = 0; //course identifier
540 foreach ($usertags as $usertag) {
541 if ($usertag->courseid != $c) {
542 $c = $usertag->courseid;
543 $items[$c] = new stdClass();
544 $items[$c]->title = $usertag->fullname . '(' . $usertag->shortname . ')';
545 $items[$c]->link = $CFG->wwwroot . '/course/view.php?name=' . $usertag->shortname;
546 $items[$c]->description = ''; //needs to be blank
547 $items[$c]->category = $categories[$usertag->category]->name;
548 $items[$c]->subject[] = $usertag->rawname;
549 $items[$c]->pubdate = $usertag->timemodified;
550 $items[$c]->tag = true;
552 $items[$c]->subject[] .= $usertag->rawname;
554 // Check and set the latest modified date.
555 $latest_date = $usertag->timemodified > $latest_date ? $usertag->timemodified : $latest_date;
558 // Setup some vars for use while creating the file
559 $path = $CFG->dataroot.'/1/usertagsrss/'.$user->userid;
560 $file_name = 'user_unit_tags_rss.xml';
561 $title = get_string('rsstitle', 'tag', ucwords(strtolower($user->firstname.' '.$user->lastname)));
562 $desc = get_string('rssdesc', 'tag');
563 // check that the path exists
564 if (!file_exists($path)) {
565 mtrace(' Creating folder '.$path);
566 check_dir_exists($path, TRUE, TRUE);
569 // create or update the feed for the user
570 // this functionality can be copied into seperate lib as in next two lines
571 //require_once($CFG->dirroot.'/local/ocilib.php');
572 //oci_create_rss_feed( $path, $file_name, $latest_date, $items, $title, $desc, $dc=true, $cc=false);
574 // Set path to RSS file
575 $full_path = "$save_path/$file_name";
577 mtrace(" Preparing to update RSS feed for $file_name");
579 // First let's make sure there is work to do by checking the time the file was last modified,
580 // if a course was update after the file was mofified
581 if (file_exists($full_path)) {
582 if ($lastmodified = filemtime($full_path)) {
583 mtrace(" XML File $file_name Created on ".date( "D, j M Y G:i:s T", $lastmodified ));
584 mtrace(' Lastest course modification on '.date( "D, j M Y G:i:s T", $latest_date ));
585 if ($latest_date > $lastmodified) {
586 mtrace(" XML File $file_name needs updating");
589 mtrace(" XML File $file_name doesn't need updating");
594 mtrace(" XML File $file_name needs updating");
599 // Now we know something has changed, write the new file
601 if (!empty($items)) {
602 // First set rss feeds common headers
603 $header = rss_standard_header(strip_tags(format_string($title,true)),
607 // Now all the rss items
608 if (!empty($header)) {
609 $articles = rss_add_items($items,$dc,$cc);
611 // Now all rss feeds common footers
612 if (!empty($header) && !empty($articles)) {
613 $footer = rss_standard_footer();
615 // Now, if everything is ok, concatenate it
616 if (!empty($header) && !empty($articles) && !empty($footer)) {
617 $result = $header.$articles.$footer;
625 // Save the XML contents to file
626 if (!empty($result)) {
627 $rss_file = fopen($full_path, "w");
629 $status = fwrite ($rss_file, $result);
637 if (empty($result)) {
638 // There was nothing to put into the XML file. Delete it!
639 if( is_file($full_path) ) {
640 mtrace(" There were no items for XML File $file_name. Deleting XML File");
642 mtrace(" $full_path -> (deleted)");
644 mtrace(" There were no items for the XML File $file_name and no file to delete. Ignore.");
647 if (!empty($status)) {
648 mtrace(" $full_path -> OK");
650 mtrace(" $full_path -> FAILED");
654 //end of oci_create_rss_feed()
665 * Get official keywords for the <meta name="keywords"> in header.html
666 * use: echo '<meta name="keywords" content="'.coursetag_get_official_keywords($COURSE->id).'"/>';
668 * @param int $courseid
671 * Function removed but fully working
672 * This function is potentially useful to anyone wanting to improve search results for course pages.
673 * The idea is to add official tags (not personal tags to prevent their deletion) to all
674 * courses (facility not added yet) which will be automatically added to the page header to boost
675 * search engine specificity/ratings.
678 function coursetag_get_official_keywords($courseid, $asarray=false) {
681 $sql = "SELECT t.id, name, rawname
682 FROM {tag} t, {tag_instance} ti
683 WHERE ti.itemid = :courseid
684 AND ti.itemtype = 'course'
685 AND t.tagtype = 'official'
688 if ($tags = $DB->get_records_sql($sql, array('courseid' => $courseid))) {
692 foreach ($tags as $tag) {
693 if( empty($CFG->keeptagnamecase) ) {
694 $name = textlib::strtotitle($tag->name);
696 $name = $tag->rawname;
698 $returnstr .= $name.', ';
700 $returnstr = rtrim($returnstr, ', ');