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 (reference ) an assoc array of name/value pairs
46 * @return CRM_Campaign_DAO_Campaign object
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);
70 $campaign = new CRM_Campaign_DAO_Campaign();
71 $campaign->copyValues($params);
74 /* Create the campaign group record */
76 $groupTableName = CRM_Contact_BAO_Group
::getTableName();
78 if (isset($params['groups']) && !empty($params['groups']['include']) && is_array($params['groups']['include'])) {
79 foreach ($params['groups']['include'] as $entityId) {
80 $dao = new CRM_Campaign_DAO_CampaignGroup();
81 $dao->campaign_id
= $campaign->id
;
82 $dao->entity_table
= $groupTableName;
83 $dao->entity_id
= $entityId;
84 $dao->group_type
= 'Include';
91 if (!empty($params['custom']) &&
92 is_array($params['custom'])
94 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_campaign', $campaign->id
);
101 * Delete the campaign
103 * @param int $id id of the campaign
107 public static function del($id) {
111 $dao = new CRM_Campaign_DAO_Campaign();
113 return $dao->delete();
117 * Takes a bunch of params that are needed to match certain criteria and
118 * retrieves the relevant objects. Typically the valid params are only
121 * @param array $params (reference ) an assoc array of name/value pairs
122 * @param array $defaults (reference ) an assoc array to hold the flattened values
124 * @return \CRM_Campaign_DAO_Campaign|null
126 public function retrieve(&$params, &$defaults) {
127 $campaign = new CRM_Campaign_DAO_Campaign();
129 $campaign->copyValues($params);
131 if ($campaign->find(TRUE)) {
132 CRM_Core_DAO
::storeValues($campaign, $defaults);
139 * Return the all eligible campaigns w/ cache.
141 * @param int $includeId lets inlcude this campaign by force.
142 * @param int $excludeId do not include this campaign.
143 * @param boolean $onlyActive consider only active campaigns.
145 * @param bool $onlyCurrent
146 * @param bool $appendDatesToTitle
147 * @param bool $forceAll
149 * @return mixed $campaigns a set of campaigns.@access public
151 public static function getCampaigns(
156 $appendDatesToTitle = FALSE,
161 $cacheKeyParams = array(
162 'includeId', 'excludeId', 'onlyActive',
163 'onlyCurrent', 'appendDatesToTitle', 'forceAll',
165 foreach ($cacheKeyParams as $param) {
166 $cacheParam = $
$param;
170 $cacheKey .= '_' . $cacheParam;
173 if (!isset($campaigns[$cacheKey])) {
174 $where = array('( camp.title IS NOT NULL )');
176 $where[] = "( camp.id != $excludeId )";
179 $where[] = '( camp.is_active = 1 )';
182 $where[] = '( camp.end_date IS NULL OR camp.end_date >= NOW() )';
184 $whereClause = implode(' AND ', $where);
186 $whereClause .= " OR ( camp.id = $includeId )";
191 $whereClause = '( 1 )';
199 FROM civicrm_campaign camp
201 Order By camp.title";
203 $campaign = CRM_Core_DAO
::executeQuery($query);
204 $campaigns[$cacheKey] = array();
205 $config = CRM_Core_Config
::singleton();
207 while ($campaign->fetch()) {
208 $title = $campaign->title
;
209 if ($appendDatesToTitle) {
211 foreach (array('start_date', 'end_date') as $date) {
212 if ($campaign->$date) {
213 $dates[] = CRM_Utils_Date
::customFormat($campaign->$date, $config->dateformatFull
);
216 if (!empty($dates)) {
217 $title .= ' (' . implode('-', $dates) . ')';
220 $campaigns[$cacheKey][$campaign->id
] = $title;
224 return $campaigns[$cacheKey];
228 * Wrapper to self::getCampaigns( )
229 * w/ permissions and component check.
232 public static function getPermissionedCampaigns($includeId = NULL,
236 $appendDatesToTitle = FALSE,
238 $doCheckForComponent = TRUE,
239 $doCheckForPermissions = TRUE
242 $cachekeyParams = array(
243 'includeId', 'excludeId', 'onlyActive', 'onlyCurrent',
244 'appendDatesToTitle', 'doCheckForComponent', 'doCheckForPermissions', 'forceAll',
246 foreach ($cachekeyParams as $param) {
247 $cacheKeyParam = $
$param;
248 if (!$cacheKeyParam) {
251 $cacheKey .= '_' . $cacheKeyParam;
254 static $validCampaigns;
255 if (!isset($validCampaigns[$cacheKey])) {
257 $campaigns = array('campaigns' => array(),
258 'hasAccessCampaign' => FALSE,
259 'isCampaignEnabled' => FALSE,
262 //do check for component.
263 if ($doCheckForComponent) {
264 $campaigns['isCampaignEnabled'] = $isValid = self
::isCampaignEnable();
267 //do check for permissions.
268 if ($doCheckForPermissions) {
269 $campaigns['hasAccessCampaign'] = $isValid = self
::accessCampaign();
272 //finally retrieve campaigns from db.
274 $campaigns['campaigns'] = self
::getCampaigns($includeId,
284 $validCampaigns[$cacheKey] = $campaigns;
287 return $validCampaigns[$cacheKey];
291 * Is CiviCampaign enabled.
294 public static function isCampaignEnable() {
295 static $isEnable = NULL;
297 if (!isset($isEnable)) {
299 $config = CRM_Core_Config
::singleton();
300 if (in_array('CiviCampaign', $config->enableComponents
)) {
309 * Retrieve campaigns for dashboard.
313 public static function getCampaignSummary($params = array(), $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 public static function getCampaignCount() {
462 return (int)CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM civicrm_campaign');
466 * Get Campaigns groups
468 * @param int $campaignId campaign id
473 public 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 public static function setIsActive($id, $is_active) {
509 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Campaign', $id, 'is_active', $is_active);
515 public static function accessCampaign() {
516 static $allow = NULL;
518 if (!isset($allow)) {
520 if (CRM_Core_Permission
::check('manage campaign') ||
521 CRM_Core_Permission
::check('administer CiviCampaign')
531 * Add select element for campaign
532 * and assign needful info to templates.
536 * @param CRM_Core_Form $form
537 * @param int $connectedCampaignId
539 public static function addCampaign(&$form, $connectedCampaignId = NULL) {
540 //some forms do set default and freeze.
542 if ($form->get('action') & CRM_Core_Action
::VIEW
) {
543 $appendDates = FALSE;
546 $campaignDetails = self
::getPermissionedCampaigns($connectedCampaignId, NULL, TRUE, TRUE, $appendDates);
547 $fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
548 foreach ($fields as $fld)$
$fld = CRM_Utils_Array
::value($fld, $campaignDetails);
550 //lets see do we have past campaigns.
551 $hasPastCampaigns = FALSE;
552 $allActiveCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, TRUE, FALSE);
553 if (count($allActiveCampaigns) > count($campaigns)) {
554 $hasPastCampaigns = TRUE;
556 $hasCampaigns = FALSE;
557 if (!empty($campaigns)) {
558 $hasCampaigns = TRUE;
560 if ($hasPastCampaigns) {
561 $hasCampaigns = TRUE;
562 $form->add('hidden', 'included_past_campaigns');
565 $showAddCampaign = FALSE;
566 $alreadyIncludedPastCampaigns = FALSE;
567 if ($connectedCampaignId ||
($isCampaignEnabled && $hasAccessCampaign)) {
568 $showAddCampaign = TRUE;
569 //lets add past campaigns as options to quick-form element.
570 if ($hasPastCampaigns && $form->getElementValue('included_past_campaigns')) {
571 $campaigns = $allActiveCampaigns;
572 $alreadyIncludedPastCampaigns = TRUE;
574 $campaign = &$form->add('select',
577 array('' => ts('- select -')) +
$campaigns,
579 array('class' => 'crm-select2')
581 //lets freeze when user does not has access or campaign is disabled.
582 if (!$isCampaignEnabled ||
!$hasAccessCampaign) {
587 $addCampaignURL = NULL;
588 if (empty($campaigns) && $hasAccessCampaign && $isCampaignEnabled) {
589 $addCampaignURL = CRM_Utils_System
::url('civicrm/campaign/add', 'reset=1');
592 $includePastCampaignURL = NULL;
593 if ($hasPastCampaigns && $isCampaignEnabled && $hasAccessCampaign) {
594 $includePastCampaignURL = CRM_Utils_System
::url('civicrm/ajax/rest',
595 'className=CRM_Campaign_Page_AJAX&fnName=allActiveCampaigns',
600 //carry this info to templates.
608 'includePastCampaignURL',
609 'alreadyIncludedPastCampaigns',
611 foreach ($infoFields as $fld) $campaignInfo[$fld] = $
$fld;
612 $form->assign('campaignInfo', $campaignInfo);
616 * Add campaign in compoent search.
617 * and assign needful info to templates.
619 * @param CRM_Core_Form $form
620 * @param string $elementName
622 public static function addCampaignInComponentSearch(&$form, $elementName = 'campaign_id') {
623 $campaignInfo = array();
624 $campaignDetails = self
::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
625 $fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
626 foreach ($fields as $fld)$
$fld = CRM_Utils_Array
::value($fld, $campaignDetails);
627 $showCampaignInSearch = FALSE;
628 if ($isCampaignEnabled && $hasAccessCampaign && !empty($campaigns)) {
629 //get the current campaign only.
630 $currentCampaigns = self
::getCampaigns(NULL, NULL, FALSE);
631 $pastCampaigns = array_diff($campaigns, $currentCampaigns);
632 $allCampaigns = array();
633 if (!empty($currentCampaigns)) {
634 $allCampaigns = array('crm_optgroup_current_campaign' => ts('Current Campaigns')) +
$currentCampaigns;
636 if (!empty($pastCampaigns)) {
637 $allCampaigns +
= array('crm_optgroup_past_campaign' => ts('Past Campaigns')) +
$pastCampaigns;
640 $showCampaignInSearch = TRUE;
641 $form->add('select', $elementName, ts('Campaigns'), $allCampaigns, FALSE,
642 array('id' => 'campaigns', 'multiple' => 'multiple', 'class' => 'crm-select2')
649 'showCampaignInSearch',
651 foreach ($infoFields as $fld) $campaignInfo[$fld] = $
$fld;
652 $form->assign('campaignInfo', $campaignInfo);