Campaign.php 20.4 KB
Newer Older
totten's avatar
totten committed
1 2 3
<?php
/*
 +--------------------------------------------------------------------+
totten's avatar
totten committed
4
 | CiviCRM version 5                                                  |
totten's avatar
totten committed
5
 +--------------------------------------------------------------------+
Seamus Lee's avatar
Seamus Lee committed
6
 | Copyright CiviCRM LLC (c) 2004-2019                                |
totten's avatar
totten committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 +--------------------------------------------------------------------+
 | This file is a part of CiviCRM.                                    |
 |                                                                    |
 | CiviCRM is free software; you can copy, modify, and distribute it  |
 | under the terms of the GNU Affero General Public License           |
 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
 |                                                                    |
 | CiviCRM is distributed in the hope that it will be useful, but     |
 | WITHOUT ANY WARRANTY; without even the implied warranty of         |
 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
 | See the GNU Affero General Public License for more details.        |
 |                                                                    |
 | You should have received a copy of the GNU Affero General Public   |
 | License and the CiviCRM Licensing Exception along                  |
 | with this program; if not, contact CiviCRM LLC                     |
 | at info[AT]civicrm[DOT]org. If you have questions about the        |
 | GNU Affero General Public License or the licensing of CiviCRM,     |
 | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
 +--------------------------------------------------------------------+
26
 */
totten's avatar
totten committed
27 28 29 30

/**
 *
 * @package CRM
Seamus Lee's avatar
Seamus Lee committed
31
 * @copyright CiviCRM LLC (c) 2004-2019
totten's avatar
totten committed
32
 */
totten's avatar
totten committed
33
class CRM_Campaign_BAO_Campaign extends CRM_Campaign_DAO_Campaign {
totten's avatar
totten committed
34 35

  /**
36
   * Takes an associative array and creates a campaign object.
totten's avatar
totten committed
37 38 39 40 41
   *
   * the function extract all the params it needs to initialize the create a
   * contact object. the params array could contain additional unused name/value
   * pairs
   *
42 43
   * @param array $params
   *   (reference ) an assoc array of name/value pairs.
totten's avatar
totten committed
44
   *
45
   * @return CRM_Campaign_DAO_Campaign
totten's avatar
totten committed
46
   */
47
  public static function create(&$params) {
totten's avatar
totten committed
48
    if (empty($params)) {
yashodha's avatar
yashodha committed
49
      return NULL;
totten's avatar
totten committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
    }

    if (!(CRM_Utils_Array::value('id', $params))) {

      if (!(CRM_Utils_Array::value('created_id', $params))) {
        $session = CRM_Core_Session::singleton();
        $params['created_id'] = $session->get('userID');
      }

      if (!(CRM_Utils_Array::value('created_date', $params))) {
        $params['created_date'] = date('YmdHis');
      }

      if (!(CRM_Utils_Array::value('name', $params))) {
        $params['name'] = CRM_Utils_String::titleToVar($params['title'], 64);
      }
66 67

      CRM_Utils_Hook::pre('create', 'Campaign', NULL, $params);
samuelsov's avatar
samuelsov committed
68
    }
samuelsov's avatar
samuelsov committed
69
    else {
70
      CRM_Utils_Hook::pre('edit', 'Campaign', $params['id'], $params);
totten's avatar
totten committed
71 72 73 74 75 76
    }

    $campaign = new CRM_Campaign_DAO_Campaign();
    $campaign->copyValues($params);
    $campaign->save();

77 78 79 80 81 82 83
    if (!empty($params['id'])) {
      CRM_Utils_Hook::post('edit', 'Campaign', $campaign->id, $campaign);
    }
    else {
      CRM_Utils_Hook::post('create', 'Campaign', $campaign->id, $campaign);
    }

totten's avatar
totten committed
84 85 86 87
    /* Create the campaign group record */

    $groupTableName = CRM_Contact_BAO_Group::getTableName();

88
    if (isset($params['groups']) && !empty($params['groups']['include']) && is_array($params['groups']['include'])) {
totten's avatar
totten committed
89
      foreach ($params['groups']['include'] as $entityId) {
totten's avatar
totten committed
90 91
        $dao = new CRM_Campaign_DAO_CampaignGroup();
        $dao->campaign_id = $campaign->id;
totten's avatar
totten committed
92
        $dao->entity_table = $groupTableName;
totten's avatar
totten committed
93 94
        $dao->entity_id = $entityId;
        $dao->group_type = 'Include';
totten's avatar
totten committed
95 96 97 98 99 100
        $dao->save();
        $dao->free();
      }
    }

    //store custom data
101
    if (!empty($params['custom']) &&
totten's avatar
totten committed
102 103 104 105 106 107 108 109 110
      is_array($params['custom'])
    ) {
      CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_campaign', $campaign->id);
    }

    return $campaign;
  }

