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