Fix financial acl permissions to respect check_permissions
[civicrm-core.git] / CRM / Core / BAO / Tag.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33 class CRM_Core_BAO_Tag extends CRM_Core_DAO_Tag {
34
35 /**
36 * @var array
37 */
38 protected $tree;
39
40 /**
41 * Class constructor.
42 */
43 public function __construct() {
44 parent::__construct();
45 }
46
47 /**
48 * Fetch object based on array of properties.
49 *
50 * @param array $params
51 * (reference ) an assoc array of name/value pairs.
52 * @param array $defaults
53 * (reference ) an assoc array to hold the flattened values.
54 *
55 * @return object
56 * CRM_Core_DAO_Tag object on success, otherwise null
57 */
58 public static function retrieve(&$params, &$defaults) {
59 $tag = new CRM_Core_DAO_Tag();
60 $tag->copyValues($params);
61 if ($tag->find(TRUE)) {
62 CRM_Core_DAO::storeValues($tag, $defaults);
63 return $tag;
64 }
65 return NULL;
66 }
67
68 /**
69 * Get tag tree.
70 *
71 * @param string $usedFor
72 * @param bool $excludeHidden
73 *
74 * @return mixed
75 */
76 public function getTree($usedFor = NULL, $excludeHidden = FALSE) {
77 if (!isset($this->tree)) {
78 $this->buildTree($usedFor, $excludeHidden);
79 }
80 return $this->tree;
81 }
82
83 /**
84 * Build a nested array from hierarchical tags.
85 *
86 * Supports infinite levels of nesting.
87 * @param null $usedFor
88 * @param bool $excludeHidden
89 */
90 public function buildTree($usedFor = NULL, $excludeHidden = FALSE) {
91 $sql = "SELECT id, parent_id, name, description, is_selectable FROM civicrm_tag";
92
93 $whereClause = [];
94 if ($usedFor) {
95 $whereClause[] = "used_for like '%{$usedFor}%'";
96 }
97 if ($excludeHidden) {
98 $whereClause[] = "is_tagset = 0";
99 }
100
101 if (!empty($whereClause)) {
102 $sql .= " WHERE " . implode(' AND ', $whereClause);
103 }
104
105 $sql .= " ORDER BY parent_id,name";
106
107 $dao = CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
108
109 $refs = [];
110 $this->tree = [];
111 while ($dao->fetch()) {
112 $thisref = &$refs[$dao->id];
113
114 $thisref['parent_id'] = $dao->parent_id;
115 $thisref['name'] = $dao->name;
116 $thisref['description'] = $dao->description;
117 $thisref['is_selectable'] = $dao->is_selectable;
118
119 if (!$dao->parent_id) {
120 $this->tree[$dao->id] = &$thisref;
121 }
122 else {
123 $refs[$dao->parent_id]['children'][$dao->id] = &$thisref;
124 }
125 }
126 }
127
128 /**
129 * Get tags used for the given entity/entities.
130 *
131 * @param array $usedFor
132 * @param bool $buildSelect
133 * @param bool $all
134 * @param int $parentId
135 *
136 * @return array
137 */
138 public static function getTagsUsedFor(
139 $usedFor = ['civicrm_contact'],
140 $buildSelect = TRUE,
141 $all = FALSE,
142 $parentId = NULL
143 ) {
144 $tags = [];
145
146 if (empty($usedFor)) {
147 return $tags;
148 }
149 if (!is_array($usedFor)) {
150 $usedFor = [$usedFor];
151 }
152
153 if ($parentId === NULL) {
154 $parentClause = " parent_id IS NULL AND ";
155 }
156 else {
157 $parentClause = " parent_id = {$parentId} AND ";
158 }
159
160 foreach ($usedFor as $entityTable) {
161 $tag = new CRM_Core_DAO_Tag();
162 $tag->fields();
163 $tag->orderBy('parent_id');
164 if ($buildSelect) {
165 $tag->whereAdd("is_tagset = 0 AND {$parentClause} used_for LIKE '%{$entityTable}%'");
166 }
167 else {
168 $tag->whereAdd("used_for LIKE '%{$entityTable}%'");
169 }
170 if (!$all) {
171 $tag->is_tagset = 0;
172 }
173 $tag->find();
174
175 while ($tag->fetch()) {
176 if ($buildSelect) {
177 $tags[$tag->id] = $tag->name;
178 }
179 else {
180 $tags[$tag->id]['name'] = $tag->name;
181 $tags[$tag->id]['parent_id'] = $tag->parent_id;
182 $tags[$tag->id]['is_tagset'] = $tag->is_tagset;
183 $tags[$tag->id]['used_for'] = $tag->used_for;
184 $tags[$tag->id]['description'] = $tag->description;
185 $tags[$tag->id]['color'] = !empty($tag->color) ? $tag->color : NULL;
186 }
187 }
188 $tag->free();
189 }
190
191 return $tags;
192 }
193
194 /**
195 * Function to retrieve tags.
196 *
197 * @param string $usedFor
198 * Which type of tag entity.
199 * @param array $tags
200 * Tags array.
201 * @param int $parentId
202 * Parent id if you want need only children.
203 * @param string $separator
204 * Separator to indicate children.
205 * @param bool $formatSelectable
206 * Add special property for non-selectable.
207 * tag, so they cannot be selected
208 *
209 * @return array
210 */
211 public static function getTags(
212 $usedFor = 'civicrm_contact',
213 &$tags = [],
214 $parentId = NULL,
215 $separator = '&nbsp;&nbsp;',
216 $formatSelectable = FALSE
217 ) {
218 if (!is_array($tags)) {
219 $tags = [];
220 }
221 // We need to build a list of tags ordered by hierarchy and sorted by
222 // name. The hierarchy will be communicated by an accumulation of
223 // separators in front of the name to give it a visual offset.
224 // Instead of recursively making mysql queries, we'll make one big
225 // query and build the hierarchy with the algorithm below.
226 $args = [1 => ['%' . $usedFor . '%', 'String']];
227 $query = "SELECT id, name, parent_id, is_tagset, is_selectable
228 FROM civicrm_tag
229 WHERE used_for LIKE %1";
230 if ($parentId) {
231 $query .= " AND parent_id = %2";
232 $args[2] = [$parentId, 'Integer'];
233 }
234 $query .= " ORDER BY name";
235 $dao = CRM_Core_DAO::executeQuery($query, $args, TRUE, NULL, FALSE, FALSE);
236
237 // Sort the tags into the correct storage by the parent_id/is_tagset
238 // filter the filter was in place previously, we're just reusing it.
239 // $roots represents the current leaf nodes that need to be checked for
240 // children. $rows represents the unplaced nodes, not all of much
241 // are necessarily placed.
242 $roots = $rows = [];
243 while ($dao->fetch()) {
244 // note that we are prepending id with "crm_disabled_opt" which identifies
245 // them as disabled so that they cannot be selected. We do some magic
246 // in crm-select2 js function that marks option values to "disabled"
247 // current QF version in CiviCRM does not support passing this attribute,
248 // so this is another ugly hack / workaround,
249 // also know one is too keen to upgrade QF :P
250 $idPrefix = '';
251 if ($formatSelectable && !$dao->is_selectable) {
252 $idPrefix = "crm_disabled_opt";
253 }
254 if ($dao->parent_id == $parentId && $dao->is_tagset == 0) {
255 $roots[] = [
256 'id' => $dao->id,
257 'prefix' => '',
258 'name' => $dao->name,
259 'idPrefix' => $idPrefix,
260 ];
261 }
262 else {
263 $rows[] = [
264 'id' => $dao->id,
265 'prefix' => '',
266 'name' => $dao->name,
267 'parent_id' => $dao->parent_id,
268 'idPrefix' => $idPrefix,
269 ];
270 }
271 }
272
273 $dao->free();
274 // While we have nodes left to build, shift the first (alphabetically)
275 // node of the list, place it in our tags list and loop through the
276 // list of unplaced nodes to find its children. We make a copy to
277 // iterate through because we must modify the unplaced nodes list
278 // during the loop.
279 while (count($roots)) {
280 $new_roots = [];
281 $current_rows = $rows;
282 $root = array_shift($roots);
283 $tags[$root['id']] = [
284 $root['prefix'],
285 $root['name'],
286 $root['idPrefix'],
287 ];
288
289 // As you find the children, append them to the end of the new set
290 // of roots (maintain alphabetical ordering). Also remove the node
291 // from the set of unplaced nodes.
292 if (is_array($current_rows)) {
293 foreach ($current_rows as $key => $row) {
294 if ($row['parent_id'] == $root['id']) {
295 $new_roots[] = [
296 'id' => $row['id'],
297 'prefix' => $tags[$root['id']][0] . $separator,
298 'name' => $row['name'],
299 'idPrefix' => $row['idPrefix'],
300 ];
301 unset($rows[$key]);
302 }
303 }
304 }
305
306 //As a group, insert the new roots into the beginning of the roots
307 //list. This maintains the hierarchical ordering of the tags.
308 $roots = array_merge($new_roots, $roots);
309 }
310
311 // Prefix each name with the calcuated spacing to give the visual
312 // appearance of ordering when transformed into HTML in the form layer.
313 // here is the actual code that to prepends and set disabled attribute for
314 // non-selectable tags
315 $formattedTags = [];
316 foreach ($tags as $key => $tag) {
317 if (!empty($tag[2])) {
318 $key = $tag[2] . "-" . $key;
319 }
320 $formattedTags[$key] = $tag[0] . $tag[1];
321 }
322
323 $tags = $formattedTags;
324 return $tags;
325 }
326
327 /**
328 * @param string $usedFor
329 * @param bool $allowSelectingNonSelectable
330 * @param null $exclude
331 * @return array
332 * @throws \CiviCRM_API3_Exception
333 */
334 public static function getColorTags($usedFor = NULL, $allowSelectingNonSelectable = FALSE, $exclude = NULL) {
335 $params = [
336 'options' => [
337 'limit' => 0,
338 'sort' => "name ASC",
339 ],
340 'is_tagset' => 0,
341 'return' => ['name', 'description', 'parent_id', 'color', 'is_selectable', 'used_for'],
342 ];
343 if ($usedFor) {
344 $params['used_for'] = ['LIKE' => "%$usedFor%"];
345 }
346 if ($exclude) {
347 $params['id'] = ['!=' => $exclude];
348 }
349 $allTags = [];
350 foreach (CRM_Utils_Array::value('values', civicrm_api3('Tag', 'get', $params)) as $id => $tag) {
351 $allTags[$id] = [
352 'text' => $tag['name'],
353 'id' => $id,
354 'description' => CRM_Utils_Array::value('description', $tag),
355 'parent_id' => CRM_Utils_Array::value('parent_id', $tag),
356 'used_for' => CRM_Utils_Array::value('used_for', $tag),
357 'color' => CRM_Utils_Array::value('color', $tag),
358 ];
359 if (!$allowSelectingNonSelectable && empty($tag['is_selectable'])) {
360 $allTags[$id]['disabled'] = TRUE;
361 }
362 }
363 return CRM_Utils_Array::buildTree($allTags);
364 }
365
366 /**
367 * Delete the tag.
368 *
369 * @param int $id
370 * Tag id.
371 *
372 * @return bool
373 */
374 public static function del($id) {
375 // since this is a destructive operation, lets make sure
376 // id is a positive number
377 CRM_Utils_Type::validate($id, 'Positive');
378
379 // delete all crm_entity_tag records with the selected tag id
380 $entityTag = new CRM_Core_DAO_EntityTag();
381 $entityTag->tag_id = $id;
382 $entityTag->delete();
383
384 // delete from tag table
385 $tag = new CRM_Core_DAO_Tag();
386 $tag->id = $id;
387
388 CRM_Utils_Hook::pre('delete', 'Tag', $id, $tag);
389
390 if ($tag->delete()) {
391 CRM_Utils_Hook::post('delete', 'Tag', $id, $tag);
392 return TRUE;
393 }
394 return FALSE;
395 }
396
397 /**
398 * Takes an associative array and creates a tag object.
399 *
400 * The function extract all the params it needs to initialize the create a
401 * contact object. the params array could contain additional unused name/value
402 * pairs
403 *
404 * @param array $params
405 * (reference) an assoc array of name/value pairs.
406 * @param array $ids
407 * (optional) the array that holds all the db ids - we are moving away from this in bao.
408 * signatures
409 *
410 * @return CRM_Core_DAO_Tag|null
411 * object on success, otherwise null
412 */
413 public static function add(&$params, $ids = []) {
414 $id = CRM_Utils_Array::value('id', $params, CRM_Utils_Array::value('tag', $ids));
415 if (!$id && !self::dataExists($params)) {
416 return NULL;
417 }
418
419 // Check permission to create or modify reserved tag
420 if (!empty($params['check_permissions']) && !CRM_Core_Permission::check('administer reserved tags')) {
421 if (!empty($params['is_reserved']) || ($id && CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $id, 'is_reserved'))) {
422 throw new CRM_Core_Exception('Insufficient permission to administer reserved tag.');
423 }
424 }
425
426 // Check permission to create or modify tagset
427 if (!empty($params['check_permissions']) && !CRM_Core_Permission::check('administer Tagsets')) {
428 if (!empty($params['is_tagset']) || ($id && CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $id, 'is_tagset'))) {
429 throw new CRM_Core_Exception('Insufficient permission to administer tagset.');
430 }
431 }
432
433 $tag = new CRM_Core_DAO_Tag();
434
435 // if parent id is set then inherit used for and is hidden properties
436 if (!empty($params['parent_id'])) {
437 // get parent details
438 $params['used_for'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $params['parent_id'], 'used_for');
439 }
440 elseif (isset($params['used_for']) && is_array($params['used_for'])) {
441 $params['used_for'] = implode(',', $params['used_for']);
442 }
443
444 if (isset($params['color']) && strtolower($params['color']) === '#ffffff') {
445 $params['color'] = '';
446 }
447
448 $tag->copyValues($params);
449 $tag->id = $id;
450 $hook = !$id ? 'create' : 'edit';
451 CRM_Utils_Hook::pre($hook, 'Tag', $tag->id, $params);
452
453 // save creator id and time
454 if (!$tag->id) {
455 $session = CRM_Core_Session::singleton();
456 $tag->created_id = $session->get('userID');
457 $tag->created_date = date('YmdHis');
458 }
459
460 $tag->save();
461 CRM_Utils_Hook::post($hook, 'Tag', $tag->id, $tag);
462
463 // if we modify parent tag, then we need to update all children
464 $tag->find(TRUE);
465 if (!$tag->parent_id && $tag->used_for) {
466 CRM_Core_DAO::executeQuery("UPDATE civicrm_tag SET used_for=%1 WHERE parent_id = %2",
467 [
468 1 => [$tag->used_for, 'String'],
469 2 => [$tag->id, 'Integer'],
470 ]
471 );
472 }
473
474 return $tag;
475 }
476
477 /**
478 * Check if there is data to create the object.
479 *
480 * @param array $params
481 * (reference ) an assoc array of name/value pairs.
482 *
483 * @return bool
484 */
485 public static function dataExists(&$params) {
486 // Disallow empty values except for the number zero.
487 // TODO: create a utility for this since it's needed in many places
488 if (!empty($params['name']) || (string) $params['name'] === '0') {
489 return TRUE;
490 }
491
492 return FALSE;
493 }
494
495 /**
496 * Get the tag sets for a entity object.
497 *
498 * @param string $entityTable
499 * Entity_table.
500 *
501 * @return array
502 * array of tag sets
503 */
504 public static function getTagSet($entityTable) {
505 $tagSets = [];
506 $query = "SELECT name, id FROM civicrm_tag
507 WHERE is_tagset=1 AND parent_id IS NULL and used_for LIKE %1";
508 $dao = CRM_Core_DAO::executeQuery($query, [
509 1 => [
510 '%' . $entityTable . '%',
511 'String',
512 ],
513 ], TRUE, NULL, FALSE, FALSE);
514 while ($dao->fetch()) {
515 $tagSets[$dao->id] = $dao->name;
516 }
517 $dao->free();
518 return $tagSets;
519 }
520
521 /**
522 * Get the tags that are not children of a tagset.
523 *
524 * @return array
525 * associated array of tag name and id
526 */
527 public static function getTagsNotInTagset() {
528 $tags = $tagSets = [];
529 // first get all the tag sets
530 $query = "SELECT id FROM civicrm_tag WHERE is_tagset=1 AND parent_id IS NULL";
531 $dao = CRM_Core_DAO::executeQuery($query);
532 while ($dao->fetch()) {
533 $tagSets[] = $dao->id;
534 }
535
536 $parentClause = '';
537 if (!empty($tagSets)) {
538 $parentClause = ' WHERE ( parent_id IS NULL ) OR ( parent_id NOT IN ( ' . implode(',', $tagSets) . ' ) )';
539 }
540
541 // get that tags that don't have tagset as parent
542 $query = "SELECT id, name FROM civicrm_tag {$parentClause}";
543 $dao = CRM_Core_DAO::executeQuery($query);
544 while ($dao->fetch()) {
545 $tags[$dao->id] = $dao->name;
546 }
547
548 return $tags;
549 }
550
551 /**
552 * Get child tags IDs
553 *
554 * @param string $searchString
555 *
556 * @return array
557 * associated array of child tags in Array('Parent Tag ID' => Array('Child Tag 1', ...)) format
558 */
559 public static function getChildTags($searchString = NULL) {
560 $childTagIDs = [];
561
562 $whereClauses = ['parent.is_tagset <> 1'];
563 if ($searchString) {
564 $whereClauses[] = " child.name LIKE '%$searchString%' ";
565 }
566
567 // only fetch those tags which has child tags
568 $dao = CRM_Utils_SQL_Select::from('civicrm_tag parent')
569 ->join('child', 'INNER JOIN civicrm_tag child ON child.parent_id = parent.id ')
570 ->select('parent.id as parent_id, GROUP_CONCAT(child.id) as child_id')
571 ->where($whereClauses)
572 ->groupBy('parent.id')
573 ->execute();
574 while ($dao->fetch()) {
575 $childTagIDs[$dao->parent_id] = (array) explode(',', $dao->child_id);
576 $parentID = $dao->parent_id;
577 if ($searchString) {
578 // recursively search for parent tag ID and it's child if any
579 while ($parentID) {
580 $newParentID = CRM_Core_DAO::singleValueQuery(" SELECT parent_id FROM civicrm_tag WHERE id = $parentID ");
581 if ($newParentID) {
582 $childTagIDs[$newParentID] = [$parentID];
583 }
584 $parentID = $newParentID;
585 }
586 }
587 }
588
589 // check if child tag has any childs, if found then include those child tags inside parent tag
590 // i.e. format Array('parent_tag' => array('child_tag_1', ...), 'child_tag_1' => array(child_tag_1_1, ..), ..)
591 // to Array('parent_tag' => array('child_tag_1', 'child_tag_1_1'...), ..)
592 foreach ($childTagIDs as $parentTagID => $childTags) {
593 foreach ($childTags as $childTag) {
594 // if $childTag has any child tag of its own
595 if (array_key_exists($childTag, $childTagIDs)) {
596 $childTagIDs[$parentTagID] = array_merge($childTagIDs[$parentTagID], $childTagIDs[$childTag]);
597 }
598 }
599 }
600
601 return $childTagIDs;
602 }
603
604 }