First commit

This commit is contained in:
Theodotos Andreou 2018-01-14 13:10:16 +00:00
commit c6e2478c40
13918 changed files with 2303184 additions and 0 deletions

View file

@ -0,0 +1,138 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
use Civi\ActionSchedule\RecipientBuilder;
/**
* Class CRM_Activity_ActionMapping
*
* This defines the scheduled-reminder functionality for contact
* entities. It is useful for, e.g., sending a reminder based on
* birth date, modification date, or other custom dates on
* the contact record.
*/
class CRM_Activity_ActionMapping extends \Civi\ActionSchedule\Mapping {
/**
* The value for civicrm_action_schedule.mapping_id which identifies the
* "Activity" mapping.
*
* Note: This value is chosen to match legacy DB IDs.
*/
const ACTIVITY_MAPPING_ID = 1;
/**
* Register Activity-related action mappings.
*
* @param \Civi\ActionSchedule\Event\MappingRegisterEvent $registrations
*/
public static function onRegisterActionMappings(\Civi\ActionSchedule\Event\MappingRegisterEvent $registrations) {
$registrations->register(CRM_Activity_ActionMapping::create(array(
'id' => CRM_Activity_ActionMapping::ACTIVITY_MAPPING_ID,
'entity' => 'civicrm_activity',
'entity_label' => ts('Activity'),
'entity_value' => 'activity_type',
'entity_value_label' => ts('Activity Type'),
'entity_status' => 'activity_status',
'entity_status_label' => ts('Activity Status'),
'entity_date_start' => 'activity_date_time',
)));
}
/**
* Get a list of recipient types.
*
* Note: A single schedule may filter on *zero* or *one* recipient types.
* When an admin chooses a value, it's stored in $schedule->recipient.
*
* @return array
* array(string $value => string $label).
* Ex: array('assignee' => 'Activity Assignee').
*/
public function getRecipientTypes() {
return \CRM_Core_OptionGroup::values('activity_contacts');
}
/**
* Generate a query to locate recipients who match the given
* schedule.
*
* @param \CRM_Core_DAO_ActionSchedule $schedule
* The schedule as configured by the administrator.
* @param string $phase
* See, e.g., RecipientBuilder::PHASE_RELATION_FIRST.
*
* @param array $defaultParams
*
* @return \CRM_Utils_SQL_Select
* @see RecipientBuilder
*/
public function createQuery($schedule, $phase, $defaultParams) {
$selectedValues = (array) \CRM_Utils_Array::explodePadded($schedule->entity_value);
$selectedStatuses = (array) \CRM_Utils_Array::explodePadded($schedule->entity_status);
$query = \CRM_Utils_SQL_Select::from("{$this->entity} e")->param($defaultParams);
$query['casAddlCheckFrom'] = 'civicrm_activity e';
$query['casContactIdField'] = 'r.contact_id';
$query['casEntityIdField'] = 'e.id';
$query['casContactTableAlias'] = NULL;
$query['casDateField'] = 'e.activity_date_time';
if (!is_null($schedule->limit_to)) {
$activityContacts = \CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
if ($schedule->limit_to == 0 || !isset($activityContacts[$schedule->recipient])) {
$recipientTypeId = \CRM_Utils_Array::key('Activity Targets', $activityContacts);
}
else {
$recipientTypeId = $schedule->recipient;
}
$query->join('r', "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$recipientTypeId}");
}
// build where clause
if (!empty($selectedValues)) {
$query->where("e.activity_type_id IN (#selectedValues)")
->param('selectedValues', $selectedValues);
}
else {
$query->where("e.activity_type_id IS NULL");
}
if (!empty($selectedStatuses)) {
$query->where("e.status_id IN (#selectedStatuss)")
->param('selectedStatuss', $selectedStatuses);
}
$query->where('e.is_current_revision = 1 AND e.is_deleted = 0');
return $query;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,158 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class is for activity assignment functions.
*/
class CRM_Activity_BAO_ActivityAssignment extends CRM_Activity_DAO_ActivityContact {
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Add activity assignment.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return object
* activity type of object that is added
*/
public static function create(&$params) {
$assignment = new CRM_Activity_BAO_ActivityContact();
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
$assignment->copyValues($params);
$assignment->record_type_id = $assigneeID;
return $assignment->save();
}
/**
* Retrieve assignee_id by activity_id.
*
* @param int $activity_id
*
* @return array
*/
public static function retrieveAssigneeIdsByActivityId($activity_id) {
$assigneeArray = array();
if (!CRM_Utils_Rule::positiveInteger($activity_id)) {
return $assigneeArray;
}
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
$sql = "
SELECT contact_id
FROM civicrm_activity_contact
INNER JOIN civicrm_contact ON contact_id = civicrm_contact.id
WHERE activity_id = %1
AND record_type_id = $assigneeID
AND civicrm_contact.is_deleted = 0
";
$assignment = CRM_Core_DAO::executeQuery($sql, array(1 => array($activity_id, 'Integer')));
while ($assignment->fetch()) {
$assigneeArray[] = $assignment->contact_id;
}
return $assigneeArray;
}
/**
* Retrieve assignee names by activity_id.
*
* @param array $activityIDs
* IDs of the activities.
* @param bool $isDisplayName
* If set returns display names of assignees.
* @param bool $skipDetails
* If false returns all details of assignee contact.
*
* @return array
*/
public static function getAssigneeNames($activityIDs, $isDisplayName = FALSE, $skipDetails = TRUE) {
$assigneeNames = array();
if (empty($activityIDs)) {
return $assigneeNames;
}
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
$whereClause = "";
if (!$skipDetails) {
$whereClause = " AND ce.is_primary= 1";
}
$inClause = implode(",", $activityIDs);
$query = "
SELECT contact_a.id, contact_a.sort_name, contact_a.display_name, ce.email,
civicrm_activity_contact.activity_id
FROM civicrm_contact contact_a
INNER JOIN civicrm_activity_contact ON civicrm_activity_contact.contact_id = contact_a.id
LEFT JOIN civicrm_email ce ON ce.contact_id = contact_a.id
WHERE civicrm_activity_contact.activity_id IN ( $inClause )
AND contact_a.is_deleted = 0
AND civicrm_activity_contact.record_type_id = $assigneeID
{$whereClause}
";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
if (!$isDisplayName) {
$assigneeNames[$dao->id] = $dao->sort_name;
}
else {
if ($skipDetails) {
$assigneeNames[$dao->id] = $dao->display_name;
}
else {
$assigneeNames[$dao->id]['contact_id'] = $dao->id;
$assigneeNames[$dao->id]['display_name'] = $dao->display_name;
$assigneeNames[$dao->id]['sort_name'] = $dao->sort_name;
$assigneeNames[$dao->id]['email'] = $dao->email;
$assigneeNames[$dao->id]['role'] = ts('Activity Assignee');
$assigneeNames[$dao->id]['activity_id'] = $dao->activity_id;
}
}
}
return $assigneeNames;
}
}

View file

@ -0,0 +1,159 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class is for activity assignment functions.
*/
class CRM_Activity_BAO_ActivityContact extends CRM_Activity_DAO_ActivityContact {
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Function to add activity contact.
*
* @param array $params
* The values for this table: activity id, contact id, record type.
*
* @return object
* activity_contact object
*/
public static function create(&$params) {
$activityContact = new CRM_Activity_DAO_ActivityContact();
$activityContact->copyValues($params);
if (!$activityContact->find(TRUE)) {
return $activityContact->save();
}
return $activityContact;
}
/**
* Retrieve names of contact by activity_id.
*
* @param int $activityID
* @param int $recordTypeID
* @param bool $alsoIDs
*
* @return array
*/
public static function getNames($activityID, $recordTypeID, $alsoIDs = FALSE) {
$names = array();
$ids = array();
if (empty($activityID)) {
return $alsoIDs ? array($names, $ids) : $names;
}
$query = "
SELECT contact_a.id, contact_a.sort_name
FROM civicrm_contact contact_a
INNER JOIN civicrm_activity_contact ON civicrm_activity_contact.contact_id = contact_a.id
WHERE civicrm_activity_contact.activity_id = %1
AND civicrm_activity_contact.record_type_id = %2
AND contact_a.is_deleted = 0
";
$params = array(
1 => array($activityID, 'Integer'),
2 => array($recordTypeID, 'Integer'),
);
$dao = CRM_Core_DAO::executeQuery($query, $params);
while ($dao->fetch()) {
$names[$dao->id] = $dao->sort_name;
$ids[] = $dao->id;
}
return $alsoIDs ? array($names, $ids) : $names;
}
/**
* Retrieve id of target contact by activity_id.
*
* @param int $activityID
* @param int $recordTypeID
*
* @return mixed
*/
public static function retrieveContactIdsByActivityId($activityID, $recordTypeID) {
$activityContact = array();
if (!CRM_Utils_Rule::positiveInteger($activityID) ||
!CRM_Utils_Rule::positiveInteger($recordTypeID)
) {
return $activityContact;
}
$sql = " SELECT contact_id
FROM civicrm_activity_contact
INNER JOIN civicrm_contact ON contact_id = civicrm_contact.id
WHERE activity_id = %1
AND record_type_id = %2
AND civicrm_contact.is_deleted = 0
";
$params = array(
1 => array($activityID, 'Integer'),
2 => array($recordTypeID, 'Integer'),
);
$dao = CRM_Core_DAO::executeQuery($sql, $params);
while ($dao->fetch()) {
$activityContact[] = $dao->contact_id;
}
return $activityContact;
}
/**
* Get the links associate array as defined by the links.ini file.
*
* Experimental... -
* Should look a bit like
* [local_col_name] => "related_tablename:related_col_name"
*
* @see DB_DataObject::getLinks()
* @see DB_DataObject::getLink()
*
* @return array|null
* array = if there are links defined for this table.
* empty array - if there is a links.ini file, but no links on this table
* null - if no links.ini exists for this database (hence try auto_links).
*/
public function links() {
$link = array('activity_id' => 'civicrm_activity:id');
return $link;
}
}

View file

@ -0,0 +1,129 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class is for activity assignment functions.
*/
class CRM_Activity_BAO_ActivityTarget extends CRM_Activity_DAO_ActivityContact {
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Add activity target.
*
* @param array $params
*
* @return object
* activity type of object that is added
*/
public static function create(&$params) {
$target = new CRM_Activity_BAO_ActivityContact();
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
$target->copyValues($params);
$target->record_type_id = $targetID;
return $target->save();
}
/**
* Retrieve id of target contact by activity_id.
*
* @param int $activity_id
*
* @return mixed
*/
public static function retrieveTargetIdsByActivityId($activity_id) {
$targetArray = array();
if (!CRM_Utils_Rule::positiveInteger($activity_id)) {
return $targetArray;
}
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
$sql = "
SELECT contact_id
FROM civicrm_activity_contact
INNER JOIN civicrm_contact ON contact_id = civicrm_contact.id
WHERE activity_id = %1
AND record_type_id = $targetID
AND civicrm_contact.is_deleted = 0
";
$target = CRM_Core_DAO::executeQuery($sql, array(1 => array($activity_id, 'Integer')));
while ($target->fetch()) {
$targetArray[] = $target->contact_id;
}
return $targetArray;
}
/**
* Retrieve names of target contact by activity_id.
*
* @param int $activityID
*
* @return array
*/
public static function getTargetNames($activityID) {
$targetNames = array();
if (empty($activityID)) {
return $targetNames;
}
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
$query = "
SELECT contact_a.id, contact_a.sort_name
FROM civicrm_contact contact_a
INNER JOIN civicrm_activity_contact ON civicrm_activity_contact.contact_id = contact_a.id
WHERE civicrm_activity_contact.activity_id = %1
AND civicrm_activity_contact.record_type_id = $targetID
AND contact_a.is_deleted = 0
";
$queryParam = array(1 => array($activityID, 'Integer'));
$dao = CRM_Core_DAO::executeQuery($query, $queryParam);
while ($dao->fetch()) {
$targetNames[$dao->id] = $dao->sort_name;
}
return $targetNames;
}
}

View file

@ -0,0 +1,137 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Generate ical invites for activities.
*/
class CRM_Activity_BAO_ICalendar {
/**
* @var object The activity for which we're generating ical.
*/
protected $activity;
/**
* Constructor.
*
* @param object $act
* Reference to an activity object.
*
* @return \CRM_Activity_BAO_ICalendar
*/
public function __construct(&$act) {
$this->activity = $act;
}
/**
* Add an ics attachment to the input array.
*
* @param array $attachments
* Reference to array in same format returned from CRM_Core_BAO_File::getEntityFile().
* @param array $contacts
* Array of contacts (attendees).
*
* @return string|null
* Array index of the added attachment in the $attachments array, else NULL.
*/
public function addAttachment(&$attachments, $contacts) {
// Check preferences setting
if (Civi::settings()->get('activity_assignee_notification_ics')) {
$config = &CRM_Core_Config::singleton();
$this->icsfile = tempnam($config->customFileUploadDir, 'ics');
if ($this->icsfile !== FALSE) {
rename($this->icsfile, $this->icsfile . '.ics');
$this->icsfile .= '.ics';
$icsFileName = basename($this->icsfile);
// get logged in user's primary email
// TODO: Is there a better way to do this?
$organizer = $this->getPrimaryEmail();
$template = CRM_Core_Smarty::singleton();
$template->assign('activity', $this->activity);
$template->assign('organizer', $organizer);
$template->assign('contacts', $contacts);
$template->assign('timezone', date_default_timezone_get());
$calendar = $template->fetch('CRM/Activity/Calendar/ICal.tpl');
if (file_put_contents($this->icsfile, $calendar) !== FALSE) {
if (empty($attachments)) {
$attachments = array();
}
$attachments['activity_ics'] = array(
'mime_type' => 'text/calendar',
'fileName' => $icsFileName,
'cleanName' => $icsFileName,
'fullPath' => $this->icsfile,
);
return 'activity_ics';
}
}
}
return NULL;
}
/**
* Remove temp file.
*/
public function cleanup() {
if (!empty ($this->icsfile)) {
@unlink($this->icsfile);
}
}
/**
* @todo Is there a better way to do this?
* @return string
*/
private function getPrimaryEmail() {
$uid = CRM_Core_Session::getLoggedInContactID();
$primary = '';
$emails = CRM_Core_BAO_Email::allEmails($uid);
foreach ($emails as $eid => $e) {
if ($e['is_primary']) {
if ($e['email']) {
$primary = $e['email'];
break;
}
}
if (count($emails) == 1) {
$primary = $e['email'];
break;
}
}
return $primary;
}
}

View file

@ -0,0 +1,652 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Activity_BAO_Query {
/**
* Build select for Case.
*
* @param CRM_Contact_BAO_Query $query
*/
public static function select(&$query) {
if (!empty($query->_returnProperties['activity_id'])) {
$query->_select['activity_id'] = 'civicrm_activity.id as activity_id';
$query->_element['activity_id'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
if (!empty($query->_returnProperties['activity_type_id'])) {
$query->_select['activity_type_id'] = 'activity_type.value as activity_type_id';
$query->_element['activity_type_id'] = 1;
$query->_tables['civicrm_activity'] = 1;
$query->_tables['activity_type'] = 1;
$query->_whereTables['civicrm_activity'] = 1;
$query->_whereTables['activity_type'] = 1;
}
if (!empty($query->_returnProperties['activity_type'])) {
$query->_select['activity_type'] = 'activity_type.label as activity_type';
$query->_element['activity_type'] = 1;
$query->_tables['civicrm_activity'] = 1;
$query->_tables['activity_type'] = 1;
$query->_whereTables['civicrm_activity'] = 1;
$query->_whereTables['activity_type'] = 1;
}
if (!empty($query->_returnProperties['activity_subject'])) {
$query->_select['activity_subject'] = 'civicrm_activity.subject as activity_subject';
$query->_element['activity_subject'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
if (!empty($query->_returnProperties['activity_date_time'])) {
$query->_select['activity_date_time'] = 'civicrm_activity.activity_date_time as activity_date_time';
$query->_element['activity_date_time'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
if (!empty($query->_returnProperties['activity_status_id'])) {
$query->_select['activity_status_id'] = 'civicrm_activity.status_id as activity_status_id';
$query->_element['activity_status_id'] = 1;
$query->_tables['civicrm_activity'] = 1;
$query->_whereTables['civicrm_activity'] = 1;
}
if (!empty($query->_returnProperties['activity_status'])) {
$query->_select['activity_status'] = 'activity_status.label as activity_status,
civicrm_activity.status_id as status_id';
$query->_element['activity_status'] = 1;
$query->_tables['civicrm_activity'] = 1;
$query->_tables['activity_status'] = 1;
$query->_whereTables['civicrm_activity'] = 1;
$query->_whereTables['activity_status'] = 1;
}
if (!empty($query->_returnProperties['activity_duration'])) {
$query->_select['activity_duration'] = 'civicrm_activity.duration as activity_duration';
$query->_element['activity_duration'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
if (!empty($query->_returnProperties['activity_location'])) {
$query->_select['activity_location'] = 'civicrm_activity.location as activity_location';
$query->_element['activity_location'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
if (!empty($query->_returnProperties['activity_details'])) {
$query->_select['activity_details'] = 'civicrm_activity.details as activity_details';
$query->_element['activity_details'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
if (!empty($query->_returnProperties['source_record_id'])) {
$query->_select['source_record_id'] = 'civicrm_activity.source_record_id as source_record_id';
$query->_element['source_record_id'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
if (!empty($query->_returnProperties['activity_is_test'])) {
$query->_select['activity_is_test'] = 'civicrm_activity.is_test as activity_is_test';
$query->_element['activity_is_test'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
if (!empty($query->_returnProperties['activity_campaign_id'])) {
$query->_select['activity_campaign_id'] = 'civicrm_activity.campaign_id as activity_campaign_id';
$query->_element['activity_campaign_id'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
if (!empty($query->_returnProperties['activity_engagement_level'])) {
$query->_select['activity_engagement_level'] = 'civicrm_activity.engagement_level as activity_engagement_level';
$query->_element['activity_engagement_level'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
if (!empty($query->_returnProperties['source_contact'])) {
$query->_select['source_contact'] = 'source_contact.sort_name as source_contact';
$query->_element['source_contact'] = 1;
$query->_tables['source_contact'] = $query->_whereTables['source_contact'] = 1;
}
if (!empty($query->_returnProperties['activity_result'])) {
$query->_select['activity_result'] = 'civicrm_activity.result as activity_result';
$query->_element['result'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
if (CRM_Utils_Array::value('parent_id', $query->_returnProperties)) {
$query->_tables['parent_id'] = 1;
$query->_whereTables['parent_id'] = 1;
$query->_element['parent_id'] = 1;
}
if (!empty($query->_returnProperties['activity_priority'])) {
$query->_select['activity_priority'] = 'activity_priority.label as activity_priority,
civicrm_activity.priority_id as priority_id';
$query->_element['activity_priority'] = 1;
$query->_tables['activity_priority'] = 1;
$query->_whereTables['activity_priority'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
}
/**
* Given a list of conditions in query generate the required where clause.
*
* @param $query
*/
public static function where(&$query) {
foreach (array_keys($query->_params) as $id) {
if (substr($query->_params[$id][0], 0, 9) == 'activity_') {
if ($query->_mode == CRM_Contact_BAO_QUERY::MODE_CONTACTS) {
$query->_useDistinct = TRUE;
}
$query->_params[$id][3];
self::whereClauseSingle($query->_params[$id], $query);
}
}
}
/**
* Where clause for a single field.
*
* @param array $values
* @param CRM_Contact_BAO_Query $query
*/
public static function whereClauseSingle(&$values, &$query) {
list($name, $op, $value, $grouping) = $values;
$fields = CRM_Activity_BAO_Activity::exportableFields();
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
if ($query->_mode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
$query->_skipDeleteClause = TRUE;
}
switch ($name) {
case 'activity_type_id':
case 'activity_status_id':
case 'activity_engagement_level':
case 'activity_id':
case 'activity_campaign_id':
case 'activity_priority_id':
// We no longer expect "subject" as a specific criteria (as of CRM-19447),
// but we still use activity_subject in Activity.Get API
case 'activity_subject':
$qillName = $name;
if (in_array($name, array('activity_engagement_level', 'activity_id'))) {
$name = $qillName = str_replace('activity_', '', $name);
}
if (in_array($name, array('activity_status_id', 'activity_subject', 'activity_priority_id'))) {
$name = str_replace('activity_', '', $name);
$qillName = str_replace('_id', '', $qillName);
}
if ($name == 'activity_campaign_id') {
$name = 'campaign_id';
}
$dataType = !empty($fields[$qillName]['type']) ? CRM_Utils_Type::typeToString($fields[$qillName]['type']) : 'String';
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_activity.$name", $op, $value, $dataType);
list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Activity_DAO_Activity', $name, $value, $op);
$query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $fields[$qillName]['title'], 2 => $op, 3 => $value));
break;
case 'activity_text':
self::whereClauseSingleActivityText($values, $query);
break;
case 'activity_type':
case 'activity_status':
case 'activity_priority':
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("$name.label", $op, $value, 'String');
list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Activity_DAO_Activity', $name, $value, $op);
$query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $fields[$name]['title'], 2 => $op, 3 => $value));
$query->_tables[$name] = $query->_whereTables[$name] = 1;
break;
case 'activity_survey_id':
if (!$value) {
break;
}
$value = CRM_Utils_Type::escape($value, 'Integer');
$query->_where[$grouping][] = " civicrm_activity.source_record_id = $value";
$query->_qill[$grouping][] = ts('Survey') . ' - ' . CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $value, 'title');
break;
case 'activity_role':
CRM_Contact_BAO_Query::$_activityRole = $values[2];
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
$targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
if ($values[2]) {
$query->_tables['civicrm_activity_contact'] = $query->_whereTables['civicrm_activity_contact'] = 1;
if ($values[2] == 1) {
$query->_where[$grouping][] = " civicrm_activity_contact.record_type_id = $sourceID";
$query->_qill[$grouping][] = ts('Activity created by');
}
elseif ($values[2] == 2) {
$query->_where[$grouping][] = " civicrm_activity_contact.record_type_id = $assigneeID";
$query->_qill[$grouping][] = ts('Activity assigned to');
}
elseif ($values[2] == 3) {
$query->_where[$grouping][] = " civicrm_activity_contact.record_type_id = $targetID";
$query->_qill[$grouping][] = ts('Activity targeted to');
}
}
break;
case 'activity_test':
// We don't want to include all tests for sql OR CRM-7827
if (!$value || $query->getOperator() != 'OR') {
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_activity.is_test", $op, $value, "Boolean");
if ($value) {
$query->_qill[$grouping][] = ts('Activity is a Test');
}
}
break;
case 'activity_date':
case 'activity_date_low':
case 'activity_date_high':
$query->dateQueryBuilder($values,
'civicrm_activity', 'activity_date', 'activity_date_time', ts('Activity Date')
);
break;
case 'activity_taglist':
$taglist = $value;
$value = array();
foreach ($taglist as $val) {
if ($val) {
$val = explode(',', $val);
foreach ($val as $tId) {
if (is_numeric($tId)) {
$value[$tId] = 1;
}
}
}
}
case 'activity_tags':
$value = array_keys($value);
$activityTags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
$names = array();
if (is_array($value)) {
foreach ($value as $k => $v) {
$names[] = $activityTags[$v];
}
}
$query->_where[$grouping][] = "civicrm_activity_tag.tag_id IN (" . implode(",", $value) . ")";
$query->_qill[$grouping][] = ts('Activity Tag %1', array(1 => $op)) . ' ' . implode(' ' . ts('OR') . ' ', $names);
$query->_tables['civicrm_activity_tag'] = $query->_whereTables['civicrm_activity_tag'] = 1;
break;
case 'activity_result':
if (is_array($value)) {
$safe = NULL;
while (list(, $k) = each($value)) {
$safe[] = "'" . CRM_Utils_Type::escape($k, 'String') . "'";
}
$query->_where[$grouping][] = "civicrm_activity.result IN (" . implode(',', $safe) . ")";
$query->_qill[$grouping][] = ts("Activity Result - %1", array(1 => implode(' or ', $safe)));
}
break;
case 'parent_id':
if ($value == 1) {
$query->_where[$grouping][] = "parent_id.parent_id IS NOT NULL";
$query->_qill[$grouping][] = ts('Activities which have Followup Activities');
}
elseif ($value == 2) {
$query->_where[$grouping][] = "parent_id.parent_id IS NULL";
$query->_qill[$grouping][] = ts('Activities without Followup Activities');
}
break;
case 'followup_parent_id':
if ($value == 1) {
$query->_where[$grouping][] = "civicrm_activity.parent_id IS NOT NULL";
$query->_qill[$grouping][] = ts('Activities which are Followup Activities');
}
elseif ($value == 2) {
$query->_where[$grouping][] = "civicrm_activity.parent_id IS NULL";
$query->_qill[$grouping][] = ts('Activities which are not Followup Activities');
}
break;
}
}
/**
* @param string $name
* @param $mode
* @param $side
*
* @return null|string
*/
public static function from($name, $mode, $side) {
$from = NULL;
switch ($name) {
case 'civicrm_activity':
//CRM-7480 we are going to civicrm_activity table either
//from civicrm_activity_target or civicrm_activity_assignment.
//as component specific activities does not have entry in
//activity target table so lets consider civicrm_activity_assignment.
$from .= " $side JOIN civicrm_activity_contact
ON ( civicrm_activity_contact.contact_id = contact_a.id ) ";
$from .= " $side JOIN civicrm_activity
ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )";
// Do not show deleted contact's activity
$from .= " INNER JOIN civicrm_contact
ON ( civicrm_activity_contact.contact_id = civicrm_contact.id and civicrm_contact.is_deleted != 1 )";
break;
case 'activity_status':
$from .= " $side JOIN civicrm_option_group option_group_activity_status ON (option_group_activity_status.name = 'activity_status')";
$from .= " $side JOIN civicrm_option_value activity_status ON (civicrm_activity.status_id = activity_status.value
AND option_group_activity_status.id = activity_status.option_group_id ) ";
break;
case 'activity_type':
$from .= " $side JOIN civicrm_option_group option_group_activity_type ON (option_group_activity_type.name = 'activity_type')";
$from .= " $side JOIN civicrm_option_value activity_type ON (civicrm_activity.activity_type_id = activity_type.value
AND option_group_activity_type.id = activity_type.option_group_id ) ";
break;
case 'activity_priority':
$from .= " $side JOIN civicrm_option_group option_group_activity_priority ON (option_group_activity_priority.name = 'priority')";
$from .= " $side JOIN civicrm_option_value activity_priority ON (civicrm_activity.priority_id = activity_priority.value
AND option_group_activity_priority.id = activity_priority.option_group_id ) ";
break;
case 'civicrm_activity_tag':
$from .= " $side JOIN civicrm_entity_tag as civicrm_activity_tag ON ( civicrm_activity_tag.entity_table = 'civicrm_activity' AND civicrm_activity_tag.entity_id = civicrm_activity.id ) ";
break;
case 'source_contact':
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
$from = "
LEFT JOIN civicrm_activity_contact ac
ON ( ac.activity_id = civicrm_activity_contact.activity_id AND ac.record_type_id = {$sourceID})
INNER JOIN civicrm_contact source_contact ON (ac.contact_id = source_contact.id)";
break;
case 'parent_id':
$from = "$side JOIN civicrm_activity AS parent_id ON civicrm_activity.id = parent_id.parent_id";
break;
}
return $from;
}
/**
* Add all the elements shared between case activity search and advanced search.
*
* @param CRM_Core_Form $form
*/
public static function buildSearchForm(&$form) {
$form->addSelect('activity_type_id',
array('entity' => 'activity', 'label' => ts('Activity Type(s)'), 'multiple' => 'multiple', 'option_url' => NULL, 'placeholder' => ts('- any -'))
);
CRM_Core_Form_Date::buildDateRange($form, 'activity_date', 1, '_low', '_high', ts('From'), FALSE, FALSE);
$form->addElement('hidden', 'activity_date_range_error');
$form->addFormRule(array('CRM_Activity_BAO_Query', 'formRule'), $form);
$followUpActivity = array(
1 => ts('Yes'),
2 => ts('No'),
);
$form->addRadio('parent_id', NULL, $followUpActivity, array('allowClear' => TRUE));
$form->addRadio('followup_parent_id', NULL, $followUpActivity, array('allowClear' => TRUE));
$activityRoles = array(
3 => ts('With'),
2 => ts('Assigned to'),
1 => ts('Added by'),
);
$form->addRadio('activity_role', NULL, $activityRoles, array('allowClear' => TRUE));
$form->setDefaults(array('activity_role' => 3));
$activityStatus = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'status_id', array('flip' => 1, 'labelColumn' => 'name'));
$form->addSelect('status_id',
array('entity' => 'activity', 'multiple' => 'multiple', 'option_url' => NULL, 'placeholder' => ts('- any -'))
);
$ssID = $form->get('ssID');
$status = array($activityStatus['Completed'], $activityStatus['Scheduled']);
//If status is saved in smart group.
if (!empty($ssID) && !empty($form->_formValues['activity_status_id'])) {
$status = $form->_formValues['activity_status_id'];
}
$form->setDefaults(array('status_id' => $status));
$form->addElement('text', 'activity_text', ts('Activity Text'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name'));
$form->addRadio('activity_option', '', CRM_Core_SelectValues::activityTextOptions());
$form->setDefaults(array('activity_option' => 'both'));
$priority = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id');
$form->addSelect('priority_id',
array('entity' => 'activity', 'label' => ts('Priority'), 'multiple' => 'multiple', 'option_url' => NULL, 'placeholder' => ts('- any -'))
);
$form->addYesNo('activity_test', ts('Activity is a Test?'));
$activity_tags = CRM_Core_BAO_Tag::getTags('civicrm_activity');
if ($activity_tags) {
foreach ($activity_tags as $tagID => $tagName) {
$form->_tagElement = &$form->addElement('checkbox', "activity_tags[$tagID]",
NULL, $tagName
);
}
}
$parentNames = CRM_Core_BAO_Tag::getTagSet('civicrm_activity');
CRM_Core_Form_Tag::buildQuickForm($form, $parentNames, 'civicrm_activity', NULL, TRUE, TRUE);
$surveys = CRM_Campaign_BAO_Survey::getSurveys(TRUE, FALSE, FALSE, TRUE);
if ($surveys) {
$form->add('select', 'activity_survey_id', ts('Survey / Petition'),
array('' => ts('- none -')) + $surveys, FALSE,
array('class' => 'crm-select2')
);
}
CRM_Core_BAO_Query::addCustomFormFields($form, array('Activity'));
CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'activity_campaign_id');
// Add engagement level CRM-7775.
$buildEngagementLevel = FALSE;
$buildSurveyResult = FALSE;
if (CRM_Campaign_BAO_Campaign::isCampaignEnable() &&
CRM_Campaign_BAO_Campaign::accessCampaign()
) {
$buildEngagementLevel = TRUE;
$form->addSelect('activity_engagement_level', array('entity' => 'activity', 'context' => 'search'));
// Add survey result field.
$optionGroups = CRM_Campaign_BAO_Survey::getResultSets('name');
$resultOptions = array();
foreach ($optionGroups as $gid => $name) {
if ($name) {
$value = CRM_Core_OptionGroup::values($name);
if (!empty($value)) {
while (list($k, $v) = each($value)) {
$resultOptions[$v] = $v;
}
}
}
}
// If no survey result options have been created, don't build
// the field to avoid clutter.
if (count($resultOptions) > 0) {
$buildSurveyResult = TRUE;
asort($resultOptions);
$form->add('select', 'activity_result', ts("Survey Result"),
$resultOptions, FALSE,
array('id' => 'activity_result', 'multiple' => 'multiple', 'class' => 'crm-select2')
);
}
}
$form->assign('buildEngagementLevel', $buildEngagementLevel);
$form->assign('buildSurveyResult', $buildSurveyResult);
$form->setDefaults(array('activity_test' => 0));
}
/**
* @param $mode
* @param bool $includeCustomFields
*
* @return array|null
*/
public static function defaultReturnProperties($mode, $includeCustomFields = TRUE) {
$properties = NULL;
if ($mode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
$properties = array(
'activity_id' => 1,
'contact_type' => 1,
'contact_sub_type' => 1,
'sort_name' => 1,
'display_name' => 1,
'activity_type' => 1,
'activity_type_id' => 1,
'activity_subject' => 1,
'activity_date_time' => 1,
'activity_duration' => 1,
'activity_location' => 1,
'activity_details' => 1,
'activity_status' => 1,
'activity_priority' => 1,
'source_contact' => 1,
'source_record_id' => 1,
'activity_is_test' => 1,
'activity_campaign_id' => 1,
'result' => 1,
'activity_engagement_level' => 1,
'parent_id' => 1,
);
if ($includeCustomFields) {
// also get all the custom activity properties
$fields = CRM_Core_BAO_CustomField::getFieldsForImport('Activity');
if (!empty($fields)) {
foreach ($fields as $name => $dontCare) {
$properties[$name] = 1;
}
}
}
}
return $properties;
}
/**
* Get the list of fields required to populate the selector.
*
* The default return properties array returns far too many fields for 'everyday use. Every field you add to this array
* kills a small kitten so add carefully.
*/
public static function selectorReturnProperties() {
$properties = array(
'activity_id' => 1,
'contact_type' => 1,
'contact_sub_type' => 1,
'sort_name' => 1,
'display_name' => 1,
'activity_type_id' => 1,
'activity_subject' => 1,
'activity_date_time' => 1,
'activity_status_id' => 1,
'source_contact' => 1,
'source_record_id' => 1,
'activity_is_test' => 1,
'activity_campaign_id' => 1,
'activity_engagement_level' => 1,
);
return $properties;
}
/**
* Custom form rules.
*
* @param array $fields
* @param array $files
* @param CRM_Core_Form $form
*
* @return bool|array
*/
public static function formRule($fields, $files, $form) {
$errors = array();
if (empty($fields['activity_date_low']) || empty($fields['activity_date_high'])) {
return TRUE;
}
CRM_Utils_Rule::validDateRange($fields, 'activity_date', $errors, ts('Activity Date'));
return empty($errors) ? TRUE : $errors;
}
/**
* Where/qill clause for notes
*
* @param array $values
*/
public static function whereClauseSingleActivityText(&$values, &$query) {
list($name, $op, $value, $grouping, $wildcard) = $values;
$activityOptionValues = $query->getWhereValues('activity_option', $grouping);
$activityOption = CRM_Utils_Array::value(2, $activityOptionValues, 6);
$query->_useDistinct = TRUE;
$label = ts('Activity Text (%1)', array(1 => CRM_Utils_Array::value($activityOption, CRM_Core_SelectValues::activityTextOptions())));
$clauses = array();
if ($activityOption % 2 == 0) {
$clauses[] = $query->buildClause('civicrm_activity.details', $op, $value, 'String');
}
if ($activityOption % 3 == 0) {
$clauses[] = $query->buildClause('civicrm_activity.subject', $op, $value, 'String');
}
$query->_where[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
list($qillOp, $qillVal) = $query->buildQillForFieldValue(NULL, $name, $value, $op);
$query->_qill[$grouping][] = ts("%1 %2 '%3'", array(1 => $label, 2 => $qillOp, 3 => $qillVal));
}
}

View file

@ -0,0 +1,76 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class is used by the Search functionality.
*
* - the search controller is used for building/processing multiform
* searches.
*
* Typically the first form will display the search criteria and it's results
*
* The second form is used to process search results with the associated actions
*
*/
class CRM_Activity_Controller_Search extends CRM_Core_Controller {
/**
* Class constructor.
*
* @param null $title
* @param bool $modal
* @param int|mixed|null $action
*/
public function __construct($title = NULL, $modal = TRUE, $action = CRM_Core_Action::NONE) {
parent::__construct($title, $modal);
$this->_stateMachine = new CRM_Activity_StateMachine_Search($this, $action);
// Create and instantiate the pages.
$this->addPages($this->_stateMachine, $action);
// Add all the actions.
$this->addActions();
}
/**
* Getter for selectorName.
*
* @return mixed
*/
public function selectorName() {
return $this->get('selectorName');
}
}

View file

@ -0,0 +1,808 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Activity/Activity.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:dfa63754ef6ea1a9c7148e735dd6ff8a)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Activity_DAO_Activity constructor.
*/
class CRM_Activity_DAO_Activity extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_activity';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
* Unique Other Activity ID
*
* @var int unsigned
*/
public $id;
/**
* Artificial FK to original transaction (e.g. contribution) IF it is not an Activity. Table can be figured out through activity_type_id, and further through component registry.
*
* @var int unsigned
*/
public $source_record_id;
/**
* FK to civicrm_option_value.id, that has to be valid, registered activity type.
*
* @var int unsigned
*/
public $activity_type_id;
/**
* The subject/purpose/short description of the activity.
*
* @var string
*/
public $subject;
/**
* Date and time this activity is scheduled to occur. Formerly named scheduled_date_time.
*
* @var datetime
*/
public $activity_date_time;
/**
* Planned or actual duration of activity expressed in minutes. Conglomerate of former duration_hours and duration_minutes.
*
* @var int unsigned
*/
public $duration;
/**
* Location of the activity (optional, open text).
*
* @var string
*/
public $location;
/**
* Phone ID of the number called (optional - used if an existing phone number is selected).
*
* @var int unsigned
*/
public $phone_id;
/**
* Phone number in case the number does not exist in the civicrm_phone table.
*
* @var string
*/
public $phone_number;
/**
* Details about the activity (agenda, notes, etc).
*
* @var longtext
*/
public $details;
/**
* ID of the status this activity is currently in. Foreign key to civicrm_option_value.
*
* @var int unsigned
*/
public $status_id;
/**
* ID of the priority given to this activity. Foreign key to civicrm_option_value.
*
* @var int unsigned
*/
public $priority_id;
/**
* Parent meeting ID (if this is a follow-up item). This is not currently implemented
*
* @var int unsigned
*/
public $parent_id;
/**
*
* @var boolean
*/
public $is_test;
/**
* Activity Medium, Implicit FK to civicrm_option_value where option_group = encounter_medium.
*
* @var int unsigned
*/
public $medium_id;
/**
*
* @var boolean
*/
public $is_auto;
/**
* FK to Relationship ID
*
* @var int unsigned
*/
public $relationship_id;
/**
*
* @var boolean
*/
public $is_current_revision;
/**
* Activity ID of the first activity record in versioning chain.
*
* @var int unsigned
*/
public $original_id;
/**
* Currently being used to store result id for survey activity, FK to option value.
*
* @var string
*/
public $result;
/**
*
* @var boolean
*/
public $is_deleted;
/**
* The campaign for which this activity has been triggered.
*
* @var int unsigned
*/
public $campaign_id;
/**
* Assign a specific level of engagement to this activity. Used for tracking constituents in ladder of engagement.
*
* @var int unsigned
*/
public $engagement_level;
/**
*
* @var int
*/
public $weight;
/**
* Activity marked as favorite.
*
* @var boolean
*/
public $is_star;
/**
* When was the activity was created.
*
* @var timestamp
*/
public $created_date;
/**
* When was the activity (or closely related entity) was created or modified or deleted.
*
* @var timestamp
*/
public $modified_date;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_activity';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'phone_id', 'civicrm_phone', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'parent_id', 'civicrm_activity', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'relationship_id', 'civicrm_relationship', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'original_id', 'civicrm_activity', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'campaign_id', 'civicrm_campaign', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'activity_id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Activity ID') ,
'description' => 'Unique Other Activity ID',
'required' => true,
'import' => true,
'where' => 'civicrm_activity.id',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
) ,
'source_record_id' => array(
'name' => 'source_record_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Source Record') ,
'description' => 'Artificial FK to original transaction (e.g. contribution) IF it is not an Activity. Table can be figured out through activity_type_id, and further through component registry.',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
) ,
'activity_type_id' => array(
'name' => 'activity_type_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Activity Type ID') ,
'description' => 'FK to civicrm_option_value.id, that has to be valid, registered activity type.',
'required' => true,
'import' => true,
'where' => 'civicrm_activity.activity_type_id',
'headerPattern' => '/(activity.)?type(.id$)/i',
'dataPattern' => '',
'export' => true,
'default' => '1',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'optionGroupName' => 'activity_type',
'optionEditPath' => 'civicrm/admin/options/activity_type',
)
) ,
'activity_subject' => array(
'name' => 'subject',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Subject') ,
'description' => 'The subject/purpose/short description of the activity.',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'import' => true,
'where' => 'civicrm_activity.subject',
'headerPattern' => '/(activity.)?subject/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'activity_date_time' => array(
'name' => 'activity_date_time',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Activity Date') ,
'description' => 'Date and time this activity is scheduled to occur. Formerly named scheduled_date_time.',
'import' => true,
'where' => 'civicrm_activity.activity_date_time',
'headerPattern' => '/(activity.)?date(.time$)?/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Select Date',
'formatType' => 'activityDateTime',
) ,
) ,
'activity_duration' => array(
'name' => 'duration',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Duration') ,
'description' => 'Planned or actual duration of activity expressed in minutes. Conglomerate of former duration_hours and duration_minutes.',
'import' => true,
'where' => 'civicrm_activity.duration',
'headerPattern' => '/(activity.)?duration(s)?$/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'activity_location' => array(
'name' => 'location',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Location') ,
'description' => 'Location of the activity (optional, open text).',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'import' => true,
'where' => 'civicrm_activity.location',
'headerPattern' => '/(activity.)?location$/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'phone_id' => array(
'name' => 'phone_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Phone (called) ID') ,
'description' => 'Phone ID of the number called (optional - used if an existing phone number is selected).',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Phone',
'html' => array(
'type' => 'EntityRef',
) ,
) ,
'phone_number' => array(
'name' => 'phone_number',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Phone (called) Number') ,
'description' => 'Phone number in case the number does not exist in the civicrm_phone table.',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'activity_details' => array(
'name' => 'details',
'type' => CRM_Utils_Type::T_LONGTEXT,
'title' => ts('Details') ,
'description' => 'Details about the activity (agenda, notes, etc).',
'import' => true,
'where' => 'civicrm_activity.details',
'headerPattern' => '/(activity.)?detail(s)?$/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'RichTextEditor',
) ,
) ,
'activity_status_id' => array(
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Activity Status') ,
'description' => 'ID of the status this activity is currently in. Foreign key to civicrm_option_value.',
'import' => true,
'where' => 'civicrm_activity.status_id',
'headerPattern' => '/(activity.)?status(.label$)?/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'optionGroupName' => 'activity_status',
'optionEditPath' => 'civicrm/admin/options/activity_status',
)
) ,
'priority_id' => array(
'name' => 'priority_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Priority') ,
'description' => 'ID of the priority given to this activity. Foreign key to civicrm_option_value.',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'optionGroupName' => 'priority',
'optionEditPath' => 'civicrm/admin/options/priority',
)
) ,
'parent_id' => array(
'name' => 'parent_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Parent Activity Id') ,
'description' => 'Parent meeting ID (if this is a follow-up item). This is not currently implemented',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'FKClassName' => 'CRM_Activity_DAO_Activity',
) ,
'activity_is_test' => array(
'name' => 'is_test',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Test') ,
'import' => true,
'where' => 'civicrm_activity.is_test',
'headerPattern' => '/(is.)?test(.activity)?/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
) ,
'activity_medium_id' => array(
'name' => 'medium_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Activity Medium') ,
'description' => 'Activity Medium, Implicit FK to civicrm_option_value where option_group = encounter_medium.',
'default' => 'NULL',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'optionGroupName' => 'encounter_medium',
'optionEditPath' => 'civicrm/admin/options/encounter_medium',
)
) ,
'is_auto' => array(
'name' => 'is_auto',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Auto') ,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
) ,
'relationship_id' => array(
'name' => 'relationship_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Relationship Id') ,
'description' => 'FK to Relationship ID',
'default' => 'NULL',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Relationship',
) ,
'is_current_revision' => array(
'name' => 'is_current_revision',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is this activity a current revision in versioning chain?') ,
'import' => true,
'where' => 'civicrm_activity.is_current_revision',
'headerPattern' => '/(is.)?(current.)?(revision|version(ing)?)/i',
'dataPattern' => '',
'export' => true,
'default' => '1',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'CheckBox',
) ,
) ,
'original_id' => array(
'name' => 'original_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Original Activity ID ') ,
'description' => 'Activity ID of the first activity record in versioning chain.',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'FKClassName' => 'CRM_Activity_DAO_Activity',
) ,
'activity_result' => array(
'name' => 'result',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Result') ,
'description' => 'Currently being used to store result id for survey activity, FK to option value.',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'activity_is_deleted' => array(
'name' => 'is_deleted',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Activity is in the Trash') ,
'import' => true,
'where' => 'civicrm_activity.is_deleted',
'headerPattern' => '/(activity.)?(trash|deleted)/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'activity_campaign_id' => array(
'name' => 'campaign_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Campaign') ,
'description' => 'The campaign for which this activity has been triggered.',
'import' => true,
'where' => 'civicrm_activity.campaign_id',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'FKClassName' => 'CRM_Campaign_DAO_Campaign',
'html' => array(
'type' => 'CheckBox',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_campaign',
'keyColumn' => 'id',
'labelColumn' => 'title',
)
) ,
'activity_engagement_level' => array(
'name' => 'engagement_level',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Engagement Index') ,
'description' => 'Assign a specific level of engagement to this activity. Used for tracking constituents in ladder of engagement.',
'import' => true,
'where' => 'civicrm_activity.engagement_level',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'optionGroupName' => 'engagement_index',
'optionEditPath' => 'civicrm/admin/options/engagement_index',
)
) ,
'weight' => array(
'name' => 'weight',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Order') ,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'is_star' => array(
'name' => 'is_star',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is Starred') ,
'description' => 'Activity marked as favorite.',
'import' => true,
'where' => 'civicrm_activity.is_star',
'headerPattern' => '/(activity.)?(star|favorite)/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
) ,
'activity_created_date' => array(
'name' => 'created_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
'title' => ts('Created Date') ,
'description' => 'When was the activity was created.',
'required' => false,
'export' => true,
'where' => 'civicrm_activity.created_date',
'headerPattern' => '',
'dataPattern' => '',
'default' => 'NULL',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
) ,
'activity_modified_date' => array(
'name' => 'modified_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
'title' => ts('Modified Date') ,
'description' => 'When was the activity (or closely related entity) was created or modified or deleted.',
'required' => false,
'export' => true,
'where' => 'civicrm_activity.modified_date',
'headerPattern' => '',
'dataPattern' => '',
'default' => 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'activity', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'activity', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'UI_source_record_id' => array(
'name' => 'UI_source_record_id',
'field' => array(
0 => 'source_record_id',
) ,
'localizable' => false,
'sig' => 'civicrm_activity::0::source_record_id',
) ,
'UI_activity_type_id' => array(
'name' => 'UI_activity_type_id',
'field' => array(
0 => 'activity_type_id',
) ,
'localizable' => false,
'sig' => 'civicrm_activity::0::activity_type_id',
) ,
'index_activity_date_time' => array(
'name' => 'index_activity_date_time',
'field' => array(
0 => 'activity_date_time',
) ,
'localizable' => false,
'sig' => 'civicrm_activity::0::activity_date_time',
) ,
'index_status_id' => array(
'name' => 'index_status_id',
'field' => array(
0 => 'status_id',
) ,
'localizable' => false,
'sig' => 'civicrm_activity::0::status_id',
) ,
'index_medium_id' => array(
'name' => 'index_medium_id',
'field' => array(
0 => 'medium_id',
) ,
'localizable' => false,
'sig' => 'civicrm_activity::0::medium_id',
) ,
'index_is_current_revision' => array(
'name' => 'index_is_current_revision',
'field' => array(
0 => 'is_current_revision',
) ,
'localizable' => false,
'sig' => 'civicrm_activity::0::is_current_revision',
) ,
'index_is_deleted' => array(
'name' => 'index_is_deleted',
'field' => array(
0 => 'is_deleted',
) ,
'localizable' => false,
'sig' => 'civicrm_activity::0::is_deleted',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,247 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Activity/ActivityContact.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:7a410e20f48318deeb83f3dd1900983a)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Activity_DAO_ActivityContact constructor.
*/
class CRM_Activity_DAO_ActivityContact extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_activity_contact';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
* Activity contact id
*
* @var int unsigned
*/
public $id;
/**
* Foreign key to the activity for this record.
*
* @var int unsigned
*/
public $activity_id;
/**
* Foreign key to the contact for this record.
*
* @var int unsigned
*/
public $contact_id;
/**
* Nature of this contact's role in the activity: 1 assignee, 2 creator, 3 focus or target.
*
* @var int unsigned
*/
public $record_type_id;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_activity_contact';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'activity_id', 'civicrm_activity', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Activity Contact ID') ,
'description' => 'Activity contact id',
'required' => true,
'table_name' => 'civicrm_activity_contact',
'entity' => 'ActivityContact',
'bao' => 'CRM_Activity_BAO_ActivityContact',
'localizable' => 0,
) ,
'activity_id' => array(
'name' => 'activity_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Activity ID') ,
'description' => 'Foreign key to the activity for this record.',
'required' => true,
'table_name' => 'civicrm_activity_contact',
'entity' => 'ActivityContact',
'bao' => 'CRM_Activity_BAO_ActivityContact',
'localizable' => 0,
'FKClassName' => 'CRM_Activity_DAO_Activity',
) ,
'contact_id' => array(
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Contact ID (match to contact)') ,
'description' => 'Foreign key to the contact for this record.',
'required' => true,
'import' => true,
'where' => 'civicrm_activity_contact.contact_id',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity_contact',
'entity' => 'ActivityContact',
'bao' => 'CRM_Activity_BAO_ActivityContact',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
) ,
'record_type_id' => array(
'name' => 'record_type_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Record Type ID') ,
'description' => 'Nature of this contact\'s role in the activity: 1 assignee, 2 creator, 3 focus or target.',
'table_name' => 'civicrm_activity_contact',
'entity' => 'ActivityContact',
'bao' => 'CRM_Activity_BAO_ActivityContact',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'optionGroupName' => 'activity_contacts',
'optionEditPath' => 'civicrm/admin/options/activity_contacts',
)
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'activity_contact', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'activity_contact', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'UI_activity_contact' => array(
'name' => 'UI_activity_contact',
'field' => array(
0 => 'contact_id',
1 => 'activity_id',
2 => 'record_type_id',
) ,
'localizable' => false,
'unique' => true,
'sig' => 'civicrm_activity_contact::1::contact_id::activity_id::record_type_id',
) ,
'index_record_type' => array(
'name' => 'index_record_type',
'field' => array(
0 => 'activity_id',
1 => 'record_type_id',
) ,
'localizable' => false,
'sig' => 'civicrm_activity_contact::0::activity_id::record_type_id',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,82 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class generates form components for Activity Filter.
*/
class CRM_Activity_Form_ActivityFilter extends CRM_Core_Form {
public function buildQuickForm() {
// add activity search filter
$activityOptions = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE);
asort($activityOptions);
$this->add('select', 'activity_type_filter_id', ts('Include'), array('' => ts('- all activity type(s) -')) + $activityOptions);
$this->add('select', 'activity_type_exclude_filter_id', ts('Exclude'), array('' => ts('- select activity type -')) + $activityOptions);
CRM_Core_Form_Date::buildDateRange(
$this, 'activity_date', 1,
'_low', '_high', ts('From:'),
FALSE, array(), 'searchDate',
FALSE, array('class' => 'crm-select2 medium')
);
$this->addSelect('status_id',
array('entity' => 'activity', 'multiple' => 'multiple', 'option_url' => NULL, 'placeholder' => ts('- any -'))
);
$this->assign('suppressForm', TRUE);
}
/**
* This virtual function is used to set the default values of
* various form elements
*
* access public
*
* @return array
* reference to the array of default values
*/
public function setDefaultValues() {
// CRM-11761 retrieve user's activity filter preferences
$defaults = array();
if (Civi::settings()->get('preserve_activity_tab_filter') && ($userID = CRM_Core_Session::getLoggedInContactID())) {
$defaults = Civi::service('settings_manager')
->getBagByContact(NULL, $userID)
->get('activity_tab_filter');
}
// set Activity status 'Scheduled' by default only for dashlet
elseif (strstr(CRM_Utils_Array::value('q', $_GET), 'dashlet')) {
$defaults['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Scheduled');
}
return $defaults;
}
}

