3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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 (reference ) an assoc array of name/value pairs
46 * @return object CRM_Campaign_DAO_Campaign object
50 static function create(&$params) {
55 if (!(CRM_Utils_Array
::value('id', $params))) {
57 if (!(CRM_Utils_Array
::value('created_id', $params))) {
58 $session = CRM_Core_Session
::singleton();
59 $params['created_id'] = $session->get('userID');
62 if (!(CRM_Utils_Array
::value('created_date', $params))) {
63 $params['created_date'] = date('YmdHis');
66 if (!(CRM_Utils_Array
::value('name', $params))) {
67 $params['name'] = CRM_Utils_String
::titleToVar($params['title'], 64);
71 $campaign = new CRM_Campaign_DAO_Campaign();
72 $campaign->copyValues($params);
75 /* Create the campaign group record */
77 $groupTableName = CRM_Contact_BAO_Group
::getTableName();
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';
92 if (!empty($params['custom']) &&
93 is_array($params['custom'])
95 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_campaign', $campaign->id
);
102 * function to delete the campaign
104 * @param int $id id of the campaign
108 public static function del($id) {
112 $dao = new CRM_Campaign_DAO_Campaign();
114 return $dao->delete();
118 * Takes a bunch of params that are needed to match certain criteria and
119 * retrieves the relevant objects. Typically the valid params are only
122 * @param array $params (reference ) an assoc array of name/value pairs
123 * @param array $defaults (reference ) an assoc array to hold the flattened values
125 * @return \CRM_Campaign_DAO_Campaign|null
128 public function retrieve(&$params, &$defaults) {
129 $campaign = new CRM_Campaign_DAO_Campaign();
131 $campaign->copyValues($params);
133 if ($campaign->find(TRUE)) {
134 CRM_Core_DAO
::storeValues($campaign, $defaults);
141 * Return the all eligible campaigns w/ cache.
143 * @param int $includeId lets inlcude this campaign by force.
144 * @param int $excludeId do not include this campaign.
145 * @param boolean $onlyActive consider only active campaigns.
147 * @return $campaigns a set of campaigns.
150 public static function getCampaigns(
155 $appendDatesToTitle = FALSE,
160 $cacheKeyParams = array(
161 'includeId', 'excludeId', 'onlyActive',
162 'onlyCurrent', 'appendDatesToTitle', 'forceAll',
164 foreach ($cacheKeyParams as $param) {
165 $cacheParam = $
$param;
169 $cacheKey .= '_' . $cacheParam;
172 if (!isset($campaigns[$cacheKey])) {
173 $where = array('( camp.title IS NOT NULL )');
175 $where[] = "( camp.id != $excludeId )";
178 $where[] = '( camp.is_active = 1 )';
181 $where[] = '( camp.end_date IS NULL OR camp.end_date >= NOW() )';
183 $whereClause = implode(' AND ', $where);
185 $whereClause .= " OR ( camp.id = $includeId )";
190 $whereClause = '( 1 )';
198 FROM civicrm_campaign camp
200 Order By camp.title";
202 $campaign = CRM_Core_DAO
::executeQuery($query);
203 $campaigns[$cacheKey] = array();
204 $config = CRM_Core_Config
::singleton();
206 while ($campaign->fetch()) {
207 $title = $campaign->title
;
208 if ($appendDatesToTitle) {
210 foreach (array('start_date', 'end_date') as $date) {
211 if ($campaign->$date) {
212 $dates[] = CRM_Utils_Date
::customFormat($campaign->$date, $config->dateformatFull
);
215 if (!empty($dates)) {
216 $title .= ' (' . implode('-', $dates) . ')';
219 $campaigns[$cacheKey][$campaign->id
] = $title;
223 return $campaigns[$cacheKey];
227 * Wrapper to self::getCampaigns( )
228 * w/ permissions and component check.
231 public static function getPermissionedCampaigns($includeId = NULL,
235 $appendDatesToTitle = FALSE,
237 $doCheckForComponent = TRUE,
238 $doCheckForPermissions = TRUE
241 $cachekeyParams = array(
242 'includeId', 'excludeId', 'onlyActive', 'onlyCurrent',
243 'appendDatesToTitle', 'doCheckForComponent', 'doCheckForPermissions', 'forceAll',
245 foreach ($cachekeyParams as $param) {
246 $cacheKeyParam = $
$param;
247 if (!$cacheKeyParam) {
250 $cacheKey .= '_' . $cacheKeyParam;
253 static $validCampaigns;
254 if (!isset($validCampaigns[$cacheKey])) {
256 $campaigns = array('campaigns' => array(),
257 'hasAccessCampaign' => FALSE,
258 'isCampaignEnabled' => FALSE,
261 //do check for component.
262 if ($doCheckForComponent) {
263 $campaigns['isCampaignEnabled'] = $isValid = self
::isCampaignEnable();
266 //do check for permissions.
267 if ($doCheckForPermissions) {
268 $campaigns['hasAccessCampaign'] = $isValid = self
::accessCampaign();
271 //finally retrieve campaigns from db.
273 $campaigns['campaigns'] = self
::getCampaigns($includeId,
283 $validCampaigns[$cacheKey] = $campaigns;
286 return $validCampaigns[$cacheKey];
290 * Is CiviCampaign enabled.
293 public static function isCampaignEnable() {
294 static $isEnable = NULL;
296 if (!isset($isEnable)) {
298 $config = CRM_Core_Config
::singleton();
299 if (in_array('CiviCampaign', $config->enableComponents
)) {
308 * Function to retrieve campaigns for dashboard.
312 static function getCampaignSummary($params = array(
313 ), $onlyCount = FALSE) {
314 $campaigns = array();
316 //build the limit and order clause.
317 $limitClause = $orderByClause = $lookupTableJoins = NULL;
320 'sort' => 'start_date',
323 'sortOrder' => 'desc',
325 foreach ($sortParams as $name => $default) {
326 if (!empty($params[$name])) {
327 $sortParams[$name] = $params[$name];
332 //need to lookup tables.
333 $orderOnCampaignTable = TRUE;
334 if ($sortParams['sort'] == 'status') {
335 $orderOnCampaignTable = FALSE;
336 $lookupTableJoins = "
337 LEFT JOIN civicrm_option_value status ON ( status.value = campaign.status_id OR campaign.status_id IS NULL )
338 INNER JOIN civicrm_option_group grp ON ( status.option_group_id = grp.id AND grp.name = 'campaign_status' )";
339 $orderByClause = "ORDER BY status.label {$sortParams['sortOrder']}";
341 elseif ($sortParams['sort'] == 'campaign_type') {
342 $orderOnCampaignTable = FALSE;
343 $lookupTableJoins = "
344 LEFT JOIN civicrm_option_value campaign_type ON ( campaign_type.value = campaign.campaign_type_id
345 OR campaign.campaign_type_id IS NULL )
346 INNER JOIN civicrm_option_group grp ON ( campaign_type.option_group_id = grp.id AND grp.name = 'campaign_type' )";
347 $orderByClause = "ORDER BY campaign_type.label {$sortParams['sortOrder']}";
349 elseif ($sortParams['sort'] == 'isActive') {
350 $sortParams['sort'] = 'is_active';
352 if ($orderOnCampaignTable) {
353 $orderByClause = "ORDER BY campaign.{$sortParams['sort']} {$sortParams['sortOrder']}";
355 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
358 //build the where clause.
359 $queryParams = $where = array();
360 if (!empty($params['id'])) {
361 $where[] = "( campaign.id = %1 )";
362 $queryParams[1] = array($params['id'], 'Positive');
364 if (!empty($params['name'])) {
365 $where[] = "( campaign.name LIKE %2 )";
366 $queryParams[2] = array('%' . trim($params['name']) . '%', 'String');
368 if (!empty($params['title'])) {
369 $where[] = "( campaign.title LIKE %3 )";
370 $queryParams[3] = array('%' . trim($params['title']) . '%', 'String');
372 if (!empty($params['start_date'])) {
373 $startDate = CRM_Utils_Date
::processDate($params['start_date']);
374 $where[] = "( campaign.start_date >= %4 OR campaign.start_date IS NULL )";
375 $queryParams[4] = array($startDate, 'String');
377 if (!empty($params['end_date'])) {
378 $endDate = CRM_Utils_Date
::processDate($params['end_date'], '235959');
379 $where[] = "( campaign.end_date <= %5 OR campaign.end_date IS NULL )";
380 $queryParams[5] = array($endDate, 'String');
382 if (!empty($params['description'])) {
383 $where[] = "( campaign.description LIKE %6 )";
384 $queryParams[6] = array('%' . trim($params['description']) . '%', 'String');
386 if (!empty($params['campaign_type_id'])) {
387 $typeId = $params['campaign_type_id'];
388 if (is_array($params['campaign_type_id'])) {
389 $typeId = implode(' , ', $params['campaign_type_id']);
391 $where[] = "( campaign.campaign_type_id IN ( {$typeId} ) )";
393 if (!empty($params['status_id'])) {
394 $statusId = $params['status_id'];
395 if (is_array($params['status_id'])) {
396 $statusId = implode(' , ', $params['status_id']);
398 $where[] = "( campaign.status_id IN ( {$statusId} ) )";
400 if (array_key_exists('is_active', $params)) {
401 $active = "( campaign.is_active = 1 )";
402 if (!empty($params['is_active'])) {
403 $active = "( campaign.is_active = 0 OR campaign.is_active IS NULL )";
408 if (!empty($where)) {
409 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
425 SELECT campaign.id as id,
426 campaign.name as name,
427 campaign.title as title,
428 campaign.is_active as is_active,
429 campaign.status_id as status_id,
430 campaign.end_date as end_date,
431 campaign.start_date as start_date,
432 campaign.description as description,
433 campaign.campaign_type_id as campaign_type_id';
435 $selectClause = 'SELECT COUNT(*)';
437 $fromClause = 'FROM civicrm_campaign campaign';
439 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
441 //in case of only count.
443 return (int)CRM_Core_DAO
::singleValueQuery($query, $queryParams);
446 $campaign = CRM_Core_DAO
::executeQuery($query, $queryParams);
447 while ($campaign->fetch()) {
448 foreach ($properties as $property) {
449 $campaigns[$campaign->id
][$property] = $campaign->$property;
457 * Get the campaign count.
461 static function getCampaignCount() {
462 return (int)CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM civicrm_campaign');
466 * Function to get Campaigns groups
468 * @param int $campaignId campaign id
473 static function getCampaignGroups($campaignId) {
474 static $campaignGroups;
479 if (!isset($campaignGroups[$campaignId])) {
480 $campaignGroups[$campaignId] = array();
483 SELECT grp.title, grp.id
484 FROM civicrm_campaign_group campgrp
485 INNER JOIN civicrm_group grp ON ( grp.id = campgrp.entity_id )
486 WHERE campgrp.group_type = 'Include'
487 AND campgrp.entity_table = 'civicrm_group'
488 AND campgrp.campaign_id = %1";
490 $groups = CRM_Core_DAO
::executeQuery($query, array(1 => array($campaignId, 'Positive')));
491 while ($groups->fetch()) {
492 $campaignGroups[$campaignId][$groups->id
] = $groups->title
;
496 return $campaignGroups[$campaignId];
500 * update the is_active flag in the db
502 * @param int $id id of the database record
503 * @param boolean $is_active value we want to set the is_active field
505 * @return Object DAO object on sucess, null otherwise
508 static function setIsActive($id, $is_active) {
509 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Campaign', $id, 'is_active', $is_active);
512 static function accessCampaign() {
513 static $allow = NULL;
515 if (!isset($allow)) {
517 if (CRM_Core_Permission
::check('manage campaign') ||
518 CRM_Core_Permission
::check('administer CiviCampaign')
528 * Add select element for campaign
529 * and assign needful info to templates.
532 public static function addCampaign(&$form, $connectedCampaignId = NULL) {
533 //some forms do set default and freeze.
535 if ($form->get('action') & CRM_Core_Action
::VIEW
) {
536 $appendDates = FALSE;
539 $campaignDetails = self
::getPermissionedCampaigns($connectedCampaignId, NULL, TRUE, TRUE, $appendDates);
540 $fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
541 foreach ($fields as $fld)$
$fld = CRM_Utils_Array
::value($fld, $campaignDetails);
543 //lets see do we have past campaigns.
544 $hasPastCampaigns = FALSE;
545 $allActiveCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, TRUE, FALSE);
546 if (count($allActiveCampaigns) > count($campaigns)) {
547 $hasPastCampaigns = TRUE;
549 $hasCampaigns = FALSE;
550 if (!empty($campaigns)) {
551 $hasCampaigns = TRUE;
553 if ($hasPastCampaigns) {
554 $hasCampaigns = TRUE;
555 $form->add('hidden', 'included_past_campaigns');
558 $showAddCampaign = FALSE;
559 $alreadyIncludedPastCampaigns = FALSE;
560 if ($connectedCampaignId ||
($isCampaignEnabled && $hasAccessCampaign)) {
561 $showAddCampaign = TRUE;
562 //lets add past campaigns as options to quick-form element.
563 if ($hasPastCampaigns && $form->getElementValue('included_past_campaigns')) {
564 $campaigns = $allActiveCampaigns;
565 $alreadyIncludedPastCampaigns = TRUE;
567 $campaign = &$form->add('select',
570 array('' => ts('- select -')) +
$campaigns,
572 array('class' => 'crm-select2')
574 //lets freeze when user does not has access or campaign is disabled.
575 if (!$isCampaignEnabled ||
!$hasAccessCampaign) {
580 $addCampaignURL = NULL;
581 if (empty($campaigns) && $hasAccessCampaign && $isCampaignEnabled) {
582 $addCampaignURL = CRM_Utils_System
::url('civicrm/campaign/add', 'reset=1');
585 $includePastCampaignURL = NULL;
586 if ($hasPastCampaigns && $isCampaignEnabled && $hasAccessCampaign) {
587 $includePastCampaignURL = CRM_Utils_System
::url('civicrm/ajax/rest',
588 'className=CRM_Campaign_Page_AJAX&fnName=allActiveCampaigns',
593 //carry this info to templates.
601 'includePastCampaignURL',
602 'alreadyIncludedPastCampaigns',
604 foreach ($infoFields as $fld) $campaignInfo[$fld] = $
$fld;
605 $form->assign('campaignInfo', $campaignInfo);
609 * Add campaign in compoent search.
610 * and assign needful info to templates.
613 public static function addCampaignInComponentSearch(&$form, $elementName = 'campaign_id') {
614 $campaignInfo = array();
615 $campaignDetails = self
::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
616 $fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
617 foreach ($fields as $fld)$
$fld = CRM_Utils_Array
::value($fld, $campaignDetails);
618 $showCampaignInSearch = FALSE;
619 if ($isCampaignEnabled && $hasAccessCampaign && !empty($campaigns)) {
620 //get the current campaign only.
621 $currentCampaigns = self
::getCampaigns(NULL, NULL, FALSE);
622 $pastCampaigns = array_diff($campaigns, $currentCampaigns);
623 $allCampaigns = array();
624 if (!empty($currentCampaigns)) {
625 $allCampaigns = array('crm_optgroup_current_campaign' => ts('Current Campaigns')) +
$currentCampaigns;
627 if (!empty($pastCampaigns)) {
628 $allCampaigns +
= array('crm_optgroup_past_campaign' => ts('Past Campaigns')) +
$pastCampaigns;
631 $showCampaignInSearch = TRUE;
632 $form->add('select', $elementName, ts('Campaigns'), $allCampaigns, FALSE,
633 array('id' => 'campaigns', 'multiple' => 'multiple', 'class' => 'crm-select2')
640 'showCampaignInSearch',
642 foreach ($infoFields as $fld) $campaignInfo[$fld] = $
$fld;
643 $form->assign('campaignInfo', $campaignInfo);