Note API - Ensure child notes are deleted with parent, and hooks are called
[civicrm-core.git] / CRM / Core / BAO / Note.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17
18/**
8eedd10a 19 * BAO object for crm_note table.
6a488035 20 */
6623e554 21class CRM_Core_BAO_Note extends CRM_Core_DAO_Note implements \Civi\Test\HookInterface {
3d3a7160 22 use CRM_Core_DynamicFKAccessTrait;
6a488035
TO
23
24 /**
0880a9d0 25 * Const the max number of notes we display at any given time.
6a488035
TO
26 * @var int
27 */
7da04cde 28 const MAX_NOTES = 3;
6a488035
TO
29
30 /**
8eedd10a 31 * Given a note id, retrieve the note text.
6a488035 32 *
6a0b768e
TO
33 * @param int $id
34 * Id of the note to retrieve.
6a488035 35 *
a6c01b45
CW
36 * @return string
37 * the note text or NULL if note not found
6a488035 38 *
b37bd515 39 * @throws \CRM_Core_Exception
40 *
41 * @deprecated
6a488035 42 */
00be9182 43 public static function getNoteText($id) {
b37bd515 44 CRM_Core_Error::deprecatedFunctionWarning('unused function');
6a488035
TO
45 return CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Note', $id, 'note');
46 }
47
48 /**
100fef9d 49 * Given a note id, retrieve the note subject
6a488035 50 *
6a0b768e
TO
51 * @param int $id
52 * Id of the note to retrieve.
6a488035 53 *
a6c01b45
CW
54 * @return string
55 * the note subject or NULL if note not found
6a488035 56 *
b37bd515 57 * @throws \CRM_Core_Exception
6a488035 58 */
00be9182 59 public static function getNoteSubject($id) {
6a488035
TO
60 return CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Note', $id, 'subject');
61 }
62
63 /**
100fef9d 64 * Given a note id, decide if the note should be displayed based on privacy setting
6a488035 65 *
6a0b768e
TO
66 * @param object $note
67 * Either the id of the note to retrieve, or the CRM_Core_DAO_Note object itself.
6a488035 68 *
7c550ca0 69 * @return bool
a6c01b45 70 * TRUE if the note should be displayed, otherwise FALSE
6a488035 71 *
6a488035 72 */
00be9182 73 public static function getNotePrivacyHidden($note) {
6a488035
TO
74 if (CRM_Core_Permission::check('view all notes')) {
75 return FALSE;
76 }
77
b37bd515 78 $noteValues = [];
79 if (is_object($note) && get_class($note) === 'CRM_Core_DAO_Note') {
6a488035
TO
80 CRM_Core_DAO::storeValues($note, $noteValues);
81 }
82 else {
83 $noteDAO = new CRM_Core_DAO_Note();
84 $noteDAO->id = $note;
85 $noteDAO->find();
86 if ($noteDAO->fetch()) {
87 CRM_Core_DAO::storeValues($noteDAO, $noteValues);
88 }
89 }
90
91 CRM_Utils_Hook::notePrivacy($noteValues);
92
9e19c4f7 93 if (empty($noteValues['privacy'])) {
6a488035
TO
94 return FALSE;
95 }
96 elseif (isset($noteValues['notePrivacy_hidden'])) {
97 // If the hook has set visibility, use that setting.
98 return $noteValues['notePrivacy_hidden'];
99 }
100 else {
101 // Default behavior (if hook has not set visibility)
102 // is to hide privacy notes unless the note creator is the current user.
103
104 if ($noteValues['privacy']) {
105 $session = CRM_Core_Session::singleton();
106 $userID = $session->get('userID');
107 return ($noteValues['contact_id'] != $userID);
108 }
109 else {
110 return FALSE;
111 }
112 }
113 }
114
115 /**
fe482240 116 * Takes an associative array and creates a note object.
6a488035
TO
117 *
118 * the function extract all the params it needs to initialize the create a
119 * note object. the params array could contain additional unused name/value
120 * pairs
121 *
6a0b768e
TO
122 * @param array $params
123 * (reference) an assoc array of name/value pairs.
124 * @param array $ids
125 * (deprecated) associated array with note id - preferably set $params['id'].
518fa0ee 126 * @return null|object
a6c01b45 127 * $note CRM_Core_BAO_Note object
12fde6ae 128 * @throws \CRM_Core_Exception
6a488035 129 */
affcc9d2 130 public static function add(&$params, $ids = []) {
6a488035
TO
131 $dataExists = self::dataExists($params);
132 if (!$dataExists) {
1273d77c 133 return NULL;
6a488035
TO
134 }
135
fb1c6b2c 136 if (!empty($params['entity_table']) && $params['entity_table'] == 'civicrm_contact' && !empty($params['check_permissions'])) {
c6835264 137 if (!CRM_Contact_BAO_Contact_Permission::allow($params['entity_id'], CRM_Core_Permission::EDIT)) {
12fde6ae 138 throw new CRM_Core_Exception('Permission denied to modify contact record');
c6835264
CW
139 }
140 }
141
6a488035
TO
142 $note = new CRM_Core_BAO_Note();
143
6a488035
TO
144 if (!isset($params['privacy'])) {
145 $params['privacy'] = 0;
146 }
147
148 $note->copyValues($params);
a7488080 149 if (empty($params['contact_id'])) {
da2dec3a 150 if (CRM_Utils_Array::value('entity_table', $params) == 'civicrm_contact') {
6a488035
TO
151 $note->contact_id = $params['entity_id'];
152 }
153 }
8df1a020 154 $id = $params['id'] ?? $ids['id'] ?? NULL;
5554f6f3 155 if ($id) {
156 $note->id = $id;
6a488035
TO
157 }
158
159 $note->save();
160
161 // check and attach and files as needed
162 CRM_Core_BAO_File::processAttachment($params, 'civicrm_note', $note->id);
163
164 if ($note->entity_table == 'civicrm_contact') {
165 CRM_Core_BAO_Log::register($note->entity_id,
166 'civicrm_note',
167 $note->id
168 );
169 $displayName = CRM_Contact_BAO_Contact::displayName($note->entity_id);
170
171 $noteActions = FALSE;
da2dec3a 172
2dbdb9b9 173 $loggedInContactID = CRM_Core_Session::getLoggedInContactID();
da2dec3a 174 if ($loggedInContactID) {
175 if ($loggedInContactID == $note->entity_id) {
6a488035
TO
176 $noteActions = TRUE;
177 }
178 elseif (CRM_Contact_BAO_Contact_Permission::allow($note->entity_id, CRM_Core_Permission::EDIT)) {
179 $noteActions = TRUE;
180 }
181 }
182
b37bd515 183 $recentOther = [];
6a488035
TO
184 if ($noteActions) {
185 $recentOther = array(
186 'editUrl' => CRM_Utils_System::url('civicrm/contact/view/note',
187 "reset=1&action=update&cid={$note->entity_id}&id={$note->id}&context=home"
188 ),
189 'deleteUrl' => CRM_Utils_System::url('civicrm/contact/view/note',
190 "reset=1&action=delete&cid={$note->entity_id}&id={$note->id}&context=home"
191 ),
192 );
193 }
194
195 // add the recently created Note
196 CRM_Utils_Recent::add($displayName . ' - ' . $note->subject,
197 CRM_Utils_System::url('civicrm/contact/view/note',
198 "reset=1&action=view&cid={$note->entity_id}&id={$note->id}&context=home"
199 ),
200 $note->id,
201 'Note',
202 $note->entity_id,
203 $displayName,
204 $recentOther
205 );
206 }
207
208 return $note;
209 }
210
211 /**
fe482240 212 * Check if there is data to create the object.
6a488035 213 *
6a0b768e
TO
214 * @param array $params
215 * (reference ) an assoc array of name/value pairs.
6a488035 216 *
7c550ca0 217 * @return bool
6a488035 218 */
00be9182 219 public static function dataExists(&$params) {
6a488035 220 // return if no data present
da2dec3a 221 if (empty($params['id']) && !strlen($params['note'])) {
6a488035
TO
222 return FALSE;
223 }
224 return TRUE;
225 }
226
227 /**
228 * Given the list of params in the params array, fetch the object
229 * and store the values in the values array
230 *
6a0b768e
TO
231 * @param array $params
232 * Input parameters to find object.
233 * @param array $values
234 * Output values of the object.
235 * @param int $numNotes
236 * The maximum number of notes to return (0 if all).
6a488035 237 *
b37bd515 238 * @return array
6a488035 239 */
00be9182 240 public static function &getValues(&$params, &$values, $numNotes = self::MAX_NOTES) {
6a488035
TO
241 if (empty($params)) {
242 return NULL;
243 }
353ffa53
TO
244 $note = new CRM_Core_BAO_Note();
245 $note->entity_id = $params['contact_id'];
6a488035
TO
246 $note->entity_table = 'civicrm_contact';
247
248 // get the total count of notes
249 $values['noteTotalCount'] = $note->count();
250
251 // get only 3 recent notes
252 $note->orderBy('modified_date desc');
253 $note->limit($numNotes);
254 $note->find();
255
b37bd515 256 $notes = [];
6a488035
TO
257 $count = 0;
258 while ($note->fetch()) {
b37bd515 259 $values['note'][$note->id] = [];
6a488035
TO
260 CRM_Core_DAO::storeValues($note, $values['note'][$note->id]);
261 $notes[] = $note;
262
263 $count++;
264 // if we have collected the number of notes, exit loop
265 if ($numNotes > 0 && $count >= $numNotes) {
266 break;
267 }
268 }
269
270 return $notes;
271 }
272
6623e554
CW
273 /**
274 * Event fired prior to modifying a Note.
275 * @param \Civi\Core\Event\PreEvent $event
276 */
277 public static function self_hook_civicrm_pre(\Civi\Core\Event\PreEvent $event) {
278 if ($event->action === 'delete' && $event->id) {
279 // When deleting a note, also delete child notes
280 // This causes recursion as this hook is called again while deleting child notes,
281 // So the children of children, etc. will also be deleted.
282 foreach (self::getDescendentIds($event->id) as $child) {
283 self::deleteRecord(['id' => $child]);
284 }
285 }
286 }
287
6a488035 288 /**
fe482240 289 * Delete the notes.
6a488035 290 *
6a0b768e 291 * @param int $id
6a488035 292 *
6623e554
CW
293 * @deprecated
294 * @return int
6a488035 295 */
6623e554
CW
296 public static function del($id) {
297 // CRM_Core_Error::deprecatedFunctionWarning('deleteRecord');
298 self::deleteRecord(['id' => $id]);
6a488035 299
6623e554 300 return 1;
6a488035
TO
301 }
302
303 /**
fe482240 304 * Delete all records for this contact id.
6a488035 305 *
6a0b768e
TO
306 * @param int $id
307 * ID of the contact for which note needs to be deleted.
6a488035
TO
308 */
309 public static function deleteContact($id) {
310 // need to delete for both entity_id
353ffa53 311 $dao = new CRM_Core_DAO_Note();
6a488035 312 $dao->entity_table = 'civicrm_contact';
353ffa53 313 $dao->entity_id = $id;
6a488035
TO
314 $dao->delete();
315
316 // and the creator contact id
317 $dao = new CRM_Core_DAO_Note();
318 $dao->contact_id = $id;
319 $dao->delete();
320 }
321
322 /**
100fef9d 323 * Retrieve all records for this entity-id
6a488035 324 *
6a0b768e
TO
325 * @param int $id
326 * ID of the relationship for which records needs to be retrieved.
77b97be7
EM
327 *
328 * @param string $entityTable
6a488035 329 *
a6c01b45
CW
330 * @return array
331 * array of note properties
6a488035 332 *
6a488035
TO
333 */
334 public static function &getNote($id, $entityTable = 'civicrm_relationship') {
affcc9d2 335 $viewNote = [];
6a488035
TO
336
337 $query = "
338 SELECT id,
339 note
340 FROM civicrm_note
341 WHERE entity_table=\"{$entityTable}\"
342 AND entity_id = %1
343 AND note is not null
344ORDER BY modified_date desc";
345 $params = array(1 => array($id, 'Integer'));
346
347 $dao = CRM_Core_DAO::executeQuery($query, $params);
348
349 while ($dao->fetch()) {
350 $viewNote[$dao->id] = $dao->note;
351 }
352
353 return $viewNote;
354 }
355
356 /**
fe482240 357 * Get log record count for a Contact.
6a488035 358 *
c490a46a 359 * @param int $contactID
6a488035 360 *
a6c01b45
CW
361 * @return int
362 * $count count of log records
6a488035 363 *
6a488035 364 */
00be9182 365 public static function getContactNoteCount($contactID) {
353ffa53
TO
366 $note = new CRM_Core_DAO_Note();
367 $note->entity_id = $contactID;
6a488035
TO
368 $note->entity_table = 'civicrm_contact';
369 $note->find();
370 $count = 0;
371 while ($note->fetch()) {
372 if (!self::getNotePrivacyHidden($note)) {
373 $count++;
374 }
375 }
376 return $count;
377 }
378
379 /**
fe482240 380 * Get all descendent notes of the note with given ID.
6a488035 381 *
6a0b768e
TO
382 * @param int $parentId
383 * ID of the note to start from.
384 * @param int $maxDepth
385 * Maximum number of levels to descend into the tree; if not given, will include all descendents.
386 * @param bool $snippet
387 * If TRUE, returned values will be pre-formatted for display in a table of notes.
6a488035 388 *
a6c01b45
CW
389 * @return array
390 * Nested associative array beginning with direct children of given note.
6a488035 391 *
6a488035
TO
392 */
393 public static function getNoteTree($parentId, $maxDepth = 0, $snippet = FALSE) {
394 return self::buildNoteTree($parentId, $maxDepth, $snippet);
395 }
396
397 /**
fe482240 398 * Get total count of direct children visible to the current user.
6a488035 399 *
6a0b768e
TO
400 * @param int $id
401 * Note ID.
6a488035 402 *
a6c01b45
CW
403 * @return int
404 * $count Number of notes having the give note as parent
6a488035 405 *
6a488035
TO
406 */
407 public static function getChildCount($id) {
353ffa53 408 $note = new CRM_Core_DAO_Note();
6a488035 409 $note->entity_table = 'civicrm_note';
353ffa53 410 $note->entity_id = $id;
6a488035
TO
411 $note->find();
412 $count = 0;
413 while ($note->fetch()) {
414 if (!self::getNotePrivacyHidden($note)) {
415 $count++;
416 }
417 }
418 return $count;
419 }
420
421 /**
fe482240 422 * Recursive function to get all descendent notes of the note with given ID.
6a488035 423 *
6a0b768e
TO
424 * @param int $parentId
425 * ID of the note to start from.
426 * @param int $maxDepth
427 * Maximum number of levels to descend into the tree; if not given, will include all descendents.
428 * @param bool $snippet
429 * If TRUE, returned values will be pre-formatted for display in a table of notes.
430 * @param array $tree
431 * (Reference) Variable to store all found descendents.
432 * @param int $depth
433 * Depth of current iteration within the descendent tree (used for comparison against maxDepth).
6a488035 434 *
a6c01b45
CW
435 * @return array
436 * Nested associative array beginning with direct children of given note.
6a488035 437 */
affcc9d2 438 private static function buildNoteTree($parentId, $maxDepth = 0, $snippet = FALSE, &$tree = [], $depth = 0) {
6a488035 439 if ($maxDepth && $depth > $maxDepth) {
ab8a593e 440 return FALSE;
6a488035
TO
441 }
442
443 // get direct children of given parentId note
353ffa53 444 $note = new CRM_Core_DAO_Note();
6a488035 445 $note->entity_table = 'civicrm_note';
353ffa53 446 $note->entity_id = $parentId;
6a488035
TO
447 $note->orderBy('modified_date asc');
448 $note->find();
449 while ($note->fetch()) {
450 // foreach child, call this function, unless the child is private/hidden
451 if (!self::getNotePrivacyHidden($note)) {
452 CRM_Core_DAO::storeValues($note, $tree[$note->id]);
453
454 // get name of user that created this note
353ffa53 455 $contact = new CRM_Contact_DAO_Contact();
6a488035
TO
456 $createdById = $note->contact_id;
457 $contact->id = $createdById;
458 $contact->find();
459 $contact->fetch();
460 $tree[$note->id]['createdBy'] = $contact->display_name;
461 $tree[$note->id]['createdById'] = $createdById;
5bfc73d6 462 $tree[$note->id]['note_date'] = CRM_Utils_Date::customFormat($tree[$note->id]['note_date']);
6a488035
TO
463 $tree[$note->id]['modified_date'] = CRM_Utils_Date::customFormat($tree[$note->id]['modified_date']);
464
9a042a42 465 // paper icon view for attachments part
466 $paperIconAttachmentInfo = CRM_Core_BAO_File::paperIconAttachment('civicrm_note', $note->id);
1a3fb0ce 467 $tree[$note->id]['attachment'] = $paperIconAttachmentInfo ? implode('', $paperIconAttachmentInfo) : '';
9a042a42 468
6a488035
TO
469 if ($snippet) {
470 $tree[$note->id]['note'] = nl2br($tree[$note->id]['note']);
471 $tree[$note->id]['note'] = smarty_modifier_mb_truncate(
472 $tree[$note->id]['note'],
473 80,
474 '...',
475 TRUE
476 );
477 CRM_Utils_Date::customFormat($tree[$note->id]['modified_date']);
478 }
479 self::buildNoteTree(
480 $note->id,
481 $maxDepth,
482 $snippet,
483 $tree[$note->id]['child'],
484 $depth + 1
485 );
486 }
487 }
488
489 return $tree;
490 }
491
492 /**
6623e554 493 * Get direct children of given parentId note
6a488035 494 *
6a0b768e 495 * @param int $parentId
6a488035 496 *
a6c01b45 497 * @return array
6623e554 498 * One-dimensional array containing ids of child notes
6a488035 499 */
6623e554
CW
500 public static function getDescendentIds($parentId) {
501 $ids = [];
353ffa53 502 $note = new CRM_Core_DAO_Note();
6a488035 503 $note->entity_table = 'civicrm_note';
353ffa53 504 $note->entity_id = $parentId;
6a488035
TO
505 $note->find();
506 while ($note->fetch()) {
6a488035 507 $ids[] = $note->id;
6a488035
TO
508 }
509 return $ids;
510 }
511
512 /**
fe482240 513 * Delete all note related to contact when contact is deleted.
6a488035 514 *
6a0b768e
TO
515 * @param int $contactID
516 * Contact id whose notes to be deleted.
6a488035 517 */
00be9182 518 public static function cleanContactNotes($contactID) {
6a488035
TO
519 $params = array(1 => array($contactID, 'Integer'));
520
521 // delete all notes related to contribution
522 $contributeQuery = "DELETE note.*
523FROM civicrm_note note LEFT JOIN civicrm_contribution contribute ON note.entity_id = contribute.id
524WHERE contribute.contact_id = %1 AND note.entity_table = 'civicrm_contribution'";
525
526 CRM_Core_DAO::executeQuery($contributeQuery, $params);
527
528 // delete all notes related to participant
529 $participantQuery = "DELETE note.*
530FROM civicrm_note note LEFT JOIN civicrm_participant participant ON note.entity_id = participant.id
531WHERE participant.contact_id = %1 AND note.entity_table = 'civicrm_participant'";
532
533 CRM_Core_DAO::executeQuery($participantQuery, $params);
534
535 // delete all contact notes
536 $contactQuery = "SELECT id FROM civicrm_note WHERE entity_id = %1 AND entity_table = 'civicrm_contact'";
537
538 $contactNoteId = CRM_Core_DAO::executeQuery($contactQuery, $params);
539 while ($contactNoteId->fetch()) {
6623e554 540 self::deleteRecord(['id' => $contactNoteId->id]);
6a488035
TO
541 }
542 }
96025800 543
6a488035 544}