View file

@ -0,0 +1,107 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class generates form components for Activity Links.
*/
class CRM_Activity_Form_ActivityLinks extends CRM_Core_Form {
public function buildQuickForm() {
self::commonBuildQuickForm($this);
}
/**
* @param $self
*/
public static function commonBuildQuickForm($self) {
$contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $self);
if (!$contactId) {
$contactId = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject, FALSE, NULL, $_REQUEST);
}
$urlParams = "action=add&reset=1&cid={$contactId}&selectedChild=activity&atype=";
$allTypes = CRM_Utils_Array::value('values', civicrm_api3('OptionValue', 'get', array(
'option_group_id' => 'activity_type',
'is_active' => 1,
'options' => array('limit' => 0, 'sort' => 'weight'),
)));
$activityTypes = array();
foreach ($allTypes as $act) {
$url = 'civicrm/activity/add';
if ($act['name'] == 'Email') {
if (!CRM_Utils_Mail::validOutBoundMail() || !$contactId) {
continue;
}
list($name, $email, $doNotEmail, $onHold, $isDeceased) = CRM_Contact_BAO_Contact::getContactDetails($contactId);
if (!$doNotEmail && $email && !$isDeceased) {
$url = 'civicrm/activity/email/add';
$act['label'] = ts('Send an Email');
}
else {
continue;
}
}
elseif ($act['name'] == 'SMS') {
if (!$contactId || !CRM_SMS_BAO_Provider::activeProviderCount()) {
continue;
}
// Check for existence of a mobile phone and ! do not SMS privacy setting
$mobileTypeID = CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Phone', 'phone_type_id', 'Mobile');
list($name, $phone, $doNotSMS) = CRM_Contact_BAO_Contact_Location::getPhoneDetails($contactId, $mobileTypeID);
if (!$doNotSMS && $phone) {
$url = 'civicrm/activity/sms/add';
}
else {
continue;
}
}
elseif ($act['name'] == 'Print PDF Letter') {
$url = 'civicrm/activity/pdf/add';
}
elseif (!empty($act['filter']) || (!empty($act['component_id']) && $act['component_id'] != '1')) {
continue;
}
$act['url'] = CRM_Utils_System::url($url,
"{$urlParams}{$act['value']}", FALSE, NULL, FALSE
);
$act += array('icon' => 'fa-plus-square-o');
$activityTypes[$act['value']] = $act;
}
$self->assign('activityTypes', $activityTypes);
$self->assign('suppressForm', TRUE);
}
}

