Merge pull request #16017 from mattwire/setentitysubtype
[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 (!$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['modified_date'])) {
139 $params['modified_date'] = date("Ymd");
140 }
141
142 if (!isset($params['privacy'])) {
143 $params['privacy'] = 0;
144 }
145
146 $note->copyValues($params);
147 if (empty($params['contact_id'])) {
148 if (CRM_Utils_Array::value('entity_table', $params) == 'civicrm_contact') {
149 $note->contact_id = $params['entity_id'];
150 }
151 }
152 $id = CRM_Utils_Array::value('id', $params, CRM_Utils_Array::value('id', $ids));
153 if ($id) {
154 $note->id = $id;
155 }
156
157 $note->save();
158
159 // check and attach and files as needed
160 CRM_Core_BAO_File::processAttachment($params, 'civicrm_note', $note->id);
161
162 if ($note->entity_table == 'civicrm_contact') {
163 CRM_Core_BAO_Log::register($note->entity_id,
164 'civicrm_note',
165 $note->id
166 );
167 $displayName = CRM_Contact_BAO_Contact::displayName($note->entity_id);
168
169 $noteActions = FALSE;
170
171 $loggedInContactID = CRM_Core_Session::singleton()->getLoggedInContactID();
172 if ($loggedInContactID) {
173 if ($loggedInContactID == $note->entity_id) {
174 $noteActions = TRUE;
175 }
176 elseif (CRM_Contact_BAO_Contact_Permission::allow($note->entity_id, CRM_Core_Permission::EDIT)) {
177 $noteActions = TRUE;
178 }
179 }
180
181 $recentOther = array();
182 if ($noteActions) {
183 $recentOther = array(
184 'editUrl' => CRM_Utils_System::url('civicrm/contact/view/note',
185 "reset=1&action=update&cid={$note->entity_id}&id={$note->id}&context=home"
186 ),
187 'deleteUrl' => CRM_Utils_System::url('civicrm/contact/view/note',
188 "reset=1&action=delete&cid={$note->entity_id}&id={$note->id}&context=home"
189 ),
190 );
191 }
192
193 // add the recently created Note
194 CRM_Utils_Recent::add($displayName . ' - ' . $note->subject,
195 CRM_Utils_System::url('civicrm/contact/view/note',
196 "reset=1&action=view&cid={$note->entity_id}&id={$note->id}&context=home"
197 ),
198 $note->id,
199 'Note',
200 $note->entity_id,
201 $displayName,
202 $recentOther
203 );
204 }
205
206 return $note;
207 }
208
209 /**
210 * Check if there is data to create the object.
211 *
212 * @param array $params
213 * (reference ) an assoc array of name/value pairs.
214 *
215 * @return bool
216 */
217 public static function dataExists(&$params) {
218 // return if no data present
219 if (empty($params['id']) && !strlen($params['note'])) {
220 return FALSE;
221 }
222 return TRUE;
223 }
224
225 /**
226 * Given the list of params in the params array, fetch the object
227 * and store the values in the values array
228 *
229 * @param array $params
230 * Input parameters to find object.
231 * @param array $values
232 * Output values of the object.
233 * @param int $numNotes
234 * The maximum number of notes to return (0 if all).
235 *
236 * @return object
237 * $notes Object of CRM_Core_BAO_Note
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 = array();
256 $count = 0;
257 while ($note->fetch()) {
258 $values['note'][$note->id] = array();
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 }