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 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 * 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 * @param bool $onlyCurrent
148 * @param bool $appendDatesToTitle
149 * @param bool $forceAll
151 * @return mixed $campaigns a set of campaigns.@access public
153 public static function getCampaigns(
158 $appendDatesToTitle = FALSE,
163 $cacheKeyParams = array(
164 'includeId', 'excludeId', 'onlyActive',
165 'onlyCurrent', 'appendDatesToTitle', 'forceAll',
167 foreach ($cacheKeyParams as $param) {
168 $cacheParam = $
$param;
172 $cacheKey .= '_' . $cacheParam;
175 if (!isset($campaigns[$cacheKey])) {
176 $where = array('( camp.title IS NOT NULL )');
178 $where[] = "( camp.id != $excludeId )";
181 $where[] = '( camp.is_active = 1 )';
184 $where[] = '( camp.end_date IS NULL OR camp.end_date >= NOW() )';
186 $whereClause = implode(' AND ', $where);
188 $whereClause .= " OR ( camp.id = $includeId )";
193 $whereClause = '( 1 )';
201 FROM civicrm_campaign camp
203 Order By camp.title";
205 $campaign = CRM_Core_DAO
::executeQuery($query);
206 $campaigns[$cacheKey] = array();
207 $config = CRM_Core_Config
::singleton();
209 while ($campaign->fetch()) {
210 $title = $campaign->title
;
211 if ($appendDatesToTitle) {
213 foreach (array('start_date', 'end_date') as $date) {
214 if ($campaign->$date) {
215 $dates[] = CRM_Utils_Date
::customFormat($campaign->$date, $config->dateformatFull
);
218 if (!empty($dates)) {
219 $title .= ' (' . implode('-', $dates) . ')';
222 $campaigns[$cacheKey][$campaign->id
] = $title;
226 return $campaigns[$cacheKey];
230 * Wrapper to self::getCampaigns( )
231 * w/ permissions and component check.
234 public static function getPermissionedCampaigns($includeId = NULL,
238 $appendDatesToTitle = FALSE,
240 $doCheckForComponent = TRUE,
241 $doCheckForPermissions = TRUE
244 $cachekeyParams = array(
245 'includeId', 'excludeId', 'onlyActive', 'onlyCurrent',
246 'appendDatesToTitle', 'doCheckForComponent', 'doCheckForPermissions', 'forceAll',
248 foreach ($cachekeyParams as $param) {
249 $cacheKeyParam = $
$param;
250 if (!$cacheKeyParam) {
253 $cacheKey .= '_' . $cacheKeyParam;
256 static $validCampaigns;
257 if (!isset($validCampaigns[$cacheKey])) {
259 $campaigns = array('campaigns' => array(),
260 'hasAccessCampaign' => FALSE,
261 'isCampaignEnabled' => FALSE,
264 //do check for component.
265 if ($doCheckForComponent) {
266 $campaigns['isCampaignEnabled'] = $isValid = self
::isCampaignEnable();
269 //do check for permissions.
270 if ($doCheckForPermissions) {
271 $campaigns['hasAccessCampaign'] = $isValid = self
::accessCampaign();
274 //finally retrieve campaigns from db.
276 $campaigns['campaigns'] = self
::getCampaigns($includeId,
286 $validCampaigns[$cacheKey] = $campaigns;
289 return $validCampaigns[$cacheKey];
293 * Is CiviCampaign enabled.
296 public static function isCampaignEnable() {
297 static $isEnable = NULL;
299 if (!isset($isEnable)) {
301 $config = CRM_Core_Config
::singleton();
302 if (in_array('CiviCampaign', $config->enableComponents
)) {
311 * Retrieve campaigns for dashboard.
315 static function getCampaignSummary($params = array(), $onlyCount = FALSE) {
316 $campaigns = array();
318 //build the limit and order clause.
319 $limitClause = $orderByClause = $lookupTableJoins = NULL;
322 'sort' => 'start_date',
325 'sortOrder' => 'desc',
327 foreach ($sortParams as $name => $default) {
328 if (!empty($params[$name])) {
329 $sortParams[$name] = $params[$name];
334 //need to lookup tables.
335 $orderOnCampaignTable = TRUE;
336 if ($sortParams['sort'] == 'status') {
337 $orderOnCampaignTable = FALSE;
338 $lookupTableJoins = "
339 LEFT JOIN civicrm_option_value status ON ( status.value = campaign.status_id OR campaign.status_id IS NULL )
340 INNER JOIN civicrm_option_group grp ON ( status.option_group_id = grp.id AND grp.name = 'campaign_status' )";
341 $orderByClause = "ORDER BY status.label {$sortParams['sortOrder']}";
343 elseif ($sortParams['sort'] == 'campaign_type') {
344 $orderOnCampaignTable = FALSE;
345 $lookupTableJoins = "
346 LEFT JOIN civicrm_option_value campaign_type ON ( campaign_type.value = campaign.campaign_type_id
347 OR campaign.campaign_type_id IS NULL )
348 INNER JOIN civicrm_option_group grp ON ( campaign_type.option_group_id = grp.id AND grp.name = 'campaign_type' )";
349 $orderByClause = "ORDER BY campaign_type.label {$sortParams['sortOrder']}";
351 elseif ($sortParams['sort'] == 'isActive') {
352 $sortParams['sort'] = 'is_active';
354 if ($orderOnCampaignTable) {
355 $orderByClause = "ORDER BY campaign.{$sortParams['sort']} {$sortParams['sortOrder']}";
357 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
360 //build the where clause.
361 $queryParams = $where = array();
362 if (!empty($params['id'])) {
363 $where[] = "( campaign.id = %1 )";
364 $queryParams[1] = array($params['id'], 'Positive');
366 if (!empty($params['name'])) {
367 $where[] = "( campaign.name LIKE %2 )";
368 $queryParams[2] = array('%' . trim($params['name']) . '%', 'String');
370 if (!empty($params['title'])) {
371 $where[] = "( campaign.title LIKE %3 )";
372 $queryParams[3] = array('%' . trim($params['title']) . '%', 'String');
374 if (!empty($params['start_date'])) {
375 $startDate = CRM_Utils_Date
::processDate($params['start_date']);
376 $where[] = "( campaign.start_date >= %4 OR campaign.start_date IS NULL )";
377 $queryParams[4] = array($startDate, 'String');
379 if (!empty($params['end_date'])) {
380 $endDate = CRM_Utils_Date
::processDate($params['end_date'], '235959');
381 $where[] = "( campaign.end_date <= %5 OR campaign.end_date IS NULL )";
382 $queryParams[5] = array($endDate, 'String');
384 if (!empty($params['description'])) {
385 $where[] = "( campaign.description LIKE %6 )";
386 $queryParams[6] = array('%' . trim($params['description']) . '%', 'String');
388 if (!empty($params['campaign_type_id'])) {
389 $typeId = $params['campaign_type_id'];
390 if (is_array($params['campaign_type_id'])) {
391 $typeId = implode(' , ', $params['campaign_type_id']);
393 $where[] = "( campaign.campaign_type_id IN ( {$typeId} ) )";
395 if (!empty($params['status_id'])) {
396 $statusId = $params['status_id'];
397 if (is_array($params['status_id'])) {
398 $statusId = implode(' , ', $params['status_id']);
400 $where[] = "( campaign.status_id IN ( {$statusId} ) )";
402 if (array_key_exists('is_active', $params)) {
403 $active = "( campaign.is_active = 1 )";
404 if (!empty($params['is_active'])) {
405 $active = "( campaign.is_active = 0 OR campaign.is_active IS NULL )";
410 if (!empty($where)) {
411 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
427 SELECT campaign.id as id,
428 campaign.name as name,
429 campaign.title as title,
430 campaign.is_active as is_active,
431 campaign.status_id as status_id,
432 campaign.end_date as end_date,
433 campaign.start_date as start_date,
434 campaign.description as description,
435 campaign.campaign_type_id as campaign_type_id';
437 $selectClause = 'SELECT COUNT(*)';
439 $fromClause = 'FROM civicrm_campaign campaign';
441 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
443 //in case of only count.
445 return (int)CRM_Core_DAO
::singleValueQuery($query, $queryParams);
448 $campaign = CRM_Core_DAO
::executeQuery($query, $queryParams);
449 while ($campaign->fetch()) {
450 foreach ($properties as $property) {
451 $campaigns[$campaign->id
][$property] = $campaign->$property;
459 * Get the campaign count.
463 static function getCampaignCount() {
464 return (int)CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM civicrm_campaign');
468 * Get Campaigns groups
470 * @param int $campaignId campaign id
475 static function getCampaignGroups($campaignId) {
476 static $campaignGroups;
481 if (!isset($campaignGroups[$campaignId])) {
482 $campaignGroups[$campaignId] = array();
485 SELECT grp.title, grp.id
486 FROM civicrm_campaign_group campgrp
487 INNER JOIN civicrm_group grp ON ( grp.id = campgrp.entity_id )
488 WHERE campgrp.group_type = 'Include'
489 AND campgrp.entity_table = 'civicrm_group'
490 AND campgrp.campaign_id = %1";
492 $groups = CRM_Core_DAO
::executeQuery($query, array(1 => array($campaignId, 'Positive')));
493 while ($groups->fetch()) {
494 $campaignGroups[$campaignId][$groups->id
] = $groups->title
;
498 return $campaignGroups[$campaignId];
502 * Update the is_active flag in the db
504 * @param int $id id of the database record
505 * @param boolean $is_active value we want to set the is_active field
507 * @return Object DAO object on sucess, null otherwise
510 static function setIsActive($id, $is_active) {
511 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Campaign', $id, 'is_active', $is_active);
517 static function accessCampaign() {
518 static $allow = NULL;
520 if (!isset($allow)) {
522 if (CRM_Core_Permission
::check('manage campaign') ||
523 CRM_Core_Permission
::check('administer CiviCampaign')
533 * Add select element for campaign
534 * and assign needful info to templates.
538 * @param CRM_Core_Form $form
539 * @param int $connectedCampaignId
541 public static function addCampaign(&$form, $connectedCampaignId = NULL) {
542 //some forms do set default and freeze.
544 if ($form->get('action') & CRM_Core_Action
::VIEW
) {
545 $appendDates = FALSE;
548 $campaignDetails = self
::getPermissionedCampaigns($connectedCampaignId, NULL, TRUE, TRUE, $appendDates);
549 $fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
550 foreach ($fields as $fld)$
$fld = CRM_Utils_Array
::value($fld, $campaignDetails);
552 //lets see do we have past campaigns.
553 $hasPastCampaigns = FALSE;
554 $allActiveCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, TRUE, FALSE);
555 if (count($allActiveCampaigns) > count($campaigns)) {
556 $hasPastCampaigns = TRUE;
558 $hasCampaigns = FALSE;
559 if (!empty($campaigns)) {
560 $hasCampaigns = TRUE;
562 if ($hasPastCampaigns) {
563 $hasCampaigns = TRUE;
564 $form->add('hidden', 'included_past_campaigns');
567 $showAddCampaign = FALSE;
568 $alreadyIncludedPastCampaigns = FALSE;
569 if ($connectedCampaignId ||
($isCampaignEnabled && $hasAccessCampaign)) {
570 $showAddCampaign = TRUE;
571 //lets add past campaigns as options to quick-form element.
572 if ($hasPastCampaigns && $form->getElementValue('included_past_campaigns')) {
573 $campaigns = $allActiveCampaigns;
574 $alreadyIncludedPastCampaigns = TRUE;
576 $campaign = &$form->add('select',
579 array('' => ts('- select -')) +
$campaigns,
581 array('class' => 'crm-select2')
583 //lets freeze when user does not has access or campaign is disabled.
584 if (!$isCampaignEnabled ||
!$hasAccessCampaign) {
589 $addCampaignURL = NULL;
590 if (empty($campaigns) && $hasAccessCampaign && $isCampaignEnabled) {
591 $addCampaignURL = CRM_Utils_System
::url('civicrm/campaign/add', 'reset=1');
594 $includePastCampaignURL = NULL;
595 if ($hasPastCampaigns && $isCampaignEnabled && $hasAccessCampaign) {
596 $includePastCampaignURL = CRM_Utils_System
::url('civicrm/ajax/rest',
597 'className=CRM_Campaign_Page_AJAX&fnName=allActiveCampaigns',
602 //carry this info to templates.
610 'includePastCampaignURL',
611 'alreadyIncludedPastCampaigns',
613 foreach ($infoFields as $fld) $campaignInfo[$fld] = $
$fld;
614 $form->assign('campaignInfo', $campaignInfo);
618 * Add campaign in compoent search.
619 * and assign needful info to templates.
621 * @param CRM_Core_Form $form
622 * @param string $elementName
624 public static function addCampaignInComponentSearch(&$form, $elementName = 'campaign_id') {
625 $campaignInfo = array();
626 $campaignDetails = self
::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
627 $fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
628 foreach ($fields as $fld)$
$fld = CRM_Utils_Array
::value($fld, $campaignDetails);
629 $showCampaignInSearch = FALSE;
630 if ($isCampaignEnabled && $hasAccessCampaign && !empty($campaigns)) {
631 //get the current campaign only.
632 $currentCampaigns = self
::getCampaigns(NULL, NULL, FALSE);
633 $pastCampaigns = array_diff($campaigns, $currentCampaigns);
634 $allCampaigns = array();
635 if (!empty($currentCampaigns)) {
636 $allCampaigns = array('crm_optgroup_current_campaign' => ts('Current Campaigns')) +
$currentCampaigns;
638 if (!empty($pastCampaigns)) {
639 $allCampaigns +
= array('crm_optgroup_past_campaign' => ts('Past Campaigns')) +
$pastCampaigns;
642 $showCampaignInSearch = TRUE;
643 $form->add('select', $elementName, ts('Campaigns'), $allCampaigns, FALSE,
644 array('id' => 'campaigns', 'multiple' => 'multiple', 'class' => 'crm-select2')
651 'showCampaignInSearch',
653 foreach ($infoFields as $fld) $campaignInfo[$fld] = $
$fld;
654 $form->assign('campaignInfo', $campaignInfo);