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