View file

@ -0,0 +1,128 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class handle activity view mode.
*/
class CRM_Activity_Form_ActivityView extends CRM_Core_Form {
/**
* Set variables up before form is built.
*/
public function preProcess() {
// Get the activity values.
$activityId = CRM_Utils_Request::retrieve('id', 'Positive', $this);
$context = CRM_Utils_Request::retrieve('context', 'String', $this);
$cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
// Check for required permissions, CRM-6264.
if ($activityId &&
!CRM_Activity_BAO_Activity::checkPermission($activityId, CRM_Core_Action::VIEW)
) {
CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
}
$session = CRM_Core_Session::singleton();
if (!in_array($context, array(
'home',
'dashlet',
'dashletFullscreen',
))
) {
$url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$cid}&selectedChild=activity");
}
else {
$url = CRM_Utils_System::url('civicrm/dashboard', 'reset=1');
}
$session->pushUserContext($url);
$defaults = array();
$params = array('id' => $activityId);
CRM_Activity_BAO_Activity::retrieve($params, $defaults);
// Set activity type name and description to template.
list($activityTypeName, $activityTypeDescription) = CRM_Core_BAO_OptionValue::getActivityTypeDetails($defaults['activity_type_id']);
$this->assign('activityTypeName', $activityTypeName);
$this->assign('activityTypeDescription', $activityTypeDescription);
if (!empty($defaults['mailingId'])) {
$this->_mailing_id = CRM_Utils_Array::value('source_record_id', $defaults);
$mailingReport = CRM_Mailing_BAO_Mailing::report($this->_mailing_id, TRUE);
CRM_Mailing_BAO_Mailing::getMailingContent($mailingReport, $this);
$this->assign('mailingReport', $mailingReport);
$full_open_report = CRM_Mailing_Event_BAO_Opened::getRows(
$this->_mailing_id, NULL, FALSE, NULL, NULL, NULL, $cid);
$this->assign('openreport', $full_open_report);
$click_thru_report = CRM_Mailing_Event_BAO_TrackableURLOpen::getRows($this->_mailing_id, NULL, FALSE, NULL, NULL, NULL, NULL, $cid);
$this->assign('clickreport', $click_thru_report);
}
foreach ($defaults as $key => $value) {
if (substr($key, -3) != '_id') {
$values[$key] = $value;
}
}
// Get the campaign.
if ($campaignId = CRM_Utils_Array::value('campaign_id', $defaults)) {
$campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
$values['campaign'] = $campaigns[$campaignId];
}
if ($engagementLevel = CRM_Utils_Array::value('engagement_level', $defaults)) {
$engagementLevels = CRM_Campaign_PseudoConstant::engagementLevel();
$values['engagement_level'] = CRM_Utils_Array::value($engagementLevel, $engagementLevels, $engagementLevel);
}
$values['attachment'] = CRM_Core_BAO_File::attachmentInfo('civicrm_activity', $activityId);
$this->assign('values', $values);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->addButtons(array(
array(
'type' => 'cancel',
'name' => ts('Done'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'isDefault' => TRUE,
),
)
);
}
}

View file

@ -0,0 +1,417 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This file is for activity search.
*/
class CRM_Activity_Form_Search extends CRM_Core_Form_Search {
/**
* The params that are sent to the query.
*
* @var array
*/
protected $_queryParams;
/**
* Are we restricting ourselves to a single contact.
*
* @var boolean
*/
protected $_single = FALSE;
/**
* Are we restricting ourselves to a single contact.
*
* @var boolean
*/
protected $_limit = NULL;
/**
* Prefix for the controller.
*/
protected $_prefix = "activity_";
/**
* The saved search ID retrieved from the GET vars.
*
* @var int
*/
protected $_ssID;
/**
* Processing needed for buildForm and later.
*/
public function preProcess() {
$this->set('searchFormName', 'Search');
// set the button names
$this->_searchButtonName = $this->getButtonName('refresh');
$this->_actionButtonName = $this->getButtonName('next', 'action');
$this->_done = FALSE;
$this->defaults = array();
// we allow the controller to set force/reset externally, useful when we are being
// driven by the wizard framework
$this->_reset = CRM_Utils_Request::retrieve('reset', 'Boolean');
$this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
$this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
$this->_context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'search');
$this->assign("context", $this->_context);
// get user submitted values
// get it from controller only if form has been submitted, else preProcess has set this
if (!empty($_POST) && !$this->controller->isModal()) {
$this->_formValues = $this->controller->exportValues($this->_name);
}
else {
$this->_formValues = $this->get('formValues');
if ($this->_force) {
// If we force the search then merge form values with url values
// and set submit values to form values.
$this->_formValues = array_merge((array) $this->_formValues, CRM_Utils_Request::exportValues());
$this->_submitValues = $this->_formValues;
}
}
if (empty($this->_formValues)) {
if (isset($this->_ssID)) {
$this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues($this->_ssID);
}
}
if ($this->_force) {
$this->postProcess();
$this->set('force', 0);
}
$sortID = NULL;
if ($this->get(CRM_Utils_Sort::SORT_ID)) {
$sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
$this->get(CRM_Utils_Sort::SORT_DIRECTION)
);
}
$this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues);
$selector = new CRM_Activity_Selector_Search($this->_queryParams,
$this->_action,
NULL,
$this->_single,
$this->_limit,
$this->_context
);
$prefix = NULL;
if ($this->_context == 'user') {
$prefix = $this->_prefix;
}
$this->assign("{$prefix}limit", $this->_limit);
$this->assign("{$prefix}single", $this->_single);
$controller = new CRM_Core_Selector_Controller($selector,
$this->get(CRM_Utils_Pager::PAGE_ID),
$sortID,
CRM_Core_Action::VIEW,
$this,
CRM_Core_Selector_Controller::TRANSFER,
$prefix
);
$controller->setEmbedded(TRUE);
$controller->moveFromSessionToTemplate();
$this->assign('summary', $this->get('summary'));
}
/**
* Build the form object.
*/
public function buildQuickForm() {
parent::buildQuickForm();
$this->addSortNameField();
CRM_Activity_BAO_Query::buildSearchForm($this);
$rows = $this->get('rows');
if (is_array($rows)) {
if (!$this->_single) {
$this->addRowSelectors($rows);
}
$permission = CRM_Core_Permission::getPermission();
$this->addTaskMenu(CRM_Activity_Task::permissionedTaskTitles($permission));
}
}
/**
* The post processing of the form gets done here.
*
* Key things done during post processing are
* - check for reset or next request. if present, skip post procesing.
* - now check if user requested running a saved search, if so, then
* the form values associated with the saved search are used for searching.
* - if user has done a submit with new values the regular post submissing is
* done.
*
* The processing consists of using a Selector / Controller framework for getting the
* search results.
*/
public function postProcess() {
if ($this->_done) {
return;
}
$this->_done = TRUE;
if (!empty($_POST)) {
$this->_formValues = $this->controller->exportValues($this->_name);
$specialParams = array(
'activity_type_id',
'status_id',
'priority_id',
'activity_text',
);
$changeNames = array(
'status_id' => 'activity_status_id',
'priority_id' => 'activity_priority_id',
);
CRM_Contact_BAO_Query::processSpecialFormValue($this->_formValues, $specialParams, $changeNames);
}
$this->fixFormValues();
if (isset($this->_ssID) && empty($_POST)) {
// if we are editing / running a saved search and the form has not been posted
$this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues($this->_ssID);
}
// We don't show test records in summaries or dashboards
if (empty($this->_formValues['activity_test']) && $this->_force) {
$this->_formValues["activity_test"] = 0;
}
CRM_Core_BAO_CustomValue::fixCustomFieldValue($this->_formValues);
$this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues);
$this->set('formValues', $this->_formValues);
$this->set('queryParams', $this->_queryParams);
$buttonName = $this->controller->getButtonName();
if ($buttonName == $this->_actionButtonName) {
// check actionName and if next, then do not repeat a search, since we are going to the next page
// hack, make sure we reset the task values
$stateMachine = $this->controller->getStateMachine();
$formName = $stateMachine->getTaskFormName();
$this->controller->resetPage($formName);
return;
}
$sortID = NULL;
if ($this->get(CRM_Utils_Sort::SORT_ID)) {
$sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
$this->get(CRM_Utils_Sort::SORT_DIRECTION)
);
}
$this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues);
$selector = new CRM_Activity_Selector_Search($this->_queryParams,
$this->_action,
NULL,
$this->_single,
$this->_limit,
$this->_context
);
$selector->setKey($this->controller->_key);
$prefix = NULL;
if ($this->_context == 'basic' || $this->_context == 'user') {
$prefix = $this->_prefix;
}
$controller = new CRM_Core_Selector_Controller($selector,
$this->get(CRM_Utils_Pager::PAGE_ID),
$sortID,
CRM_Core_Action::VIEW,
$this,
CRM_Core_Selector_Controller::SESSION,
$prefix
);
$controller->setEmbedded(TRUE);
$query = &$selector->getQuery();
if ($this->_context == 'user') {
$query->setSkipPermission(TRUE);
}
$controller->run();
}
public function fixFormValues() {
if (!$this->_force) {
return;
}
$status = CRM_Utils_Request::retrieve('status', 'String', $this);
if ($status) {
$this->_formValues['activity_status_id'] = $status;
$this->_defaults['activity_status_id'] = $status;
}
$survey = CRM_Utils_Request::retrieve('survey', 'Positive');
if ($survey) {
$this->_formValues['activity_survey_id'] = $this->_defaults['activity_survey_id'] = $survey;
$sid = CRM_Utils_Array::value('activity_survey_id', $this->_formValues);
$activity_type_id = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $sid, 'activity_type_id');
// since checkbox are replaced by multiple select option
$this->_formValues['activity_type_id'] = $activity_type_id;
$this->_defaults['activity_type_id'] = $activity_type_id;
}
$cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
if ($cid) {
$cid = CRM_Utils_Type::escape($cid, 'Integer');
if ($cid > 0) {
$this->_formValues['contact_id'] = $cid;
$activity_role = CRM_Utils_Request::retrieve('activity_role', 'Positive', $this);
if ($activity_role) {
$this->_formValues['activity_role'] = $activity_role;
}
else {
$this->_defaults['sort_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'sort_name');
}
// also assign individual mode to the template
$this->_single = TRUE;
}
}
// Added for membership search
$signupType = CRM_Utils_Request::retrieve('signupType', 'Positive');
if ($signupType) {
$this->_formValues['activity_role'] = 1;
$this->_defaults['activity_role'] = 1;
$activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
$renew = CRM_Utils_Array::key('Membership Renewal', $activityTypes);
$signup = CRM_Utils_Array::key('Membership Signup', $activityTypes);
switch ($signupType) {
case 3: // signups and renewals
$this->_formValues['activity_type_id'][$renew] = 1;
$this->_defaults['activity_type_id'][$renew] = 1;
case 1: // signups only
$this->_formValues['activity_type_id'][$signup] = 1;
$this->_defaults['activity_type_id'][$signup] = 1;
break;
case 2: // renewals only
$this->_formValues['activity_type_id'][$renew] = 1;
$this->_defaults['activity_type_id'][$renew] = 1;
break;
}
}
$dateLow = CRM_Utils_Request::retrieve('dateLow', 'String');
if ($dateLow) {
$dateLow = date('m/d/Y', strtotime($dateLow));
$this->_formValues['activity_date_relative'] = 0;
$this->_defaults['activity_date_relative'] = 0;
$this->_formValues['activity_date_low'] = $dateLow;
$this->_defaults['activity_date_low'] = $dateLow;
}
$dateHigh = CRM_Utils_Request::retrieve('dateHigh', 'String');
if ($dateHigh) {
// Activity date time assumes midnight at the beginning of the date
// This sets it to almost midnight at the end of the date
/* if ($dateHigh <= 99999999) {
$dateHigh = 1000000 * $dateHigh + 235959;
} */
$dateHigh = date('m/d/Y', strtotime($dateHigh));
$this->_formValues['activity_date_relative'] = 0;
$this->_defaults['activity_date_relative'] = 0;
$this->_formValues['activity_date_high'] = $dateHigh;
$this->_defaults['activity_date_high'] = $dateHigh;
}
// Enable search activity by custom value
$requestParams = CRM_Utils_Request::exportValues();
foreach (array_keys($requestParams) as $key) {
if (substr($key, 0, 7) != 'custom_') {
continue;
}
elseif (empty($requestParams[$key])) {
continue;
}
$customValue = CRM_Utils_Request::retrieve($key, 'String', $this);
if ($customValue) {
$this->_formValues[$key] = $customValue;
$this->_defaults[$key] = $customValue;
}
}
if (!empty($this->_defaults)) {
$this->setDefaults($this->_defaults);
}
}
/**
* @return null
*/
public function getFormValues() {
return NULL;
}
/**
* Return a descriptive name for the page, used in wizard header
*
* @return string
*/
public function getTitle() {
return ts('Find Activities');
}
}

View file

@ -0,0 +1,207 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Class for activity task actions.
*/
class CRM_Activity_Form_Task extends CRM_Core_Form {
/**
* The task being performed.
*
* @var int
*/
protected $_task;
/**
* The additional clause that we restrict the search with.
*
* @var string
*/
protected $_componentClause = NULL;
/**
* The array that holds all the component ids.
*
* @var array
*/
protected $_componentIds;
/**
* The array that holds all the contact ids.
*
* @var array
*/
public $_contactIds;
/**
* The array that holds all the member ids.
*
* @var array
*/
public $_activityHolderIds;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
self::preProcessCommon($this);
}
/**
* Common pre-process function.
*
* @param CRM_Core_Form $form
* @param bool $useTable
*/
public static function preProcessCommon(&$form, $useTable = FALSE) {
$form->_activityHolderIds = array();
$values = $form->controller->exportValues($form->get('searchFormName'));
$form->_task = $values['task'];
$activityTasks = CRM_Activity_Task::tasks();
$form->assign('taskName', $activityTasks[$form->_task]);
$ids = array();
if ($values['radio_ts'] == 'ts_sel') {
foreach ($values as $name => $value) {
if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
$ids[] = substr($name, CRM_Core_Form::CB_PREFIX_LEN);
}
}
}
else {
$queryParams = $form->get('queryParams');
$query = new CRM_Contact_BAO_Query($queryParams, NULL, NULL, FALSE, FALSE,
CRM_Contact_BAO_Query::MODE_ACTIVITY
);
$query->_distinctComponentClause = '( civicrm_activity.id )';
$query->_groupByComponentClause = " GROUP BY civicrm_activity.id ";
// CRM-12675
$activityClause = NULL;
$components = CRM_Core_Component::getNames();
$componentClause = array();
foreach ($components as $componentID => $componentName) {
if ($componentName != 'CiviCase' && !CRM_Core_Permission::check("access $componentName")) {
$componentClause[] = " (activity_type.component_id IS NULL OR activity_type.component_id <> {$componentID}) ";
}
}
if (!empty($componentClause)) {
$activityClause = implode(' AND ', $componentClause);
}
$result = $query->searchQuery(0, 0, NULL, FALSE, FALSE, FALSE, FALSE, FALSE, $activityClause);
while ($result->fetch()) {
if (!empty($result->activity_id)) {
$ids[] = $result->activity_id;
}
}
}
if (!empty($ids)) {
$form->_componentClause = ' civicrm_activity.id IN ( ' . implode(',', $ids) . ' ) ';
$form->assign('totalSelectedActivities', count($ids));
}
$form->_activityHolderIds = $form->_componentIds = $ids;
// Set the context for redirection for any task actions.
$qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $form);
$urlParams = 'force=1';
if (CRM_Utils_Rule::qfKey($qfKey)) {
$urlParams .= "&qfKey=$qfKey";
}
$session = CRM_Core_Session::singleton();
$searchFormName = strtolower($form->get('searchFormName'));
if ($searchFormName == 'search') {
$session->replaceUserContext(CRM_Utils_System::url('civicrm/activity/search', $urlParams));
}
else {
$session->replaceUserContext(CRM_Utils_System::url("civicrm/contact/search/$searchFormName",
$urlParams
));
}
}
/**
* Given the membership id, compute the contact id
* since it's used for things like send email.
*/
public function setContactIDs() {
$IDs = implode(',', $this->_activityHolderIds);
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
$query = "
SELECT contact_id
FROM civicrm_activity_contact
WHERE activity_id IN ( $IDs ) AND
record_type_id = {$sourceID}";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$contactIDs[] = $dao->contact_id;
}
$this->_contactIds = $contactIDs;
}
/**
* Simple shell that derived classes can call to add buttons to
* the form with a customized title for the main Submit
*
* @param string $title
* Title of the main button.
* @param string $nextType
* Button type for the form after processing.
* @param string $backType
* @param bool $submitOnce
*/
public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
$this->addButtons(array(
array(
'type' => $nextType,
'name' => $title,
'isDefault' => TRUE,
),
array(
'type' => $backType,
'name' => ts('Cancel'),
),
));
}
}

View file

@ -0,0 +1,154 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to delete a group of
* contacts. This class provides functionality for the actual
* addition of contacts to groups.
*/
class CRM_Activity_Form_Task_AddToTag extends CRM_Activity_Form_Task {
/**
* Name of the tag.
*
* @var string
*/
protected $_name;
/**
* All the tags in the system.
*
* @var array
*/
protected $_tags;
/**
* Build the form object.
*/
public function buildQuickForm() {
// add select for tag
$this->_tags = CRM_Core_BAO_Tag::getTags('civicrm_activity');
foreach ($this->_tags as $tagID => $tagName) {
$this->_tagElement = &$this->addElement('checkbox', "tag[$tagID]", NULL, $tagName);
}
$parentNames = CRM_Core_BAO_Tag::getTagSet('civicrm_activity');
CRM_Core_Form_Tag::buildQuickForm($this, $parentNames, 'civicrm_activity');
$this->addDefaultButtons(ts('Tag Activities'));
}
public function addRules() {
$this->addFormRule(array('CRM_Activity_Form_Task_AddToTag', 'formRule'));
}
/**
* @param CRM_Core_Form $form
* @param $rule
*
* @return array
*/
public static function formRule($form, $rule) {
$errors = array();
if (empty($form['tag']) && empty($form['activity_taglist'])) {
$errors['_qf_default'] = ts("Please select at least one tag.");
}
return $errors;
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
// Get the submitted values in an array.
$params = $this->controller->exportValues($this->_name);
$activityTags = $tagList = array();
// check if contact tags exists
if (!empty($params['tag'])) {
$activityTags = $params['tag'];
}
// check if tags are selected from taglists
if (!empty($params['activity_taglist'])) {
foreach ($params['activity_taglist'] as $val) {
if ($val) {
if (is_numeric($val)) {
$tagList[$val] = 1;
}
else {
$tagIDs = explode(',', $val);
if (!empty($tagIDs)) {
foreach ($tagIDs as $tagID) {
if (is_numeric($tagID)) {
$tagList[$tagID] = 1;
}
}
}
}
}
}
}
$tagSets = CRM_Core_BAO_Tag::getTagsUsedFor('civicrm_activity', FALSE, TRUE);
foreach ($tagSets as $key => $value) {
$this->_tags[$key] = $value['name'];
}
// merge activity and taglist tags
$allTags = CRM_Utils_Array::crmArrayMerge($activityTags, $tagList);
$this->_name = array();
foreach ($allTags as $key => $dnc) {
$this->_name[] = $this->_tags[$key];
list($total, $added, $notAdded) = CRM_Core_BAO_EntityTag::addEntitiesToTag($this->_activityHolderIds, $key,
'civicrm_activity', FALSE);
$status = array(ts('Activity tagged', array('count' => $added, 'plural' => '%count activities tagged')));
if ($notAdded) {
$status[] = ts('1 activity already had this tag', array(
'count' => $notAdded,
'plural' => '%count activities already had this tag',
));
}
$status = '<ul><li>' . implode('</li><li>', $status) . '</li></ul>';
CRM_Core_Session::setStatus($status, ts("Added Tag <em>%1</em>", array(1 => $this->_tags[$key])), 'success', array('expires' => 0));
}
}
}

