Merge pull request #10532 from monishdeb/CRM-20488_soft_credit_organization
[civicrm-core.git] / CRM / Core / BAO / Note.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
0f03f337 6 | Copyright CiviCRM LLC (c) 2004-2017 |
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
0f03f337 31 * @copyright CiviCRM LLC (c) 2004-2017
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'].
6a488035 136 *
1273d77c 137 * @return object|null
a6c01b45 138 * $note CRM_Core_BAO_Note object
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'])) {
6a488035
TO
164 if ($params['entity_table'] == 'civicrm_contact') {
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;
186 $session = CRM_Core_Session::singleton();
187 if ($session->get('userID')) {
188 if ($session->get('userID') == $note->entity_id) {
189 $noteActions = TRUE;
190 }
191 elseif (CRM_Contact_BAO_Contact_Permission::allow($note->entity_id, CRM_Core_Permission::EDIT)) {
192 $noteActions = TRUE;
193 }
194 }
195
196 $recentOther = array();
197 if ($noteActions) {
198 $recentOther = array(
199 'editUrl' => CRM_Utils_System::url('civicrm/contact/view/note',
200 "reset=1&action=update&cid={$note->entity_id}&id={$note->id}&context=home"
201 ),
202 'deleteUrl' => CRM_Utils_System::url('civicrm/contact/view/note',
203 "reset=1&action=delete&cid={$note->entity_id}&id={$note->id}&context=home"
204 ),
205 );
206 }
207
208 // add the recently created Note
209 CRM_Utils_Recent::add($displayName . ' - ' . $note->subject,
210 CRM_Utils_System::url('civicrm/contact/view/note',
211 "reset=1&action=view&cid={$note->entity_id}&id={$note->id}&context=home"
212 ),
213 $note->id,
214 'Note',
215 $note->entity_id,
216 $displayName,
217 $recentOther
218 );
219 }
220
221 return $note;
222 }
223
224 /**
fe482240 225 * Check if there is data to create the object.
6a488035 226 *
6a0b768e
TO
227 * @param array $params
228 * (reference ) an assoc array of name/value pairs.
6a488035 229 *
7c550ca0 230 * @return bool
6a488035 231 */
00be9182 232 public static function dataExists(&$params) {
6a488035
TO
233 // return if no data present
234 if (!strlen($params['note'])) {
235 return FALSE;
236 }
237 return TRUE;
238 }
239
240 /**
241 * Given the list of params in the params array, fetch the object
242 * and store the values in the values array
243 *
6a0b768e
TO
244 * @param array $params
245 * Input parameters to find object.
246 * @param array $values
247 * Output values of the object.
248 * @param int $numNotes
249 * The maximum number of notes to return (0 if all).
6a488035 250 *
a6c01b45
CW
251 * @return object
252 * $notes Object of CRM_Core_BAO_Note
6a488035 253 */
00be9182 254 public static function &getValues(&$params, &$values, $numNotes = self::MAX_NOTES) {
6a488035
TO
255 if (empty($params)) {
256 return NULL;
257 }
353ffa53
TO
258 $note = new CRM_Core_BAO_Note();
259 $note->entity_id = $params['contact_id'];
6a488035
TO
260 $note->entity_table = 'civicrm_contact';
261
262 // get the total count of notes
263 $values['noteTotalCount'] = $note->count();
264
265 // get only 3 recent notes
266 $note->orderBy('modified_date desc');
267 $note->limit($numNotes);
268 $note->find();
269
270 $notes = array();
271 $count = 0;
272 while ($note->fetch()) {
273 $values['note'][$note->id] = array();
274 CRM_Core_DAO::storeValues($note, $values['note'][$note->id]);
275 $notes[] = $note;
276
277 $count++;
278 // if we have collected the number of notes, exit loop
279 if ($numNotes > 0 && $count >= $numNotes) {
280 break;
281 }
282 }
283
284 return $notes;
285 }
286
287 /**
fe482240 288 * Delete the notes.
6a488035 289 *
6a0b768e
TO
290 * @param int $id
291 * Note id.
292 * @param bool $showStatus
293 * Do we need to set status or not.
6a488035 294 *
72b3a70c
CW
295 * @return int|NULL
296 * no of deleted notes on success, null otherwise
6a488035 297 */
00be9182 298 public static function del($id, $showStatus = TRUE) {
353ffa53
TO
299 $return = NULL;
300 $recent = array($id);
301 $note = new CRM_Core_DAO_Note();
6a488035
TO
302 $note->id = $id;
303 $note->find();
304 $note->fetch();
305 if ($note->entity_table == 'civicrm_note') {
306 $status = ts('Selected Comment has been deleted successfully.');
307 }
308 else {
309 $status = ts('Selected Note has been deleted successfully.');
310 }
311
312 // Delete all descendents of this Note
313 foreach (self::getDescendentIds($id) as $childId) {
314 $childNote = new CRM_Core_DAO_Note();
315 $childNote->id = $childId;
316 $childNote->delete();
82f5e43b 317 $childNote->free();
6a488035
TO
318 $recent[] = $childId;
319 }
320
321 $return = $note->delete();
82f5e43b 322 $note->free();
6a488035
TO
323 if ($showStatus) {
324 CRM_Core_Session::setStatus($status, ts('Deleted'), 'success');
325 }
326
327 // delete the recently created Note
328 foreach ($recent as $recentId) {
329 $noteRecent = array(
330 'id' => $recentId,
331 'type' => 'Note',
332 );
333 CRM_Utils_Recent::del($noteRecent);
334 }
335 return $return;
336 }
337
338 /**
fe482240 339 * Delete all records for this contact id.
6a488035 340 *
6a0b768e
TO
341 * @param int $id
342 * ID of the contact for which note needs to be deleted.
6a488035
TO
343 */
344 public static function deleteContact($id) {
345 // need to delete for both entity_id
353ffa53 346 $dao = new CRM_Core_DAO_Note();
6a488035 347 $dao->entity_table = 'civicrm_contact';
353ffa53 348 $dao->entity_id = $id;
6a488035
TO
349 $dao->delete();
350
351 // and the creator contact id
352 $dao = new CRM_Core_DAO_Note();
353 $dao->contact_id = $id;
354 $dao->delete();
355 }
356
357 /**
100fef9d 358 * Retrieve all records for this entity-id
6a488035 359 *
6a0b768e
TO
360 * @param int $id
361 * ID of the relationship for which records needs to be retrieved.
77b97be7
EM
362 *
363 * @param string $entityTable
6a488035 364 *
a6c01b45
CW
365 * @return array
366 * array of note properties
6a488035 367 *
6a488035
TO
368 */
369 public static function &getNote($id, $entityTable = 'civicrm_relationship') {
370 $viewNote = array();
371
372 $query = "
373 SELECT id,
374 note
375 FROM civicrm_note
376 WHERE entity_table=\"{$entityTable}\"
377 AND entity_id = %1
378 AND note is not null
379ORDER BY modified_date desc";
380 $params = array(1 => array($id, 'Integer'));
381
382 $dao = CRM_Core_DAO::executeQuery($query, $params);
383
384 while ($dao->fetch()) {
385 $viewNote[$dao->id] = $dao->note;
386 }
387
388 return $viewNote;
389 }
390
391 /**
fe482240 392 * Get log record count for a Contact.
6a488035 393 *
c490a46a 394 * @param int $contactID
6a488035 395 *
a6c01b45
CW
396 * @return int
397 * $count count of log records
6a488035 398 *
6a488035 399 */
00be9182 400 public static function getContactNoteCount($contactID) {
353ffa53
TO
401 $note = new CRM_Core_DAO_Note();
402 $note->entity_id = $contactID;
6a488035
TO
403 $note->entity_table = 'civicrm_contact';
404 $note->find();
405 $count = 0;
406 while ($note->fetch()) {
407 if (!self::getNotePrivacyHidden($note)) {
408 $count++;
409 }
410 }
411 return $count;
412 }
413
414 /**
fe482240 415 * Get all descendent notes of the note with given ID.
6a488035 416 *
6a0b768e
TO
417 * @param int $parentId
418 * ID of the note to start from.
419 * @param int $maxDepth
420 * Maximum number of levels to descend into the tree; if not given, will include all descendents.
421 * @param bool $snippet
422 * If TRUE, returned values will be pre-formatted for display in a table of notes.
6a488035 423 *
a6c01b45
CW
424 * @return array
425 * Nested associative array beginning with direct children of given note.
6a488035 426 *
6a488035
TO
427 */
428 public static function getNoteTree($parentId, $maxDepth = 0, $snippet = FALSE) {
429 return self::buildNoteTree($parentId, $maxDepth, $snippet);
430 }
431
432 /**
fe482240 433 * Get total count of direct children visible to the current user.
6a488035 434 *
6a0b768e
TO
435 * @param int $id
436 * Note ID.
6a488035 437 *
a6c01b45
CW
438 * @return int
439 * $count Number of notes having the give note as parent
6a488035 440 *
6a488035
TO
441 */
442 public static function getChildCount($id) {
353ffa53 443 $note = new CRM_Core_DAO_Note();
6a488035 444 $note->entity_table = 'civicrm_note';
353ffa53 445 $note->entity_id = $id;
6a488035
TO
446 $note->find();
447 $count = 0;
448 while ($note->fetch()) {
449 if (!self::getNotePrivacyHidden($note)) {
450 $count++;
451 }
452 }
453 return $count;
454 }
455
456 /**
fe482240 457 * Recursive function to get all descendent notes of the note with given ID.
6a488035 458 *
6a0b768e
TO
459 * @param int $parentId
460 * ID of the note to start from.
461 * @param int $maxDepth
462 * Maximum number of levels to descend into the tree; if not given, will include all descendents.
463 * @param bool $snippet
464 * If TRUE, returned values will be pre-formatted for display in a table of notes.
465 * @param array $tree
466 * (Reference) Variable to store all found descendents.
467 * @param int $depth
468 * Depth of current iteration within the descendent tree (used for comparison against maxDepth).
6a488035 469 *
a6c01b45
CW
470 * @return array
471 * Nested associative array beginning with direct children of given note.
6a488035 472 */
1a3fb0ce 473 private static function buildNoteTree($parentId, $maxDepth = 0, $snippet = FALSE, &$tree = array(), $depth = 0) {
6a488035 474 if ($maxDepth && $depth > $maxDepth) {
ab8a593e 475 return FALSE;
6a488035
TO
476 }
477
478 // get direct children of given parentId note
353ffa53 479 $note = new CRM_Core_DAO_Note();
6a488035 480 $note->entity_table = 'civicrm_note';
353ffa53 481 $note->entity_id = $parentId;
6a488035
TO
482 $note->orderBy('modified_date asc');
483 $note->find();
484 while ($note->fetch()) {
485 // foreach child, call this function, unless the child is private/hidden
486 if (!self::getNotePrivacyHidden($note)) {
487 CRM_Core_DAO::storeValues($note, $tree[$note->id]);
488
489 // get name of user that created this note
353ffa53 490 $contact = new CRM_Contact_DAO_Contact();
6a488035
TO
491 $createdById = $note->contact_id;
492 $contact->id = $createdById;
493 $contact->find();
494 $contact->fetch();
495 $tree[$note->id]['createdBy'] = $contact->display_name;
496 $tree[$note->id]['createdById'] = $createdById;
497 $tree[$note->id]['modified_date'] = CRM_Utils_Date::customFormat($tree[$note->id]['modified_date']);
498
9a042a42 499 // paper icon view for attachments part
500 $paperIconAttachmentInfo = CRM_Core_BAO_File::paperIconAttachment('civicrm_note', $note->id);
1a3fb0ce 501 $tree[$note->id]['attachment'] = $paperIconAttachmentInfo ? implode('', $paperIconAttachmentInfo) : '';
9a042a42 502
6a488035
TO
503 if ($snippet) {
504 $tree[$note->id]['note'] = nl2br($tree[$note->id]['note']);
505 $tree[$note->id]['note'] = smarty_modifier_mb_truncate(
506 $tree[$note->id]['note'],
507 80,
508 '...',
509 TRUE
510 );
511 CRM_Utils_Date::customFormat($tree[$note->id]['modified_date']);
512 }
513 self::buildNoteTree(
514 $note->id,
515 $maxDepth,
516 $snippet,
517 $tree[$note->id]['child'],
518 $depth + 1
519 );
520 }
521 }
522
523 return $tree;
524 }
525
526 /**
100fef9d 527 * Given a note id, get a list of the ids of all notes that are descendents of that note
6a488035 528 *
6a0b768e
TO
529 * @param int $parentId
530 * Id of the given note.
531 * @param array $ids
532 * (reference) one-dimensional array to store found descendent ids.
6a488035 533 *
a6c01b45
CW
534 * @return array
535 * One-dimensional array containing ids of all desendent notes
6a488035 536 */
c490a46a 537 public static function getDescendentIds($parentId, &$ids = array()) {
6a488035 538 // get direct children of given parentId note
353ffa53 539 $note = new CRM_Core_DAO_Note();
6a488035 540 $note->entity_table = 'civicrm_note';
353ffa53 541 $note->entity_id = $parentId;
6a488035
TO
542 $note->find();
543 while ($note->fetch()) {
544 // foreach child, add to ids list, and recurse
545 $ids[] = $note->id;
546 self::getDescendentIds($note->id, $ids);
547 }
548 return $ids;
549 }
550
551 /**
fe482240 552 * Delete all note related to contact when contact is deleted.
6a488035 553 *
6a0b768e
TO
554 * @param int $contactID
555 * Contact id whose notes to be deleted.
6a488035 556 */
00be9182 557 public static function cleanContactNotes($contactID) {
6a488035
TO
558 $params = array(1 => array($contactID, 'Integer'));
559
560 // delete all notes related to contribution
561 $contributeQuery = "DELETE note.*
562FROM civicrm_note note LEFT JOIN civicrm_contribution contribute ON note.entity_id = contribute.id
563WHERE contribute.contact_id = %1 AND note.entity_table = 'civicrm_contribution'";
564
565 CRM_Core_DAO::executeQuery($contributeQuery, $params);
566
567 // delete all notes related to participant
568 $participantQuery = "DELETE note.*
569FROM civicrm_note note LEFT JOIN civicrm_participant participant ON note.entity_id = participant.id
570WHERE participant.contact_id = %1 AND note.entity_table = 'civicrm_participant'";
571
572 CRM_Core_DAO::executeQuery($participantQuery, $params);
573
574 // delete all contact notes
575 $contactQuery = "SELECT id FROM civicrm_note WHERE entity_id = %1 AND entity_table = 'civicrm_contact'";
576
577 $contactNoteId = CRM_Core_DAO::executeQuery($contactQuery, $params);
578 while ($contactNoteId->fetch()) {
579 self::del($contactNoteId->id, FALSE);
580 }
581 }
96025800 582
583bd2a5
SL
583 /**
584 * Whitelist of possible values for the entity_table field
585 * @return array
586 */
587 public static function entityTables() {
466fce54
CW
588 return array(
589 'civicrm_relationship' => 'Relationship',
590 'civicrm_contact' => 'Contact',
591 'civicrm_participant' => 'Participant',
592 'civicrm_contribution' => 'Contribution',
583bd2a5 593 );
583bd2a5
SL
594 }
595
6a488035 596}