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