commiting uncommited changes on live site
[weblabels.fsf.org.git] / crm.fsf.org / 20131203 / files / sites / all / modules-new / civicrm / CRM / Report / Form / Contribute / History.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_History extends CRM_Report_Form {
36 // Primary Contacts count limitCONSTROW_COUNT_LIMIT = 10;
37
38 protected $_addressField = FALSE;
39 protected $_emailField = FALSE;
40 protected $_phoneField = FALSE;
41 protected $_relationshipColumns = array();
42
43 protected $_customGroupExtends = array(
44 'Contact',
45 'Individual',
46 'Contribution',
47 );
48
49 protected $_referenceYear = array(
50 'this_year' => '',
51 'other_year' => '',
52 );
53 protected $_yearStatisticsFrom = '';
54
55 protected $_yearStatisticsTo = '';
56
57 /**
58 */
59 public function __construct() {
60 $this->_autoIncludeIndexedFieldsAsOrderBys = 1;
61 $yearsInPast = 4;
62 $date = CRM_Core_SelectValues::date('custom', NULL, $yearsInPast, 0);
63 $count = $date['maxYear'];
64 $optionYear = array('' => ts('- select -'));
65
66 $this->_yearStatisticsFrom = $date['minYear'];
67 $this->_yearStatisticsTo = $date['maxYear'];
68
69 while ($date['minYear'] <= $count) {
70 $optionYear[$date['minYear']] = $date['minYear'];
71 $date['minYear']++;
72 }
73
74 $relationTypeOp = array();
75 $relationshipTypes = CRM_Core_PseudoConstant::relationshipType();
76 foreach ($relationshipTypes as $rid => $rtype) {
77 if ($rtype['label_a_b'] != $rtype['label_b_a']) {
78 $relationTypeOp[$rid] = "{$rtype['label_a_b']}/{$rtype['label_b_a']}";
79 }
80 else {
81 $relationTypeOp[$rid] = $rtype['label_a_b'];
82 }
83 }
84
85 $this->_columns = array(
86 'civicrm_contact' => array(
87 'dao' => 'CRM_Contact_DAO_Contact',
88 'fields' => array(
89 'sort_name' => array(
90 'title' => ts('Contact Name'),
91 'default' => TRUE,
92 'required' => TRUE,
93 'no_repeat' => TRUE,
94 ),
95 'first_name' => array(
96 'title' => ts('First Name'),
97 ),
98 'middle_name' => array(
99 'title' => ts('Middle Name'),
100 ),
101 'last_name' => array(
102 'title' => ts('Last Name'),
103 ),
104 'id' => array(
105 'no_display' => TRUE,
106 'default' => TRUE,
107 'required' => TRUE,
108 ),
109 'gender_id' => array(
110 'title' => ts('Gender'),
111 ),
112 'birth_date' => array(
113 'title' => ts('Birth Date'),
114 ),
115 'age' => array(
116 'title' => ts('Age'),
117 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
118 ),
119 'contact_type' => array(
120 'title' => ts('Contact Type'),
121 ),
122 'contact_sub_type' => array(
123 'title' => ts('Contact Subtype'),
124 ),
125 ),
126 'grouping' => 'contact-fields',
127 'order_bys' => array(
128 'sort_name' => array(
129 'title' => ts('Last Name, First Name'),
130 'default' => '1',
131 'default_weight' => '0',
132 'default_order' => 'ASC',
133 ),
134 'first_name' => array(
135 'name' => 'first_name',
136 'title' => ts('First Name'),
137 ),
138 'gender_id' => array(
139 'name' => 'gender_id',
140 'title' => ts('Gender'),
141 ),
142 'birth_date' => array(
143 'name' => 'birth_date',
144 'title' => ts('Birth Date'),
145 ),
146 'contact_type' => array(
147 'title' => ts('Contact Type'),
148 ),
149 'contact_sub_type' => array(
150 'title' => ts('Contact Subtype'),
151 ),
152 ),
153 'filters' => array(
154 'sort_name' => array('title' => ts('Contact Name')),
155 'id' => array(
156 'title' => ts('Contact ID'),
157 'no_display' => TRUE,
158 ),
159 'gender_id' => array(
160 'title' => ts('Gender'),
161 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
162 'options' => CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'),
163 ),
164 'birth_date' => array(
165 'title' => ts('Birth Date'),
166 'operatorType' => CRM_Report_Form::OP_DATE,
167 ),
168 'contact_type' => array(
169 'title' => ts('Contact Type'),
170 ),
171 'contact_sub_type' => array(
172 'title' => ts('Contact Subtype'),
173 ),
174 ),
175 ),
176 'civicrm_email' => array(
177 'dao' => 'CRM_Core_DAO_Email',
178 'fields' => array(
179 'email' => array(
180 'title' => ts('Email'),
181 'no_repeat' => TRUE,
182 ),
183 ),
184 'grouping' => 'contact-fields',
185 ),
186 'civicrm_phone' => array(
187 'dao' => 'CRM_Core_DAO_Phone',
188 'fields' => array(
189 'phone' => array(
190 'title' => ts('Phone'),
191 'no_repeat' => TRUE,
192 ),
193 ),
194 'grouping' => 'contact-fields',
195 ),
196 ) + $this->addAddressFields(FALSE, FALSE, FALSE, array()) + array(
197 'civicrm_relationship' => array(
198 'dao' => 'CRM_Contact_DAO_Relationship',
199 'fields' => array(
200 'relationship_type_id' => array(
201 'title' => ts('Relationship Type'),
202 'default' => TRUE,
203 ),
204 'contact_id_a' => array('no_display' => TRUE),
205 'contact_id_b' => array('no_display' => TRUE),
206 ),
207 'filters' => array(
208 'relationship_type_id' => array(
209 'title' => ts('Relationship Type'),
210 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
211 'options' => $relationTypeOp,
212 'type' => CRM_Utils_Type::T_STRING,
213 ),
214 ),
215 ),
216 ) + array(
217 'civicrm_contribution' => array(
218 'dao' => 'CRM_Contribute_DAO_Contribution',
219 'fields' => array(
220 'total_amount' => array(
221 'title' => ts('Amount Statistics'),
222 'default' => TRUE,
223 'required' => TRUE,
224 'no_display' => TRUE,
225 'statistics' => array('sum' => ts('Aggregate Amount')),
226 ),
227 'receive_date' => array(
228 'required' => TRUE,
229 'default' => TRUE,
230 'no_display' => TRUE,
231 ),
232 ),
233 'grouping' => 'contri-fields',
234 'filters' => array(
235 'this_year' => array(
236 'title' => ts('This Year'),
237 'operatorType' => CRM_Report_Form::OP_SELECT,
238 'options' => $optionYear,
239 'default' => '',
240 ),
241 'other_year' => array(
242 'title' => ts('Other Years'),
243 'operatorType' => CRM_Report_Form::OP_SELECT,
244 'options' => $optionYear,
245 'default' => '',
246 ),
247 'receive_date' => array('operatorType' => CRM_Report_Form::OP_DATE),
248 'contribution_status_id' => array(
249 'title' => ts('Contribution Status'),
250 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
251 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
252 'default' => array(1),
253 ),
254 'financial_type_id' => array(
255 'title' => ts('Financial Type'),
256 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
257 'options' => CRM_Contribute_PseudoConstant::financialType(),
258 ),
259 'total_amount' => array(
260 'title' => ts('Contribution Amount'),
261 ),
262 'total_sum' => array(
263 'title' => ts('Aggregate Amount'),
264 'type' => CRM_Report_Form::OP_INT,
265 'dbAlias' => 'civicrm_contribution_total_amount_sum',
266 'having' => TRUE,
267 ),
268 ),
269 ),
270 );
271
272 $this->_columns['civicrm_contribution']['fields']['civicrm_upto_' .
273 $this->_yearStatisticsFrom] = array(
274 'title' => ts('Up To %1 Donation', array(1 => $this->_yearStatisticsFrom)),
275 'default' => TRUE,
276 'type' => CRM_Utils_Type::T_MONEY,
277 'is_statistics' => TRUE,
278 );
279
280 $yearConter = $this->_yearStatisticsFrom;
281 $yearConter++;
282 while ($yearConter <= $this->_yearStatisticsTo) {
283 $this->_columns['civicrm_contribution']['fields'][$yearConter] = array(
284 'title' => ts('%1 Donation', array(1 => $yearConter)),
285 'default' => TRUE,
286 'type' => CRM_Utils_Type::T_MONEY,
287 'is_statistics' => TRUE,
288 );
289 $yearConter++;
290 }
291
292 $this->_columns['civicrm_contribution']['fields']['aggregate_amount'] = array(
293 'title' => ts('Aggregate Amount'),
294 'type' => CRM_Utils_Type::T_MONEY,
295 'is_statistics' => TRUE,
296 );
297
298 $this->_groupFilter = TRUE;
299 $this->_tagFilter = TRUE;
300 parent::__construct();
301 }
302
303 public function preProcess() {
304 parent::preProcess();
305 }
306
307 public function select() {
308 $select = array();
309 $this->_columnHeaders = array();
310
311 foreach ($this->_columns as $tableName => $table) {
312 if (array_key_exists('fields', $table)) {
313 foreach ($table['fields'] as $fieldName => $field) {
314
315 if (!empty($field['required']) ||
316 !empty($this->_params['fields'][$fieldName])
317 ) {
318 if ($tableName == 'civicrm_address') {
319 $this->_addressField = TRUE;
320 }
321 if ($tableName == 'civicrm_email') {
322 $this->_emailField = TRUE;
323 }
324 if ($tableName == 'civicrm_phone') {
325 $this->_phoneField = TRUE;
326 }
327 if ($tableName == 'civicrm_relationship') {
328 $this->_relationshipColumns["{$tableName}_{$fieldName}"] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
329 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
330 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
331 continue;
332 }
333
334 if (!empty($field['is_statistics'])) {
335 $this->_columnHeaders[$fieldName]['type'] = $field['type'];
336 $this->_columnHeaders[$fieldName]['title'] = $field['title'];
337 continue;
338 }
339 elseif ($fieldName == 'receive_date') {
340 if ((CRM_Utils_Array::value('this_year_op', $this->_params) ==
341 'fiscal' && !empty($this->_params['this_year_value'])) ||
342 (CRM_Utils_Array::value('other_year_op', $this->_params ==
343 'fiscal') && !empty($this->_params['other_year_value']))
344 ) {
345 $select[] = self::fiscalYearOffset($field['dbAlias']) .
346 " as {$tableName}_{$fieldName}";
347 }
348 else {
349 $select[] = " YEAR(" . $field['dbAlias'] . ")" .
350 " as {$tableName}_{$fieldName}";
351 }
352 }
353 elseif ($fieldName == 'total_amount') {
354 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}";
355 }
356 else {
357 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
358 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
359 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
360 }
361 if (!empty($field['no_display'])) {
362 $this->_columnHeaders["{$tableName}_{$fieldName}"]['no_display'] = TRUE;
363 }
364 }
365 }
366 }
367 }
368
369 $this->_select = "SELECT " . implode(', ', $select) . " ";
370 }
371
372 public function from() {
373 $this->_from = "
374 FROM civicrm_contact {$this->_aliases['civicrm_contact']}
375 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
376 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND
377 {$this->_aliases['civicrm_contribution']}.is_test = 0 ";
378
379 if ($this->_emailField) {
380 $this->_from .= " LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
381 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
382 {$this->_aliases['civicrm_email']}.is_primary = 1) ";
383 }
384
385 if ($this->_phoneField) {
386 $this->_from .= " LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
387 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
388 {$this->_aliases['civicrm_phone']}.is_primary = 1) ";
389 }
390
391 $relContacAlias = 'contact_relationship';
392 $this->_relationshipFrom = " INNER JOIN civicrm_relationship {$this->_aliases['civicrm_relationship']}
393 ON (({$this->_aliases['civicrm_relationship']}.contact_id_a = {$relContacAlias}.id OR {$this->_aliases['civicrm_relationship']}.contact_id_b = {$relContacAlias}.id ) AND {$this->_aliases['civicrm_relationship']}.is_active = 1) ";
394
395 if ($this->_addressField) {
396 $this->_from .= "
397 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
398 ON {$this->_aliases['civicrm_contact']}.id =
399 {$this->_aliases['civicrm_address']}.contact_id AND
400 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
401 }
402 }
403
404 public function where() {
405 $whereClauses = $havingClauses = $relationshipWhere = array();
406 $this->_relationshipWhere = '';
407 $this->_statusClause = '';
408
409 foreach ($this->_columns as $tableName => $table) {
410 if (array_key_exists('filters', $table)) {
411 foreach ($table['filters'] as $fieldName => $field) {
412 $clause = NULL;
413 if ($fieldName == 'this_year' || $fieldName == 'other_year') {
414 continue;
415 }
416 elseif (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE
417 ) {
418 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
419 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
420 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
421
422 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
423 }
424 else {
425 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
426 if ($op) {
427 $clause = $this->whereClause($field,
428 $op,
429 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
430 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
431 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
432 );
433 }
434 }
435
436 if (!empty($clause)) {
437 if ($tableName == 'civicrm_relationship') {
438 $relationshipWhere[] = $clause;
439 continue;
440 }
441
442 if ($fieldName == 'contribution_status_id') {
443 $this->_statusClause = " AND " . $clause;
444 }
445
446 if (!empty($field['having'])) {
447 $havingClauses[] = $clause;
448 }
449 else {
450 $whereClauses[] = $clause;
451 }
452 }
453 }
454 }
455 }
456
457 if (empty($whereClauses)) {
458 $this->_where = "WHERE ( 1 ) ";
459 $this->_having = "";
460 }
461 else {
462 $this->_where = "WHERE " . implode(' AND ', $whereClauses);
463 }
464
465 if ($this->_aclWhere) {
466 $this->_where .= " AND {$this->_aclWhere} ";
467 }
468
469 if (!empty($havingClauses)) {
470 // use this clause to construct group by clause.
471 $this->_having = "HAVING " . implode(' AND ', $havingClauses);
472 }
473
474 if (!empty($relationshipWhere)) {
475 $this->_relationshipWhere = ' AND ' .
476 implode(' AND ', $relationshipWhere);
477 }
478 }
479
480 public function groupBy() {
481 $this->_groupBy = "GROUP BY {$this->_aliases['civicrm_contribution']}.contact_id, YEAR({$this->_aliases['civicrm_contribution']}.receive_date)";
482 }
483
484 /**
485 * Override to set limit to 10.
486 *
487 * @param int $rowCount
488 *
489 * @return array
490 */
491 public function limit($rowCount = self::ROW_COUNT_LIMIT) {
492 return parent::limit($rowCount);
493 }
494
495 /**
496 * Override to set pager with limit is 10.
497 *
498 * @param int $rowCount
499 */
500 public function setPager($rowCount = self::ROW_COUNT_LIMIT) {
501 parent::setPager($rowCount);
502 }
503
504 /**
505 * @param $rows
506 *
507 * @return array
508 */
509 public function statistics(&$rows) {
510 $statistics = parent::statistics($rows);
511 $count = 0;
512 foreach ($rows as $rownum => $row) {
513 if (is_numeric($rownum)) {
514 $count++;
515 }
516 }
517 $statistics['counts']['rowCount'] = array(
518 'title' => ts('Primary Contact(s) Listed'),
519 'value' => $count,
520 );
521
522 if ($this->_rowsFound && ($this->_rowsFound > $count)) {
523 $statistics['counts']['rowsFound'] = array(
524 'title' => ts('Total Primary Contact(s)'),
525 'value' => $this->_rowsFound,
526 );
527 }
528
529 return $statistics;
530 }
531
532 /**
533 * @param $fields
534 * @param $files
535 * @param $self
536 *
537 * @return array
538 */
539 public static function formRule($fields, $files, $self) {
540 $errors = array();
541 if (!empty($fields['this_year_value']) &&
542 !empty($fields['other_year_value']) &&
543 ($fields['this_year_value'] == $fields['other_year_value'])
544 ) {
545 $errors['other_year_value'] = ts("Value for filters 'This Year' and 'Other Years' can not be same.");
546 }
547 return $errors;
548 }
549
550 public function postProcess() {
551 // get ready with post process params
552 $this->beginPostProcess();
553 $this->fixReportParams();
554
555 $this->buildACLClause($this->_aliases['civicrm_contact']);
556 $this->select();
557 $this->where();
558 $this->from();
559 $this->customDataFrom();
560 $this->groupBy();
561
562 $sql = NULL;
563 $rows = array();
564
565 // build array of result based on column headers. This method also allows
566 // modifying column headers before using it to build result set i.e $rows.
567 $this->buildRows($sql, $rows);
568
569 // format result set.
570 $this->formatDisplay($rows, FALSE);
571
572 // assign variables to templates
573 $this->doTemplateAssignment($rows);
574
575 // do print / pdf / instance stuff if needed
576 $this->endPostProcess($rows);
577 }
578
579 public function fixReportParams() {
580 if (!empty($this->_params['this_year_value'])) {
581 $this->_referenceYear['this_year'] = $this->_params['this_year_value'];
582 }
583 if (!empty($this->_params['other_year_value'])) {
584 $this->_referenceYear['other_year'] = $this->_params['other_year_value'];
585 }
586 }
587
588 /**
589 * @param $sql
590 * @param $rows
591 */
592 public function buildRows($sql, &$rows) {
593 $contactIds = array();
594
595 $addWhere = '';
596
597 if (!empty($this->_referenceYear['other_year'])) {
598 (CRM_Utils_Array::value('other_year_op', $this->_params) ==
599 'calendar') ? $other_receive_date = 'YEAR (contri.receive_date)' : $other_receive_date = self::fiscalYearOffset('contri.receive_date');
600 $addWhere .= " AND {$this->_aliases['civicrm_contact']}.id NOT IN ( SELECT DISTINCT cont.id FROM civicrm_contact cont, civicrm_contribution contri WHERE cont.id = contri.contact_id AND {$other_receive_date} = {$this->_referenceYear['other_year']} AND contri.is_test = 0 ) ";
601 }
602 if (!empty($this->_referenceYear['this_year'])) {
603 (CRM_Utils_Array::value('this_year_op', $this->_params) ==
604 'calendar') ? $receive_date = 'YEAR (contri.receive_date)' : $receive_date = self::fiscalYearOffset('contri.receive_date');
605 $addWhere .= " AND {$this->_aliases['civicrm_contact']}.id IN ( SELECT DISTINCT cont.id FROM civicrm_contact cont, civicrm_contribution contri WHERE cont.id = contri.contact_id AND {$receive_date} = {$this->_referenceYear['this_year']} AND contri.is_test = 0 ) ";
606 }
607 $this->limit();
608 $getContacts = "SELECT SQL_CALC_FOUND_ROWS {$this->_aliases['civicrm_contact']}.id as cid, SUM({$this->_aliases['civicrm_contribution']}.total_amount) as civicrm_contribution_total_amount_sum {$this->_from} {$this->_where} {$addWhere} GROUP BY {$this->_aliases['civicrm_contact']}.id {$this->_having} {$this->_limit}";
609
610 $dao = CRM_Core_DAO::executeQuery($getContacts);
611
612 while ($dao->fetch()) {
613 $contactIds[] = $dao->cid;
614 }
615 $dao->free();
616 $this->setPager();
617
618 $relationshipRows = array();
619 if (empty($contactIds)) {
620 return;
621 }
622
623 $primaryContributions = $this->buildContributionRows($contactIds);
624
625 list($relationshipRows, $relatedContactIds) = $this->buildRelationshipRows($contactIds);
626
627 if (empty($relatedContactIds)) {
628 $rows = $primaryContributions;
629 return;
630 }
631
632 $relatedContributions = $this->buildContributionRows($relatedContactIds);
633
634 $summaryYears = array();
635 $summaryYears[] = "civicrm_upto_{$this->_yearStatisticsFrom}";
636 $yearConter = $this->_yearStatisticsFrom;
637 $yearConter++;
638 while ($yearConter <= $this->_yearStatisticsTo) {
639 $summaryYears[] = $yearConter;
640 $yearConter++;
641 }
642 $summaryYears[] = 'aggregate_amount';
643
644 foreach ($primaryContributions as $cid => $primaryRow) {
645 $row = $primaryRow;
646 if (!isset($relationshipRows[$cid])) {
647 $rows[$cid] = $row;
648 continue;
649 }
650 $total = array();
651 $total['civicrm_contact_sort_name'] = ts('Total');
652 foreach ($summaryYears as $year) {
653 $total[$year] = CRM_Utils_Array::value($year, $primaryRow, 0);
654 }
655
656 $relatedContact = FALSE;
657 $rows[$cid] = $row;
658 foreach ($relationshipRows[$cid] as $relcid => $relRow) {
659 if (!isset($relatedContributions[$relcid])) {
660 continue;
661 }
662 $relatedContact = TRUE;
663 $relatedRow = $relatedContributions[$relcid];
664 foreach ($summaryYears as $year) {
665 $total[$year] += CRM_Utils_Array::value($year, $relatedRow, 0);
666 }
667
668 foreach (array_keys($this->_relationshipColumns) as $col) {
669 if (!empty($relRow[$col])) {
670 $relatedRow[$col] = $relRow[$col];
671 }
672 }
673 $rows["{$cid}_{$relcid}"] = $relatedRow;
674 }
675 if ($relatedContact) {
676 $rows["{$cid}_total"] = $total;
677 $rows["{$cid}_bank"] = array('civicrm_contact_sort_name' => '&nbsp;');
678 }
679 }
680 }
681
682 /**
683 * @param $contactIds
684 *
685 * @return array
686 */
687 public function buildContributionRows($contactIds) {
688 $rows = array();
689 if (empty($contactIds)) {
690 return $rows;
691 }
692
693 $sqlContribution = "{$this->_select} {$this->_from} WHERE {$this->_aliases['civicrm_contact']}.id IN (" .
694 implode(',', $contactIds) .
695 ") AND {$this->_aliases['civicrm_contribution']}.is_test = 0 {$this->_statusClause} {$this->_groupBy} ";
696
697 $dao = CRM_Core_DAO::executeQuery($sqlContribution);
698 $contributionSum = 0;
699 $yearcal = array();
700 while ($dao->fetch()) {
701 if (!$dao->civicrm_contact_id) {
702 continue;
703 }
704
705 foreach ($this->_columnHeaders as $key => $value) {
706 if (property_exists($dao, $key)) {
707 $rows[$dao->civicrm_contact_id][$key] = $dao->$key;
708 }
709 }
710 if ($dao->civicrm_contribution_receive_date) {
711 if ($dao->civicrm_contribution_receive_date >
712 $this->_yearStatisticsFrom
713 ) {
714 $rows[$dao->civicrm_contact_id][$dao->civicrm_contribution_receive_date] = $dao->civicrm_contribution_total_amount;
715 }
716 else {
717 if (!isset($rows[$dao->civicrm_contact_id]["civicrm_upto_{$this->_yearStatisticsFrom}"])) {
718 $rows[$dao->civicrm_contact_id]["civicrm_upto_{$this->_yearStatisticsFrom}"] = 0;
719 }
720
721 $rows[$dao->civicrm_contact_id]["civicrm_upto_{$this->_yearStatisticsFrom}"] += $dao->civicrm_contribution_total_amount;
722 }
723 }
724
725 if (!isset($rows[$dao->civicrm_contact_id]['aggregate_amount'])) {
726 $rows[$dao->civicrm_contact_id]['aggregate_amount'] = 0;
727 }
728 $rows[$dao->civicrm_contact_id]['aggregate_amount'] += $dao->civicrm_contribution_total_amount;
729 }
730 $dao->free();
731 return $rows;
732 }
733
734 /**
735 * @param $contactIds
736 *
737 * @return array
738 */
739 public function buildRelationshipRows($contactIds) {
740 $relationshipRows = $relatedContactIds = array();
741 if (empty($contactIds)) {
742 return array($relationshipRows, $relatedContactIds);
743 }
744
745 $relContactAlias = 'contact_relationship';
746 $addRelSelect = '';
747 if (!empty($this->_relationshipColumns)) {
748 $addRelSelect = ', ' . implode(', ', $this->_relationshipColumns);
749 }
750 $sqlRelationship = "SELECT {$this->_aliases['civicrm_relationship']}.relationship_type_id as relationship_type_id, {$this->_aliases['civicrm_relationship']}.contact_id_a as contact_id_a, {$this->_aliases['civicrm_relationship']}.contact_id_b as contact_id_b {$addRelSelect} FROM civicrm_contact {$relContactAlias} {$this->_relationshipFrom} WHERE {$relContactAlias}.id IN (" .
751 implode(',', $contactIds) .
752 ") AND {$this->_aliases['civicrm_relationship']}.is_active = 1 {$this->_relationshipWhere} GROUP BY {$this->_aliases['civicrm_relationship']}.contact_id_a, {$this->_aliases['civicrm_relationship']}.contact_id_b";
753 $relationshipTypes = CRM_Core_PseudoConstant::relationshipType();
754
755 $dao = CRM_Core_DAO::executeQuery($sqlRelationship);
756 while ($dao->fetch()) {
757 $row = array();
758 foreach (array_keys($this->_relationshipColumns) as $rel_column) {
759 $row[$rel_column] = $dao->$rel_column;
760 }
761 if (in_array($dao->contact_id_a, $contactIds)) {
762 $row['civicrm_relationship_relationship_type_id'] = $relationshipTypes[$dao->relationship_type_id]['label_a_b'];
763 $row['civicrm_relationship_contact_id'] = $dao->contact_id_b;
764 $relationshipRows[$dao->contact_id_a][$dao->contact_id_b] = $row;
765 $relatedContactIds[$dao->contact_id_b] = $dao->contact_id_b;
766 }
767 if (in_array($dao->contact_id_b, $contactIds)) {
768 $row['civicrm_relationship_contact_id'] = $dao->contact_id_a;
769 $row['civicrm_relationship_relationship_type_id'] = $relationshipTypes[$dao->relationship_type_id]['label_b_a'];
770 $relationshipRows[$dao->contact_id_b][$dao->contact_id_a] = $row;
771 $relatedContactIds[$dao->contact_id_a] = $dao->contact_id_a;
772 }
773 }
774 $dao->free();
775 return array($relationshipRows, $relatedContactIds);
776 }
777
778 /**
779 * Override "This Year" $op options
780 * @param string $type
781 * @param null $fieldName
782 *
783 * @return array
784 */
785 public function getOperationPair($type = "string", $fieldName = NULL) {
786 if ($fieldName == 'this_year' || $fieldName == 'other_year') {
787 return array(
788 'calendar' => ts('Is Calendar Year'),
789 'fiscal' => ts('Fiscal Year Starting'),
790 );
791 }
792 return parent::getOperationPair($type, $fieldName);
793 }
794
795 /**
796 * Alter display of rows.
797 *
798 * Iterate through the rows retrieved via SQL and make changes for display purposes,
799 * such as rendering contacts as links.
800 *
801 * @param array $rows
802 * Rows generated by SQL, with an array for each row.
803 */
804 public function alterDisplay(&$rows) {
805 if (empty($rows)) {
806 return;
807 }
808
809 $last_primary = NULL;
810 foreach ($rows as $rowNum => $row) {
811 //handle gender
812 if (array_key_exists('civicrm_contact_gender_id', $row)) {
813 if ($value = $row['civicrm_contact_gender_id']) {
814 $gender = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');
815 $row['civicrm_contact_gender_id'] = $rows[$rowNum]['civicrm_contact_gender_id'] = $gender[$value];
816 }
817 $entryFound = TRUE;
818 }
819
820 // Highlight primary contact and amount row
821 if (is_numeric($rowNum) ||
822 ($last_primary && ($rowNum == "{$last_primary}_total"))
823 ) {
824 if (is_numeric($rowNum)) {
825 $last_primary = $rowNum;
826 }
827 foreach ($row as $key => $value) {
828 if ($key == 'civicrm_contact_id') {
829 continue;
830 }
831 if (empty($value)) {
832 $row[$key] = '';
833 continue;
834 }
835
836 if ($last_primary && ($rowNum == "{$last_primary}_total")) {
837 $value = CRM_Utils_Money::format($value, ' ');
838 }
839 $row[$key] = '<strong>' . $value . '</strong>';
840 }
841 $rows[$rowNum] = $row;
842 }
843
844 // Convert Display name into link
845 if (!empty($row['civicrm_contact_sort_name']) &&
846 !empty($row['civicrm_contact_id'])
847 ) {
848 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
849 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'],
850 $this->_absoluteUrl, $this->_id
851 );
852 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
853 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contribution Details for this Contact.");
854 }
855
856 // display birthday in the configured custom format
857 if (array_key_exists('civicrm_contact_birth_date', $row)) {
858 $birthDate = $row['civicrm_contact_birth_date'];
859 if ($birthDate) {
860 $rows[$rowNum]['civicrm_contact_birth_date'] = CRM_Utils_Date::customFormat($birthDate, '%Y%m%d');
861 }
862 $entryFound = TRUE;
863 }
864
865 }
866 }
867
868 }