INFRA-132 - CRM/Campaign - Convert single-line @param to multi-line
[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 object
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 $campaigns a set of campaigns.@access public
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 = array(
169 'includeId', 'excludeId', 'onlyActive',
170 'onlyCurrent', 'appendDatesToTitle', 'forceAll',
171 );
172 foreach ($cacheKeyParams as $param) {
173 $cacheParam = $$param;
174 if (!$cacheParam) {
175 $cacheParam = 0;
176 }
177 $cacheKey .= '_' . $cacheParam;
178 }
179
180 if (!isset($campaigns[$cacheKey])) {
181 $where = array('( camp.title IS NOT NULL )');
182 if ($excludeId) {
183 $where[] = "( camp.id != $excludeId )";
184 }
185 if ($onlyActive) {
186 $where[] = '( camp.is_active = 1 )';
187 }
188 if ($onlyCurrent) {
189 $where[] = '( camp.end_date IS NULL OR camp.end_date >= NOW() )';
190 }
191 $whereClause = implode(' AND ', $where);
192 if ($includeId) {
193 $whereClause .= " OR ( camp.id = $includeId )";
194 }
195
196 //lets force all.
197 if ($forceAll) {
198 $whereClause = '( 1 )';
199 }
200
201 $query = "
202 SELECT camp.id,
203 camp.title,
204 camp.start_date,
205 camp.end_date
206 FROM civicrm_campaign camp
207 WHERE {$whereClause}
208 Order By camp.title";
209
210 $campaign = CRM_Core_DAO::executeQuery($query);
211 $campaigns[$cacheKey] = array();
212 $config = CRM_Core_Config::singleton();
213
214 while ($campaign->fetch()) {
215 $title = $campaign->title;
216 if ($appendDatesToTitle) {
217 $dates = array();
218 foreach (array('start_date', 'end_date') as $date) {
219 if ($campaign->$date) {
220 $dates[] = CRM_Utils_Date::customFormat($campaign->$date, $config->dateformatFull);
221 }
222 }
223 if (!empty($dates)) {
224 $title .= ' (' . implode('-', $dates) . ')';
225 }
226 }
227 $campaigns[$cacheKey][$campaign->id] = $title;
228 }
229 }
230
231 return $campaigns[$cacheKey];
232 }
233
234 /**
235 * Wrapper to self::getCampaigns( )
236 * w/ permissions and component check.
237 *
238 */
239 public static function getPermissionedCampaigns($includeId = NULL,
240 $excludeId = NULL,
241 $onlyActive = TRUE,
242 $onlyCurrent = TRUE,
243 $appendDatesToTitle = FALSE,
244 $forceAll = FALSE,
245 $doCheckForComponent = TRUE,
246 $doCheckForPermissions = TRUE
247 ) {
248 $cacheKey = 0;
249 $cachekeyParams = array(
250 'includeId', 'excludeId', 'onlyActive', 'onlyCurrent',
251 'appendDatesToTitle', 'doCheckForComponent', 'doCheckForPermissions', 'forceAll',
252 );
253 foreach ($cachekeyParams as $param) {
254 $cacheKeyParam = $$param;
255 if (!$cacheKeyParam) {
256 $cacheKeyParam = 0;
257 }
258 $cacheKey .= '_' . $cacheKeyParam;
259 }
260
261 static $validCampaigns;
262 if (!isset($validCampaigns[$cacheKey])) {
263 $isValid = TRUE;
264 $campaigns = array('campaigns' => array(),
265 'hasAccessCampaign' => FALSE,
266 'isCampaignEnabled' => FALSE,
267 );
268
269 //do check for component.
270 if ($doCheckForComponent) {
271 $campaigns['isCampaignEnabled'] = $isValid = self::isCampaignEnable();
272 }
273
274 //do check for permissions.
275 if ($doCheckForPermissions) {
276 $campaigns['hasAccessCampaign'] = $isValid = self::accessCampaign();
277 }
278
279 //finally retrieve campaigns from db.
280 if ($isValid) {
281 $campaigns['campaigns'] = self::getCampaigns($includeId,
282 $excludeId,
283 $onlyActive,
284 $onlyCurrent,
285 $appendDatesToTitle,
286 $forceAll
287 );
288 }
289
290 //store in cache.
291 $validCampaigns[$cacheKey] = $campaigns;
292 }
293
294 return $validCampaigns[$cacheKey];
295 }
296
297 /**
298 * Is CiviCampaign enabled.
299 * @return bool
300 */
301 public static function isCampaignEnable() {
302 static $isEnable = NULL;
303
304 if (!isset($isEnable)) {
305 $isEnable = FALSE;
306 $config = CRM_Core_Config::singleton();
307 if (in_array('CiviCampaign', $config->enableComponents)) {
308 $isEnable = TRUE;
309 }
310 }
311
312 return $isEnable;
313 }
314
315 /**
316 * Retrieve campaigns for dashboard.
317 *
318 * @static
319 */
320 public static function getCampaignSummary($params = array(), $onlyCount = FALSE) {
321 $campaigns = array();
322
323 //build the limit and order clause.
324 $limitClause = $orderByClause = $lookupTableJoins = NULL;
325 if (!$onlyCount) {
326 $sortParams = array(
327 'sort' => 'start_date',
328 'offset' => 0,
329 'rowCount' => 10,
330 'sortOrder' => 'desc',
331 );
332 foreach ($sortParams as $name => $default) {
333 if (!empty($params[$name])) {
334 $sortParams[$name] = $params[$name];
335 }
336 }
337
338
339 //need to lookup tables.
340 $orderOnCampaignTable = TRUE;
341 if ($sortParams['sort'] == 'status') {
342 $orderOnCampaignTable = FALSE;
343 $lookupTableJoins = "
344 LEFT JOIN civicrm_option_value status ON ( status.value = campaign.status_id OR campaign.status_id IS NULL )
345 INNER JOIN civicrm_option_group grp ON ( status.option_group_id = grp.id AND grp.name = 'campaign_status' )";
346 $orderByClause = "ORDER BY status.label {$sortParams['sortOrder']}";
347 }
348 elseif ($sortParams['sort'] == 'campaign_type') {
349 $orderOnCampaignTable = FALSE;
350 $lookupTableJoins = "
351 LEFT JOIN civicrm_option_value campaign_type ON ( campaign_type.value = campaign.campaign_type_id
352 OR campaign.campaign_type_id IS NULL )
353 INNER JOIN civicrm_option_group grp ON ( campaign_type.option_group_id = grp.id AND grp.name = 'campaign_type' )";
354 $orderByClause = "ORDER BY campaign_type.label {$sortParams['sortOrder']}";
355 }
356 elseif ($sortParams['sort'] == 'isActive') {
357 $sortParams['sort'] = 'is_active';
358 }
359 if ($orderOnCampaignTable) {
360 $orderByClause = "ORDER BY campaign.{$sortParams['sort']} {$sortParams['sortOrder']}";
361 }
362 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
363 }
364
365 //build the where clause.
366 $queryParams = $where = array();
367 if (!empty($params['id'])) {
368 $where[] = "( campaign.id = %1 )";
369 $queryParams[1] = array($params['id'], 'Positive');
370 }
371 if (!empty($params['name'])) {
372 $where[] = "( campaign.name LIKE %2 )";
373 $queryParams[2] = array('%' . trim($params['name']) . '%', 'String');
374 }
375 if (!empty($params['title'])) {
376 $where[] = "( campaign.title LIKE %3 )";
377 $queryParams[3] = array('%' . trim($params['title']) . '%', 'String');
378 }
379 if (!empty($params['start_date'])) {
380 $startDate = CRM_Utils_Date::processDate($params['start_date']);
381 $where[] = "( campaign.start_date >= %4 OR campaign.start_date IS NULL )";
382 $queryParams[4] = array($startDate, 'String');
383 }
384 if (!empty($params['end_date'])) {
385 $endDate = CRM_Utils_Date::processDate($params['end_date'], '235959');
386 $where[] = "( campaign.end_date <= %5 OR campaign.end_date IS NULL )";
387 $queryParams[5] = array($endDate, 'String');
388 }
389 if (!empty($params['description'])) {
390 $where[] = "( campaign.description LIKE %6 )";
391 $queryParams[6] = array('%' . trim($params['description']) . '%', 'String');
392 }
393 if (!empty($params['campaign_type_id'])) {
394 $typeId = $params['campaign_type_id'];
395 if (is_array($params['campaign_type_id'])) {
396 $typeId = implode(' , ', $params['campaign_type_id']);
397 }
398 $where[] = "( campaign.campaign_type_id IN ( {$typeId} ) )";
399 }
400 if (!empty($params['status_id'])) {
401 $statusId = $params['status_id'];
402 if (is_array($params['status_id'])) {
403 $statusId = implode(' , ', $params['status_id']);
404 }
405 $where[] = "( campaign.status_id IN ( {$statusId} ) )";
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 = array(
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 * @static
467 */
468 public static function getCampaignCount() {
469 return (int)CRM_Core_DAO::singleValueQuery('SELECT COUNT(*) FROM civicrm_campaign');
470 }
471
472 /**
473 * Get Campaigns groups
474 *
475 * @param int $campaignId
476 * Campaign id.
477 *
478 * @return array
479 * @static
480 */
481 public static function getCampaignGroups($campaignId) {
482 static $campaignGroups;
483 if (!$campaignId) {
484 return array();
485 }
486
487 if (!isset($campaignGroups[$campaignId])) {
488 $campaignGroups[$campaignId] = array();
489
490 $query = "
491 SELECT grp.title, grp.id
492 FROM civicrm_campaign_group campgrp
493 INNER JOIN civicrm_group grp ON ( grp.id = campgrp.entity_id )
494 WHERE campgrp.group_type = 'Include'
495 AND campgrp.entity_table = 'civicrm_group'
496 AND campgrp.campaign_id = %1";
497
498 $groups = CRM_Core_DAO::executeQuery($query, array(1 => array($campaignId, 'Positive')));
499 while ($groups->fetch()) {
500 $campaignGroups[$campaignId][$groups->id] = $groups->title;
501 }
502 }
503
504 return $campaignGroups[$campaignId];
505 }
506
507 /**
508 * Update the is_active flag in the db
509 *
510 * @param int $id
511 * Id of the database record.
512 * @param bool $is_active
513 * Value we want to set the is_active field.
514 *
515 * @return Object DAO object on sucess, null otherwise
516 * @static
517 */
518 public static function setIsActive($id, $is_active) {
519 return CRM_Core_DAO::setFieldValue('CRM_Campaign_DAO_Campaign', $id, 'is_active', $is_active);
520 }
521
522 /**
523 * @return bool
524 */
525 public static function accessCampaign() {
526 static $allow = NULL;
527
528 if (!isset($allow)) {
529 $allow = FALSE;
530 if (CRM_Core_Permission::check('manage campaign') ||
531 CRM_Core_Permission::check('administer CiviCampaign')
532 ) {
533 $allow = TRUE;
534 }
535 }
536
537 return $allow;
538 }
539
540 /*
541 * Add select element for campaign
542 * and assign needful info to templates.
543 *
544 */
545 /**
546 * @param CRM_Core_Form $form
547 * @param int $connectedCampaignId
548 */
549 public static function addCampaign(&$form, $connectedCampaignId = NULL) {
550 //some forms do set default and freeze.
551 $appendDates = TRUE;
552 if ($form->get('action') & CRM_Core_Action::VIEW) {
553 $appendDates = FALSE;
554 }
555
556 $campaignDetails = self::getPermissionedCampaigns($connectedCampaignId, NULL, TRUE, TRUE, $appendDates);
557 $fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
558 foreach ($fields as $fld)$$fld = CRM_Utils_Array::value($fld, $campaignDetails);
559
560 //lets see do we have past campaigns.
561 $hasPastCampaigns = FALSE;
562 $allActiveCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, TRUE, FALSE);
563 if (count($allActiveCampaigns) > count($campaigns)) {
564 $hasPastCampaigns = TRUE;
565 }
566 $hasCampaigns = FALSE;
567 if (!empty($campaigns)) {
568 $hasCampaigns = TRUE;
569 }
570 if ($hasPastCampaigns) {
571 $hasCampaigns = TRUE;
572 $form->add('hidden', 'included_past_campaigns');
573 }
574
575 $showAddCampaign = FALSE;
576 $alreadyIncludedPastCampaigns = FALSE;
577 if ($connectedCampaignId || ($isCampaignEnabled && $hasAccessCampaign)) {
578 $showAddCampaign = TRUE;
579 //lets add past campaigns as options to quick-form element.
580 if ($hasPastCampaigns && $form->getElementValue('included_past_campaigns')) {
581 $campaigns = $allActiveCampaigns;
582 $alreadyIncludedPastCampaigns = TRUE;
583 }
584 $campaign = &$form->add('select',
585 'campaign_id',
586 ts('Campaign'),
587 array('' => ts('- select -')) + $campaigns,
588 FALSE,
589 array('class' => 'crm-select2')
590 );
591 //lets freeze when user does not has access or campaign is disabled.
592 if (!$isCampaignEnabled || !$hasAccessCampaign) {
593 $campaign->freeze();
594 }
595 }
596
597 $addCampaignURL = NULL;
598 if (empty($campaigns) && $hasAccessCampaign && $isCampaignEnabled) {
599 $addCampaignURL = CRM_Utils_System::url('civicrm/campaign/add', 'reset=1');
600 }
601
602 $includePastCampaignURL = NULL;
603 if ($hasPastCampaigns && $isCampaignEnabled && $hasAccessCampaign) {
604 $includePastCampaignURL = CRM_Utils_System::url('civicrm/ajax/rest',
605 'className=CRM_Campaign_Page_AJAX&fnName=allActiveCampaigns',
606 FALSE, NULL, FALSE
607 );
608 }
609
610 //carry this info to templates.
611 $infoFields = array(
612 'hasCampaigns',
613 'addCampaignURL',
614 'showAddCampaign',
615 'hasPastCampaigns',
616 'hasAccessCampaign',
617 'isCampaignEnabled',
618 'includePastCampaignURL',
619 'alreadyIncludedPastCampaigns',
620 );
621 foreach ($infoFields as $fld) $campaignInfo[$fld] = $$fld;
622 $form->assign('campaignInfo', $campaignInfo);
623 }
624
625 /**
626 * Add campaign in compoent search.
627 * and assign needful info to templates.
628 *
629 * @param CRM_Core_Form $form
630 * @param string $elementName
631 */
632 public static function addCampaignInComponentSearch(&$form, $elementName = 'campaign_id') {
633 $campaignInfo = array();
634 $campaignDetails = self::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
635 $fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
636 foreach ($fields as $fld)$$fld = CRM_Utils_Array::value($fld, $campaignDetails);
637 $showCampaignInSearch = FALSE;
638 if ($isCampaignEnabled && $hasAccessCampaign && !empty($campaigns)) {
639 //get the current campaign only.
640 $currentCampaigns = self::getCampaigns(NULL, NULL, FALSE);
641 $pastCampaigns = array_diff($campaigns, $currentCampaigns);
642 $allCampaigns = array();
643 if (!empty($currentCampaigns)) {
644 $allCampaigns = array('crm_optgroup_current_campaign' => ts('Current Campaigns')) + $currentCampaigns;
645 }
646 if (!empty($pastCampaigns)) {
647 $allCampaigns += array('crm_optgroup_past_campaign' => ts('Past Campaigns')) + $pastCampaigns;
648 }
649
650 $showCampaignInSearch = TRUE;
651 $form->add('select', $elementName, ts('Campaigns'), $allCampaigns, FALSE,
652 array('id' => 'campaigns', 'multiple' => 'multiple', 'class' => 'crm-select2')
653 );
654 }
655 $infoFields = array(
656 'elementName',
657 'hasAccessCampaign',
658 'isCampaignEnabled',
659 'showCampaignInSearch',
660 );
661 foreach ($infoFields as $fld) $campaignInfo[$fld] = $$fld;
662 $form->assign('campaignInfo', $campaignInfo);
663 }
664 }