3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Campaign_BAO_Campaign
extends CRM_Campaign_DAO_Campaign
{
20 * Takes an associative array and creates a campaign object.
22 * the function extract all the params it needs to initialize the create a
23 * contact object. the params array could contain additional unused name/value
26 * @param array $params
27 * (reference ) an assoc array of name/value pairs.
29 * @return CRM_Campaign_DAO_Campaign
31 public static function create(&$params) {
36 if (empty($params['id'])) {
37 if (empty($params['created_id'])) {
38 $params['created_id'] = CRM_Core_Session
::getLoggedInContactID();
41 if (empty($params['created_date'])) {
42 $params['created_date'] = date('YmdHis');
45 if (empty($params['name'])) {
46 $params['name'] = CRM_Utils_String
::titleToVar($params['title'], 64);
50 $campaign = self
::writeRecord($params);
52 /* Create the campaign group record */
53 $groupTableName = CRM_Contact_BAO_Group
::getTableName();
55 if (isset($params['groups']) && !empty($params['groups']['include']) && is_array($params['groups']['include'])) {
56 foreach ($params['groups']['include'] as $entityId) {
57 $dao = new CRM_Campaign_DAO_CampaignGroup();
58 $dao->campaign_id
= $campaign->id
;
59 $dao->entity_table
= $groupTableName;
60 $dao->entity_id
= $entityId;
61 $dao->group_type
= 'Include';
67 if (!empty($params['custom']) && is_array($params['custom'])) {
68 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_campaign', $campaign->id
);
75 * Delete the campaign.
82 public static function del($id) {
87 CRM_Utils_Hook
::pre('delete', 'Campaign', $id, CRM_Core_DAO
::$_nullArray);
89 $dao = new CRM_Campaign_DAO_Campaign();
91 $result = $dao->delete();
93 CRM_Utils_Hook
::post('delete', 'Campaign', $id, $dao);
99 * Retrieve DB object based on input parameters.
101 * It also stores all the retrieved values in the default array.
103 * @param array $params
104 * (reference ) an assoc array of name/value pairs.
105 * @param array $defaults
106 * (reference ) an assoc array to hold the flattened values.
108 * @return \CRM_Campaign_DAO_Campaign|null
110 public static function retrieve(&$params, &$defaults) {
111 $campaign = new CRM_Campaign_DAO_Campaign();
113 $campaign->copyValues($params);
115 if ($campaign->find(TRUE)) {
116 CRM_Core_DAO
::storeValues($campaign, $defaults);
123 * Return the all eligible campaigns w/ cache.
125 * @param int $includeId
126 * Lets inlcude this campaign by force.
127 * @param int $excludeId
128 * Do not include this campaign.
129 * @param bool $onlyActive
130 * Consider only active campaigns.
132 * @param bool $onlyCurrent
133 * @param bool $appendDatesToTitle
134 * @param bool $forceAll
137 * $campaigns a set of campaigns.
139 public static function getCampaigns(
144 $appendDatesToTitle = FALSE,
154 'appendDatesToTitle',
157 foreach ($cacheKeyParams as $param) {
158 $cacheParam = $
$param;
162 $cacheKey .= '_' . $cacheParam;
165 if (!isset($campaigns[$cacheKey])) {
166 $where = ['( camp.title IS NOT NULL )'];
168 $where[] = "( camp.id != $excludeId )";
171 $where[] = '( camp.is_active = 1 )';
174 $where[] = '( camp.end_date IS NULL OR camp.end_date >= NOW() )';
176 $whereClause = implode(' AND ', $where);
178 $whereClause .= " OR ( camp.id = $includeId )";
183 $whereClause = '( 1 )';
191 FROM civicrm_campaign camp
193 Order By camp.title";
195 $campaign = CRM_Core_DAO
::executeQuery($query);
196 $campaigns[$cacheKey] = [];
197 $config = CRM_Core_Config
::singleton();
199 while ($campaign->fetch()) {
200 $title = $campaign->title
;
201 if ($appendDatesToTitle) {
203 foreach (['start_date', 'end_date'] as $date) {
204 if ($campaign->$date) {
205 $dates[] = CRM_Utils_Date
::customFormat($campaign->$date, $config->dateformatFull
);
208 if (!empty($dates)) {
209 $title .= ' (' . implode('-', $dates) . ')';
212 $campaigns[$cacheKey][$campaign->id
] = $title;
216 return $campaigns[$cacheKey];
220 * Wrapper to self::getCampaigns( )
221 * w/ permissions and component check.
223 * @param int $includeId
224 * @param int $excludeId
225 * @param bool $onlyActive
226 * @param bool $onlyCurrent
227 * @param bool $appendDatesToTitle
228 * @param bool $forceAll
229 * @param bool $doCheckForComponent
230 * @param bool $doCheckForPermissions
234 public static function getPermissionedCampaigns(
239 $appendDatesToTitle = FALSE,
241 $doCheckForComponent = TRUE,
242 $doCheckForPermissions = TRUE
250 'appendDatesToTitle',
251 'doCheckForComponent',
252 'doCheckForPermissions',
255 foreach ($cachekeyParams as $param) {
256 $cacheKeyParam = $
$param;
257 if (!$cacheKeyParam) {
260 $cacheKey .= '_' . $cacheKeyParam;
263 static $validCampaigns;
264 if (!isset($validCampaigns[$cacheKey])) {
268 'hasAccessCampaign' => FALSE,
269 'isCampaignEnabled' => FALSE,
272 //do check for component.
273 if ($doCheckForComponent) {
274 $campaigns['isCampaignEnabled'] = $isValid = self
::isCampaignEnable();
277 //do check for permissions.
278 if ($doCheckForPermissions) {
279 $campaigns['hasAccessCampaign'] = $isValid = self
::accessCampaign();
282 //finally retrieve campaigns from db.
284 $campaigns['campaigns'] = self
::getCampaigns($includeId,
294 $validCampaigns[$cacheKey] = $campaigns;
297 return $validCampaigns[$cacheKey];
301 * Is CiviCampaign enabled.
304 public static function isCampaignEnable() {
305 static $isEnable = NULL;
307 if (!isset($isEnable)) {
309 $config = CRM_Core_Config
::singleton();
310 if (in_array('CiviCampaign', $config->enableComponents
)) {
319 * Retrieve campaigns for dashboard.
321 * @param array $params
322 * @param bool $onlyCount
326 public static function getCampaignSummary($params = [], $onlyCount = FALSE) {
329 //build the limit and order clause.
330 $limitClause = $orderByClause = $lookupTableJoins = NULL;
333 'sort' => 'start_date',
336 'sortOrder' => 'desc',
338 foreach ($sortParams as $name => $default) {
339 if (!empty($params[$name])) {
340 $sortParams[$name] = $params[$name];
344 //need to lookup tables.
345 $orderOnCampaignTable = TRUE;
346 if ($sortParams['sort'] == 'status') {
347 $orderOnCampaignTable = FALSE;
348 $lookupTableJoins = "
349 LEFT JOIN civicrm_option_value status ON ( status.value = campaign.status_id OR campaign.status_id IS NULL )
350 INNER JOIN civicrm_option_group grp ON ( status.option_group_id = grp.id AND grp.name = 'campaign_status' )";
351 $orderByClause = "ORDER BY status.label {$sortParams['sortOrder']}";
353 elseif ($sortParams['sort'] == 'campaign_type') {
354 $orderOnCampaignTable = FALSE;
355 $lookupTableJoins = "
356 LEFT JOIN civicrm_option_value campaign_type ON ( campaign_type.value = campaign.campaign_type_id
357 OR campaign.campaign_type_id IS NULL )
358 INNER JOIN civicrm_option_group grp ON ( campaign_type.option_group_id = grp.id AND grp.name = 'campaign_type' )";
359 $orderByClause = "ORDER BY campaign_type.label {$sortParams['sortOrder']}";
361 elseif ($sortParams['sort'] == 'isActive') {
362 $sortParams['sort'] = 'is_active';
364 if ($orderOnCampaignTable) {
365 $orderByClause = "ORDER BY campaign.{$sortParams['sort']} {$sortParams['sortOrder']}";
367 $orderByClause = ($orderByClause) ?
$orderByClause . ", campaign.id {$sortParams['sortOrder']}" : $orderByClause;
368 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
371 //build the where clause.
372 $queryParams = $where = [];
373 if (!empty($params['id'])) {
374 $where[] = "( campaign.id = %1 )";
375 $queryParams[1] = [$params['id'], 'Positive'];
377 if (!empty($params['name'])) {
378 $where[] = "( campaign.name LIKE %2 )";
379 $queryParams[2] = ['%' . trim($params['name']) . '%', 'String'];
381 if (!empty($params['title'])) {
382 $where[] = "( campaign.title LIKE %3 )";
383 $queryParams[3] = ['%' . trim($params['title']) . '%', 'String'];
385 if (!empty($params['start_date'])) {
386 $startDate = CRM_Utils_Date
::processDate($params['start_date']);
387 $where[] = "( campaign.start_date >= %4 OR campaign.start_date IS NULL )";
388 $queryParams[4] = [$startDate, 'String'];
390 if (!empty($params['end_date'])) {
391 $endDate = CRM_Utils_Date
::processDate($params['end_date'], '235959');
392 $where[] = "( campaign.end_date <= %5 OR campaign.end_date IS NULL )";
393 $queryParams[5] = [$endDate, 'String'];
395 if (!empty($params['description'])) {
396 $where[] = "( campaign.description LIKE %6 )";
397 $queryParams[6] = ['%' . trim($params['description']) . '%', 'String'];
399 if (!empty($params['campaign_type_id'])) {
400 $where[] = "( campaign.campaign_type_id IN ( %7 ) )";
401 $queryParams[7] = [implode(',', (array) $params['campaign_type_id']), 'CommaSeparatedIntegers'];
403 if (!empty($params['status_id'])) {
404 $where[] = "( campaign.status_id IN ( %8 ) )";
405 $queryParams[8] = [implode(',', (array) $params['status_id']), 'CommaSeparatedIntegers'];
407 if (array_key_exists('is_active', $params)) {
408 $active = "( campaign.is_active = 1 )";
409 if (!empty($params['is_active'])) {
410 $active = "( campaign.is_active = 0 OR campaign.is_active IS NULL )";
415 if (!empty($where)) {
416 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
432 SELECT campaign.id as id,
433 campaign.name as name,
434 campaign.title as title,
435 campaign.is_active as is_active,
436 campaign.status_id as status_id,
437 campaign.end_date as end_date,
438 campaign.start_date as start_date,
439 campaign.description as description,
440 campaign.campaign_type_id as campaign_type_id';
442 $selectClause = 'SELECT COUNT(*)';
444 $fromClause = 'FROM civicrm_campaign campaign';
446 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
448 //in case of only count.
450 return (int) CRM_Core_DAO
::singleValueQuery($query, $queryParams);
453 $campaign = CRM_Core_DAO
::executeQuery($query, $queryParams);
454 while ($campaign->fetch()) {
455 foreach ($properties as $property) {
456 $campaigns[$campaign->id
][$property] = $campaign->$property;
464 * Get the campaign count.
467 public static function getCampaignCount() {
468 return (int) CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM civicrm_campaign');
472 * Get Campaigns groups.
474 * @param int $campaignId
479 public static function getCampaignGroups($campaignId) {
480 static $campaignGroups;
485 if (!isset($campaignGroups[$campaignId])) {
486 $campaignGroups[$campaignId] = [];
489 SELECT grp.title, grp.id
490 FROM civicrm_campaign_group campgrp
491 INNER JOIN civicrm_group grp ON ( grp.id = campgrp.entity_id )
492 WHERE campgrp.group_type = 'Include'
493 AND campgrp.entity_table = 'civicrm_group'
494 AND campgrp.campaign_id = %1";
496 $groups = CRM_Core_DAO
::executeQuery($query, [1 => [$campaignId, 'Positive']]);
497 while ($groups->fetch()) {
498 $campaignGroups[$campaignId][$groups->id
] = $groups->title
;
502 return $campaignGroups[$campaignId];
506 * Update the is_active flag in the db.
509 * Id of the database record.
510 * @param bool $is_active
511 * Value we want to set the is_active field.
514 * true if we found and updated the object, else false
516 public static function setIsActive($id, $is_active) {
517 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Campaign', $id, 'is_active', $is_active);
523 public static function accessCampaign() {
524 static $allow = NULL;
526 if (!isset($allow)) {
528 if (CRM_Core_Permission
::check('manage campaign') ||
529 CRM_Core_Permission
::check('administer CiviCampaign')
539 * Add select element for campaign
540 * and assign needful info to templates.
542 * @param CRM_Core_Form $form
543 * @param int $connectedCampaignId
545 public static function addCampaign(&$form, $connectedCampaignId = NULL) {
546 //some forms do set default and freeze.
548 if ($form->get('action') & CRM_Core_Action
::VIEW
) {
549 $appendDates = FALSE;
552 $campaignDetails = self
::getPermissionedCampaigns($connectedCampaignId, NULL, TRUE, TRUE, $appendDates);
554 $campaigns = $campaignDetails['campaigns'] ??
NULL;
555 $hasAccessCampaign = $campaignDetails['hasAccessCampaign'] ??
NULL;
556 $isCampaignEnabled = $campaignDetails['isCampaignEnabled'] ??
NULL;
558 $showAddCampaign = FALSE;
559 if ($connectedCampaignId ||
($isCampaignEnabled && $hasAccessCampaign)) {
560 $showAddCampaign = TRUE;
561 $campaign = $form->addEntityRef('campaign_id', ts('Campaign'), [
562 'entity' => 'Campaign',
564 'select' => ['minimumInputLength' => 0],
566 //lets freeze when user does not has access or campaign is disabled.
567 if (!$isCampaignEnabled ||
!$hasAccessCampaign) {
572 //carry this info to templates.
574 'showAddCampaign' => $showAddCampaign,
575 'hasAccessCampaign' => $hasAccessCampaign,
576 'isCampaignEnabled' => $isCampaignEnabled,
579 $form->assign('campaignInfo', $campaignInfo);
583 * Add campaign in component search.
584 * and assign needful info to templates.
586 * @param CRM_Core_Form $form
587 * @param string $elementName
589 public static function addCampaignInComponentSearch(&$form, $elementName = 'campaign_id') {
591 $campaignDetails = self
::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
592 $fields = ['campaigns', 'hasAccessCampaign', 'isCampaignEnabled'];
593 foreach ($fields as $fld) {
594 $
$fld = $campaignDetails[$fld] ??
NULL;
596 $showCampaignInSearch = FALSE;
597 if ($isCampaignEnabled && $hasAccessCampaign && !empty($campaigns)) {
598 //get the current campaign only.
599 $currentCampaigns = self
::getCampaigns(NULL, NULL, FALSE);
600 $pastCampaigns = array_diff($campaigns, $currentCampaigns);
602 if (!empty($currentCampaigns)) {
603 $allCampaigns = ['crm_optgroup_current_campaign' => ts('Current Campaigns')] +
$currentCampaigns;
605 if (!empty($pastCampaigns)) {
606 $allCampaigns +
= ['crm_optgroup_past_campaign' => ts('Past Campaigns')] +
$pastCampaigns;
609 $showCampaignInSearch = TRUE;
610 $form->add('select', $elementName, ts('Campaigns'), $allCampaigns, FALSE,
611 ['id' => 'campaigns', 'multiple' => 'multiple', 'class' => 'crm-select2']
618 'showCampaignInSearch',
620 foreach ($infoFields as $fld) {
621 $campaignInfo[$fld] = $
$fld;
623 $form->assign('campaignInfo', $campaignInfo);
629 public static function getEntityRefFilters() {
631 ['key' => 'campaign_type_id', 'value' => ts('Campaign Type')],
632 ['key' => 'status_id', 'value' => ts('Status')],
634 'key' => 'start_date',
635 'value' => ts('Start Date'),
637 ['key' => '{">":"now"}', 'value' => ts('Upcoming')],
639 'key' => '{"BETWEEN":["now - 3 month","now"]}',
640 'value' => ts('Past 3 Months'),
643 'key' => '{"BETWEEN":["now - 6 month","now"]}',
644 'value' => ts('Past 6 Months'),
647 'key' => '{"BETWEEN":["now - 1 year","now"]}',
648 'value' => ts('Past Year'),
654 'value' => ts('End Date'),
656 ['key' => '{">":"now"}', 'value' => ts('In the future')],
657 ['key' => '{"<":"now"}', 'value' => ts('In the past')],
658 ['key' => '{"IS NULL":"1"}', 'value' => ts('Not set')],
665 * Links to create new campaigns from entityRef widget
669 public static function getEntityRefCreateLinks() {
670 if (CRM_Core_Permission
::check([['administer CiviCampaign', 'manage campaign']])) {
673 'label' => ts('New Campaign'),
674 'url' => CRM_Utils_System
::url('civicrm/campaign/add', "reset=1",
675 NULL, NULL, FALSE, FALSE, TRUE),
676 'type' => 'Campaign',