View file

@ -0,0 +1,258 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality for batch profile update for Activities
*/
class CRM_Activity_Form_Task_Batch extends CRM_Activity_Form_Task {
/**
* The title of the group.
*
* @var string
*/
protected $_title;
/**
* Maximum profile fields that will be displayed.
*/
protected $_maxFields = 9;
/**
* Variable to store redirect path.
*/
protected $_userContext;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
// Initialize the task and row fields.
parent::preProcess();
// Get the contact read only fields to display.
$readOnlyFields = array_merge(array('sort_name' => ts('Added By'), 'target_sort_name' => ts('With Contact')),
CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'contact_autocomplete_options',
TRUE, NULL, FALSE, 'name', TRUE
)
);
// Get the read only field data.
$returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
$contactDetails = CRM_Contact_BAO_Contact_Utils::contactDetails($this->_activityHolderIds,
'Activity', $returnProperties
);
$readOnlyFields['assignee_display_name'] = ts('Assigned to');
if (!empty($contactDetails)) {
foreach ($contactDetails as $key => $value) {
$assignee = CRM_Activity_BAO_ActivityAssignment::retrieveAssigneeIdsByActivityId($key);
foreach ($assignee as $values) {
$assigneeContact[] = CRM_Contact_BAO_Contact::displayName($values);
}
$contactDetails[$key]['assignee_display_name'] = !empty($assigneeContact) ? implode(';', $assigneeContact) : NULL;
}
}
$this->assign('contactDetails', $contactDetails);
$this->assign('readOnlyFields', $readOnlyFields);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$ufGroupId = $this->get('ufGroupId');
if (!$ufGroupId) {
throw new CRM_Core_Exception('The profile id is missing');
}
$this->_title = ts('Update multiple activities') . ' - ' . CRM_Core_BAO_UFGroup::getTitle($ufGroupId);
CRM_Utils_System::setTitle($this->_title);
$this->addDefaultButtons(ts('Save'));
$this->_fields = array();
$this->_fields = CRM_Core_BAO_UFGroup::getFields($ufGroupId, FALSE, CRM_Core_Action::VIEW);
// remove file type field and then limit fields
$suppressFields = FALSE;
$removehtmlTypes = array('File', 'Autocomplete-Select');
foreach ($this->_fields as $name => $field) {
if (CRM_Core_BAO_CustomField::getKeyID($name) &&
in_array($this->_fields[$name]['html_type'], $removehtmlTypes)
) {
$suppressFields = TRUE;
unset($this->_fields[$name]);
}
// Fix to reduce size as we are using this field in grid.
if (is_array($field['attributes']) && !empty($this->_fields[$name]['attributes']['size']) && $this->_fields[$name]['attributes']['size'] > 19) {
// Shrink class to "form-text-medium".
$this->_fields[$name]['attributes']['size'] = 19;
}
}
$this->_fields = array_slice($this->_fields, 0, $this->_maxFields);
$this->addButtons(array(
array(
'type' => 'submit',
'name' => ts('Update Activities'),
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
));
$this->assign('profileTitle', $this->_title);
$this->assign('componentIds', $this->_activityHolderIds);
// Load all campaigns.
if (array_key_exists('activity_campaign_id', $this->_fields)) {
$this->_componentCampaigns = array();
CRM_Core_PseudoConstant::populate($this->_componentCampaigns,
'CRM_Activity_DAO_Activity',
TRUE, 'campaign_id', 'id',
' id IN (' . implode(' , ', array_values($this->_activityHolderIds)) . ' ) '
);
}
$customFields = CRM_Core_BAO_CustomField::getFields('Activity');
// It is possible to have fields that are required in CiviCRM not be required in the
// profile. Overriding that here. Perhaps a better approach would be to
// make them required in the schema & read that up through getFields functionality.
$requiredFields = array('activity_date_time');
foreach ($this->_activityHolderIds as $activityId) {
$typeId = CRM_Core_DAO::getFieldValue("CRM_Activity_DAO_Activity", $activityId, 'activity_type_id');
foreach ($this->_fields as $name => $field) {
if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
$customValue = CRM_Utils_Array::value($customFieldID, $customFields);
if (!empty($customValue['extends_entity_column_value'])) {
$entityColumnValue = explode(CRM_Core_DAO::VALUE_SEPARATOR,
$customValue['extends_entity_column_value']
);
}
if (!empty($entityColumnValue[$typeId]) ||
CRM_Utils_System::isNull($entityColumnValue[$typeId])
) {
CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $activityId);
}
}
else {
// Handle non custom fields.
if (in_array($field['name'], $requiredFields)) {
$field['is_required'] = TRUE;
}
CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $activityId);
}
}
}
$this->assign('fields', $this->_fields);
// Don't set the status message when form is submitted.
// $buttonName = $this->controller->getButtonName('submit');
if ($suppressFields) {
CRM_Core_Session::setStatus(ts("File or Autocomplete-Select type field(s) in the selected profile are not supported for Update multiple activities."), ts('Some Fields Excluded'), 'info');
}
$this->addDefaultButtons(ts('Update Activities'));
}
/**
* Set default values for the form.
*/
public function setDefaultValues() {
if (empty($this->_fields)) {
return;
}
$defaults = array();
foreach ($this->_activityHolderIds as $activityId) {
CRM_Core_BAO_UFGroup::setProfileDefaults(NULL, $this->_fields, $defaults, FALSE, $activityId, 'Activity');
}
return $defaults;
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
$params = $this->exportValues();
if (isset($params['field'])) {
foreach ($params['field'] as $key => $value) {
$value['custom'] = CRM_Core_BAO_CustomField::postProcess($value,
$key, 'Activity'
);
$value['id'] = $key;
if (!empty($value['activity_status_id'])) {
$value['status_id'] = $value['activity_status_id'];
}
if (!empty($value['activity_details'])) {
$value['details'] = $value['activity_details'];
}
if (!empty($value['activity_location'])) {
$value['location'] = $value['activity_location'];
}
if (!empty($value['activity_subject'])) {
$value['subject'] = $value['activity_subject'];
}
$activityId = civicrm_api3('activity', 'create', $value);
// @todo this would be done by the api call above if the parames were passed through.
if (!empty($value['custom']) &&
is_array($value['custom'])
) {
CRM_Core_BAO_CustomValueTable::store($value['custom'], 'civicrm_activity', $activityId['id']);
}
}
CRM_Core_Session::setStatus("", ts("Updates Saved"), "success");
}
else {
CRM_Core_Session::setStatus("", ts("No Updates Saved"), "info");
}
}
}

View file

@ -0,0 +1,88 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to delete a group of
* Activities. This class provides functionality for the actual
* deletion.
*/
class CRM_Activity_Form_Task_Delete extends CRM_Activity_Form_Task {
/**
* Are we operating in "single mode", i.e. deleting one
* specific Activity?
*
* @var boolean
*/
protected $_single = FALSE;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
parent::preProcess();
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->addDefaultButtons(ts('Delete Activities'), 'done');
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
$deleted = $failed = 0;
foreach ($this->_activityHolderIds as $activityId['id']) {
$moveToTrash = CRM_Case_BAO_Case::isCaseActivity($activityId['id']);
if (CRM_Activity_BAO_Activity::deleteActivity($activityId, $moveToTrash)) {
$deleted++;
}
else {
$failed++;
}
}
if ($deleted) {
$msg = ts('%count activity deleted.', array('plural' => '%count activities deleted.', 'count' => $deleted));
CRM_Core_Session::setStatus($msg, ts('Removed'), 'success');
}
if ($failed) {
CRM_Core_Session::setStatus(ts('1 could not be deleted.', array('plural' => '%count could not be deleted.', 'count' => $failed)), ts('Error'), 'error');
}
}
}

View file

@ -0,0 +1,96 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to email a group of contacts.
*/
class CRM_Activity_Form_Task_Email extends CRM_Activity_Form_Task {
/**
* Are we operating in "single mode", i.e. sending email to one
* specific contact?
*
* @var boolean
*/
public $_single = FALSE;
public $_noEmails = FALSE;
/**
* All the existing templates in the system.
*
* @var array
*/
public $_templates = NULL;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
CRM_Contact_Form_Task_EmailCommon::preProcessFromAddress($this);
parent::preProcess();
// we have all the contribution ids, so now we get the contact ids
parent::setContactIDs();
$this->assign('single', $this->_single);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
// Enable form element.
$this->assign('emailTask', TRUE);
CRM_Contact_Form_Task_EmailCommon::buildQuickForm($this);
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
CRM_Contact_Form_Task_EmailCommon::postProcess($this);
}
/**
* List available tokens for this form.
*
* @return array
*/
public function listTokens() {
$tokens = CRM_Core_SelectValues::contactTokens();
return $tokens;
}
}

View file

@ -0,0 +1,124 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to email a group of contacts
*/
class CRM_Activity_Form_Task_FileOnCase extends CRM_Activity_Form_Task {
/**
* The title of the group.
*
* @var string
*/
protected $_title;
/**
* Variable to store redirect path.
*/
protected $_userContext;
/**
* Variable to store contact Ids.
*/
public $_contacts;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
parent::preProcess();
$session = CRM_Core_Session::singleton();
$this->_userContext = $session->readUserContext();
CRM_Utils_System::setTitle(ts('File on Case'));
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->addEntityRef('unclosed_case_id', ts('Select Case'), array('entity' => 'Case'), TRUE);
$this->addDefaultButtons(ts('Save'));
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
$formparams = $this->exportValues();
$caseId = $formparams['unclosed_case_id'];
$filedActivities = 0;
foreach ($this->_activityHolderIds as $key => $id) {
$targetContactValues = $defaults = array();
$params = array('id' => $id);
CRM_Activity_BAO_Activity::retrieve($params, $defaults);
if (CRM_Case_BAO_Case::checkPermission($id, 'File On Case', $defaults['activity_type_id'])) {
if (!CRM_Utils_Array::crmIsEmptyArray($defaults['target_contact'])) {
$targetContactValues = array_combine(array_unique($defaults['target_contact']),
explode(';', trim($defaults['target_contact_value']))
);
$targetContactValues = implode(',', array_keys($targetContactValues));
}
$params = array(
'caseID' => $caseId,
'activityID' => $id,
'newSubject' => empty($defaults['subject']) ? '' : $defaults['subject'],
'targetContactIds' => $targetContactValues,
'mode' => 'file',
);
$error_msg = CRM_Activity_Page_AJAX::_convertToCaseActivity($params);
if (empty($error_msg['error_msg'])) {
$filedActivities++;
}
else {
CRM_Core_Session::setStatus($error_msg['error_msg'], ts("Error"), "error");
}
}
else {
CRM_Core_Session::setStatus(ts('Not permitted to file activity %1 %2.', array(
1 => empty($defaults['subject']) ? '' : $defaults['subject'],
2 => $defaults['activity_date_time'],
)),
ts("Error"), "error");
}
}
CRM_Core_Session::setStatus($filedActivities, ts("Filed Activities"), "success");
CRM_Core_Session::setStatus("", ts('Total Selected Activities: %1', array(1 => count($this->_activityHolderIds))), "info");
}
}

View file

@ -0,0 +1,173 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to email a group of contacts.
*/
class CRM_Activity_Form_Task_PickOption extends CRM_Activity_Form_Task {
/**
* The title of the group.
*
* @var string
*/
protected $_title;
/**
* Maximum Activities that should be allowed to update.
*/
protected $_maxActivities = 100;
/**
* Variable to store redirect path.
*/
protected $_userContext;
/**
* Variable to store contact Ids.
*/
public $_contacts;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
// initialize the task and row fields.
parent::preProcess();
$session = CRM_Core_Session::singleton();
$this->_userContext = $session->readUserContext();
CRM_Utils_System::setTitle(ts('Send Email to Contacts'));
$validate = FALSE;
//validations
if (count($this->_activityHolderIds) > $this->_maxActivities) {
CRM_Core_Session::setStatus(ts("The maximum number of Activities you can select to send an email is %1. You have selected %2. Please select fewer Activities from your search results and try again.", array(
1 => $this->_maxActivities,
2 => count($this->_activityHolderIds),
)), ts("Maximum Exceeded"), "error");
$validate = TRUE;
}
// then redirect
if ($validate) {
CRM_Utils_System::redirect($this->_userContext);
}
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->addElement('checkbox', 'with_contact', ts('With Contact'));
$this->addElement('checkbox', 'assigned_to', ts('Assigned to Contact'));
$this->addElement('checkbox', 'created_by', ts('Created by'));
$this->setDefaults(array('with_contact' => 1));
$this->addDefaultButtons(ts('Continue'));
}
/**
* Add local and global form rules.
*/
public function addRules() {
$this->addFormRule(array('CRM_Activity_Form_Task_PickOption', 'formRule'));
}
/**
* Global validation rules for the form.
*
* @param array $fields
* Posted values of the form.
*
* @return array
* list of errors to be posted back to the form
*/
public static function formRule($fields) {
if (!isset($fields['with_contact']) &&
!isset($fields['assigned_to']) &&
!isset($fields['created_by'])
) {
return array('with_contact' => ts('You must select at least one email recipient type.'));
}
return TRUE;
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
// Clear any formRule errors from Email form in case they came back here via Cancel button
$this->controller->resetPage('Email');
$params = $this->exportValues();
$this->_contacts = array();
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
$targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
// Get assignee contacts.
if (!empty($params['assigned_to'])) {
foreach ($this->_activityHolderIds as $key => $id) {
$ids = array_keys(CRM_Activity_BAO_ActivityContact::getNames($id, $assigneeID));
$this->_contacts = array_merge($this->_contacts, $ids);
}
}
// Get target contacts.
if (!empty($params['with_contact'])) {
foreach ($this->_activityHolderIds as $key => $id) {
$ids = array_keys(CRM_Activity_BAO_ActivityContact::getNames($id, $targetID));
$this->_contacts = array_merge($this->_contacts, $ids);
}
}
// Get 'Added by' contacts.
if (!empty($params['created_by'])) {
parent::setContactIDs();
if (!empty($this->_contactIds)) {
$this->_contacts = array_merge($this->_contacts, $this->_contactIds);
}
}
$this->_contacts = array_unique($this->_contacts);
// Bounce to pick option if no contacts to send to.
if (empty($this->_contacts)) {
$urlParams = "_qf_PickOption_display=true&qfKey={$params['qfKey']}";
$urlRedirect = CRM_Utils_System::url('civicrm/activity/search', $urlParams);
CRM_Core_Error::statusBounce(
ts('It appears you have no contacts with email addresses from the selected recipients.'),
$urlRedirect
);
}
$this->set('contacts', $this->_contacts);
}
}

View file

@ -0,0 +1,161 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality for batch profile update for Activity.
*/
class CRM_Activity_Form_Task_PickProfile extends CRM_Activity_Form_Task {
/**
* The title of the group.
*
* @var string
*/
protected $_title;
/**
* Maximum Activities that should be allowed to update.
*/
protected $_maxActivities = 100;
/**
* Variable to store redirect path.
*/
protected $_userContext;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
// Initialize the task and row fields.
parent::preProcess();
$session = CRM_Core_Session::singleton();
$this->_userContext = $session->readUserContext();
CRM_Utils_System::setTitle(ts('Update multiple activities'));
$validate = FALSE;
// Validations.
if (count($this->_activityHolderIds) > $this->_maxActivities) {
CRM_Core_Session::setStatus(ts("The maximum number of activities you can select for Update multiple activities is %1. You have selected %2. Please select fewer Activities from your search results and try again.", array(
1 => $this->_maxActivities,
2 => count($this->_activityHolderIds),
)), ts('Maximum Exceeded'), 'error');
$validate = TRUE;
}
// Then redirect.
if ($validate) {
CRM_Utils_System::redirect($this->_userContext);
}
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$types = array('Activity');
$profiles = CRM_Core_BAO_UFGroup::getProfiles($types, TRUE);
$activityTypeIds = array_flip(CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name'));
$nonEditableActivityTypeIds = array(
$activityTypeIds['Email'],
$activityTypeIds['Bulk Email'],
$activityTypeIds['Contribution'],
$activityTypeIds['Inbound Email'],
$activityTypeIds['Pledge Reminder'],
$activityTypeIds['Membership Signup'],
$activityTypeIds['Membership Renewal'],
$activityTypeIds['Event Registration'],
$activityTypeIds['Pledge Acknowledgment'],
);
$notEditable = FALSE;
foreach ($this->_activityHolderIds as $activityId) {
$typeId = CRM_Core_DAO::getFieldValue("CRM_Activity_DAO_Activity", $activityId, 'activity_type_id');
if (in_array($typeId, $nonEditableActivityTypeIds)) {
$notEditable = TRUE;
break;
}
}
if (empty($profiles)) {
CRM_Core_Session::setStatus(ts("You will need to create a Profile containing the %1 fields you want to edit before you can use Update multiple activities. Navigate to Administer > Customize Data and Screens > Profiles to configure a Profile. Consult the online Administrator documentation for more information.", array(1 => $types[0])), ts("No Profile Configured"), "alert");
CRM_Utils_System::redirect($this->_userContext);
}
elseif ($notEditable) {
CRM_Core_Session::setStatus("", ts("Some of the selected activities are not editable."), "alert");
CRM_Utils_System::redirect($this->_userContext);
}
$ufGroupElement = $this->add('select', 'uf_group_id', ts('Select Profile'),
array(
'' => ts('- select profile -'),
) + $profiles, TRUE
);
$this->addDefaultButtons(ts('Continue'));
}
/**
* Add local and global form rules.
*/
public function addRules() {
$this->addFormRule(array('CRM_Activity_Form_Task_PickProfile', 'formRule'));
}
/**
* Global validation rules for the form.
*
* @param array $fields
* Posted values of the form.
*
* @return array
* list of errors to be posted back to the form
*/
public static function formRule($fields) {
return TRUE;
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
$params = $this->exportValues();
$this->set('ufGroupId', $params['uf_group_id']);
// also reset the batch page so it gets new values from the db
$this->controller->resetPage('Batch');
}
}

View file

@ -0,0 +1,88 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to print activity records.
*/
class CRM_Activity_Form_Task_Print extends CRM_Activity_Form_Task {
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
parent::preprocess();
// set print view, so that print templates are called
$this->controller->setPrint(1);
// get the formatted params
$queryParams = $this->get('queryParams');
$sortID = NULL;
if ($this->get(CRM_Utils_Sort::SORT_ID)) {
$sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
$this->get(CRM_Utils_Sort::SORT_DIRECTION)
);
}
$selector = new CRM_Activity_Selector_Search($queryParams, $this->_action, $this->_componentClause);
$controller = new CRM_Core_Selector_Controller($selector, NULL, $sortID, CRM_Core_Action::VIEW, $this, CRM_Core_Selector_Controller::SCREEN);
$controller->setEmbedded(TRUE);
$controller->run();
}
/**
* Build the form object.
*
* Consists of
* - displaying the QILL (query in local language)
* - displaying elements for saving the search
*/
public function buildQuickForm() {
// just need to add a javacript to popup the window for printing
$this->addButtons(array(
array(
'type' => 'next',
'name' => ts('Print Activities'),
'js' => array('onclick' => 'window.print()'),
'isDefault' => TRUE,
),
array(
'type' => 'back',
'name' => ts('Done'),
),
));
}
}

View file

@ -0,0 +1,147 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to remove tags of contact(s).
*/
class CRM_Activity_Form_Task_RemoveFromTag extends CRM_Activity_Form_Task {
/**
* Name of the tag
*
* @var string
*/
protected $_name;
/**
* All the tags in the system
*
* @var array
*/
protected $_tags;
/**
* Build the form object.
*/
public function buildQuickForm() {
// add select for tag
$this->_tags = CRM_Core_BAO_Tag::getTags('civicrm_activity');
foreach ($this->_tags as $tagID => $tagName) {
$this->_tagElement = &$this->addElement('checkbox', "tag[$tagID]", NULL, $tagName);
}
$parentNames = CRM_Core_BAO_Tag::getTagSet('civicrm_activity');
CRM_Core_Form_Tag::buildQuickForm($this, $parentNames, 'civicrm_activity', NULL, TRUE, FALSE);
$this->addDefaultButtons(ts('Remove Tags from activities'));
}
public function addRules() {
$this->addFormRule(array('CRM_Activity_Form_Task_RemoveFromTag', 'formRule'));
}
/**
* @param CRM_Core_Form $form
* @param $rule
*
* @return array
*/
public static function formRule($form, $rule) {
$errors = array();
if (empty($form['tag']) && empty($form['activity_taglist'])) {
$errors['_qf_default'] = "Please select atleast one tag.";
}
return $errors;
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
//get the submitted values in an array
$params = $this->controller->exportValues($this->_name);
$activityTags = $tagList = array();
// check if contact tags exists
if (!empty($params['tag'])) {
$activityTags = $params['tag'];
}
// check if tags are selected from taglists
if (!empty($params['activity_taglist'])) {
foreach ($params['activity_taglist'] as $val) {
if ($val) {
if (is_numeric($val)) {
$tagList[$val] = 1;
}
else {
list($label, $tagID) = explode(',', $val);
$tagList[$tagID] = 1;
}
}
}
}
$tagSets = CRM_Core_BAO_Tag::getTagsUsedFor('civicrm_activity', FALSE, TRUE);
foreach ($tagSets as $key => $value) {
$this->_tags[$key] = $value['name'];
}
// merge contact and taglist tags
$allTags = CRM_Utils_Array::crmArrayMerge($activityTags, $tagList);
$this->_name = array();
foreach ($allTags as $key => $dnc) {
$this->_name[] = $this->_tags[$key];
list($total, $removed, $notRemoved) = CRM_Core_BAO_EntityTag::removeEntitiesFromTag($this->_activityHolderIds,
$key, 'civicrm_activity', FALSE);
$status = array(
ts('%count activity un-tagged', array(
'count' => $removed,
'plural' => '%count activities un-tagged',
)),
);
if ($notRemoved) {
$status[] = ts('1 activity already did not have this tag', array(
'count' => $notRemoved,
'plural' => '%count activities already did not have this tag',
));
}
$status = '<ul><li>' . implode('</li><li>', $status) . '</li></ul>';
CRM_Core_Session::setStatus($status, ts("Removed Tag <em>%1</em>", array(1 => $this->_tags[$key])), 'success', array('expires' => 0));
}
}
}

View file

@ -0,0 +1,88 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to sms a group of contacts.
*/
class CRM_Activity_Form_Task_SMS extends CRM_Activity_Form_Task {
/**
* Are we operating in "single mode", i.e. sending sms to one
* specific contact?
*
* @var boolean
*/
public $_single = FALSE;
/**
* All the existing templates in the system.
*
* @var array
*/
public $_templates = NULL;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
parent::preProcess();
CRM_Contact_Form_Task_SMSCommon::preProcessProvider($this);
$this->assign('single', $this->_single);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
// Enable form element.
$this->assign('SMSTask', TRUE);
CRM_Contact_Form_Task_SMSCommon::buildQuickForm($this);
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
CRM_Contact_Form_Task_SMSCommon::postProcess($this);
}
/**
* List available tokens for this form.
*
* @return array
*/
public function listTokens() {
$tokens = CRM_Core_SelectValues::contactTokens();
return $tokens;
}
}

