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 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']) && !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 * function to 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 * Function to retrieve campaigns for dashboard.
315 static function getCampaignSummary($params = array(
316 ), $onlyCount = FALSE) {
317 $campaigns = array();
319 //build the limit and order clause.
320 $limitClause = $orderByClause = $lookupTableJoins = NULL;
323 'sort' => 'start_date',
326 'sortOrder' => 'desc',
328 foreach ($sortParams as $name => $default) {
329 if (!empty($params[$name])) {
330 $sortParams[$name] = $params[$name];
335 //need to lookup tables.
336 $orderOnCampaignTable = TRUE;
337 if ($sortParams['sort'] == 'status') {
338 $orderOnCampaignTable = FALSE;
339 $lookupTableJoins = "
340 LEFT JOIN civicrm_option_value status ON ( status.value = campaign.status_id OR campaign.status_id IS NULL )
341 INNER JOIN civicrm_option_group grp ON ( status.option_group_id = grp.id AND grp.name = 'campaign_status' )";
342 $orderByClause = "ORDER BY status.label {$sortParams['sortOrder']}";
344 elseif ($sortParams['sort'] == 'campaign_type') {
345 $orderOnCampaignTable = FALSE;
346 $lookupTableJoins = "
347 LEFT JOIN civicrm_option_value campaign_type ON ( campaign_type.value = campaign.campaign_type_id
348 OR campaign.campaign_type_id IS NULL )
349 INNER JOIN civicrm_option_group grp ON ( campaign_type.option_group_id = grp.id AND grp.name = 'campaign_type' )";
350 $orderByClause = "ORDER BY campaign_type.label {$sortParams['sortOrder']}";
352 elseif ($sortParams['sort'] == 'isActive') {
353 $sortParams['sort'] = 'is_active';
355 if ($orderOnCampaignTable) {
356 $orderByClause = "ORDER BY campaign.{$sortParams['sort']} {$sortParams['sortOrder']}";
358 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
361 //build the where clause.
362 $queryParams = $where = array();
363 if (!empty($params['id'])) {
364 $where[] = "( campaign.id = %1 )";
365 $queryParams[1] = array($params['id'], 'Positive');
367 if (!empty($params['name'])) {
368 $where[] = "( campaign.name LIKE %2 )";
369 $queryParams[2] = array('%' . trim($params['name']) . '%', 'String');
371 if (!empty($params['title'])) {
372 $where[] = "( campaign.title LIKE %3 )";
373 $queryParams[3] = array('%' . trim($params['title']) . '%', 'String');
375 if (!empty($params['start_date'])) {
376 $startDate = CRM_Utils_Date
::processDate($params['start_date']);
377 $where[] = "( campaign.start_date >= %4 OR campaign.start_date IS NULL )";
378 $queryParams[4] = array($startDate, 'String');
380 if (!empty($params['end_date'])) {
381 $endDate = CRM_Utils_Date
::processDate($params['end_date'], '235959');
382 $where[] = "( campaign.end_date <= %5 OR campaign.end_date IS NULL )";
383 $queryParams[5] = array($endDate, 'String');
385 if (!empty($params['description'])) {
386 $where[] = "( campaign.description LIKE %6 )";
387 $queryParams[6] = array('%' . trim($params['description']) . '%', 'String');
389 if (!empty($params['campaign_type_id'])) {
390 $typeId = $params['campaign_type_id'];
391 if (is_array($params['campaign_type_id'])) {
392 $typeId = implode(' , ', $params['campaign_type_id']);
394 $where[] = "( campaign.campaign_type_id IN ( {$typeId} ) )";
396 if (!empty($params['status_id'])) {
397 $statusId = $params['status_id'];
398 if (is_array($params['status_id'])) {
399 $statusId = implode(' , ', $params['status_id']);
401 $where[] = "( campaign.status_id IN ( {$statusId} ) )";
403 if (array_key_exists('is_active', $params)) {
404 $active = "( campaign.is_active = 1 )";
405 if (!empty($params['is_active'])) {
406 $active = "( campaign.is_active = 0 OR campaign.is_active IS NULL )";
411 if (!empty($where)) {
412 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
428 SELECT campaign.id as id,
429 campaign.name as name,
430 campaign.title as title,
431 campaign.is_active as is_active,
432 campaign.status_id as status_id,
433 campaign.end_date as end_date,
434 campaign.start_date as start_date,
435 campaign.description as description,
436 campaign.campaign_type_id as campaign_type_id';
438 $selectClause = 'SELECT COUNT(*)';
440 $fromClause = 'FROM civicrm_campaign campaign';
442 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
444 //in case of only count.
446 return (int)CRM_Core_DAO
::singleValueQuery($query, $queryParams);
449 $campaign = CRM_Core_DAO
::executeQuery($query, $queryParams);
450 while ($campaign->fetch()) {
451 foreach ($properties as $property) {
452 $campaigns[$campaign->id
][$property] = $campaign->$property;
460 * Get the campaign count.
464 static function getCampaignCount() {
465 return (int)CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM civicrm_campaign');
469 * Function to get Campaigns groups
471 * @param int $campaignId campaign id
476 static function getCampaignGroups($campaignId) {
477 static $campaignGroups;
482 if (!isset($campaignGroups[$campaignId])) {
483 $campaignGroups[$campaignId] = array();
486 SELECT grp.title, grp.id
487 FROM civicrm_campaign_group campgrp
488 INNER JOIN civicrm_group grp ON ( grp.id = campgrp.entity_id )
489 WHERE campgrp.group_type = 'Include'
490 AND campgrp.entity_table = 'civicrm_group'
491 AND campgrp.campaign_id = %1";
493 $groups = CRM_Core_DAO
::executeQuery($query, array(1 => array($campaignId, 'Positive')));
494 while ($groups->fetch()) {
495 $campaignGroups[$campaignId][$groups->id
] = $groups->title
;
499 return $campaignGroups[$campaignId];
503 * update the is_active flag in the db
505 * @param int $id id of the database record
506 * @param boolean $is_active value we want to set the is_active field
508 * @return Object DAO object on sucess, null otherwise
511 static function setIsActive($id, $is_active) {
512 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Campaign', $id, 'is_active', $is_active);
515 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.
535 public static function addCampaign(&$form, $connectedCampaignId = NULL) {
536 //some forms do set default and freeze.
538 if ($form->get('action') & CRM_Core_Action
::VIEW
) {
539 $appendDates = FALSE;
542 $campaignDetails = self
::getPermissionedCampaigns($connectedCampaignId, NULL, TRUE, TRUE, $appendDates);
543 $fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
544 foreach ($fields as $fld)$
$fld = CRM_Utils_Array
::value($fld, $campaignDetails);
546 //lets see do we have past campaigns.
547 $hasPastCampaigns = FALSE;
548 $allActiveCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, TRUE, FALSE);
549 if (count($allActiveCampaigns) > count($campaigns)) {
550 $hasPastCampaigns = TRUE;
552 $hasCampaigns = FALSE;
553 if (!empty($campaigns)) {
554 $hasCampaigns = TRUE;
556 if ($hasPastCampaigns) {
557 $hasCampaigns = TRUE;
558 $form->add('hidden', 'included_past_campaigns');
561 $showAddCampaign = FALSE;
562 $alreadyIncludedPastCampaigns = FALSE;
563 if ($connectedCampaignId ||
($isCampaignEnabled && $hasAccessCampaign)) {
564 $showAddCampaign = TRUE;
565 //lets add past campaigns as options to quick-form element.
566 if ($hasPastCampaigns && $form->getElementValue('included_past_campaigns')) {
567 $campaigns = $allActiveCampaigns;
568 $alreadyIncludedPastCampaigns = TRUE;
570 $campaign = &$form->add('select',
573 array('' => ts('- select -')) +
$campaigns,
575 array('class' => 'crm-select2')
577 //lets freeze when user does not has access or campaign is disabled.
578 if (!$isCampaignEnabled ||
!$hasAccessCampaign) {
583 $addCampaignURL = NULL;
584 if (empty($campaigns) && $hasAccessCampaign && $isCampaignEnabled) {
585 $addCampaignURL = CRM_Utils_System
::url('civicrm/campaign/add', 'reset=1');
588 $includePastCampaignURL = NULL;
589 if ($hasPastCampaigns && $isCampaignEnabled && $hasAccessCampaign) {
590 $includePastCampaignURL = CRM_Utils_System
::url('civicrm/ajax/rest',
591 'className=CRM_Campaign_Page_AJAX&fnName=allActiveCampaigns',
596 //carry this info to templates.
604 'includePastCampaignURL',
605 'alreadyIncludedPastCampaigns',
607 foreach ($infoFields as $fld) $campaignInfo[$fld] = $
$fld;
608 $form->assign('campaignInfo', $campaignInfo);
612 * Add campaign in compoent search.
613 * and assign needful info to templates.
616 public static function addCampaignInComponentSearch(&$form, $elementName = 'campaign_id') {
617 $campaignInfo = array();
618 $campaignDetails = self
::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
619 $fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
620 foreach ($fields as $fld)$
$fld = CRM_Utils_Array
::value($fld, $campaignDetails);
621 $showCampaignInSearch = FALSE;
622 if ($isCampaignEnabled && $hasAccessCampaign && !empty($campaigns)) {
623 //get the current campaign only.
624 $currentCampaigns = self
::getCampaigns(NULL, NULL, FALSE);
625 $pastCampaigns = array_diff($campaigns, $currentCampaigns);
626 $allCampaigns = array();
627 if (!empty($currentCampaigns)) {
628 $allCampaigns = array('crm_optgroup_current_campaign' => ts('Current Campaigns')) +
$currentCampaigns;
630 if (!empty($pastCampaigns)) {
631 $allCampaigns +
= array('crm_optgroup_past_campaign' => ts('Past Campaigns')) +
$pastCampaigns;
634 $showCampaignInSearch = TRUE;
635 $form->add('select', $elementName, ts('Campaigns'), $allCampaigns, FALSE,
636 array('id' => 'campaigns', 'multiple' => 'multiple', 'class' => 'crm-select2')
643 'showCampaignInSearch',
645 foreach ($infoFields as $fld) $campaignInfo[$fld] = $
$fld;
646 $form->assign('campaignInfo', $campaignInfo);