3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2016
33 class CRM_Campaign_BAO_Campaign
extends CRM_Campaign_DAO_Campaign
{
36 * Takes an associative array and creates a campaign object.
38 * the function extract all the params it needs to initialize the create a
39 * contact object. the params array could contain additional unused name/value
42 * @param array $params
43 * (reference ) an assoc array of name/value pairs.
45 * @return CRM_Campaign_DAO_Campaign
47 public static function create(&$params) {
52 if (!(CRM_Utils_Array
::value('id', $params))) {
54 if (!(CRM_Utils_Array
::value('created_id', $params))) {
55 $session = CRM_Core_Session
::singleton();
56 $params['created_id'] = $session->get('userID');
59 if (!(CRM_Utils_Array
::value('created_date', $params))) {
60 $params['created_date'] = date('YmdHis');
63 if (!(CRM_Utils_Array
::value('name', $params))) {
64 $params['name'] = CRM_Utils_String
::titleToVar($params['title'], 64);
67 CRM_Utils_Hook
::pre('create', 'Campaign', NULL, $params);
70 CRM_Utils_Hook
::pre('edit', 'Campaign', $params['id'], $params);
73 $campaign = new CRM_Campaign_DAO_Campaign();
74 $campaign->copyValues($params);
77 if (!empty($params['id'])) {
78 CRM_Utils_Hook
::post('edit', 'Campaign', $campaign->id
, $campaign);
81 CRM_Utils_Hook
::post('create', 'Campaign', $campaign->id
, $campaign);
84 /* Create the campaign group record */
86 $groupTableName = CRM_Contact_BAO_Group
::getTableName();
88 if (isset($params['groups']) && !empty($params['groups']['include']) && is_array($params['groups']['include'])) {
89 foreach ($params['groups']['include'] as $entityId) {
90 $dao = new CRM_Campaign_DAO_CampaignGroup();
91 $dao->campaign_id
= $campaign->id
;
92 $dao->entity_table
= $groupTableName;
93 $dao->entity_id
= $entityId;
94 $dao->group_type
= 'Include';
101 if (!empty($params['custom']) &&
102 is_array($params['custom'])
104 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_campaign', $campaign->id
);
111 * Delete the campaign.
114 * Id of the campaign.
118 public static function del($id) {
123 CRM_Utils_Hook
::pre('delete', 'Campaign', $id, CRM_Core_DAO
::$_nullArray);
125 $dao = new CRM_Campaign_DAO_Campaign();
127 $result = $dao->delete();
129 CRM_Utils_Hook
::post('delete', 'Campaign', $id, $dao);
135 * Retrieve DB object based on input parameters.
137 * It also stores all the retrieved values in the default array.
139 * @param array $params
140 * (reference ) an assoc array of name/value pairs.
141 * @param array $defaults
142 * (reference ) an assoc array to hold the flattened values.
144 * @return \CRM_Campaign_DAO_Campaign|null
146 public static function retrieve(&$params, &$defaults) {
147 $campaign = new CRM_Campaign_DAO_Campaign();
149 $campaign->copyValues($params);
151 if ($campaign->find(TRUE)) {
152 CRM_Core_DAO
::storeValues($campaign, $defaults);
159 * Return the all eligible campaigns w/ cache.
161 * @param int $includeId
162 * Lets inlcude this campaign by force.
163 * @param int $excludeId
164 * Do not include this campaign.
165 * @param bool $onlyActive
166 * Consider only active campaigns.
168 * @param bool $onlyCurrent
169 * @param bool $appendDatesToTitle
170 * @param bool $forceAll
173 * $campaigns a set of campaigns.
175 public static function getCampaigns(
180 $appendDatesToTitle = FALSE,
185 $cacheKeyParams = array(
190 'appendDatesToTitle',
193 foreach ($cacheKeyParams as $param) {
194 $cacheParam = $
$param;
198 $cacheKey .= '_' . $cacheParam;
201 if (!isset($campaigns[$cacheKey])) {
202 $where = array('( camp.title IS NOT NULL )');
204 $where[] = "( camp.id != $excludeId )";
207 $where[] = '( camp.is_active = 1 )';
210 $where[] = '( camp.end_date IS NULL OR camp.end_date >= NOW() )';
212 $whereClause = implode(' AND ', $where);
214 $whereClause .= " OR ( camp.id = $includeId )";
219 $whereClause = '( 1 )';
227 FROM civicrm_campaign camp
229 Order By camp.title";
231 $campaign = CRM_Core_DAO
::executeQuery($query);
232 $campaigns[$cacheKey] = array();
233 $config = CRM_Core_Config
::singleton();
235 while ($campaign->fetch()) {
236 $title = $campaign->title
;
237 if ($appendDatesToTitle) {
239 foreach (array('start_date', 'end_date') as $date) {
240 if ($campaign->$date) {
241 $dates[] = CRM_Utils_Date
::customFormat($campaign->$date, $config->dateformatFull
);
244 if (!empty($dates)) {
245 $title .= ' (' . implode('-', $dates) . ')';
248 $campaigns[$cacheKey][$campaign->id
] = $title;
252 return $campaigns[$cacheKey];
256 * Wrapper to self::getCampaigns( )
257 * w/ permissions and component check.
259 * @param int $includeId
260 * @param int $excludeId
261 * @param bool $onlyActive
262 * @param bool $onlyCurrent
263 * @param bool $appendDatesToTitle
264 * @param bool $forceAll
265 * @param bool $doCheckForComponent
266 * @param bool $doCheckForPermissions
270 public static function getPermissionedCampaigns(
275 $appendDatesToTitle = FALSE,
277 $doCheckForComponent = TRUE,
278 $doCheckForPermissions = TRUE
281 $cachekeyParams = array(
286 'appendDatesToTitle',
287 'doCheckForComponent',
288 'doCheckForPermissions',
291 foreach ($cachekeyParams as $param) {
292 $cacheKeyParam = $
$param;
293 if (!$cacheKeyParam) {
296 $cacheKey .= '_' . $cacheKeyParam;
299 static $validCampaigns;
300 if (!isset($validCampaigns[$cacheKey])) {
303 'campaigns' => array(),
304 'hasAccessCampaign' => FALSE,
305 'isCampaignEnabled' => FALSE,
308 //do check for component.
309 if ($doCheckForComponent) {
310 $campaigns['isCampaignEnabled'] = $isValid = self
::isCampaignEnable();
313 //do check for permissions.
314 if ($doCheckForPermissions) {
315 $campaigns['hasAccessCampaign'] = $isValid = self
::accessCampaign();
318 //finally retrieve campaigns from db.
320 $campaigns['campaigns'] = self
::getCampaigns($includeId,
330 $validCampaigns[$cacheKey] = $campaigns;
333 return $validCampaigns[$cacheKey];
337 * Is CiviCampaign enabled.
340 public static function isCampaignEnable() {
341 static $isEnable = NULL;
343 if (!isset($isEnable)) {
345 $config = CRM_Core_Config
::singleton();
346 if (in_array('CiviCampaign', $config->enableComponents
)) {
355 * Retrieve campaigns for dashboard.
357 * @param array $params
358 * @param bool $onlyCount
362 public static function getCampaignSummary($params = array(), $onlyCount = FALSE) {
363 $campaigns = array();
365 //build the limit and order clause.
366 $limitClause = $orderByClause = $lookupTableJoins = NULL;
369 'sort' => 'start_date',
372 'sortOrder' => 'desc',
374 foreach ($sortParams as $name => $default) {
375 if (!empty($params[$name])) {
376 $sortParams[$name] = $params[$name];
380 //need to lookup tables.
381 $orderOnCampaignTable = TRUE;
382 if ($sortParams['sort'] == 'status') {
383 $orderOnCampaignTable = FALSE;
384 $lookupTableJoins = "
385 LEFT JOIN civicrm_option_value status ON ( status.value = campaign.status_id OR campaign.status_id IS NULL )
386 INNER JOIN civicrm_option_group grp ON ( status.option_group_id = grp.id AND grp.name = 'campaign_status' )";
387 $orderByClause = "ORDER BY status.label {$sortParams['sortOrder']}";
389 elseif ($sortParams['sort'] == 'campaign_type') {
390 $orderOnCampaignTable = FALSE;
391 $lookupTableJoins = "
392 LEFT JOIN civicrm_option_value campaign_type ON ( campaign_type.value = campaign.campaign_type_id
393 OR campaign.campaign_type_id IS NULL )
394 INNER JOIN civicrm_option_group grp ON ( campaign_type.option_group_id = grp.id AND grp.name = 'campaign_type' )";
395 $orderByClause = "ORDER BY campaign_type.label {$sortParams['sortOrder']}";
397 elseif ($sortParams['sort'] == 'isActive') {
398 $sortParams['sort'] = 'is_active';
400 if ($orderOnCampaignTable) {
401 $orderByClause = "ORDER BY campaign.{$sortParams['sort']} {$sortParams['sortOrder']}";
403 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
406 //build the where clause.
407 $queryParams = $where = array();
408 if (!empty($params['id'])) {
409 $where[] = "( campaign.id = %1 )";
410 $queryParams[1] = array($params['id'], 'Positive');
412 if (!empty($params['name'])) {
413 $where[] = "( campaign.name LIKE %2 )";
414 $queryParams[2] = array('%' . trim($params['name']) . '%', 'String');
416 if (!empty($params['title'])) {
417 $where[] = "( campaign.title LIKE %3 )";
418 $queryParams[3] = array('%' . trim($params['title']) . '%', 'String');
420 if (!empty($params['start_date'])) {
421 $startDate = CRM_Utils_Date
::processDate($params['start_date']);
422 $where[] = "( campaign.start_date >= %4 OR campaign.start_date IS NULL )";
423 $queryParams[4] = array($startDate, 'String');
425 if (!empty($params['end_date'])) {
426 $endDate = CRM_Utils_Date
::processDate($params['end_date'], '235959');
427 $where[] = "( campaign.end_date <= %5 OR campaign.end_date IS NULL )";
428 $queryParams[5] = array($endDate, 'String');
430 if (!empty($params['description'])) {
431 $where[] = "( campaign.description LIKE %6 )";
432 $queryParams[6] = array('%' . trim($params['description']) . '%', 'String');
434 if (!empty($params['campaign_type_id'])) {
435 $typeId = $params['campaign_type_id'];
436 if (is_array($params['campaign_type_id'])) {
437 $typeId = implode(' , ', $params['campaign_type_id']);
439 $where[] = "( campaign.campaign_type_id IN ( {$typeId} ) )";
441 if (!empty($params['status_id'])) {
442 $statusId = $params['status_id'];
443 if (is_array($params['status_id'])) {
444 $statusId = implode(' , ', $params['status_id']);
446 $where[] = "( campaign.status_id IN ( {$statusId} ) )";
448 if (array_key_exists('is_active', $params)) {
449 $active = "( campaign.is_active = 1 )";
450 if (!empty($params['is_active'])) {
451 $active = "( campaign.is_active = 0 OR campaign.is_active IS NULL )";
456 if (!empty($where)) {
457 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
473 SELECT campaign.id as id,
474 campaign.name as name,
475 campaign.title as title,
476 campaign.is_active as is_active,
477 campaign.status_id as status_id,
478 campaign.end_date as end_date,
479 campaign.start_date as start_date,
480 campaign.description as description,
481 campaign.campaign_type_id as campaign_type_id';
483 $selectClause = 'SELECT COUNT(*)';
485 $fromClause = 'FROM civicrm_campaign campaign';
487 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
489 //in case of only count.
491 return (int) CRM_Core_DAO
::singleValueQuery($query, $queryParams);
494 $campaign = CRM_Core_DAO
::executeQuery($query, $queryParams);
495 while ($campaign->fetch()) {
496 foreach ($properties as $property) {
497 $campaigns[$campaign->id
][$property] = $campaign->$property;
505 * Get the campaign count.
508 public static function getCampaignCount() {
509 return (int) CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM civicrm_campaign');
513 * Get Campaigns groups.
515 * @param int $campaignId
520 public static function getCampaignGroups($campaignId) {
521 static $campaignGroups;
526 if (!isset($campaignGroups[$campaignId])) {
527 $campaignGroups[$campaignId] = array();
530 SELECT grp.title, grp.id
531 FROM civicrm_campaign_group campgrp
532 INNER JOIN civicrm_group grp ON ( grp.id = campgrp.entity_id )
533 WHERE campgrp.group_type = 'Include'
534 AND campgrp.entity_table = 'civicrm_group'
535 AND campgrp.campaign_id = %1";
537 $groups = CRM_Core_DAO
::executeQuery($query, array(1 => array($campaignId, 'Positive')));
538 while ($groups->fetch()) {
539 $campaignGroups[$campaignId][$groups->id
] = $groups->title
;
543 return $campaignGroups[$campaignId];
547 * Update the is_active flag in the db.
550 * Id of the database record.
551 * @param bool $is_active
552 * Value we want to set the is_active field.
554 * @return CRM_Campaign_DAO_Campaign|null
555 * DAO object on success, null otherwise
557 public static function setIsActive($id, $is_active) {
558 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Campaign', $id, 'is_active', $is_active);
564 public static function accessCampaign() {
565 static $allow = NULL;
567 if (!isset($allow)) {
569 if (CRM_Core_Permission
::check('manage campaign') ||
570 CRM_Core_Permission
::check('administer CiviCampaign')
580 * Add select element for campaign
581 * and assign needful info to templates.
583 * @param CRM_Core_Form $form
584 * @param int $connectedCampaignId
586 public static function addCampaign(&$form, $connectedCampaignId = NULL) {
587 //some forms do set default and freeze.
589 if ($form->get('action') & CRM_Core_Action
::VIEW
) {
590 $appendDates = FALSE;
593 $campaignDetails = self
::getPermissionedCampaigns($connectedCampaignId, NULL, TRUE, TRUE, $appendDates);
594 $fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
595 foreach ($fields as $fld) {
596 $
$fld = CRM_Utils_Array
::value($fld, $campaignDetails);
599 //lets see do we have past campaigns.
600 $hasPastCampaigns = FALSE;
601 $allActiveCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, TRUE, FALSE);
602 if (count($allActiveCampaigns) > count($campaigns)) {
603 $hasPastCampaigns = TRUE;
605 $hasCampaigns = FALSE;
606 if (!empty($campaigns)) {
607 $hasCampaigns = TRUE;
609 if ($hasPastCampaigns) {
610 $hasCampaigns = TRUE;
611 $form->add('hidden', 'included_past_campaigns');
614 $showAddCampaign = FALSE;
615 $alreadyIncludedPastCampaigns = FALSE;
616 if ($connectedCampaignId ||
($isCampaignEnabled && $hasAccessCampaign)) {
617 $showAddCampaign = TRUE;
618 //lets add past campaigns as options to quick-form element.
619 if ($hasPastCampaigns && $form->getElementValue('included_past_campaigns')) {
620 $campaigns = $allActiveCampaigns;
621 $alreadyIncludedPastCampaigns = TRUE;
623 $campaign = &$form->add('select',
626 array('' => ts('- select -')) +
$campaigns,
628 array('class' => 'crm-select2')
630 //lets freeze when user does not has access or campaign is disabled.
631 if (!$isCampaignEnabled ||
!$hasAccessCampaign) {
636 $addCampaignURL = NULL;
637 if (empty($campaigns) && $hasAccessCampaign && $isCampaignEnabled) {
638 $addCampaignURL = CRM_Utils_System
::url('civicrm/campaign/add', 'reset=1');
641 $includePastCampaignURL = NULL;
642 if ($hasPastCampaigns && $isCampaignEnabled && $hasAccessCampaign) {
643 $includePastCampaignURL = CRM_Utils_System
::url('civicrm/ajax/rest',
644 'className=CRM_Campaign_Page_AJAX&fnName=allActiveCampaigns',
649 //carry this info to templates.
657 'includePastCampaignURL',
658 'alreadyIncludedPastCampaigns',
660 foreach ($infoFields as $fld) {
661 $campaignInfo[$fld] = $
$fld;
663 $form->assign('campaignInfo', $campaignInfo);
667 * Add campaign in component search.
668 * and assign needful info to templates.
670 * @param CRM_Core_Form $form
671 * @param string $elementName
673 public static function addCampaignInComponentSearch(&$form, $elementName = 'campaign_id') {
674 $campaignInfo = array();
675 $campaignDetails = self
::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
676 $fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
677 foreach ($fields as $fld) {
678 $
$fld = CRM_Utils_Array
::value($fld, $campaignDetails);
680 $showCampaignInSearch = FALSE;
681 if ($isCampaignEnabled && $hasAccessCampaign && !empty($campaigns)) {
682 //get the current campaign only.
683 $currentCampaigns = self
::getCampaigns(NULL, NULL, FALSE);
684 $pastCampaigns = array_diff($campaigns, $currentCampaigns);
685 $allCampaigns = array();
686 if (!empty($currentCampaigns)) {
687 $allCampaigns = array('crm_optgroup_current_campaign' => ts('Current Campaigns')) +
$currentCampaigns;
689 if (!empty($pastCampaigns)) {
690 $allCampaigns +
= array('crm_optgroup_past_campaign' => ts('Past Campaigns')) +
$pastCampaigns;
693 $showCampaignInSearch = TRUE;
694 $form->add('select', $elementName, ts('Campaigns'), $allCampaigns, FALSE,
695 array('id' => 'campaigns', 'multiple' => 'multiple', 'class' => 'crm-select2')
702 'showCampaignInSearch',
704 foreach ($infoFields as $fld) {
705 $campaignInfo[$fld] = $
$fld;
707 $form->assign('campaignInfo', $campaignInfo);