INFRA-132 - Civi - PHPStorm cleanup
[civicrm-core.git] / CRM / Mailing / Selector / Browse.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36/**
37 * This class is used to browse past mailings.
38 */
39class CRM_Mailing_Selector_Browse extends CRM_Core_Selector_Base implements CRM_Core_Selector_API {
40
41 /**
100fef9d 42 * Array of supported links, currenly null
6a488035
TO
43 *
44 * @var array
45 * @static
46 */
47 static $_links = NULL;
48
49 /**
100fef9d 50 * We use desc to remind us what that column is, name is used in the tpl
6a488035
TO
51 *
52 * @var array
53 * @static
54 */
55 static $_columnHeaders;
56
57 protected $_parent;
58
59 /**
60 * Class constructor
61 *
6a488035 62 *
6c8f6e67 63 * @return \CRM_Mailing_Selector_Browse
d60f50a8 64 * @access public
6a488035 65 */
00be9182 66 public function __construct() {
6a488035 67 }
6a488035
TO
68
69 /**
70 * This method returns the links that are given for each search row.
71 *
72 * @return array
6a488035 73 */
00be9182 74 public static function &links() {
6a488035
TO
75 return self::$_links;
76 }
6a488035
TO
77
78 /**
100fef9d 79 * Getter for array of the parameters required for creating pager.
6a488035 80 *
dd244018 81 * @param $action
c490a46a 82 * @param array $params
6a488035 83 */
00be9182 84 public function getPagerParams($action, &$params) {
6a488035
TO
85 $params['csvString'] = NULL;
86 $params['rowCount'] = CRM_Utils_Pager::ROWCOUNT;
87 $params['status'] = ts('Mailings %%StatusMessage%%');
88 $params['buttonTop'] = 'PagerTopButton';
89 $params['buttonBottom'] = 'PagerBottomButton';
90 }
6a488035
TO
91
92 /**
100fef9d 93 * Returns the column headers as an array of tuples:
6a488035
TO
94 * (name, sortName (key to the sort array))
95 *
90c8230e
TO
96 * @param string $action
97 * The action being performed.
98 * @param enum $output
99 * What should the result set include (web/email/csv).
6a488035 100 *
a6c01b45
CW
101 * @return array
102 * the column headers that need to be displayed
6a488035 103 */
00be9182 104 public function &getColumnHeaders($action = NULL, $output = NULL) {
6a488035 105 $mailing = CRM_Mailing_BAO_Mailing::getTableName();
9da8dc8c 106 $job = CRM_Mailing_BAO_MailingJob::getTableName();
6a488035
TO
107 if (!isset(self::$_columnHeaders)) {
108 $completedOrder = NULL;
109
110 // Set different default sort depending on type of mailings (CRM-7652)
111 $unscheduledOrder = $scheduledOrder = $archivedOrder = CRM_Utils_Sort::DONTCARE;
112 if ($this->_parent->get('unscheduled')) {
113 $unscheduledOrder = CRM_Utils_Sort::DESCENDING;
114 }
115 elseif ($this->_parent->get('scheduled')) {
116 $scheduledOrder = CRM_Utils_Sort::DESCENDING;
117 }
118 else {
119 // sort by completed date for archived and undefined get
120 $completedOrder = CRM_Utils_Sort::DESCENDING;
121 }
122 $nameHeaderLabel = ($this->_parent->get('sms')) ? ts('SMS Name') : ts('Mailing Name');
123
124 self::$_columnHeaders = array(
125 array(
126 'name' => $nameHeaderLabel,
127 'sort' => 'name',
128 'direction' => CRM_Utils_Sort::DONTCARE,
129 ),
130 array(
131 'name' => ts('Status'),
132 'sort' => 'status',
133 'direction' => CRM_Utils_Sort::DONTCARE,
134 ),
135 array(
136 'name' => ts('Created By'),
137 'sort' => 'created_by',
138 'direction' => CRM_Utils_Sort::DONTCARE,
139 ),
140 array(
141 'name' => ts('Created Date'),
142 'sort' => 'created_date',
143 'direction' => $unscheduledOrder,
144 ),
145 array(
146 'name' => ts('Sent By'),
147 'sort' => 'scheduled_by',
148 'direction' => CRM_Utils_Sort::DONTCARE,
149 ),
150 array(
151 'name' => ts('Scheduled'),
152 'sort' => 'scheduled_date',
153 'direction' => $scheduledOrder,
154 ),
155 array(
156 'name' => ts('Started'),
157 'sort' => 'start_date',
158 'direction' => CRM_Utils_Sort::DONTCARE,
159 ),
160 array(
161 'name' => ts('Completed'),
162 'sort' => 'end_date',
163 'direction' => $completedOrder,
164 ),
165 );
166
167 if (CRM_Campaign_BAO_Campaign::isCampaignEnable()) {
35f7561f
TO
168 self::$_columnHeaders[] = array(
169 'name' => ts('Campaign'),
6a488035
TO
170 'sort' => 'campaign_id',
171 'direction' => CRM_Utils_Sort::DONTCARE,
172 );
173 }
174
175 if ($output != CRM_Core_Selector_Controller::EXPORT) {
176 self::$_columnHeaders[] = array('name' => ts('Action'));
177 }
178 }
179 return self::$_columnHeaders;
180 }
181
182 /**
183 * Returns total number of rows for the query.
184 *
185 * @param
186 *
a6c01b45
CW
187 * @return int
188 * Total number of rows
6a488035 189 */
00be9182 190 public function getTotalCount($action) {
9da8dc8c 191 $job = CRM_Mailing_BAO_MailingJob::getTableName();
6a488035
TO
192 $mailing = CRM_Mailing_BAO_Mailing::getTableName();
193 $mailingACL = CRM_Mailing_BAO_Mailing::mailingACL();
194
195 //get the where clause.
196 $params = array();
197 $whereClause = "$mailingACL AND " . $this->whereClause($params);
198
199 // CRM-11919 added addition ON clauses to mailing_job to match getRows
200 $query = "
201 SELECT COUNT( DISTINCT $mailing.id ) as count
202 FROM $mailing
203LEFT JOIN $job ON ( $mailing.id = $job.mailing_id AND civicrm_mailing_job.is_test = 0 AND civicrm_mailing_job.parent_id IS NULL )
204LEFT JOIN civicrm_contact createdContact ON ( $mailing.created_id = createdContact.id )
205LEFT JOIN civicrm_contact scheduledContact ON ( $mailing.scheduled_id = scheduledContact.id )
206 WHERE $whereClause";
207
208 return CRM_Core_DAO::singleValueQuery($query, $params);
209 }
210
211 /**
100fef9d 212 * Returns all the rows in the given offset and rowCount
6a488035 213 *
90c8230e
TO
214 * @param enum $action
215 * The action being performed.
216 * @param int $offset
217 * The row number to start from.
218 * @param int $rowCount
219 * The number of rows to return.
220 * @param string $sort
221 * The sql string that describes the sort order.
222 * @param enum $output
223 * What should the result set include (web/email/csv).
6a488035 224 *
a6c01b45
CW
225 * @return int
226 * the total number of rows for this action
6a488035 227 */
00be9182 228 public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
6a488035
TO
229 static $actionLinks = NULL;
230 if (empty($actionLinks)) {
231 $cancelExtra = ts('Are you sure you want to cancel this mailing?');
232 $deleteExtra = ts('Are you sure you want to delete this mailing?');
233 $archiveExtra = ts('Are you sure you want to archive this mailing?');
234
235 $actionLinks = array(
236 CRM_Core_Action::ENABLE => array(
237 'name' => ts('Approve/Reject'),
238 'url' => 'civicrm/mailing/approve',
239 'qs' => 'mid=%%mid%%&reset=1',
240 'title' => ts('Approve/Reject Mailing'),
241 ),
242 CRM_Core_Action::VIEW => array(
243 'name' => ts('Report'),
244 'url' => 'civicrm/mailing/report',
245 'qs' => 'mid=%%mid%%&reset=1',
246 'title' => ts('View Mailing Report'),
247 ),
248 CRM_Core_Action::UPDATE => array(
249 'name' => ts('Re-Use'),
250 'url' => 'civicrm/mailing/send',
251 'qs' => 'mid=%%mid%%&reset=1',
252 'title' => ts('Re-Send Mailing'),
253 ),
254 CRM_Core_Action::DISABLE => array(
255 'name' => ts('Cancel'),
256 'url' => 'civicrm/mailing/browse',
257 'qs' => 'action=disable&mid=%%mid%%&reset=1',
258 'extra' => 'onclick="if (confirm(\'' . $cancelExtra . '\')) this.href+=\'&amp;confirmed=1\'; else return false;"',
259 'title' => ts('Cancel Mailing'),
260 ),
261 CRM_Core_Action::PREVIEW => array(
262 'name' => ts('Continue'),
263 'url' => 'civicrm/mailing/send',
264 'qs' => 'mid=%%mid%%&continue=true&reset=1',
265 'title' => ts('Continue Mailing'),
266 ),
267 CRM_Core_Action::DELETE => array(
268 'name' => ts('Delete'),
269 'url' => 'civicrm/mailing/browse',
270 'qs' => 'action=delete&mid=%%mid%%&reset=1',
271 'extra' => 'onclick="if (confirm(\'' . $deleteExtra . '\')) this.href+=\'&amp;confirmed=1\'; else return false;"',
272 'title' => ts('Delete Mailing'),
273 ),
274 CRM_Core_Action::RENEW => array(
275 'name' => ts('Archive'),
276 'url' => 'civicrm/mailing/browse/archived',
277 'qs' => 'action=renew&mid=%%mid%%&reset=1',
278 'extra' => 'onclick="if (confirm(\'' . $archiveExtra . '\')) this.href+=\'&amp;confirmed=1\'; else return false;"',
279 'title' => ts('Archive Mailing'),
280 ),
281 );
282 }
283
284 $allAccess = TRUE;
285 $workFlow = $showApprovalLinks = $showScheduleLinks = $showCreateLinks = FALSE;
286 if (CRM_Mailing_Info::workflowEnabled()) {
287 $allAccess = FALSE;
288 $workFlow = TRUE;
289 //supercedes all permission
290 if (CRM_Core_Permission::check('access CiviMail')) {
291 $allAccess = TRUE;
292 }
293
294 if (CRM_Core_Permission::check('approve mailings')) {
295 $showApprovalLinks = TRUE;
296 }
297
298 if (CRM_Core_Permission::check('create mailings')) {
299 $showCreateLinks = TRUE;
300 }
301
302 if (CRM_Core_Permission::check('schedule mailings')) {
303 $showScheduleLinks = TRUE;
304 }
305 }
306 $mailing = new CRM_Mailing_BAO_Mailing();
307
308 $params = array();
309
310 $whereClause = ' AND ' . $this->whereClause($params);
311
312 if (empty($params)) {
313 $this->_parent->assign('isSearch', 0);
314 }
315 else {
316 $this->_parent->assign('isSearch', 1);
317 }
318 $rows = &$mailing->getRows($offset, $rowCount, $sort, $whereClause, $params);
319
320 //get the search base mailing Ids, CRM-3711.
321 $searchMailings = $mailing->searchMailingIDs();
322
323 //check for delete CRM-4418
324 $allowToDelete = CRM_Core_Permission::check('delete in CiviMail');
325
326 if ($output != CRM_Core_Selector_Controller::EXPORT) {
327
328 //create the appropriate $op to use for hook_civicrm_links
329 $pageTypes = array('view', 'mailing', 'browse');
330 if ($this->_parent->_unscheduled) {
331 $pageTypes[] = 'unscheduled';
332 }
333 if ($this->_parent->_scheduled) {
334 $pageTypes[] = 'scheduled';
335 }
336 if ($this->_parent->_archived) {
337 $pageTypes[] = 'archived';
338 }
339 $opString = implode('.', $pageTypes);
340
341 foreach ($rows as $key => $row) {
342 $actionMask = NULL;
343 if ($row['sms_provider_id']) {
344 $actionLinks[CRM_Core_Action::PREVIEW]['url'] = 'civicrm/sms/send';
345 }
346
347 if (!($row['status'] == 'Not scheduled') && !$row['sms_provider_id']) {
348 if ($allAccess || $showCreateLinks) {
349 $actionMask = CRM_Core_Action::VIEW;
350 }
351
352 if (!in_array($row['id'], $searchMailings)) {
353 if ($allAccess || $showCreateLinks) {
354 $actionMask |= CRM_Core_Action::UPDATE;
355 }
356 }
357 }
358 else {
359 if ($allAccess || ($showCreateLinks || $showScheduleLinks)) {
360 $actionMask = CRM_Core_Action::PREVIEW;
361 }
362 }
363 if (in_array($row['status'], array(
364 'Scheduled', 'Running', 'Paused'))) {
365 if ($allAccess ||
366 ($showApprovalLinks && $showCreateLinks && $showScheduleLinks)
367 ) {
368
369 $actionMask |= CRM_Core_Action::DISABLE;
370 }
371 if ($row['status'] == 'Scheduled' &&
372 empty($row['approval_status_id'])
373 ) {
374 if ($workFlow && ($allAccess || $showApprovalLinks)) {
375 $actionMask |= CRM_Core_Action::ENABLE;
376 }
377 }
378 }
379
dd244018 380 if (in_array($row['status'], array('Complete', 'Canceled')) &&
6eb1b55e 381 !$row['archived']) {
6a488035
TO
382 if ($allAccess || $showCreateLinks) {
383 $actionMask |= CRM_Core_Action::RENEW;
384 }
385 }
386
387 //check for delete permission.
388 if ($allowToDelete) {
389 $actionMask |= CRM_Core_Action::DELETE;
390 }
391
392 if ($actionMask == NULL) {
393 $actionMask = CRM_Core_Action::ADD;
394 }
395 //get status strings as per locale settings CRM-4411.
9da8dc8c 396 $rows[$key]['status'] = CRM_Mailing_BAO_MailingJob::status($row['status']);
6a488035
TO
397
398 $rows[$key]['action'] = CRM_Core_Action::formLink($actionLinks,
399 $actionMask,
400 array('mid' => $row['id']),
401 "more",
402 FALSE,
403 $opString,
404 "Mailing",
405 $row['id']
406 );
407
408 //unset($rows[$key]['id']);
409 // if the scheduled date is 0, replace it with an empty string
410 if ($rows[$key]['scheduled_iso'] == '0000-00-00 00:00:00') {
411 $rows[$key]['scheduled'] = '';
412 }
413 unset($rows[$key]['scheduled_iso']);
414 }
415 }
416
417 // also initialize the AtoZ pager
418 $this->pagerAtoZ();
419 return $rows;
420 }
421
422 /**
100fef9d 423 * Name of export file.
6a488035 424 *
90c8230e
TO
425 * @param string $output
426 * Type of output.
6a488035 427 *
a6c01b45
CW
428 * @return string
429 * name of the file
6a488035 430 */
00be9182 431 public function getExportFileName($output = 'csv') {
6a488035
TO
432 return ts('CiviMail Mailings');
433 }
434
e0ef6999
EM
435 /**
436 * @param $parent
437 */
00be9182 438 public function setParent($parent) {
6a488035
TO
439 $this->_parent = $parent;
440 }
441
e0ef6999 442 /**
c490a46a 443 * @param array $params
e0ef6999
EM
444 * @param bool $sortBy
445 *
446 * @return int|string
447 */
00be9182 448 public function whereClause(&$params, $sortBy = TRUE) {
6a488035 449 $values = $clauses = array();
f5d7a1ab 450 $isFormSubmitted = $this->_parent->get('hidden_find_mailings');
6a488035 451
f5d7a1ab 452 $title = $this->_parent->get('mailing_name');
6a488035
TO
453 if ($title) {
454 $clauses[] = 'name LIKE %1';
455 if (strpos($title, '%') !== FALSE) {
456 $params[1] = array($title, 'String', FALSE);
457 }
458 else {
459 $params[1] = array($title, 'String', TRUE);
460 }
461 }
462
f6df2c32 463 $dateClause1 = $dateClause2 = array();
6a488035
TO
464 $from = $this->_parent->get('mailing_from');
465 if (!CRM_Utils_System::isNull($from)) {
2d882552
PJ
466 if ($this->_parent->get('unscheduled')) {
467 $dateClause1[] = 'civicrm_mailing.created_date >= %2';
468 }
469 else {
470 $dateClause1[] = 'civicrm_mailing_job.start_date >= %2';
471 $dateClause2[] = 'civicrm_mailing_job.scheduled_date >= %2';
472 }
473 $params[2] = array($from, 'String');
6a488035
TO
474 }
475
476 $to = $this->_parent->get('mailing_to');
477 if (!CRM_Utils_System::isNull($to)) {
2d882552
PJ
478 if ($this->_parent->get('unscheduled')) {
479 $dateClause1[] = ' civicrm_mailing.created_date <= %3 ';
480 }
481 else {
482 $dateClause1[] = 'civicrm_mailing_job.start_date <= %3';
483 $dateClause2[] = 'civicrm_mailing_job.scheduled_date <= %3';
484 }
6a488035
TO
485 $params[3] = array($to, 'String');
486 }
487
f6df2c32 488 $dateClauses = array();
6a488035 489 if (!empty($dateClause1)) {
f6df2c32
DS
490 $dateClauses[] = implode(' AND ', $dateClause1);
491 }
492 if (!empty($dateClause2)) {
493 $dateClauses[] = implode(' AND ', $dateClause2);
494 }
495 $dateClauses = implode(' OR ', $dateClauses);
496 if (!empty($dateClauses)) {
497 $clauses[] = "({$dateClauses})";
6a488035
TO
498 }
499
6a488035 500 if ($this->_parent->get('sms')) {
f6df2c32 501 $clauses[] = "civicrm_mailing.sms_provider_id IS NOT NULL";
6a488035
TO
502 }
503 else {
f6df2c32 504 $clauses[] = "civicrm_mailing.sms_provider_id IS NULL";
6a488035
TO
505 }
506
f5d7a1ab
DS
507 // get values submitted by form
508 $isDraft = $this->_parent->get('status_unscheduled');
509 $isArchived = $this->_parent->get('is_archived');
f6df2c32
DS
510 $mailingStatus = $this->_parent->get('mailing_status');
511
f5d7a1ab
DS
512 if (!$isFormSubmitted && $this->_parent->get('scheduled')) {
513 // mimic default behavior for scheduled screen
514 $isArchived = 0;
515 $mailingStatus = array('Scheduled' => 1, 'Complete' => 1, 'Running' => 1, 'Canceled' => 1);
516 }
517 if (!$isFormSubmitted && $this->_parent->get('archived')) {
518 // mimic default behavior for archived screen
519 $isArchived = 1;
520 }
521 if (!$isFormSubmitted && $this->_parent->get('unscheduled')) {
522 // mimic default behavior for draft screen
523 $isDraft = 1;
524 }
525
753f3087 526 $statusClauses = array();
f5d7a1ab 527 if ($isDraft) {
753f3087 528 $statusClauses[] = "civicrm_mailing.scheduled_id IS NULL";
f5d7a1ab 529 }
f6df2c32 530 if (!empty($mailingStatus)) {
753f3087
DS
531 $statusClauses[] = "civicrm_mailing_job.status IN ('" . implode("', '", array_keys($mailingStatus)) . "')";
532 }
533 if (!empty($statusClauses)) {
534 $clauses[] = "(" . implode(' OR ', $statusClauses) . ")";
2d882552 535 }
cbb4cb7b 536
f6df2c32
DS
537 if (isset($isArchived)) {
538 if ($isArchived) {
753f3087 539 $clauses[] = "civicrm_mailing.is_archived = 1";
0db6c3e1
TO
540 }
541 else {
f6df2c32 542 $clauses[] = "(civicrm_mailing.is_archived IS NULL OR civicrm_mailing.is_archived = 0)";
6a488035 543 }
2d882552
PJ
544 }
545
6a488035
TO
546 if ($sortBy &&
547 $this->_parent->_sortByCharacter !== NULL
548 ) {
549 $clauses[] = "name LIKE '" . strtolower(CRM_Core_DAO::escapeWildCardString($this->_parent->_sortByCharacter)) . "%'";
550 }
551
552 // dont do a the below assignement when doing a
553 // AtoZ pager clause
554 if ($sortBy) {
555 if (count($clauses) > 1) {
556 $this->_parent->assign('isSearch', 1);
557 }
558 else {
559 $this->_parent->assign('isSearch', 0);
560 }
561 }
562
563 $createOrSentBy = $this->_parent->get('sort_name');
564 if (!CRM_Utils_System::isNull($createOrSentBy)) {
565 $clauses[] = '(createdContact.sort_name LIKE %4 OR scheduledContact.sort_name LIKE %4)';
566 $params[4] = array('%' . $createOrSentBy . '%', 'String');
567 }
568
569 $createdId = $this->_parent->get('createdId');
570 if ($createdId) {
571 $clauses[] = "(created_id = {$createdId})";
572 $params[5] = array($createdId, 'Integer');
573 }
574
575 $campainIds = $this->_parent->get('campaign_id');
576 if (!CRM_Utils_System::isNull($campainIds)) {
577 if (!is_array($campainIds)) {
578 $campaignIds = array($campaignIds);
579 }
580 $clauses[] = '( campaign_id IN ( ' . implode(' , ', array_values($campainIds)) . ' ) )';
581 }
582
583 if (empty($clauses)) {
584 return 1;
585 }
586
587 return implode(' AND ', $clauses);
588 }
589
00be9182 590 public function pagerAtoZ() {
6a488035
TO
591
592 $params = array();
593 $whereClause = $this->whereClause($params, FALSE);
594
595 $query = "
596SELECT DISTINCT UPPER(LEFT(name, 1)) as sort_name
597FROM civicrm_mailing
598LEFT JOIN civicrm_mailing_job ON (civicrm_mailing_job.mailing_id = civicrm_mailing.id)
599LEFT JOIN civicrm_contact createdContact ON ( civicrm_mailing.created_id = createdContact.id )
600LEFT JOIN civicrm_contact scheduledContact ON ( civicrm_mailing.scheduled_id = scheduledContact.id )
601WHERE $whereClause
602ORDER BY LEFT(name, 1)
603";
604
605 $dao = CRM_Core_DAO::executeQuery($query, $params);
606
607 $aToZBar = CRM_Utils_PagerAToZ::getAToZBar($dao, $this->_parent->_sortByCharacter, TRUE);
608 $this->_parent->assign('aToZ', $aToZBar);
609 }
610}