  /**
111
   * Delete the campaign.
totten's avatar
totten committed
112
   *
113 114
   * @param int $id
   *   Id of the campaign.
115 116
   *
   * @return bool|mixed
totten's avatar
totten committed
117 118 119 120 121
   */
  public static function del($id) {
    if (!$id) {
      return FALSE;
    }
122 123 124

    CRM_Utils_Hook::pre('delete', 'Campaign', $id, CRM_Core_DAO::$_nullArray);

totten's avatar
totten committed
125 126
    $dao = new CRM_Campaign_DAO_Campaign();
    $dao->id = $id;
127 128 129 130 131
    $result = $dao->delete();

    CRM_Utils_Hook::post('delete', 'Campaign', $id, $dao);

    return $result;
totten's avatar
totten committed
132 133 134
  }

  /**
135 136 137
   * Retrieve DB object based on input parameters.
   *
   * It also stores all the retrieved values in the default array.
totten's avatar
totten committed
138
   *
139 140 141 142
   * @param array $params
   *   (reference ) an assoc array of name/value pairs.
   * @param array $defaults
   *   (reference ) an assoc array to hold the flattened values.
totten's avatar
totten committed
143
   *
144
   * @return \CRM_Campaign_DAO_Campaign|null
totten's avatar
totten committed
145
   */
BjoernE's avatar
BjoernE committed
146
  public static function retrieve(&$params, &$defaults) {
totten's avatar
totten committed
147 148 149 150 151 152 153 154 155 156 157 158 159 160
    $campaign = new CRM_Campaign_DAO_Campaign();

    $campaign->copyValues($params);

    if ($campaign->find(TRUE)) {
      CRM_Core_DAO::storeValues($campaign, $defaults);
      return $campaign;
    }
    return NULL;
  }

