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