View file

@ -0,0 +1,89 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to save a search
* Saved Searches are used for saving frequently used queries
*/
class CRM_Activity_Form_Task_SearchTaskHookSample extends CRM_Activity_Form_Task {
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
parent::preProcess();
$rows = array();
// display name and activity details of all selected contacts
$activityIDs = implode(',', $this->_activityHolderIds);
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
$query = "
SELECT at.subject as subject,
ov.label as activity_type,
at.activity_date_time as activity_date,
ct.display_name as display_name
FROM civicrm_activity at
LEFT JOIN civicrm_activity_contact ac ON ( ac.activity_id = at.id AND ac.record_type_id = {$sourceID} )
INNER JOIN civicrm_contact ct ON ( ac.contact_id = ct.id )
LEFT JOIN civicrm_option_group og ON ( og.name = 'activity_type' )
LEFT JOIN civicrm_option_value ov ON (at.activity_type_id = ov.value AND og.id = ov.option_group_id )
WHERE at.id IN ( $activityIDs )";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$rows[] = array(
'subject' => $dao->subject,
'activity_type' => $dao->activity_type,
'activity_date' => $dao->activity_date,
'display_name' => $dao->display_name,
);
}
$this->assign('rows', $rows);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->addButtons(array(
array(
'type' => 'done',
'name' => ts('Done'),
'isDefault' => TRUE,
),
));
}
}

View file

@ -0,0 +1,60 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Activity_Import_Controller extends CRM_Core_Controller {
/**
* Class constructor.
*
* @param string $title
* @param bool|int $action
* @param bool $modal
*/
public function __construct($title = NULL, $action = CRM_Core_Action::NONE, $modal = TRUE) {
parent::__construct($title, $modal);
// lets get around the time limit issue if possible, CRM-2113
if (!ini_get('safe_mode')) {
set_time_limit(0);
}
$this->_stateMachine = new CRM_Import_StateMachine($this, $action);
// create and instantiate the pages
$this->addPages($this->_stateMachine, $action);
// add all the actions
$config = CRM_Core_Config::singleton();
$this->addActions($config->uploadDir, array('uploadFile'));
}
}

View file

@ -0,0 +1,123 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Activity_Import_Field {
/**
* @var string
* Name of the field
*/
public $_name;
/**
* Title of the field to be used in display
*/
public $_title;
/**
* Type of field
* @var enum
*/
public $_type;
/**
* Is this field required
* @var boolean
*/
public $_required;
/**
* Data to be carried for use by a derived class
* @var object
*/
public $_payload;
/**
* Regexp to match the CSV header of this column/field
* @var string
*/
public $_headerPattern;
/**
* Regexp to match the pattern of data from various column/fields
* @var string
*/
public $_dataPattern;
/**
* Value of this field
* @var object
*/
public $_value;
/**
* @param string $name
* @param $title
* @param int $type
* @param string $headerPattern
* @param string $dataPattern
*/
public function __construct($name, $title, $type = CRM_Utils_Type::T_INT, $headerPattern = '//', $dataPattern = '//') {
$this->_name = $name;
$this->_title = $title;
$this->_type = $type;
$this->_headerPattern = $headerPattern;
$this->_dataPattern = $dataPattern;
$this->_value = NULL;
}
public function resetValue() {
$this->_value = NULL;
}
/**
* The value is in string format. convert the value to the type of this field
* and set the field value with the appropriate type
* @param $value
*/
public function setValue($value) {
$this->_value = $value;
}
/**
* @return bool
*/
public function validate() {
if (CRM_Utils_System::isNull($this->_value)) {
return TRUE;
}
return TRUE;
}
}

View file

@ -0,0 +1,79 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class gets the name of the file to upload.
*/
class CRM_Activity_Import_Form_DataSource extends CRM_Import_Form_DataSource {
const PATH = 'civicrm/import/activity';
const IMPORT_ENTITY = 'Activity';
/**
* Build the form object.
*/
public function buildQuickForm() {
parent::buildQuickForm();
// FIXME: This 'onDuplicate' form element is never used -- copy/paste error?
$duplicateOptions = array();
$duplicateOptions[] = $this->createElement('radio',
NULL, NULL, ts('Skip'), CRM_Import_Parser::DUPLICATE_SKIP
);
$duplicateOptions[] = $this->createElement('radio',
NULL, NULL, ts('Update'), CRM_Import_Parser::DUPLICATE_UPDATE
);
$duplicateOptions[] = $this->createElement('radio',
NULL, NULL, ts('Fill'), CRM_Import_Parser::DUPLICATE_FILL
);
$this->addGroup($duplicateOptions, 'onDuplicate',
ts('On duplicate entries')
);
}
/**
* Process the uploaded file.
*/
public function postProcess() {
$this->storeFormValues(array(
'onDuplicate',
'dateFormats',
'savedMapping',
));
$this->submitFileForMapping('CRM_Activity_Import_Parser_Activity');
}
}

View file