  /**
   * Return the all eligible campaigns w/ cache.
   *
161 162 163 164 165 166
   * @param int $includeId
   *   Lets inlcude this campaign by force.
   * @param int $excludeId
   *   Do not include this campaign.
   * @param bool $onlyActive
   *   Consider only active campaigns.
totten's avatar
totten committed
167
   *
Eileen McNaughton's avatar
Eileen McNaughton committed
168 169 170 171
   * @param bool $onlyCurrent
   * @param bool $appendDatesToTitle
   * @param bool $forceAll
   *
172 173
   * @return mixed
   *   $campaigns a set of campaigns.
totten's avatar
totten committed
174 175 176
   */
  public static function getCampaigns(
    $includeId = NULL,
totten's avatar
totten committed
177 178 179
    $excludeId = NULL,
    $onlyActive = TRUE,
    $onlyCurrent = TRUE,
totten's avatar
totten committed
180
    $appendDatesToTitle = FALSE,
totten's avatar
totten committed
181
    $forceAll = FALSE
totten's avatar
totten committed
182 183 184 185
  ) {
    static $campaigns;
    $cacheKey = 0;
    $cacheKeyParams = array(
totten's avatar
totten committed
186 187 188 189 190 191
      'includeId',
      'excludeId',
      'onlyActive',
      'onlyCurrent',
      'appendDatesToTitle',
      'forceAll',
totten's avatar
totten committed
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
    );
    foreach ($cacheKeyParams as $param) {
      $cacheParam = $$param;
      if (!$cacheParam) {
        $cacheParam = 0;
      }
      $cacheKey .= '_' . $cacheParam;
    }

    if (!isset($campaigns[$cacheKey])) {
      $where = array('( camp.title IS NOT NULL )');
      if ($excludeId) {
        $where[] = "( camp.id != $excludeId )";
      }
      if ($onlyActive) {
        $where[] = '( camp.is_active = 1 )';
      }
      if ($onlyCurrent) {
        $where[] = '( camp.end_date IS NULL OR camp.end_date >= NOW() )';
      }
      $whereClause = implode(' AND ', $where);
      if ($includeId) {
        $whereClause .= " OR ( camp.id = $includeId )";
      }

      //lets force all.
      if ($forceAll) {
        $whereClause = '( 1 )';
      }

      $query = "
  SELECT  camp.id,
          camp.title,
          camp.start_date,
          camp.end_date
    FROM  civicrm_campaign camp
   WHERE  {$whereClause}
Order By  camp.title";

      $campaign = CRM_Core_DAO::executeQuery($query);
      $campaigns[$cacheKey] = array();
      $config = CRM_Core_Config::singleton();

      while ($campaign->fetch()) {
        $title = $campaign->title;
        if ($appendDatesToTitle) {
          $dates = array();
          foreach (array('start_date', 'end_date') as $date) {
            if ($campaign->$date) {
              $dates[] = CRM_Utils_Date::customFormat($campaign->$date, $config->dateformatFull);
            }
          }
          if (!empty($dates)) {
            $title .= ' (' . implode('-', $dates) . ')';
          }
        }
        $campaigns[$cacheKey][$campaign->id] = $title;
      }
    }

    return $campaigns[$cacheKey];
  }

  /**
   * Wrapper to self::getCampaigns( )
   * w/ permissions and component check.
258 259 260 261 262 263 264 265 266 267 268
   *
   * @param int $includeId
   * @param int $excludeId
   * @param bool $onlyActive
   * @param bool $onlyCurrent
   * @param bool $appendDatesToTitle
   * @param bool $forceAll
   * @param bool $doCheckForComponent
   * @param bool $doCheckForPermissions
   *
   * @return mixed
totten's avatar
totten committed
269
   */
totten's avatar
totten committed
270 271
  public static function getPermissionedCampaigns(
    $includeId = NULL,
totten's avatar
totten committed
272 273 274 275 276 277 278 279 280 281
    $excludeId = NULL,
    $onlyActive = TRUE,
    $onlyCurrent = TRUE,
    $appendDatesToTitle = FALSE,
    $forceAll = FALSE,
    $doCheckForComponent = TRUE,
    $doCheckForPermissions = TRUE
  ) {
    $cacheKey = 0;
    $cachekeyParams = array(
totten's avatar
totten committed
282 283 284 285 286 287 288 289
      'includeId',
      'excludeId',
      'onlyActive',
      'onlyCurrent',
      'appendDatesToTitle',
      'doCheckForComponent',
      'doCheckForPermissions',
      'forceAll',
totten's avatar
totten committed
290 291 292 293 294 295 296 297 298 299 300 301
    );
    foreach ($cachekeyParams as $param) {
      $cacheKeyParam = $$param;
      if (!$cacheKeyParam) {
        $cacheKeyParam = 0;
      }
      $cacheKey .= '_' . $cacheKeyParam;
    }

    static $validCampaigns;
    if (!isset($validCampaigns[$cacheKey])) {
      $isValid = TRUE;
totten's avatar
totten committed
302
      $campaigns = array(
totten's avatar
totten committed
303
        'campaigns' => array(),
totten's avatar
totten committed
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
        'hasAccessCampaign' => FALSE,
        'isCampaignEnabled' => FALSE,
      );

      //do check for component.
      if ($doCheckForComponent) {
        $campaigns['isCampaignEnabled'] = $isValid = self::isCampaignEnable();
      }

      //do check for permissions.
      if ($doCheckForPermissions) {
        $campaigns['hasAccessCampaign'] = $isValid = self::accessCampaign();
      }

      //finally retrieve campaigns from db.
      if ($isValid) {
        $campaigns['campaigns'] = self::getCampaigns($includeId,
          $excludeId,
          $onlyActive,
          $onlyCurrent,
          $appendDatesToTitle,
          $forceAll
        );
      }

      //store in cache.
      $validCampaigns[$cacheKey] = $campaigns;
    }

    return $validCampaigns[$cacheKey];
  }

336
  /**
totten's avatar
totten committed
337
   * Is CiviCampaign enabled.
338
   * @return bool
totten's avatar
totten committed
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
   */
  public static function isCampaignEnable() {
    static $isEnable = NULL;

    if (!isset($isEnable)) {
      $isEnable = FALSE;
      $config = CRM_Core_Config::singleton();
      if (in_array('CiviCampaign', $config->enableComponents)) {
        $isEnable = TRUE;
      }
    }

    return $isEnable;
  }

