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