Fix Tests
[civicrm-core.git] / CRM / Activity / BAO / Activity.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
32 */
33
34 /**
35 * This class is for activity functions.
36 */
37 class CRM_Activity_BAO_Activity extends CRM_Activity_DAO_Activity {
38
39 /**
40 * Static field for all the activity information that we can potentially export.
41 *
42 * @var array
43 */
44 static $_exportableFields = NULL;
45
46 /**
47 * Static field for all the activity information that we can potentially import.
48 *
49 * @var array
50 */
51 static $_importableFields = NULL;
52
53 /**
54 * Check if there is absolute minimum of data to add the object.
55 *
56 * @param array $params
57 * (reference ) an assoc array of name/value pairs.
58 *
59 * @return bool
60 */
61 public static function dataExists(&$params) {
62 if (!empty($params['source_contact_id']) || !empty($params['id'])) {
63 return TRUE;
64 }
65 return FALSE;
66 }
67
68 /**
69 * Fetch object based on array of properties.
70 *
71 * @param array $params
72 * (reference ) an assoc array of name/value pairs.
73 * @param array $defaults
74 * (reference ) an assoc array to hold the flattened values.
75 *
76 * @return CRM_Activity_DAO_Activity
77 */
78 public static function retrieve(&$params, &$defaults) {
79 $activity = new CRM_Activity_DAO_Activity();
80 $activity->copyValues($params);
81
82 if ($activity->find(TRUE)) {
83 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
84 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
85 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
86 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
87
88 // TODO: at some stage we'll have to deal
89 // with multiple values for assignees and targets, but
90 // for now, let's just fetch first row.
91 $defaults['assignee_contact'] = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $assigneeID);
92 $assignee_contact_names = CRM_Activity_BAO_ActivityContact::getNames($activity->id, $assigneeID);
93 $defaults['assignee_contact_value'] = implode('; ', $assignee_contact_names);
94 $sourceContactId = self::getActivityContact($activity->id, $sourceID);
95 if ($activity->activity_type_id != CRM_Core_OptionGroup::getValue('activity_type', 'Bulk Email', 'name')) {
96 $defaults['target_contact'] = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $targetID);
97 $target_contact_names = CRM_Activity_BAO_ActivityContact::getNames($activity->id, $targetID);
98 $defaults['target_contact_value'] = implode('; ', $target_contact_names);
99 }
100 elseif (CRM_Core_Permission::check('access CiviMail') ||
101 (CRM_Mailing_Info::workflowEnabled() &&
102 CRM_Core_Permission::check('create mailings')
103 )
104 ) {
105 $defaults['mailingId'] = CRM_Utils_System::url('civicrm/mailing/report',
106 "mid={$activity->source_record_id}&reset=1&atype={$activity->activity_type_id}&aid={$activity->id}&cid={$sourceContactId}&context=activity"
107 );
108 }
109 else {
110 $defaults['target_contact_value'] = ts('(recipients)');
111 }
112
113 $sourceContactId = self::getActivityContact($activity->id, $sourceID);
114 $defaults['source_contact_id'] = $sourceContactId;
115
116 if ($sourceContactId &&
117 !CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
118 $sourceContactId,
119 'is_deleted'
120 )
121 ) {
122 $defaults['source_contact'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
123 $sourceContactId,
124 'sort_name'
125 );
126 }
127
128 // Get case subject.
129 $defaults['case_subject'] = CRM_Case_BAO_Case::getCaseSubject($activity->id);
130
131 CRM_Core_DAO::storeValues($activity, $defaults);
132
133 return $activity;
134 }
135 return NULL;
136 }
137
138 /**
139 * Delete the activity.
140 *
141 * @param array $params
142 * @param bool $moveToTrash
143 *
144 * @return mixed
145 */
146 public static function deleteActivity(&$params, $moveToTrash = FALSE) {
147 // CRM-9137
148 if (!empty($params['id']) && !is_array($params['id'])) {
149 CRM_Utils_Hook::pre('delete', 'Activity', $params['id'], $params);
150 }
151 else {
152 CRM_Utils_Hook::pre('delete', 'Activity', NULL, $params);
153 }
154
155 $transaction = new CRM_Core_Transaction();
156 if (is_array(CRM_Utils_Array::value('source_record_id', $params))) {
157 $sourceRecordIds = implode(',', $params['source_record_id']);
158 }
159 else {
160 $sourceRecordIds = CRM_Utils_Array::value('source_record_id', $params);
161 }
162
163 $result = NULL;
164 if (!$moveToTrash) {
165 if (!isset($params['id'])) {
166 if (is_array($params['activity_type_id'])) {
167 $activityTypes = implode(',', $params['activity_type_id']);
168 }
169 else {
170 $activityTypes = $params['activity_type_id'];
171 }
172
173 $query = "DELETE FROM civicrm_activity WHERE source_record_id IN ({$sourceRecordIds}) AND activity_type_id IN ( {$activityTypes} )";
174 $dao = CRM_Core_DAO::executeQuery($query);
175 }
176 else {
177 $activity = new CRM_Activity_DAO_Activity();
178 $activity->copyValues($params);
179 $result = $activity->delete();
180
181 // CRM-8708
182 $activity->case_id = CRM_Case_BAO_Case::getCaseIdByActivityId($activity->id);
183
184 // CRM-13994 delete activity entity_tag
185 $query = "DELETE FROM civicrm_entity_tag WHERE entity_table = 'civicrm_activity' AND entity_id = {$activity->id}";
186 $dao = CRM_Core_DAO::executeQuery($query);
187 }
188 }
189 else {
190 $activity = new CRM_Activity_DAO_Activity();
191 $activity->copyValues($params);
192
193 $activity->is_deleted = 1;
194 $result = $activity->save();
195
196 // CRM-4525 log activity delete
197 $logMsg = 'Case Activity deleted for';
198 $msgs = array();
199
200 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
201 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
202 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
203 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
204 $sourceContactId = self::getActivityContact($activity->id, $sourceID);
205 if ($sourceContactId) {
206 $msgs[] = " source={$sourceContactId}";
207 }
208
209 // get target contacts.
210 $targetContactIds = CRM_Activity_BAO_ActivityContact::getNames($activity->id, $targetID);
211 if (!empty($targetContactIds)) {
212 $msgs[] = " target =" . implode(',', array_keys($targetContactIds));
213 }
214 // get assignee contacts.
215 $assigneeContactIds = CRM_Activity_BAO_ActivityContact::getNames($activity->id, $assigneeID);
216 if (!empty($assigneeContactIds)) {
217 $msgs[] = " assignee =" . implode(',', array_keys($assigneeContactIds));
218 }
219
220 $logMsg .= implode(', ', $msgs);
221
222 self::logActivityAction($activity, $logMsg);
223 }
224
225 // delete the recently created Activity
226 if ($result) {
227 $activityRecent = array(
228 'id' => $activity->id,
229 'type' => 'Activity',
230 );
231 CRM_Utils_Recent::del($activityRecent);
232 }
233
234 $transaction->commit();
235 if (isset($activity)) {
236 // CRM-8708
237 $activity->case_id = CRM_Case_BAO_Case::getCaseIdByActivityId($activity->id);
238 CRM_Utils_Hook::post('delete', 'Activity', $activity->id, $activity);
239 }
240
241 return $result;
242 }
243
244 /**
245 * Delete activity assignment record.
246 *
247 * @param int $activityId
248 * @param int $recordTypeID
249 */
250 public static function deleteActivityContact($activityId, $recordTypeID = NULL) {
251 $activityContact = new CRM_Activity_BAO_ActivityContact();
252 $activityContact->activity_id = $activityId;
253 if ($recordTypeID) {
254 $activityContact->record_type_id = $recordTypeID;
255 }
256
257 // Let's check if activity contact record exits and then delete.
258 // Looks like delete leads to deadlock when multiple simultaneous
259 // requests are done. CRM-15470
260 if ($activityContact->find()) {
261 $activityContact->delete();
262 }
263 }
264
265 /**
266 * Process the activities.
267 *
268 * @param array $params
269 * Associated array of the submitted values.
270 *
271 * @throws CRM_Core_Exception
272 *
273 * @return CRM_Activity_BAO_Activity|null|object
274 */
275 public static function create(&$params) {
276 // check required params
277 if (!self::dataExists($params)) {
278 throw new CRM_Core_Exception('Not enough data to create activity object');
279 }
280
281 $activity = new CRM_Activity_DAO_Activity();
282
283 if (isset($params['id']) && empty($params['id'])) {
284 unset($params['id']);
285 }
286
287 if (empty($params['status_id']) && empty($params['activity_status_id']) && empty($params['id'])) {
288 if (isset($params['activity_date_time']) &&
289 strcmp($params['activity_date_time'], CRM_Utils_Date::processDate(date('Ymd')) == -1)
290 ) {
291 $params['status_id'] = 2;
292 }
293 else {
294 $params['status_id'] = 1;
295 }
296 }
297
298 // Set priority to Normal for Auto-populated activities (for Cases)
299 if (CRM_Utils_Array::value('priority_id', $params) === NULL &&
300 // if not set and not 0
301 !CRM_Utils_Array::value('id', $params)
302 ) {
303 $priority = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id');
304 $params['priority_id'] = array_search('Normal', $priority);
305 }
306
307 if (!empty($params['target_contact_id']) && is_array($params['target_contact_id'])) {
308 $params['target_contact_id'] = array_unique($params['target_contact_id']);
309 }
310 if (!empty($params['assignee_contact_id']) && is_array($params['assignee_contact_id'])) {
311 $params['assignee_contact_id'] = array_unique($params['assignee_contact_id']);
312 }
313
314 // CRM-9137
315 if (!empty($params['id'])) {
316 CRM_Utils_Hook::pre('edit', 'Activity', $activity->id, $params);
317 }
318 else {
319 CRM_Utils_Hook::pre('create', 'Activity', NULL, $params);
320 }
321
322 $activity->copyValues($params);
323 if (isset($params['case_id'])) {
324 // CRM-8708, preserve case ID even though it's not part of the SQL model
325 $activity->case_id = $params['case_id'];
326 }
327 elseif (is_numeric($activity->id)) {
328 // CRM-8708, preserve case ID even though it's not part of the SQL model
329 $activity->case_id = CRM_Case_BAO_Case::getCaseIdByActivityId($activity->id);
330 }
331
332 // start transaction
333 $transaction = new CRM_Core_Transaction();
334
335 $result = $activity->save();
336
337 if (is_a($result, 'CRM_Core_Error')) {
338 $transaction->rollback();
339 return $result;
340 }
341
342 $activityId = $activity->id;
343 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
344 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
345 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
346 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
347
348 if (isset($params['source_contact_id'])) {
349 $acParams = array(
350 'activity_id' => $activityId,
351 'contact_id' => $params['source_contact_id'],
352 'record_type_id' => $sourceID,
353 );
354 self::deleteActivityContact($activityId, $sourceID);
355 CRM_Activity_BAO_ActivityContact::create($acParams);
356 }
357
358 // check and attach and files as needed
359 CRM_Core_BAO_File::processAttachment($params, 'civicrm_activity', $activityId);
360
361 // attempt to save activity assignment
362 $resultAssignment = NULL;
363 if (!empty($params['assignee_contact_id'])) {
364
365 $assignmentParams = array('activity_id' => $activityId);
366
367 if (is_array($params['assignee_contact_id'])) {
368 if (CRM_Utils_Array::value('deleteActivityAssignment', $params, TRUE)) {
369 // first delete existing assignments if any
370 self::deleteActivityContact($activityId, $assigneeID);
371 }
372
373 $values = array();
374 foreach ($params['assignee_contact_id'] as $acID) {
375 if ($acID) {
376 $values[] = "( $activityId, $acID, $assigneeID )";
377 }
378 }
379 while (!empty($values)) {
380 $input = array_splice($values, 0, CRM_Core_DAO::BULK_INSERT_COUNT);
381 $str = implode(',', $input);
382 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES $str;";
383 CRM_Core_DAO::executeQuery($sql);
384 }
385 }
386 else {
387 $assignmentParams['contact_id'] = $params['assignee_contact_id'];
388 $assignmentParams['record_type_id'] = $assigneeID;
389 if (!empty($params['id'])) {
390 $assignment = new CRM_Activity_BAO_ActivityContact();
391 $assignment->activity_id = $activityId;
392 $assignment->record_type_id = $assigneeID;
393 $assignment->find(TRUE);
394
395 if ($assignment->contact_id != $params['assignee_contact_id']) {
396 $assignmentParams['id'] = $assignment->id;
397 $resultAssignment = CRM_Activity_BAO_ActivityContact::create($assignmentParams);
398 }
399 }
400 else {
401 $resultAssignment = CRM_Activity_BAO_ActivityContact::create($assignmentParams);
402 }
403 }
404 }
405 else {
406 if (CRM_Utils_Array::value('deleteActivityAssignment', $params, TRUE)) {
407 self::deleteActivityContact($activityId, $assigneeID);
408 }
409 }
410
411 if (is_a($resultAssignment, 'CRM_Core_Error')) {
412 $transaction->rollback();
413 return $resultAssignment;
414 }
415
416 // attempt to save activity targets
417 $resultTarget = NULL;
418 if (!empty($params['target_contact_id'])) {
419
420 $targetParams = array('activity_id' => $activityId);
421 $resultTarget = array();
422 if (is_array($params['target_contact_id'])) {
423 if (CRM_Utils_Array::value('deleteActivityTarget', $params, TRUE)) {
424 // first delete existing targets if any
425 self::deleteActivityContact($activityId, $targetID);
426 }
427
428 $values = array();
429 foreach ($params['target_contact_id'] as $tid) {
430 if ($tid) {
431 $values[] = "( $activityId, $tid, $targetID )";
432 }
433 }
434
435 while (!empty($values)) {
436 $input = array_splice($values, 0, CRM_Core_DAO::BULK_INSERT_COUNT);
437 $str = implode(',', $input);
438 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES $str;";
439 CRM_Core_DAO::executeQuery($sql);
440 }
441 }
442 else {
443 $targetParams['contact_id'] = $params['target_contact_id'];
444 $targetParams['record_type_id'] = $targetID;
445 if (!empty($params['id'])) {
446 $target = new CRM_Activity_BAO_ActivityContact();
447 $target->activity_id = $activityId;
448 $target->record_type_id = $targetID;
449 $target->find(TRUE);
450
451 if ($target->contact_id != $params['target_contact_id']) {
452 $targetParams['id'] = $target->id;
453 $resultTarget = CRM_Activity_BAO_ActivityContact::create($targetParams);
454 }
455 }
456 else {
457 $resultTarget = CRM_Activity_BAO_ActivityContact::create($targetParams);
458 }
459 }
460 }
461 else {
462 if (CRM_Utils_Array::value('deleteActivityTarget', $params, TRUE)) {
463 self::deleteActivityContact($activityId, $targetID);
464 }
465 }
466
467 // write to changelog before transaction is committed/rolled
468 // back (and prepare status to display)
469 if (!empty($params['id'])) {
470 $logMsg = "Activity (id: {$result->id} ) updated with ";
471 }
472 else {
473 $logMsg = "Activity created for ";
474 }
475
476 $msgs = array();
477 if (isset($params['source_contact_id'])) {
478 $msgs[] = "source={$params['source_contact_id']}";
479 }
480
481 if (!empty($params['target_contact_id'])) {
482 if (is_array($params['target_contact_id']) && !CRM_Utils_Array::crmIsEmptyArray($params['target_contact_id'])) {
483 $msgs[] = "target=" . implode(',', $params['target_contact_id']);
484 // take only first target
485 // will be used for recently viewed display
486 $t = array_slice($params['target_contact_id'], 0, 1);
487 $recentContactId = $t[0];
488 }
489 // Is array check fixes warning without degrading functionality but it seems this bit of code may no longer work
490 // as it may always be an array
491 elseif (isset($params['target_contact_id']) && !is_array($params['target_contact_id'])) {
492 $msgs[] = "target={$params['target_contact_id']}";
493 // will be used for recently viewed display
494 $recentContactId = $params['target_contact_id'];
495 }
496 }
497 else {
498 // at worst, take source for recently viewed display
499 $recentContactId = CRM_Utils_Array::value('source_contact_id', $params);
500 }
501
502 if (isset($params['assignee_contact_id'])) {
503 if (is_array($params['assignee_contact_id'])) {
504 $msgs[] = "assignee=" . implode(',', $params['assignee_contact_id']);
505 }
506 else {
507 $msgs[] = "assignee={$params['assignee_contact_id']}";
508 }
509 }
510 $logMsg .= implode(', ', $msgs);
511
512 self::logActivityAction($result, $logMsg);
513
514 if (!empty($params['custom']) &&
515 is_array($params['custom'])
516 ) {
517 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_activity', $result->id);
518 }
519
520 $transaction->commit();
521 if (empty($params['skipRecentView'])) {
522 $recentOther = array();
523 if (!empty($params['case_id'])) {
524 $caseContactID = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseContact', $params['case_id'], 'contact_id', 'case_id');
525 $url = CRM_Utils_System::url('civicrm/case/activity/view',
526 "reset=1&aid={$activity->id}&cid={$caseContactID}&caseID={$params['case_id']}&context=home"
527 );
528 }
529 else {
530 $q = "action=view&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home";
531 if ($activity->activity_type_id != CRM_Core_OptionGroup::getValue('activity_type', 'Email', 'name')) {
532 $url = CRM_Utils_System::url('civicrm/activity', $q);
533 if ($activity->activity_type_id == CRM_Core_OptionGroup::getValue('activity_type', 'Print PDF Letter', 'name')) {
534 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/activity/pdf/add',
535 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home"
536 );
537 }
538 else {
539 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/activity/add',
540 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home"
541 );
542 }
543
544 if (CRM_Core_Permission::check("delete activities")) {
545 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/activity',
546 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home"
547 );
548 }
549 }
550 else {
551 $url = CRM_Utils_System::url('civicrm/activity/view', $q);
552 if (CRM_Core_Permission::check('delete activities')) {
553 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/activity',
554 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home"
555 );
556 }
557 }
558 }
559
560 if (!isset($activity->parent_id)) {
561 $recentContactDisplay = CRM_Contact_BAO_Contact::displayName($recentContactId);
562 // add the recently created Activity
563 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE);
564 $activitySubject = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activity->id, 'subject');
565
566 $title = "";
567 if (isset($activitySubject)) {
568 $title = $activitySubject . ' - ';
569 }
570
571 $title = $title . $recentContactDisplay;
572 if (!empty($activityTypes[$activity->activity_type_id])) {
573 $title .= ' (' . $activityTypes[$activity->activity_type_id] . ')';
574 }
575
576 CRM_Utils_Recent::add($title,
577 $url,
578 $activity->id,
579 'Activity',
580 $recentContactId,
581 $recentContactDisplay,
582 $recentOther
583 );
584 }
585 }
586
587 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
588
589 if (!empty($params['id'])) {
590 CRM_Utils_Hook::post('edit', 'Activity', $activity->id, $activity);
591 }
592 else {
593 CRM_Utils_Hook::post('create', 'Activity', $activity->id, $activity);
594 }
595
596 // if the subject contains a ‘[case #…]’ string, file that activity on the related case (CRM-5916)
597 $matches = array();
598 if (preg_match('/\[case #([0-9a-h]{7})\]/', CRM_Utils_Array::value('subject', $params), $matches)) {
599 $key = CRM_Core_DAO::escapeString(CIVICRM_SITE_KEY);
600 $hash = $matches[1];
601 $query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('$key', id)), 1, 7) = '$hash'";
602 $caseParams = array(
603 'activity_id' => $activity->id,
604 'case_id' => CRM_Core_DAO::singleValueQuery($query),
605 );
606 if ($caseParams['case_id']) {
607 CRM_Case_BAO_Case::processCaseActivity($caseParams);
608 }
609 else {
610 self::logActivityAction($activity, "unknown case hash encountered: $hash");
611 }
612 }
613
614 return $result;
615 }
616
617 /**
618 * Create an activity.
619 *
620 * @todo elaborate on what this does.
621 *
622 * @param CRM_Core_DAO_Activity $activity
623 * @param string $logMessage
624 *
625 * @return bool
626 */
627 public static function logActivityAction($activity, $logMessage = NULL) {
628 $id = CRM_Core_Session::getLoggedInContactID();
629 if (!$id) {
630 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
631 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
632 $id = self::getActivityContact($activity->id, $sourceID);
633 }
634 $logParams = array(
635 'entity_table' => 'civicrm_activity',
636 'entity_id' => $activity->id,
637 'modified_id' => $id,
638 'modified_date' => date('YmdHis'),
639 'data' => $logMessage,
640 );
641 CRM_Core_BAO_Log::add($logParams);
642 return TRUE;
643 }
644
645 /**
646 * Get the list Activities.
647 *
648 * @param array $params
649 * Array of parameters.
650 * Keys include
651 * - contact_id int contact_id whose activities we want to retrieve
652 * - offset int which row to start from ?
653 * - rowCount int how many rows to fetch
654 * - sort object|array object or array describing sort order for sql query.
655 * - admin boolean if contact is admin
656 * - caseId int case ID
657 * - context string page on which selector is build
658 * - activity_type_id int|string the activitiy types we want to restrict by
659 * @param bool $getCount
660 * Get count of the activities
661 *
662 * @return array|int
663 * Relevant data object values of open activities
664 */
665 public static function getActivities($params, $getCount = FALSE) {
666 $activities = array();
667
668 // fetch all activity IDs whose target/assignee/source contact id is $params['contact_id']
669 // currently cannot be done via Activity.Get API so we are using SQL query instead
670 if (!empty($params['contact_id'])) {
671 $activityIDs = CRM_Core_DAO::singleValueQuery("SELECT GROUP_CONCAT(DISTINCT activity_id SEPARATOR ',')
672 FROM civicrm_activity_contact
673 WHERE contact_id = %1", array(1 => array($params['contact_id'], 'Integer')));
674
675 // if no activities found for given $params['contact_id'] then return empty array
676 if (empty($activityIDs)) {
677 return $getCount ? count($activities) : $activities;
678 }
679 $activityIDs = explode(',', $activityIDs);
680 }
681
682 // CRM-20441 Check if user has access to the activities.
683 // This is a temporary fix we need to figure out the rules around
684 // the right permissions to access Activities.
685 // This attpemts to reduce fatal errors in 4.7.19 RC.
686 if (!empty($activityIDs)) {
687 foreach ($activityIDs as $key => $activityId) {
688 try {
689 civicrm_api3('Activity', 'get', array('id' => $activityId, 'check_permissions' => 1));
690 }
691 catch (Exception $e) {
692 unset($activityIDs[$key]);
693 }
694 }
695 }
696
697 // fetch all active activity types
698 $activityTypes = CRM_Core_OptionGroup::values('activity_type');
699
700 // Activity.Get API params
701 $activityParams = array(
702 'id' => (!empty($activityIDs)) ? array('IN' => $activityIDs) : NULL,
703 'is_deleted' => 0,
704 'is_current_revision' => 1,
705 'is_test' => 0,
706 'return' => array(
707 'activity_date_time',
708 'source_record_id',
709 'source_contact_id',
710 'source_contact_name',
711 'assignee_contact_id',
712 'target_contact_id',
713 'target_contact_name',
714 'assignee_contact_name',
715 'status_id',
716 'subject',
717 'activity_type_id',
718 'activity_type',
719 'case_id',
720 'campaign_id',
721 ),
722 'check_permissions' => 1,
723 'options' => array(
724 'offset' => CRM_Utils_Array::value('offset', $params, 0),
725 ),
726 );
727
728 if ($params['context'] != 'activity') {
729 $activityParams['status_id'] = CRM_Core_PseudoConstant::getKey(__CLASS__, 'status_id', 'Scheduled');
730 }
731
732 // activity type ID clause
733 if (!empty($params['activity_type_id'])) {
734 if (is_array($params['activity_type_id'])) {
735 foreach ($params['activity_type_id'] as $idx => $value) {
736 $params['activity_type_id'][$idx] = CRM_Utils_Type::escape($value, 'Positive');
737 }
738 $activityParams['activity_type_id'] = array('IN' => $params['activity_type_id']);
739 }
740 else {
741 $activityParams['activity_type_id'] = CRM_Utils_Type::escape($params['activity_type_id'], 'Positive');
742 }
743 }
744 elseif (!empty($activityTypes) && count($activityTypes)) {
745 $activityParams['activity_type_id'] = array('IN' => array_keys($activityTypes));
746 }
747
748 $excludeActivityIDs = array();
749 if (!empty($params['activity_type_exclude_id'])) {
750 if (is_array($params['activity_type_exclude_id'])) {
751 foreach ($params['activity_type_exclude_id'] as $idx => $value) {
752 $excludeActivityIDs[$idx] = CRM_Utils_Type::escape($value, 'Positive');
753 }
754 }
755 else {
756 $excludeActivityIDs[] = CRM_Utils_Type::escape($params['activity_type_exclude_id'], 'Positive');
757 }
758 }
759
760 if (!empty($params['rowCount']) &&
761 $params['rowCount'] > 0
762 ) {
763 $activityParams['options']['limit'] = $params['rowCount'];
764 }
765 // set limit = 0 if we need to fetch the activity count
766 elseif ($getCount) {
767 $activityParams['options']['limit'] = 0;
768 }
769
770 if (!empty($params['sort'])) {
771 if (is_a($params['sort'], 'CRM_Utils_Sort')) {
772 $order = $params['sort']->orderBy();
773 }
774 elseif (trim($params['sort'])) {
775 $order = CRM_Utils_Type::escape($params['sort'], 'String');
776 }
777 }
778
779 if (empty($order)) {
780 // context = 'activity' in Activities tab.
781 $activityParams['options']['sort'] = (CRM_Utils_Array::value('context', $params) == 'activity') ? "activity_date_time DESC" : "status_id ASC, activity_date_time ASC";
782 }
783 else {
784 $activityParams['options']['sort'] = str_replace('activity_type ', 'activity_type_id.label ', $order);
785 }
786
787 //TODO :
788 // 1. we should use Activity.Getcount for fetching count only, but in order to check that
789 // current logged in user has permission to view Case activities we are performing filtering out those activities from list (see below).
790 // This logic need to be incorporated in Activity.get definition
791 $result = civicrm_api3('Activity', 'Get', $activityParams);
792
793 $enabledComponents = self::activityComponents();
794 $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
795 $bulkActivityTypeID = CRM_Core_PseudoConstant::getKey(__CLASS__, 'activity_type_id', 'Bulk Email');
796
797 // CRM-3553, need to check user has access to target groups.
798 $mailingIDs = CRM_Mailing_BAO_Mailing::mailingACLIDs();
799 $accessCiviMail = ((CRM_Core_Permission::check('access CiviMail')) ||
800 (CRM_Mailing_Info::workflowEnabled() && CRM_Core_Permission::check('create mailings'))
801 );
802
803 $mappingParams = array(
804 'id' => 'activity_id',
805 'source_record_id' => 'source_record_id',
806 'activity_type_id' => 'activity_type_id',
807 'activity_date_time' => 'activity_date_time',
808 'status_id' => 'status_id',
809 'subject' => 'subject',
810 'campaign_id' => 'campaign_id',
811 'assignee_contact_name' => 'assignee_contact_name',
812 'target_contact_name' => 'target_contact_name',
813 'source_contact_id' => 'source_contact_id',
814 'source_contact_name' => 'source_contact_name',
815 'case_id' => 'case_id',
816 );
817
818 foreach ($result['values'] as $id => $activity) {
819 // skip case activities if CiviCase is not enabled OR those actvities which are
820 if ((!empty($activity['case_id']) && !in_array('CiviCase', $enabledComponents)) ||
821 (count($excludeActivityIDs) && in_array($activity['activity_type_id'], $excludeActivityIDs))
822 ) {
823 continue;
824 }
825
826 $activities[$id] = array();
827
828 // if count is needed, no need to populate the array list with attributes
829 if ($getCount) {
830 continue;
831 }
832
833 $isBulkActivity = (!$bulkActivityTypeID || ($bulkActivityTypeID != $activity['activity_type_id']));
834 foreach ($mappingParams as $apiKey => $expectedName) {
835 if (in_array($apiKey, array('assignee_contact_name', 'target_contact_name'))) {
836 $activities[$id][$expectedName] = CRM_Utils_Array::value($apiKey, $activity, array());
837 if ($apiKey == 'target_contact_name' && count($activity['target_contact_name'])) {
838 $activities[$id]['target_contact_counter'] = count($activity['target_contact_name']);
839 }
840
841 if ($isBulkActivity) {
842 $activities[$id]['recipients'] = ts('(%1 recipients)', array(1 => count($activity['target_contact_name'])));
843 $activities[$id]['mailingId'] = FALSE;
844 if ($accessCiviMail &&
845 ($mailingIDs === TRUE || in_array($activity['source_record_id'], $mailingIDs))
846 ) {
847 $activities[$id]['mailingId'] = TRUE;
848 }
849 }
850 }
851 // case related fields
852 elseif ($apiKey == 'case_id' && !$isBulkActivity) {
853 $activities[$id][$expectedName] = CRM_Utils_Array::value($apiKey, $activity);
854
855 // fetch case subject for case ID found
856 if (!empty($activity['case_id'])) {
857 $activities[$id]['case_subject'] = CRM_Core_DAO::executeQuery('CRM_Case_DAO_Case', $activity['case_id'], 'subject');
858 }
859 }
860 else {
861 $activities[$id][$expectedName] = CRM_Utils_Array::value($apiKey, $activity);
862 if ($apiKey == 'activity_type_id') {
863 $activities[$id]['activity_type'] = CRM_Utils_Array::value($activities[$id][$expectedName], $activityTypes);
864 }
865 elseif ($apiKey == 'campaign_id') {
866 $activities[$id]['campaign'] = CRM_Utils_Array::value($activities[$id][$expectedName], $allCampaigns);
867 }
868 }
869 }
870 // if deleted, wrap in <del>
871 if (!empty($activity['source_contact_id']) &&
872 CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $activity['source_contact_id'], 'is_deleted')
873 ) {
874 $activities[$id]['source_contact_name'] = sprintf("<del>%s<del>", $activity['source_contact_name']);
875 }
876 $activities[$id]['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity::getParentFor($id, 'civicrm_activity');
877 }
878
879 return $getCount ? count($activities) : $activities;
880 }
881
882 /**
883 * Get the component id and name if those are enabled and allowed.
884 *
885 * Checks whether logged in user has permission.
886 * To decide whether we are going to include
887 * component related activities with core activity retrieve process.
888 * (what did that just mean?)
889 *
890 * @return array
891 * Array of component id and name.
892 */
893 public static function activityComponents() {
894 $components = array();
895 $compInfo = CRM_Core_Component::getEnabledComponents();
896 foreach ($compInfo as $compObj) {
897 if (!empty($compObj->info['showActivitiesInCore'])) {
898 if ($compObj->info['name'] == 'CiviCampaign') {
899 $componentPermission = "administer {$compObj->name}";
900 }
901 else {
902 $componentPermission = "access {$compObj->name}";
903 }
904 if ($compObj->info['name'] == 'CiviCase') {
905 if (CRM_Case_BAO_Case::accessCiviCase()) {
906 $components[$compObj->componentID] = $compObj->info['name'];
907 }
908 }
909 elseif (CRM_Core_Permission::check($componentPermission)) {
910 $components[$compObj->componentID] = $compObj->info['name'];
911 }
912 }
913 }
914
915 return $components;
916 }
917
918 /**
919 * Send the message to all the contacts.
920 *
921 * Also insert a contact activity in each contacts record.
922 *
923 * @param array $contactDetails
924 * The array of contact details to send the email.
925 * @param string $subject
926 * The subject of the message.
927 * @param $text
928 * @param $html
929 * @param string $emailAddress
930 * Use this 'to' email address instead of the default Primary address.
931 * @param int $userID
932 * Use this userID if set.
933 * @param string $from
934 * @param array $attachments
935 * The array of attachments if any.
936 * @param string $cc
937 * Cc recipient.
938 * @param string $bcc
939 * Bcc recipient.
940 * @param array $contactIds
941 * Contact ids.
942 * @param string $additionalDetails
943 * The additional information of CC and BCC appended to the activity Details.
944 *
945 * @return array
946 * ( sent, activityId) if any email is sent and activityId
947 */
948 public static function sendEmail(
949 &$contactDetails,
950 &$subject,
951 &$text,
952 &$html,
953 $emailAddress,
954 $userID = NULL,
955 $from = NULL,
956 $attachments = NULL,
957 $cc = NULL,
958 $bcc = NULL,
959 $contactIds = NULL,
960 $additionalDetails = NULL,
961 $contributionIds = NULL
962 ) {
963 // get the contact details of logged in contact, which we set as from email
964 if ($userID == NULL) {
965 $userID = CRM_Core_Session::getLoggedInContactID();
966 }
967
968 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($userID);
969 if (!$fromEmail) {
970 return array(count($contactDetails), 0, count($contactDetails));
971 }
972 if (!trim($fromDisplayName)) {
973 $fromDisplayName = $fromEmail;
974 }
975
976 // CRM-4575
977 // token replacement of addressee/email/postal greetings
978 // get the tokens added in subject and message
979 $subjectToken = CRM_Utils_Token::getTokens($subject);
980 $messageToken = CRM_Utils_Token::getTokens($text);
981 $messageToken = array_merge($messageToken, CRM_Utils_Token::getTokens($html));
982 $allTokens = array_merge($messageToken, $subjectToken);
983
984 if (!$from) {
985 $from = "$fromDisplayName <$fromEmail>";
986 }
987
988 //create the meta level record first ( email activity )
989 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
990 'Email',
991 'name'
992 );
993
994 // CRM-6265: save both text and HTML parts in details (if present)
995 if ($html and $text) {
996 $details = "-ALTERNATIVE ITEM 0-\n$html$additionalDetails\n-ALTERNATIVE ITEM 1-\n$text$additionalDetails\n-ALTERNATIVE END-\n";
997 }
998 else {
999 $details = $html ? $html : $text;
1000 $details .= $additionalDetails;
1001 }
1002
1003 $activityParams = array(
1004 'source_contact_id' => $userID,
1005 'activity_type_id' => $activityTypeID,
1006 'activity_date_time' => date('YmdHis'),
1007 'subject' => $subject,
1008 'details' => $details,
1009 // FIXME: check for name Completed and get ID from that lookup
1010 'status_id' => 2,
1011 );
1012
1013 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
1014 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1015
1016 // add the attachments to activity params here
1017 if ($attachments) {
1018 // first process them
1019 $activityParams = array_merge($activityParams,
1020 $attachments
1021 );
1022 }
1023
1024 $activity = self::create($activityParams);
1025
1026 // get the set of attachments from where they are stored
1027 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_activity',
1028 $activity->id
1029 );
1030 $returnProperties = array();
1031 if (isset($messageToken['contact'])) {
1032 foreach ($messageToken['contact'] as $key => $value) {
1033 $returnProperties[$value] = 1;
1034 }
1035 }
1036
1037 if (isset($subjectToken['contact'])) {
1038 foreach ($subjectToken['contact'] as $key => $value) {
1039 if (!isset($returnProperties[$value])) {
1040 $returnProperties[$value] = 1;
1041 }
1042 }
1043 }
1044
1045 // get token details for contacts, call only if tokens are used
1046 $details = array();
1047 if (!empty($returnProperties) || !empty($tokens) || !empty($allTokens)) {
1048 list($details) = CRM_Utils_Token::getTokenDetails(
1049 $contactIds,
1050 $returnProperties,
1051 NULL, NULL, FALSE,
1052 $allTokens,
1053 'CRM_Activity_BAO_Activity'
1054 );
1055 }
1056
1057 // call token hook
1058 $tokens = array();
1059 CRM_Utils_Hook::tokens($tokens);
1060 $categories = array_keys($tokens);
1061
1062 $escapeSmarty = FALSE;
1063 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
1064 $smarty = CRM_Core_Smarty::singleton();
1065 $escapeSmarty = TRUE;
1066 }
1067
1068 $contributionDetails = array();
1069 if (!empty($contributionIds)) {
1070 $contributionDetails = CRM_Contribute_BAO_Contribution::replaceContributionTokens(
1071 $contributionIds,
1072 $subject,
1073 $subjectToken,
1074 $text,
1075 $html,
1076 $messageToken,
1077 $escapeSmarty
1078 );
1079 }
1080
1081 $sent = $notSent = array();
1082 foreach ($contactDetails as $values) {
1083 $contactId = $values['contact_id'];
1084 $emailAddress = $values['email'];
1085
1086 if (!empty($contributionDetails)) {
1087 $subject = $contributionDetails[$contactId]['subject'];
1088 $text = $contributionDetails[$contactId]['text'];
1089 $html = $contributionDetails[$contactId]['html'];
1090 }
1091
1092 if (!empty($details) && is_array($details["{$contactId}"])) {
1093 // unset email from details since it always returns primary email address
1094 unset($details["{$contactId}"]['email']);
1095 unset($details["{$contactId}"]['email_id']);
1096 $values = array_merge($values, $details["{$contactId}"]);
1097 }
1098
1099 $tokenSubject = CRM_Utils_Token::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1100 $tokenSubject = CRM_Utils_Token::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1101
1102 // CRM-4539
1103 if ($values['preferred_mail_format'] == 'Text' || $values['preferred_mail_format'] == 'Both') {
1104 $tokenText = CRM_Utils_Token::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1105 $tokenText = CRM_Utils_Token::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1106 }
1107 else {
1108 $tokenText = NULL;
1109 }
1110
1111 if ($values['preferred_mail_format'] == 'HTML' || $values['preferred_mail_format'] == 'Both') {
1112 $tokenHtml = CRM_Utils_Token::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1113 $tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1114 }
1115 else {
1116 $tokenHtml = NULL;
1117 }
1118
1119 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
1120 // also add the contact tokens to the template
1121 $smarty->assign_by_ref('contact', $values);
1122
1123 $tokenSubject = $smarty->fetch("string:$tokenSubject");
1124 $tokenText = $smarty->fetch("string:$tokenText");
1125 $tokenHtml = $smarty->fetch("string:$tokenHtml");
1126 }
1127
1128 $sent = FALSE;
1129 if (self::sendMessage(
1130 $from,
1131 $userID,
1132 $contactId,
1133 $tokenSubject,
1134 $tokenText,
1135 $tokenHtml,
1136 $emailAddress,
1137 $activity->id,
1138 $attachments,
1139 $cc,
1140 $bcc
1141 )
1142 ) {
1143 $sent = TRUE;
1144 }
1145 }
1146
1147 return array($sent, $activity->id);
1148 }
1149
1150 /**
1151 * Send SMS.
1152 *
1153 * @param array $contactDetails
1154 * @param array $activityParams
1155 * @param array $smsParams
1156 * @param $contactIds
1157 * @param int $userID
1158 *
1159 * @return array
1160 * @throws CRM_Core_Exception
1161 */
1162 public static function sendSMS(
1163 &$contactDetails,
1164 &$activityParams,
1165 &$smsParams = array(),
1166 &$contactIds,
1167 $userID = NULL
1168 ) {
1169 if ($userID == NULL) {
1170 $userID = CRM_Core_Session::getLoggedInContactID();
1171 }
1172
1173 $text = &$activityParams['sms_text_message'];
1174
1175 // CRM-4575
1176 // token replacement of addressee/email/postal greetings
1177 // get the tokens added in subject and message
1178 $messageToken = CRM_Utils_Token::getTokens($text);
1179
1180 // Create the meta level record first ( sms activity )
1181 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
1182 'SMS',
1183 'name'
1184 );
1185
1186 $details = $text;
1187
1188 $activitySubject = $activityParams['activity_subject'];
1189 $activityParams = array(
1190 'source_contact_id' => $userID,
1191 'activity_type_id' => $activityTypeID,
1192 'activity_date_time' => date('YmdHis'),
1193 'subject' => $activitySubject,
1194 'details' => $details,
1195 // FIXME: check for name Completed and get ID from that lookup
1196 'status_id' => 2,
1197 );
1198
1199 $activity = self::create($activityParams);
1200 $activityID = $activity->id;
1201
1202 $returnProperties = array();
1203
1204 if (isset($messageToken['contact'])) {
1205 foreach ($messageToken['contact'] as $key => $value) {
1206 $returnProperties[$value] = 1;
1207 }
1208 }
1209
1210 // call token hook
1211 $tokens = array();
1212 CRM_Utils_Hook::tokens($tokens);
1213 $categories = array_keys($tokens);
1214
1215 // get token details for contacts, call only if tokens are used
1216 $details = array();
1217 if (!empty($returnProperties) || !empty($tokens)) {
1218 list($details) = CRM_Utils_Token::getTokenDetails($contactIds,
1219 $returnProperties,
1220 NULL, NULL, FALSE,
1221 $messageToken,
1222 'CRM_Activity_BAO_Activity'
1223 );
1224 }
1225
1226 $success = 0;
1227 $escapeSmarty = FALSE;
1228 $errMsgs = array();
1229 foreach ($contactDetails as $values) {
1230 $contactId = $values['contact_id'];
1231
1232 if (!empty($details) && is_array($details["{$contactId}"])) {
1233 // unset phone from details since it always returns primary number
1234 unset($details["{$contactId}"]['phone']);
1235 unset($details["{$contactId}"]['phone_type_id']);
1236 $values = array_merge($values, $details["{$contactId}"]);
1237 }
1238
1239 $tokenText = CRM_Utils_Token::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1240 $tokenText = CRM_Utils_Token::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1241
1242 // Only send if the phone is of type mobile
1243 $phoneTypes = CRM_Core_OptionGroup::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
1244 if ($values['phone_type_id'] == CRM_Utils_Array::value('Mobile', $phoneTypes)) {
1245 $smsParams['To'] = $values['phone'];
1246 }
1247 else {
1248 $smsParams['To'] = '';
1249 }
1250
1251 $sendResult = self::sendSMSMessage(
1252 $contactId,
1253 $tokenText,
1254 $smsParams,
1255 $activityID,
1256 $userID
1257 );
1258
1259 if (PEAR::isError($sendResult)) {
1260 // Collect all of the PEAR_Error objects
1261 $errMsgs[] = $sendResult;
1262 }
1263 else {
1264 $success++;
1265 }
1266 }
1267
1268 // If at least one message was sent and no errors
1269 // were generated then return a boolean value of TRUE.
1270 // Otherwise, return FALSE (no messages sent) or
1271 // and array of 1 or more PEAR_Error objects.
1272 $sent = FALSE;
1273 if ($success > 0 && count($errMsgs) == 0) {
1274 $sent = TRUE;
1275 }
1276 elseif (count($errMsgs) > 0) {
1277 $sent = $errMsgs;
1278 }
1279
1280 return array($sent, $activity->id, $success);
1281 }
1282
1283 /**
1284 * Send the sms message to a specific contact.
1285 *
1286 * @param int $toID
1287 * The contact id of the recipient.
1288 * @param $tokenText
1289 * @param array $smsParams
1290 * The params used for sending sms.
1291 * @param int $activityID
1292 * The activity ID that tracks the message.
1293 * @param int $userID
1294 *
1295 * @return bool|PEAR_Error
1296 * true on success or PEAR_Error object
1297 */
1298 public static function sendSMSMessage(
1299 $toID,
1300 &$tokenText,
1301 $smsParams = array(),
1302 $activityID,
1303 $userID = NULL
1304 ) {
1305 $toDoNotSms = "";
1306 $toPhoneNumber = "";
1307
1308 if ($smsParams['To']) {
1309 $toPhoneNumber = trim($smsParams['To']);
1310 }
1311 elseif ($toID) {
1312 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
1313 $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($toID, FALSE, 'Mobile', $filters);
1314 // To get primary mobile phonenumber,if not get the first mobile phonenumber
1315 if (!empty($toPhoneNumbers)) {
1316 $toPhoneNumerDetails = reset($toPhoneNumbers);
1317 $toPhoneNumber = CRM_Utils_Array::value('phone', $toPhoneNumerDetails);
1318 // Contact allows to send sms
1319 $toDoNotSms = 0;
1320 }
1321 }
1322
1323 // make sure both phone are valid
1324 // and that the recipient wants to receive sms
1325 if (empty($toPhoneNumber) or $toDoNotSms) {
1326 return PEAR::raiseError(
1327 'Recipient phone number is invalid or recipient does not want to receive SMS',
1328 NULL,
1329 PEAR_ERROR_RETURN
1330 );
1331 }
1332
1333 $recipient = $smsParams['To'];
1334 $smsParams['contact_id'] = $toID;
1335 $smsParams['parent_activity_id'] = $activityID;
1336
1337 $providerObj = CRM_SMS_Provider::singleton(array('provider_id' => $smsParams['provider_id']));
1338 $sendResult = $providerObj->send($recipient, $smsParams, $tokenText, NULL, $userID);
1339 if (PEAR::isError($sendResult)) {
1340 return $sendResult;
1341 }
1342
1343 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1344 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1345
1346 // add activity target record for every sms that is send
1347 $activityTargetParams = array(
1348 'activity_id' => $activityID,
1349 'contact_id' => $toID,
1350 'record_type_id' => $targetID,
1351 );
1352 CRM_Activity_BAO_ActivityContact::create($activityTargetParams);
1353
1354 return TRUE;
1355 }
1356
1357 /**
1358 * Send the message to a specific contact.
1359 *
1360 * @param string $from
1361 * The name and email of the sender.
1362 * @param int $fromID
1363 * @param int $toID
1364 * The contact id of the recipient.
1365 * @param string $subject
1366 * The subject of the message.
1367 * @param $text_message
1368 * @param $html_message
1369 * @param string $emailAddress
1370 * Use this 'to' email address instead of the default Primary address.
1371 * @param int $activityID
1372 * The activity ID that tracks the message.
1373 * @param null $attachments
1374 * @param null $cc
1375 * @param null $bcc
1376 *
1377 * @return bool
1378 * TRUE if successful else FALSE.
1379 */
1380 public static function sendMessage(
1381 $from,
1382 $fromID,
1383 $toID,
1384 &$subject,
1385 &$text_message,
1386 &$html_message,
1387 $emailAddress,
1388 $activityID,
1389 $attachments = NULL,
1390 $cc = NULL,
1391 $bcc = NULL
1392 ) {
1393 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($toID);
1394 if ($emailAddress) {
1395 $toEmail = trim($emailAddress);
1396 }
1397
1398 // make sure both email addresses are valid
1399 // and that the recipient wants to receive email
1400 if (empty($toEmail) or $toDoNotEmail) {
1401 return FALSE;
1402 }
1403 if (!trim($toDisplayName)) {
1404 $toDisplayName = $toEmail;
1405 }
1406
1407 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1408 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1409
1410 // create the params array
1411 $mailParams = array(
1412 'groupName' => 'Activity Email Sender',
1413 'from' => $from,
1414 'toName' => $toDisplayName,
1415 'toEmail' => $toEmail,
1416 'subject' => $subject,
1417 'cc' => $cc,
1418 'bcc' => $bcc,
1419 'text' => $text_message,
1420 'html' => $html_message,
1421 'attachments' => $attachments,
1422 );
1423
1424 if (!CRM_Utils_Mail::send($mailParams)) {
1425 return FALSE;
1426 }
1427
1428 // add activity target record for every mail that is send
1429 $activityTargetParams = array(
1430 'activity_id' => $activityID,
1431 'contact_id' => $toID,
1432 'record_type_id' => $targetID,
1433 );
1434 CRM_Activity_BAO_ActivityContact::create($activityTargetParams);
1435 return TRUE;
1436 }
1437
1438 /**
1439 * Combine all the importable fields from the lower levels object.
1440 *
1441 * The ordering is important, since currently we do not have a weight
1442 * scheme. Adding weight is super important and should be done in the
1443 * next week or so, before this can be called complete.
1444 *
1445 * @param bool $status
1446 *
1447 * @return array
1448 * array of importable Fields
1449 */
1450 public static function &importableFields($status = FALSE) {
1451 if (!self::$_importableFields) {
1452 if (!self::$_importableFields) {
1453 self::$_importableFields = array();
1454 }
1455 if (!$status) {
1456 $fields = array('' => array('title' => ts('- do not import -')));
1457 }
1458 else {
1459 $fields = array('' => array('title' => ts('- Activity Fields -')));
1460 }
1461
1462 $tmpFields = CRM_Activity_DAO_Activity::import();
1463 $contactFields = CRM_Contact_BAO_Contact::importableFields('Individual', NULL);
1464
1465 // Using new Dedupe rule.
1466 $ruleParams = array(
1467 'contact_type' => 'Individual',
1468 'used' => 'Unsupervised',
1469 );
1470 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
1471
1472 $tmpConatctField = array();
1473 if (is_array($fieldsArray)) {
1474 foreach ($fieldsArray as $value) {
1475 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
1476 $value,
1477 'id',
1478 'column_name'
1479 );
1480 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
1481 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
1482 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
1483 }
1484 }
1485 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
1486 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
1487 $fields = array_merge($fields, $tmpConatctField);
1488 $fields = array_merge($fields, $tmpFields);
1489 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Activity'));
1490 self::$_importableFields = $fields;
1491 }
1492 return self::$_importableFields;
1493 }
1494
1495 /**
1496 * @deprecated - use the api instead.
1497 *
1498 * Get the Activities of a target contact.
1499 *
1500 * @param int $contactId
1501 * Id of the contact whose activities need to find.
1502 *
1503 * @return array
1504 * array of activity fields
1505 */
1506 public static function getContactActivity($contactId) {
1507 // @todo remove this function entirely.
1508 $activities = array();
1509 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1510 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1511 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
1512 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1513
1514 // First look for activities where contactId is one of the targets
1515 $query = "
1516 SELECT activity_id, record_type_id
1517 FROM civicrm_activity_contact
1518 WHERE contact_id = $contactId
1519 ";
1520 $dao = CRM_Core_DAO::executeQuery($query);
1521 while ($dao->fetch()) {
1522 if ($dao->record_type_id == $targetID) {
1523 $activities[$dao->activity_id]['targets'][$contactId] = $contactId;
1524 }
1525 elseif ($dao->record_type_id == $assigneeID) {
1526 $activities[$dao->activity_id]['asignees'][$contactId] = $contactId;
1527 }
1528 else {
1529 // do source stuff here
1530 $activities[$dao->activity_id]['source_contact_id'] = $contactId;
1531 }
1532 }
1533
1534 $activityIds = array_keys($activities);
1535 if (count($activityIds) < 1) {
1536 return array();
1537 }
1538
1539 $activityIds = implode(',', $activityIds);
1540 $query = "
1541 SELECT activity.id as activity_id,
1542 activity_type_id,
1543 subject, location, activity_date_time, details, status_id
1544 FROM civicrm_activity activity
1545 WHERE activity.id IN ($activityIds)";
1546
1547 $dao = CRM_Core_DAO::executeQuery($query);
1548
1549 $activityTypes = CRM_Core_OptionGroup::values('activity_type');
1550 $activityStatuses = CRM_Core_OptionGroup::values('activity_status');
1551
1552 while ($dao->fetch()) {
1553 $activities[$dao->activity_id]['id'] = $dao->activity_id;
1554 $activities[$dao->activity_id]['activity_type_id'] = $dao->activity_type_id;
1555 $activities[$dao->activity_id]['subject'] = $dao->subject;
1556 $activities[$dao->activity_id]['location'] = $dao->location;
1557 $activities[$dao->activity_id]['activity_date_time'] = $dao->activity_date_time;
1558 $activities[$dao->activity_id]['details'] = $dao->details;
1559 $activities[$dao->activity_id]['status_id'] = $dao->status_id;
1560 $activities[$dao->activity_id]['activity_name'] = $activityTypes[$dao->activity_type_id];
1561 $activities[$dao->activity_id]['status'] = $activityStatuses[$dao->status_id];
1562
1563 // set to null if not set
1564 if (!isset($activities[$dao->activity_id]['source_contact_id'])) {
1565 $activities[$dao->activity_id]['source_contact_id'] = NULL;
1566 }
1567 }
1568 return $activities;
1569 }
1570
1571 /**
1572 * Add activity for Membership/Event/Contribution.
1573 *
1574 * @param object $activity
1575 * (reference) particular component object.
1576 * @param string $activityType
1577 * For Membership Signup or Renewal.
1578 * @param int $targetContactID
1579 *
1580 * @return bool|NULL
1581 */
1582 public static function addActivity(
1583 &$activity,
1584 $activityType = 'Membership Signup',
1585 $targetContactID = NULL
1586 ) {
1587 if ($activity->__table == 'civicrm_membership') {
1588 $membershipType = CRM_Member_PseudoConstant::membershipType($activity->membership_type_id);
1589
1590 if (!$membershipType) {
1591 $membershipType = ts('Membership');
1592 }
1593
1594 $subject = "{$membershipType}";
1595
1596 if (!empty($activity->source) && $activity->source != 'null') {
1597 $subject .= " - {$activity->source}";
1598 }
1599
1600 if ($activity->owner_membership_id) {
1601 $query = "
1602 SELECT display_name
1603 FROM civicrm_contact, civicrm_membership
1604 WHERE civicrm_contact.id = civicrm_membership.contact_id
1605 AND civicrm_membership.id = $activity->owner_membership_id
1606 ";
1607 $displayName = CRM_Core_DAO::singleValueQuery($query);
1608 $subject .= " (by {$displayName})";
1609 }
1610
1611 $subject .= " - Status: " . CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $activity->status_id, 'label');
1612 // CRM-72097 changed from start date to today
1613 $date = date('YmdHis');
1614 $component = 'Membership';
1615 }
1616 elseif ($activity->__table == 'civicrm_participant') {
1617 $event = CRM_Event_BAO_Event::getEvents(1, $activity->event_id, TRUE, FALSE);
1618
1619 $roles = CRM_Event_PseudoConstant::participantRole();
1620 $status = CRM_Event_PseudoConstant::participantStatus();
1621
1622 $subject = $event[$activity->event_id];
1623 if (!empty($roles[$activity->role_id])) {
1624 $subject .= ' - ' . $roles[$activity->role_id];
1625 }
1626 if (!empty($status[$activity->status_id])) {
1627 $subject .= ' - ' . $status[$activity->status_id];
1628 }
1629 $date = date('YmdHis');
1630 if ($activityType != 'Email') {
1631 $activityType = 'Event Registration';
1632 }
1633 $component = 'Event';
1634 }
1635 elseif ($activity->__table == 'civicrm_contribution') {
1636 // create activity record only for Completed Contributions
1637 if ($activity->contribution_status_id != 1) {
1638 return NULL;
1639 }
1640
1641 $subject = NULL;
1642
1643 $subject .= CRM_Utils_Money::format($activity->total_amount, $activity->currency);
1644 if (!empty($activity->source) && $activity->source != 'null') {
1645 $subject .= " - {$activity->source}";
1646 }
1647 $date = CRM_Utils_Date::isoToMysql($activity->receive_date);
1648 $activityType = $component = 'Contribution';
1649 }
1650 $activityParams = array(
1651 'source_contact_id' => $activity->contact_id,
1652 'source_record_id' => $activity->id,
1653 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
1654 $activityType,
1655 'name'
1656 ),
1657 'subject' => $subject,
1658 'activity_date_time' => $date,
1659 'is_test' => $activity->is_test,
1660 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
1661 'Completed',
1662 'name'
1663 ),
1664 'skipRecentView' => TRUE,
1665 'campaign_id' => $activity->campaign_id,
1666 );
1667
1668 if (!empty($activity->activity_id)) {
1669 $activityParams['id'] = $activity->activity_id;
1670 }
1671 // create activity with target contacts
1672 $id = CRM_Core_Session::getLoggedInContactID();
1673 if ($id) {
1674 $activityParams['source_contact_id'] = $id;
1675 $activityParams['target_contact_id'][] = $activity->contact_id;
1676 }
1677
1678 // CRM-14945
1679 if (property_exists($activity, 'details')) {
1680 $activityParams['details'] = $activity->details;
1681 }
1682 //CRM-4027
1683 if ($targetContactID) {
1684 $activityParams['target_contact_id'][] = $targetContactID;
1685 }
1686 if (is_a(self::create($activityParams), 'CRM_Core_Error')) {
1687 CRM_Core_Error::fatal("Failed creating Activity for $component of id {$activity->id}");
1688 return FALSE;
1689 }
1690 }
1691
1692 /**
1693 * Get Parent activity for currently viewed activity.
1694 *
1695 * @param int $activityId
1696 * Current activity id.
1697 *
1698 * @return int
1699 * Id of parent activity otherwise false.
1700 */
1701 public static function getParentActivity($activityId) {
1702 static $parentActivities = array();
1703
1704 $activityId = CRM_Utils_Type::escape($activityId, 'Integer');
1705
1706 if (!array_key_exists($activityId, $parentActivities)) {
1707 $parentActivities[$activityId] = array();
1708
1709 $parentId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1710 $activityId,
1711 'parent_id'
1712 );
1713
1714 $parentActivities[$activityId] = $parentId ? $parentId : FALSE;
1715 }
1716
1717 return $parentActivities[$activityId];
1718 }
1719
1720 /**
1721 * Get total count of prior revision of currently viewed activity.
1722 *
1723 * @param $activityID
1724 * Current activity id.
1725 *
1726 * @return int
1727 * $params count of prior activities otherwise false.
1728 */
1729 public static function getPriorCount($activityID) {
1730 static $priorCounts = array();
1731
1732 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
1733
1734 if (!array_key_exists($activityID, $priorCounts)) {
1735 $priorCounts[$activityID] = array();
1736 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1737 $activityID,
1738 'original_id'
1739 );
1740 $count = 0;
1741 if ($originalID) {
1742 $query = "
1743 SELECT count( id ) AS cnt
1744 FROM civicrm_activity
1745 WHERE ( id = {$originalID} OR original_id = {$originalID} )
1746 AND is_current_revision = 0
1747 AND id < {$activityID}
1748 ";
1749 $params = array(1 => array($originalID, 'Integer'));
1750 $count = CRM_Core_DAO::singleValueQuery($query, $params);
1751 }
1752 $priorCounts[$activityID] = $count ? $count : 0;
1753 }
1754
1755 return $priorCounts[$activityID];
1756 }
1757
1758 /**
1759 * Get all prior activities of currently viewed activity.
1760 *
1761 * @param $activityID
1762 * Current activity id.
1763 * @param bool $onlyPriorRevisions
1764 *
1765 * @return array
1766 * prior activities info.
1767 */
1768 public static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
1769 static $priorActivities = array();
1770
1771 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
1772 $index = $activityID . '_' . (int) $onlyPriorRevisions;
1773
1774 if (!array_key_exists($index, $priorActivities)) {
1775 $priorActivities[$index] = array();
1776
1777 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1778 $activityID,
1779 'original_id'
1780 );
1781 if (!$originalID) {
1782 $originalID = $activityID;
1783 }
1784 if ($originalID) {
1785 $query = "
1786 SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
1787 FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
1788 WHERE (ca.id = %1 OR ca.original_id = %1)
1789 AND cl.entity_table = 'civicrm_activity'
1790 AND cl.entity_id = ca.id
1791 AND cl.modified_id = c.id
1792 ";
1793 if ($onlyPriorRevisions) {
1794 $query .= " AND ca.id < {$activityID}";
1795 }
1796 $query .= " ORDER BY ca.id DESC";
1797
1798 $params = array(1 => array($originalID, 'Integer'));
1799 $dao = CRM_Core_DAO::executeQuery($query, $params);
1800
1801 while ($dao->fetch()) {
1802 $priorActivities[$index][$dao->activityID]['id'] = $dao->activityID;
1803 $priorActivities[$index][$dao->activityID]['name'] = $dao->name;
1804 $priorActivities[$index][$dao->activityID]['date'] = $dao->date;
1805 }
1806 $dao->free();
1807 }
1808 }
1809 return $priorActivities[$index];
1810 }
1811
1812 /**
1813 * Find the latest revision of a given activity.
1814 *
1815 * @param int $activityID
1816 * Prior activity id.
1817 *
1818 * @return int
1819 * current activity id.
1820 */
1821 public static function getLatestActivityId($activityID) {
1822 static $latestActivityIds = array();
1823
1824 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
1825
1826 if (!array_key_exists($activityID, $latestActivityIds)) {
1827 $latestActivityIds[$activityID] = array();
1828
1829 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1830 $activityID,
1831 'original_id'
1832 );
1833 if ($originalID) {
1834 $activityID = $originalID;
1835 }
1836 $params = array(1 => array($activityID, 'Integer'));
1837 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
1838
1839 $latestActivityIds[$activityID] = CRM_Core_DAO::singleValueQuery($query, $params);
1840 }
1841
1842 return $latestActivityIds[$activityID];
1843 }
1844
1845 /**
1846 * Create a follow up a given activity.
1847 *
1848 * @param int $activityId
1849 * activity id of parent activity.
1850 * @param array $params
1851 *
1852 * @return CRM_Activity_BAO_Activity|null|object
1853 */
1854 public static function createFollowupActivity($activityId, $params) {
1855 if (!$activityId) {
1856 return NULL;
1857 }
1858
1859 $followupParams = array();
1860 $followupParams['parent_id'] = $activityId;
1861 $followupParams['source_contact_id'] = CRM_Core_Session::getLoggedInContactID();
1862 $followupParams['status_id'] = CRM_Core_OptionGroup::getValue('activity_status', 'Scheduled', 'name');
1863
1864 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
1865 // Get Subject of Follow-up Activiity, CRM-4491
1866 $followupParams['subject'] = CRM_Utils_Array::value('followup_activity_subject', $params);
1867 $followupParams['assignee_contact_id'] = CRM_Utils_Array::value('followup_assignee_contact_id', $params);
1868
1869 // Create target contact for followup.
1870 if (!empty($params['target_contact_id'])) {
1871 $followupParams['target_contact_id'] = $params['target_contact_id'];
1872 }
1873
1874 $followupParams['activity_date_time'] = CRM_Utils_Date::processDate($params['followup_date'],
1875 $params['followup_date_time']
1876 );
1877 $followupActivity = self::create($followupParams);
1878
1879 return $followupActivity;
1880 }
1881
1882 /**
1883 * Get Activity specific File according activity type Id.
1884 *
1885 * @param int $activityTypeId
1886 * Activity id.
1887 * @param string $crmDir
1888 *
1889 * @return string|bool
1890 * if file exists returns $activityTypeFile activity filename otherwise false.
1891 */
1892 public static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
1893 $activityTypes = CRM_Case_PseudoConstant::caseActivityType(FALSE, TRUE);
1894
1895 if ($activityTypes[$activityTypeId]['name']) {
1896 $activityTypeFile = CRM_Utils_String::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
1897 }
1898 else {
1899 return FALSE;
1900 }
1901
1902 global $civicrm_root;
1903 $config = CRM_Core_Config::singleton();
1904 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
1905 if (empty($config->customPHPPathDir)) {
1906 return FALSE;
1907 }
1908 elseif (!file_exists(rtrim($config->customPHPPathDir, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
1909 return FALSE;
1910 }
1911 }
1912
1913 return $activityTypeFile;
1914 }
1915
1916 /**
1917 * Restore the activity.
1918 *
1919 * @param array $params
1920 *
1921 * @return CRM_Activity_DAO_Activity
1922 */
1923 public static function restoreActivity(&$params) {
1924 $activity = new CRM_Activity_DAO_Activity();
1925 $activity->copyValues($params);
1926
1927 $activity->is_deleted = 0;
1928 $result = $activity->save();
1929
1930 return $result;
1931 }
1932
1933 /**
1934 * Get the exportable fields for Activities.
1935 *
1936 * @param string $name
1937 * If it is called by case $name = Case else $name = Activity.
1938 *
1939 * @return array
1940 * array of exportable Fields
1941 */
1942 public static function &exportableFields($name = 'Activity') {
1943 if (!isset(self::$_exportableFields[$name])) {
1944 self::$_exportableFields[$name] = array();
1945
1946 // TODO: ideally we should retrieve all fields from xml, in this case since activity processing is done
1947 // my case hence we have defined fields as case_*
1948 if ($name == 'Activity') {
1949 $exportableFields = CRM_Activity_DAO_Activity::export();
1950 $exportableFields['source_contact_id']['title'] = ts('Source Contact ID');
1951 $exportableFields['source_contact'] = array(
1952 'title' => ts('Source Contact'),
1953 'type' => CRM_Utils_Type::T_STRING,
1954 );
1955
1956 $Activityfields = array(
1957 'activity_type' => array(
1958 'title' => ts('Activity Type'),
1959 'name' => 'activity_type',
1960 'type' => CRM_Utils_Type::T_STRING,
1961 'searchByLabel' => TRUE,
1962 ),
1963 'activity_status' => array(
1964 'title' => ts('Activity Status'),
1965 'name' => 'activity_status',
1966 'type' => CRM_Utils_Type::T_STRING,
1967 'searchByLabel' => TRUE,
1968 ),
1969 'activity_priority' => array(
1970 'title' => ts('Activity Priority'),
1971 'name' => 'activity_priority',
1972 'type' => CRM_Utils_Type::T_STRING,
1973 'searchByLabel' => TRUE,
1974 ),
1975 );
1976 $fields = array_merge($Activityfields, $exportableFields);
1977 }
1978 else {
1979 // Set title to activity fields.
1980 $fields = array(
1981 'case_activity_subject' => array('title' => ts('Activity Subject'), 'type' => CRM_Utils_Type::T_STRING),
1982 'case_source_contact_id' => array('title' => ts('Activity Reporter'), 'type' => CRM_Utils_Type::T_STRING),
1983 'case_recent_activity_date' => array('title' => ts('Activity Actual Date'), 'type' => CRM_Utils_Type::T_DATE),
1984 'case_scheduled_activity_date' => array(
1985 'title' => ts('Activity Scheduled Date'),
1986 'type' => CRM_Utils_Type::T_DATE,
1987 ),
1988 'case_recent_activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type::T_STRING),
1989 'case_activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type::T_STRING),
1990 'case_activity_duration' => array('title' => ts('Activity Duration'), 'type' => CRM_Utils_Type::T_INT),
1991 'case_activity_medium_id' => array('title' => ts('Activity Medium'), 'type' => CRM_Utils_Type::T_INT),
1992 'case_activity_details' => array('title' => ts('Activity Details'), 'type' => CRM_Utils_Type::T_TEXT),
1993 'case_activity_is_auto' => array(
1994 'title' => ts('Activity Auto-generated?'),
1995 'type' => CRM_Utils_Type::T_BOOLEAN,
1996 ),
1997 );
1998 }
1999
2000 // add custom data for case activities
2001 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Activity'));
2002
2003 self::$_exportableFields[$name] = $fields;
2004 }
2005 return self::$_exportableFields[$name];
2006 }
2007
2008 /**
2009 * Get the allowed profile fields for Activities.
2010 *
2011 * @return array
2012 * array of activity profile Fields
2013 */
2014 public static function getProfileFields() {
2015 $exportableFields = self::exportableFields('Activity');
2016 $skipFields = array(
2017 'activity_id',
2018 'activity_type',
2019 'source_contact_id',
2020 'source_contact',
2021 'activity_campaign',
2022 'activity_is_test',
2023 'is_current_revision',
2024 'activity_is_deleted',
2025 );
2026 $config = CRM_Core_Config::singleton();
2027 if (!in_array('CiviCampaign', $config->enableComponents)) {
2028 $skipFields[] = 'activity_engagement_level';
2029 }
2030
2031 foreach ($skipFields as $field) {
2032 if (isset($exportableFields[$field])) {
2033 unset($exportableFields[$field]);
2034 }
2035 }
2036
2037 // hack to use 'activity_type_id' instead of 'activity_type'
2038 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2039 unset($exportableFields['activity_status']);
2040
2041 return $exportableFields;
2042 }
2043
2044 /**
2045 * This function deletes the activity record related to contact record.
2046 *
2047 * This is conditional on there being no target and assignee record
2048 * with other contacts.
2049 *
2050 * @param int $contactId
2051 * ContactId.
2052 *
2053 * @return true/null
2054 */
2055 public static function cleanupActivity($contactId) {
2056 $result = NULL;
2057 if (!$contactId) {
2058 return $result;
2059 }
2060 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2061 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2062
2063 $transaction = new CRM_Core_Transaction();
2064
2065 // delete activity if there is no record in civicrm_activity_contact
2066 // pointing to any other contact record
2067 $activityContact = new CRM_Activity_DAO_ActivityContact();
2068 $activityContact->contact_id = $contactId;
2069 $activityContact->record_type_id = $sourceID;
2070 $activityContact->find();
2071
2072 while ($activityContact->fetch()) {
2073 // delete activity_contact record for the deleted contact
2074 $activityContact->delete();
2075
2076 $activityContactOther = new CRM_Activity_DAO_ActivityContact();
2077 $activityContactOther->activity_id = $activityContact->activity_id;
2078
2079 // delete activity only if no other contacts connected
2080 if (!$activityContactOther->find(TRUE)) {
2081 $activityParams = array('id' => $activityContact->activity_id);
2082 $result = self::deleteActivity($activityParams);
2083 }
2084
2085 $activityContactOther->free();
2086 }
2087
2088 $activityContact->free();
2089 $transaction->commit();
2090
2091 return $result;
2092 }
2093
2094 /**
2095 * Does user has sufficient permission for view/edit activity record.
2096 *
2097 * @param int $activityId
2098 * Activity record id.
2099 * @param int $action
2100 * Edit/view.
2101 *
2102 * @return bool
2103 */
2104 public static function checkPermission($activityId, $action) {
2105 $allow = FALSE;
2106 if (!$activityId ||
2107 !in_array($action, array(CRM_Core_Action::UPDATE, CRM_Core_Action::VIEW))
2108 ) {
2109 return $allow;
2110 }
2111
2112 $activity = new CRM_Activity_DAO_Activity();
2113 $activity->id = $activityId;
2114 if (!$activity->find(TRUE)) {
2115 return $allow;
2116 }
2117
2118 // Component related permissions.
2119 $compPermissions = array(
2120 'CiviCase' => array(
2121 'administer CiviCase',
2122 'access my cases and activities',
2123 'access all cases and activities',
2124 ),
2125 'CiviMail' => array('access CiviMail'),
2126 'CiviEvent' => array('access CiviEvent'),
2127 'CiviGrant' => array('access CiviGrant'),
2128 'CiviPledge' => array('access CiviPledge'),
2129 'CiviMember' => array('access CiviMember'),
2130 'CiviReport' => array('access CiviReport'),
2131 'CiviContribute' => array('access CiviContribute'),
2132 'CiviCampaign' => array('administer CiviCampaign'),
2133 );
2134
2135 // Return early when it is case activity.
2136 $isCaseActivity = CRM_Case_BAO_Case::isCaseActivity($activityId);
2137 // Check for civicase related permission.
2138 if ($isCaseActivity) {
2139 $allow = FALSE;
2140 foreach ($compPermissions['CiviCase'] as $per) {
2141 if (CRM_Core_Permission::check($per)) {
2142 $allow = TRUE;
2143 break;
2144 }
2145 }
2146
2147 // Check for case specific permissions.
2148 if ($allow) {
2149 $oper = 'view';
2150 if ($action == CRM_Core_Action::UPDATE) {
2151 $oper = 'edit';
2152 }
2153 $allow = CRM_Case_BAO_Case::checkPermission($activityId,
2154 $oper,
2155 $activity->activity_type_id
2156 );
2157 }
2158
2159 return $allow;
2160 }
2161
2162 // First check the component permission.
2163 $sql = "
2164 SELECT component_id
2165 FROM civicrm_option_value val
2166 INNER JOIN civicrm_option_group grp ON ( grp.id = val.option_group_id AND grp.name = %1 )
2167 WHERE val.value = %2";
2168 $params = array(
2169 1 => array('activity_type', 'String'),
2170 2 => array($activity->activity_type_id, 'Integer'),
2171 );
2172 $componentId = CRM_Core_DAO::singleValueQuery($sql, $params);
2173
2174 if ($componentId) {
2175 $componentName = CRM_Core_Component::getComponentName($componentId);
2176 $compPermission = CRM_Utils_Array::value($componentName, $compPermissions);
2177
2178 // Here we are interesting in any single permission.
2179 if (is_array($compPermission)) {
2180 foreach ($compPermission as $per) {
2181 if (CRM_Core_Permission::check($per)) {
2182 $allow = TRUE;
2183 break;
2184 }
2185 }
2186 }
2187 }
2188
2189 // Check for this permission related to contact.
2190 $permission = CRM_Core_Permission::VIEW;
2191 if ($action == CRM_Core_Action::UPDATE) {
2192 $permission = CRM_Core_Permission::EDIT;
2193 }
2194
2195 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2196 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2197 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
2198 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
2199
2200 // Check for source contact.
2201 if (!$componentId || $allow) {
2202 $sourceContactId = self::getActivityContact($activity->id, $sourceID);
2203 // Account for possibility of activity not having a source contact (as it may have been deleted).
2204 $allow = $sourceContactId ? CRM_Contact_BAO_Contact_Permission::allow($sourceContactId, $permission) : TRUE;
2205 }
2206
2207 // Check for target and assignee contacts.
2208 if ($allow) {
2209 // First check for supper permission.
2210 $supPermission = 'view all contacts';
2211 if ($action == CRM_Core_Action::UPDATE) {
2212 $supPermission = 'edit all contacts';
2213 }
2214 $allow = CRM_Core_Permission::check($supPermission);
2215
2216 // User might have sufficient permission, through acls.
2217 if (!$allow) {
2218 $allow = TRUE;
2219 // Get the target contacts.
2220 $targetContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $targetID);
2221 foreach ($targetContacts as $cnt => $contactId) {
2222 if (!CRM_Contact_BAO_Contact_Permission::allow($contactId, $permission)) {
2223 $allow = FALSE;
2224 break;
2225 }
2226 }
2227
2228 // Get the assignee contacts.
2229 if ($allow) {
2230 $assigneeContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $assigneeID);
2231 foreach ($assigneeContacts as $cnt => $contactId) {
2232 if (!CRM_Contact_BAO_Contact_Permission::allow($contactId, $permission)) {
2233 $allow = FALSE;
2234 break;
2235 }
2236 }
2237 }
2238 }
2239 }
2240
2241 return $allow;
2242 }
2243
2244 /**
2245 * Wrapper for ajax activity selector.
2246 *
2247 * @param array $params
2248 * Associated array for params record id.
2249 *
2250 * @return array
2251 * Associated array of contact activities
2252 */
2253 public static function getContactActivitySelector(&$params) {
2254 // Format the params.
2255 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2256 $params['rowCount'] = $params['rp'];
2257 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
2258 $params['caseId'] = NULL;
2259 $context = CRM_Utils_Array::value('context', $params);
2260 $showContactOverlay = !CRM_Utils_String::startsWith($context, "dashlet");
2261 $activityTypeInfo = civicrm_api3('OptionValue', 'get', array(
2262 'option_group_id' => "activity_type",
2263 'options' => array('limit' => 0),
2264 ));
2265 $activityIcons = array();
2266 foreach ($activityTypeInfo['values'] as $type) {
2267 if (!empty($type['icon'])) {
2268 $activityIcons[$type['value']] = $type['icon'];
2269 }
2270 }
2271
2272 // Get contact activities.
2273 $activities = CRM_Activity_BAO_Activity::getActivities($params);
2274
2275 // Add total.
2276 $params['total'] = count($activities);
2277
2278 // Format params and add links.
2279 $contactActivities = array();
2280
2281 if (!empty($activities)) {
2282 $activityStatus = CRM_Core_PseudoConstant::activityStatus();
2283
2284 // Check logged in user for permission.
2285 $page = new CRM_Core_Page();
2286 CRM_Contact_Page_View::checkUserPermission($page, $params['contact_id']);
2287 $permissions = array($page->_permission);
2288 if (CRM_Core_Permission::check('delete activities')) {
2289 $permissions[] = CRM_Core_Permission::DELETE;
2290 }
2291
2292 $mask = CRM_Core_Action::mask($permissions);
2293
2294 foreach ($activities as $activityId => $values) {
2295 $activity = array();
2296 $activity['DT_RowId'] = $activityId;
2297 // Add class to this row if overdue.
2298 $activity['DT_RowClass'] = "crm-entity status-id-{$values['status_id']}";
2299 if (CRM_Utils_Date::overdue(CRM_Utils_Array::value('activity_date_time', $values))
2300 && CRM_Utils_Array::value('status_id', $values) == 1
2301 ) {
2302 $activity['DT_RowClass'] .= ' status-overdue';
2303 }
2304 else {
2305 $activity['DT_RowClass'] .= ' status-ontime';
2306 }
2307
2308 $activity['DT_RowAttr'] = array();
2309 $activity['DT_RowAttr']['data-entity'] = 'activity';
2310 $activity['DT_RowAttr']['data-id'] = $activityId;
2311
2312 $activity['activity_type'] = (!empty($activityIcons[$values['activity_type_id']]) ? '<span class="crm-i ' . $activityIcons[$values['activity_type_id']] . '"></span> ' : '') . $values['activity_type'];
2313 $activity['subject'] = $values['subject'];
2314
2315 $activity['source_contact_name'] = '';
2316 if ($params['contact_id'] == $values['source_contact_id']) {
2317 $activity['source_contact_name'] = $values['source_contact_name'];
2318 }
2319 elseif ($values['source_contact_id']) {
2320 $srcTypeImage = "";
2321 if ($showContactOverlay) {
2322 $srcTypeImage = CRM_Contact_BAO_Contact_Utils::getImage(
2323 CRM_Contact_BAO_Contact::getContactType($values['source_contact_id']),
2324 FALSE,
2325 $values['source_contact_id']);
2326 }
2327 $activity['source_contact_name'] = $srcTypeImage . CRM_Utils_System::href($values['source_contact_name'],
2328 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
2329 }
2330 else {
2331 $activity['source_contact_name'] = '<em>n/a</em>';
2332 }
2333
2334 $activity['target_contact_name'] = '';
2335 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
2336 $activity['target_contact'] = CRM_Utils_System::href($values['recipients'],
2337 'civicrm/mailing/report/event',
2338 "mid={$values['source_record_id']}&reset=1&event=queue&cid={$params['contact_id']}&context=activitySelector");
2339 }
2340 elseif (!empty($values['recipients'])) {
2341 $activity['target_contact_name'] = $values['recipients'];
2342 }
2343 elseif (isset($values['target_contact_counter']) && $values['target_contact_counter']) {
2344 $activity['target_contact_name'] = '';
2345 foreach ($values['target_contact_name'] as $tcID => $tcName) {
2346 $targetTypeImage = "";
2347 $targetLink = CRM_Utils_System::href($tcName, 'civicrm/contact/view', "reset=1&cid={$tcID}");
2348 if ($showContactOverlay) {
2349 $targetTypeImage = CRM_Contact_BAO_Contact_Utils::getImage(
2350 CRM_Contact_BAO_Contact::getContactType($tcID),
2351 FALSE,
2352 $tcID);
2353 $activity['target_contact_name'] .= "<div>$targetTypeImage $targetLink";
2354 }
2355 else {
2356 $activity['target_contact_name'] .= $targetLink;
2357 }
2358 }
2359
2360 if ($extraCount = $values['target_contact_counter'] - 1) {
2361 $activity['target_contact_name'] .= ";<br />" . "(" . ts('%1 more', array(1 => $extraCount)) . ")";
2362 }
2363 if ($showContactOverlay) {
2364 $activity['target_contact_name'] .= "</div> ";
2365 }
2366 }
2367 elseif (!$values['target_contact_name']) {
2368 $activity['target_contact_name'] = '<em>n/a</em>';
2369 }
2370
2371 $activity['assignee_contact_name'] = '';
2372 if (empty($values['assignee_contact_name'])) {
2373 $activity['assignee_contact_name'] = '<em>n/a</em>';
2374 }
2375 elseif (!empty($values['assignee_contact_name'])) {
2376 $count = 0;
2377 $activity['assignee_contact_name'] = '';
2378 foreach ($values['assignee_contact_name'] as $acID => $acName) {
2379 if ($acID && $count < 5) {
2380 $assigneeTypeImage = "";
2381 $assigneeLink = CRM_Utils_System::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
2382 if ($showContactOverlay) {
2383 $assigneeTypeImage = CRM_Contact_BAO_Contact_Utils::getImage(
2384 CRM_Contact_BAO_Contact::getContactType($acID),
2385 FALSE,
2386 $acID);
2387 $activity['assignee_contact_name'] .= "<div>$assigneeTypeImage $assigneeLink";
2388 }
2389 else {
2390 $activity['assignee_contact_name'] .= $assigneeLink;
2391 }
2392
2393 $count++;
2394 if ($count) {
2395 $activity['assignee_contact_name'] .= ";&nbsp;";
2396 }
2397 if ($showContactOverlay) {
2398 $activity['assignee_contact_name'] .= "</div> ";
2399 }
2400
2401 if ($count == 4) {
2402 $activity['assignee_contact_name'] .= "(" . ts('more') . ")";
2403 break;
2404 }
2405 }
2406 }
2407 }
2408
2409 $activity['activity_date_time'] = CRM_Utils_Date::customFormat($values['activity_date_time']);
2410 $activity['status_id'] = $activityStatus[$values['status_id']];
2411
2412 // build links
2413 $activity['links'] = '';
2414 $accessMailingReport = FALSE;
2415 if (!empty($values['mailingId'])) {
2416 $accessMailingReport = TRUE;
2417 }
2418
2419 $actionLinks = CRM_Activity_Selector_Activity::actionLinks(
2420 CRM_Utils_Array::value('activity_type_id', $values),
2421 CRM_Utils_Array::value('source_record_id', $values),
2422 $accessMailingReport,
2423 CRM_Utils_Array::value('activity_id', $values)
2424 );
2425
2426 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
2427
2428 $activity['links'] = CRM_Core_Action::formLink($actionLinks,
2429 $actionMask,
2430 array(
2431 'id' => $values['activity_id'],
2432 'cid' => $params['contact_id'],
2433 'cxt' => $context,
2434 'caseid' => CRM_Utils_Array::value('case_id', $values),
2435 ),
2436 ts('more'),
2437 FALSE,
2438 'activity.tab.row',
2439 'Activity',
2440 $values['activity_id']
2441 );
2442
2443 if ($values['is_recurring_activity']) {
2444 $activity['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity::getPositionAndCount($values['activity_id'], 'civicrm_activity');
2445 }
2446
2447 array_push($contactActivities, $activity);
2448 }
2449 }
2450
2451 $activitiesDT = array();
2452 $activitiesDT['data'] = $contactActivities;
2453 $activitiesDT['recordsTotal'] = $params['total'];
2454 $activitiesDT['recordsFiltered'] = $params['total'];
2455
2456 return $activitiesDT;
2457 }
2458
2459 /**
2460 * Copy custom fields and attachments from an existing activity to another.
2461 *
2462 * @see CRM_Case_Page_AJAX::_convertToCaseActivity()
2463 *
2464 * @param array $params
2465 */
2466 public static function copyExtendedActivityData($params) {
2467 // attach custom data to the new activity
2468 $customParams = $htmlType = array();
2469 $customValues = CRM_Core_BAO_CustomValueTable::getEntityValues($params['activityID'], 'Activity');
2470
2471 if (!empty($customValues)) {
2472 $fieldIds = implode(', ', array_keys($customValues));
2473 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
2474 $result = CRM_Core_DAO::executeQuery($sql);
2475
2476 while ($result->fetch()) {
2477 $htmlType[] = $result->id;
2478 }
2479
2480 foreach ($customValues as $key => $value) {
2481 if ($value !== NULL) {
2482 // CRM-10542
2483 if (in_array($key, $htmlType)) {
2484 $fileValues = CRM_Core_BAO_File::path($value, $params['activityID']);
2485 $customParams["custom_{$key}_-1"] = array(
2486 'name' => $fileValues[0],
2487 'path' => $fileValues[1],
2488 );
2489 }
2490 else {
2491 $customParams["custom_{$key}_-1"] = $value;
2492 }
2493 }
2494 }
2495 CRM_Core_BAO_CustomValueTable::postProcess($customParams, 'civicrm_activity',
2496 $params['mainActivityId'], 'Activity'
2497 );
2498 }
2499
2500 // copy activity attachments ( if any )
2501 CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
2502 }
2503
2504 /**
2505 * Get activity contact.
2506 *
2507 * @param int $activityId
2508 * @param int $recordTypeID
2509 * @param string $column
2510 *
2511 * @return null
2512 */
2513 public static function getActivityContact($activityId, $recordTypeID = NULL, $column = 'contact_id') {
2514 $activityContact = new CRM_Activity_BAO_ActivityContact();
2515 $activityContact->activity_id = $activityId;
2516 if ($recordTypeID) {
2517 $activityContact->record_type_id = $recordTypeID;
2518 }
2519 if ($activityContact->find(TRUE)) {
2520 return $activityContact->$column;
2521 }
2522 return NULL;
2523 }
2524
2525 /**
2526 * Get source contact id.
2527 *
2528 * @param int $activityId
2529 *
2530 * @return null
2531 */
2532 public static function getSourceContactID($activityId) {
2533 static $sourceID = NULL;
2534 if (!$sourceID) {
2535 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2536 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2537 }
2538
2539 return self::getActivityContact($activityId, $sourceID);
2540 }
2541
2542 /**
2543 * Set api filter.
2544 *
2545 * @todo Document what this is for.
2546 *
2547 * @param array $params
2548 */
2549 public function setApiFilter(&$params) {
2550 if (!empty($params['target_contact_id'])) {
2551 $this->selectAdd();
2552 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2553 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
2554 $obj = new CRM_Activity_BAO_ActivityContact();
2555 $params['return.target_contact_id'] = 1;
2556 $this->joinAdd($obj, 'LEFT');
2557 $this->selectAdd('civicrm_activity.*');
2558 $this->whereAdd(" civicrm_activity_contact.contact_id = {$params['target_contact_id']} AND civicrm_activity_contact.record_type_id = {$targetID}");
2559 }
2560 }
2561
2562 /**
2563 * Send activity as attachment.
2564 *
2565 * @param object $activity
2566 * @param array $mailToContacts
2567 * @param array $params
2568 *
2569 * @return bool
2570 */
2571 public static function sendToAssignee($activity, $mailToContacts, $params = array()) {
2572 if (!CRM_Utils_Array::crmIsEmptyArray($mailToContacts)) {
2573 $clientID = CRM_Utils_Array::value('client_id', $params);
2574 $caseID = CRM_Utils_Array::value('case_id', $params);
2575
2576 $ics = new CRM_Activity_BAO_ICalendar($activity);
2577 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_activity', $activity->id);
2578 $ics->addAttachment($attachments, $mailToContacts);
2579
2580 $result = CRM_Case_BAO_Case::sendActivityCopy($clientID, $activity->id, $mailToContacts, $attachments, $caseID);
2581 $ics->cleanup();
2582 return $result;
2583 }
2584 return FALSE;
2585 }
2586
2587 }