MDL-13116 lang string typo fix
[moodle.git] / tag / lib.php
CommitLineData
1aebe71e 1<?php
d4be9d6d 2
b3541b6a 3define('DEFAULT_TAG_TABLE_FIELDS', 'id, tagtype, name, rawname, flag');
4d4dac81 4
c933a060 5/**
6 * Creates tags
7
8 * Ex: tag_create('A VeRY cOoL Tag, Another NICE tag')
d4be9d6d 9 * will create the following normalized {@link tag_normalize()} entries in tags table:
10 * 'a very cool tag'
c933a060 11 * 'another nice tag'
d4be9d6d 12 *
c933a060 13 * @param string $tag_names_csv CSV tag names (can be unnormalized) to be created.
14 * @param string $tag_type type of tag to be created ("default" is the default value).
15 * @return an array of tags ids, indexed by their normalized names
16 */
17function tag_create($tag_names_csv, $tag_type="default") {
18 global $USER;
ab86d9c7 19 $textlib = textlib_get_instance();
d4be9d6d 20
4f81c51d 21 $tags = explode(",", $tag_names_csv );
c933a060 22
23 $tag_object = new StdClass;
24 $tag_object->tagtype = $tag_type;
25 $tag_object->userid = $USER->id;
26
27 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
28 $can_create_tags = has_capability('moodle/tag:create',$systemcontext);
3d436d8a 29
4f81c51d 30 $norm_tag_names_csv = '';
31 foreach ($tags as $tag) {
c933a060 32
4f81c51d 33 // rawname keeps the original casing of the string
34 $tag_object->rawname = tag_normalize($tag, false);
3d436d8a 35
26d8649f 36 // name lowercases the string
4f81c51d 37 $tag_object->name = tag_normalize($tag);
38 $norm_tag_names_csv .= $tag_object->name . ',';
26d8649f 39
3d436d8a 40 $tag_object->timemodified = time();
41
26d8649f 42 $exists = record_exists('tag', 'name', $tag_object->name);
3d436d8a 43
3a597ace 44 if ( !$exists && is_tag_name_valid($tag_object->name) ) {
3d436d8a 45 if ($can_create_tags) {
46 insert_record('tag', $tag_object);
47 }
48 else {
49 require_capability('moodle/tag:create',$systemcontext);
50 }
c933a060 51 }
52 }
53
ab86d9c7 54 $norm_tag_names_csv = $textlib->substr($norm_tag_names_csv,0,-1);
3d436d8a 55
4f81c51d 56 return tags_id( $norm_tag_names_csv );
c933a060 57
58}
59
60/**
61 * Deletes tags
d4be9d6d 62 *
c933a060 63 * Ex 1: tag_delete('a very cool tag, another nice tag')
64 * Will delete the tags with names 'a very cool tag' and 'another nice tag' from the 'tags' table, if they exist!
65 *
66 * Ex 2: tag_delete('computers, 123, 143, algorithms')
67 * Will delete tags with names 'computers' and 'algorithms' and tags with ids 123 and 143.
d4be9d6d 68 *
69 *
c933a060 70 * @param string $tag_names_or_ids_csv **normalized** tag names or ids of the tags to be deleted.
71 */
72
73function tag_delete($tag_names_or_ids_csv) {
74
ab86d9c7 75 //covert all names to ids
76 $tag_ids_csv = tag_id_from_string($tag_names_or_ids_csv);
d4be9d6d 77
ab86d9c7 78 //put apostrophes
bd1f4559 79 $tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv) . "'";
c933a060 80
bd1f4559 81 // tag instances needs to be deleted as well
ab86d9c7 82 // delete_records_select('tag_instance',"tagid IN ($tag_ids_csv_with_apos)");
83 // Luiz: (in near future) tag instances should be cascade deleted by RDMS referential integrity constraints, when moodle implements it
84 // For now, tag_instance orphans should be removed using tag_instance_table_cleanup()
d4be9d6d 85
f458e359 86 $return1 = delete_records_select('tag',"name IN ($tag_ids_csv_with_apos)");
87 $return2 = delete_records_select('tag',"id IN ($tag_ids_csv_with_apos)");
88
89 return $return1 && $return2;
c933a060 90
91}
92
93/**
94 * Get all tags from the records
95 *
96 * @param string $tag_types_csv (optional, default value is "default". If '*' is passed, tags of any type will be returned).
97 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
d4be9d6d 98 * @param string $fields a comma separated list of fields to return
b3541b6a 99 * (optional, by default 'id, tagtype, name, rawname, flag'). The first field will be used as key for the
d4be9d6d 100 * array so must be a unique field such as 'id'.
c933a060 101 */
b3541b6a 102function get_all_tags($tag_types_csv="default", $sort='name ASC', $fields=DEFAULT_TAG_TABLE_FIELDS) {
3d436d8a 103
c933a060 104 if ($tag_types_csv == '*'){
105 return get_records('tag', '', '', $sort, $fields);
106 }
3d436d8a 107
c933a060 108 $tag_types_csv_with_apos = "'" . str_replace(',', "','", $tag_types_csv ) . "'";
3d436d8a 109
c933a060 110 return get_records_list('tag', 'tagtype', $tag_types_csv_with_apos, $sort, $fields);
111}
112
113/**
114 * Determines if a tag exists
115 *
116 * @param string $tag_name_or_id **normalized** tag name, or an id.
117 * @return true if exists or false otherwise
d4be9d6d 118 *
c933a060 119 */
120function tag_exists($tag_name_or_id) {
3d436d8a 121
c933a060 122 if (is_numeric($tag_name_or_id)) {
123 return record_exists('tag', 'id', $tag_name_or_id);
70e9b59d 124
125 } else {
126 // normalised tag names are always lowercase only
127 return record_exists('tag', 'name', moodle_strtolower($tag_name_or_id));
c933a060 128 }
129}
130
131/**
132 * Function that returns the id of a tag
133 *
134 * @param String $tag_name **normalized** name of the tag
135 * @return int id of the matching tag
136 */
137function tag_id($tag_name) {
138 $tag = get_record('tag', 'name', trim($tag_name), '', '', '', '', 'id');
3d436d8a 139
4f81c51d 140 if ($tag){
141 return $tag->id;
142 }
143 else{
144 return false;
3d436d8a 145 }
c933a060 146}
147
148/**
149 * Function that returns the ids of tags
d4be9d6d 150 *
c933a060 151 * Ex: tags_id('computers, algorithms')
d4be9d6d 152 *
c933a060 153 * @param String $tag_names_csv comma separated **normalized** tag names.
154 * @return Array array with the tags ids, indexed by their **normalized** names
155 */
156function tags_id($tag_names_csv) {
3d436d8a 157
c933a060 158 $normalized_tag_names_csv = tag_normalize($tag_names_csv);
159 $tag_names_csv_with_apos = "'" . str_replace(',', "','", $normalized_tag_names_csv ) . "'";
160
c933a060 161 $tags_ids = array();
70e9b59d 162
163 if ($tag_objects = get_records_list('tag','name', $tag_names_csv_with_apos, "" , "name, id" )) {
164 foreach ($tag_objects as $tag) {
165 $tags_ids[$tag->name] = $tag->id;
166 }
c933a060 167 }
168
169 return $tags_ids;
170}
171
172/**
173 * Function that returns the name of a tag
174 *
175 * @param int $tag_id id of the tag
176 * @return String name of the tag with the id passed
177 */
178function tag_name($tag_id) {
179 $tag = get_record('tag', 'id', $tag_id, '', '', '', '', 'name');
3d436d8a 180
4f81c51d 181 if ($tag){
182 return $tag->name;
183 }
184 else{
185 return '';
186 }
c933a060 187}
188
189/**
190 * Function that retrieves the names of tags given their ids
191 *
192 * @param String $tag_ids_csv comma separated tag ids
193 * @return Array an array with the tags names, indexed by their ids
194 */
195
196function tags_name($tag_ids_csv) {
3d436d8a 197
4f81c51d 198 //remove any white spaces
199 $tag_ids_csv = str_replace(' ', '', $tag_ids_csv);
3d436d8a 200
c933a060 201 $tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv ) . "'";
3d436d8a 202
c933a060 203 $tag_objects = get_records_list('tag','id', $tag_ids_csv_with_apos, "" , "name, id" );
204
205 $tags_names = array();
206 foreach ($tag_objects as $tag) {
207 $tags_names[$tag->id] = $tag->name;
208 }
209
210 return $tags_names;
211}
212
4f81c51d 213/**
d4be9d6d 214 * Function that returns the name of a tag for display.
215 *
4f81c51d 216 * @param mixed $tag_object
217 * @return string
218 */
219function tag_display_name($tag_object){
3d436d8a 220
4f81c51d 221 global $CFG;
3d436d8a 222
c91146b9 223 if( empty($CFG->keeptagnamecase) ) {
4f81c51d 224 //this is the normalized tag name
8e1ec6be 225 $textlib = textlib_get_instance();
e8515774 226 return $textlib->strtotitle($tag_object->name);
4f81c51d 227 }
228 else {
229 //original casing of the tag name
230 return $tag_object->rawname;
231 }
3d436d8a 232
4f81c51d 233}
234
c933a060 235/**
236 * Function that retrieves a tag object by its id
237 *
238 * @param String $tag_id
239 * @return mixed a fieldset object containing the first matching record, or false if none found
240 */
241function tag_by_id($tag_id) {
3d436d8a 242
c933a060 243 return get_record('tag','id',$tag_id);
244}
245
246/**
247 * Function that retrieves a tag object by its name
248 *
249 * @param String $tag_name
250 * @return mixed a fieldset object containing the first matching record, or false if none found
251 */
252function tag_by_name($tag_name) {
253 $tag = get_record('tag','name',$tag_name);
254 return $tag;
255}
256
257/**
4f81c51d 258 * In a comma separated string of ids or names of tags, replaces all tag names with their correspoding ids
d4be9d6d 259 *
260 * Ex:
4f81c51d 261 * Suppose the DB contains only the following entries in the tags table:
d4be9d6d 262 * id name
4f81c51d 263 * 10 moodle
264 * 12 science
265 * 22 education
d4be9d6d 266 *
4f81c51d 267 * tag_id_from_string('moodle, 12, education, programming, 33, 11')
268 * will return '10,12,22,,33,11'
d4be9d6d 269 *
c933a060 270 * This is a helper function used by functions of this API to process function arguments ($tag_name_or_id)
d4be9d6d 271 *
c933a060 272 * @param string $tag_names_or_ids_csv comma separated **normalized** names or ids of tags
d4be9d6d 273 * @return int comma separated ids of the tags
c933a060 274 */
275function tag_id_from_string($tag_names_or_ids_csv) {
276
277 $tag_names_or_ids = explode(',', $tag_names_or_ids_csv);
278
279 $tag_ids = array();
280 foreach ($tag_names_or_ids as $name_or_id) {
281
282 if (is_numeric($name_or_id)){
4f81c51d 283 $tag_ids[] = trim($name_or_id);
c933a060 284 }
285 elseif (is_string($name_or_id)) {
286 $tag_ids[] = tag_id( $name_or_id );
287 }
288
289 }
290
291 $tag_ids_csv = implode(',',$tag_ids);
292 $tag_ids_csv = str_replace(' ', '', $tag_ids_csv);
3d436d8a 293
4f81c51d 294 return $tag_ids_csv;
c933a060 295}
296
297/**
4f81c51d 298 * In a comma separated string of ids or names of tags, replaces all tag ids with their correspoding names
d4be9d6d 299 *
300 * Ex:
4f81c51d 301 * Suppose the DB contains only the following entries in the tags table:
d4be9d6d 302 * id name
4f81c51d 303 * 10 moodle
304 * 12 science
305 * 22 education
d4be9d6d 306 *
4f81c51d 307 * tag_name_from_string('mOOdle, 10, HiStOrY, 17, 22')
308 * will return the string 'mOOdle,moodle,HiStOrY,,education'
d4be9d6d 309 *
c933a060 310 * This is a helper function used by functions of this API to process function arguments ($tag_name_or_id)
d4be9d6d 311 *
b3541b6a 312 * @param string $tag_names_or_ids_csv comma separated names or ids of tags
d4be9d6d 313 * @return int comma separated names of the tags
c933a060 314 */
315function tag_name_from_string($tag_names_or_ids_csv) {
3d436d8a 316
c933a060 317 $tag_names_or_ids = explode(',', $tag_names_or_ids_csv);
318
319 $tag_names = array();
320 foreach ($tag_names_or_ids as $name_or_id) {
321
322 if (is_numeric($name_or_id)){
323 $tag_names[] = tag_name($name_or_id);
324 }
325 elseif (is_string($name_or_id)) {
4f81c51d 326 $tag_names[] = trim($name_or_id);
c933a060 327 }
328
329 }
330
331 $tag_names_csv = implode(',',$tag_names);
3d436d8a 332
4f81c51d 333 return $tag_names_csv;
3d436d8a 334
c933a060 335}
336
3a597ace 337
338/**
339 * Determines if a tag name is valid
340 *
341 * @param string $name
342 * @return boolean
343 */
344function is_tag_name_valid($name){
345
346 $normalized = tag_normalize($name);
347
348 return !strcmp($normalized, $name) && !empty($name) && !is_numeric($name);
349
350}
351
352
c933a060 353/**
354 * Associates a tag with an item
d4be9d6d 355 *
c933a060 356 * Ex 1: tag_an_item('user', '1', 'hisTOrY, RELIGIONS, roman' )
357 * This will tag an user whose id is 1 with "history", "religions", "roman"
358 * If the tag names passed do not exist, they will get created.
d4be9d6d 359 *
c933a060 360 * Ex 2: tag_an_item('user', '1', 'hisTory, 12, 11, roman')
361 * This will tag an user whose id is 1 with 'history', 'roman' and with tags of ids 12 and 11
d4be9d6d 362 *
c933a060 363 * @param string $item_type name of the table where the item is stored. Ex: 'user'
364 * @param string $item_id id of the item to be tagged
365 * @param string $tag_names_or_ids_csv comma separated tag names (can be unormalized) or ids of existing tags
366 * @param string $tag_type type of the tags that are beeing added (optional, default value is "default")
367 */
368
369function tag_an_item($item_type, $item_id, $tag_names_or_ids_csv, $tag_type="default") {
370
1acd661d 371 global $CFG;
c933a060 372 //convert any tag ids passed to their corresponding tag names
4f81c51d 373 $tag_names_csv = tag_name_from_string($tag_names_or_ids_csv);
3a597ace 374
c933a060 375 //create the tags
376 $tags_created_ids = tag_create($tag_names_csv,$tag_type);
377
1acd661d 378 //tag instances of an item are ordered, get the last one
379 $query = "
380 SELECT
932e97ea 381 MAX(ordering) AS max_order
1acd661d 382 FROM
383 {$CFG->prefix}tag_instance ti
384 WHERE
385 ti.itemtype = '{$item_type}'
386 AND
387 ti.itemid = '{$item_id}'
388 ";
3a597ace 389
390 $max_order = get_field_sql($query);
391
1acd661d 392 $tag_names = explode(',', tag_normalize($tag_names_csv));
3a597ace 393
1acd661d 394 $ordering = array();
395 foreach($tag_names as $tag_name){
396 $ordering[$tag_name] = ++$max_order;
397 }
3a597ace 398
1acd661d 399 //setup tag_instance object
c933a060 400 $tag_instance = new StdClass;
401 $tag_instance->itemtype = $item_type;
402 $tag_instance->itemid = $item_id;
3a597ace 403
404
c933a060 405 //create tag instances
1acd661d 406 foreach ($tags_created_ids as $tag_normalized_name => $tag_id) {
3d436d8a 407
c933a060 408 $tag_instance->tagid = $tag_id;
1acd661d 409 $tag_instance->ordering = $ordering[$tag_normalized_name];
bd1f4559 410 $tag_instance->timemodified = time();
1acd661d 411 $tag_instance_exists = get_record('tag_instance', 'tagid', $tag_id, 'itemtype', $item_type, 'itemid', $item_id);
3d436d8a 412
1acd661d 413 if (!$tag_instance_exists) {
26d8649f 414 insert_record('tag_instance',$tag_instance);
415 }
1acd661d 416 else {
bd1f4559 417 $tag_instance_exists->timemodified = time();
1acd661d 418 $tag_instance_exists->ordering = $ordering[$tag_normalized_name];
419 update_record('tag_instance',$tag_instance_exists);
420 }
c933a060 421 }
c933a060 422
3d436d8a 423
424 // update_tag_correlations($item_type, $item_id);
c933a060 425
426}
427
428
429/**
430 * Updates the tags associated with an item
d4be9d6d 431 *
c933a060 432 * Ex 1:
433 * Suppose user 1 is tagged only with "algorithms", "computers" and "software"
434 * By calling update_item_tags('user', 1, 'algorithms, software, mathematics')
435 * User 1 will now be tagged only with "algorithms", "software" and "mathematics"
d4be9d6d 436 *
c933a060 437 * Ex 2:
438 * update_item_tags('user', '1', 'algorithms, 12, 13')
439 * User 1 will now be tagged only with "algorithms", and with tags of ids 12 and 13
d4be9d6d 440 *
441 *
c933a060 442 * @param string $item_type name of the table where the item is stored. Ex: 'user'
443 * @param string $item_id id of the item to be tagged
444 * @param string $tag_names_or_ids_csv comma separated tag names (can be unormalized) or ids of existing tags
445 * @param string $tag_type type of the tags that are beeing added (optional, default value is "default")
446 */
447
448function update_item_tags($item_type, $item_id, $tag_names_or_ids_csv, $tag_type="default") {
3d436d8a 449
c933a060 450 //if $tag_names_csv is an empty string, remove all tag associations of the item
451 if( empty($tag_names_or_ids_csv) ){
452 untag_an_item($item_type, $item_id);
453 return;
454 }
3d436d8a 455
c933a060 456 //convert any tag ids passed to their corresponding tag names
3d436d8a 457 $tag_names_csv = tag_name_from_string($tag_names_or_ids_csv);
458
c933a060 459 //associate the tags passed with the item
460 tag_an_item($item_type, $item_id, $tag_names_csv, $tag_type );
461
462 //get the ids of the tags passed
4f81c51d 463 $existing_and_new_tags_ids = tags_id( tag_normalize($tag_names_csv) );
c933a060 464
465 // delete any tag instance with $item_type and $item_id
466 // that are not in $tag_names_csv
467 $tags_id_csv = "'" . implode("','", $existing_and_new_tags_ids) . "'" ;
468
469 $select = "
470 itemid = '{$item_id}'
471 AND
472 itemtype = '{$item_type}'
473 AND
474 tagid NOT IN ({$tags_id_csv})
475 ";
476
477 delete_records_select('tag_instance', $select);
478
479}
480
481/**
482 * Removes the association of an item with a tag
d4be9d6d 483 *
c933a060 484 * Ex: untag_an_item('user', '1', 'history, 11, roman' )
485 * The user with id 1 will no longer be tagged with 'history', 'roman' and the tag of id 11
486 * Calling untag_an_item('user','1') will remove all tags associated with user 1.
d4be9d6d 487 *
c933a060 488 * @param string $item_type name of the table where the item is stored. Ex: 'user'
489 * @param string $item_id id of the item to be untagged
ab86d9c7 490 * @param string $tag_names_or_ids_csv comma separated tag **normalized** names or ids of existing tags (optional, if none is given, all tags of the item will be removed)
c933a060 491 */
492
493function untag_an_item($item_type, $item_id, $tag_names_or_ids_csv='') {
3d436d8a 494
c933a060 495 if ($tag_names_or_ids_csv == ""){
496
497 delete_records('tag_instance','itemtype', $item_type, 'itemid', $item_id);
498
499 }
500 else {
3d436d8a 501
ab86d9c7 502 $tag_ids_csv = tag_id_from_string($tag_names_or_ids_csv);
c933a060 503
504 $tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv ) . "'";
505
506 delete_records_select('tag_instance',
ab86d9c7 507 "tagid IN ({$tag_ids_csv_with_apos}) AND itemtype='$item_type' AND itemid='$item_id'");
c933a060 508 }
509
510 //update_tag_correlations($item_type, $item_id);
511
512}
513
514/**
515 * Function that gets the tags that are associated with an item
d4be9d6d 516 *
c933a060 517 * Ex: get_item_tags('user', '1')
d4be9d6d 518 *
c933a060 519 * @param string $item_type name of the table where the item is stored. Ex: 'user'
520 * @param string $item_id id of the item beeing queried
ab86d9c7 521 * @param string $sort an order to sort the results in, a valid SQL ORDER BY parameter (default is 'ti.ordering ASC')
b3541b6a 522 * @param string $fields tag fields to be selected (optional, default is 'id, name, rawname, tagtype, flag')
c933a060 523 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
524 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
525 * @return mixed an array of objects, or false if no records were found or an error occured.
526 */
527
474373aa 528function get_item_tags($item_type, $item_id, $sort='ti.ordering ASC', $fields=DEFAULT_TAG_TABLE_FIELDS, $limitfrom='', $limitnum='', $tagtype='') {
3d436d8a 529
c933a060 530 global $CFG;
3d436d8a 531
c933a060 532 $fields = 'tg.' . $fields;
533 $fields = str_replace(',', ',tg.', $fields);
3d436d8a 534
1acd661d 535 if ($sort) {
536 $sort = ' ORDER BY '. $sort;
537 }
3a597ace 538
474373aa 539 if ($tagtype) {
ab86d9c7 540 $tagwhere = " AND tg.tagtype = '$tagtype' ";
474373aa 541 } else {
ab86d9c7 542 $tagwhere = '';
474373aa 543 }
544
c933a060 545 $query = "
546 SELECT
547 {$fields}
d4be9d6d 548 FROM
c933a060 549 {$CFG->prefix}tag_instance ti
550 INNER JOIN
551 {$CFG->prefix}tag tg
552 ON
553 tg.id = ti.tagid
d4be9d6d 554 WHERE
c933a060 555 ti.itemtype = '{$item_type}' AND
1acd661d 556 ti.itemid = '{$item_id}'
474373aa 557 $tagwhere
1acd661d 558 {$sort}
559 ";
c933a060 560
561 return get_records_sql($query, $limitfrom, $limitnum);
562
563}
564
565
566
567/**
568 * Function that returns the items of a certain type associated with a certain tag
d4be9d6d 569 *
c933a060 570 * Ex 1: get_items_tagged_with('user', 'banana')
571 * Ex 2: get_items_tagged_with('user', '11')
d4be9d6d 572 *
c933a060 573 * @param string $item_type name of the table where the item is stored. Ex: 'user'
574 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
575 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
576 * (to avoid field name ambiguity in the query, use the identifier "it" Ex: 'it.name ASC' )
d4be9d6d 577 * @param string $fields a comma separated list of fields to return
c933a060 578 * (optional, by default all fields are returned). The first field will be used as key for the
4d4dac81 579 * array so must be a unique field such as 'id'. )
c933a060 580 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
581 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
582 * @return mixed an array of objects indexed by their ids, or false if no records were found or an error occured.
583 */
584
585function get_items_tagged_with($item_type, $tag_name_or_id, $sort='', $fields='*', $limitfrom='', $limitnum='') {
3d436d8a 586
c933a060 587 global $CFG;
3d436d8a 588
c933a060 589 $tag_id = tag_id_from_string($tag_name_or_id);
590
591 $fields = 'it.' . $fields;
592 $fields = str_replace(',', ',it.', $fields);
593
594 if ($sort) {
595 $sort = ' ORDER BY '. $sort;
3d436d8a 596 }
597
c933a060 598 $query = "
599 SELECT
600 {$fields}
d4be9d6d 601 FROM
c933a060 602 {$CFG->prefix}{$item_type} it
603 INNER JOIN
604 {$CFG->prefix}tag_instance tt
605 ON
606 it.id = tt.itemid
d4be9d6d 607 WHERE
c933a060 608 tt.itemtype = '{$item_type}' AND
d4be9d6d 609 tt.tagid = '{$tag_id}'
c933a060 610 {$sort}
611 ";
612
613
614 return get_records_sql($query, $limitfrom, $limitnum);
615
616}
617
618/**
619 * Returns the number of items tagged with a tag
620 *
621 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
d4be9d6d 622 * @param string $item_type name of the table where the item is stored. Ex: 'user' (optional, if none is set any
c933a060 623 * type will be counted)
624 * @return int the count. If an error occurrs, 0 is returned.
625 */
626function count_items_tagged_with($tag_name_or_id, $item_type='') {
3d436d8a 627
c933a060 628 global $CFG;
629
630 $tag_id = tag_id_from_string($tag_name_or_id);
631
632 if (empty($item_type)){
633 $query = "
634 SELECT
635 COUNT(*) AS count
d4be9d6d 636 FROM
c933a060 637 {$CFG->prefix}tag_instance tt
d4be9d6d 638 WHERE
c933a060 639 tagid = {$tag_id}";
640 }
641 else
642 {
643 $query = "
644 SELECT
645 COUNT(*) AS count
d4be9d6d 646 FROM
c933a060 647 {$CFG->prefix}{$item_type} it
648 INNER JOIN
649 {$CFG->prefix}tag_instance tt
650 ON
651 it.id = tt.itemid
d4be9d6d 652 WHERE
c933a060 653 tt.itemtype = '{$item_type}' AND
d4be9d6d 654 tt.tagid = '{$tag_id}' ";
c933a060 655 }
656
657
658 return count_records_sql($query);
659
660}
661
662
663/**
664 * Determines if an item is tagged with a certain tag
665 *
666 * @param string $item_type name of the table where the item is stored. Ex: 'user'
667 * @param string $item_id id of the item beeing queried
668 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
669 * @return bool true if a matching record exists, else false.
670 */
671function is_item_tagged_with($item_type,$item_id, $tag_name_or_id) {
672
673 $tag_id = tag_id_from_string($tag_name_or_id);
674
675 return record_exists('tag_instance','itemtype',$item_type,'itemid',$item_id, 'tagid', $tag_id);
676}
677
678/**
679 * Search for tags with names that match some text
680 *
681 * @param string $text string that the tag names will be matched against
682 * @param boolean $ordered If true, tags are ordered by their popularity. If false, no ordering.
683 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
684 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
685 * @return mixed an array of objects, or false if no records were found or an error occured.
686 */
687
688function search_tags($text, $ordered=true, $limitfrom='' , $limitnum='' ) {
689
690 global $CFG;
691
692 $text = tag_normalize($text);
693
694 if ($ordered) {
695 $query = "
d4be9d6d 696 SELECT
697 tg.id, tg.name, tg.rawname, COUNT(ti.id) AS count
698 FROM
c933a060 699 {$CFG->prefix}tag tg
d4be9d6d 700 LEFT JOIN
c933a060 701 {$CFG->prefix}tag_instance ti
d4be9d6d 702 ON
c933a060 703 tg.id = ti.tagid
d4be9d6d 704 WHERE
c933a060 705 tg.name
706 LIKE
d4be9d6d 707 '%{$text}%'
708 GROUP BY
2f5b642e 709 tg.id, tg.name, tg.rawname
d4be9d6d 710 ORDER BY
711 count
c933a060 712 DESC";
713 } else {
714 $query = "
d4be9d6d 715 SELECT
4f81c51d 716 tg.id, tg.name, tg.rawname
c933a060 717 FROM
718 {$CFG->prefix}tag tg
719 WHERE
720 tg.name
721 LIKE
722 '%{$text}%'
d4be9d6d 723 ";
c933a060 724 }
3d436d8a 725
c933a060 726
727 return get_records_sql($query, $limitfrom , $limitnum);
3d436d8a 728
c933a060 729}
730
731/**
732 * Function that returns tags that start with some text
733 *
734 * @param string $text string that the tag names will be matched against
735 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
736 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
737 * @return mixed an array of objects, or false if no records were found or an error occured.
738 */
739function similar_tags($text, $limitfrom='' , $limitnum='' ) {
c933a060 740 global $CFG;
741
9c9d3076 742 $text = moodle_strtolower($text);
c933a060 743
9c9d3076 744 $query = "SELECT tg.id, tg.name, tg.rawname
745 FROM {$CFG->prefix}tag tg
746 WHERE tg.name LIKE '{$text}%'";
c933a060 747
748 return get_records_sql($query, $limitfrom , $limitnum);
749}
750
751/**
752 * Returns tags related to a tag
d4be9d6d 753 *
754 * Related tags of a tag come from two sources:
c933a060 755 * - manually added related tags, which are tag_instance entries for that tag
756 * - correlated tags, which are a calculated
d4be9d6d 757 *
c933a060 758 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
759 * @param int $limitnum return a subset comprising this many records (optional, default is 10)
1e550d2f 760 * @return array an array of tag objects
c933a060 761 */
762
763function related_tags($tag_name_or_id, $limitnum=10) {
764
765 $tag_id = tag_id_from_string($tag_name_or_id);
766
767 //gets the manually added related tags
1e550d2f 768 if (!$manual_related_tags = get_item_tags('tag', $tag_id, 'ti.ordering ASC', DEFAULT_TAG_TABLE_FIELDS)) {
769 $manual_related_tags = array();
770 }
c933a060 771
772 //gets the correlated tags
75307861 773 $automatic_related_tags = correlated_tags($tag_id, $limitnum);
c933a060 774
1e550d2f 775 $related_tags = array_merge($manual_related_tags, $automatic_related_tags);
c933a060 776
1e550d2f 777 return array_slice(object_array_unique($related_tags), 0 , $limitnum);
c933a060 778}
779
780/**
781 * Returns the correlated tags of a tag
782 * The correlated tags are retrieved from the tag_correlation table, which is a caching table.
783 *
784 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
1e550d2f 785 * @return array an array of tag objects, or empty array if none
c933a060 786 */
75307861 787function correlated_tags($tag_name_or_id, $limitnum=null) {
3d436d8a 788
c933a060 789 $tag_id = tag_id_from_string($tag_name_or_id);
790
1e550d2f 791 if (!$tag_correlation = get_record('tag_correlation', 'tagid', $tag_id)) {
792 return array();
793 }
794
795 if (empty($tag_correlation->correlatedtags)) {
c933a060 796 return array();
797 }
798
75307861 799 if (!$result = get_records_select('tag', "id IN ({$tag_correlation->correlatedtags})", '', DEFAULT_TAG_TABLE_FIELDS, 0, $limitnum)) {
1e550d2f 800 return array();
801 }
c933a060 802
1e550d2f 803 return $result;
c933a060 804}
805
806/**
807 * Recalculates tag correlations of all the tags associated with an item
d4be9d6d 808 * This function could be called whenever the tags associations with an item changes
c933a060 809 * ( for example when tag_an_item() or untag_an_item() is called )
810 *
811 * @param string $item_type name of the table where the item is stored. Ex: 'user'
812 * @param string $item_id id of the item
813 */
814function update_tag_correlations($item_type, $item_id) {
815
816 $item_tags = get_item_tags($item_type, $item_id);
817
818 foreach ($item_tags as $tag) {
819 cache_correlated_tags($tag->id);
820 }
821}
822
823/**
824 * Calculates and stores the correlated tags of a tag.
825 * The correlations are stored in the 'tag_correlation' table.
826 *
827 * Two tags are correlated if they appear together a lot.
828 * Ex.: Users tagged with "computers" will probably also be tagged with "algorithms".
d4be9d6d 829 *
830 * The rationale for the 'tag_correlation' table is performance.
831 * It works as a cache for a potentially heavy load query done at the 'tag_instance' table.
832 * So, the 'tag_correlation' table stores redundant information derived from the 'tag_instance' table.
833 *
c933a060 834 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
835 * @param number $min_correlation cutoff percentage (optional, default is 0.25)
836 * @param int $limitnum return a subset comprising this many records (optional, default is 10)
837 */
75307861 838function cache_correlated_tags($tag_name_or_id, $min_correlation=2) {
c933a060 839 global $CFG;
d4be9d6d 840
c933a060 841 $tag_id = tag_id_from_string($tag_name_or_id);
842
3d436d8a 843 // query that counts how many times any tag appears together in items
844 // with the tag passed as argument ($tag_id)
dbf8c19c 845 $query = "SELECT tb.tagid , COUNT(*) AS nr
1e550d2f 846 FROM {$CFG->prefix}tag_instance ta
847 INNER JOIN {$CFG->prefix}tag_instance tb ON ta.itemid = tb.itemid
c0491d4a 848 WHERE ta.tagid = {$tag_id} AND tb.tagid != {$tag_id}
1e550d2f 849 GROUP BY tb.tagid
850 ORDER BY nr DESC";
851
852 $correlated = array();
853
c0491d4a 854 // Correlated tags happen when they appear together in more occasions
855 // than $min_correlation.
75307861 856 if ($tag_correlations = get_records_sql($query)) {
1e550d2f 857 foreach($tag_correlations as $correlation) {
c0491d4a 858 if($correlation->nr >= $min_correlation){
1e550d2f 859 $correlated[] = $correlation->tagid;
860 }
c933a060 861 }
862 }
c933a060 863
1e550d2f 864 $correlated = implode(',', $correlated);
c933a060 865
866 //saves correlation info in the caching table
1e550d2f 867 if ($tag_correlation_obj = get_record('tag_correlation', 'tagid', $tag_id)) {
868 $tag_correlation_obj->correlatedtags = $correlated;
869 update_record('tag_correlation', $tag_correlation_obj);
c933a060 870
1e550d2f 871 } else {
872 $tag_correlation_obj = new object();
873 $tag_correlation_obj->tagid = $tag_id;
874 $tag_correlation_obj->correlatedtags = $correlated;
875 insert_record('tag_correlation', $tag_correlation_obj);
c933a060 876 }
c933a060 877}
878
879/**
d4be9d6d 880 * This function cleans up the 'tag_instance' table
c933a060 881 * It removes orphans in 'tag_instances' table
882 *
883 */
884function tag_instance_table_cleanup() {
885
886 global $CFG;
3d436d8a 887
c933a060 888 //get the itemtypes present in the 'tag_instance' table
889 $query = "
890 SELECT
891 DISTINCT(itemtype)
892 FROM
893 {$CFG->prefix}tag_instance
894 ";
3d436d8a 895
b8ab75ea 896 if ($items_types = get_records_sql($query)) {
897
898 // for each itemtype, remove tag_instances that are orphans
899 // That is: For a given tag_instance, if in the itemtype table there's no entry with id equal to itemid,
900 // then this tag_instance is an orphan and it will be removed.
901 foreach ($items_types as $type) {
902
903 $query = "
904 {$CFG->prefix}tag_instance.id
905 IN
906 ( SELECT sq1.id
907 FROM
d4be9d6d 908 (SELECT sq2.*
c933a060 909 FROM {$CFG->prefix}tag_instance sq2
67ab5a01 910 LEFT JOIN {$CFG->prefix}{$type->itemtype} item
d4be9d6d 911 ON sq2.itemid = item.id
912 WHERE item.id IS NULL
913 AND sq2.itemtype = '{$type->itemtype}')
b8ab75ea 914 sq1
915 ) ";
3d436d8a 916
b8ab75ea 917 delete_records_select('tag_instance', $query);
918 }
c933a060 919 }
3d436d8a 920
c933a060 921 // remove tag_instances that are orphans because tagid does not correspond to an
922 // existing tag
923 $query = "
924 {$CFG->prefix}tag_instance.id
925 IN
d4be9d6d 926 (SELECT sq1.id
927 FROM
928 (SELECT sq2.*
c933a060 929 FROM {$CFG->prefix}tag_instance sq2
930 LEFT JOIN {$CFG->prefix}tag tg
d4be9d6d 931 ON sq2.tagid = tg.id
932 WHERE tg.id IS NULL )
c933a060 933 sq1
d4be9d6d 934 )
c933a060 935 ";
3d436d8a 936
c933a060 937 delete_records_select('tag_instance', $query);
938}
939
940
941/**
4eb718d8 942 * Function that normalizes a list of tag names
d4be9d6d 943 *
c933a060 944 * Ex: tag_normalize('bANAana') -> returns 'banana'
945 * tag_normalize('lots of spaces') -> returns 'lots of spaces'
946 * tag_normalize('%!%!% non alpha numeric %!%!%') -> returns 'non alpha numeric'
d4be9d6d 947 * tag_normalize('tag one, TAG TWO, TAG three, and anotheR tag')
948 * -> returns 'tag one,tag two,tag three,and another tag'
949 *
c933a060 950 * @param string $tag_names_csv unnormalized CSV tag names
951 * @return string **normalized** CSV tag names
952 */
953
4f81c51d 954function tag_normalize($tag_names_csv, $lowercase=true) {
4eb718d8 955 $tag_names_csv = clean_param($tag_names_csv, PARAM_TAGLIST);
c933a060 956
4eb718d8 957 if ($lowercase){
958 $tag_names_csv = moodle_strtolower($tag_names_csv);
c933a060 959 }
960
4eb718d8 961 return $tag_names_csv;
c933a060 962}
963
c933a060 964function tag_flag_inappropriate($tag_names_or_ids_csv){
3d436d8a 965
c933a060 966 $tag_ids_csv = tag_id_from_string($tag_names_or_ids_csv);
3d436d8a 967
c933a060 968 $tag_ids = explode(',', $tag_ids_csv);
3d436d8a 969
970 foreach ($tag_ids as $id){
c933a060 971 $tag = get_record('tag','id',$id, '', '', '', '', 'id,flag');
3d436d8a 972
c933a060 973 $tag->flag++;
974 $tag->timemodified = time();
3d436d8a 975
c933a060 976 update_record('tag', $tag);
977 }
978}
979
980function tag_flag_reset($tag_names_or_ids_csv){
3d436d8a 981
c933a060 982 global $CFG;
3d436d8a 983
c933a060 984 $tag_ids_csv = tag_id_from_string($tag_names_or_ids_csv);
3d436d8a 985
c933a060 986 $tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv) . "'";
3d436d8a 987
c933a060 988 $timemodified = time();
3d436d8a 989
c933a060 990 $query = "
991 UPDATE
992 {$CFG->prefix}tag tg
d4be9d6d 993 SET
c933a060 994 tg.flag = 0,
995 tg.timemodified = {$timemodified}
996 WHERE
d4be9d6d 997 tg.id
c933a060 998 IN
999 ({$tag_ids_csv_with_apos})
1000 ";
3d436d8a 1001
c933a060 1002 execute_sql($query, false);
1003}
1004
3a597ace 1005/**
d4be9d6d 1006 * Function that updates tags names.
3a597ace 1007 * Updates only if the new name suggested for a tag doesn´t exist already.
1008 *
1009 * @param Array $tags_names_changed array of new tag names indexed by tag ids.
1010 * @return Array array of tags names that were effectively updated, indexed by tag ids.
1011 */
1012function tag_update_name($tags_names_changed){
1013
1014 $tags_names_updated = array();
1015
1016 foreach ($tags_names_changed as $id => $newname){
1017
1018 $norm_newname = tag_normalize($newname);
1019
1020 if( !tag_exists($norm_newname) && is_tag_name_valid($norm_newname) ) {
1021
1022 $tag = tag_by_id($id);
1023
1024 $tags_names_updated[$id] = $tag->name;
1025
1026 // rawname keeps the original casing of the string
1027 $tag->rawname = tag_normalize($newname, false);
1028
1029 // name lowercases the string
1030 $tag->name = $norm_newname;
1031
1032 $tag->timemodified = time();
1033
1034 update_record('tag',$tag);
1035
1036 }
1037 }
1038
1039 return $tags_names_updated;
1040
1041}
1042
c933a060 1043/**
1044 * Function that returns comma separated HTML links to the tag pages of the tags passed
1045 *
1046 * @param array $tag_objects an array of tag objects
1047 * @return string CSV, HTML links to tag pages
1048 */
1049
1050function tag_links_csv($tag_objects) {
3d436d8a 1051
c933a060 1052 global $CFG;
1053 $tag_links = '';
1054
1055 if (empty($tag_objects)) {
1056 return '';
1057 }
1058
1059 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1060 $can_manage_tags = has_capability('moodle/tag:manage', $systemcontext);
3d436d8a 1061
c933a060 1062 foreach ($tag_objects as $tag){
1063 //highlight tags that have been flagged as inappropriate for those who can manage them
4f81c51d 1064 $tagname = tag_display_name($tag);
c933a060 1065 if ($tag->flag > 0 && $can_manage_tags) {
1066 $tagname = '<span class="flagged-tag">' . $tagname . '</span>';
1067 }
1068 $tag_links .= ' <a href="'.$CFG->wwwroot.'/tag/index.php?id='.$tag->id.'">'.$tagname.'</a>,';
1069 }
1070
1071 return rtrim($tag_links, ',');
1072}
1073
1074/**
1075 * Function that returns comma separated names of the tags passed
1076 * Example of string that might be returned: 'history, wars, greek history'
d4be9d6d 1077 *
1078 * @param array $tag_objects
c933a060 1079 * @return string CSV tag names
1080 */
1081
1082function tag_names_csv($tag_objects) {
1083
1084 if (empty($tag_objects)) {
1085 return '';
1086 }
3d436d8a 1087
c933a060 1088 $tags = array();
1089
1090 foreach ($tag_objects as $tag){
4f81c51d 1091 $tags[] = tag_display_name($tag);
c933a060 1092 }
1093
5557c75a 1094 return implode(', ', $tags);
c933a060 1095}
1096
1097
1098/**
4d4dac81 1099 * Returns most popular tags, ordered by their popularity
c933a060 1100 *
1101 * @param int $nr_of_tags number of random tags to be returned
1102 * @param unknown_type $tag_type
1103 * @return mixed an array of tag objects with the following fields: id, name and count
1104 */
4d4dac81 1105function popular_tags_count($nr_of_tags=20, $tag_type = 'default') {
3d436d8a 1106
c933a060 1107 global $CFG;
3d436d8a 1108
c933a060 1109 $query = "
d4be9d6d 1110 SELECT
1111 tg.rawname, tg.id, tg.name, COUNT(ti.id) AS count, tg.flag
1112 FROM
1113 {$CFG->prefix}tag_instance ti
1114 INNER JOIN
1115 {$CFG->prefix}tag tg
1116 ON
c933a060 1117 tg.id = ti.tagid
d4be9d6d 1118 GROUP BY
b20863a9 1119 tg.id, tg.rawname, tg.name, tg.flag
d4be9d6d 1120 ORDER BY
1121 count
4d4dac81 1122 DESC
1123 ";
ab86d9c7 1124
4d4dac81 1125 return get_records_sql($query,0,$nr_of_tags);
3d436d8a 1126
1127
c933a060 1128}
1129
19e41f75 1130function tag_cron(){
3d436d8a 1131
19e41f75 1132 tag_instance_table_cleanup();
3d436d8a 1133
b8ab75ea 1134 if ($tags = get_all_tags('*')) {
3d436d8a 1135
b8ab75ea 1136 foreach ($tags as $tag){
1137 cache_correlated_tags($tag->id);
1138 }
19e41f75 1139 }
3d436d8a 1140
19e41f75 1141}
9f788215 1142/*-------------------- Printing functions -------------------- */
c933a060 1143
1144/**
1145 * Prints a box that contains the management links of a tag
1146 *
1147 * @param $tag_object
ab86d9c7 1148 * @param $return if true return html string
c933a060 1149 */
1150
ab86d9c7 1151function print_tag_management_box($tag_object, $return=false) {
c933a060 1152
1153 global $USER, $CFG;
1154
4f81c51d 1155 $tagname = tag_display_name($tag_object);
c933a060 1156
ab86d9c7 1157 $output = '';
1158
b95e4f14 1159 if (!isguestuser()) {
c933a060 1160
353a8961 1161 $output .= print_box_start('box','tag-management-box', true);
c933a060 1162
b95e4f14 1163 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
c933a060 1164
d66790b7 1165 $links = array();
c933a060 1166
b95e4f14 1167 // if the user is not tagged with the $tag_object tag, a link "add blahblah to my interests" will appear
1168 if( !is_item_tagged_with('user', $USER->id, $tag_object->id )) {
d66790b7 1169 $links[] = '<a href="' . $CFG->wwwroot . '/user/tag.php?action=addinterest&amp;sesskey='.sesskey().'&amp;id='. $tag_object->id .'">'.get_string('addtagtomyinterests','tag',$tagname). '</a>';
b95e4f14 1170 }
ab86d9c7 1171
b95e4f14 1172 // only people with moodle/tag:edit capability may edit the tag description
1173 if ( has_capability('moodle/tag:edit',$systemcontext) && is_item_tagged_with('user', $USER->id, $tag_object->id ) ) {
d66790b7 1174 $links[] = '<a href="'. $CFG->wwwroot . '/tag/edit.php?id='.$tag_object->id .'">'.get_string('edittag', 'tag').'</a>';
b95e4f14 1175 }
1176
1177 // flag as inappropriate link
d66790b7 1178 $links[] = '<a href="' . $CFG->wwwroot . '/user/tag.php?action=flaginappropriate&amp;sesskey='.sesskey().'&amp;id='. $tag_object->id .'">' . get_string('flagasinappropriate','tag',$tagname). '</a>';
1179
1180 // Manage all tags links
1181 if ( has_capability('moodle/tag:manage',$systemcontext) ) {
1182 $links[] = '<a href="'.$CFG->wwwroot.'/tag/manage.php">' . get_string('managetags', 'tag') . '</a>' ;
1183 }
1184
1185 $output .= implode(' | ', $links);
b95e4f14 1186
353a8961 1187 $output .= print_box_end(true);
b95e4f14 1188
1189 }
ab86d9c7 1190
1191 if ($return) {
1192 return $output;
d66790b7 1193 } else {
ab86d9c7 1194 echo $output;
1195 }
c933a060 1196
c933a060 1197}
1198
1199/**
1200 * Prints a box with the description of a tag and its related tags
1201 *
1202 * @param unknown_type $tag_object
ab86d9c7 1203 * @param $return if true return html string
c933a060 1204 */
1205
ab86d9c7 1206function print_tag_description_box($tag_object, $return=false) {
3d436d8a 1207
c933a060 1208 global $USER, $CFG;
1209
4f81c51d 1210 $tagname = tag_display_name($tag_object);
ab86d9c7 1211 $related_tags = related_tags($tag_object->id);
c933a060 1212
2773ced4 1213 $content = !empty($tag_object->description) || $related_tags;
c933a060 1214
2773ced4 1215 $output = '';
d4be9d6d 1216
2773ced4 1217 if ($content) {
353a8961 1218 $output .= print_box_start('generalbox', 'tag-description',true);
2773ced4 1219 }
3d436d8a 1220
c933a060 1221 if (!empty($tag_object->description)) {
d4be9d6d 1222 $options = new object();
1223 $options->para = false;
1224 $output .= format_text($tag_object->description, $tag_object->descriptionformat, $options);
c933a060 1225 }
c933a060 1226
c933a060 1227 if ($related_tags) {
d4be9d6d 1228 $output .= '<br /><br /><strong>'.get_string('relatedtags','tag').': </strong>' . tag_links_csv($related_tags);
ab86d9c7 1229 }
1230
2773ced4 1231 if ($content) {
353a8961 1232 $output .= print_box_end(true);
2773ced4 1233 }
ab86d9c7 1234
1235 if ($return) {
1236 return $output;
2773ced4 1237 } else {
ab86d9c7 1238 echo $output;
c933a060 1239 }
c933a060 1240}
1241
1242/**
1243 * Prints a table of the users tagged with the tag passed as argument
1244 *
1245 * @param $tag_object
1246 * @param int $users_per_row number of users per row to display
1247 * @param int $limitfrom prints users starting at this point (optional, required if $limitnum is set).
1248 * @param int $limitnum prints this many users (optional, required if $limitfrom is set).
ab86d9c7 1249 * @param $return if true return html string
c933a060 1250 */
1251
ab86d9c7 1252function print_tagged_users_table($tag_object, $limitfrom='' , $limitnum='', $return=false) {
c933a060 1253
1254 //List of users with this tag
1255 $userlist = array_values( get_items_tagged_with(
3d436d8a 1256 'user',
1257 $tag_object->id,
1258 'lastaccess DESC' ,
1259 'id, firstname, lastname, picture',
1260 $limitfrom,
1261 $limitnum) );
c933a060 1262
6cbf4bd4 1263 $output = print_user_list($userlist, true);
c933a060 1264
ab86d9c7 1265 if ($return) {
1266 return $output;
1267 }
1268 else {
1269 echo $output;
1270 }
c933a060 1271
1272}
1273
1274/**
327136f7 1275 * Prints a list of users
c933a060 1276 * @param array $userlist an array of user objects
ab86d9c7 1277 * @param $return if true return html string
c933a060 1278 */
ab86d9c7 1279function print_user_list($userlist, $return=false) {
1280
1281 $output = '';
3d436d8a 1282
8fc45264 1283 $output .= '<ul class="inline-list">';
327136f7 1284 foreach ($userlist as $user){
8fc45264 1285 $output .= '<li>'. print_user_box( $user , true) ."</li>\n";
c933a060 1286 }
8fc45264 1287 $output .= "</ul>\n";
327136f7 1288
ab86d9c7 1289 if ($return) {
1290 return $output;
1291 }
1292 else {
1293 echo $output;
1294 }
3d436d8a 1295
c933a060 1296}
1297
1298/**
1299 * Prints an individual user box
1300 *
1301 * @param $user user object (contains the following fields: id, firstname, lastname and picture)
ab86d9c7 1302 * @param $return if true return html string
c933a060 1303 */
ab86d9c7 1304function print_user_box($user, $return=false) {
b7ff675c 1305
c933a060 1306 global $CFG;
ab86d9c7 1307 $textlib = textlib_get_instance();
d4be9d6d 1308
c933a060 1309 $usercontext = get_context_instance(CONTEXT_USER, $user->id);
1310
1311 $profilelink = '';
1312 if ( has_capability('moodle/user:viewdetails', $usercontext) ) {
1313 $profilelink = $CFG->wwwroot.'/user/view.php?id='.$user->id;
1314 }
1315
ab86d9c7 1316 $output = '';
1317
353a8961 1318 $output .= print_box_start('user-box', 'user'.$user->id, true);
c933a060 1319
8fc45264 1320 $fullname = fullname($user);
1321 $alt = '';
b7ff675c 1322 if (!empty($profilelink)) {
ab86d9c7 1323 $output .= '<a href="'.$profilelink.'">';
8fc45264 1324 $alt = $fullname;
b7ff675c 1325 }
1326
8fc45264 1327 //print user image - if image is only content of link it needs ALT text!
b7ff675c 1328 if ($user->picture) {
8fc45264 1329 $output .= '<img alt="'.$alt.'" class="user-image" src="'. $CFG->wwwroot .'/user/pix.php/'. $user->id .'/f1.jpg"'.'/>';
b7ff675c 1330 } else {
8fc45264 1331 $output .= '<img alt="'.$alt.'" class="user-image" src="'. $CFG->wwwroot .'/pix/u/f1.png"'.'/>';
b7ff675c 1332 }
1333
ab86d9c7 1334 $output .= '<br />';
b7ff675c 1335
1336 if (!empty($profilelink)) {
ab86d9c7 1337 $output .= '</a>';
b7ff675c 1338 }
1339
b7ff675c 1340 //truncate name if it's too big
ab86d9c7 1341 if ($textlib->strlen($fullname) > 26) $fullname = $textlib->substr($fullname,0,26) . '...';
1342
1343 $output .= '<strong>' . $fullname . '</strong>';
b7ff675c 1344
353a8961 1345 $output .= print_box_end(true);
c933a060 1346
ab86d9c7 1347 if ($return) {
1348 return $output;
1349 }
1350 else {
1351 echo $output;
1352 }
c933a060 1353
1354}
1355
1356/**
1357 * Prints the tag search box
ab86d9c7 1358 * @param $return if true return html string
c933a060 1359 *
1360 */
ab86d9c7 1361function print_tag_search_box($return=false) {
3d436d8a 1362
c933a060 1363 global $CFG;
3d436d8a 1364
ab86d9c7 1365 $output = '';
1366 $output .= print_box_start('','tag-search-box', true);
3d436d8a 1367
ab86d9c7 1368 $output .= '<form action="'.$CFG->wwwroot.'/tag/search.php" style="display:inline">';
1369 $output .= '<div>';
1370 $output .= '<input id="searchform_search" name="query" type="text" size="40" />';
1371 $output .= '<button id="searchform_button" type="submit">'. get_string('search', 'tag') .'</button><br />';
1372 $output .= '</div>';
1373 $output .= '</form>';
3d436d8a 1374
ab86d9c7 1375 $output .= print_box_end(true);
1376
1377 if ($return) {
1378 return $output;
1379 }
1380 else {
1381 echo $output;
1382 }
c933a060 1383}
1384
1385/**
1386 * Prints the tag search results
1387 *
1388 * @param string $query text that tag names will be matched against
1389 * @param int $page current page
1390 * @param int $perpage nr of users displayed per page
ab86d9c7 1391 * @param $return if true return html string
c933a060 1392 */
ab86d9c7 1393function print_tag_search_results($query, $page, $perpage, $return=false) {
c933a060 1394
1395 global $CFG, $USER;
3d436d8a 1396
c933a060 1397 $count = sizeof( search_tags($query,false) );
1398 $tags = array_values(search_tags($query, true, $page * $perpage , $perpage));
3d436d8a 1399
c933a060 1400 $baseurl = $CFG->wwwroot.'/tag/search.php?query=' . $query;
1401
ab86d9c7 1402 $output = '';
1403
c933a060 1404 // link "Add $query to my interests"
1405 $addtaglink = '';
1406 if( !is_item_tagged_with('user', $USER->id, $query )) {
f458e359 1407 $addtaglink = '<a href="' . $CFG->wwwroot . '/user/tag.php?action=addinterest&amp;sesskey='.sesskey().'&amp;name='. $query .'">';
c933a060 1408 $addtaglink .= get_string('addtagtomyinterests','tag',$query). '</a>';
1409 }
1410
3d436d8a 1411
c933a060 1412 if($tags) { // there are results to display!!
3d436d8a 1413
2a484a6e 1414 $output .= print_heading(get_string('searchresultsfor', 'tag', $query) . " : {$count}", '', 3, 'main' ,true);
3d436d8a 1415
c933a060 1416 //print a link "Add $query to my interests"
1417 if (!empty($addtaglink)) {
ab86d9c7 1418 $output .= print_box($addtaglink,'box','tag-management-box',true);
c933a060 1419 }
1420
1421 $nr_of_lis_per_ul = 6;
1422 $nr_of_uls = ceil( sizeof($tags) / $nr_of_lis_per_ul);
3d436d8a 1423
ab86d9c7 1424 $output .= '<ul id="tag-search-results">';
3d436d8a 1425 for($i = 0; $i < $nr_of_uls; $i++) {
ab86d9c7 1426 $output .= '<li>';
3d436d8a 1427 foreach (array_slice($tags, $i * $nr_of_lis_per_ul, $nr_of_lis_per_ul ) as $tag) {
1428 $tag_link = ' <a href="'.$CFG->wwwroot.'/tag/index.php?id='.$tag->id.'">'.tag_display_name($tag).'</a>';
ab86d9c7 1429 $output .= '&#8226;' . $tag_link . '<br/>';
c933a060 1430 }
ab86d9c7 1431 $output .= '</li>';
3d436d8a 1432 }
ab86d9c7 1433 $output .= '</ul>';
1434 $output .= '<div>&nbsp;</div>'; // <-- small layout hack in order to look good in Firefox
3d436d8a 1435
2a484a6e 1436 $output .= print_paging_bar($count, $page, $perpage, $baseurl.'&amp;', 'page', false, true);
c933a060 1437 }
1438 else { //no results were found!!
3d436d8a 1439
2a484a6e 1440 $output .= print_heading(get_string('noresultsfor', 'tag', $query), '', 3, 'main' , true);
c933a060 1441
1442 //print a link "Add $query to my interests"
1443 if (!empty($addtaglink)) {
ab86d9c7 1444 $output .= print_box($addtaglink,'box','tag-management-box', true);
c933a060 1445 }
3d436d8a 1446
c933a060 1447 }
1448
ab86d9c7 1449 if ($return) {
1450 return $output;
1451 }
1452 else {
1453 echo $output;
1454 }
1455
3d436d8a 1456
c933a060 1457}
1458
1459/**
1460 * Prints a tag cloud
1461 *
4f81c51d 1462 * @param array $tagcloud array of tag objects (fields: id, name, rawname, count and flag)
1463 * @param boolean $shuffle wether or not to shuffle the array passed
c933a060 1464 * @param int $max_size maximum text size, in percentage
1465 * @param int $min_size minimum text size, in percentage
ab86d9c7 1466 * @param $return if true return html string
c933a060 1467 */
0495bd91 1468function print_tag_cloud($tagcloud, $shuffle=true, $max_size=180, $min_size=80, $return=false) {
3d436d8a 1469
c933a060 1470 global $CFG;
1471
1472 if (empty($tagcloud)) {
1473 return;
1474 }
3d436d8a 1475
5099a711 1476 if ($shuffle) {
c933a060 1477 shuffle($tagcloud);
5099a711 1478 } else {
1479 ksort($tagcloud);
1480 }
ab86d9c7 1481
c933a060 1482 $count = array();
1483 foreach ($tagcloud as $key => $value){
1484 if(!empty($value->count)) {
1485 $count[$key] = log10($value->count);
1486 }
1487 else{
1488 $count[$key] = 0;
1489 }
1490 }
3d436d8a 1491
c933a060 1492 $max = max($count);
1493 $min = min($count);
3d436d8a 1494
c933a060 1495 $spread = $max - $min;
1496 if (0 == $spread) { // we don't want to divide by zero
1497 $spread = 1;
1498 }
3d436d8a 1499
c933a060 1500 $step = ($max_size - $min_size)/($spread);
1501
1502 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1503 $can_manage_tags = has_capability('moodle/tag:manage', $systemcontext);
3d436d8a 1504
c933a060 1505 //prints the tag cloud
0495bd91 1506 $output = '<ul id="tag-cloud-list">';
c933a060 1507 foreach ($tagcloud as $key => $tag) {
3d436d8a 1508
c933a060 1509 $size = $min_size + ((log10($tag->count) - $min) * $step);
1510 $size = ceil($size);
1511
1512 $style = 'style="font-size: '.$size.'%"';
1513 $title = 'title="'.s(get_string('thingstaggedwith','tag', $tag)).'"';
1514 $href = 'href="'.$CFG->wwwroot.'/tag/index.php?id='.$tag->id.'"';
1515
1516 //highlight tags that have been flagged as inappropriate for those who can manage them
4f81c51d 1517 $tagname = tag_display_name($tag);
c933a060 1518 if ($tag->flag > 0 && $can_manage_tags) {
4f81c51d 1519 $tagname = '<span class="flagged-tag">' . tag_display_name($tag) . '</span>';
c933a060 1520 }
3d436d8a 1521
c933a060 1522 $tag_link = '<li><a '.$href.' '.$title.' '. $style .'>'.$tagname.'</a></li> ';
3d436d8a 1523
0495bd91 1524 $output .= $tag_link;
3d436d8a 1525
1526 }
0495bd91 1527 $output .= '</ul>';
1528
1529 if ($return) {
1530 return $output;
1531 } else {
1532 echo $output;
1533 }
3d436d8a 1534
c933a060 1535}
1536
c933a060 1537?>