  /**
colemanw's avatar
colemanw committed
355
   * Retrieve campaigns for dashboard.
totten's avatar
totten committed
356
   *
Eileen McNaughton's avatar
Eileen McNaughton committed
357 358 359 360
   * @param array $params
   * @param bool $onlyCount
   *
   * @return array|int
totten's avatar
totten committed
361
   */
362
  public static function getCampaignSummary($params = array(), $onlyCount = FALSE) {
totten's avatar
totten committed
363 364 365 366 367 368 369 370 371 372 373 374
    $campaigns = array();

    //build the limit and order clause.
    $limitClause = $orderByClause = $lookupTableJoins = NULL;
    if (!$onlyCount) {
      $sortParams = array(
        'sort' => 'start_date',
        'offset' => 0,
        'rowCount' => 10,
        'sortOrder' => 'desc',
      );
      foreach ($sortParams as $name => $default) {
375
        if (!empty($params[$name])) {
totten's avatar
totten committed
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
          $sortParams[$name] = $params[$name];
        }
      }

      //need to lookup tables.
      $orderOnCampaignTable = TRUE;
      if ($sortParams['sort'] == 'status') {
        $orderOnCampaignTable = FALSE;
        $lookupTableJoins = "
 LEFT JOIN civicrm_option_value status ON ( status.value = campaign.status_id OR campaign.status_id IS NULL )
INNER JOIN civicrm_option_group grp ON ( status.option_group_id = grp.id AND grp.name = 'campaign_status' )";
        $orderByClause = "ORDER BY status.label {$sortParams['sortOrder']}";
      }
      elseif ($sortParams['sort'] == 'campaign_type') {
        $orderOnCampaignTable = FALSE;
        $lookupTableJoins = "
 LEFT JOIN civicrm_option_value campaign_type ON ( campaign_type.value = campaign.campaign_type_id
                                                   OR campaign.campaign_type_id IS NULL )
INNER JOIN civicrm_option_group grp ON ( campaign_type.option_group_id = grp.id AND grp.name = 'campaign_type' )";
        $orderByClause = "ORDER BY campaign_type.label {$sortParams['sortOrder']}";
      }
      elseif ($sortParams['sort'] == 'isActive') {
        $sortParams['sort'] = 'is_active';
      }
      if ($orderOnCampaignTable) {
        $orderByClause = "ORDER BY campaign.{$sortParams['sort']} {$sortParams['sortOrder']}";
      }
      $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
    }

    //build the where clause.
    $queryParams = $where = array();
408
    if (!empty($params['id'])) {
totten's avatar
totten committed
409 410 411
      $where[] = "( campaign.id = %1 )";
      $queryParams[1] = array($params['id'], 'Positive');
    }
412
    if (!empty($params['name'])) {
totten's avatar
totten committed
413 414 415
      $where[] = "( campaign.name LIKE %2 )";
      $queryParams[2] = array('%' . trim($params['name']) . '%', 'String');
    }
416
    if (!empty($params['title'])) {
totten's avatar
totten committed
417 418 419
      $where[] = "( campaign.title LIKE %3 )";
      $queryParams[3] = array('%' . trim($params['title']) . '%', 'String');
    }
420
    if (!empty($params['start_date'])) {
totten's avatar
totten committed
421 422
      $startDate = CRM_Utils_Date::processDate($params['start_date']);
      $where[] = "( campaign.start_date >= %4 OR campaign.start_date IS NULL )";
totten's avatar
totten committed
423 424
      $queryParams[4] = array($startDate, 'String');
    }
425
    if (!empty($params['end_date'])) {
totten's avatar
totten committed
426 427
      $endDate = CRM_Utils_Date::processDate($params['end_date'], '235959');
      $where[] = "( campaign.end_date <= %5 OR campaign.end_date IS NULL )";
totten's avatar
totten committed
428 429
      $queryParams[5] = array($endDate, 'String');
    }
430
    if (!empty($params['description'])) {
totten's avatar
totten committed
431 432 433
      $where[] = "( campaign.description LIKE %6 )";
      $queryParams[6] = array('%' . trim($params['description']) . '%', 'String');
    }
434
    if (!empty($params['campaign_type_id'])) {
totten's avatar
totten committed
435 436 437 438 439 440
      $typeId = $params['campaign_type_id'];
      if (is_array($params['campaign_type_id'])) {
        $typeId = implode(' , ', $params['campaign_type_id']);
      }
      $where[] = "( campaign.campaign_type_id IN ( {$typeId} ) )";
    }
441
    if (!empty($params['status_id'])) {
totten's avatar
totten committed
442 443 444 445 446 447 448 449
      $statusId = $params['status_id'];
      if (is_array($params['status_id'])) {
        $statusId = implode(' , ', $params['status_id']);
      }
      $where[] = "( campaign.status_id IN ( {$statusId} ) )";
    }
    if (array_key_exists('is_active', $params)) {
      $active = "( campaign.is_active = 1 )";
450
      if (!empty($params['is_active'])) {
totten's avatar
totten committed
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
        $active = "( campaign.is_active = 0 OR campaign.is_active IS NULL )";
      }
      $where[] = $active;
    }
    $whereClause = NULL;
    if (!empty($where)) {
      $whereClause = ' WHERE ' . implode(" \nAND ", $where);
    }

    $properties = array(
      'id',
      'name',
      'title',
      'start_date',
      'end_date',
      'status_id',
      'is_active',
      'description',
      'campaign_type_id',
    );

    $selectClause = '
SELECT  campaign.id               as id,
        campaign.name             as name,
        campaign.title            as title,
        campaign.is_active        as is_active,
        campaign.status_id        as status_id,
        campaign.end_date         as end_date,
        campaign.start_date       as start_date,
        campaign.description      as description,
        campaign.campaign_type_id as campaign_type_id';
    if ($onlyCount) {
      $selectClause = 'SELECT COUNT(*)';
    }
    $fromClause = 'FROM  civicrm_campaign campaign';

    $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";

    //in case of only count.
    if ($onlyCount) {
totten's avatar
totten committed
491
      return (int) CRM_Core_DAO::singleValueQuery($query, $queryParams);
totten's avatar
totten committed
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
    }

    $campaign = CRM_Core_DAO::executeQuery($query, $queryParams);
    while ($campaign->fetch()) {
      foreach ($properties as $property) {
        $campaigns[$campaign->id][$property] = $campaign->$property;
      }
    }

    return $campaigns;
  }

