mass update of comment blocks
[civicrm-core.git] / CRM / Campaign / BAO / Campaign.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35 Class CRM_Campaign_BAO_Campaign extends CRM_Campaign_DAO_Campaign {
36
37 /**
38 * takes an associative array and creates a campaign object
39 *
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
42 * pairs
43 *
44 * @param array $params (reference ) an assoc array of name/value pairs
45 *
46 * @return object CRM_Campaign_DAO_Campaign object
47 * @access public
48 * @static
49 */
50 static function create(&$params) {
51 if (empty($params)) {
52 return;
53 }
54
55 if (!(CRM_Utils_Array::value('id', $params))) {
56
57 if (!(CRM_Utils_Array::value('created_id', $params))) {
58 $session = CRM_Core_Session::singleton();
59 $params['created_id'] = $session->get('userID');
60 }
61
62 if (!(CRM_Utils_Array::value('created_date', $params))) {
63 $params['created_date'] = date('YmdHis');
64 }
65
66 if (!(CRM_Utils_Array::value('name', $params))) {
67 $params['name'] = CRM_Utils_String::titleToVar($params['title'], 64);
68 }
69 }
70
71 $campaign = new CRM_Campaign_DAO_Campaign();
72 $campaign->copyValues($params);
73 $campaign->save();
74
75 /* Create the campaign group record */
76
77 $groupTableName = CRM_Contact_BAO_Group::getTableName();
78
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';
86 $dao->save();
87 $dao->free();
88 }
89 }
90
91 //store custom data
92 if (!empty($params['custom']) &&
93 is_array($params['custom'])
94 ) {
95 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_campaign', $campaign->id);
96 }
97
98 return $campaign;
99 }
100
101 /**
102 * function to delete the campaign
103 *
104 * @param int $id id of the campaign
105 *
106 * @return bool|mixed
107 */
108 public static function del($id) {
109 if (!$id) {
110 return FALSE;
111 }
112 $dao = new CRM_Campaign_DAO_Campaign();
113 $dao->id = $id;
114 return $dao->delete();
115 }
116
117 /**
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
120 * campaign_id.
121 *
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
124 *
125 * @return \CRM_Campaign_DAO_Campaign|null
126 * @access public
127 */
128 public function retrieve(&$params, &$defaults) {
129 $campaign = new CRM_Campaign_DAO_Campaign();
130
131 $campaign->copyValues($params);
132
133 if ($campaign->find(TRUE)) {
134 CRM_Core_DAO::storeValues($campaign, $defaults);
135 return $campaign;
136 }
137 return NULL;
138 }
139
140 /**
141 * Return the all eligible campaigns w/ cache.
142 *
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.
146 *
147 * @return $campaigns a set of campaigns.
148 * @access public
149 */
150 public static function getCampaigns(
151 $includeId = NULL,
152 $excludeId = NULL,
153 $onlyActive = TRUE,
154 $onlyCurrent = TRUE,
155 $appendDatesToTitle = FALSE,
156 $forceAll = FALSE
157 ) {
158 static $campaigns;
159 $cacheKey = 0;
160 $cacheKeyParams = array(
161 'includeId', 'excludeId', 'onlyActive',
162 'onlyCurrent', 'appendDatesToTitle', 'forceAll',
163 );
164 foreach ($cacheKeyParams as $param) {
165 $cacheParam = $$param;
166 if (!$cacheParam) {
167 $cacheParam = 0;
168 }
169 $cacheKey .= '_' . $cacheParam;
170 }
171
172 if (!isset($campaigns[$cacheKey])) {
173 $where = array('( camp.title IS NOT NULL )');
174 if ($excludeId) {
175 $where[] = "( camp.id != $excludeId )";
176 }
177 if ($onlyActive) {
178 $where[] = '( camp.is_active = 1 )';
179 }
180 if ($onlyCurrent) {
181 $where[] = '( camp.end_date IS NULL OR camp.end_date >= NOW() )';
182 }
183 $whereClause = implode(' AND ', $where);
184 if ($includeId) {
185 $whereClause .= " OR ( camp.id = $includeId )";
186 }
187
188 //lets force all.
189 if ($forceAll) {
190 $whereClause = '( 1 )';
191 }
192
193 $query = "
194 SELECT camp.id,
195 camp.title,
196 camp.start_date,
197 camp.end_date
198 FROM civicrm_campaign camp
199 WHERE {$whereClause}
200 Order By camp.title";
201
202 $campaign = CRM_Core_DAO::executeQuery($query);
203 $campaigns[$cacheKey] = array();
204 $config = CRM_Core_Config::singleton();
205
206 while ($campaign->fetch()) {
207 $title = $campaign->title;
208 if ($appendDatesToTitle) {
209 $dates = array();
210 foreach (array('start_date', 'end_date') as $date) {
211 if ($campaign->$date) {
212 $dates[] = CRM_Utils_Date::customFormat($campaign->$date, $config->dateformatFull);
213 }
214 }
215 if (!empty($dates)) {
216 $title .= ' (' . implode('-', $dates) . ')';
217 }
218 }
219 $campaigns[$cacheKey][$campaign->id] = $title;
220 }
221 }
222
223 return $campaigns[$cacheKey];
224 }
225
226 /**
227 * Wrapper to self::getCampaigns( )
228 * w/ permissions and component check.
229 *
230 */
231 public static function getPermissionedCampaigns($includeId = NULL,
232 $excludeId = NULL,
233 $onlyActive = TRUE,
234 $onlyCurrent = TRUE,
235 $appendDatesToTitle = FALSE,
236 $forceAll = FALSE,
237 $doCheckForComponent = TRUE,
238 $doCheckForPermissions = TRUE
239 ) {
240 $cacheKey = 0;
241 $cachekeyParams = array(
242 'includeId', 'excludeId', 'onlyActive', 'onlyCurrent',
243 'appendDatesToTitle', 'doCheckForComponent', 'doCheckForPermissions', 'forceAll',
244 );
245 foreach ($cachekeyParams as $param) {
246 $cacheKeyParam = $$param;
247 if (!$cacheKeyParam) {
248 $cacheKeyParam = 0;
249 }
250 $cacheKey .= '_' . $cacheKeyParam;
251 }
252
253 static $validCampaigns;
254 if (!isset($validCampaigns[$cacheKey])) {
255 $isValid = TRUE;
256 $campaigns = array('campaigns' => array(),
257 'hasAccessCampaign' => FALSE,
258 'isCampaignEnabled' => FALSE,
259 );
260
261 //do check for component.
262 if ($doCheckForComponent) {
263 $campaigns['isCampaignEnabled'] = $isValid = self::isCampaignEnable();
264 }
265
266 //do check for permissions.
267 if ($doCheckForPermissions) {
268 $campaigns['hasAccessCampaign'] = $isValid = self::accessCampaign();
269 }
270
271 //finally retrieve campaigns from db.
272 if ($isValid) {
273 $campaigns['campaigns'] = self::getCampaigns($includeId,
274 $excludeId,
275 $onlyActive,
276 $onlyCurrent,
277 $appendDatesToTitle,
278 $forceAll
279 );
280 }
281
282 //store in cache.
283 $validCampaigns[$cacheKey] = $campaigns;
284 }
285
286 return $validCampaigns[$cacheKey];
287 }
288
289 /*
290 * Is CiviCampaign enabled.
291 *
292 */
293 public static function isCampaignEnable() {
294 static $isEnable = NULL;
295
296 if (!isset($isEnable)) {
297 $isEnable = FALSE;
298 $config = CRM_Core_Config::singleton();
299 if (in_array('CiviCampaign', $config->enableComponents)) {
300 $isEnable = TRUE;
301 }
302 }
303
304 return $isEnable;
305 }
306
307 /**
308 * Function to retrieve campaigns for dashboard.
309 *
310 * @static
311 */
312 static function getCampaignSummary($params = array(
313 ), $onlyCount = FALSE) {
314 $campaigns = array();
315
316 //build the limit and order clause.
317 $limitClause = $orderByClause = $lookupTableJoins = NULL;
318 if (!$onlyCount) {
319 $sortParams = array(
320 'sort' => 'start_date',
321 'offset' => 0,
322 'rowCount' => 10,
323 'sortOrder' => 'desc',
324 );
325 foreach ($sortParams as $name => $default) {
326 if (!empty($params[$name])) {
327 $sortParams[$name] = $params[$name];
328 }
329 }
330
331
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']}";
340 }
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']}";
348 }
349 elseif ($sortParams['sort'] == 'isActive') {
350 $sortParams['sort'] = 'is_active';
351 }
352 if ($orderOnCampaignTable) {
353 $orderByClause = "ORDER BY campaign.{$sortParams['sort']} {$sortParams['sortOrder']}";
354 }
355 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
356 }
357
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');
363 }
364 if (!empty($params['name'])) {
365 $where[] = "( campaign.name LIKE %2 )";
366 $queryParams[2] = array('%' . trim($params['name']) . '%', 'String');
367 }
368 if (!empty($params['title'])) {
369 $where[] = "( campaign.title LIKE %3 )";
370 $queryParams[3] = array('%' . trim($params['title']) . '%', 'String');
371 }
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');
376 }
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');
381 }
382 if (!empty($params['description'])) {
383 $where[] = "( campaign.description LIKE %6 )";
384 $queryParams[6] = array('%' . trim($params['description']) . '%', 'String');
385 }
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']);
390 }
391 $where[] = "( campaign.campaign_type_id IN ( {$typeId} ) )";
392 }
393 if (!empty($params['status_id'])) {
394 $statusId = $params['status_id'];
395 if (is_array($params['status_id'])) {
396 $statusId = implode(' , ', $params['status_id']);
397 }
398 $where[] = "( campaign.status_id IN ( {$statusId} ) )";
399 }
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 )";
404 }
405 $where[] = $active;
406 }
407 $whereClause = NULL;
408 if (!empty($where)) {
409 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
410 }
411
412 $properties = array(
413 'id',
414 'name',
415 'title',
416 'start_date',
417 'end_date',
418 'status_id',
419 'is_active',
420 'description',
421 'campaign_type_id',
422 );
423
424 $selectClause = '
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';
434 if ($onlyCount) {
435 $selectClause = 'SELECT COUNT(*)';
436 }
437 $fromClause = 'FROM civicrm_campaign campaign';
438
439 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
440
441 //in case of only count.
442 if ($onlyCount) {
443 return (int)CRM_Core_DAO::singleValueQuery($query, $queryParams);
444 }
445
446 $campaign = CRM_Core_DAO::executeQuery($query, $queryParams);
447 while ($campaign->fetch()) {
448 foreach ($properties as $property) {
449 $campaigns[$campaign->id][$property] = $campaign->$property;
450 }
451 }
452
453 return $campaigns;
454 }
455
456 /**
457 * Get the campaign count.
458 *
459 * @static
460 */
461 static function getCampaignCount() {
462 return (int)CRM_Core_DAO::singleValueQuery('SELECT COUNT(*) FROM civicrm_campaign');
463 }
464
465 /**
466 * Function to get Campaigns groups
467 *
468 * @param int $campaignId campaign id
469 *
470 * @return array
471 * @static
472 */
473 static function getCampaignGroups($campaignId) {
474 static $campaignGroups;
475 if (!$campaignId) {
476 return array();
477 }
478
479 if (!isset($campaignGroups[$campaignId])) {
480 $campaignGroups[$campaignId] = array();
481
482 $query = "
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";
489
490 $groups = CRM_Core_DAO::executeQuery($query, array(1 => array($campaignId, 'Positive')));
491 while ($groups->fetch()) {
492 $campaignGroups[$campaignId][$groups->id] = $groups->title;
493 }
494 }
495
496 return $campaignGroups[$campaignId];
497 }
498
499 /**
500 * update the is_active flag in the db
501 *
502 * @param int $id id of the database record
503 * @param boolean $is_active value we want to set the is_active field
504 *
505 * @return Object DAO object on sucess, null otherwise
506 * @static
507 */
508 static function setIsActive($id, $is_active) {
509 return CRM_Core_DAO::setFieldValue('CRM_Campaign_DAO_Campaign', $id, 'is_active', $is_active);
510 }
511
512 static function accessCampaign() {
513 static $allow = NULL;
514
515 if (!isset($allow)) {
516 $allow = FALSE;
517 if (CRM_Core_Permission::check('manage campaign') ||
518 CRM_Core_Permission::check('administer CiviCampaign')
519 ) {
520 $allow = TRUE;
521 }
522 }
523
524 return $allow;
525 }
526
527 /*
528 * Add select element for campaign
529 * and assign needful info to templates.
530 *
531 */
532 public static function addCampaign(&$form, $connectedCampaignId = NULL) {
533 //some forms do set default and freeze.
534 $appendDates = TRUE;
535 if ($form->get('action') & CRM_Core_Action::VIEW) {
536 $appendDates = FALSE;
537 }
538
539 $campaignDetails = self::getPermissionedCampaigns($connectedCampaignId, NULL, TRUE, TRUE, $appendDates);
540 $fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
541 foreach ($fields as $fld)$$fld = CRM_Utils_Array::value($fld, $campaignDetails);
542
543 //lets see do we have past campaigns.
544 $hasPastCampaigns = FALSE;
545 $allActiveCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, TRUE, FALSE);
546 if (count($allActiveCampaigns) > count($campaigns)) {
547 $hasPastCampaigns = TRUE;
548 }
549 $hasCampaigns = FALSE;
550 if (!empty($campaigns)) {
551 $hasCampaigns = TRUE;
552 }
553 if ($hasPastCampaigns) {
554 $hasCampaigns = TRUE;
555 $form->add('hidden', 'included_past_campaigns');
556 }
557
558 $showAddCampaign = FALSE;
559 $alreadyIncludedPastCampaigns = FALSE;
560 if ($connectedCampaignId || ($isCampaignEnabled && $hasAccessCampaign)) {
561 $showAddCampaign = TRUE;
562 //lets add past campaigns as options to quick-form element.
563 if ($hasPastCampaigns && $form->getElementValue('included_past_campaigns')) {
564 $campaigns = $allActiveCampaigns;
565 $alreadyIncludedPastCampaigns = TRUE;
566 }
567 $campaign = &$form->add('select',
568 'campaign_id',
569 ts('Campaign'),
570 array('' => ts('- select -')) + $campaigns,
571 FALSE,
572 array('class' => 'crm-select2')
573 );
574 //lets freeze when user does not has access or campaign is disabled.
575 if (!$isCampaignEnabled || !$hasAccessCampaign) {
576 $campaign->freeze();
577 }
578 }
579
580 $addCampaignURL = NULL;
581 if (empty($campaigns) && $hasAccessCampaign && $isCampaignEnabled) {
582 $addCampaignURL = CRM_Utils_System::url('civicrm/campaign/add', 'reset=1');
583 }
584
585 $includePastCampaignURL = NULL;
586 if ($hasPastCampaigns && $isCampaignEnabled && $hasAccessCampaign) {
587 $includePastCampaignURL = CRM_Utils_System::url('civicrm/ajax/rest',
588 'className=CRM_Campaign_Page_AJAX&fnName=allActiveCampaigns',
589 FALSE, NULL, FALSE
590 );
591 }
592
593 //carry this info to templates.
594 $infoFields = array(
595 'hasCampaigns',
596 'addCampaignURL',
597 'showAddCampaign',
598 'hasPastCampaigns',
599 'hasAccessCampaign',
600 'isCampaignEnabled',
601 'includePastCampaignURL',
602 'alreadyIncludedPastCampaigns',
603 );
604 foreach ($infoFields as $fld) $campaignInfo[$fld] = $$fld;
605 $form->assign('campaignInfo', $campaignInfo);
606 }
607
608 /*
609 * Add campaign in compoent search.
610 * and assign needful info to templates.
611 *
612 */
613 public static function addCampaignInComponentSearch(&$form, $elementName = 'campaign_id') {
614 $campaignInfo = array();
615 $campaignDetails = self::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
616 $fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
617 foreach ($fields as $fld)$$fld = CRM_Utils_Array::value($fld, $campaignDetails);
618 $showCampaignInSearch = FALSE;
619 if ($isCampaignEnabled && $hasAccessCampaign && !empty($campaigns)) {
620 //get the current campaign only.
621 $currentCampaigns = self::getCampaigns(NULL, NULL, FALSE);
622 $pastCampaigns = array_diff($campaigns, $currentCampaigns);
623 $allCampaigns = array();
624 if (!empty($currentCampaigns)) {
625 $allCampaigns = array('crm_optgroup_current_campaign' => ts('Current Campaigns')) + $currentCampaigns;
626 }
627 if (!empty($pastCampaigns)) {
628 $allCampaigns += array('crm_optgroup_past_campaign' => ts('Past Campaigns')) + $pastCampaigns;
629 }
630
631 $showCampaignInSearch = TRUE;
632 $form->add('select', $elementName, ts('Campaigns'), $allCampaigns, FALSE,
633 array('id' => 'campaigns', 'multiple' => 'multiple', 'class' => 'crm-select2')
634 );
635 }
636 $infoFields = array(
637 'elementName',
638 'hasAccessCampaign',
639 'isCampaignEnabled',
640 'showCampaignInSearch',
641 );
642 foreach ($infoFields as $fld) $campaignInfo[$fld] = $$fld;
643 $form->assign('campaignInfo', $campaignInfo);
644 }
645 }
646