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