  /**
   * Get the campaign count.
   *
   */
508
  public static function getCampaignCount() {
totten's avatar
totten committed
509
    return (int) CRM_Core_DAO::singleValueQuery('SELECT COUNT(*) FROM civicrm_campaign');
totten's avatar
totten committed
510 511 512
  }

  /**
513
   * Get Campaigns groups.
totten's avatar
totten committed
514
   *
515 516
   * @param int $campaignId
   *   Campaign id.
totten's avatar
totten committed
517
   *
518
   * @return array
totten's avatar
totten committed
519
   */
520
  public static function getCampaignGroups($campaignId) {
totten's avatar
totten committed
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
    static $campaignGroups;
    if (!$campaignId) {
      return array();
    }

    if (!isset($campaignGroups[$campaignId])) {
      $campaignGroups[$campaignId] = array();

      $query = "
    SELECT  grp.title, grp.id
      FROM  civicrm_campaign_group campgrp
INNER JOIN  civicrm_group grp ON ( grp.id = campgrp.entity_id )
     WHERE  campgrp.group_type = 'Include'
       AND  campgrp.entity_table = 'civicrm_group'
       AND  campgrp.campaign_id = %1";

      $groups = CRM_Core_DAO::executeQuery($query, array(1 => array($campaignId, 'Positive')));
      while ($groups->fetch()) {
        $campaignGroups[$campaignId][$groups->id] = $groups->title;
      }
    }

    return $campaignGroups[$campaignId];
  }

