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