a08dbacf4faad35694c58b854e2497b488616bae
[civicrm-core.git] / CRM / Core / BAO / Note.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * BAO object for crm_note table.
20 */
21 class CRM_Core_BAO_Note extends CRM_Core_DAO_Note {
22 use CRM_Core_DynamicFKAccessTrait;
23
24 /**
25 * Const the max number of notes we display at any given time.
26 * @var int
27 */
28 const MAX_NOTES = 3;
29
30 /**
31 * Given a note id, retrieve the note text.
32 *
33 * @param int $id
34 * Id of the note to retrieve.
35 *
36 * @return string
37 * the note text or NULL if note not found
38 *
39 * @throws \CRM_Core_Exception
40 *
41 * @deprecated
42 */
43 public static function getNoteText($id) {
44 CRM_Core_Error::deprecatedFunctionWarning('unused function');
45 return CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Note', $id, 'note');
46 }
47
48 /**
49 * Given a note id, retrieve the note subject
50 *
51 * @param int $id
52 * Id of the note to retrieve.
53 *
54 * @return string
55 * the note subject or NULL if note not found
56 *
57 * @throws \CRM_Core_Exception
58 */
59 public static function getNoteSubject($id) {
60 return CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Note', $id, 'subject');
61 }
62
63 /**
64 * Given a note id, decide if the note should be displayed based on privacy setting
65 *
66 * @param object $note
67 * Either the id of the note to retrieve, or the CRM_Core_DAO_Note object itself.
68 *
69 * @return bool
70 * TRUE if the note should be displayed, otherwise FALSE
71 *
72 */
73 public static function getNotePrivacyHidden($note) {
74 if (CRM_Core_Permission::check('view all notes')) {
75 return FALSE;
76 }
77
78 $noteValues = [];
79 if (is_object($note) && get_class($note) === 'CRM_Core_DAO_Note') {
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
93 if (empty($noteValues['privacy'])) {
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 /**
116 * Takes an associative array and creates a note object.
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 *
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'].
126 * @return null|object
127 * $note CRM_Core_BAO_Note object
128 * @throws \CRM_Core_Exception
129 */
130 public static function add(&$params, $ids = []) {
131 $dataExists = self::dataExists($params);
132 if (!$dataExists) {
133 return NULL;
134 }
135
136 if (!empty($params['entity_table']) && $params['entity_table'] == 'civicrm_contact' && !empty($params['check_permissions'])) {
137 if (!CRM_Contact_BAO_Contact_Permission::allow($params['entity_id'], CRM_Core_Permission::EDIT)) {
138 throw new CRM_Core_Exception('Permission denied to modify contact record');
139 }
140 }
141
142 $note = new CRM_Core_BAO_Note();
143
144 if (!isset($params['privacy'])) {
145 $params['privacy'] = 0;
146 }
147
148 $note->copyValues($params);
149 if (empty($params['contact_id'])) {
150 if (CRM_Utils_Array::value('entity_table', $params) == 'civicrm_contact') {
151 $note->contact_id = $params['entity_id'];
152 }
153 }
154 $id = $params['id'] ?? $ids['id'] ?? NULL;
155 if ($id) {
156 $note->id = $id;
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;
172
173 $loggedInContactID = CRM_Core_Session::getLoggedInContactID();
174 if ($loggedInContactID) {
175 if ($loggedInContactID == $note->entity_id) {
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
183 $recentOther = [];
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 /**
212 * Check if there is data to create the object.
213 *
214 * @param array $params
215 * (reference ) an assoc array of name/value pairs.
216 *
217 * @return bool
218 */
219 public static function dataExists(&$params) {
220 // return if no data present
221 if (empty($params['id']) && !strlen($params['note'])) {
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 *
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).
237 *
238 * @return array
239 */
240 public static function &getValues(&$params, &$values, $numNotes = self::MAX_NOTES) {
241 if (empty($params)) {
242 return NULL;
243 }
244 $note = new CRM_Core_BAO_Note();
245 $note->entity_id = $params['contact_id'];
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
256 $notes = [];
257 $count = 0;
258 while ($note->fetch()) {
259 $values['note'][$note->id] = [];
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
273 /**
274 * Delete the notes.
275 *
276 * @param int $id
277 * Note id.
278 * @param bool $showStatus
279 * Do we need to set status or not.
280 *
281 * @return int|null
282 * no of deleted notes on success, null otherwise
283 */
284 public static function del($id, $showStatus = TRUE) {
285 $return = NULL;
286 $recent = array($id);
287 $note = new CRM_Core_DAO_Note();
288 $note->id = $id;
289 $note->find();
290 $note->fetch();
291 if ($note->entity_table == 'civicrm_note') {
292 $status = ts('Selected Comment has been deleted successfully.');
293 }
294 else {
295 $status = ts('Selected Note has been deleted successfully.');
296 }
297
298 // Delete all descendents of this Note
299 foreach (self::getDescendentIds($id) as $childId) {
300 $childNote = new CRM_Core_DAO_Note();
301 $childNote->id = $childId;
302 $childNote->delete();
303 $recent[] = $childId;
304 }
305
306 $return = $note->delete();
307 if ($showStatus) {
308 CRM_Core_Session::setStatus($status, ts('Deleted'), 'success');
309 }
310
311 // delete the recently created Note
312 foreach ($recent as $recentId) {
313 $noteRecent = array(
314 'id' => $recentId,
315 'type' => 'Note',
316 );
317 CRM_Utils_Recent::del($noteRecent);
318 }
319 return $return;
320 }
321
322 /**
323 * Delete all records for this contact id.
324 *
325 * @param int $id
326 * ID of the contact for which note needs to be deleted.
327 */
328 public static function deleteContact($id) {
329 // need to delete for both entity_id
330 $dao = new CRM_Core_DAO_Note();
331 $dao->entity_table = 'civicrm_contact';
332 $dao->entity_id = $id;
333 $dao->delete();
334
335 // and the creator contact id
336 $dao = new CRM_Core_DAO_Note();
337 $dao->contact_id = $id;
338 $dao->delete();
339 }
340
341 /**
342 * Retrieve all records for this entity-id
343 *
344 * @param int $id
345 * ID of the relationship for which records needs to be retrieved.
346 *
347 * @param string $entityTable
348 *
349 * @return array
350 * array of note properties
351 *
352 */
353 public static function &getNote($id, $entityTable = 'civicrm_relationship') {
354 $viewNote = [];
355
356 $query = "
357 SELECT id,
358 note
359 FROM civicrm_note
360 WHERE entity_table=\"{$entityTable}\"
361 AND entity_id = %1
362 AND note is not null
363 ORDER BY modified_date desc";
364 $params = array(1 => array($id, 'Integer'));
365
366 $dao = CRM_Core_DAO::executeQuery($query, $params);
367
368 while ($dao->fetch()) {
369 $viewNote[$dao->id] = $dao->note;
370 }
371
372 return $viewNote;
373 }
374
375 /**
376 * Get log record count for a Contact.
377 *
378 * @param int $contactID
379 *
380 * @return int
381 * $count count of log records
382 *
383 */
384 public static function getContactNoteCount($contactID) {
385 $note = new CRM_Core_DAO_Note();
386 $note->entity_id = $contactID;
387 $note->entity_table = 'civicrm_contact';
388 $note->find();
389 $count = 0;
390 while ($note->fetch()) {
391 if (!self::getNotePrivacyHidden($note)) {
392 $count++;
393 }
394 }
395 return $count;
396 }
397
398 /**
399 * Get all descendent notes of the note with given ID.
400 *
401 * @param int $parentId
402 * ID of the note to start from.
403 * @param int $maxDepth
404 * Maximum number of levels to descend into the tree; if not given, will include all descendents.
405 * @param bool $snippet
406 * If TRUE, returned values will be pre-formatted for display in a table of notes.
407 *
408 * @return array
409 * Nested associative array beginning with direct children of given note.
410 *
411 */
412 public static function getNoteTree($parentId, $maxDepth = 0, $snippet = FALSE) {
413 return self::buildNoteTree($parentId, $maxDepth, $snippet);
414 }
415
416 /**
417 * Get total count of direct children visible to the current user.
418 *
419 * @param int $id
420 * Note ID.
421 *
422 * @return int
423 * $count Number of notes having the give note as parent
424 *
425 */
426 public static function getChildCount($id) {
427 $note = new CRM_Core_DAO_Note();
428 $note->entity_table = 'civicrm_note';
429 $note->entity_id = $id;
430 $note->find();
431 $count = 0;
432 while ($note->fetch()) {
433 if (!self::getNotePrivacyHidden($note)) {
434 $count++;
435 }
436 }
437 return $count;
438 }
439
440 /**
441 * Recursive function to get all descendent notes of the note with given ID.
442 *
443 * @param int $parentId
444 * ID of the note to start from.
445 * @param int $maxDepth
446 * Maximum number of levels to descend into the tree; if not given, will include all descendents.
447 * @param bool $snippet
448 * If TRUE, returned values will be pre-formatted for display in a table of notes.
449 * @param array $tree
450 * (Reference) Variable to store all found descendents.
451 * @param int $depth
452 * Depth of current iteration within the descendent tree (used for comparison against maxDepth).
453 *
454 * @return array
455 * Nested associative array beginning with direct children of given note.
456 */
457 private static function buildNoteTree($parentId, $maxDepth = 0, $snippet = FALSE, &$tree = [], $depth = 0) {
458 if ($maxDepth && $depth > $maxDepth) {
459 return FALSE;
460 }
461
462 // get direct children of given parentId note
463 $note = new CRM_Core_DAO_Note();
464 $note->entity_table = 'civicrm_note';
465 $note->entity_id = $parentId;
466 $note->orderBy('modified_date asc');
467 $note->find();
468 while ($note->fetch()) {
469 // foreach child, call this function, unless the child is private/hidden
470 if (!self::getNotePrivacyHidden($note)) {
471 CRM_Core_DAO::storeValues($note, $tree[$note->id]);
472
473 // get name of user that created this note
474 $contact = new CRM_Contact_DAO_Contact();
475 $createdById = $note->contact_id;
476 $contact->id = $createdById;
477 $contact->find();
478 $contact->fetch();
479 $tree[$note->id]['createdBy'] = $contact->display_name;
480 $tree[$note->id]['createdById'] = $createdById;
481 $tree[$note->id]['note_date'] = CRM_Utils_Date::customFormat($tree[$note->id]['note_date']);
482 $tree[$note->id]['modified_date'] = CRM_Utils_Date::customFormat($tree[$note->id]['modified_date']);
483
484 // paper icon view for attachments part
485 $paperIconAttachmentInfo = CRM_Core_BAO_File::paperIconAttachment('civicrm_note', $note->id);
486 $tree[$note->id]['attachment'] = $paperIconAttachmentInfo ? implode('', $paperIconAttachmentInfo) : '';
487
488 if ($snippet) {
489 $tree[$note->id]['note'] = nl2br($tree[$note->id]['note']);
490 $tree[$note->id]['note'] = smarty_modifier_mb_truncate(
491 $tree[$note->id]['note'],
492 80,
493 '...',
494 TRUE
495 );
496 CRM_Utils_Date::customFormat($tree[$note->id]['modified_date']);
497 }
498 self::buildNoteTree(
499 $note->id,
500 $maxDepth,
501 $snippet,
502 $tree[$note->id]['child'],
503 $depth + 1
504 );
505 }
506 }
507
508 return $tree;
509 }
510
511 /**
512 * Given a note id, get a list of the ids of all notes that are descendents of that note
513 *
514 * @param int $parentId
515 * Id of the given note.
516 * @param array $ids
517 * (reference) one-dimensional array to store found descendent ids.
518 *
519 * @return array
520 * One-dimensional array containing ids of all desendent notes
521 */
522 public static function getDescendentIds($parentId, &$ids = []) {
523 // get direct children of given parentId note
524 $note = new CRM_Core_DAO_Note();
525 $note->entity_table = 'civicrm_note';
526 $note->entity_id = $parentId;
527 $note->find();
528 while ($note->fetch()) {
529 // foreach child, add to ids list, and recurse
530 $ids[] = $note->id;
531 self::getDescendentIds($note->id, $ids);
532 }
533 return $ids;
534 }
535
536 /**
537 * Delete all note related to contact when contact is deleted.
538 *
539 * @param int $contactID
540 * Contact id whose notes to be deleted.
541 */
542 public static function cleanContactNotes($contactID) {
543 $params = array(1 => array($contactID, 'Integer'));
544
545 // delete all notes related to contribution
546 $contributeQuery = "DELETE note.*
547 FROM civicrm_note note LEFT JOIN civicrm_contribution contribute ON note.entity_id = contribute.id
548 WHERE contribute.contact_id = %1 AND note.entity_table = 'civicrm_contribution'";
549
550 CRM_Core_DAO::executeQuery($contributeQuery, $params);
551
552 // delete all notes related to participant
553 $participantQuery = "DELETE note.*
554 FROM civicrm_note note LEFT JOIN civicrm_participant participant ON note.entity_id = participant.id
555 WHERE participant.contact_id = %1 AND note.entity_table = 'civicrm_participant'";
556
557 CRM_Core_DAO::executeQuery($participantQuery, $params);
558
559 // delete all contact notes
560 $contactQuery = "SELECT id FROM civicrm_note WHERE entity_id = %1 AND entity_table = 'civicrm_contact'";
561
562 $contactNoteId = CRM_Core_DAO::executeQuery($contactQuery, $params);
563 while ($contactNoteId->fetch()) {
564 self::del($contactNoteId->id, FALSE);
565 }
566 }
567
568 /**
569 * Whitelist of possible values for the entity_table field
570 * @return array
571 */
572 public static function entityTables() {
573 return array(
574 'civicrm_relationship' => 'Relationship',
575 'civicrm_contact' => 'Contact',
576 'civicrm_participant' => 'Participant',
577 'civicrm_contribution' => 'Contribution',
578 );
579 }
580
581 }