  /**
547
   * Update the is_active flag in the db.
totten's avatar
totten committed
548
   *
549 550 551 552
   * @param int $id
   *   Id of the database record.
   * @param bool $is_active
   *   Value we want to set the is_active field.
totten's avatar
totten committed
553
   *
554 555
   * @return bool
   *   true if we found and updated the object, else false
totten's avatar
totten committed
556
   */
557
  public static function setIsActive($id, $is_active) {
totten's avatar
totten committed
558 559 560
    return CRM_Core_DAO::setFieldValue('CRM_Campaign_DAO_Campaign', $id, 'is_active', $is_active);
  }

561 562 563
  /**
   * @return bool
   */
564
  public static function accessCampaign() {
totten's avatar
totten committed
565 566 567 568 569 570 571 572 573 574 575 576 577 578
    static $allow = NULL;

    if (!isset($allow)) {
      $allow = FALSE;
      if (CRM_Core_Permission::check('manage campaign') ||
        CRM_Core_Permission::check('administer CiviCampaign')
      ) {
        $allow = TRUE;
      }
    }

    return $allow;
  }

579
  /**
totten's avatar
totten committed
580 581
   * Add select element for campaign
   * and assign needful info to templates.
582
   *
583
   * @param CRM_Core_Form $form
colemanw's avatar
colemanw committed
584
   * @param int $connectedCampaignId
585
   */
totten's avatar
totten committed
586 587 588 589 590 591 592 593 594
  public static function addCampaign(&$form, $connectedCampaignId = NULL) {
    //some forms do set default and freeze.
    $appendDates = TRUE;
    if ($form->get('action') & CRM_Core_Action::VIEW) {
      $appendDates = FALSE;
    }

    $campaignDetails = self::getPermissionedCampaigns($connectedCampaignId, NULL, TRUE, TRUE, $appendDates);
    $fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
totten's avatar
totten committed
595 596 597
    foreach ($fields as $fld) {
      $$fld = CRM_Utils_Array::value($fld, $campaignDetails);
    }
totten's avatar
totten committed
598 599 600 601

    $showAddCampaign = FALSE;
    if ($connectedCampaignId || ($isCampaignEnabled && $hasAccessCampaign)) {
      $showAddCampaign = TRUE;
602 603 604 605
      $campaign = $form->addEntityRef('campaign_id', ts('Campaign'), [
        'entity' => 'campaign',
        'create' => TRUE,
      ]);
totten's avatar
totten committed
606 607 608 609 610 611 612 613 614 615 616 617
      //lets freeze when user does not has access or campaign is disabled.
      if (!$isCampaignEnabled || !$hasAccessCampaign) {
        $campaign->freeze();
      }
    }

    //carry this info to templates.
    $infoFields = array(
      'showAddCampaign',
      'hasAccessCampaign',
      'isCampaignEnabled',
    );
totten's avatar
totten committed
618 619 620
    foreach ($infoFields as $fld) {
      $campaignInfo[$fld] = $$fld;
    }
totten's avatar
totten committed
621 622 623
    $form->assign('campaignInfo', $campaignInfo);
  }

624
  /**
625
   * Add campaign in component search.
totten's avatar
totten committed
626 627
   * and assign needful info to templates.
   *
628
   * @param CRM_Core_Form $form
629
   * @param string $elementName
totten's avatar
totten committed
630 631
   */
  public static function addCampaignInComponentSearch(&$form, $elementName = 'campaign_id') {
totten's avatar
totten committed
632
    $campaignInfo = array();
totten's avatar
totten committed
633
    $campaignDetails = self::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
totten's avatar
totten committed
634
    $fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
totten's avatar
totten committed
635 636 637
    foreach ($fields as $fld) {
      $$fld = CRM_Utils_Array::value($fld, $campaignDetails);
    }
totten's avatar
totten committed
638 639 640 641
    $showCampaignInSearch = FALSE;
    if ($isCampaignEnabled && $hasAccessCampaign && !empty($campaigns)) {
      //get the current campaign only.
      $currentCampaigns = self::getCampaigns(NULL, NULL, FALSE);
totten's avatar
totten committed
642 643
      $pastCampaigns = array_diff($campaigns, $currentCampaigns);
      $allCampaigns = array();
totten's avatar
totten committed
644
      if (!empty($currentCampaigns)) {
645
        $allCampaigns = array('crm_optgroup_current_campaign' => ts('Current Campaigns')) + $currentCampaigns;
totten's avatar
totten committed
646 647
      }
      if (!empty($pastCampaigns)) {
648
        $allCampaigns += array('crm_optgroup_past_campaign' => ts('Past Campaigns')) + $pastCampaigns;
totten's avatar
totten committed
649 650 651 652
      }

      $showCampaignInSearch = TRUE;
      $form->add('select', $elementName, ts('Campaigns'), $allCampaigns, FALSE,
653
        array('id' => 'campaigns', 'multiple' => 'multiple', 'class' => 'crm-select2')
totten's avatar
totten committed
654 655 656 657 658 659 660 661
      );
    }
    $infoFields = array(
      'elementName',
      'hasAccessCampaign',
      'isCampaignEnabled',
      'showCampaignInSearch',
    );
totten's avatar
totten committed
662 663 664
    foreach ($infoFields as $fld) {
      $campaignInfo[$fld] = $$fld;
    }
totten's avatar
totten committed
665 666
    $form->assign('campaignInfo', $campaignInfo);
  }
667

668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
  /**
   * Links to create new campaigns from entityRef widget
   *
   * @return array|bool
   */
  public static function entityRefCreateLinks() {
    if (CRM_Core_Permission::check([['administer CiviCampaign', 'manage campaign']])) {
      return [
        [
          'label' => ts('New Campaign'),
          'url' => CRM_Utils_System::url('civicrm/campaign/add', "reset=1",
            NULL, NULL, FALSE, FALSE, TRUE),
          'type' => 'Campaign',
        ]];
    }
    return FALSE;
  }

totten's avatar
totten committed
686
}