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