@ -0,0 +1,471 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class gets the name of the file to upload.
*/
class CRM_Activity_Import_Form_MapField extends CRM_Import_Form_MapField {
/**
* Set variables up before form is built.
*/
public function preProcess() {
$this->_mapperFields = $this->get('fields');
unset($this->_mapperFields['id']);
asort($this->_mapperFields);
$this->_columnCount = $this->get('columnCount');
$this->assign('columnCount', $this->_columnCount);
$this->_dataValues = $this->get('dataValues');
$this->assign('dataValues', $this->_dataValues);
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
if ($skipColumnHeader) {
$this->assign('skipColumnHeader', $skipColumnHeader);
$this->assign('rowDisplayCount', 3);
// If we had a column header to skip, stash it for later.
$this->_columnHeaders = $this->_dataValues[0];
}
else {
$this->assign('rowDisplayCount', 2);
}
$highlightedFields = array();
$requiredFields = array(
'activity_date_time',
'activity_type_id',
'activity_label',
'target_contact_id',
'activity_subject',
);
foreach ($requiredFields as $val) {
$highlightedFields[] = $val;
}
$this->assign('highlightedFields', $highlightedFields);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
// To save the current mappings.
if (!$this->get('savedMapping')) {
$saveDetailsName = ts('Save this field mapping');
$this->applyFilter('saveMappingName', 'trim');
$this->add('text', 'saveMappingName', ts('Name'));
$this->add('text', 'saveMappingDesc', ts('Description'));
}
else {
$savedMapping = $this->get('savedMapping');
// Mapping is to be loaded from database.
list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingRelation) = CRM_Core_BAO_Mapping::getMappingFields($savedMapping);
// Get loaded Mapping Fields.
$mappingName = CRM_Utils_Array::value('1', $mappingName);
$mappingContactType = CRM_Utils_Array::value('1', $mappingContactType);
$mappingLocation = CRM_Utils_Array::value('1', $mappingLocation);
$mappingPhoneType = CRM_Utils_Array::value('1', $mappingPhoneType);
$mappingRelation = CRM_Utils_Array::value('1', $mappingRelation);
$this->assign('loadedMapping', $savedMapping);
$this->set('loadedMapping', $savedMapping);
$params = array('id' => $savedMapping);
$temp = array();
$mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp);
$this->assign('savedName', $mappingDetails->name);
$this->add('hidden', 'mappingId', $savedMapping);
$this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
$saveDetailsName = ts('Save as a new field mapping');
$this->add('text', 'saveMappingName', ts('Name'));
$this->add('text', 'saveMappingDesc', ts('Description'));
}
$this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)"));
$this->addFormRule(array('CRM_Activity_Import_Form_MapField', 'formRule'));
//-------- end of saved mapping stuff ---------
$defaults = array();
$mapperKeys = array_keys($this->_mapperFields);
$hasHeaders = !empty($this->_columnHeaders);
$headerPatterns = $this->get('headerPatterns');
$dataPatterns = $this->get('dataPatterns');
$hasLocationTypes = $this->get('fieldTypes');
// Initialize all field usages to false.
foreach ($mapperKeys as $key) {
$this->_fieldUsed[$key] = FALSE;
}
$this->_location_types = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
$sel1 = $this->_mapperFields;
$sel2[''] = NULL;
$js = "<script type='text/javascript'>\n";
$formName = 'document.forms.' . $this->_name;
// Used to warn for mismatch column count or mismatch mapping.
$warning = 0;
for ($i = 0; $i < $this->_columnCount; $i++) {
$sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', array(1 => $i)), NULL);
$jsSet = FALSE;
if ($this->get('savedMapping')) {
if (isset($mappingName[$i])) {
if ($mappingName[$i] != ts('- do not import -')) {
$mappingHeader = array_keys($this->_mapperFields, $mappingName[$i]);
if (!isset($locationId) || !$locationId) {
$js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
}
if (!isset($phoneType) || !$phoneType) {
$js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
}
$js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
$defaults["mapper[$i]"] = array(
$mappingHeader[0],
(isset($locationId)) ? $locationId : "",
(isset($phoneType)) ? $phoneType : "",
);
$jsSet = TRUE;
}
else {
$defaults["mapper[$i]"] = array();
}
if (!$jsSet) {
for ($k = 1; $k < 4; $k++) {
$js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
}
}
}
else {
// this load section to help mapping if we ran out of saved columns when doing Load Mapping
$js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
if ($hasHeaders) {
$defaults["mapper[$i]"] = array(
$this->defaultFromHeader($this->_columnHeaders[$i],
$headerPatterns
),
);
}
else {
$defaults["mapper[$i]"] = array($this->defaultFromData($dataPatterns, $i));
}
}
// End of load mapping.
}
else {
$js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
if ($hasHeaders) {
// Infer the default from the skipped headers if we have them
$defaults["mapper[$i]"] = array(
$this->defaultFromHeader($this->_columnHeaders[$i],
$headerPatterns
),
0,
);
}
else {
// Otherwise guess the default from the form of the data
$defaults["mapper[$i]"] = array(
$this->defaultFromData($dataPatterns, $i),
0,
);
}
}
$sel->setOptions(array($sel1, $sel2, (isset($sel3)) ? $sel3 : "", (isset($sel4)) ? $sel4 : ""));
}
$js .= "</script>\n";
$this->assign('initHideBoxes', $js);
// Set warning if mismatch in more than.
if (isset($mappingName)) {
if (($this->_columnCount != count($mappingName))) {
$warning++;
}
}
if ($warning != 0 && $this->get('savedMapping')) {
$session = CRM_Core_Session::singleton();
$session->setStatus(ts('The data columns in this import file appear to be different from the saved mapping. Please verify that you have selected the correct saved mapping before continuing.'));
}
else {
$session = CRM_Core_Session::singleton();
$session->setStatus(NULL);
}
$this->setDefaults($defaults);
$this->addButtons(array(
array(
'type' => 'back',
'name' => ts('Previous'),
),
array(
'type' => 'next',
'name' => ts('Continue'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
}
/**
* Global validation rules for the form.
*
* @param array $fields
* Posted values of the form.
*
* @return array
* list of errors to be posted back to the form
*/
public static function formRule($fields) {
$errors = array();
// define so we avoid notices below
$errors['_qf_default'] = '';
$fieldMessage = NULL;
if (!array_key_exists('savedMapping', $fields)) {
$importKeys = array();
foreach ($fields['mapper'] as $mapperPart) {
$importKeys[] = $mapperPart[0];
}
// FIXME: should use the schema titles, not redeclare them
$requiredFields = array(
'target_contact_id' => ts('Contact ID'),
'activity_date_time' => ts('Activity Date'),
'activity_subject' => ts('Activity Subject'),
'activity_type_id' => ts('Activity Type ID'),
);
$params = array(
'used' => 'Unsupervised',
'contact_type' => 'Individual',
);
list($ruleFields, $threshold) = CRM_Dedupe_BAO_RuleGroup::dedupeRuleFieldsWeight($params);
$weightSum = 0;
foreach ($importKeys as $key => $val) {
if (array_key_exists($val, $ruleFields)) {
$weightSum += $ruleFields[$val];
}
}
foreach ($ruleFields as $field => $weight) {
$fieldMessage .= ' ' . $field . '(weight ' . $weight . ')';
}
foreach ($requiredFields as $field => $title) {
if (!in_array($field, $importKeys)) {
if ($field == 'target_contact_id') {
if ($weightSum >= $threshold || in_array('external_identifier', $importKeys)) {
continue;
}
else {
$errors['_qf_default'] .= ts('Missing required contact matching fields.')
. $fieldMessage . ' '
. ts('(Sum of all weights should be greater than or equal to threshold: %1).', array(1 => $threshold))
. '<br />';
}
}
elseif ($field == 'activity_type_id') {
if (in_array('activity_label', $importKeys)) {
continue;
}
else {
$errors['_qf_default'] .= ts('Missing required field: Provide %1 or %2',
array(
1 => $title,
2 => 'Activity Type Label',
)) . '<br />';
}
}
else {
$errors['_qf_default'] .= ts('Missing required field: %1', array(1 => $title)) . '<br />';
}
}
}
}
if (!empty($fields['saveMapping'])) {
$nameField = CRM_Utils_Array::value('saveMappingName', $fields);
if (empty($nameField)) {
$errors['saveMappingName'] = ts('Name is required to save Import Mapping');
}
else {
$mappingTypeId = CRM_Core_OptionGroup::getValue('mapping_type', 'Import Activity', 'name');
if (CRM_Core_BAO_Mapping::checkMapping($nameField, $mappingTypeId)) {
$errors['saveMappingName'] = ts('Duplicate Import Mapping Name');
}
}
}
if (empty($errors['_qf_default'])) {
unset($errors['_qf_default']);
}
if (!empty($errors)) {
if (!empty($errors['saveMappingName'])) {
$_flag = 1;
$assignError = new CRM_Core_Page();
$assignError->assign('mappingDetailsError', $_flag);
}
return $errors;
}
return TRUE;
}
/**
* Process the mapped fields and map it into the uploaded file.
*
* Preview the file and extract some summary statistics
*/
public function postProcess() {
$params = $this->controller->exportValues('MapField');
// Reload the mapfield if load mapping is pressed.
if (!empty($params['savedMapping'])) {
$this->set('savedMapping', $params['savedMapping']);
$this->controller->resetPage($this->_name);
return;
}
$fileName = $this->controller->exportValue('DataSource', 'uploadFile');
$seperator = $this->controller->exportValue('DataSource', 'fieldSeparator');
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
$mapperKeys = array();
$mapper = array();
$mapperKeys = $this->controller->exportValue($this->_name, 'mapper');
$mapperKeysMain = array();
$mapperLocType = array();
$mapperPhoneType = array();
for ($i = 0; $i < $this->_columnCount; $i++) {
$mapper[$i] = $this->_mapperFields[$mapperKeys[$i][0]];
$mapperKeysMain[$i] = $mapperKeys[$i][0];
if ((CRM_Utils_Array::value(1, $mapperKeys[$i])) && (is_numeric($mapperKeys[$i][1]))) {
$mapperLocType[$i] = $mapperKeys[$i][1];
}
else {
$mapperLocType[$i] = NULL;
}
if ((CRM_Utils_Array::value(2, $mapperKeys[$i])) && (!is_numeric($mapperKeys[$i][2]))) {
$mapperPhoneType[$i] = $mapperKeys[$i][2];
}
else {
$mapperPhoneType[$i] = NULL;
}
}
$this->set('mapper', $mapper);
// store mapping Id to display it in the preview page
if (!empty($params['mappingId'])) {
$this->set('loadMappingId', $params['mappingId']);
}
// Updating Mapping Records.
if (!empty($params['updateMapping'])) {
$mappingFields = new CRM_Core_DAO_MappingField();
$mappingFields->mapping_id = $params['mappingId'];
$mappingFields->find();
$mappingFieldsId = array();
while ($mappingFields->fetch()) {
if ($mappingFields->id) {
$mappingFieldsId[$mappingFields->column_number] = $mappingFields->id;
}
}
for ($i = 0; $i < $this->_columnCount; $i++) {
$updateMappingFields = new CRM_Core_DAO_MappingField();
$updateMappingFields->id = $mappingFieldsId[$i];
$updateMappingFields->mapping_id = $params['mappingId'];
$updateMappingFields->column_number = $i;
$updateMappingFields->name = $mapper[$i];
$updateMappingFields->save();
}
}
// Saving Mapping Details and Records.
if (!empty($params['saveMapping'])) {
$mappingParams = array(
'name' => $params['saveMappingName'],
'description' => $params['saveMappingDesc'],
'mapping_type_id' => CRM_Core_OptionGroup::getValue('mapping_type',
'Import Activity',
'name'
),
);
$saveMapping = CRM_Core_BAO_Mapping::add($mappingParams);
for ($i = 0; $i < $this->_columnCount; $i++) {
$saveMappingFields = new CRM_Core_DAO_MappingField();
$saveMappingFields->mapping_id = $saveMapping->id;
$saveMappingFields->column_number = $i;
$saveMappingFields->name = $mapper[$i];
$saveMappingFields->save();
}
$this->set('savedMapping', $saveMappingFields->mapping_id);
}
$parser = new CRM_Activity_Import_Parser_Activity($mapperKeysMain, $mapperLocType, $mapperPhoneType);
$parser->run($fileName, $seperator, $mapper, $skipColumnHeader,
CRM_Import_Parser::MODE_PREVIEW
);
// add all the necessary variables to the form
$parser->set($this);
}
}

View file

@ -0,0 +1,188 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class previews the uploaded file and returns summary statistics.
*/
class CRM_Activity_Import_Form_Preview extends CRM_Import_Form_Preview {
/**
* Set variables up before form is built.
*/
public function preProcess() {
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
// Get the data from the session.
$dataValues = $this->get('dataValues');
$mapper = $this->get('mapper');
$invalidRowCount = $this->get('invalidRowCount');
$conflictRowCount = $this->get('conflictRowCount');
$mismatchCount = $this->get('unMatchCount');
// Get the mapping name displayed if the mappingId is set.
$mappingId = $this->get('loadMappingId');
if ($mappingId) {
$mapDAO = new CRM_Core_DAO_Mapping();
$mapDAO->id = $mappingId;
$mapDAO->find(TRUE);
$this->assign('loadedMapping', $mappingId);
$this->assign('savedName', $mapDAO->name);
}
if ($skipColumnHeader) {
$this->assign('skipColumnHeader', $skipColumnHeader);
$this->assign('rowDisplayCount', 3);
}
else {
$this->assign('rowDisplayCount', 2);
}
if ($invalidRowCount) {
$urlParams = 'type=' . CRM_Import_Parser::ERROR . '&parser=CRM_Activity_Import_Parser';
$this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
if ($conflictRowCount) {
$urlParams = 'type=' . CRM_Import_Parser::CONFLICT . '&parser=CRM_Activity_Import_Parser';
$this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
if ($mismatchCount) {
$urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Activity_Import_Parser';
$this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
$properties = array(
'mapper',
'dataValues',
'columnCount',
'totalRowCount',
'validRowCount',
'invalidRowCount',
'conflictRowCount',
'downloadErrorRecordsUrl',
'downloadConflictRecordsUrl',
'downloadMismatchRecordsUrl',
);
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
}
}
/**
* Process the mapped fields and map it into the uploaded file.
*
* Preview the file and extract some summary statistics
*/
public function postProcess() {
$fileName = $this->controller->exportValue('DataSource', 'uploadFile');
$seperator = $this->controller->exportValue('DataSource', 'fieldSeparator');
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
$invalidRowCount = $this->get('invalidRowCount');
$conflictRowCount = $this->get('conflictRowCount');
$onDuplicate = $this->get('onDuplicate');
$mapper = $this->controller->exportValue('MapField', 'mapper');
$mapperKeys = array();
$mapperLocType = array();
$mapperPhoneType = array();
foreach ($mapper as $key => $value) {
$mapperKeys[$key] = $mapper[$key][0];
if (!empty($mapper[$key][1]) && is_numeric($mapper[$key][1])) {
$mapperLocType[$key] = $mapper[$key][1];
}
else {
$mapperLocType[$key] = NULL;
}
if (!empty($mapper[$key][2]) && (!is_numeric($mapper[$key][2]))) {
$mapperPhoneType[$key] = $mapper[$key][2];
}
else {
$mapperPhoneType[$key] = NULL;
}
}
$parser = new CRM_Activity_Import_Parser_Activity($mapperKeys, $mapperLocType, $mapperPhoneType);
$mapFields = $this->get('fields');
foreach ($mapper as $key => $value) {
$header = array();
if (isset($mapFields[$mapper[$key][0]])) {
$header[] = $mapFields[$mapper[$key][0]];
}
$mapperFields[] = implode(' - ', $header);
}
$parser->run($fileName, $seperator,
$mapperFields,
$skipColumnHeader,
CRM_Import_Parser::MODE_IMPORT,
$onDuplicate
);
// add all the necessary variables to the form
$parser->set($this, CRM_Import_Parser::MODE_IMPORT);
// check if there is any error occurred
$errorStack = CRM_Core_Error::singleton();
$errors = $errorStack->getErrors();
$errorMessage = array();
if (is_array($errors)) {
foreach ($errors as $key => $value) {
$errorMessage[] = $value['message'];
}
$errorFile = $fileName['name'] . '.error.log';
if ($fd = fopen($errorFile, 'w')) {
fwrite($fd, implode('\n', $errorMessage));
}
fclose($fd);
$this->set('errorFile', $errorFile);
$urlParams = 'type=' . CRM_Import_Parser::ERROR . '&parser=CRM_Activity_Import_Parser';
$this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
$urlParams = 'type=' . CRM_Import_Parser::CONFLICT . '&parser=CRM_Activity_Import_Parser';
$this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
$urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Activity_Import_Parser';
$this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
}
}

View file

@ -0,0 +1,110 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class summarizes the import results.
*/
class CRM_Activity_Import_Form_Summary extends CRM_Import_Form_Summary {
/**
* Set variables up before form is built.
*/
public function preProcess() {
// set the error message path to display
$this->assign('errorFile', $this->get('errorFile'));
$totalRowCount = $this->get('totalRowCount');
$relatedCount = $this->get('relatedCount');
$totalRowCount += $relatedCount;
$this->set('totalRowCount', $totalRowCount);
$invalidRowCount = $this->get('invalidRowCount');
$conflictRowCount = $this->get('conflictRowCount');
$duplicateRowCount = $this->get('duplicateRowCount');
$onDuplicate = $this->get('onDuplicate');
$mismatchCount = $this->get('unMatchCount');
if ($duplicateRowCount > 0) {
$urlParams = 'type=' . CRM_Import_Parser::DUPLICATE . '&parser=CRM_Activity_Import_Parser';
$this->set('downloadDuplicateRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
elseif ($mismatchCount) {
$urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Activity_Import_Parser';
$this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
else {
$duplicateRowCount = 0;
$this->set('duplicateRowCount', $duplicateRowCount);
}
$this->assign('dupeError', FALSE);
if ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) {
$dupeActionString = ts('These records have been updated with the imported data.');
}
elseif ($onDuplicate == CRM_Import_Parser::DUPLICATE_FILL) {
$dupeActionString = ts('These records have been filled in with the imported data.');
}
else {
// Skip by default.
$dupeActionString = ts('These records have not been imported.');
$this->assign('dupeError', TRUE);
// Only subtract dupes from successful import if we're skipping.
$this->set('validRowCount', $totalRowCount - $invalidRowCount -
$conflictRowCount - $duplicateRowCount - $mismatchCount
);
}
$this->assign('dupeActionString', $dupeActionString);
$properties = array(
'totalRowCount',
'validRowCount',
'invalidRowCount',
'conflictRowCount',
'downloadConflictRecordsUrl',
'downloadErrorRecordsUrl',
'duplicateRowCount',
'downloadDuplicateRecordsUrl',
'downloadMismatchRecordsUrl',
'groupAdditions',
'unMatchCount',
);
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
}
}
}

View file

@ -0,0 +1,398 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
abstract class CRM_Activity_Import_Parser extends CRM_Import_Parser {
protected $_fileName;
/**
* Imported file size.
*/
protected $_fileSize;
/**
* Separator being used.
*/
protected $_seperator;
/**
* Total number of lines in file.
*/
protected $_lineCount;
/**
* Whether the file has a column header or not.
*
* @var boolean
*/
protected $_haveColumnHeader;
/**
* @param string $fileName
* @param string $seperator
* @param $mapper
* @param bool $skipColumnHeader
* @param int $mode
* @param int $onDuplicate
*
* @return mixed
* @throws Exception
*/
public function run(
$fileName,
$seperator = ',',
&$mapper,
$skipColumnHeader = FALSE,
$mode = self::MODE_PREVIEW,
$onDuplicate = self::DUPLICATE_SKIP
) {
if (!is_array($fileName)) {
CRM_Core_Error::fatal();
}
$fileName = $fileName['name'];
$this->init();
$this->_haveColumnHeader = $skipColumnHeader;
$this->_seperator = $seperator;
$fd = fopen($fileName, "r");
if (!$fd) {
return FALSE;
}
$this->_lineCount = $this->_warningCount = 0;
$this->_invalidRowCount = $this->_validCount = 0;
$this->_totalCount = $this->_conflictCount = 0;
$this->_errors = array();
$this->_warnings = array();
$this->_conflicts = array();
$this->_fileSize = number_format(filesize($fileName) / 1024.0, 2);
if ($mode == self::MODE_MAPFIELD) {
$this->_rows = array();
}
else {
$this->_activeFieldCount = count($this->_activeFields);
}
while (!feof($fd)) {
$this->_lineCount++;
$values = fgetcsv($fd, 8192, $seperator);
if (!$values) {
continue;
}
self::encloseScrub($values);
// skip column header if we're not in mapfield mode
if ($mode != self::MODE_MAPFIELD && $skipColumnHeader) {
$skipColumnHeader = FALSE;
continue;
}
// Trim whitespace around the values.
$empty = TRUE;
foreach ($values as $k => $v) {
$values[$k] = trim($v, " \t\r\n");
}
if (CRM_Utils_System::isNull($values)) {
continue;
}
$this->_totalCount++;
if ($mode == self::MODE_MAPFIELD) {
$returnCode = $this->mapField($values);
}
elseif ($mode == self::MODE_PREVIEW) {
$returnCode = $this->preview($values);
}
elseif ($mode == self::MODE_SUMMARY) {
$returnCode = $this->summary($values);
}
elseif ($mode == self::MODE_IMPORT) {
$returnCode = $this->import($onDuplicate, $values);
}
else {
$returnCode = self::ERROR;
}
// note that a line could be valid but still produce a warning
if ($returnCode & self::VALID) {
$this->_validCount++;
if ($mode == self::MODE_MAPFIELD) {
$this->_rows[] = $values;
$this->_activeFieldCount = max($this->_activeFieldCount, count($values));
}
}
if ($returnCode & self::WARNING) {
$this->_warningCount++;
if ($this->_warningCount < $this->_maxWarningCount) {
$this->_warningCount[] = $line;
}
}
if ($returnCode & self::ERROR) {
$this->_invalidRowCount++;
if ($this->_invalidRowCount < $this->_maxErrorCount) {
$recordNumber = $this->_lineCount;
if ($this->_haveColumnHeader) {
$recordNumber--;
}
array_unshift($values, $recordNumber);
$this->_errors[] = $values;
}
}
if ($returnCode & self::CONFLICT) {
$this->_conflictCount++;
$recordNumber = $this->_lineCount;
if ($this->_haveColumnHeader) {
$recordNumber--;
}
array_unshift($values, $recordNumber);
$this->_conflicts[] = $values;
}
if ($returnCode & self::DUPLICATE) {
if ($returnCode & self::MULTIPLE_DUPE) {
// TODO: multi-dupes should be counted apart from singles
// on non-skip action.
}
$this->_duplicateCount++;
$recordNumber = $this->_lineCount;
if ($this->_haveColumnHeader) {
$recordNumber--;
}
array_unshift($values, $recordNumber);
$this->_duplicates[] = $values;
if ($onDuplicate != self::DUPLICATE_SKIP) {
$this->_validCount++;
}
}
// we give the derived class a way of aborting the process
// note that the return code could be multiple code or'ed together
if ($returnCode & self::STOP) {
break;
}
// if we are done processing the maxNumber of lines, break
if ($this->_maxLinesToProcess > 0 && $this->_validCount >= $this->_maxLinesToProcess) {
break;
}
}
fclose($fd);
if ($mode == self::MODE_PREVIEW || $mode == self::MODE_IMPORT) {
$customHeaders = $mapper;
$customfields = CRM_Core_BAO_CustomField::getFields('Activity');
foreach ($customHeaders as $key => $value) {
if ($id = CRM_Core_BAO_CustomField::getKeyID($value)) {
$customHeaders[$key] = $customfields[$id][0];
}
}
if ($this->_invalidRowCount) {
// removed view url for invlaid contacts
$headers = array_merge(array(
ts('Line Number'),
ts('Reason'),
),
$customHeaders
);
$this->_errorFileName = self::errorFileName(self::ERROR);
self::exportCSV($this->_errorFileName, $headers, $this->_errors);
}
if ($this->_conflictCount) {
$headers = array_merge(array(
ts('Line Number'),
ts('Reason'),
),
$customHeaders
);
$this->_conflictFileName = self::errorFileName(self::CONFLICT);
self::exportCSV($this->_conflictFileName, $headers, $this->_conflicts);
}
if ($this->_duplicateCount) {
$headers = array_merge(array(
ts('Line Number'),
ts('View Activity History URL'),
),
$customHeaders
);
$this->_duplicateFileName = self::errorFileName(self::DUPLICATE);
self::exportCSV($this->_duplicateFileName, $headers, $this->_duplicates);
}
}
return $this->fini();
}
/**
* Given a list of the importable field keys that the user has selected set the active fields array to this list.
*
* @param array $fieldKeys
*/
public function setActiveFields($fieldKeys) {
$this->_activeFieldCount = count($fieldKeys);
foreach ($fieldKeys as $key) {
if (empty($this->_fields[$key])) {
$this->_activeFields[] = new CRM_Activity_Import_Field('', ts('- do not import -'));
}
else {
$this->_activeFields[] = clone($this->_fields[$key]);
}
}
}
/**
* Format the field values for input to the api.
*
* @return array
* (reference ) associative array of name/value pairs
*/
public function &getActiveFieldParams() {
$params = array();
for ($i = 0; $i < $this->_activeFieldCount; $i++) {
if (isset($this->_activeFields[$i]->_value)
&& !isset($params[$this->_activeFields[$i]->_name])
&& !isset($this->_activeFields[$i]->_related)
) {
$params[$this->_activeFields[$i]->_name] = $this->_activeFields[$i]->_value;
}
}
return $params;
}
/**
* @param string $name
* @param $title
* @param int $type
* @param string $headerPattern
* @param string $dataPattern
*/
public function addField($name, $title, $type = CRM_Utils_Type::T_INT, $headerPattern = '//', $dataPattern = '//') {
if (empty($name)) {
$this->_fields['doNotImport'] = new CRM_Activity_Import_Field($name, $title, $type, $headerPattern, $dataPattern);
}
else {
$tempField = CRM_Contact_BAO_Contact::importableFields('Individual', NULL);
if (!array_key_exists($name, $tempField)) {
$this->_fields[$name] = new CRM_Activity_Import_Field($name, $title, $type, $headerPattern, $dataPattern);
}
else {
$this->_fields[$name] = new CRM_Contact_Import_Field($name, $title, $type, $headerPattern, $dataPattern, CRM_Utils_Array::value('hasLocationType', $tempField[$name]));
}
}
}
/**
* Store parser values.
*
* @param CRM_Core_Session $store
*
* @param int $mode
*/
public function set($store, $mode = self::MODE_SUMMARY) {
$store->set('fileSize', $this->_fileSize);
$store->set('lineCount', $this->_lineCount);
$store->set('seperator', $this->_seperator);
$store->set('fields', $this->getSelectValues());
$store->set('fieldTypes', $this->getSelectTypes());
$store->set('headerPatterns', $this->getHeaderPatterns());
$store->set('dataPatterns', $this->getDataPatterns());
$store->set('columnCount', $this->_activeFieldCount);
$store->set('totalRowCount', $this->_totalCount);
$store->set('validRowCount', $this->_validCount);
$store->set('invalidRowCount', $this->_invalidRowCount);
$store->set('conflictRowCount', $this->_conflictCount);
if ($this->_invalidRowCount) {
$store->set('errorsFileName', $this->_errorFileName);
}
if ($this->_conflictCount) {
$store->set('conflictsFileName', $this->_conflictFileName);
}
if (isset($this->_rows) && !empty($this->_rows)) {
$store->set('dataValues', $this->_rows);
}
if ($mode == self::MODE_IMPORT) {
$store->set('duplicateRowCount', $this->_duplicateCount);
if ($this->_duplicateCount) {
$store->set('duplicatesFileName', $this->_duplicateFileName);
}
}
}
/**
* Export data to a CSV file.
*
* @param string $fileName
* @param array $header
* @param array $data
*/
public static function exportCSV($fileName, $header, $data) {
$output = array();
$fd = fopen($fileName, 'w');
foreach ($header as $key => $value) {
$header[$key] = "\"$value\"";
}
$config = CRM_Core_Config::singleton();
$output[] = implode($config->fieldSeparator, $header);
foreach ($data as $datum) {
foreach ($datum as $key => $value) {
$datum[$key] = "\"$value\"";
}
$output[] = implode($config->fieldSeparator, $datum);
}
fwrite($fd, implode("\n", $output));
fclose($fd);
}
}

View file

@ -0,0 +1,400 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Class to parse activity csv files.
*/
class CRM_Activity_Import_Parser_Activity extends CRM_Activity_Import_Parser {
protected $_mapperKeys;
private $_contactIdIndex;
private $_activityTypeIndex;
private $_activityLabelIndex;
private $_activityDateIndex;
/**
* Array of successfully imported activity id's
*
* @array
*/
protected $_newActivity;
/**
* Class constructor.
*
* @param array $mapperKeys
* @param int $mapperLocType
* @param int $mapperPhoneType
*/
public function __construct(&$mapperKeys, $mapperLocType = NULL, $mapperPhoneType = NULL) {
parent::__construct();
$this->_mapperKeys = &$mapperKeys;
}
/**
* Function of undocumented functionality required by the interface.
*/
protected function fini() {}
/**
* The initializer code, called before the processing.
*/
public function init() {
$activityContact = CRM_Activity_BAO_ActivityContact::import();
$activityTarget['target_contact_id'] = $activityContact['contact_id'];
$fields = array_merge(CRM_Activity_BAO_Activity::importableFields(),
$activityTarget
);
$fields = array_merge($fields, array(
'source_contact_id' => array(
'title' => ts('Source Contact'),
'headerPattern' => '/Source.Contact?/i',
),
'activity_label' => array(
'title' => ts('Activity Type Label'),
'headerPattern' => '/(activity.)?type label?/i',
),
));
foreach ($fields as $name => $field) {
$field['type'] = CRM_Utils_Array::value('type', $field, CRM_Utils_Type::T_INT);
$field['dataPattern'] = CRM_Utils_Array::value('dataPattern', $field, '//');
$field['headerPattern'] = CRM_Utils_Array::value('headerPattern', $field, '//');
$this->addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern']);
}
$this->_newActivity = array();
$this->setActiveFields($this->_mapperKeys);
// FIXME: we should do this in one place together with Form/MapField.php
$this->_contactIdIndex = -1;
$this->_activityTypeIndex = -1;
$this->_activityLabelIndex = -1;
$this->_activityDateIndex = -1;
$index = 0;
foreach ($this->_mapperKeys as $key) {
switch ($key) {
case 'target_contact_id':
case 'external_identifier':
$this->_contactIdIndex = $index;
break;
case 'activity_label':
$this->_activityLabelIndex = $index;
break;
case 'activity_type_id':
$this->_activityTypeIndex = $index;
break;
case 'activity_date_time':
$this->_activityDateIndex = $index;
break;
}
$index++;
}
}
/**
* Handle the values in mapField mode.
*
* @param array $values
* The array of values belonging to this line.
*
* @return bool
*/
public function mapField(&$values) {
return CRM_Import_Parser::VALID;
}
/**
* Handle the values in preview mode.
*
* @param array $values
* The array of values belonging to this line.
*
* @return bool
* the result of this processing
*/
public function preview(&$values) {
return $this->summary($values);
}
/**
* Handle the values in summary mode.
*
* @param array $values
* The array of values belonging to this line.
*
* @return bool
* the result of this processing
*/
public function summary(&$values) {
$erroneousField = NULL;
$this->setActiveFieldValues($values, $erroneousField);
$index = -1;
if ($this->_activityTypeIndex > -1 && $this->_activityLabelIndex > -1) {
array_unshift($values, ts('Please select either Activity Type ID OR Activity Type Label.'));
return CRM_Import_Parser::ERROR;
}
elseif ($this->_activityLabelIndex > -1) {
$index = $this->_activityLabelIndex;
}
elseif ($this->_activityTypeIndex > -1) {
$index = $this->_activityTypeIndex;
}
if ($index < 0 or $this->_activityDateIndex < 0) {
$errorRequired = TRUE;
}
else {
$errorRequired = !CRM_Utils_Array::value($index, $values) || !CRM_Utils_Array::value($this->_activityDateIndex, $values);
}
if ($errorRequired) {
array_unshift($values, ts('Missing required fields'));
return CRM_Import_Parser::ERROR;
}
$params = &$this->getActiveFieldParams();
$errorMessage = NULL;
// For date-Formats
$session = CRM_Core_Session::singleton();
$dateType = $session->get('dateTypes');
if (!isset($params['source_contact_id'])) {
$params['source_contact_id'] = $session->get('userID');
}
foreach ($params as $key => $val) {
if ($key == 'activity_date_time') {
if ($val) {
$dateValue = CRM_Utils_Date::formatDate($val, $dateType);
if ($dateValue) {
$params[$key] = $dateValue;
}
else {
CRM_Contact_Import_Parser_Contact::addToErrorMsg('Activity date', $errorMessage);
}
}
}
elseif ($key == 'activity_engagement_level' && $val &&
!CRM_Utils_Rule::positiveInteger($val)
) {
CRM_Contact_Import_Parser_Contact::addToErrorMsg('Activity Engagement Index', $errorMessage);
}
}
// Date-Format part ends.
// Checking error in custom data.
$params['contact_type'] = isset($this->_contactType) ? $this->_contactType : 'Activity';
CRM_Contact_Import_Parser_Contact::isErrorInCustomData($params, $errorMessage);
if ($errorMessage) {
$tempMsg = "Invalid value for field(s) : $errorMessage";
array_unshift($values, $tempMsg);
$errorMessage = NULL;
return CRM_Import_Parser::ERROR;
}
return CRM_Import_Parser::VALID;
}
/**
* Handle the values in import mode.
*
* @param int $onDuplicate
* The code for what action to take on duplicates.
* @param array $values
* The array of values belonging to this line.
*
* @return bool
* the result of this processing
*/
public function import($onDuplicate, &$values) {
// First make sure this is a valid line
$response = $this->summary($values);
if ($response != CRM_Import_Parser::VALID) {
return $response;
}
$params = &$this->getActiveFieldParams();
$activityLabel = array_search('activity_label', $this->_mapperKeys);
if ($activityLabel) {
$params = array_merge($params, array('activity_label' => $values[$activityLabel]));
}
// For date-Formats.
$session = CRM_Core_Session::singleton();
$dateType = $session->get('dateTypes');
if (!isset($params['source_contact_id'])) {
$params['source_contact_id'] = $session->get('userID');
}
$customFields = CRM_Core_BAO_CustomField::getFields('Activity');
foreach ($params as $key => $val) {
if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
if ($key == 'activity_date_time' && $val) {
$params[$key] = CRM_Utils_Date::formatDate($val, $dateType);
}
elseif (!empty($customFields[$customFieldID]) && $customFields[$customFieldID]['data_type'] == 'Date') {
CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $params, $dateType, $key);
}
elseif (!empty($customFields[$customFieldID]) && $customFields[$customFieldID]['data_type'] == 'Boolean') {
$params[$key] = CRM_Utils_String::strtoboolstr($val);
}
}
elseif ($key == 'activity_date_time') {
$params[$key] = CRM_Utils_Date::formatDate($val, $dateType);
}
elseif ($key == 'activity_subject') {
$params['subject'] = $val;
}
}
// Date-Format part ends.
require_once 'CRM/Utils/DeprecatedUtils.php';
$formatError = _civicrm_api3_deprecated_activity_formatted_param($params, $params, TRUE);
if ($formatError) {
array_unshift($values, $formatError['error_message']);
return CRM_Import_Parser::ERROR;
}
$params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
NULL,
'Activity'
);
if ($this->_contactIdIndex < 0) {
// Retrieve contact id using contact dedupe rule.
// Since we are supporting only individual's activity import.
$params['contact_type'] = 'Individual';
$params['version'] = 3;
$error = _civicrm_api3_deprecated_duplicate_formatted_contact($params);
if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
$matchedIDs = explode(',', $error['error_message']['params'][0]);
if (count($matchedIDs) > 1) {
array_unshift($values, 'Multiple matching contact records detected for this row. The activity was not imported');
return CRM_Import_Parser::ERROR;
}
else {
$cid = $matchedIDs[0];
$params['target_contact_id'] = $cid;
$params['version'] = 3;
$newActivity = civicrm_api('activity', 'create', $params);
if (!empty($newActivity['is_error'])) {
array_unshift($values, $newActivity['error_message']);
return CRM_Import_Parser::ERROR;
}
$this->_newActivity[] = $newActivity['id'];
return CRM_Import_Parser::VALID;
}
}
else {
// Using new Dedupe rule.
$ruleParams = array(
'contact_type' => 'Individual',
'used' => 'Unsupervised',
);
$fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
$disp = NULL;
foreach ($fieldsArray as $value) {
if (array_key_exists(trim($value), $params)) {
$paramValue = $params[trim($value)];
if (is_array($paramValue)) {
$disp .= $params[trim($value)][0][trim($value)] . " ";
}
else {
$disp .= $params[trim($value)] . " ";
}
}
}
if (!empty($params['external_identifier'])) {
if ($disp) {
$disp .= "AND {$params['external_identifier']}";
}
else {
$disp = $params['external_identifier'];
}
}
array_unshift($values, 'No matching Contact found for (' . $disp . ')');
return CRM_Import_Parser::ERROR;
}
}
else {
if (!empty($params['external_identifier'])) {
$targetContactId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
$params['external_identifier'], 'id', 'external_identifier'
);
if (!empty($params['target_contact_id']) &&
$params['target_contact_id'] != $targetContactId
) {
array_unshift($values, 'Mismatch of External ID:' . $params['external_identifier'] . ' and Contact Id:' . $params['target_contact_id']);
return CRM_Import_Parser::ERROR;
}
elseif ($targetContactId) {
$params['target_contact_id'] = $targetContactId;
}
else {
array_unshift($values, 'No Matching Contact for External ID:' . $params['external_identifier']);
return CRM_Import_Parser::ERROR;
}
}
$params['version'] = 3;
$newActivity = civicrm_api('activity', 'create', $params);
if (!empty($newActivity['is_error'])) {
array_unshift($values, $newActivity['error_message']);
return CRM_Import_Parser::ERROR;
}
$this->_newActivity[] = $newActivity['id'];
return CRM_Import_Parser::VALID;
}
}
}

View file

@ -0,0 +1,469 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
*/
/**
* This class contains all the function that are called using AJAX (jQuery)
*/
class CRM_Activity_Page_AJAX {
public static function getCaseActivity() {
// Should those params be passed through the validateParams method?
$caseID = CRM_Utils_Type::validate($_GET['caseID'], 'Integer');
$contactID = CRM_Utils_Type::validate($_GET['cid'], 'Integer');
$userID = CRM_Utils_Type::validate($_GET['userID'], 'Integer');
$context = CRM_Utils_Type::validate(CRM_Utils_Array::value('context', $_GET), 'String');
$optionalParameters = array(
'source_contact_id' => 'Integer',
'status_id' => 'Integer',
'activity_deleted' => 'Boolean',
'activity_type_id' => 'Integer',
'activity_date_low' => 'Date',
'activity_date_high' => 'Date',
);
$params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
$params += CRM_Core_Page_AJAX::validateParams(array(), $optionalParameters);
// get the activities related to given case
$activities = CRM_Case_BAO_Case::getCaseActivity($caseID, $params, $contactID, $context, $userID);
CRM_Utils_JSON::output($activities);
}
public static function getCaseGlobalRelationships() {
$params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
// get the activities related to given case
$globalGroupInfo = array();
// get the total row count
CRM_Case_BAO_Case::getGlobalContacts($globalGroupInfo, NULL, FALSE, TRUE, NULL, NULL);
// limit the rows
$relGlobal = CRM_Case_BAO_Case::getGlobalContacts($globalGroupInfo, $params['sortBy'], $showLinks = TRUE, FALSE, $params['offset'], $params['rp']);
$relationships = array();
// after sort we can update username fields to be a url
foreach ($relGlobal as $key => $value) {
$relationship = array();
$relationship['sort_name'] = $value['sort_name'];
$relationship['phone'] = $value['phone'];
$relationship['email'] = $value['email'];
array_push($relationships, $relationship);
}
$globalRelationshipsDT = array();
$globalRelationshipsDT['data'] = $relationships;
$globalRelationshipsDT['recordsTotal'] = count($relationships);
$globalRelationshipsDT['recordsFiltered'] = count($relationships);
CRM_Utils_JSON::output($globalRelationshipsDT);
}
public static function getCaseClientRelationships() {
$caseID = CRM_Utils_Type::escape($_GET['caseID'], 'Integer');
$contactID = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
$params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
// Retrieve ALL client relationships
$relClient = CRM_Contact_BAO_Relationship::getRelationship($contactID,
CRM_Contact_BAO_Relationship::CURRENT,
0, 0, 0, NULL, NULL, FALSE
);
$caseRelationships = CRM_Case_BAO_Case::getCaseRoles($contactID, $caseID);
// Now build 'Other Relationships' array by removing relationships that are already listed under Case Roles
// so they don't show up twice.
$clientRelationships = array();
foreach ($relClient as $r) {
if (!array_key_exists($r['id'], $caseRelationships)) {
$clientRelationships[] = $r;
}
}
// sort clientRelationships array using jquery call params
foreach ($clientRelationships as $key => $row) {
$sortArray[$key] = $row[$params['_raw_values']['sort'][0]];
}
$sort_type = "SORT_" . strtoupper($params['_raw_values']['order'][0]);
array_multisort($sortArray, constant($sort_type), $clientRelationships);
$relationships = array();
// after sort we can update username fields to be a url
foreach ($clientRelationships as $key => $value) {
$relationship = array();
$relationship['relation'] = $value['relation'];
$relationship['name'] = '<a href=' . CRM_Utils_System::url('civicrm/contact/view',
'action=view&reset=1&cid=' . $clientRelationships[$key]['cid']) . '>' . $clientRelationships[$key]['name'] . '</a>';
$relationship['phone'] = $value['phone'];
$relationship['email'] = $value['email'];
array_push($relationships, $relationship);
}
$clientRelationshipsDT = array();
$clientRelationshipsDT['data'] = $relationships;
$clientRelationshipsDT['recordsTotal'] = count($relationships);
$clientRelationshipsDT['recordsFiltered'] = count($relationships);
CRM_Utils_JSON::output($clientRelationshipsDT);
}
public static function getCaseRoles() {
$caseID = CRM_Utils_Type::escape($_GET['caseID'], 'Integer');
$contactID = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
$params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
$caseRelationships = CRM_Case_BAO_Case::getCaseRoles($contactID, $caseID);
$caseTypeName = CRM_Case_BAO_Case::getCaseType($caseID, 'name');
$xmlProcessor = new CRM_Case_XMLProcessor_Process();
$caseRoles = $xmlProcessor->get($caseTypeName, 'CaseRoles');
$hasAccessToAllCases = CRM_Core_Permission::check('access all cases and activities');
$managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseTypeName);
foreach ($caseRelationships as $key => $value) {
// This role has been filled
unset($caseRoles[$value['relation_type']]);
// mark original case relationships record to use on setting edit links below
$caseRelationships[$key]['source'] = 'caseRel';
}
$caseRoles['client'] = CRM_Case_BAO_Case::getContactNames($caseID);
// move/transform caseRoles array data to caseRelationships
// for sorting and display
// CRM-14466 added cid to the non-client array to avoid php notice
foreach ($caseRoles as $id => $value) {
if ($id != "client") {
$rel = array();
$rel['relation'] = $value;
$rel['relation_type'] = $id;
$rel['name'] = '(not assigned)';
$rel['phone'] = '';
$rel['email'] = '';
$rel['source'] = 'caseRoles';
$caseRelationships[] = $rel;
}
else {
foreach ($value as $clientRole) {
$relClient = array();
$relClient['relation'] = 'Client';
$relClient['name'] = $clientRole['sort_name'];
$relClient['phone'] = $clientRole['phone'];
$relClient['email'] = $clientRole['email'];
$relClient['cid'] = $clientRole['contact_id'];
$relClient['source'] = 'contact';
$caseRelationships[] = $relClient;
}
}
}
// sort clientRelationships array using jquery call params
foreach ($caseRelationships as $key => $row) {
$sortArray[$key] = $row[$params['_raw_values']['sort'][0]];
}
$sort_type = "SORT_" . strtoupper($params['_raw_values']['order'][0]);
array_multisort($sortArray, constant($sort_type), $caseRelationships);
$relationships = array();
// set user name, email and edit columns links
foreach ($caseRelationships as $key => &$row) {
$typeLabel = $row['relation'];
// Add "<br />(Case Manager)" to label
if (!empty($row['relation_type']) && $row['relation_type'] == $managerRoleId) {
$row['relation'] .= '<br />' . '(' . ts('Case Manager') . ')';
}
// view user links
if (!empty($row['cid'])) {
$row['name'] = '<a class="view-contact" title="' . ts('View Contact') . '" href=' . CRM_Utils_System::url('civicrm/contact/view',
'action=view&reset=1&cid=' . $row['cid']) . '>' . $row['name'] . '</a>';
}
// email column links/icon
if ($row['email']) {
$row['email'] = '<a class="crm-hover-button crm-popup" href="' . CRM_Utils_System::url('civicrm/activity/email/add', 'reset=1&action=add&atype=3&cid=' . $row['cid']) . '&caseid=' . $caseID . '" title="' . ts('Send an Email') . '"><i class="crm-i fa-envelope"></i></a>';
}
// edit links
$row['actions'] = '';
if ($hasAccessToAllCases) {
$contactType = empty($row['relation_type']) ? '' : (string) CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', $row['relation_type'], 'contact_type_b');
$contactType = $contactType == 'Contact' ? '' : $contactType;
switch ($row['source']) {
case 'caseRel':
$row['actions'] = '<a href="#editCaseRoleDialog" title="' . ts('Reassign %1', array(1 => $typeLabel)) . '" class="crm-hover-button case-miniform" data-contact_type="' . $contactType . '" data-rel_type="' . $row['relation_type'] . '_' . $row['relationship_direction'] . '" data-cid="' . $row['cid'] . '" data-rel_id="' . $row['rel_id'] . '"data-key="' . CRM_Core_Key::get('civicrm/ajax/relation') . '">' .
'<i class="crm-i fa-pencil"></i>' .
'</a>' .
'<a href="#deleteCaseRoleDialog" title="' . ts('Remove %1', array(1 => $typeLabel)) . '" class="crm-hover-button case-miniform" data-contact_type="' . $contactType . '" data-rel_type="' . $row['relation_type'] . '_' . $row['relationship_direction'] . '" data-cid="' . $row['cid'] . '" data-key="' . CRM_Core_Key::get('civicrm/ajax/delcaserole') . '">' .
'<span class="icon delete-icon"></span>' .
'</a>';
break;
case 'caseRoles':
$row['actions'] = '<a href="#editCaseRoleDialog" title="' . ts('Assign %1', array(1 => $typeLabel)) . '" class="crm-hover-button case-miniform" data-contact_type="' . $contactType . '" data-rel_type="' . $row['relation_type'] . '_a_b" data-key="' . CRM_Core_Key::get('civicrm/ajax/relation') . '">' .
'<i class="crm-i fa-pencil"></i>' .
'</a>';
break;
}
}
unset($row['cid']);
unset($row['relation_type']);
unset($row['rel_id']);
unset($row['client_id']);
unset($row['source']);
array_push($relationships, $row);
}
$params['total'] = count($relationships);
$caseRelationshipsDT = array();
$caseRelationshipsDT['data'] = $relationships;
$caseRelationshipsDT['recordsTotal'] = $params['total'];
$caseRelationshipsDT['recordsFiltered'] = $params['total'];
CRM_Utils_JSON::output($caseRelationshipsDT);
}
public static function convertToCaseActivity() {
$params = array('caseID', 'activityID', 'contactID', 'newSubject', 'targetContactIds', 'mode');
$vals = array();
foreach ($params as $param) {
$vals[$param] = CRM_Utils_Array::value($param, $_POST);
}
CRM_Utils_JSON::output(self::_convertToCaseActivity($vals));
}
/**
* @param array $params
*
* @return array
*/
public static function _convertToCaseActivity($params) {
if (!$params['activityID'] || !$params['caseID']) {
return (array('error_msg' => 'required params missing.'));
}
$otherActivity = new CRM_Activity_DAO_Activity();
$otherActivity->id = $params['activityID'];
if (!$otherActivity->find(TRUE)) {
return (array('error_msg' => 'activity record is missing.'));
}
$actDateTime = CRM_Utils_Date::isoToMysql($otherActivity->activity_date_time);
// Create new activity record.
$mainActivity = new CRM_Activity_DAO_Activity();
$mainActVals = array();
CRM_Core_DAO::storeValues($otherActivity, $mainActVals);
// Get new activity subject.
if (!empty($params['newSubject'])) {
$mainActVals['subject'] = $params['newSubject'];
}
$mainActivity->copyValues($mainActVals);
$mainActivity->id = NULL;
$mainActivity->activity_date_time = $actDateTime;
// Make sure this is current revision.
$mainActivity->is_current_revision = TRUE;
// Drop all relations.
$mainActivity->parent_id = $mainActivity->original_id = NULL;
$mainActivity->save();
$mainActivityId = $mainActivity->id;
CRM_Activity_BAO_Activity::logActivityAction($mainActivity);
$mainActivity->free();
// Mark previous activity as deleted. If it was a non-case activity
// then just change the subject.
if (in_array($params['mode'], array(
'move',
'file',
))) {
$caseActivity = new CRM_Case_DAO_CaseActivity();
$caseActivity->case_id = $params['caseID'];
$caseActivity->activity_id = $otherActivity->id;
if ($params['mode'] == 'move' || $caseActivity->find(TRUE)) {
$otherActivity->is_deleted = 1;
}
else {
$otherActivity->subject = ts('(Filed on case %1)', array(
1 => $params['caseID'],
)) . ' ' . $otherActivity->subject;
}
$otherActivity->activity_date_time = $actDateTime;
$otherActivity->save();
$caseActivity->free();
}
$otherActivity->free();
$targetContacts = array();
if (!empty($params['targetContactIds'])) {
$targetContacts = array_unique(explode(',', $params['targetContactIds']));
}
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
$targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
$sourceContactID = CRM_Activity_BAO_Activity::getSourceContactID($params['activityID']);
$src_params = array(
'activity_id' => $mainActivityId,
'contact_id' => $sourceContactID,
'record_type_id' => $sourceID,
);
CRM_Activity_BAO_ActivityContact::create($src_params);
foreach ($targetContacts as $key => $value) {
$targ_params = array(
'activity_id' => $mainActivityId,
'contact_id' => $value,
'record_type_id' => $targetID,
);
CRM_Activity_BAO_ActivityContact::create($targ_params);
}
//CRM-21114 retrieve assignee contacts from original case; allow overriding from params
$assigneeContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($params['activityID'], $assigneeID);
if (!empty($params['assigneeContactIds'])) {
$assigneeContacts = array_unique(explode(',', $params['assigneeContactIds']));
}
foreach ($assigneeContacts as $key => $value) {
$assigneeParams = array(
'activity_id' => $mainActivityId,
'contact_id' => $value,
'record_type_id' => $assigneeID,
);
CRM_Activity_BAO_ActivityContact::create($assigneeParams);
}
// Attach newly created activity to case.
$caseActivity = new CRM_Case_DAO_CaseActivity();
$caseActivity->case_id = $params['caseID'];
$caseActivity->activity_id = $mainActivityId;
$caseActivity->save();
$error_msg = $caseActivity->_lastError;
$caseActivity->free();
$params['mainActivityId'] = $mainActivityId;
CRM_Activity_BAO_Activity::copyExtendedActivityData($params);
return (array('error_msg' => $error_msg, 'newId' => $mainActivity->id));
}
/**
* Get activities for the contact.
*
* @return array
*/
public static function getContactActivity() {
$requiredParameters = array(
'cid' => 'Integer',
);
$optionalParameters = array(
'context' => 'String',
'activity_type_id' => 'Integer',
'activity_type_exclude_id' => 'Integer',
'activity_status_id' => 'String',
'activity_date_relative' => 'String',
'activity_date_low' => 'String',
'activity_date_high' => 'String',
);
$params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
$params += CRM_Core_Page_AJAX::validateParams($requiredParameters, $optionalParameters);
// To be consistent, the cid parameter should be renamed to contact_id in
// the template file, see templates/CRM/Activity/Selector/Selector.tpl
$params['contact_id'] = $params['cid'];
unset($params['cid']);
// get the contact activities
$activities = CRM_Activity_BAO_Activity::getContactActivitySelector($params);
foreach ($activities['data'] as $key => $value) {
// Check if recurring activity.
if (!empty($value['is_recurring_activity'])) {
$repeat = $value['is_recurring_activity'];
$activities['data'][$key]['activity_type'] .= '<br/><span class="bold">' . ts('Repeating (%1 of %2)', array(1 => $repeat[0], 2 => $repeat[1])) . '</span>';
}
}
// store the activity filter preference CRM-11761
if (Civi::settings()->get('preserve_activity_tab_filter') && ($userID = CRM_Core_Session::getLoggedInContactID())) {
unset($optionalParameters['context']);
foreach ($optionalParameters as $searchField => $dataType) {
$formSearchField = $searchField;
if ($searchField == 'activity_type_id') {
$formSearchField = 'activity_type_filter_id';
}
elseif ($searchField == 'activity_type_exclude_id') {
$formSearchField = 'activity_type_exclude_filter_id';
}
if (!empty($params[$searchField])) {
$activityFilter[$formSearchField] = CRM_Utils_Type::escape($params[$searchField], $dataType);
if (in_array($searchField, array('activity_date_low', 'activity_date_high'))) {
$activityFilter['activity_date_relative'] = 0;
}
elseif ($searchField == 'activity_status_id') {
$activityFilter['status_id'] = explode(',', $activityFilter[$searchField]);
}
}
elseif (in_array($searchField, array('activity_type_id', 'activity_type_exclude_id'))) {
$activityFilter[$formSearchField] = '';
}
}
/**
* @var \Civi\Core\SettingsBag $cSettings
*/
$cSettings = Civi::service('settings_manager')->getBagByContact(CRM_Core_Config::domainID(), $userID);
$cSettings->set('activity_tab_filter', $activityFilter);
}
if (!empty($_GET['is_unit_test'])) {
return array($activities, $activityFilter);
}
CRM_Utils_JSON::output($activities);
}
}

