Merge pull request #16967 from wmortada/wp#46-2
[civicrm-core.git] / CRM / Campaign / BAO / Campaign.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Campaign_BAO_Campaign extends CRM_Campaign_DAO_Campaign {
18
19 /**
20 * Takes an associative array and creates a campaign object.
21 *
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
24 * pairs
25 *
26 * @param array $params
27 * (reference ) an assoc array of name/value pairs.
28 *
29 * @return CRM_Campaign_DAO_Campaign
30 */
31 public static function create(&$params) {
32 if (empty($params)) {
33 return NULL;
34 }
35
36 if (empty($params['id'])) {
37
38 if (empty($params['created_id'])) {
39 $session = CRM_Core_Session::singleton();
40 $params['created_id'] = $session->get('userID');
41 }
42
43 if (empty($params['created_date'])) {
44 $params['created_date'] = date('YmdHis');
45 }
46
47 if (empty($params['name'])) {
48 $params['name'] = CRM_Utils_String::titleToVar($params['title'], 64);
49 }
50
51 CRM_Utils_Hook::pre('create', 'Campaign', NULL, $params);
52 }
53 else {
54 CRM_Utils_Hook::pre('edit', 'Campaign', $params['id'], $params);
55 }
56
57 $campaign = new CRM_Campaign_DAO_Campaign();
58 $campaign->copyValues($params);
59 $campaign->save();
60
61 if (!empty($params['id'])) {
62 CRM_Utils_Hook::post('edit', 'Campaign', $campaign->id, $campaign);
63 }
64 else {
65 CRM_Utils_Hook::post('create', 'Campaign', $campaign->id, $campaign);
66 }
67
68 /* Create the campaign group record */
69
70 $groupTableName = CRM_Contact_BAO_Group::getTableName();
71
72 if (isset($params['groups']) && !empty($params['groups']['include']) && is_array($params['groups']['include'])) {
73 foreach ($params['groups']['include'] as $entityId) {
74 $dao = new CRM_Campaign_DAO_CampaignGroup();
75 $dao->campaign_id = $campaign->id;
76 $dao->entity_table = $groupTableName;
77 $dao->entity_id = $entityId;
78 $dao->group_type = 'Include';
79 $dao->save();
80 }
81 }
82
83 //store custom data
84 if (!empty($params['custom']) &&
85 is_array($params['custom'])
86 ) {
87 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_campaign', $campaign->id);
88 }
89
90 return $campaign;
91 }
92
93 /**
94 * Delete the campaign.
95 *
96 * @param int $id
97 * Id of the campaign.
98 *
99 * @return bool|mixed
100 */
101 public static function del($id) {
102 if (!$id) {
103 return FALSE;
104 }
105
106 CRM_Utils_Hook::pre('delete', 'Campaign', $id, CRM_Core_DAO::$_nullArray);
107
108 $dao = new CRM_Campaign_DAO_Campaign();
109 $dao->id = $id;
110 $result = $dao->delete();
111
112 CRM_Utils_Hook::post('delete', 'Campaign', $id, $dao);
113
114 return $result;
115 }
116
117 /**
118 * Retrieve DB object based on input parameters.
119 *
120 * It also stores all the retrieved values in the default array.
121 *
122 * @param array $params
123 * (reference ) an assoc array of name/value pairs.
124 * @param array $defaults
125 * (reference ) an assoc array to hold the flattened values.
126 *
127 * @return \CRM_Campaign_DAO_Campaign|null
128 */
129 public static function retrieve(&$params, &$defaults) {
130 $campaign = new CRM_Campaign_DAO_Campaign();
131
132 $campaign->copyValues($params);
133
134 if ($campaign->find(TRUE)) {
135 CRM_Core_DAO::storeValues($campaign, $defaults);
136 return $campaign;
137 }
138 return NULL;
139 }
140
141 /**
142 * Return the all eligible campaigns w/ cache.
143 *
144 * @param int $includeId
145 * Lets inlcude this campaign by force.
146 * @param int $excludeId
147 * Do not include this campaign.
148 * @param bool $onlyActive
149 * Consider only active campaigns.
150 *
151 * @param bool $onlyCurrent
152 * @param bool $appendDatesToTitle
153 * @param bool $forceAll
154 *
155 * @return mixed
156 * $campaigns a set of campaigns.
157 */
158 public static function getCampaigns(
159 $includeId = NULL,
160 $excludeId = NULL,
161 $onlyActive = TRUE,
162 $onlyCurrent = TRUE,
163 $appendDatesToTitle = FALSE,
164 $forceAll = FALSE
165 ) {
166 static $campaigns;
167 $cacheKey = 0;
168 $cacheKeyParams = [
169 'includeId',
170 'excludeId',
171 'onlyActive',
172 'onlyCurrent',
173 'appendDatesToTitle',
174 'forceAll',
175 ];
176 foreach ($cacheKeyParams as $param) {
177 $cacheParam = $$param;
178 if (!$cacheParam) {
179 $cacheParam = 0;
180 }
181 $cacheKey .= '_' . $cacheParam;
182 }
183
184 if (!isset($campaigns[$cacheKey])) {
185 $where = ['( camp.title IS NOT NULL )'];
186 if ($excludeId) {
187 $where[] = "( camp.id != $excludeId )";
188 }
189 if ($onlyActive) {
190 $where[] = '( camp.is_active = 1 )';
191 }
192 if ($onlyCurrent) {
193 $where[] = '( camp.end_date IS NULL OR camp.end_date >= NOW() )';
194 }
195 $whereClause = implode(' AND ', $where);
196 if ($includeId) {
197 $whereClause .= " OR ( camp.id = $includeId )";
198 }
199
200 //lets force all.
201 if ($forceAll) {
202 $whereClause = '( 1 )';
203 }
204
205 $query = "
206 SELECT camp.id,
207 camp.title,
208 camp.start_date,
209 camp.end_date
210 FROM civicrm_campaign camp
211 WHERE {$whereClause}
212 Order By camp.title";
213
214 $campaign = CRM_Core_DAO::executeQuery($query);
215 $campaigns[$cacheKey] = [];
216 $config = CRM_Core_Config::singleton();
217
218 while ($campaign->fetch()) {
219 $title = $campaign->title;
220 if ($appendDatesToTitle) {
221 $dates = [];
222 foreach (['start_date', 'end_date'] as $date) {
223 if ($campaign->$date) {
224 $dates[] = CRM_Utils_Date::customFormat($campaign->$date, $config->dateformatFull);
225 }
226 }
227 if (!empty($dates)) {
228 $title .= ' (' . implode('-', $dates) . ')';
229 }
230 }
231 $campaigns[$cacheKey][$campaign->id] = $title;
232 }
233 }
234
235 return $campaigns[$cacheKey];
236 }
237
238 /**
239 * Wrapper to self::getCampaigns( )
240 * w/ permissions and component check.
241 *
242 * @param int $includeId
243 * @param int $excludeId
244 * @param bool $onlyActive
245 * @param bool $onlyCurrent
246 * @param bool $appendDatesToTitle
247 * @param bool $forceAll
248 * @param bool $doCheckForComponent
249 * @param bool $doCheckForPermissions
250 *
251 * @return mixed
252 */
253 public static function getPermissionedCampaigns(
254 $includeId = NULL,
255 $excludeId = NULL,
256 $onlyActive = TRUE,
257 $onlyCurrent = TRUE,
258 $appendDatesToTitle = FALSE,
259 $forceAll = FALSE,
260 $doCheckForComponent = TRUE,
261 $doCheckForPermissions = TRUE
262 ) {
263 $cacheKey = 0;
264 $cachekeyParams = [
265 'includeId',
266 'excludeId',
267 'onlyActive',
268 'onlyCurrent',
269 'appendDatesToTitle',
270 'doCheckForComponent',
271 'doCheckForPermissions',
272 'forceAll',
273 ];
274 foreach ($cachekeyParams as $param) {
275 $cacheKeyParam = $$param;
276 if (!$cacheKeyParam) {
277 $cacheKeyParam = 0;
278 }
279 $cacheKey .= '_' . $cacheKeyParam;
280 }
281
282 static $validCampaigns;
283 if (!isset($validCampaigns[$cacheKey])) {
284 $isValid = TRUE;
285 $campaigns = [
286 'campaigns' => [],
287 'hasAccessCampaign' => FALSE,
288 'isCampaignEnabled' => FALSE,
289 ];
290
291 //do check for component.
292 if ($doCheckForComponent) {
293 $campaigns['isCampaignEnabled'] = $isValid = self::isCampaignEnable();
294 }
295
296 //do check for permissions.
297 if ($doCheckForPermissions) {
298 $campaigns['hasAccessCampaign'] = $isValid = self::accessCampaign();
299 }
300
301 //finally retrieve campaigns from db.
302 if ($isValid) {
303 $campaigns['campaigns'] = self::getCampaigns($includeId,
304 $excludeId,
305 $onlyActive,
306 $onlyCurrent,
307 $appendDatesToTitle,
308 $forceAll
309 );
310 }
311
312 //store in cache.
313 $validCampaigns[$cacheKey] = $campaigns;
314 }
315
316 return $validCampaigns[$cacheKey];
317 }
318
319 /**
320 * Is CiviCampaign enabled.
321 * @return bool
322 */
323 public static function isCampaignEnable() {
324 static $isEnable = NULL;
325
326 if (!isset($isEnable)) {
327 $isEnable = FALSE;
328 $config = CRM_Core_Config::singleton();
329 if (in_array('CiviCampaign', $config->enableComponents)) {
330 $isEnable = TRUE;
331 }
332 }
333
334 return $isEnable;
335 }
336
337 /**
338 * Retrieve campaigns for dashboard.
339 *
340 * @param array $params
341 * @param bool $onlyCount
342 *
343 * @return array|int
344 */
345 public static function getCampaignSummary($params = [], $onlyCount = FALSE) {
346 $campaigns = [];
347
348 //build the limit and order clause.
349 $limitClause = $orderByClause = $lookupTableJoins = NULL;
350 if (!$onlyCount) {
351 $sortParams = [
352 'sort' => 'start_date',
353 'offset' => 0,
354 'rowCount' => 10,
355 'sortOrder' => 'desc',
356 ];
357 foreach ($sortParams as $name => $default) {
358 if (!empty($params[$name])) {
359 $sortParams[$name] = $params[$name];
360 }
361 }
362
363 //need to lookup tables.
364 $orderOnCampaignTable = TRUE;
365 if ($sortParams['sort'] == 'status') {
366 $orderOnCampaignTable = FALSE;
367 $lookupTableJoins = "
368 LEFT JOIN civicrm_option_value status ON ( status.value = campaign.status_id OR campaign.status_id IS NULL )
369 INNER JOIN civicrm_option_group grp ON ( status.option_group_id = grp.id AND grp.name = 'campaign_status' )";
370 $orderByClause = "ORDER BY status.label {$sortParams['sortOrder']}";
371 }
372 elseif ($sortParams['sort'] == 'campaign_type') {
373 $orderOnCampaignTable = FALSE;
374 $lookupTableJoins = "
375 LEFT JOIN civicrm_option_value campaign_type ON ( campaign_type.value = campaign.campaign_type_id
376 OR campaign.campaign_type_id IS NULL )
377 INNER JOIN civicrm_option_group grp ON ( campaign_type.option_group_id = grp.id AND grp.name = 'campaign_type' )";
378 $orderByClause = "ORDER BY campaign_type.label {$sortParams['sortOrder']}";
379 }
380 elseif ($sortParams['sort'] == 'isActive') {
381 $sortParams['sort'] = 'is_active';
382 }
383 if ($orderOnCampaignTable) {
384 $orderByClause = "ORDER BY campaign.{$sortParams['sort']} {$sortParams['sortOrder']}";
385 }
386 $orderByClause = ($orderByClause) ? $orderByClause . ", campaign.id {$sortParams['sortOrder']}" : $orderByClause;
387 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
388 }
389
390 //build the where clause.
391 $queryParams = $where = [];
392 if (!empty($params['id'])) {
393 $where[] = "( campaign.id = %1 )";
394 $queryParams[1] = [$params['id'], 'Positive'];
395 }
396 if (!empty($params['name'])) {
397 $where[] = "( campaign.name LIKE %2 )";
398 $queryParams[2] = ['%' . trim($params['name']) . '%', 'String'];
399 }
400 if (!empty($params['title'])) {
401 $where[] = "( campaign.title LIKE %3 )";
402 $queryParams[3] = ['%' . trim($params['title']) . '%', 'String'];
403 }
404 if (!empty($params['start_date'])) {
405 $startDate = CRM_Utils_Date::processDate($params['start_date']);
406 $where[] = "( campaign.start_date >= %4 OR campaign.start_date IS NULL )";
407 $queryParams[4] = [$startDate, 'String'];
408 }
409 if (!empty($params['end_date'])) {
410 $endDate = CRM_Utils_Date::processDate($params['end_date'], '235959');
411 $where[] = "( campaign.end_date <= %5 OR campaign.end_date IS NULL )";
412 $queryParams[5] = [$endDate, 'String'];
413 }
414 if (!empty($params['description'])) {
415 $where[] = "( campaign.description LIKE %6 )";
416 $queryParams[6] = ['%' . trim($params['description']) . '%', 'String'];
417 }
418 if (!empty($params['campaign_type_id'])) {
419 $where[] = "( campaign.campaign_type_id IN ( %7 ) )";
420 $queryParams[7] = [implode(',', (array) $params['campaign_type_id']), 'CommaSeparatedIntegers'];
421 }
422 if (!empty($params['status_id'])) {
423 $where[] = "( campaign.status_id IN ( %8 ) )";
424 $queryParams[8] = [implode(',', (array) $params['status_id']), 'CommaSeparatedIntegers'];
425 }
426 if (array_key_exists('is_active', $params)) {
427 $active = "( campaign.is_active = 1 )";
428 if (!empty($params['is_active'])) {
429 $active = "( campaign.is_active = 0 OR campaign.is_active IS NULL )";
430 }
431 $where[] = $active;
432 }
433 $whereClause = NULL;
434 if (!empty($where)) {
435 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
436 }
437
438 $properties = [
439 'id',
440 'name',
441 'title',
442 'start_date',
443 'end_date',
444 'status_id',
445 'is_active',
446 'description',
447 'campaign_type_id',
448 ];
449
450 $selectClause = '
451 SELECT campaign.id as id,
452 campaign.name as name,
453 campaign.title as title,
454 campaign.is_active as is_active,
455 campaign.status_id as status_id,
456 campaign.end_date as end_date,
457 campaign.start_date as start_date,
458 campaign.description as description,
459 campaign.campaign_type_id as campaign_type_id';
460 if ($onlyCount) {
461 $selectClause = 'SELECT COUNT(*)';
462 }
463 $fromClause = 'FROM civicrm_campaign campaign';
464
465 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
466
467 //in case of only count.
468 if ($onlyCount) {
469 return (int) CRM_Core_DAO::singleValueQuery($query, $queryParams);
470 }
471
472 $campaign = CRM_Core_DAO::executeQuery($query, $queryParams);
473 while ($campaign->fetch()) {
474 foreach ($properties as $property) {
475 $campaigns[$campaign->id][$property] = $campaign->$property;
476 }
477 }
478
479 return $campaigns;
480 }
481
482 /**
483 * Get the campaign count.
484 *
485 */
486 public static function getCampaignCount() {
487 return (int) CRM_Core_DAO::singleValueQuery('SELECT COUNT(*) FROM civicrm_campaign');
488 }
489
490 /**
491 * Get Campaigns groups.
492 *
493 * @param int $campaignId
494 * Campaign id.
495 *
496 * @return array
497 */
498 public static function getCampaignGroups($campaignId) {
499 static $campaignGroups;
500 if (!$campaignId) {
501 return [];
502 }
503
504 if (!isset($campaignGroups[$campaignId])) {
505 $campaignGroups[$campaignId] = [];
506
507 $query = "
508 SELECT grp.title, grp.id
509 FROM civicrm_campaign_group campgrp
510 INNER JOIN civicrm_group grp ON ( grp.id = campgrp.entity_id )
511 WHERE campgrp.group_type = 'Include'
512 AND campgrp.entity_table = 'civicrm_group'
513 AND campgrp.campaign_id = %1";
514
515 $groups = CRM_Core_DAO::executeQuery($query, [1 => [$campaignId, 'Positive']]);
516 while ($groups->fetch()) {
517 $campaignGroups[$campaignId][$groups->id] = $groups->title;
518 }
519 }
520
521 return $campaignGroups[$campaignId];
522 }
523
524 /**
525 * Update the is_active flag in the db.
526 *
527 * @param int $id
528 * Id of the database record.
529 * @param bool $is_active
530 * Value we want to set the is_active field.
531 *
532 * @return bool
533 * true if we found and updated the object, else false
534 */
535 public static function setIsActive($id, $is_active) {
536 return CRM_Core_DAO::setFieldValue('CRM_Campaign_DAO_Campaign', $id, 'is_active', $is_active);
537 }
538
539 /**
540 * @return bool
541 */
542 public static function accessCampaign() {
543 static $allow = NULL;
544
545 if (!isset($allow)) {
546 $allow = FALSE;
547 if (CRM_Core_Permission::check('manage campaign') ||
548 CRM_Core_Permission::check('administer CiviCampaign')
549 ) {
550 $allow = TRUE;
551 }
552 }
553
554 return $allow;
555 }
556
557 /**
558 * Add select element for campaign
559 * and assign needful info to templates.
560 *
561 * @param CRM_Core_Form $form
562 * @param int $connectedCampaignId
563 */
564 public static function addCampaign(&$form, $connectedCampaignId = NULL) {
565 //some forms do set default and freeze.
566 $appendDates = TRUE;
567 if ($form->get('action') & CRM_Core_Action::VIEW) {
568 $appendDates = FALSE;
569 }
570
571 $campaignDetails = self::getPermissionedCampaigns($connectedCampaignId, NULL, TRUE, TRUE, $appendDates);
572
573 $campaigns = $campaignDetails['campaigns'] ?? NULL;
574 $hasAccessCampaign = $campaignDetails['hasAccessCampaign'] ?? NULL;
575 $isCampaignEnabled = $campaignDetails['isCampaignEnabled'] ?? NULL;
576
577 $showAddCampaign = FALSE;
578 if ($connectedCampaignId || ($isCampaignEnabled && $hasAccessCampaign)) {
579 $showAddCampaign = TRUE;
580 $campaign = $form->addEntityRef('campaign_id', ts('Campaign'), [
581 'entity' => 'Campaign',
582 'create' => TRUE,
583 'select' => ['minimumInputLength' => 0],
584 ]);
585 //lets freeze when user does not has access or campaign is disabled.
586 if (!$isCampaignEnabled || !$hasAccessCampaign) {
587 $campaign->freeze();
588 }
589 }
590
591 //carry this info to templates.
592 $campaignInfo = [
593 'showAddCampaign' => $showAddCampaign,
594 'hasAccessCampaign' => $hasAccessCampaign,
595 'isCampaignEnabled' => $isCampaignEnabled,
596 ];
597
598 $form->assign('campaignInfo', $campaignInfo);
599 }
600
601 /**
602 * Add campaign in component search.
603 * and assign needful info to templates.
604 *
605 * @param CRM_Core_Form $form
606 * @param string $elementName
607 */
608 public static function addCampaignInComponentSearch(&$form, $elementName = 'campaign_id') {
609 $campaignInfo = [];
610 $campaignDetails = self::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
611 $fields = ['campaigns', 'hasAccessCampaign', 'isCampaignEnabled'];
612 foreach ($fields as $fld) {
613 $$fld = $campaignDetails[$fld] ?? NULL;
614 }
615 $showCampaignInSearch = FALSE;
616 if ($isCampaignEnabled && $hasAccessCampaign && !empty($campaigns)) {
617 //get the current campaign only.
618 $currentCampaigns = self::getCampaigns(NULL, NULL, FALSE);
619 $pastCampaigns = array_diff($campaigns, $currentCampaigns);
620 $allCampaigns = [];
621 if (!empty($currentCampaigns)) {
622 $allCampaigns = ['crm_optgroup_current_campaign' => ts('Current Campaigns')] + $currentCampaigns;
623 }
624 if (!empty($pastCampaigns)) {
625 $allCampaigns += ['crm_optgroup_past_campaign' => ts('Past Campaigns')] + $pastCampaigns;
626 }
627
628 $showCampaignInSearch = TRUE;
629 $form->add('select', $elementName, ts('Campaigns'), $allCampaigns, FALSE,
630 ['id' => 'campaigns', 'multiple' => 'multiple', 'class' => 'crm-select2']
631 );
632 }
633 $infoFields = [
634 'elementName',
635 'hasAccessCampaign',
636 'isCampaignEnabled',
637 'showCampaignInSearch',
638 ];
639 foreach ($infoFields as $fld) {
640 $campaignInfo[$fld] = $$fld;
641 }
642 $form->assign('campaignInfo', $campaignInfo);
643 }
644
645 /**
646 * @return array
647 */
648 public static function getEntityRefFilters() {
649 return [
650 ['key' => 'campaign_type_id', 'value' => ts('Campaign Type')],
651 ['key' => 'status_id', 'value' => ts('Status')],
652 [
653 'key' => 'start_date',
654 'value' => ts('Start Date'),
655 'options' => [
656 ['key' => '{">":"now"}', 'value' => ts('Upcoming')],
657 [
658 'key' => '{"BETWEEN":["now - 3 month","now"]}',
659 'value' => ts('Past 3 Months'),
660 ],
661 [
662 'key' => '{"BETWEEN":["now - 6 month","now"]}',
663 'value' => ts('Past 6 Months'),
664 ],
665 [
666 'key' => '{"BETWEEN":["now - 1 year","now"]}',
667 'value' => ts('Past Year'),
668 ],
669 ],
670 ],
671 [
672 'key' => 'end_date',
673 'value' => ts('End Date'),
674 'options' => [
675 ['key' => '{">":"now"}', 'value' => ts('In the future')],
676 ['key' => '{"<":"now"}', 'value' => ts('In the past')],
677 ['key' => '{"IS NULL":"1"}', 'value' => ts('Not set')],
678 ],
679 ],
680 ];
681 }
682
683 /**
684 * Links to create new campaigns from entityRef widget
685 *
686 * @return array|bool
687 */
688 public static function getEntityRefCreateLinks() {
689 if (CRM_Core_Permission::check([['administer CiviCampaign', 'manage campaign']])) {
690 return [
691 [
692 'label' => ts('New Campaign'),
693 'url' => CRM_Utils_System::url('civicrm/campaign/add', "reset=1",
694 NULL, NULL, FALSE, FALSE, TRUE),
695 'type' => 'Campaign',
696 ],
697 ];
698 }
699 return FALSE;
700 }
701
702 }