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