View file

@ -0,0 +1,219 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Main page for viewing activities,
*/
class CRM_Activity_Page_Tab extends CRM_Core_Page {
/**
* Browse all activities for a particular contact.
*/
public function browse() {
$this->assign('admin', FALSE);
$this->assign('context', 'activity');
// also create the form element for the activity filter box
$controller = new CRM_Core_Controller_Simple(
'CRM_Activity_Form_ActivityFilter',
ts('Activity Filter'),
NULL,
FALSE, FALSE, TRUE
);
$controller->set('contactId', $this->_contactId);
$controller->setEmbedded(TRUE);
$controller->run();
$this->ajaxResponse['tabCount'] = CRM_Contact_BAO_Contact::getCountComponent('activity', $this->_contactId);
}
/**
* Edit tab.
*
* @return mixed
*/
public function edit() {
// used for ajax tabs
$context = CRM_Utils_Request::retrieve('context', 'String', $this);
$this->assign('context', $context);
$this->_id = CRM_Utils_Request::retrieve('id', 'Integer', $this);
$this->_caseId = CRM_Utils_Request::retrieve('caseid', 'Integer', $this);
$activityTypeId = CRM_Utils_Request::retrieve('atype', 'Positive', $this);
// Email and Create Letter activities use a different form class
$emailTypeValue = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
'activity_type_id',
'Email'
);
$letterTypeValue = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
'activity_type_id',
'Print PDF Letter'
);
switch ($activityTypeId) {
case $emailTypeValue:
$wrapper = new CRM_Utils_Wrapper();
$arguments = array('attachUpload' => 1);
return $wrapper->run('CRM_Contact_Form_Task_Email', ts('Email a Contact'), $arguments);
case $letterTypeValue:
$wrapper = new CRM_Utils_Wrapper();
$arguments = array('attachUpload' => 1);
return $wrapper->run('CRM_Contact_Form_Task_PDF', ts('Create PDF Letter'), $arguments);
default:
$controller = new CRM_Core_Controller_Simple('CRM_Activity_Form_Activity',
ts('Contact Activities'),
$this->_action,
FALSE, FALSE, FALSE, TRUE
);
}
$controller->setEmbedded(TRUE);
$controller->set('contactId', $this->_contactId);
$controller->set('atype', $activityTypeId);
$controller->set('id', $this->_id);
$controller->set('pid', $this->get('pid'));
$controller->set('action', $this->_action);
$controller->set('context', $context);
$controller->process();
$controller->run();
}
/**
* Heart of the viewing process.
*
* The runner gets all the meta data for the contact and calls the appropriate type of page to view.
*/
public function preProcess() {
$this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
$this->assign('contactId', $this->_contactId);
// FIXME: need to fix this conflict
$this->assign('contactID', $this->_contactId);
// check logged in url permission
CRM_Contact_Page_View::checkUserPermission($this);
$this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
$this->assign('action', $this->_action);
// also create the form element for the activity links box
$controller = new CRM_Core_Controller_Simple(
'CRM_Activity_Form_ActivityLinks',
ts('Activity Links'),
NULL,
FALSE, FALSE, TRUE
);
$controller->setEmbedded(TRUE);
$controller->run();
}
public function delete() {
$controller = new CRM_Core_Controller_Simple(
'CRM_Activity_Form_Activity',
ts('Activity Record'),
$this->_action
);
$controller->set('id', $this->_id);
$controller->setEmbedded(TRUE);
$controller->process();
$controller->run();
}
/**
* Perform actions and display for activities.
*/
public function run() {
$context = CRM_Utils_Request::retrieve('context', 'String', $this);
$contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
$action = CRM_Utils_Request::retrieve('action', 'String', $this);
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
// Do check for view/edit operation.
if ($this->_id &&
in_array($action, array(CRM_Core_Action::UPDATE, CRM_Core_Action::VIEW))
) {
if (!CRM_Activity_BAO_Activity::checkPermission($this->_id, $action)) {
CRM_Core_Error::fatal(ts('You are not authorized to access this page.'));
}
}
if ($context == 'standalone' || (!$contactId && ($action != CRM_Core_Action::DELETE) && !$this->_id)) {
$this->_action = CRM_Core_Action::ADD;
$this->assign('action', $this->_action);
}
else {
// we should call contact view, preprocess only for activity in contact summary
$this->preProcess();
}
// route behaviour of contact/view/activity based on action defined
if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD | CRM_Core_Action::VIEW)
) {
$this->edit();
$activityTypeId = CRM_Utils_Request::retrieve('atype', 'Positive', $this);
// Email and Create Letter activities use a different form class
$emailTypeValue = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
'activity_type_id',
'Email'
);
$letterTypeValue = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
'activity_type_id',
'Print PDF Letter'
);
if (in_array($activityTypeId, array(
$emailTypeValue,
$letterTypeValue,
))) {
return;
}
}
elseif ($this->_action & (CRM_Core_Action::DELETE | CRM_Core_Action::DETACH)) {
$this->delete();
}
else {
$this->browse();
}
return parent::run();
}
}

View file

@ -0,0 +1,76 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class is for building event(participation) block on user dashboard.
*/
class CRM_Activity_Page_UserDashboard extends CRM_Contact_Page_View_UserDashBoard {
/**
* List participations for the UF user.
*
* @return bool
*/
public function listActivities() {
$controller
= new CRM_Core_Controller_Simple(
'CRM_Activity_Form_Search', ts('Activities'),
NULL,
FALSE, FALSE, TRUE, FALSE
);
$controller->setEmbedded(TRUE);
$controller->reset();
$controller->set('context', 'user');
$controller->set('cid', $this->_contactId);
// Limit to status "Scheduled" and "Available"
$controller->set('status', array('IN' => array(1, 7)));
$controller->set('activity_role', 2);
$controller->set('force', 1);
$controller->process();
$controller->run();
return FALSE;
}
/**
* The main function that is called when the page loads.
*
* It decides the which action has to be taken for the page.
*/
public function run() {
parent::preProcess();
$this->listActivities();
}
}

View file

