commiting uncommited changes on live site
[weblabels.fsf.org.git] / crm.fsf.org / 20131203 / files / sites / all / modules-new / civicrm / CRM / Report / Form / Contribute / TopDonor.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
32 * $Id$
33 *
34 */
35 class CRM_Report_Form_Contribute_TopDonor extends CRM_Report_Form {
36
37 protected $_summary = NULL;
38 protected $_customGroupExtends = array(
39 'Contact',
40 'Individual',
41 'Contribution',
42 );
43
44 public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
45
46 protected $_charts = array(
47 '' => 'Tabular',
48 'barChart' => 'Bar Chart',
49 'pieChart' => 'Pie Chart',
50 );
51
52 /**
53 */
54 public function __construct() {
55 $this->_autoIncludeIndexedFieldsAsOrderBys = 1;
56 $this->_columns = array(
57 'civicrm_contact' => array(
58 'dao' => 'CRM_Contact_DAO_Contact',
59 'fields' => array(
60 'display_name' => array(
61 'title' => ts('Contact Name'),
62 'required' => TRUE,
63 'no_repeat' => TRUE,
64 ),
65 'first_name' => array(
66 'title' => ts('First Name'),
67 ),
68 'middle_name' => array(
69 'title' => ts('Middle Name'),
70 ),
71 'last_name' => array(
72 'title' => ts('Last Name'),
73 ),
74 'id' => array(
75 'no_display' => TRUE,
76 'required' => TRUE,
77 ),
78 'gender_id' => array(
79 'title' => ts('Gender'),
80 ),
81 'birth_date' => array(
82 'title' => ts('Birth Date'),
83 ),
84 'age' => array(
85 'title' => ts('Age'),
86 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
87 ),
88 'contact_type' => array(
89 'title' => ts('Contact Type'),
90 ),
91 'contact_sub_type' => array(
92 'title' => ts('Contact Subtype'),
93 ),
94 ),
95 'filters' => array(
96 'gender_id' => array(
97 'title' => ts('Gender'),
98 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
99 'options' => CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'),
100 ),
101 'contact_type' => array(
102 'title' => ts('Contact Type'),
103 ),
104 'contact_sub_type' => array(
105 'title' => ts('Contact Subtype'),
106 ),
107 ),
108 ),
109 );
110 $this->_columns += $this->getAddressColumns();
111 $this->_columns += array(
112 'civicrm_contribution' => array(
113 'dao' => 'CRM_Contribute_DAO_Contribution',
114 'fields' => array(
115 'total_amount' => array(
116 'title' => ts('Amount Statistics'),
117 'required' => TRUE,
118 'statistics' => array(
119 'sum' => ts('Aggregate Amount'),
120 'count' => ts('Donations'),
121 'avg' => ts('Average'),
122 ),
123 ),
124 'currency' => array(
125 'required' => TRUE,
126 'no_display' => TRUE,
127 ),
128 ),
129 'filters' => array(
130 'sort_name' => array(
131 'title' => ts('Participant Name'),
132 'operator' => 'like',
133 ),
134 'id' => array(
135 'title' => ts('Contact ID'),
136 'no_display' => TRUE,
137 ),
138 'birth_date' => array(
139 'title' => ts('Birth Date'),
140 'operatorType' => CRM_Report_Form::OP_DATE,
141 ),
142 'receive_date' => array(
143 'default' => 'this.year',
144 'operatorType' => CRM_Report_Form::OP_DATE,
145 ),
146 'currency' => array(
147 'title' => 'Currency',
148 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
149 'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
150 'default' => NULL,
151 'type' => CRM_Utils_Type::T_STRING,
152 ),
153 'total_range' => array(
154 'title' => ts('Show no. of Top Donors'),
155 'type' => CRM_Utils_Type::T_INT,
156 'default_op' => 'eq',
157 ),
158 'financial_type_id' => array(
159 'name' => 'financial_type_id',
160 'title' => ts('Financial Type'),
161 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
162 'options' => CRM_Contribute_PseudoConstant::financialType(),
163 ),
164 'contribution_status_id' => array(
165 'title' => ts('Contribution Status'),
166 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
167 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
168 'default' => array(1),
169 ),
170 ),
171 ),
172 'civicrm_email' => array(
173 'dao' => 'CRM_Core_DAO_Email',
174 'fields' => array(
175 'email' => array(
176 'title' => ts('Email'),
177 'default' => TRUE,
178 'no_repeat' => TRUE,
179 ),
180 ),
181 'grouping' => 'email-fields',
182 ),
183 'civicrm_phone' => array(
184 'dao' => 'CRM_Core_DAO_Phone',
185 'fields' => array(
186 'phone' => array(
187 'title' => ts('Phone'),
188 'default' => TRUE,
189 'no_repeat' => TRUE,
190 ),
191 ),
192 'grouping' => 'phone-fields',
193 ),
194 );
195
196 $this->_groupFilter = TRUE;
197 $this->_tagFilter = TRUE;
198 $this->_currencyColumn = 'civicrm_contribution_currency';
199 parent::__construct();
200 }
201
202 public function preProcess() {
203 parent::preProcess();
204 }
205
206 public function select() {
207 $select = array();
208 $this->_columnHeaders = array();
209 //Headers for Rank column
210 $this->_columnHeaders["civicrm_donor_rank"]['title'] = ts('Rank');
211 $this->_columnHeaders["civicrm_donor_rank"]['type'] = 1;
212 //$select[] ="(@rank:=@rank+1) as civicrm_donor_rank ";
213
214 foreach ($this->_columns as $tableName => $table) {
215 if (array_key_exists('fields', $table)) {
216 foreach ($table['fields'] as $fieldName => $field) {
217 if (!empty($field['required']) ||
218 !empty($this->_params['fields'][$fieldName])
219 ) {
220 // only include statistics columns if set
221 if (!empty($field['statistics'])) {
222 foreach ($field['statistics'] as $stat => $label) {
223 switch (strtolower($stat)) {
224 case 'sum':
225 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
226 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
227 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
228 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
229 break;
230
231 case 'count':
232 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
233 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
234 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
235 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
236 break;
237
238 case 'avg':
239 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
240 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
241 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
242 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
243 break;
244 }
245 }
246 }
247 else {
248 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
249 // $field['type'] is not always set. Use string type as default if not set.
250 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = isset($field['type']) ? $field['type'] : 2;
251 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
252 }
253 }
254 }
255 }
256 }
257
258 $this->_select = " SELECT * FROM ( SELECT " . implode(', ', $select) . " ";
259 }
260
261 /**
262 * @param $fields
263 * @param $files
264 * @param $self
265 *
266 * @return array
267 */
268 public static function formRule($fields, $files, $self) {
269 $errors = array();
270
271 $op = CRM_Utils_Array::value('total_range_op', $fields);
272 $val = CRM_Utils_Array::value('total_range_value', $fields);
273
274 if (!in_array($op, array(
275 'eq',
276 'lte',
277 ))
278 ) {
279 $errors['total_range_op'] = ts("Please select 'Is equal to' OR 'Is Less than or equal to' operator");
280 }
281
282 if ($val && !CRM_Utils_Rule::positiveInteger($val)) {
283 $errors['total_range_value'] = ts("Please enter positive number");
284 }
285 return $errors;
286 }
287
288 public function from() {
289 $this->_from = "
290 FROM civicrm_contact {$this->_aliases['civicrm_contact']} {$this->_aclFrom}
291 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
292 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND {$this->_aliases['civicrm_contribution']}.is_test = 0
293 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
294 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
295 AND {$this->_aliases['civicrm_email']}.is_primary = 1
296 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
297 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
298 {$this->_aliases['civicrm_phone']}.is_primary = 1
299 ";
300 $this->addAddressFromClause();
301 }
302
303 public function where() {
304 $clauses = array();
305 $this->_tempClause = $this->_outerCluase = $this->_groupLimit = '';
306 foreach ($this->_columns as $tableName => $table) {
307 if (array_key_exists('filters', $table)) {
308 foreach ($table['filters'] as $fieldName => $field) {
309 $clause = NULL;
310 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
311 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
312 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
313 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
314
315 if ($relative || $from || $to) {
316 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
317 }
318 }
319 else {
320 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
321 if ($op) {
322 $clause = $this->whereClause($field,
323 $op,
324 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
325 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
326 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
327 );
328 }
329 }
330
331 if (!empty($clause)) {
332 if ($fieldName == 'total_range') {
333 $value = CRM_Utils_Array::value("total_range_value", $this->_params);
334 $this->_outerCluase = " WHERE (( @rows := @rows + 1) <= {$value}) ";
335 $this->_groupLimit = " LIMIT {$value}";
336 }
337 else {
338 $clauses[] = $clause;
339 }
340 }
341 }
342 }
343 }
344 if (empty($clauses)) {
345 $this->_where = "WHERE ( 1 ) ";
346 }
347 else {
348 $this->_where = "WHERE " . implode(' AND ', $clauses);
349 }
350
351 if ($this->_aclWhere) {
352 $this->_where .= " AND {$this->_aclWhere} ";
353 }
354 }
355
356 public function groupBy() {
357 $this->_groupBy = "GROUP BY {$this->_aliases['civicrm_contact']}.id, {$this->_aliases['civicrm_contribution']}.currency";
358 }
359
360 public function postProcess() {
361
362 $this->beginPostProcess();
363
364 // get the acl clauses built before we assemble the query
365 $this->buildACLClause($this->_aliases['civicrm_contact']);
366
367 $this->select();
368
369 $this->from();
370
371 $this->where();
372
373 $this->groupBy();
374
375 $this->limit();
376
377 //set the variable value rank, rows = 0
378 $setVariable = " SET @rows:=0, @rank=0 ";
379 CRM_Core_DAO::singleValueQuery($setVariable);
380
381 $sql = " {$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}
382 ORDER BY civicrm_contribution_total_amount_sum DESC
383 ) as abc {$this->_outerCluase} $this->_limit
384 ";
385
386 $dao = CRM_Core_DAO::executeQuery($sql);
387
388 while ($dao->fetch()) {
389 $row = array();
390 foreach ($this->_columnHeaders as $key => $value) {
391 if (property_exists($dao, $key)) {
392 $row[$key] = $dao->$key;
393 }
394 }
395 $rows[] = $row;
396 }
397 $this->formatDisplay($rows);
398
399 $this->doTemplateAssignment($rows);
400
401 $this->endPostProcess($rows);
402 }
403
404 /**
405 * @param int $groupID
406 */
407 public function add2group($groupID) {
408 if (is_numeric($groupID)) {
409
410 $sql = "
411 {$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}
412 ORDER BY civicrm_contribution_total_amount_sum DESC
413 ) as abc {$this->_groupLimit}";
414 $dao = CRM_Core_DAO::executeQuery($sql);
415
416 $contact_ids = array();
417 // Add resulting contacts to group
418 while ($dao->fetch()) {
419 $contact_ids[$dao->civicrm_contact_id] = $dao->civicrm_contact_id;
420 }
421
422 CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $groupID);
423 CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
424 }
425 }
426
427 /**
428 * @param int $rowCount
429 */
430 public function limit($rowCount = CRM_Report_Form::ROW_COUNT_LIMIT) {
431 // lets do the pager if in html mode
432 $this->_limit = NULL;
433
434 // CRM-14115, over-ride row count if rowCount is specified in URL
435 if ($this->_dashBoardRowCount) {
436 $rowCount = $this->_dashBoardRowCount;
437 }
438 if ($this->_outputMode == 'html' || $this->_outputMode == 'group') {
439 // Replace only first occurrence of SELECT.
440 $this->_select = preg_replace('/SELECT/', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select, 1);
441 $pageId = CRM_Utils_Request::retrieve('crmPID', 'Integer', CRM_Core_DAO::$_nullObject);
442
443 if (!$pageId && !empty($_POST) && isset($_POST['crmPID_B'])) {
444 if (!isset($_POST['PagerBottomButton'])) {
445 unset($_POST['crmPID_B']);
446 }
447 else {
448 $pageId = max((int) @$_POST['crmPID_B'], 1);
449 }
450 }
451
452 $pageId = $pageId ? $pageId : 1;
453 $this->set(CRM_Utils_Pager::PAGE_ID, $pageId);
454 $offset = ($pageId - 1) * $rowCount;
455
456 $offset = CRM_Utils_Type::escape($offset, 'Int');
457 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
458
459 $this->_limit = " LIMIT $offset, " . $rowCount;
460 }
461 }
462
463 /**
464 * Alter display of rows.
465 *
466 * Iterate through the rows retrieved via SQL and make changes for display purposes,
467 * such as rendering contacts as links.
468 *
469 * @param array $rows
470 * Rows generated by SQL, with an array for each row.
471 */
472 public function alterDisplay(&$rows) {
473 $entryFound = FALSE;
474 $rank = 1;
475 if (!empty($rows)) {
476 foreach ($rows as $rowNum => $row) {
477
478 $rows[$rowNum]['civicrm_donor_rank'] = $rank++;
479 // convert display name to links
480 if (array_key_exists('civicrm_contact_display_name', $row) &&
481 array_key_exists('civicrm_contact_id', $row) &&
482 !empty($row['civicrm_contribution_currency'])
483 ) {
484 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
485 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'] .
486 "&currency_value=" . $row['civicrm_contribution_currency'],
487 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
488 );
489 $rows[$rowNum]['civicrm_contact_display_name_link'] = $url;
490 $entryFound = TRUE;
491 }
492 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s)') ? TRUE : $entryFound;
493
494 //handle gender
495 if (array_key_exists('civicrm_contact_gender_id', $row)) {
496 if ($value = $row['civicrm_contact_gender_id']) {
497 $gender = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');
498 $rows[$rowNum]['civicrm_contact_gender_id'] = $gender[$value];
499 }
500 $entryFound = TRUE;
501 }
502
503 // display birthday in the configured custom format
504 if (array_key_exists('civicrm_contact_birth_date', $row)) {
505 $birthDate = $row['civicrm_contact_birth_date'];
506 if ($birthDate) {
507 $rows[$rowNum]['civicrm_contact_birth_date'] = CRM_Utils_Date::customFormat($birthDate, '%Y%m%d');
508 }
509 $entryFound = TRUE;
510 }
511
512 // skip looking further in rows, if first row itself doesn't
513 // have the column we need
514 if (!$entryFound) {
515 break;
516 }
517 }
518 }
519 }
520
521 }