3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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']) && CRM_Utils_Array
::value('include', $params['groups']) && 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 (CRM_Utils_Array
::value('custom', $params) &&
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
106 public static function del($id) {
110 $dao = new CRM_Campaign_DAO_Campaign();
112 return $dao->delete();
116 * Takes a bunch of params that are needed to match certain criteria and
117 * retrieves the relevant objects. Typically the valid params are only
120 * @param array $params (reference ) an assoc array of name/value pairs
121 * @param array $defaults (reference ) an assoc array to hold the flattened values
125 public function retrieve(&$params, &$defaults) {
126 $campaign = new CRM_Campaign_DAO_Campaign();
128 $campaign->copyValues($params);
130 if ($campaign->find(TRUE)) {
131 CRM_Core_DAO
::storeValues($campaign, $defaults);
138 * Return the all eligible campaigns w/ cache.
140 * @param int $includeId lets inlcude this campaign by force.
141 * @param int $excludeId do not include this campaign.
142 * @param boolean $onlyActive consider only active campaigns.
144 * @return $campaigns a set of campaigns.
147 public static function getCampaigns(
152 $appendDatesToTitle = FALSE,
157 $cacheKeyParams = array(
158 'includeId', 'excludeId', 'onlyActive',
159 'onlyCurrent', 'appendDatesToTitle', 'forceAll',
161 foreach ($cacheKeyParams as $param) {
162 $cacheParam = $
$param;
166 $cacheKey .= '_' . $cacheParam;
169 if (!isset($campaigns[$cacheKey])) {
170 $where = array('( camp.title IS NOT NULL )');
172 $where[] = "( camp.id != $excludeId )";
175 $where[] = '( camp.is_active = 1 )';
178 $where[] = '( camp.end_date IS NULL OR camp.end_date >= NOW() )';
180 $whereClause = implode(' AND ', $where);
182 $whereClause .= " OR ( camp.id = $includeId )";
187 $whereClause = '( 1 )';
195 FROM civicrm_campaign camp
197 Order By camp.title";
199 $campaign = CRM_Core_DAO
::executeQuery($query);
200 $campaigns[$cacheKey] = array();
201 $config = CRM_Core_Config
::singleton();
203 while ($campaign->fetch()) {
204 $title = $campaign->title
;
205 if ($appendDatesToTitle) {
207 foreach (array('start_date', 'end_date') as $date) {
208 if ($campaign->$date) {
209 $dates[] = CRM_Utils_Date
::customFormat($campaign->$date, $config->dateformatFull
);
212 if (!empty($dates)) {
213 $title .= ' (' . implode('-', $dates) . ')';
216 $campaigns[$cacheKey][$campaign->id
] = $title;
220 return $campaigns[$cacheKey];
224 * Wrapper to self::getCampaigns( )
225 * w/ permissions and component check.
228 public static function getPermissionedCampaigns($includeId = NULL,
232 $appendDatesToTitle = FALSE,
234 $doCheckForComponent = TRUE,
235 $doCheckForPermissions = TRUE
238 $cachekeyParams = array(
239 'includeId', 'excludeId', 'onlyActive', 'onlyCurrent',
240 'appendDatesToTitle', 'doCheckForComponent', 'doCheckForPermissions', 'forceAll',
242 foreach ($cachekeyParams as $param) {
243 $cacheKeyParam = $
$param;
244 if (!$cacheKeyParam) {
247 $cacheKey .= '_' . $cacheKeyParam;
250 static $validCampaigns;
251 if (!isset($validCampaigns[$cacheKey])) {
253 $campaigns = array('campaigns' => array(),
254 'hasAccessCampaign' => FALSE,
255 'isCampaignEnabled' => FALSE,
258 //do check for component.
259 if ($doCheckForComponent) {
260 $campaigns['isCampaignEnabled'] = $isValid = self
::isCampaignEnable();
263 //do check for permissions.
264 if ($doCheckForPermissions) {
265 $campaigns['hasAccessCampaign'] = $isValid = self
::accessCampaign();
268 //finally retrieve campaigns from db.
270 $campaigns['campaigns'] = self
::getCampaigns($includeId,
280 $validCampaigns[$cacheKey] = $campaigns;
283 return $validCampaigns[$cacheKey];
287 * Is CiviCampaign enabled.
290 public static function isCampaignEnable() {
291 static $isEnable = NULL;
293 if (!isset($isEnable)) {
295 $config = CRM_Core_Config
::singleton();
296 if (in_array('CiviCampaign', $config->enableComponents
)) {
305 * Function to retrieve campaigns for dashboard.
309 static function getCampaignSummary($params = array(
310 ), $onlyCount = FALSE) {
311 $campaigns = array();
313 //build the limit and order clause.
314 $limitClause = $orderByClause = $lookupTableJoins = NULL;
317 'sort' => 'start_date',
320 'sortOrder' => 'desc',
322 foreach ($sortParams as $name => $default) {
323 if (CRM_Utils_Array
::value($name, $params)) {
324 $sortParams[$name] = $params[$name];
329 //need to lookup tables.
330 $orderOnCampaignTable = TRUE;
331 if ($sortParams['sort'] == 'status') {
332 $orderOnCampaignTable = FALSE;
333 $lookupTableJoins = "
334 LEFT JOIN civicrm_option_value status ON ( status.value = campaign.status_id OR campaign.status_id IS NULL )
335 INNER JOIN civicrm_option_group grp ON ( status.option_group_id = grp.id AND grp.name = 'campaign_status' )";
336 $orderByClause = "ORDER BY status.label {$sortParams['sortOrder']}";
338 elseif ($sortParams['sort'] == 'campaign_type') {
339 $orderOnCampaignTable = FALSE;
340 $lookupTableJoins = "
341 LEFT JOIN civicrm_option_value campaign_type ON ( campaign_type.value = campaign.campaign_type_id
342 OR campaign.campaign_type_id IS NULL )
343 INNER JOIN civicrm_option_group grp ON ( campaign_type.option_group_id = grp.id AND grp.name = 'campaign_type' )";
344 $orderByClause = "ORDER BY campaign_type.label {$sortParams['sortOrder']}";
346 elseif ($sortParams['sort'] == 'isActive') {
347 $sortParams['sort'] = 'is_active';
349 if ($orderOnCampaignTable) {
350 $orderByClause = "ORDER BY campaign.{$sortParams['sort']} {$sortParams['sortOrder']}";
352 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
355 //build the where clause.
356 $queryParams = $where = array();
357 if (CRM_Utils_Array
::value('id', $params)) {
358 $where[] = "( campaign.id = %1 )";
359 $queryParams[1] = array($params['id'], 'Positive');
361 if (CRM_Utils_Array
::value('name', $params)) {
362 $where[] = "( campaign.name LIKE %2 )";
363 $queryParams[2] = array('%' . trim($params['name']) . '%', 'String');
365 if (CRM_Utils_Array
::value('title', $params)) {
366 $where[] = "( campaign.title LIKE %3 )";
367 $queryParams[3] = array('%' . trim($params['title']) . '%', 'String');
369 if (CRM_Utils_Array
::value('start_date', $params)) {
370 $startDate = CRM_Utils_Date
::processDate($params['start_date']);
371 $where[] = "( campaign.start_date >= %4 OR campaign.start_date IS NULL )";
372 $queryParams[4] = array($startDate, 'String');
374 if (CRM_Utils_Array
::value('end_date', $params)) {
375 $endDate = CRM_Utils_Date
::processDate($params['end_date'], '235959');
376 $where[] = "( campaign.end_date <= %5 OR campaign.end_date IS NULL )";
377 $queryParams[5] = array($endDate, 'String');
379 if (CRM_Utils_Array
::value('description', $params)) {
380 $where[] = "( campaign.description LIKE %6 )";
381 $queryParams[6] = array('%' . trim($params['description']) . '%', 'String');
383 if (CRM_Utils_Array
::value('campaign_type_id', $params)) {
384 $typeId = $params['campaign_type_id'];
385 if (is_array($params['campaign_type_id'])) {
386 $typeId = implode(' , ', $params['campaign_type_id']);
388 $where[] = "( campaign.campaign_type_id IN ( {$typeId} ) )";
390 if (CRM_Utils_Array
::value('status_id', $params)) {
391 $statusId = $params['status_id'];
392 if (is_array($params['status_id'])) {
393 $statusId = implode(' , ', $params['status_id']);
395 $where[] = "( campaign.status_id IN ( {$statusId} ) )";
397 if (array_key_exists('is_active', $params)) {
398 $active = "( campaign.is_active = 1 )";
399 if (CRM_Utils_Array
::value('is_active', $params)) {
400 $active = "( campaign.is_active = 0 OR campaign.is_active IS NULL )";
405 if (!empty($where)) {
406 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
422 SELECT campaign.id as id,
423 campaign.name as name,
424 campaign.title as title,
425 campaign.is_active as is_active,
426 campaign.status_id as status_id,
427 campaign.end_date as end_date,
428 campaign.start_date as start_date,
429 campaign.description as description,
430 campaign.campaign_type_id as campaign_type_id';
432 $selectClause = 'SELECT COUNT(*)';
434 $fromClause = 'FROM civicrm_campaign campaign';
436 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
438 //in case of only count.
440 return (int)CRM_Core_DAO
::singleValueQuery($query, $queryParams);
443 $campaign = CRM_Core_DAO
::executeQuery($query, $queryParams);
444 while ($campaign->fetch()) {
445 foreach ($properties as $property) {
446 $campaigns[$campaign->id
][$property] = $campaign->$property;
454 * Get the campaign count.
458 static function getCampaignCount() {
459 return (int)CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM civicrm_campaign');
463 * Function to get Campaigns groups
465 * @param int $campaignId campaign id
469 static function getCampaignGroups($campaignId) {
470 static $campaignGroups;
475 if (!isset($campaignGroups[$campaignId])) {
476 $campaignGroups[$campaignId] = array();
479 SELECT grp.title, grp.id
480 FROM civicrm_campaign_group campgrp
481 INNER JOIN civicrm_group grp ON ( grp.id = campgrp.entity_id )
482 WHERE campgrp.group_type = 'Include'
483 AND campgrp.entity_table = 'civicrm_group'
484 AND campgrp.campaign_id = %1";
486 $groups = CRM_Core_DAO
::executeQuery($query, array(1 => array($campaignId, 'Positive')));
487 while ($groups->fetch()) {
488 $campaignGroups[$campaignId][$groups->id
] = $groups->title
;
492 return $campaignGroups[$campaignId];
496 * update the is_active flag in the db
498 * @param int $id id of the database record
499 * @param boolean $is_active value we want to set the is_active field
501 * @return Object DAO object on sucess, null otherwise
504 static function setIsActive($id, $is_active) {
505 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Campaign', $id, 'is_active', $is_active);
508 static function accessCampaign() {
509 static $allow = NULL;
511 if (!isset($allow)) {
513 if (CRM_Core_Permission
::check('manage campaign') ||
514 CRM_Core_Permission
::check('administer CiviCampaign')
524 * Add select element for campaign
525 * and assign needful info to templates.
528 public static function addCampaign(&$form, $connectedCampaignId = NULL) {
529 //some forms do set default and freeze.
531 if ($form->get('action') & CRM_Core_Action
::VIEW
) {
532 $appendDates = FALSE;
535 $campaignDetails = self
::getPermissionedCampaigns($connectedCampaignId, NULL, TRUE, TRUE, $appendDates);
536 $fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
537 foreach ($fields as $fld)$
$fld = CRM_Utils_Array
::value($fld, $campaignDetails);
539 //lets see do we have past campaigns.
540 $hasPastCampaigns = FALSE;
541 $allActiveCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, TRUE, FALSE);
542 if (count($allActiveCampaigns) > count($campaigns)) {
543 $hasPastCampaigns = TRUE;
545 $hasCampaigns = FALSE;
546 if (!empty($campaigns)) {
547 $hasCampaigns = TRUE;
549 if ($hasPastCampaigns) {
550 $hasCampaigns = TRUE;
551 $form->add('hidden', 'included_past_campaigns');
554 $showAddCampaign = FALSE;
555 $alreadyIncludedPastCampaigns = FALSE;
556 if ($connectedCampaignId ||
($isCampaignEnabled && $hasAccessCampaign)) {
557 $showAddCampaign = TRUE;
558 //lets add past campaigns as options to quick-form element.
559 if ($hasPastCampaigns && $form->getElementValue('included_past_campaigns')) {
560 $campaigns = $allActiveCampaigns;
561 $alreadyIncludedPastCampaigns = TRUE;
563 $campaign = &$form->add('select',
567 '' => ts('- select -')) +
$campaigns
569 //lets freeze when user does not has access or campaign is disabled.
570 if (!$isCampaignEnabled ||
!$hasAccessCampaign) {
575 $addCampaignURL = NULL;
576 if (empty($campaigns) && $hasAccessCampaign && $isCampaignEnabled) {
577 $addCampaignURL = CRM_Utils_System
::url('civicrm/campaign/add', 'reset=1');
580 $includePastCampaignURL = NULL;
581 if ($hasPastCampaigns && $isCampaignEnabled && $hasAccessCampaign) {
582 $includePastCampaignURL = CRM_Utils_System
::url('civicrm/ajax/rest',
583 'className=CRM_Campaign_Page_AJAX&fnName=allActiveCampaigns',
588 //carry this info to templates.
596 'includePastCampaignURL',
597 'alreadyIncludedPastCampaigns',
599 foreach ($infoFields as $fld) $campaignInfo[$fld] = $
$fld;
600 $form->assign('campaignInfo', $campaignInfo);
604 * Add campaign in compoent search.
605 * and assign needful info to templates.
608 public static function addCampaignInComponentSearch(&$form, $elementName = 'campaign_id') {
609 $campaignInfo = array();
610 $campaignDetails = self
::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
611 $fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
612 foreach ($fields as $fld)$
$fld = CRM_Utils_Array
::value($fld, $campaignDetails);
613 $showCampaignInSearch = FALSE;
614 if ($isCampaignEnabled && $hasAccessCampaign && !empty($campaigns)) {
615 //get the current campaign only.
616 $currentCampaigns = self
::getCampaigns(NULL, NULL, FALSE);
617 $pastCampaigns = array_diff($campaigns, $currentCampaigns);
618 $allCampaigns = array();
619 if (!empty($currentCampaigns)) {
620 $allCampaigns = array('current_campaign' => ts('Current Campaigns'));
621 foreach ($currentCampaigns as & $camp) $camp = " {$camp}";
622 $allCampaigns +
= $currentCampaigns;
624 if (!empty($pastCampaigns)) {
625 $allCampaigns +
= array('past_campaign' => ts('Past Campaigns'));
626 foreach ($pastCampaigns as & $camp) $camp = " {$camp}";
627 $allCampaigns +
= $pastCampaigns;
630 $showCampaignInSearch = TRUE;
631 $form->add('select', $elementName, ts('Campaigns'), $allCampaigns, FALSE,
632 array('id' => 'campaigns', 'multiple' => 'multiple', 'title' => ts('- select -'))
639 'showCampaignInSearch',
641 foreach ($infoFields as $fld) $campaignInfo[$fld] = $
$fld;
642 $form->assign('campaignInfo', $campaignInfo);