@ -0,0 +1,546 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class is used to retrieve and display activities for a contact.
*/
class CRM_Activity_Selector_Activity extends CRM_Core_Selector_Base implements CRM_Core_Selector_API {
/**
* We use desc to remind us what that column is, name is used in the tpl
*
* @var array
*/
static $_columnHeaders;
/**
* ContactId - contact id of contact whose activies are displayed
*
* @var int
*/
protected $_contactId;
protected $_admin;
protected $_context;
protected $_activityTypeIDs;
protected $_viewOptions;
/**
* Class constructor.
*
* @param int $contactId
* Contact whose activities we want to display.
* @param int $permission
* The permission we have for this contact.
*
* @param bool $admin
* @param string $context
* @param null $activityTypeIDs
*
* @return \CRM_Activity_Selector_Activity
*/
public function __construct(
$contactId,
$permission,
$admin = FALSE,
$context = 'activity',
$activityTypeIDs = NULL) {
$this->_contactId = $contactId;
$this->_permission = $permission;
$this->_admin = $admin;
$this->_context = $context;
$this->_activityTypeIDs = $activityTypeIDs;
// get all enabled view componentc (check if case is enabled)
$this->_viewOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'contact_view_options', TRUE, NULL, TRUE
);
}
/**
* This method returns the action links that are given for each search row.
* currently the action links added for each row are
*
* - View
*
* @param int $activityTypeId
* @param int $sourceRecordId
* @param bool $accessMailingReport
* @param int $activityId
* @param null $key
* @param null $compContext
*
* @return array
*/
public static function actionLinks(
$activityTypeId,
$sourceRecordId = NULL,
$accessMailingReport = FALSE,
$activityId = NULL,
$key = NULL,
$compContext = NULL) {
static $activityActTypes = NULL;
//CRM-14277 added addtitional param to handle activity search
$extraParams = "&searchContext=activity";
$extraParams .= ($key) ? "&key={$key}" : NULL;
if ($compContext) {
$extraParams .= "&compContext={$compContext}";
}
$showView = TRUE;
$showUpdate = $showDelete = FALSE;
$qsUpdate = NULL;
if (!$activityActTypes) {
$activeActTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name', TRUE);
}
$activityTypeName = CRM_Utils_Array::value($activityTypeId, $activeActTypes);
// CRM-7607
// Lets allow to have normal operation for only activity types.
// When activity type is disabled or no more exists give only delete.
switch ($activityTypeName) {
case 'Event Registration':
case 'Change Registration':
$url = 'civicrm/contact/view/participant';
$qsView = "action=view&reset=1&id={$sourceRecordId}&cid=%%cid%%&context=%%cxt%%{$extraParams}";
break;
case 'Contribution':
$url = 'civicrm/contact/view/contribution';
$qsView = "action=view&reset=1&id={$sourceRecordId}&cid=%%cid%%&context=%%cxt%%{$extraParams}";
break;
case 'Payment':
case 'Refund':
$participantId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $sourceRecordId, 'participant_id', 'contribution_id');
if (!empty($participantId)) {
$url = 'civicrm/contact/view/participant';
$qsView = "action=view&reset=1&id={$participantId}&cid=%%cid%%&context=%%cxt%%{$extraParams}";
}
break;
case 'Membership Signup':
case 'Membership Renewal':
case 'Change Membership Status':
case 'Change Membership Type':
$url = 'civicrm/contact/view/membership';
$qsView = "action=view&reset=1&id={$sourceRecordId}&cid=%%cid%%&context=%%cxt%%{$extraParams}";
break;
case 'Pledge Reminder':
case 'Pledge Acknowledgment':
$url = 'civicrm/contact/view/activity';
$qsView = "atype={$activityTypeId}&action=view&reset=1&id=%%id%%&cid=%%cid%%&context=%%cxt%%{$extraParams}";
break;
case 'Email':
case 'Bulk Email':
$url = 'civicrm/activity/view';
$delUrl = 'civicrm/activity';
$qsView = "atype={$activityTypeId}&action=view&reset=1&id=%%id%%&cid=%%cid%%&context=%%cxt%%{$extraParams}";
if ($activityTypeName == 'Email') {
$showDelete = TRUE;
}
break;
case 'Inbound Email':
$url = 'civicrm/contact/view/activity';
$qsView = "atype={$activityTypeId}&action=view&reset=1&id=%%id%%&cid=%%cid%%&context=%%cxt%%{$extraParams}";
break;
case 'Open Case':
case 'Change Case Type':
case 'Change Case Status':
case 'Change Case Start Date':
$showUpdate = $showDelete = FALSE;
$url = 'civicrm/activity';
$qsView = "atype={$activityTypeId}&action=view&reset=1&id=%%id%%&cid=%%cid%%&context=%%cxt%%{$extraParams}";
$qsUpdate = "atype={$activityTypeId}&action=update&reset=1&id=%%id%%&cid=%%cid%%&context=%%cxt%%{$extraParams}";
break;
default:
$url = 'civicrm/activity';
$showView = $showDelete = $showUpdate = TRUE;
$qsView = "atype={$activityTypeId}&action=view&reset=1&id=%%id%%&cid=%%cid%%&context=%%cxt%%{$extraParams}";
$qsUpdate = "atype={$activityTypeId}&action=update&reset=1&id=%%id%%&cid=%%cid%%&context=%%cxt%%{$extraParams}";
// When type is not available lets hide view and update.
if (empty($activityTypeName)) {
$showView = $showUpdate = FALSE;
}
break;
}
$qsDelete = "atype={$activityTypeId}&action=delete&reset=1&id=%%id%%&cid=%%cid%%&context=%%cxt%%{$extraParams}";
$actionLinks = array();
if ($showView) {
$actionLinks += array(
CRM_Core_Action::
VIEW => array(
'name' => ts('View'),
'url' => $url,
'qs' => $qsView,
'title' => ts('View Activity'),
),
);
}
if ($showUpdate) {
$updateUrl = 'civicrm/activity/add';
if ($activityTypeName == 'Email') {
$updateUrl = 'civicrm/activity/email/add';
}
elseif ($activityTypeName == 'Print PDF Letter') {
$updateUrl = 'civicrm/activity/pdf/add';
}
if (CRM_Activity_BAO_Activity::checkPermission($activityId, CRM_Core_Action::UPDATE)) {
$actionLinks += array(
CRM_Core_Action::
UPDATE => array(
'name' => ts('Edit'),
'url' => $updateUrl,
'qs' => $qsUpdate,
'title' => ts('Update Activity'),
),
);
}
}
if (
$activityTypeName &&
CRM_Case_BAO_Case::checkPermission($activityId, 'File On Case', $activityTypeId)
) {
$actionLinks += array(
CRM_Core_Action::
ADD => array(
'name' => ts('File on Case'),
'url' => '#',
'extra' => 'onclick="javascript:fileOnCase( \'file\', \'%%id%%\', null, this ); return false;"',
'title' => ts('File on Case'),
),
);
}
if ($showDelete) {
if (!isset($delUrl) || !$delUrl) {
$delUrl = $url;
}
$actionLinks += array(
CRM_Core_Action::
DELETE => array(
'name' => ts('Delete'),
'url' => $delUrl,
'qs' => $qsDelete,
'title' => ts('Delete Activity'),
),
);
}
if ($accessMailingReport) {
$actionLinks += array(
CRM_Core_Action::
BROWSE => array(
'name' => ts('Mailing Report'),
'url' => 'civicrm/mailing/report',
'qs' => "mid={$sourceRecordId}&reset=1&cid=%%cid%%&context=activitySelector",
'title' => ts('View Mailing Report'),
),
);
}
return $actionLinks;
}
/**
* Getter for array of the parameters required for creating pager.
*
* @param $action
* @param array $params
*/
public function getPagerParams($action, &$params) {
$params['status'] = ts('Activities %%StatusMessage%%');
$params['csvString'] = NULL;
$params['rowCount'] = CRM_Utils_Pager::ROWCOUNT;
$params['buttonTop'] = 'PagerTopButton';
$params['buttonBottom'] = 'PagerBottomButton';
}
/**
* Returns the column headers as an array of tuples:
* (name, sortName (key to the sort array))
*
* @param string $action
* The action being performed.
* @param string $output
* What should the result set include (web/email/csv).
*
* @return array
* the column headers that need to be displayed
*/
public function &getColumnHeaders($action = NULL, $output = NULL) {
if ($output == CRM_Core_Selector_Controller::EXPORT || $output == CRM_Core_Selector_Controller::SCREEN) {
$csvHeaders = array(ts('Activity Type'), ts('Description'), ts('Activity Date'));
foreach (self::_getColumnHeaders() as $column) {
if (array_key_exists('name', $column)) {
$csvHeaders[] = $column['name'];
}
}
return $csvHeaders;
}
else {
return self::_getColumnHeaders();
}
}
/**
* Returns total number of rows for the query.
*
* @param string $action
* Action being performed.
*
* @param null $case
*
* @return int
* Total number of rows
*/
public function getTotalCount($action, $case = NULL) {
$params = array(
'contact_id' => $this->_contactId,
'admin' => $this->_admin,
'caseId' => $case,
'context' => $this->_context,
'activity_type_id' => $this->_activityTypeIDs,
'offset' => 0,
'rowCount' => 0,
'sort' => NULL,
);
return CRM_Activity_BAO_Activity::deprecatedGetActivitiesCount($params);
}
/**
* Returns all the rows in the given offset and rowCount.
*
* @param string $action
* The action being performed.
* @param int $offset
* The row number to start from.
* @param int $rowCount
* The number of rows to return.
* @param string $sort
* The sql string that describes the sort order.
* @param string $output
* What should the result set include (web/email/csv).
*
* @param null $case
*
* @return int
* the total number of rows for this action
*/
public function &getRows($action, $offset, $rowCount, $sort, $output = NULL, $case = NULL) {
$params = array(
'contact_id' => $this->_contactId,
'admin' => $this->_admin,
'caseId' => $case,
'context' => $this->_context,
'activity_type_id' => $this->_activityTypeIDs,
'offset' => $offset,
'rowCount' => $rowCount,
'sort' => $sort,
);
$config = CRM_Core_Config::singleton();
$rows = CRM_Activity_BAO_Activity::deprecatedGetActivities($params);
if (empty($rows)) {
return $rows;
}
$activityStatus = CRM_Core_PseudoConstant::activityStatus();
$engagementLevels = CRM_Campaign_PseudoConstant::engagementLevel();
// CRM-4418
$permissions = array($this->_permission);
if (CRM_Core_Permission::check('delete activities')) {
$permissions[] = CRM_Core_Permission::DELETE;
}
$mask = CRM_Core_Action::mask($permissions);
foreach ($rows as $k => $row) {
$row = &$rows[$k];
// DRAFTING: provide a facility for db-stored strings
// localize the built-in activity names for display
// (these are not enums, so we can't use any automagic here)
switch ($row['activity_type']) {
case 'Meeting':
$row['activity_type'] = ts('Meeting');
break;
case 'Phone Call':
$row['activity_type'] = ts('Phone Call');
break;
case 'Email':
$row['activity_type'] = ts('Email');
break;
case 'SMS':
$row['activity_type'] = ts('SMS');
break;
case 'Event':
$row['activity_type'] = ts('Event');
break;
}
// add class to this row if overdue
if (CRM_Utils_Date::overdue(CRM_Utils_Array::value('activity_date_time', $row))
&& CRM_Utils_Array::value('status_id', $row) == 1
) {
$row['overdue'] = 1;
$row['class'] = 'status-overdue';
}
else {
$row['overdue'] = 0;
$row['class'] = 'status-ontime';
}
$row['status'] = $row['status_id'] ? $activityStatus[$row['status_id']] : NULL;
if ($engagementLevel = CRM_Utils_Array::value('engagement_level', $row)) {
$row['engagement_level'] = CRM_Utils_Array::value($engagementLevel, $engagementLevels, $engagementLevel);
}
// CRM-3553
$accessMailingReport = FALSE;
if (!empty($row['mailingId'])) {
$accessMailingReport = TRUE;
}
$actionLinks = $this->actionLinks(CRM_Utils_Array::value('activity_type_id', $row),
CRM_Utils_Array::value('source_record_id', $row),
$accessMailingReport,
CRM_Utils_Array::value('activity_id', $row),
$this->_key
);
$actionMask = array_sum(array_keys($actionLinks)) & $mask;
if ($output != CRM_Core_Selector_Controller::EXPORT && $output != CRM_Core_Selector_Controller::SCREEN) {
$row['action'] = CRM_Core_Action::formLink($actionLinks,
$actionMask,
array(
'id' => $row['activity_id'],
'cid' => $this->_contactId,
'cxt' => $this->_context,
'caseid' => CRM_Utils_Array::value('case_id', $row),
),
ts('more'),
FALSE,
'activity.selector.action',
'Activity',
$row['activity_id']
);
}
unset($row);
}
return $rows;
}
/**
* Name of export file.
*
* @param string $output
* Type of output.
*
* @return string
* name of the file
*/
public function getExportFileName($output = 'csv') {
return ts('CiviCRM Activity');
}
/**
* Get colunmn headers for search selector.
*
*
* @return array
*/
private static function &_getColumnHeaders() {
if (!isset(self::$_columnHeaders)) {
self::$_columnHeaders = array(
array(
'name' => ts('Type'),
'sort' => 'activity_type',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Subject'),
'sort' => 'subject',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Added By'),
'sort' => 'source_contact_name',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array('name' => ts('With')),
array('name' => ts('Assigned')),
array(
'name' => ts('Date'),
'sort' => 'activity_date_time',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Status'),
'sort' => 'status_id',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array('desc' => ts('Actions')),
);
}
return self::$_columnHeaders;
}
}

View file

@ -0,0 +1,459 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class is used to retrieve and display a range of contacts that match the given criteria.
*
* Specifically for results of advanced search options.
*/
class CRM_Activity_Selector_Search extends CRM_Core_Selector_Base implements CRM_Core_Selector_API {
/**
* This defines two actions- View and Edit.
*
* @var array
*/
static $_links = NULL;
/**
* We use desc to remind us what that column is, name is used in the tpl
*
* @var array
*/
static $_columnHeaders;
/**
* Properties of contact we're interested in displaying
* @var array
*/
static $_properties = array(
'contact_id',
'contact_type',
'contact_sub_type',
'sort_name',
'display_name',
'activity_id',
'activity_date_time',
'activity_status_id',
'activity_status',
'activity_subject',
'source_record_id',
'activity_type_id',
'activity_type',
'activity_is_test',
'activity_campaign_id',
'activity_engagement_level',
);
/**
* Are we restricting ourselves to a single contact.
*
* @var boolean
*/
protected $_single = FALSE;
/**
* Are we restricting ourselves to a single contact.
*
* @var boolean
*/
protected $_limit = NULL;
/**
* What context are we being invoked from.
*
* @var string
*/
protected $_context = NULL;
/**
* What component context are we being invoked from.
*
* @var string
*/
protected $_compContext = NULL;
/**
* QueryParams is the array returned by exportValues called on.
* the HTML_QuickForm_Controller for that page.
*
* @var array
*/
public $_queryParams;
/**
* Represent the type of selector.
*
* @var int
*/
protected $_action;
/**
* The additional clause that we restrict the search with.
*
* @var string
*/
protected $_activityClause = NULL;
/**
* The query object.
*
* @var string
*/
protected $_query;
/**
* Class constructor.
*
* @param array $queryParams
* Array of parameters for query.
* @param \const|int $action - action of search basic or advanced.
* @param string $activityClause
* If the caller wants to further restrict the search (used in activities).
* @param bool $single
* Are we dealing only with one contact?.
* @param int $limit
* How many activities do we want returned.
*
* @param string $context
* @param null $compContext
*
* @return \CRM_Activity_Selector_Search
*/
public function __construct(
&$queryParams,
$action = CRM_Core_Action::NONE,
$activityClause = NULL,
$single = FALSE,
$limit = NULL,
$context = 'search',
$compContext = NULL
) {
// submitted form values
$this->_queryParams = &$queryParams;
$this->_single = $single;
$this->_limit = $limit;
$this->_context = $context;
$this->_compContext = $compContext;
$this->_activityClause = $activityClause;
// CRM-12675
$components = CRM_Core_Component::getNames();
$componentClause = array();
foreach ($components as $componentID => $componentName) {
// CRM-19201: Add support for searching CiviCampaign and CiviCase
// activities. For CiviCase, "access all cases and activities" is
// required here rather than "access my cases and activities" to
// prevent those with only the later permission from seeing a list
// of all cases which might present a privacy issue.
if (!CRM_Core_Permission::access($componentName, TRUE, TRUE)) {
$componentClause[] = " (activity_type.component_id IS NULL OR activity_type.component_id <> {$componentID}) ";
}
}
if (!empty($componentClause)) {
$componentRestriction = implode(' AND ', $componentClause);
if (empty($this->_activityClause)) {
$this->_activityClause = $componentRestriction;
}
else {
$this->_activityClause .= ' AND ' . $componentRestriction;
}
}
// type of selector
$this->_action = $action;
$this->_query = new CRM_Contact_BAO_Query($this->_queryParams,
CRM_Activity_BAO_Query::selectorReturnProperties(),
NULL, FALSE, FALSE,
CRM_Contact_BAO_Query::MODE_ACTIVITY
);
$this->_query->_distinctComponentClause = '( civicrm_activity.id )';
$this->_query->_groupByComponentClause = " GROUP BY civicrm_activity.id ";
}
/**
* Getter for array of the parameters required for creating pager.
*
* @param $action
* @param array $params
*/
public function getPagerParams($action, &$params) {
$params['status'] = ts('Activities %%StatusMessage%%');
$params['csvString'] = NULL;
$params['rowCount'] = CRM_Utils_Pager::ROWCOUNT;
$params['buttonTop'] = 'PagerTopButton';
$params['buttonBottom'] = 'PagerBottomButton';
}
/**
* Returns total number of rows for the query.
*
* @param string $action
*
* @return int
* Total number of rows
*/
public function getTotalCount($action) {
return $this->_query->searchQuery(0, 0, NULL,
TRUE, FALSE,
FALSE, FALSE,
FALSE,
$this->_activityClause
);
}
/**
* Returns all the rows in the given offset and rowCount.
*
* @param string $action
* The action being performed.
* @param int $offset
* The row number to start from.
* @param int $rowCount
* The number of rows to return.
* @param string $sort
* The sql string that describes the sort order.
* @param string $output
* What should the result set include (web/email/csv).
*
* @return array
* rows in the given offset and rowCount
*/
public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$result = $this->_query->searchQuery(
$offset, $rowCount, $sort,
FALSE, FALSE,
FALSE, FALSE,
FALSE,
$this->_activityClause
);
$rows = array();
$mailingIDs = CRM_Mailing_BAO_Mailing::mailingACLIDs();
$accessCiviMail = CRM_Core_Permission::check('access CiviMail');
// Get all campaigns.
$allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
$engagementLevels = CRM_Campaign_PseudoConstant::engagementLevel();
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
$targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
// Get all activity types
$activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name', TRUE);
while ($result->fetch()) {
$row = array();
// Ignore rows where we dont have an activity id.
if (empty($result->activity_id)) {
continue;
}
$this->_query->convertToPseudoNames($result);
// the columns we are interested in
foreach (self::$_properties as $property) {
if (isset($result->$property)) {
$row[$property] = $result->$property;
}
}
$contactId = CRM_Utils_Array::value('contact_id', $row);
if (!$contactId) {
$contactId = CRM_Utils_Array::value('source_contact_id', $row);
}
$row['target_contact_name'] = CRM_Activity_BAO_ActivityContact::getNames($row['activity_id'], $targetID);
$row['assignee_contact_name'] = CRM_Activity_BAO_ActivityContact::getNames($row['activity_id'], $assigneeID);
list($row['source_contact_name'], $row['source_contact_id']) = CRM_Activity_BAO_ActivityContact::getNames($row['activity_id'], $sourceID, TRUE);
$row['source_contact_name'] = implode(',', array_values($row['source_contact_name']));
$row['source_contact_id'] = implode(',', $row['source_contact_id']);
if ($this->_context == 'search') {
$row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->activity_id;
}
$row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id
);
$accessMailingReport = FALSE;
$activityTypeId = $row['activity_type_id'];
if ($row['activity_is_test']) {
$row['activity_type'] = $row['activity_type'] . " (test)";
}
$bulkActivityTypeID = CRM_Utils_Array::key('Bulk Email', $activityTypes);
$row['mailingId'] = '';
if (
$accessCiviMail &&
($mailingIDs === TRUE || in_array($result->source_record_id, $mailingIDs)) &&
($bulkActivityTypeID == $activityTypeId)
) {
$row['mailingId'] = CRM_Utils_System::url('civicrm/mailing/report',
"mid={$result->source_record_id}&reset=1&cid={$contactId}&context=activitySelector"
);
$row['recipients'] = ts('(recipients)');
$row['target_contact_name'] = '';
$row['assignee_contact_name'] = '';
$accessMailingReport = TRUE;
}
$activityActions = new CRM_Activity_Selector_Activity($result->contact_id, NULL);
$actionLinks = $activityActions->actionLinks($activityTypeId,
CRM_Utils_Array::value('source_record_id', $row),
$accessMailingReport,
CRM_Utils_Array::value('activity_id', $row),
$this->_key,
$this->_compContext
);
$row['action'] = CRM_Core_Action::formLink($actionLinks, NULL,
array(
'id' => $result->activity_id,
'cid' => $contactId,
'cxt' => $this->_context,
),
ts('more'),
FALSE,
'activity.selector.row',
'Activity',
$result->activity_id
);
// Carry campaign to selector.
$row['campaign'] = CRM_Utils_Array::value($result->activity_campaign_id, $allCampaigns);
$row['campaign_id'] = $result->activity_campaign_id;
if ($engagementLevel = CRM_Utils_Array::value('activity_engagement_level', $row)) {
$row['activity_engagement_level'] = CRM_Utils_Array::value($engagementLevel,
$engagementLevels, $engagementLevel
);
}
// Check if recurring activity.
$repeat = CRM_Core_BAO_RecurringEntity::getPositionAndCount($row['activity_id'], 'civicrm_activity');
$row['repeat'] = '';
if ($repeat) {
$row['repeat'] = ts('Repeating (%1 of %2)', array(1 => $repeat[0], 2 => $repeat[1]));
}
$rows[] = $row;
}
return $rows;
}
/**
* @return array
* which contains an array of strings
*/
public function getQILL() {
return $this->_query->qill();
}
/**
* Returns the column headers as an array of tuples:
* (name, sortName (key to the sort array))
*
* @param string $action
* The action being performed.
* @param string $output
* What should the result set include (web/email/csv).
*
* @return array
* the column headers that need to be displayed
*/
public function &getColumnHeaders($action = NULL, $output = NULL) {
if (!isset(self::$_columnHeaders)) {
self::$_columnHeaders = array(
array(
'name' => ts('Type'),
'sort' => 'activity_type_id',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Subject'),
'sort' => 'activity_subject',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Added By'),
'sort' => 'source_contact',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array('name' => ts('With')),
array('name' => ts('Assigned')),
array(
'name' => ts('Date'),
'sort' => 'activity_date_time',
'direction' => CRM_Utils_Sort::DESCENDING,
),
array(
'name' => ts('Status'),
'sort' => 'activity_status',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'desc' => ts('Actions'),
),
);
}
return self::$_columnHeaders;
}
/**
* @return mixed
*/
public function alphabetQuery() {
return $this->_query->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
}
/**
* @return string
*/
public function &getQuery() {
return $this->_query;
}
/**
* Name of export file.
*
* @param string $output
* Type of output.
*
* @return string
* name of the file
*/
public function getExportFileName($output = 'csv') {
return ts('CiviCRM Activity Search');
}
}

View file

@ -0,0 +1,114 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Activity_StateMachine_Search extends CRM_Core_StateMachine {
/**
* The task that the wizard is currently processing.
*
* @var string
*/
protected $_task;
/**
* Class constructor.
*
* @param object $controller
* @param \const|int $action
*/
public function __construct($controller, $action = CRM_Core_Action::NONE) {
parent::__construct($controller, $action);
$this->_pages = array();
$this->_pages['CRM_Activity_Form_Search'] = NULL;
list($task, $result) = $this->taskName($controller, 'Search');
$this->_task = $task;
if (is_array($task)) {
foreach ($task as $t) {
$this->_pages[$t] = NULL;
}
}
else {
$this->_pages[$task] = NULL;
}
$this->addSequentialPages($this->_pages, $action);
}
/**
* Determine the form name based on the action. This allows us
* to avoid using conditional state machine, much more efficient
* and simpler
*
* @param CRM_Core_Controller $controller
* The controller object.
*
* @param string $formName
*
* @return string
* the name of the form that will handle the task
*/
public function taskName($controller, $formName = 'Search') {
// total hack, check POST vars and then session to determine stuff
$value = CRM_Utils_Array::value('task', $_POST);
if (!isset($value)) {
$value = $this->_controller->get('task');
}
$this->_controller->set('task', $value);
return CRM_Activity_Task::getTask($value);
}
/**
* Return the form name of the task.
*
* @return string
*/
public function getTaskFormName() {
return CRM_Utils_String::getClassName($this->_task);
}
/**
* Should the controller reset the session.
* In some cases, specifically search we want to remember
* state across various actions and want to go back to the
* beginning from the final state, but retain the same session
* values
*
* @return bool
*/
public function shouldReset() {
return FALSE;
}
}

View file

@ -0,0 +1,206 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Class to represent the actions that can be performed on a group of contacts used by the search forms.
*/
class CRM_Activity_Task {
const
DELETE_ACTIVITIES = 1,
PRINT_ACTIVITIES = 2,
EXPORT_ACTIVITIES = 3,
BATCH_ACTIVITIES = 4,
EMAIL_CONTACTS = 5,
EMAIL_SMS = 6;
/**
* The task array.
*
* @var array
*/
static $_tasks = NULL;
/**
* The optional task array.
*
* @var array
*/
static $_optionalTasks = NULL;
/**
* These tasks are the core set of tasks that the user can perform
* on a contact / group of contacts.
*
* @return array
* the set of tasks for a group of contacts
*/
public static function &tasks() {
if (!(self::$_tasks)) {
self::$_tasks = array(
1 => array(
'title' => ts('Delete activities'),
'class' => 'CRM_Activity_Form_Task_Delete',
'result' => FALSE,
),
2 => array(
'title' => ts('Print selected rows'),
'class' => 'CRM_Activity_Form_Task_Print',
'result' => FALSE,
),
3 => array(
'title' => ts('Export activities'),
'class' => array(
'CRM_Export_Form_Select',
'CRM_Export_Form_Map',
),
'result' => FALSE,
),
4 => array(
'title' => ts('Update multiple activities'),
'class' => array(
'CRM_Activity_Form_Task_PickProfile',
'CRM_Activity_Form_Task_Batch',
),
'result' => FALSE,
),
5 => array(
'title' => ts('Email - send now'),
'class' => array(
'CRM_Activity_Form_Task_PickOption',
'CRM_Activity_Form_Task_Email',
),
'result' => FALSE,
),
6 => array(
'title' => ts('SMS - send reply'),
'class' => 'CRM_Activity_Form_Task_SMS',
'result' => FALSE,
),
7 => array(
'title' => ts('Tag - add to activities'),
'class' => 'CRM_Activity_Form_Task_AddToTag',
'result' => FALSE,
),
8 => array(
'title' => ts('Tag - remove from activities'),
'class' => 'CRM_Activity_Form_Task_RemoveFromTag',
'result' => FALSE,
),
);
$config = CRM_Core_Config::singleton();
if (in_array('CiviCase', $config->enableComponents)) {
if (CRM_Core_Permission::check('access all cases and activities') ||
CRM_Core_Permission::check('access my cases and activities')
) {
self::$_tasks[6] = array(
'title' => ts('File on case'),
'class' => 'CRM_Activity_Form_Task_FileOnCase',
'result' => FALSE,
);
}
}
// CRM-4418, check for delete
if (!CRM_Core_Permission::check('delete activities')) {
unset(self::$_tasks[1]);
}
CRM_Utils_Hook::searchTasks('activity', self::$_tasks);
asort(self::$_tasks);
}
return self::$_tasks;
}
/**
* These tasks are the core set of task titles on activity.
*
* @return array
* the set of task titles
*/
public static function &taskTitles() {
self::tasks();
$titles = array();
foreach (self::$_tasks as $id => $value) {
$titles[$id] = $value['title'];
}
return $titles;
}
/**
* Show tasks selectively based on the permission level of the user.
*
* @param int $permission
*
* @return array
* set of tasks that are valid for the user
*/
public static function &permissionedTaskTitles($permission) {
$tasks = array();
if ($permission == CRM_Core_Permission::EDIT) {
$tasks = self::taskTitles();
}
else {
$tasks = array(
3 => self::$_tasks[3]['title'],
);
//CRM-4418,
if (CRM_Core_Permission::check('delete activities')) {
$tasks[1] = self::$_tasks[1]['title'];
}
}
return $tasks;
}
/**
* These tasks are the core set of tasks that the user can perform on activity.
*
* @param int $value
*
* @return array
* the set of tasks for a group of activity
*/
public static function getTask($value) {
self::tasks();
if (!$value || !CRM_Utils_Array::value($value, self::$_tasks)) {
// make the print task by default
$value = 2;
}
return array(
self::$_tasks[$value]['class'],
self::$_tasks[$value]['result'],
);
}
}

View file

@ -0,0 +1,121 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Class CRM_Member_Tokens
*
* Generate "activity.*" tokens.
*
* This TokenSubscriber was produced by refactoring the code from the
* scheduled-reminder system with the goal of making that system
* more flexible. The current implementation is still coupled to
* scheduled-reminders. It would be good to figure out a more generic
* implementation which is not tied to scheduled reminders, although
* that is outside the current scope.
*/
class CRM_Activity_Tokens extends \Civi\Token\AbstractTokenSubscriber {
/**
* CRM_Activity_Tokens constructor.
*/
public function __construct() {
parent::__construct('activity', array_merge(
array(
'activity_id' => ts('Activity ID'),
'activity_type' => ts('Activity Type'),
'subject' => ts('Activity Subject'),
'details' => ts('Activity Details'),
'activity_date_time' => ts('Activity Date-Time'),
),
CRM_Utils_Token::getCustomFieldTokens('Activity')
));
}
/**
* @inheritDoc
*/
public function checkActive(\Civi\Token\TokenProcessor $processor) {
// Extracted from scheduled-reminders code. See the class description.
return
!empty($processor->context['actionMapping'])
&& $processor->context['actionMapping']->getEntity() === 'civicrm_activity';
}
/**
* @inheritDoc
*/
public function alterActionScheduleQuery(\Civi\ActionSchedule\Event\MailingQueryEvent $e) {
if ($e->mapping->getEntity() !== 'civicrm_activity') {
return;
}
// The joint expression for activities needs some extra nuance to handle.
// Multiple revisions of the activity.
// Q: Could we simplify & move the extra AND clauses into `where(...)`?
$e->query->param('casEntityJoinExpr', 'e.id = reminder.entity_id AND e.is_current_revision = 1 AND e.is_deleted = 0');
$e->query->select('e.*'); // FIXME: seems too broad.
$e->query->select('ov.label as activity_type, e.id as activity_id');
$e->query->join("og", "!casMailingJoinType civicrm_option_group og ON og.name = 'activity_type'");
$e->query->join("ov", "!casMailingJoinType civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id");
// if CiviCase component is enabled, join for caseId.
$compInfo = CRM_Core_Component::getEnabledComponents();
if (array_key_exists('CiviCase', $compInfo)) {
$e->query->select("civicrm_case_activity.case_id as case_id");
$e->query->join('civicrm_case_activity', "LEFT JOIN `civicrm_case_activity` ON `e`.`id` = `civicrm_case_activity`.`activity_id`");
}
}
/**
* @inheritDoc
*/
public function evaluateToken(\Civi\Token\TokenRow $row, $entity, $field, $prefetch = NULL) {
$actionSearchResult = $row->context['actionSearchResult'];
if (in_array($field, array('activity_date_time'))) {
$row->tokens($entity, $field, \CRM_Utils_Date::customFormat($actionSearchResult->$field));
}
elseif (isset($actionSearchResult->$field)) {
$row->tokens($entity, $field, $actionSearchResult->$field);
}
elseif ($cfID = \CRM_Core_BAO_CustomField::getKeyID($field)) {
$row->customToken($entity, $cfID, $actionSearchResult->entity_id);
}
else {
$row->tokens($entity, $field, '');
}
}
}