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
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
157 * $campaigns a set of campaigns.
160 public static function getCampaigns(
165 $appendDatesToTitle = FALSE,
170 $cacheKeyParams = array(
175 'appendDatesToTitle',
178 foreach ($cacheKeyParams as $param) {
179 $cacheParam = $
$param;
183 $cacheKey .= '_' . $cacheParam;
186 if (!isset($campaigns[$cacheKey])) {
187 $where = array('( camp.title IS NOT NULL )');
189 $where[] = "( camp.id != $excludeId )";
192 $where[] = '( camp.is_active = 1 )';
195 $where[] = '( camp.end_date IS NULL OR camp.end_date >= NOW() )';
197 $whereClause = implode(' AND ', $where);
199 $whereClause .= " OR ( camp.id = $includeId )";
204 $whereClause = '( 1 )';
212 FROM civicrm_campaign camp
214 Order By camp.title";
216 $campaign = CRM_Core_DAO
::executeQuery($query);
217 $campaigns[$cacheKey] = array();
218 $config = CRM_Core_Config
::singleton();
220 while ($campaign->fetch()) {
221 $title = $campaign->title
;
222 if ($appendDatesToTitle) {
224 foreach (array('start_date', 'end_date') as $date) {
225 if ($campaign->$date) {
226 $dates[] = CRM_Utils_Date
::customFormat($campaign->$date, $config->dateformatFull
);
229 if (!empty($dates)) {
230 $title .= ' (' . implode('-', $dates) . ')';
233 $campaigns[$cacheKey][$campaign->id
] = $title;
237 return $campaigns[$cacheKey];
241 * Wrapper to self::getCampaigns( )
242 * w/ permissions and component check.
244 public static function getPermissionedCampaigns(
249 $appendDatesToTitle = FALSE,
251 $doCheckForComponent = TRUE,
252 $doCheckForPermissions = TRUE
255 $cachekeyParams = array(
260 'appendDatesToTitle',
261 'doCheckForComponent',
262 'doCheckForPermissions',
265 foreach ($cachekeyParams as $param) {
266 $cacheKeyParam = $
$param;
267 if (!$cacheKeyParam) {
270 $cacheKey .= '_' . $cacheKeyParam;
273 static $validCampaigns;
274 if (!isset($validCampaigns[$cacheKey])) {
277 'campaigns' => array(),
278 'hasAccessCampaign' => FALSE,
279 'isCampaignEnabled' => FALSE,
282 //do check for component.
283 if ($doCheckForComponent) {
284 $campaigns['isCampaignEnabled'] = $isValid = self
::isCampaignEnable();
287 //do check for permissions.
288 if ($doCheckForPermissions) {
289 $campaigns['hasAccessCampaign'] = $isValid = self
::accessCampaign();
292 //finally retrieve campaigns from db.
294 $campaigns['campaigns'] = self
::getCampaigns($includeId,
304 $validCampaigns[$cacheKey] = $campaigns;
307 return $validCampaigns[$cacheKey];
311 * Is CiviCampaign enabled.
314 public static function isCampaignEnable() {
315 static $isEnable = NULL;
317 if (!isset($isEnable)) {
319 $config = CRM_Core_Config
::singleton();
320 if (in_array('CiviCampaign', $config->enableComponents
)) {
329 * Retrieve campaigns for dashboard.
333 public static function getCampaignSummary($params = array(), $onlyCount = FALSE) {
334 $campaigns = array();
336 //build the limit and order clause.
337 $limitClause = $orderByClause = $lookupTableJoins = NULL;
340 'sort' => 'start_date',
343 'sortOrder' => 'desc',
345 foreach ($sortParams as $name => $default) {
346 if (!empty($params[$name])) {
347 $sortParams[$name] = $params[$name];
351 //need to lookup tables.
352 $orderOnCampaignTable = TRUE;
353 if ($sortParams['sort'] == 'status') {
354 $orderOnCampaignTable = FALSE;
355 $lookupTableJoins = "
356 LEFT JOIN civicrm_option_value status ON ( status.value = campaign.status_id OR campaign.status_id IS NULL )
357 INNER JOIN civicrm_option_group grp ON ( status.option_group_id = grp.id AND grp.name = 'campaign_status' )";
358 $orderByClause = "ORDER BY status.label {$sortParams['sortOrder']}";
360 elseif ($sortParams['sort'] == 'campaign_type') {
361 $orderOnCampaignTable = FALSE;
362 $lookupTableJoins = "
363 LEFT JOIN civicrm_option_value campaign_type ON ( campaign_type.value = campaign.campaign_type_id
364 OR campaign.campaign_type_id IS NULL )
365 INNER JOIN civicrm_option_group grp ON ( campaign_type.option_group_id = grp.id AND grp.name = 'campaign_type' )";
366 $orderByClause = "ORDER BY campaign_type.label {$sortParams['sortOrder']}";
368 elseif ($sortParams['sort'] == 'isActive') {
369 $sortParams['sort'] = 'is_active';
371 if ($orderOnCampaignTable) {
372 $orderByClause = "ORDER BY campaign.{$sortParams['sort']} {$sortParams['sortOrder']}";
374 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
377 //build the where clause.
378 $queryParams = $where = array();
379 if (!empty($params['id'])) {
380 $where[] = "( campaign.id = %1 )";
381 $queryParams[1] = array($params['id'], 'Positive');
383 if (!empty($params['name'])) {
384 $where[] = "( campaign.name LIKE %2 )";
385 $queryParams[2] = array('%' . trim($params['name']) . '%', 'String');
387 if (!empty($params['title'])) {
388 $where[] = "( campaign.title LIKE %3 )";
389 $queryParams[3] = array('%' . trim($params['title']) . '%', 'String');
391 if (!empty($params['start_date'])) {
392 $startDate = CRM_Utils_Date
::processDate($params['start_date']);
393 $where[] = "( campaign.start_date >= %4 OR campaign.start_date IS NULL )";
394 $queryParams[4] = array($startDate, 'String');
396 if (!empty($params['end_date'])) {
397 $endDate = CRM_Utils_Date
::processDate($params['end_date'], '235959');
398 $where[] = "( campaign.end_date <= %5 OR campaign.end_date IS NULL )";
399 $queryParams[5] = array($endDate, 'String');
401 if (!empty($params['description'])) {
402 $where[] = "( campaign.description LIKE %6 )";
403 $queryParams[6] = array('%' . trim($params['description']) . '%', 'String');
405 if (!empty($params['campaign_type_id'])) {
406 $typeId = $params['campaign_type_id'];
407 if (is_array($params['campaign_type_id'])) {
408 $typeId = implode(' , ', $params['campaign_type_id']);
410 $where[] = "( campaign.campaign_type_id IN ( {$typeId} ) )";
412 if (!empty($params['status_id'])) {
413 $statusId = $params['status_id'];
414 if (is_array($params['status_id'])) {
415 $statusId = implode(' , ', $params['status_id']);
417 $where[] = "( campaign.status_id IN ( {$statusId} ) )";
419 if (array_key_exists('is_active', $params)) {
420 $active = "( campaign.is_active = 1 )";
421 if (!empty($params['is_active'])) {
422 $active = "( campaign.is_active = 0 OR campaign.is_active IS NULL )";
427 if (!empty($where)) {
428 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
444 SELECT campaign.id as id,
445 campaign.name as name,
446 campaign.title as title,
447 campaign.is_active as is_active,
448 campaign.status_id as status_id,
449 campaign.end_date as end_date,
450 campaign.start_date as start_date,
451 campaign.description as description,
452 campaign.campaign_type_id as campaign_type_id';
454 $selectClause = 'SELECT COUNT(*)';
456 $fromClause = 'FROM civicrm_campaign campaign';
458 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
460 //in case of only count.
462 return (int) CRM_Core_DAO
::singleValueQuery($query, $queryParams);
465 $campaign = CRM_Core_DAO
::executeQuery($query, $queryParams);
466 while ($campaign->fetch()) {
467 foreach ($properties as $property) {
468 $campaigns[$campaign->id
][$property] = $campaign->$property;
476 * Get the campaign count.
480 public static function getCampaignCount() {
481 return (int) CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM civicrm_campaign');
485 * Get Campaigns groups
487 * @param int $campaignId
493 public static function getCampaignGroups($campaignId) {
494 static $campaignGroups;
499 if (!isset($campaignGroups[$campaignId])) {
500 $campaignGroups[$campaignId] = array();
503 SELECT grp.title, grp.id
504 FROM civicrm_campaign_group campgrp
505 INNER JOIN civicrm_group grp ON ( grp.id = campgrp.entity_id )
506 WHERE campgrp.group_type = 'Include'
507 AND campgrp.entity_table = 'civicrm_group'
508 AND campgrp.campaign_id = %1";
510 $groups = CRM_Core_DAO
::executeQuery($query, array(1 => array($campaignId, 'Positive')));
511 while ($groups->fetch()) {
512 $campaignGroups[$campaignId][$groups->id
] = $groups->title
;
516 return $campaignGroups[$campaignId];
520 * Update the is_active flag in the db
523 * Id of the database record.
524 * @param bool $is_active
525 * Value we want to set the is_active field.
528 * DAO object on sucess, null otherwise
531 public static function setIsActive($id, $is_active) {
532 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Campaign', $id, 'is_active', $is_active);
538 public static function accessCampaign() {
539 static $allow = NULL;
541 if (!isset($allow)) {
543 if (CRM_Core_Permission
::check('manage campaign') ||
544 CRM_Core_Permission
::check('administer CiviCampaign')
554 * Add select element for campaign
555 * and assign needful info to templates.
558 * @param CRM_Core_Form $form
559 * @param int $connectedCampaignId
561 public static function addCampaign(&$form, $connectedCampaignId = NULL) {
562 //some forms do set default and freeze.
564 if ($form->get('action') & CRM_Core_Action
::VIEW
) {
565 $appendDates = FALSE;
568 $campaignDetails = self
::getPermissionedCampaigns($connectedCampaignId, NULL, TRUE, TRUE, $appendDates);
569 $fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
570 foreach ($fields as $fld) {
571 $
$fld = CRM_Utils_Array
::value($fld, $campaignDetails);
574 //lets see do we have past campaigns.
575 $hasPastCampaigns = FALSE;
576 $allActiveCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, TRUE, FALSE);
577 if (count($allActiveCampaigns) > count($campaigns)) {
578 $hasPastCampaigns = TRUE;
580 $hasCampaigns = FALSE;
581 if (!empty($campaigns)) {
582 $hasCampaigns = TRUE;
584 if ($hasPastCampaigns) {
585 $hasCampaigns = TRUE;
586 $form->add('hidden', 'included_past_campaigns');
589 $showAddCampaign = FALSE;
590 $alreadyIncludedPastCampaigns = FALSE;
591 if ($connectedCampaignId ||
($isCampaignEnabled && $hasAccessCampaign)) {
592 $showAddCampaign = TRUE;
593 //lets add past campaigns as options to quick-form element.
594 if ($hasPastCampaigns && $form->getElementValue('included_past_campaigns')) {
595 $campaigns = $allActiveCampaigns;
596 $alreadyIncludedPastCampaigns = TRUE;
598 $campaign = &$form->add('select',
601 array('' => ts('- select -')) +
$campaigns,
603 array('class' => 'crm-select2')
605 //lets freeze when user does not has access or campaign is disabled.
606 if (!$isCampaignEnabled ||
!$hasAccessCampaign) {
611 $addCampaignURL = NULL;
612 if (empty($campaigns) && $hasAccessCampaign && $isCampaignEnabled) {
613 $addCampaignURL = CRM_Utils_System
::url('civicrm/campaign/add', 'reset=1');
616 $includePastCampaignURL = NULL;
617 if ($hasPastCampaigns && $isCampaignEnabled && $hasAccessCampaign) {
618 $includePastCampaignURL = CRM_Utils_System
::url('civicrm/ajax/rest',
619 'className=CRM_Campaign_Page_AJAX&fnName=allActiveCampaigns',
624 //carry this info to templates.
632 'includePastCampaignURL',
633 'alreadyIncludedPastCampaigns',
635 foreach ($infoFields as $fld) {
636 $campaignInfo[$fld] = $
$fld;
638 $form->assign('campaignInfo', $campaignInfo);
642 * Add campaign in compoent search.
643 * and assign needful info to templates.
645 * @param CRM_Core_Form $form
646 * @param string $elementName
648 public static function addCampaignInComponentSearch(&$form, $elementName = 'campaign_id') {
649 $campaignInfo = array();
650 $campaignDetails = self
::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
651 $fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
652 foreach ($fields as $fld) {
653 $
$fld = CRM_Utils_Array
::value($fld, $campaignDetails);
655 $showCampaignInSearch = FALSE;
656 if ($isCampaignEnabled && $hasAccessCampaign && !empty($campaigns)) {
657 //get the current campaign only.
658 $currentCampaigns = self
::getCampaigns(NULL, NULL, FALSE);
659 $pastCampaigns = array_diff($campaigns, $currentCampaigns);
660 $allCampaigns = array();
661 if (!empty($currentCampaigns)) {
662 $allCampaigns = array('crm_optgroup_current_campaign' => ts('Current Campaigns')) +
$currentCampaigns;
664 if (!empty($pastCampaigns)) {
665 $allCampaigns +
= array('crm_optgroup_past_campaign' => ts('Past Campaigns')) +
$pastCampaigns;
668 $showCampaignInSearch = TRUE;
669 $form->add('select', $elementName, ts('Campaigns'), $allCampaigns, FALSE,
670 array('id' => 'campaigns', 'multiple' => 'multiple', 'class' => 'crm-select2')
677 'showCampaignInSearch',
679 foreach ($infoFields as $fld) {
680 $campaignInfo[$fld] = $
$fld;
682 $form->assign('campaignInfo', $campaignInfo);