MDL-51283 core_tag: change tagtype to isstandard
[moodle.git] / tag / classes / area.php
CommitLineData
c026a28d
MG
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
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.
8//
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.
13//
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/>.
16
17/**
18 * Class core_tag_area for managing tag areas
19 *
20 * @package core_tag
21 * @copyright 2015 Marina Glancy
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25defined('MOODLE_INTERNAL') || die();
26
27/**
28 * Class to manage tag areas
29 *
30 * @package core_tag
31 * @copyright 2015 Marina Glancy
32 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33 */
34class core_tag_area {
35
36 /**
37 * Returns the list of areas indexed by itemtype and component
38 *
39 * @param int $tagcollid return only areas in this tag collection
40 * @param bool $enabledonly return only enabled tag areas
41 * @return array itemtype=>component=>tagarea object
42 */
43 public static function get_areas($tagcollid = null, $enabledonly = false) {
44 global $DB;
45 $cache = cache::make('core', 'tags');
46 if (($itemtypes = $cache->get('tag_area')) === false) {
47 $colls = core_tag_collection::get_collections();
48 $defaultcoll = reset($colls);
49 $itemtypes = array();
50 $areas = $DB->get_records('tag_area', array(), 'component,itemtype');
51 foreach ($areas as $area) {
52 if ($colls[$area->tagcollid]->component) {
53 $area->locked = true;
54 }
55 $itemtypes[$area->itemtype][$area->component] = $area;
56 }
57 $cache->set('tag_area', $itemtypes);
58 }
59 if ($tagcollid || $enabledonly) {
60 $rv = array();
61 foreach ($itemtypes as $itemtype => $it) {
62 foreach ($it as $component => $v) {
63 if (($v->tagcollid == $tagcollid || !$tagcollid) && (!$enabledonly || $v->enabled)) {
64 $rv[$itemtype][$component] = $v;
65 }
66 }
67 }
68 return $rv;
69 }
70 return $itemtypes;
71 }
72
73 /**
74 * Retrieves info about one tag area
75 *
76 * @param int $tagareaid
77 * @return stdClass
78 */
79 public static function get_by_id($tagareaid) {
80 $tagareas = self::get_areas();
81 foreach ($tagareas as $itemtype => $it) {
82 foreach ($it as $component => $v) {
83 if ($v->id == $tagareaid) {
84 return $v;
85 }
86 }
87 }
88 return null;
89 }
90
91 /**
92 * Returns the display name for this area
93 *
94 * @param string $component
95 * @param string $itemtype
96 * @return lang_string
97 */
98 public static function display_name($component, $itemtype) {
99 $identifier = 'tagarea_' . clean_param($itemtype, PARAM_STRINGID);
100 if ($component === 'core') {
101 $component = 'tag';
102 }
103 return new lang_string($identifier, $component);
104 }
105
106 /**
107 * Returns whether the tag area is enabled
108 *
109 * @param string $component component responsible for tagging
110 * @param string $itemtype what is being tagged, for example, 'post', 'course', 'user', etc.
111 * @return bool|null
112 */
113 public static function is_enabled($component, $itemtype) {
114 global $CFG;
115 if (empty($CFG->usetags)) {
116 return false;
117 }
118 $itemtypes = self::get_areas();
119 if (isset($itemtypes[$itemtype][$component])) {
120 return $itemtypes[$itemtype][$component]->enabled ? true : false;
121 }
122 return null;
123 }
124
125 /**
126 * Returns the id of the tag collection that should be used for storing tags of this itemtype
127 *
128 * @param string $component component responsible for tagging
129 * @param string $itemtype what is being tagged, for example, 'post', 'course', 'user', etc.
130 * @return int
131 */
132 public static function get_collection($component, $itemtype) {
133 $itemtypes = self::get_areas();
134 if (array_key_exists($itemtype, $itemtypes)) {
135 if (!array_key_exists($component, $itemtypes[$itemtype])) {
136 $component = key($itemtypes[$itemtype]);
137 }
138 return $itemtypes[$itemtype][$component]->tagcollid;
139 }
140 return core_tag_collection::get_default();
141 }
142
143 /**
144 * Returns all tag areas and collections that are currently cached in DB for this component
145 *
146 * @param string $componentname
147 * @return array first element is the list of areas and the second list of collections
148 */
149 protected static function get_definitions_for_component($componentname) {
150 global $DB;
151 list($a, $b) = core_component::normalize_component($componentname);
152 $component = $b ? ($a . '_' . $b) : $a;
153 $sql = 'component = :component';
154 $params = array('component' => $component);
155 if ($component === 'core') {
156 $sql .= ' OR component LIKE :coreprefix';
157 $params['coreprefix'] = 'core_%';
158 }
159 $fields = $DB->sql_concat_join("':'", array('itemtype', 'component'));
160 $existingareas = $DB->get_records_sql(
161 "SELECT $fields AS returnkey, a.* FROM {tag_area} a WHERE $sql", $params);
162 $fields = $DB->sql_concat_join("':'", array('name', 'component'));
163 $existingcolls = $DB->get_records_sql(
164 "SELECT $fields AS returnkey, t.* FROM {tag_coll} t WHERE $sql", $params);
165 return array($existingareas, $existingcolls);
166
167 }
168
169 /**
170 * Completely delete a tag area and all instances inside it
171 *
172 * @param stdClass $record
173 */
174 protected static function delete($record) {
175 global $DB;
176
177 core_tag_tag::delete_instances($record->component, $record->itemtype);
178
179 $DB->delete_records('tag_area',
180 array('itemtype' => $record->itemtype,
181 'component' => $record->component));
182
183 // Reset cache.
184 cache::make('core', 'tags')->delete('tag_area');
185 }
186
187 /**
188 * Create a new tag area
189 *
190 * @param stdClass $record
191 */
192 protected static function create($record) {
193 global $DB;
194 if (empty($record->tagcollid)) {
195 $record->tagcollid = core_tag_collection::get_default();
196 }
197 $DB->insert_record('tag_area', array('component' => $record->component,
198 'itemtype' => $record->itemtype,
199 'tagcollid' => $record->tagcollid,
200 'callback' => $record->callback,
201 'callbackfile' => $record->callbackfile));
202
203 // Reset cache.
204 cache::make('core', 'tags')->delete('tag_area');
205 }
206
207 /**
208 * Update the tag area
209 *
210 * @param stdClass $existing current record from DB table tag_area
211 * @param array|stdClass $data fields that need updating
212 */
213 public static function update($existing, $data) {
214 global $DB;
215 $data = array_intersect_key((array)$data,
216 array('enabled' => 1, 'tagcollid' => 1,
217 'callback' => 1, 'callbackfile' => 1));
218 foreach ($data as $key => $value) {
219 if ($existing->$key == $value) {
220 unset($data[$key]);
221 }
222 }
223 if (!$data) {
224 return;
225 }
226
227 if (!empty($data['tagcollid'])) {
228 self::move_tags($existing->component, $existing->itemtype, $data['tagcollid']);
229 }
230
231 $data['id'] = $existing->id;
232 $DB->update_record('tag_area', $data);
233
234 // Reset cache.
235 cache::make('core', 'tags')->delete('tag_area');
236 }
237
238 /**
239 * Update the database to contain a list of tagged areas for a component.
240 * The list of tagged areas is read from [plugindir]/db/tag.php
241 *
242 * @param string $componentname - The frankenstyle component name.
243 */
244 public static function reset_definitions_for_component($componentname) {
245 global $DB;
246 $dir = core_component::get_component_directory($componentname);
247 $file = $dir . '/db/tag.php';
248 $tagareas = null;
249 if (file_exists($file)) {
250 require_once($file);
251 }
252
253 list($a, $b) = core_component::normalize_component($componentname);
254 $component = $b ? ($a . '_' . $b) : $a;
255
256 list($existingareas, $existingcolls) = self::get_definitions_for_component($componentname);
257
258 $itemtypes = array();
259 $collections = array();
260 $needcleanup = false;
261 if ($tagareas) {
262 foreach ($tagareas as $tagarea) {
263 $record = (object)$tagarea;
264 if ($component !== 'core' || empty($record->component)) {
265 if (isset($record->component) && $record->component !== $component) {
266 debugging("Item type {$record->itemtype} has illegal component {$record->component}", DEBUG_DEVELOPER);
267 }
268 $record->component = $component;
269 }
270 unset($record->tagcollid);
271 if (!empty($record->collection)) {
272 // Create collection if it does not exist, or update 'searchable' and/or 'customurl' if needed.
273 $key = $record->collection . ':' . $record->component;
274 $collectiondata = array_intersect_key((array)$record,
275 array('component' => 1, 'searchable' => 1, 'customurl' => 1));
276 $collectiondata['name'] = $record->collection;
277 if (!array_key_exists($key, $existingcolls)) {
278 $existingcolls[$key] = core_tag_collection::create($collectiondata);
279 } else {
280 core_tag_collection::update($existingcolls[$key], $collectiondata);
281 }
282 $record->tagcollid = $existingcolls[$key]->id;
283 $collections[$key] = $existingcolls[$key];
284 unset($record->collection);
285 }
286 unset($record->searchable);
287 unset($record->customurl);
288 if (!isset($record->callback)) {
289 $record->callback = null;
290 }
291 if (!isset($record->callbackfile)) {
292 $record->callbackfile = null;
293 }
294 $itemtypes[$record->itemtype . ':' . $record->component] = $record;
295 }
296 }
297 $todeletearea = array_diff_key($existingareas, $itemtypes);
298 $todeletecoll = array_diff_key($existingcolls, $collections);
299
300 // Delete tag areas that are no longer needed.
301 foreach ($todeletearea as $key => $record) {
302 self::delete($record);
303 }
304
305 // Update tag areas if changed.
306 $toupdatearea = array_intersect_key($existingareas, $itemtypes);
307 foreach ($toupdatearea as $key => $tagarea) {
308 if (!isset($itemtypes[$key]->tagcollid)) {
309 foreach ($todeletecoll as $tagcoll) {
310 if ($tagcoll->id == $tagarea->tagcollid) {
311 $itemtypes[$key]->tagcollid = core_tag_collection::get_default();
312 }
313 }
314 }
315 self::update($tagarea, $itemtypes[$key]);
316 }
317
318 // Create new tag areas.
319 $toaddarea = array_diff_key($itemtypes, $existingareas);
320 foreach ($toaddarea as $record) {
321 self::create($record);
322 }
323
324 // Delete tag collections that are no longer needed.
325 foreach ($todeletecoll as $key => $tagcoll) {
326 core_tag_collection::delete($tagcoll);
327 }
328 }
329
330 /**
331 * Deletes all tag areas, collections and instances associated with the plugin.
332 *
333 * @param string $pluginname
334 */
335 public static function uninstall($pluginname) {
336 global $DB;
337
338 list($a, $b) = core_component::normalize_component($pluginname);
339 if (empty($b) || $a === 'core') {
340 throw new coding_exception('Core component can not be uninstalled');
341 }
342 $component = $a . '_' . $b;
343
344 core_tag_tag::delete_instances($component);
345
346 $DB->delete_records('tag_area', array('component' => $component));
347 $DB->delete_records('tag_coll', array('component' => $component));
348 cache::make('core', 'tags')->delete_many(array('tag_area', 'tag_coll'));
349 }
350
351 /**
352 * Moves existing tags associated with an item type to another tag collection
353 *
354 * @param string $component
355 * @param string $itemtype
356 * @param int $tagcollid
357 */
358 public static function move_tags($component, $itemtype, $tagcollid) {
359 global $DB;
360 $params = array('itemtype1' => $itemtype, 'component1' => $component,
361 'itemtype2' => $itemtype, 'component2' => $component,
362 'tagcollid1' => $tagcollid, 'tagcollid2' => $tagcollid);
363
364 // Find all collections that need to be cleaned later.
365 $sql = "SELECT DISTINCT t.tagcollid " .
366 "FROM {tag_instance} ti " .
367 "JOIN {tag} t ON t.id = ti.tagid AND t.tagcollid <> :tagcollid1 " .
368 "WHERE ti.itemtype = :itemtype2 AND ti.component = :component2 ";
369 $cleanupcollections = $DB->get_fieldset_sql($sql, $params);
370
371 // Find all tags that are related to the tags being moved and make sure they are present in the target tagcoll.
721d6659 372 // This query is a little complicated because Oracle does not allow to run SELECT DISTINCT on CLOB fields.
e11d7380 373 $sql = "SELECT name, rawname, description, descriptionformat, userid, isstandard, flag ".
721d6659
MG
374 "FROM {tag} WHERE id IN ".
375 "(SELECT r.id ".
c026a28d
MG
376 "FROM {tag_instance} ti ". // Instances that need moving.
377 "JOIN {tag} t ON t.id = ti.tagid AND t.tagcollid <> :tagcollid1 ". // Tags that need moving.
378 "JOIN {tag_instance} tr ON tr.itemtype = 'tag' and tr.component = 'core' AND tr.itemid = t.id ".
379 "JOIN {tag} r ON r.id = tr.tagid ". // Tags related to the tags that need moving.
380 "LEFT JOIN {tag} re ON re.name = r.name AND re.tagcollid = :tagcollid2 ". // Existing tags in the target tagcoll with the same name as related tags.
381 "WHERE ti.itemtype = :itemtype2 AND ti.component = :component2 ".
721d6659 382 " AND re.id IS NULL)"; // We need related tags that ARE NOT present in the target tagcoll.
c026a28d
MG
383 $result = $DB->get_records_sql($sql, $params);
384 foreach ($result as $tag) {
385 $tag->tagcollid = $tagcollid;
386 $tag->id = $DB->insert_record('tag', $tag);
387 \core\event\tag_created::create_from_tag($tag);
388 }
389
390 // Find all tags that need moving and have related tags, remember their related tags.
391 $sql = "SELECT t.name AS tagname, r.rawname AS relatedtag ".
392 "FROM {tag_instance} ti ". // Instances that need moving.
393 "JOIN {tag} t ON t.id = ti.tagid AND t.tagcollid <> :tagcollid1 ". // Tags that need moving.
394 "JOIN {tag_instance} tr ON t.id = tr.tagid AND tr.itemtype = 'tag' and tr.component = 'core' ".
395 "JOIN {tag} r ON r.id = tr.itemid ". // Tags related to the tags that need moving.
396 "WHERE ti.itemtype = :itemtype2 AND ti.component = :component2 ".
397 "ORDER BY t.id, tr.ordering ";
398 $relatedtags = array();
399 $result = $DB->get_recordset_sql($sql, $params);
400 foreach ($result as $record) {
401 $relatedtags[$record->tagname][] = $record->relatedtag;
402 }
403 $result->close();
404
405 // Find all tags that are used for this itemtype/component and are not present in the target tag collection.
25430f75 406 // This query is a little complicated because Oracle does not allow to run SELECT DISTINCT on CLOB fields.
e11d7380 407 $sql = "SELECT id, name, rawname, description, descriptionformat, userid, isstandard, flag
25430f75
MG
408 FROM {tag} WHERE id IN
409 (SELECT t.id
c026a28d
MG
410 FROM {tag_instance} ti
411 JOIN {tag} t ON t.id = ti.tagid AND t.tagcollid <> :tagcollid1
412 LEFT JOIN {tag} tt ON tt.name = t.name AND tt.tagcollid = :tagcollid2
413 WHERE ti.itemtype = :itemtype2 AND ti.component = :component2
25430f75 414 AND tt.id IS NULL)";
71da0356 415 $movedtags = array(); // Keep track of moved tags so we don't hit DB index violation.
c026a28d
MG
416 $result = $DB->get_records_sql($sql, $params);
417 foreach ($result as $tag) {
418 $originaltagid = $tag->id;
71da0356
MG
419 if (array_key_exists($tag->name, $movedtags)) {
420 // Case of corrupted data when the same tag was in several collections.
421 $tag->id = $movedtags[$tag->name];
422 } else {
423 // Copy the tag into the new collection.
424 unset($tag->id);
425 $tag->tagcollid = $tagcollid;
426 $tag->id = $DB->insert_record('tag', $tag);
427 \core\event\tag_created::create_from_tag($tag);
428 $movedtags[$tag->name] = $tag->id;
429 }
c026a28d
MG
430 $DB->execute("UPDATE {tag_instance} SET tagid = ? WHERE tagid = ? AND itemtype = ? AND component = ?",
431 array($tag->id, $originaltagid, $itemtype, $component));
432 }
433
434 // Find all tags that are used for this itemtype/component and are already present in the target tag collection.
435 $sql = "SELECT DISTINCT t.id, tt.id AS targettagid
436 FROM {tag_instance} ti
437 JOIN {tag} t ON t.id = ti.tagid AND t.tagcollid <> :tagcollid1
438 JOIN {tag} tt ON tt.name = t.name AND tt.tagcollid = :tagcollid2
439 WHERE ti.itemtype = :itemtype2 AND ti.component = :component2";
440 $result = $DB->get_records_sql($sql, $params);
441 foreach ($result as $tag) {
442 $DB->execute("UPDATE {tag_instance} SET tagid = ? WHERE tagid = ? AND itemtype = ? AND component = ?",
443 array($tag->targettagid, $tag->id, $itemtype, $component));
444 }
445
446 // Add related tags to the moved tags.
447 if ($relatedtags) {
448 $tags = core_tag_tag::get_by_name_bulk($tagcollid, array_keys($relatedtags));
449 foreach ($tags as $tag) {
450 $tag->add_related_tags($relatedtags[$tag->name]);
451 }
452 }
453
454 if ($cleanupcollections) {
455 core_tag_collection::cleanup_unused_tags($cleanupcollections);
456 }
457
458 // Reset caches.
459 cache::make('core', 'tags')->delete('tag_area');
460 }
461}