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
30 * @throws \CRM_Core_Exception
32 public static function create(&$params) {
37 if (empty($params['id'])) {
38 if (empty($params['created_id'])) {
39 $params['created_id'] = CRM_Core_Session
::getLoggedInContactID();
42 if (empty($params['created_date'])) {
43 $params['created_date'] = date('YmdHis');
46 if (empty($params['name'])) {
47 $params['name'] = CRM_Utils_String
::titleToVar($params['title'], 64);
51 /* @var \CRM_Campaign_DAO_Campaign $campaign */
52 $campaign = self
::writeRecord($params);
54 /* Create the campaign group record */
55 $groupTableName = CRM_Contact_BAO_Group
::getTableName();
57 if (isset($params['groups']) && !empty($params['groups']['include']) && is_array($params['groups']['include'])) {
58 foreach ($params['groups']['include'] as $entityId) {
59 $dao = new CRM_Campaign_DAO_CampaignGroup();
60 $dao->campaign_id
= $campaign->id
;
61 $dao->entity_table
= $groupTableName;
62 $dao->entity_id
= $entityId;
63 $dao->group_type
= 'Include';
69 if (!empty($params['custom']) && is_array($params['custom'])) {
70 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_campaign', $campaign->id
);
77 * Delete the campaign.
84 public static function del($id) {
89 CRM_Utils_Hook
::pre('delete', 'Campaign', $id);
91 $dao = new CRM_Campaign_DAO_Campaign();
93 $result = $dao->delete();
95 CRM_Utils_Hook
::post('delete', 'Campaign', $id, $dao);
101 * Retrieve DB object based on input parameters.
103 * It also stores all the retrieved values in the default array.
105 * @param array $params
106 * (reference ) an assoc array of name/value pairs.
107 * @param array $defaults
108 * (reference ) an assoc array to hold the flattened values.
110 * @return \CRM_Campaign_DAO_Campaign|null
112 public static function retrieve(&$params, &$defaults) {
113 $campaign = new CRM_Campaign_DAO_Campaign();
115 $campaign->copyValues($params);
117 if ($campaign->find(TRUE)) {
118 CRM_Core_DAO
::storeValues($campaign, $defaults);
125 * Return the all eligible campaigns w/ cache.
127 * @param int $includeId
128 * Lets include this campaign by force.
129 * @param int $excludeId
130 * Do not include this campaign.
131 * @param bool $onlyActive
132 * Consider only active campaigns.
134 * @param bool $onlyCurrent
135 * @param bool $appendDatesToTitle
136 * @param bool $forceAll
139 * $campaigns a set of campaigns.
141 public static function getCampaigns(
146 $appendDatesToTitle = FALSE,
156 'appendDatesToTitle',
159 foreach ($cacheKeyParams as $param) {
160 $cacheParam = $
$param;
164 $cacheKey .= '_' . $cacheParam;
167 if (!isset($campaigns[$cacheKey])) {
168 $where = ['( camp.title IS NOT NULL )'];
170 $where[] = "( camp.id != $excludeId )";
173 $where[] = '( camp.is_active = 1 )';
176 $where[] = '( camp.end_date IS NULL OR camp.end_date >= NOW() )';
178 $whereClause = implode(' AND ', $where);
180 $whereClause .= " OR ( camp.id = $includeId )";
185 $whereClause = '( 1 )';
193 FROM civicrm_campaign camp
195 Order By camp.title";
197 $campaign = CRM_Core_DAO
::executeQuery($query);
198 $campaigns[$cacheKey] = [];
199 $config = CRM_Core_Config
::singleton();
201 while ($campaign->fetch()) {
202 $title = $campaign->title
;
203 if ($appendDatesToTitle) {
205 foreach (['start_date', 'end_date'] as $date) {
206 if ($campaign->$date) {
207 $dates[] = CRM_Utils_Date
::customFormat($campaign->$date, $config->dateformatFull
);
210 if (!empty($dates)) {
211 $title .= ' (' . implode('-', $dates) . ')';
214 $campaigns[$cacheKey][$campaign->id
] = $title;
218 return $campaigns[$cacheKey];
222 * Wrapper to self::getCampaigns( )
223 * w/ permissions and component check.
225 * @param int $includeId
226 * @param int $excludeId
227 * @param bool $onlyActive
228 * @param bool $onlyCurrent
229 * @param bool $appendDatesToTitle
230 * @param bool $forceAll
231 * @param bool $doCheckForComponent
232 * @param bool $doCheckForPermissions
236 public static function getPermissionedCampaigns(
241 $appendDatesToTitle = FALSE,
243 $doCheckForComponent = TRUE,
244 $doCheckForPermissions = TRUE
252 'appendDatesToTitle',
253 'doCheckForComponent',
254 'doCheckForPermissions',
257 foreach ($cachekeyParams as $param) {
258 $cacheKeyParam = $
$param;
259 if (!$cacheKeyParam) {
262 $cacheKey .= '_' . $cacheKeyParam;
265 static $validCampaigns;
266 if (!isset($validCampaigns[$cacheKey])) {
270 'hasAccessCampaign' => FALSE,
271 'isCampaignEnabled' => FALSE,
274 //do check for component.
275 if ($doCheckForComponent) {
276 $campaigns['isCampaignEnabled'] = $isValid = self
::isCampaignEnable();
279 //do check for permissions.
280 if ($doCheckForPermissions) {
281 $campaigns['hasAccessCampaign'] = $isValid = self
::accessCampaign();
284 //finally retrieve campaigns from db.
286 $campaigns['campaigns'] = self
::getCampaigns($includeId,
296 $validCampaigns[$cacheKey] = $campaigns;
299 return $validCampaigns[$cacheKey];
303 * Is CiviCampaign enabled.
306 public static function isCampaignEnable() {
307 static $isEnable = NULL;
309 if (!isset($isEnable)) {
311 $config = CRM_Core_Config
::singleton();
312 if (in_array('CiviCampaign', $config->enableComponents
)) {
321 * Retrieve campaigns for dashboard.
323 * @param array $params
324 * @param bool $onlyCount
328 public static function getCampaignSummary($params = [], $onlyCount = FALSE) {
331 //build the limit and order clause.
332 $limitClause = $orderByClause = $lookupTableJoins = NULL;
335 'sort' => 'start_date',
338 'sortOrder' => 'desc',
340 foreach ($sortParams as $name => $default) {
341 if (!empty($params[$name])) {
342 $sortParams[$name] = $params[$name];
346 //need to lookup tables.
347 $orderOnCampaignTable = TRUE;
348 if ($sortParams['sort'] === 'status') {
349 $orderOnCampaignTable = FALSE;
350 $lookupTableJoins = "
351 LEFT JOIN civicrm_option_value status ON ( status.value = campaign.status_id OR campaign.status_id IS NULL )
352 INNER JOIN civicrm_option_group grp ON ( status.option_group_id = grp.id AND grp.name = 'campaign_status' )";
353 $orderByClause = "ORDER BY status.label {$sortParams['sortOrder']}";
355 elseif ($sortParams['sort'] === 'campaign_type') {
356 $orderOnCampaignTable = FALSE;
357 $lookupTableJoins = "
358 LEFT JOIN civicrm_option_value campaign_type ON ( campaign_type.value = campaign.campaign_type_id
359 OR campaign.campaign_type_id IS NULL )
360 INNER JOIN civicrm_option_group grp ON ( campaign_type.option_group_id = grp.id AND grp.name = 'campaign_type' )";
361 $orderByClause = "ORDER BY campaign_type.label {$sortParams['sortOrder']}";
363 elseif ($sortParams['sort'] === 'isActive') {
364 $sortParams['sort'] = 'is_active';
366 if ($orderOnCampaignTable) {
367 $orderByClause = "ORDER BY campaign.{$sortParams['sort']} {$sortParams['sortOrder']}";
369 $orderByClause = ($orderByClause) ?
$orderByClause . ", campaign.id {$sortParams['sortOrder']}" : $orderByClause;
370 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
373 //build the where clause.
374 $queryParams = $where = [];
375 if (!empty($params['id'])) {
376 $where[] = "( campaign.id = %1 )";
377 $queryParams[1] = [$params['id'], 'Positive'];
379 if (!empty($params['name'])) {
380 $where[] = "( campaign.name LIKE %2 )";
381 $queryParams[2] = ['%' . trim($params['name']) . '%', 'String'];
383 if (!empty($params['title'])) {
384 $where[] = "( campaign.title LIKE %3 )";
385 $queryParams[3] = ['%' . trim($params['title']) . '%', 'String'];
387 if (!empty($params['start_date'])) {
388 $startDate = CRM_Utils_Date
::processDate($params['start_date']);
389 $where[] = "( campaign.start_date >= %4 OR campaign.start_date IS NULL )";
390 $queryParams[4] = [$startDate, 'String'];
392 if (!empty($params['end_date'])) {
393 $endDate = CRM_Utils_Date
::processDate($params['end_date'], '235959');
394 $where[] = "( campaign.end_date <= %5 OR campaign.end_date IS NULL )";
395 $queryParams[5] = [$endDate, 'String'];
397 if (!empty($params['description'])) {
398 $where[] = "( campaign.description LIKE %6 )";
399 $queryParams[6] = ['%' . trim($params['description']) . '%', 'String'];
401 if (!empty($params['campaign_type_id'])) {
402 $where[] = "( campaign.campaign_type_id IN ( %7 ) )";
403 $queryParams[7] = [implode(',', (array) $params['campaign_type_id']), 'CommaSeparatedIntegers'];
405 if (!empty($params['status_id'])) {
406 $where[] = "( campaign.status_id IN ( %8 ) )";
407 $queryParams[8] = [implode(',', (array) $params['status_id']), 'CommaSeparatedIntegers'];
409 if (array_key_exists('is_active', $params)) {
410 $active = "( campaign.is_active = 1 )";
411 if (!empty($params['is_active'])) {
412 $active = "( campaign.is_active = 0 OR campaign.is_active IS NULL )";
417 if (!empty($where)) {
418 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
434 SELECT campaign.id as id,
435 campaign.name as name,
436 campaign.title as title,
437 campaign.is_active as is_active,
438 campaign.status_id as status_id,
439 campaign.end_date as end_date,
440 campaign.start_date as start_date,
441 campaign.description as description,
442 campaign.campaign_type_id as campaign_type_id';
444 $selectClause = 'SELECT COUNT(*)';
446 $fromClause = 'FROM civicrm_campaign campaign';
448 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
450 //in case of only count.
452 return (int) CRM_Core_DAO
::singleValueQuery($query, $queryParams);
455 $campaign = CRM_Core_DAO
::executeQuery($query, $queryParams);
456 while ($campaign->fetch()) {
457 foreach ($properties as $property) {
458 $campaigns[$campaign->id
][$property] = $campaign->$property;
466 * Get the campaign count.
470 public static function getCampaignCount(): int {
471 return (int) CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM civicrm_campaign');
475 * Get Campaigns groups.
477 * @param int $campaignId
482 public static function getCampaignGroups($campaignId) {
483 static $campaignGroups;
488 if (!isset($campaignGroups[$campaignId])) {
489 $campaignGroups[$campaignId] = [];
492 SELECT grp.title, grp.id
493 FROM civicrm_campaign_group campgrp
494 INNER JOIN civicrm_group grp ON ( grp.id = campgrp.entity_id )
495 WHERE campgrp.group_type = 'Include'
496 AND campgrp.entity_table = 'civicrm_group'
497 AND campgrp.campaign_id = %1";
499 $groups = CRM_Core_DAO
::executeQuery($query, [1 => [$campaignId, 'Positive']]);
500 while ($groups->fetch()) {
501 $campaignGroups[$campaignId][$groups->id
] = $groups->title
;
505 return $campaignGroups[$campaignId];
509 * Update the is_active flag in the db.
512 * Id of the database record.
513 * @param bool $is_active
514 * Value we want to set the is_active field.
517 * true if we found and updated the object, else false
519 public static function setIsActive($id, $is_active) {
520 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Campaign', $id, 'is_active', $is_active);
526 public static function accessCampaign() {
527 static $allow = NULL;
529 if (!isset($allow)) {
531 if (CRM_Core_Permission
::check('manage campaign') ||
532 CRM_Core_Permission
::check('administer CiviCampaign')
542 * Add select element for campaign
543 * and assign needful info to templates.
545 * @param CRM_Core_Form $form
546 * @param int $connectedCampaignId
548 public static function addCampaign(&$form, $connectedCampaignId = NULL) {
549 //some forms do set default and freeze.
551 if ($form->get('action') & CRM_Core_Action
::VIEW
) {
552 $appendDates = FALSE;
555 $campaignDetails = self
::getPermissionedCampaigns($connectedCampaignId, NULL, TRUE, TRUE, $appendDates);
557 $campaigns = $campaignDetails['campaigns'] ??
NULL;
558 $hasAccessCampaign = $campaignDetails['hasAccessCampaign'] ??
NULL;
559 $isCampaignEnabled = $campaignDetails['isCampaignEnabled'] ??
NULL;
561 $showAddCampaign = FALSE;
562 if ($connectedCampaignId ||
($isCampaignEnabled && $hasAccessCampaign)) {
563 $showAddCampaign = TRUE;
564 $campaign = $form->addEntityRef('campaign_id', ts('Campaign'), [
565 'entity' => 'Campaign',
567 'select' => ['minimumInputLength' => 0],
569 //lets freeze when user does not has access or campaign is disabled.
570 if (!$isCampaignEnabled ||
!$hasAccessCampaign) {
575 //carry this info to templates.
577 'showAddCampaign' => $showAddCampaign,
578 'hasAccessCampaign' => $hasAccessCampaign,
579 'isCampaignEnabled' => $isCampaignEnabled,
582 $form->assign('campaignInfo', $campaignInfo);
586 * Add campaign in component search.
587 * and assign needful info to templates.
589 * @param CRM_Core_Form $form
590 * @param string $elementName
592 public static function addCampaignInComponentSearch(&$form, $elementName = 'campaign_id') {
594 $campaignDetails = self
::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
595 $campaigns = $campaignDetails['campaigns'] ??
NULL;
596 $hasAccessCampaign = $campaignDetails['hasAccessCampaign'] ??
NULL;
597 $isCampaignEnabled = $campaignDetails['isCampaignEnabled'] ??
NULL;
599 $showCampaignInSearch = FALSE;
600 if ($isCampaignEnabled && $hasAccessCampaign && !empty($campaigns)) {
601 //get the current campaign only.
602 $currentCampaigns = self
::getCampaigns(NULL, NULL, FALSE);
603 $pastCampaigns = array_diff($campaigns, $currentCampaigns);
605 if (!empty($currentCampaigns)) {
606 $allCampaigns = ['crm_optgroup_current_campaign' => ts('Current Campaigns')] +
$currentCampaigns;
608 if (!empty($pastCampaigns)) {
609 $allCampaigns +
= ['crm_optgroup_past_campaign' => ts('Past Campaigns')] +
$pastCampaigns;
612 $showCampaignInSearch = TRUE;
613 $form->add('select', $elementName, ts('Campaigns'), $allCampaigns, FALSE,
614 ['id' => 'campaigns', 'multiple' => 'multiple', 'class' => 'crm-select2']
621 'showCampaignInSearch',
623 foreach ($infoFields as $fld) {
624 $campaignInfo[$fld] = $
$fld;
626 $form->assign('campaignInfo', $campaignInfo);
632 public static function getEntityRefFilters() {
634 ['key' => 'campaign_type_id', 'value' => ts('Campaign Type')],
635 ['key' => 'status_id', 'value' => ts('Status')],
637 'key' => 'start_date',
638 'value' => ts('Start Date'),
640 ['key' => '{">":"now"}', 'value' => ts('Upcoming')],
642 'key' => '{"BETWEEN":["now - 3 month","now"]}',
643 'value' => ts('Past 3 Months'),
646 'key' => '{"BETWEEN":["now - 6 month","now"]}',
647 'value' => ts('Past 6 Months'),
650 'key' => '{"BETWEEN":["now - 1 year","now"]}',
651 'value' => ts('Past Year'),
657 'value' => ts('End Date'),
659 ['key' => '{">":"now"}', 'value' => ts('In the future')],
660 ['key' => '{"<":"now"}', 'value' => ts('In the past')],
661 ['key' => '{"IS NULL":"1"}', 'value' => ts('Not set')],
668 * Links to create new campaigns from entityRef widget
672 public static function getEntityRefCreateLinks() {
673 if (CRM_Core_Permission
::check([['administer CiviCampaign', 'manage campaign']])) {
676 'label' => ts('New Campaign'),
677 'url' => CRM_Utils_System
::url('civicrm/campaign/add', "reset=1",
678 NULL, NULL, FALSE, FALSE, TRUE),
679 'type' => 'Campaign',