3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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
45 * (reference ) an assoc array of name/value pairs.
47 * @return CRM_Campaign_DAO_Campaign object
50 public 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 * Delete the campaign
105 * Id of the campaign.
109 public static function del($id) {
113 $dao = new CRM_Campaign_DAO_Campaign();
115 return $dao->delete();
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
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.
128 * @return \CRM_Campaign_DAO_Campaign|null
130 public function retrieve(&$params, &$defaults) {
131 $campaign = new CRM_Campaign_DAO_Campaign();
133 $campaign->copyValues($params);
135 if ($campaign->find(TRUE)) {
136 CRM_Core_DAO
::storeValues($campaign, $defaults);
143 * Return the all eligible campaigns w/ cache.
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.
152 * @param bool $onlyCurrent
153 * @param bool $appendDatesToTitle
154 * @param bool $forceAll
156 * @return mixed $campaigns a set of campaigns.@access public
158 public static function getCampaigns(
163 $appendDatesToTitle = FALSE,
168 $cacheKeyParams = array(
169 'includeId', 'excludeId', 'onlyActive',
170 'onlyCurrent', 'appendDatesToTitle', 'forceAll',
172 foreach ($cacheKeyParams as $param) {
173 $cacheParam = $
$param;
177 $cacheKey .= '_' . $cacheParam;
180 if (!isset($campaigns[$cacheKey])) {
181 $where = array('( camp.title IS NOT NULL )');
183 $where[] = "( camp.id != $excludeId )";
186 $where[] = '( camp.is_active = 1 )';
189 $where[] = '( camp.end_date IS NULL OR camp.end_date >= NOW() )';
191 $whereClause = implode(' AND ', $where);
193 $whereClause .= " OR ( camp.id = $includeId )";
198 $whereClause = '( 1 )';
206 FROM civicrm_campaign camp
208 Order By camp.title";
210 $campaign = CRM_Core_DAO
::executeQuery($query);
211 $campaigns[$cacheKey] = array();
212 $config = CRM_Core_Config
::singleton();
214 while ($campaign->fetch()) {
215 $title = $campaign->title
;
216 if ($appendDatesToTitle) {
218 foreach (array('start_date', 'end_date') as $date) {
219 if ($campaign->$date) {
220 $dates[] = CRM_Utils_Date
::customFormat($campaign->$date, $config->dateformatFull
);
223 if (!empty($dates)) {
224 $title .= ' (' . implode('-', $dates) . ')';
227 $campaigns[$cacheKey][$campaign->id
] = $title;
231 return $campaigns[$cacheKey];
235 * Wrapper to self::getCampaigns( )
236 * w/ permissions and component check.
239 public static function getPermissionedCampaigns($includeId = NULL,
243 $appendDatesToTitle = FALSE,
245 $doCheckForComponent = TRUE,
246 $doCheckForPermissions = TRUE
249 $cachekeyParams = array(
250 'includeId', 'excludeId', 'onlyActive', 'onlyCurrent',
251 'appendDatesToTitle', 'doCheckForComponent', 'doCheckForPermissions', 'forceAll',
253 foreach ($cachekeyParams as $param) {
254 $cacheKeyParam = $
$param;
255 if (!$cacheKeyParam) {
258 $cacheKey .= '_' . $cacheKeyParam;
261 static $validCampaigns;
262 if (!isset($validCampaigns[$cacheKey])) {
264 $campaigns = array('campaigns' => array(),
265 'hasAccessCampaign' => FALSE,
266 'isCampaignEnabled' => FALSE,
269 //do check for component.
270 if ($doCheckForComponent) {
271 $campaigns['isCampaignEnabled'] = $isValid = self
::isCampaignEnable();
274 //do check for permissions.
275 if ($doCheckForPermissions) {
276 $campaigns['hasAccessCampaign'] = $isValid = self
::accessCampaign();
279 //finally retrieve campaigns from db.
281 $campaigns['campaigns'] = self
::getCampaigns($includeId,
291 $validCampaigns[$cacheKey] = $campaigns;
294 return $validCampaigns[$cacheKey];
298 * Is CiviCampaign enabled.
301 public static function isCampaignEnable() {
302 static $isEnable = NULL;
304 if (!isset($isEnable)) {
306 $config = CRM_Core_Config
::singleton();
307 if (in_array('CiviCampaign', $config->enableComponents
)) {
316 * Retrieve campaigns for dashboard.
320 public static function getCampaignSummary($params = array(), $onlyCount = FALSE) {
321 $campaigns = array();
323 //build the limit and order clause.
324 $limitClause = $orderByClause = $lookupTableJoins = NULL;
327 'sort' => 'start_date',
330 'sortOrder' => 'desc',
332 foreach ($sortParams as $name => $default) {
333 if (!empty($params[$name])) {
334 $sortParams[$name] = $params[$name];
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']}";
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']}";
356 elseif ($sortParams['sort'] == 'isActive') {
357 $sortParams['sort'] = 'is_active';
359 if ($orderOnCampaignTable) {
360 $orderByClause = "ORDER BY campaign.{$sortParams['sort']} {$sortParams['sortOrder']}";
362 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
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');
371 if (!empty($params['name'])) {
372 $where[] = "( campaign.name LIKE %2 )";
373 $queryParams[2] = array('%' . trim($params['name']) . '%', 'String');
375 if (!empty($params['title'])) {
376 $where[] = "( campaign.title LIKE %3 )";
377 $queryParams[3] = array('%' . trim($params['title']) . '%', 'String');
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');
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');
389 if (!empty($params['description'])) {
390 $where[] = "( campaign.description LIKE %6 )";
391 $queryParams[6] = array('%' . trim($params['description']) . '%', 'String');
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']);
398 $where[] = "( campaign.campaign_type_id IN ( {$typeId} ) )";
400 if (!empty($params['status_id'])) {
401 $statusId = $params['status_id'];
402 if (is_array($params['status_id'])) {
403 $statusId = implode(' , ', $params['status_id']);
405 $where[] = "( campaign.status_id IN ( {$statusId} ) )";
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 )";
415 if (!empty($where)) {
416 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
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';
442 $selectClause = 'SELECT COUNT(*)';
444 $fromClause = 'FROM civicrm_campaign campaign';
446 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
448 //in case of only count.
450 return (int)CRM_Core_DAO
::singleValueQuery($query, $queryParams);
453 $campaign = CRM_Core_DAO
::executeQuery($query, $queryParams);
454 while ($campaign->fetch()) {
455 foreach ($properties as $property) {
456 $campaigns[$campaign->id
][$property] = $campaign->$property;
464 * Get the campaign count.
468 public static function getCampaignCount() {
469 return (int)CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM civicrm_campaign');
473 * Get Campaigns groups
475 * @param int $campaignId
481 public static function getCampaignGroups($campaignId) {
482 static $campaignGroups;
487 if (!isset($campaignGroups[$campaignId])) {
488 $campaignGroups[$campaignId] = array();
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";
498 $groups = CRM_Core_DAO
::executeQuery($query, array(1 => array($campaignId, 'Positive')));
499 while ($groups->fetch()) {
500 $campaignGroups[$campaignId][$groups->id
] = $groups->title
;
504 return $campaignGroups[$campaignId];
508 * Update the is_active flag in the db
511 * Id of the database record.
512 * @param bool $is_active
513 * Value we want to set the is_active field.
515 * @return Object DAO object on sucess, null otherwise
518 public static function setIsActive($id, $is_active) {
519 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Campaign', $id, 'is_active', $is_active);
525 public static function accessCampaign() {
526 static $allow = NULL;
528 if (!isset($allow)) {
530 if (CRM_Core_Permission
::check('manage campaign') ||
531 CRM_Core_Permission
::check('administer CiviCampaign')
541 * Add select element for campaign
542 * and assign needful info to templates.
546 * @param CRM_Core_Form $form
547 * @param int $connectedCampaignId
549 public static function addCampaign(&$form, $connectedCampaignId = NULL) {
550 //some forms do set default and freeze.
552 if ($form->get('action') & CRM_Core_Action
::VIEW
) {
553 $appendDates = FALSE;
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);
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;
566 $hasCampaigns = FALSE;
567 if (!empty($campaigns)) {
568 $hasCampaigns = TRUE;
570 if ($hasPastCampaigns) {
571 $hasCampaigns = TRUE;
572 $form->add('hidden', 'included_past_campaigns');
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;
584 $campaign = &$form->add('select',
587 array('' => ts('- select -')) +
$campaigns,
589 array('class' => 'crm-select2')
591 //lets freeze when user does not has access or campaign is disabled.
592 if (!$isCampaignEnabled ||
!$hasAccessCampaign) {
597 $addCampaignURL = NULL;
598 if (empty($campaigns) && $hasAccessCampaign && $isCampaignEnabled) {
599 $addCampaignURL = CRM_Utils_System
::url('civicrm/campaign/add', 'reset=1');
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',
610 //carry this info to templates.
618 'includePastCampaignURL',
619 'alreadyIncludedPastCampaigns',
621 foreach ($infoFields as $fld) $campaignInfo[$fld] = $
$fld;
622 $form->assign('campaignInfo', $campaignInfo);
626 * Add campaign in compoent search.
627 * and assign needful info to templates.
629 * @param CRM_Core_Form $form
630 * @param string $elementName
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;
646 if (!empty($pastCampaigns)) {
647 $allCampaigns +
= array('crm_optgroup_past_campaign' => ts('Past Campaigns')) +
$pastCampaigns;
650 $showCampaignInSearch = TRUE;
651 $form->add('select', $elementName, ts('Campaigns'), $allCampaigns, FALSE,
652 array('id' => 'campaigns', 'multiple' => 'multiple', 'class' => 'crm-select2')
659 'showCampaignInSearch',
661 foreach ($infoFields as $fld) $campaignInfo[$fld] = $
$fld;
662 $form->assign('campaignInfo', $campaignInfo);