3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
35 class CRM_Campaign_BAO_Campaign
extends CRM_Campaign_DAO_Campaign
{
38 * Takes an associative array and creates a campaign object.
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
44 * @param array $params
45 * (reference ) an assoc array of name/value pairs.
47 * @return CRM_Campaign_DAO_Campaign
49 public static function create(&$params) {
54 if (!(CRM_Utils_Array
::value('id', $params))) {
56 if (!(CRM_Utils_Array
::value('created_id', $params))) {
57 $session = CRM_Core_Session
::singleton();
58 $params['created_id'] = $session->get('userID');
61 if (!(CRM_Utils_Array
::value('created_date', $params))) {
62 $params['created_date'] = date('YmdHis');
65 if (!(CRM_Utils_Array
::value('name', $params))) {
66 $params['name'] = CRM_Utils_String
::titleToVar($params['title'], 64);
69 CRM_Utils_Hook
::pre('create', 'Campaign', NULL, $params);
72 CRM_Utils_Hook
::pre('edit', 'Campaign', $params['id'], $params);
75 $campaign = new CRM_Campaign_DAO_Campaign();
76 $campaign->copyValues($params);
79 if (!empty($params['id'])) {
80 CRM_Utils_Hook
::post('edit', 'Campaign', $campaign->id
, $campaign);
83 CRM_Utils_Hook
::post('create', 'Campaign', $campaign->id
, $campaign);
86 /* Create the campaign group record */
88 $groupTableName = CRM_Contact_BAO_Group
::getTableName();
90 if (isset($params['groups']) && !empty($params['groups']['include']) && is_array($params['groups']['include'])) {
91 foreach ($params['groups']['include'] as $entityId) {
92 $dao = new CRM_Campaign_DAO_CampaignGroup();
93 $dao->campaign_id
= $campaign->id
;
94 $dao->entity_table
= $groupTableName;
95 $dao->entity_id
= $entityId;
96 $dao->group_type
= 'Include';
103 if (!empty($params['custom']) &&
104 is_array($params['custom'])
106 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_campaign', $campaign->id
);
113 * Delete the campaign.
116 * Id of the campaign.
120 public static function del($id) {
125 CRM_Utils_Hook
::pre('delete', 'Campaign', $id, CRM_Core_DAO
::$_nullArray);
127 $dao = new CRM_Campaign_DAO_Campaign();
129 $result = $dao->delete();
131 CRM_Utils_Hook
::post('delete', 'Campaign', $id, $dao);
137 * Retrieve DB object based on input parameters.
139 * It also stores all the retrieved values in the default array.
141 * @param array $params
142 * (reference ) an assoc array of name/value pairs.
143 * @param array $defaults
144 * (reference ) an assoc array to hold the flattened values.
146 * @return \CRM_Campaign_DAO_Campaign|null
148 public static function retrieve(&$params, &$defaults) {
149 $campaign = new CRM_Campaign_DAO_Campaign();
151 $campaign->copyValues($params);
153 if ($campaign->find(TRUE)) {
154 CRM_Core_DAO
::storeValues($campaign, $defaults);
161 * Return the all eligible campaigns w/ cache.
163 * @param int $includeId
164 * Lets inlcude this campaign by force.
165 * @param int $excludeId
166 * Do not include this campaign.
167 * @param bool $onlyActive
168 * Consider only active campaigns.
170 * @param bool $onlyCurrent
171 * @param bool $appendDatesToTitle
172 * @param bool $forceAll
175 * $campaigns a set of campaigns.
177 public static function getCampaigns(
182 $appendDatesToTitle = FALSE,
187 $cacheKeyParams = array(
192 'appendDatesToTitle',
195 foreach ($cacheKeyParams as $param) {
196 $cacheParam = $
$param;
200 $cacheKey .= '_' . $cacheParam;
203 if (!isset($campaigns[$cacheKey])) {
204 $where = array('( camp.title IS NOT NULL )');
206 $where[] = "( camp.id != $excludeId )";
209 $where[] = '( camp.is_active = 1 )';
212 $where[] = '( camp.end_date IS NULL OR camp.end_date >= NOW() )';
214 $whereClause = implode(' AND ', $where);
216 $whereClause .= " OR ( camp.id = $includeId )";
221 $whereClause = '( 1 )';
229 FROM civicrm_campaign camp
231 Order By camp.title";
233 $campaign = CRM_Core_DAO
::executeQuery($query);
234 $campaigns[$cacheKey] = array();
235 $config = CRM_Core_Config
::singleton();
237 while ($campaign->fetch()) {
238 $title = $campaign->title
;
239 if ($appendDatesToTitle) {
241 foreach (array('start_date', 'end_date') as $date) {
242 if ($campaign->$date) {
243 $dates[] = CRM_Utils_Date
::customFormat($campaign->$date, $config->dateformatFull
);
246 if (!empty($dates)) {
247 $title .= ' (' . implode('-', $dates) . ')';
250 $campaigns[$cacheKey][$campaign->id
] = $title;
254 return $campaigns[$cacheKey];
258 * Wrapper to self::getCampaigns( )
259 * w/ permissions and component check.
261 * @param int $includeId
262 * @param int $excludeId
263 * @param bool $onlyActive
264 * @param bool $onlyCurrent
265 * @param bool $appendDatesToTitle
266 * @param bool $forceAll
267 * @param bool $doCheckForComponent
268 * @param bool $doCheckForPermissions
272 public static function getPermissionedCampaigns(
277 $appendDatesToTitle = FALSE,
279 $doCheckForComponent = TRUE,
280 $doCheckForPermissions = TRUE
283 $cachekeyParams = array(
288 'appendDatesToTitle',
289 'doCheckForComponent',
290 'doCheckForPermissions',
293 foreach ($cachekeyParams as $param) {
294 $cacheKeyParam = $
$param;
295 if (!$cacheKeyParam) {
298 $cacheKey .= '_' . $cacheKeyParam;
301 static $validCampaigns;
302 if (!isset($validCampaigns[$cacheKey])) {
305 'campaigns' => array(),
306 'hasAccessCampaign' => FALSE,
307 'isCampaignEnabled' => FALSE,
310 //do check for component.
311 if ($doCheckForComponent) {
312 $campaigns['isCampaignEnabled'] = $isValid = self
::isCampaignEnable();
315 //do check for permissions.
316 if ($doCheckForPermissions) {
317 $campaigns['hasAccessCampaign'] = $isValid = self
::accessCampaign();
320 //finally retrieve campaigns from db.
322 $campaigns['campaigns'] = self
::getCampaigns($includeId,
332 $validCampaigns[$cacheKey] = $campaigns;
335 return $validCampaigns[$cacheKey];
339 * Is CiviCampaign enabled.
342 public static function isCampaignEnable() {
343 static $isEnable = NULL;
345 if (!isset($isEnable)) {
347 $config = CRM_Core_Config
::singleton();
348 if (in_array('CiviCampaign', $config->enableComponents
)) {
357 * Retrieve campaigns for dashboard.
359 * @param array $params
360 * @param bool $onlyCount
364 public static function getCampaignSummary($params = array(), $onlyCount = FALSE) {
365 $campaigns = array();
367 //build the limit and order clause.
368 $limitClause = $orderByClause = $lookupTableJoins = NULL;
371 'sort' => 'start_date',
374 'sortOrder' => 'desc',
376 foreach ($sortParams as $name => $default) {
377 if (!empty($params[$name])) {
378 $sortParams[$name] = $params[$name];
382 //need to lookup tables.
383 $orderOnCampaignTable = TRUE;
384 if ($sortParams['sort'] == 'status') {
385 $orderOnCampaignTable = FALSE;
386 $lookupTableJoins = "
387 LEFT JOIN civicrm_option_value status ON ( status.value = campaign.status_id OR campaign.status_id IS NULL )
388 INNER JOIN civicrm_option_group grp ON ( status.option_group_id = grp.id AND grp.name = 'campaign_status' )";
389 $orderByClause = "ORDER BY status.label {$sortParams['sortOrder']}";
391 elseif ($sortParams['sort'] == 'campaign_type') {
392 $orderOnCampaignTable = FALSE;
393 $lookupTableJoins = "
394 LEFT JOIN civicrm_option_value campaign_type ON ( campaign_type.value = campaign.campaign_type_id
395 OR campaign.campaign_type_id IS NULL )
396 INNER JOIN civicrm_option_group grp ON ( campaign_type.option_group_id = grp.id AND grp.name = 'campaign_type' )";
397 $orderByClause = "ORDER BY campaign_type.label {$sortParams['sortOrder']}";
399 elseif ($sortParams['sort'] == 'isActive') {
400 $sortParams['sort'] = 'is_active';
402 if ($orderOnCampaignTable) {
403 $orderByClause = "ORDER BY campaign.{$sortParams['sort']} {$sortParams['sortOrder']}";
405 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
408 //build the where clause.
409 $queryParams = $where = array();
410 if (!empty($params['id'])) {
411 $where[] = "( campaign.id = %1 )";
412 $queryParams[1] = array($params['id'], 'Positive');
414 if (!empty($params['name'])) {
415 $where[] = "( campaign.name LIKE %2 )";
416 $queryParams[2] = array('%' . trim($params['name']) . '%', 'String');
418 if (!empty($params['title'])) {
419 $where[] = "( campaign.title LIKE %3 )";
420 $queryParams[3] = array('%' . trim($params['title']) . '%', 'String');
422 if (!empty($params['start_date'])) {
423 $startDate = CRM_Utils_Date
::processDate($params['start_date']);
424 $where[] = "( campaign.start_date >= %4 OR campaign.start_date IS NULL )";
425 $queryParams[4] = array($startDate, 'String');
427 if (!empty($params['end_date'])) {
428 $endDate = CRM_Utils_Date
::processDate($params['end_date'], '235959');
429 $where[] = "( campaign.end_date <= %5 OR campaign.end_date IS NULL )";
430 $queryParams[5] = array($endDate, 'String');
432 if (!empty($params['description'])) {
433 $where[] = "( campaign.description LIKE %6 )";
434 $queryParams[6] = array('%' . trim($params['description']) . '%', 'String');
436 if (!empty($params['campaign_type_id'])) {
437 $typeId = $params['campaign_type_id'];
438 if (is_array($params['campaign_type_id'])) {
439 $typeId = implode(' , ', $params['campaign_type_id']);
441 $where[] = "( campaign.campaign_type_id IN ( {$typeId} ) )";
443 if (!empty($params['status_id'])) {
444 $statusId = $params['status_id'];
445 if (is_array($params['status_id'])) {
446 $statusId = implode(' , ', $params['status_id']);
448 $where[] = "( campaign.status_id IN ( {$statusId} ) )";
450 if (array_key_exists('is_active', $params)) {
451 $active = "( campaign.is_active = 1 )";
452 if (!empty($params['is_active'])) {
453 $active = "( campaign.is_active = 0 OR campaign.is_active IS NULL )";
458 if (!empty($where)) {
459 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
475 SELECT campaign.id as id,
476 campaign.name as name,
477 campaign.title as title,
478 campaign.is_active as is_active,
479 campaign.status_id as status_id,
480 campaign.end_date as end_date,
481 campaign.start_date as start_date,
482 campaign.description as description,
483 campaign.campaign_type_id as campaign_type_id';
485 $selectClause = 'SELECT COUNT(*)';
487 $fromClause = 'FROM civicrm_campaign campaign';
489 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
491 //in case of only count.
493 return (int) CRM_Core_DAO
::singleValueQuery($query, $queryParams);
496 $campaign = CRM_Core_DAO
::executeQuery($query, $queryParams);
497 while ($campaign->fetch()) {
498 foreach ($properties as $property) {
499 $campaigns[$campaign->id
][$property] = $campaign->$property;
507 * Get the campaign count.
510 public static function getCampaignCount() {
511 return (int) CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM civicrm_campaign');
515 * Get Campaigns groups.
517 * @param int $campaignId
522 public static function getCampaignGroups($campaignId) {
523 static $campaignGroups;
528 if (!isset($campaignGroups[$campaignId])) {
529 $campaignGroups[$campaignId] = array();
532 SELECT grp.title, grp.id
533 FROM civicrm_campaign_group campgrp
534 INNER JOIN civicrm_group grp ON ( grp.id = campgrp.entity_id )
535 WHERE campgrp.group_type = 'Include'
536 AND campgrp.entity_table = 'civicrm_group'
537 AND campgrp.campaign_id = %1";
539 $groups = CRM_Core_DAO
::executeQuery($query, array(1 => array($campaignId, 'Positive')));
540 while ($groups->fetch()) {
541 $campaignGroups[$campaignId][$groups->id
] = $groups->title
;
545 return $campaignGroups[$campaignId];
549 * Update the is_active flag in the db.
552 * Id of the database record.
553 * @param bool $is_active
554 * Value we want to set the is_active field.
556 * @return CRM_Campaign_DAO_Campaign|null
557 * DAO object on success, null otherwise
559 public static function setIsActive($id, $is_active) {
560 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Campaign', $id, 'is_active', $is_active);
566 public static function accessCampaign() {
567 static $allow = NULL;
569 if (!isset($allow)) {
571 if (CRM_Core_Permission
::check('manage campaign') ||
572 CRM_Core_Permission
::check('administer CiviCampaign')
582 * Add select element for campaign
583 * and assign needful info to templates.
585 * @param CRM_Core_Form $form
586 * @param int $connectedCampaignId
588 public static function addCampaign(&$form, $connectedCampaignId = NULL) {
589 //some forms do set default and freeze.
591 if ($form->get('action') & CRM_Core_Action
::VIEW
) {
592 $appendDates = FALSE;
595 $campaignDetails = self
::getPermissionedCampaigns($connectedCampaignId, NULL, TRUE, TRUE, $appendDates);
596 $fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
597 foreach ($fields as $fld) {
598 $
$fld = CRM_Utils_Array
::value($fld, $campaignDetails);
601 //lets see do we have past campaigns.
602 $hasPastCampaigns = FALSE;
603 $allActiveCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, TRUE, FALSE);
604 if (count($allActiveCampaigns) > count($campaigns)) {
605 $hasPastCampaigns = TRUE;
607 $hasCampaigns = FALSE;
608 if (!empty($campaigns)) {
609 $hasCampaigns = TRUE;
611 if ($hasPastCampaigns) {
612 $hasCampaigns = TRUE;
613 $form->add('hidden', 'included_past_campaigns');
616 $showAddCampaign = FALSE;
617 $alreadyIncludedPastCampaigns = FALSE;
618 if ($connectedCampaignId ||
($isCampaignEnabled && $hasAccessCampaign)) {
619 $showAddCampaign = TRUE;
620 //lets add past campaigns as options to quick-form element.
621 if ($hasPastCampaigns && $form->getElementValue('included_past_campaigns')) {
622 $campaigns = $allActiveCampaigns;
623 $alreadyIncludedPastCampaigns = TRUE;
625 $campaign = &$form->add('select',
628 array('' => ts('- select -')) +
$campaigns,
630 array('class' => 'crm-select2')
632 //lets freeze when user does not has access or campaign is disabled.
633 if (!$isCampaignEnabled ||
!$hasAccessCampaign) {
638 $addCampaignURL = NULL;
639 if (empty($campaigns) && $hasAccessCampaign && $isCampaignEnabled) {
640 $addCampaignURL = CRM_Utils_System
::url('civicrm/campaign/add', 'reset=1');
643 $includePastCampaignURL = NULL;
644 if ($hasPastCampaigns && $isCampaignEnabled && $hasAccessCampaign) {
645 $includePastCampaignURL = CRM_Utils_System
::url('civicrm/ajax/rest',
646 'className=CRM_Campaign_Page_AJAX&fnName=allActiveCampaigns',
651 //carry this info to templates.
659 'includePastCampaignURL',
660 'alreadyIncludedPastCampaigns',
662 foreach ($infoFields as $fld) {
663 $campaignInfo[$fld] = $
$fld;
665 $form->assign('campaignInfo', $campaignInfo);
669 * Add campaign in component search.
670 * and assign needful info to templates.
672 * @param CRM_Core_Form $form
673 * @param string $elementName
675 public static function addCampaignInComponentSearch(&$form, $elementName = 'campaign_id') {
676 $campaignInfo = array();
677 $campaignDetails = self
::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
678 $fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
679 foreach ($fields as $fld) {
680 $
$fld = CRM_Utils_Array
::value($fld, $campaignDetails);
682 $showCampaignInSearch = FALSE;
683 if ($isCampaignEnabled && $hasAccessCampaign && !empty($campaigns)) {
684 //get the current campaign only.
685 $currentCampaigns = self
::getCampaigns(NULL, NULL, FALSE);
686 $pastCampaigns = array_diff($campaigns, $currentCampaigns);
687 $allCampaigns = array();
688 if (!empty($currentCampaigns)) {
689 $allCampaigns = array('crm_optgroup_current_campaign' => ts('Current Campaigns')) +
$currentCampaigns;
691 if (!empty($pastCampaigns)) {
692 $allCampaigns +
= array('crm_optgroup_past_campaign' => ts('Past Campaigns')) +
$pastCampaigns;
695 $showCampaignInSearch = TRUE;
696 $form->add('select', $elementName, ts('Campaigns'), $allCampaigns, FALSE,
697 array('id' => 'campaigns', 'multiple' => 'multiple', 'class' => 'crm-select2')
704 'showCampaignInSearch',
706 foreach ($infoFields as $fld) {
707 $campaignInfo[$fld] = $
$fld;
709 $form->assign('campaignInfo', $campaignInfo);