Merge pull request #8694 from eileenmcnaughton/unhurt-my-server
[civicrm-core.git] / CRM / Report / Form / Contribute / OrganizationSummary.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
32 * $Id$
33 *
34 */
35 class CRM_Report_Form_Contribute_OrganizationSummary extends CRM_Report_Form {
36
37 protected $_addressField = FALSE;
38
39 protected $_emailField = FALSE;
40
41 public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
42
43 protected $_summary = NULL;
44
45 /**
46 * Organisation contact ie. 'contact_id_b' or 'contact_id_a'
47 * @var string
48 */
49 protected $orgContact;
50
51 /**
52 * Related Contact ie. 'contact_id_b' or 'contact_id_a'
53 * @var string
54 */
55 protected $otherContact;
56
57 /**
58 */
59 /**
60 */
61 public function __construct() {
62 self::validRelationships();
63 $config = CRM_Core_Config::singleton();
64 $campaignEnabled = in_array('CiviCampaign', $config->enableComponents);
65 if ($campaignEnabled) {
66 $getCampaigns = CRM_Campaign_BAO_Campaign::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
67 $this->activeCampaigns = $getCampaigns['campaigns'];
68 asort($this->activeCampaigns);
69 }
70
71 $this->_columns = array(
72 'civicrm_contact_organization' => array(
73 'dao' => 'CRM_Contact_DAO_Contact',
74 'fields' => array(
75 'organization_name' => array(
76 'title' => ts('Organization Name'),
77 'required' => TRUE,
78 'no_repeat' => TRUE,
79 ),
80 'id' => array(
81 'no_display' => TRUE,
82 'required' => TRUE,
83 ),
84 'contact_type' => array(
85 'title' => ts('Contact Type'),
86 ),
87 'contact_sub_type' => array(
88 'title' => ts('Contact Subtype'),
89 ),
90 ),
91 'filters' => array(
92 'organization_name' => array('title' => ts('Organization Name')),
93 ),
94 'grouping' => 'organization-fields',
95 ),
96 'civicrm_line_item' => array(
97 'dao' => 'CRM_Price_DAO_LineItem',
98 ),
99 'civicrm_relationship' => array(
100 'dao' => 'CRM_Contact_DAO_Relationship',
101 'fields' => array(
102 'relationship_type_id' => array(
103 'title' => ts('Relationship Type'),
104 ),
105 ),
106 'filters' => array(
107 'relationship_type_id' => array(
108 'title' => ts('Relationship Type'),
109 'type' => CRM_Utils_Type::T_INT,
110 'operatorType' => CRM_Report_Form::OP_SELECT,
111 'options' => $this->relationTypes,
112 'default' => key($this->relationTypes),
113 ),
114 ),
115 'grouping' => 'organization-fields',
116 ),
117 'civicrm_contact' => array(
118 'dao' => 'CRM_Contact_DAO_Contact',
119 'fields' => array(
120 'sort_name' => array(
121 'title' => ts('Contact Name'),
122 'required' => TRUE,
123 ),
124 'id' => array(
125 'no_display' => TRUE,
126 'required' => TRUE,
127 ),
128 ),
129 'grouping' => 'contact-fields',
130 ),
131 'civicrm_contribution' => array(
132 'dao' => 'CRM_Contribute_DAO_Contribution',
133 'fields' => array(
134 'total_amount' => array(
135 'title' => ts('Amount'),
136 'required' => TRUE,
137 ),
138 'id' => array(
139 'no_display' => TRUE,
140 'required' => TRUE,
141 ),
142 'contribution_status_id' => array(
143 'title' => ts('Contribution Status'),
144 'default' => TRUE,
145 ),
146 'check_number' => array(
147 'title' => ts('Check Number'),
148 ),
149 'currency' => array(
150 'required' => TRUE,
151 'no_display' => TRUE,
152 ),
153 'trxn_id' => NULL,
154 'receive_date' => array('default' => TRUE),
155 'receipt_date' => NULL,
156 ),
157 'filters' => array(
158 'receive_date' => array('operatorType' => CRM_Report_Form::OP_DATE),
159 'total_amount' => array('title' => ts('Amount Between')),
160 'currency' => array(
161 'title' => ts('Currency'),
162 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
163 'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
164 'default' => NULL,
165 'type' => CRM_Utils_Type::T_STRING,
166 ),
167 'contribution_status_id' => array(
168 'title' => ts('Contribution Status'),
169 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
170 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
171 'default' => array(1),
172 ),
173 ),
174 'grouping' => 'contri-fields',
175 ),
176 'civicrm_address' => array(
177 'dao' => 'CRM_Core_DAO_Address',
178 'fields' => array(
179 'street_address' => NULL,
180 'city' => NULL,
181 'postal_code' => NULL,
182 'state_province_id' => array(
183 'title' => ts('State/Province'),
184 ),
185 'country_id' => array(
186 'title' => ts('Country'),
187 ),
188 ),
189 'grouping' => 'contact-fields',
190 ),
191 'civicrm_email' => array(
192 'dao' => 'CRM_Core_DAO_Email',
193 'fields' => array('email' => NULL),
194 'grouping' => 'contact-fields',
195 ),
196 );
197
198 if ($campaignEnabled && !empty($this->activeCampaigns)) {
199 $this->_columns['civicrm_contribution']['fields']['campaign_id'] = array(
200 'title' => ts('Campaign'),
201 'default' => 'false',
202 );
203 $this->_columns['civicrm_contribution']['filters']['campaign_id'] = array(
204 'title' => ts('Campaign'),
205 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
206 'options' => $this->activeCampaigns,
207 'type' => CRM_Utils_Type::T_INT,
208 );
209 }
210
211 $this->_currencyColumn = 'civicrm_contribution_currency';
212 parent::__construct();
213 }
214
215 public function preProcess() {
216 parent::preProcess();
217 }
218
219 public function select() {
220 $this->_columnHeaders = $select = array();
221 foreach ($this->_columns as $tableName => $table) {
222 if (array_key_exists('fields', $table)) {
223 foreach ($table['fields'] as $fieldName => $field) {
224 if (!empty($field['required']) || !empty($this->_params['fields'][$fieldName])) {
225 if ($tableName == 'civicrm_address') {
226 $this->_addressField = TRUE;
227 }
228 elseif ($tableName == 'civicrm_email') {
229 $this->_emailField = TRUE;
230 }
231
232 if (!empty($field['statistics'])) {
233 foreach ($field['statistics'] as $stat => $label) {
234 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}_{$stat}";
235 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
236 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
237 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
238 }
239 }
240 else {
241 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
242
243 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
244 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
245 }
246 }
247 }
248 }
249 }
250 $this->_selectClauses = $select;
251 $this->_select = "SELECT " . implode(', ', $select) . " ";
252 }
253
254 public function from() {
255
256 $this->_from = NULL;
257 $this->_from = "
258 FROM civicrm_relationship {$this->_aliases['civicrm_relationship']}
259 LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact_organization']} ON
260 ({$this->_aliases['civicrm_contact_organization']}.id = {$this->_aliases['civicrm_relationship']}.$this->orgContact AND {$this->_aliases['civicrm_contact_organization']}.contact_type='Organization')
261 LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact']} ON
262 ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_relationship']}.$this->otherContact )
263 {$this->_aclFrom}
264 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']} ON
265 ({$this->_aliases['civicrm_contribution']}.contact_id = {$this->_aliases['civicrm_relationship']}.$this->otherContact ) AND {$this->_aliases['civicrm_contribution']}.is_test = 0 ";
266
267 if ($this->_addressField) {
268 $this->_from .= "
269 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']} ON
270 {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id AND
271 {$this->_aliases['civicrm_address']}.is_primary = 1\n ";
272 }
273 if ($this->_emailField) {
274 $this->_from .= "
275 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']} ON
276 {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
277 {$this->_aliases['civicrm_email']}.is_primary = 1\n ";
278 }
279 }
280
281 public function where() {
282 $clauses = array();
283 foreach ($this->_columns as $tableName => $table) {
284 if (array_key_exists('filters', $table)) {
285 foreach ($table['filters'] as $fieldName => $field) {
286 $clause = NULL;
287 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
288 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
289 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
290 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
291
292 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
293 }
294 else {
295 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
296 if ($op) {
297 if ($fieldName == 'relationship_type_id') {
298 $clause = "{$this->_aliases['civicrm_relationship']}.relationship_type_id=" . $this->relationshipId;
299 }
300 else {
301 $clause = $this->whereClause($field,
302 $op,
303 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
304 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
305 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
306 );
307 }
308 }
309 }
310
311 if (!empty($clause)) {
312 $clauses[] = $clause;
313 }
314 }
315 }
316 }
317
318 if (empty($clauses)) {
319 $this->_where = "WHERE ( 1 )";
320 }
321 else {
322 $this->_where = "WHERE " . implode(' AND ', $clauses);
323 }
324
325 if ($this->_aclWhere) {
326 $this->_where .= " AND {$this->_aclWhere} ";
327 }
328 }
329
330 public function groupBy() {
331 $groupBy = array(
332 "{$this->_aliases['civicrm_relationship']}.$this->orgContact",
333 "{$this->_aliases['civicrm_relationship']}.$this->otherContact",
334 "{$this->_aliases['civicrm_contribution']}.id",
335 "{$this->_aliases['civicrm_relationship']}.relationship_type_id",
336 );
337 $this->_groupBy = CRM_Contact_BAO_Query::getGroupByFromSelectColumns($this->_selectClauses, $groupBy);
338 }
339
340 public function orderBy() {
341 $this->_orderBy = " ORDER BY {$this->_aliases['civicrm_contact_organization']}.organization_name, {$this->_aliases['civicrm_relationship']}.$this->orgContact, {$this->_aliases['civicrm_contact']}.sort_name, {$this->_aliases['civicrm_relationship']}.$this->otherContact";
342 }
343
344 /**
345 * @param $rows
346 *
347 * @return array
348 */
349 public function statistics(&$rows) {
350 $statistics = parent::statistics($rows);
351
352 //hack filter display for relationship type
353 $type = substr($this->_params['relationship_type_id_value'], -3);
354 foreach ($statistics['filters'] as $id => $value) {
355 if ($value['title'] == 'Relationship Type' && !empty($id)) {
356 $statistics['filters'][$id]['value'] = 'Is equal to ' .
357 $this->relationTypes[$this->relationshipId . '_' . $type];
358 }
359 }
360 return $statistics;
361 }
362
363 public function postProcess() {
364 $this->beginPostProcess();
365 $this->buildACLClause(array($this->_aliases['civicrm_contact'], $this->_aliases['civicrm_contact_organization']));
366 $sql = $this->buildQuery(TRUE);
367 $rows = array();
368 $this->buildRows($sql, $rows);
369 $this->formatDisplay($rows);
370 $this->doTemplateAssignment($rows);
371 $this->endPostProcess($rows);
372 }
373
374 /**
375 * Set variables to be accessed by API and form layer in processing.
376 */
377 public function beginPostProcessCommon() {
378 $getRelationship = $this->_params['relationship_type_id_value'];
379 $type = substr($getRelationship, -3);
380 $this->relationshipId = intval((substr($getRelationship, 0, strpos($getRelationship, '_'))));
381 if ($type == 'b_a') {
382 $this->orgContact = 'contact_id_b';
383 $this->otherContact = 'contact_id_a';
384 }
385 else {
386 $this->orgContact = 'contact_id_a';
387 $this->otherContact = 'contact_id_b';
388 }
389 }
390
391 public function validRelationships() {
392 $this->relationTypes = $relationTypes = array();
393
394 $params = array('contact_type_b' => 'Organization', 'version' => 3);
395 $typesA = civicrm_api('relationship_type', 'get', $params);
396
397 if (empty($typesA['is_error'])) {
398 foreach ($typesA['values'] as $rel) {
399 $relationTypes[$rel['id']][$rel['id'] . '_b_a'] = $rel['label_b_a'];
400 }
401 }
402
403 $params = array('contact_type_a' => 'Organization', 'version' => 3);
404 $typesB = civicrm_api('relationship_type', 'get', $params);
405
406 if (empty($typesB['is_error'])) {
407 foreach ($typesB['values'] as $rel) {
408 $relationTypes[$rel['id']][$rel['id'] . '_a_b'] = $rel['label_a_b'];
409 }
410 }
411
412 ksort($relationTypes);
413 foreach ($relationTypes as $relationship) {
414 foreach ($relationship as $index => $label) {
415 $this->relationTypes[$index] = $label;
416 }
417 }
418 }
419
420 /**
421 * Alter display of rows.
422 *
423 * Iterate through the rows retrieved via SQL and make changes for display purposes,
424 * such as rendering contacts as links.
425 *
426 * @param array $rows
427 * Rows generated by SQL, with an array for each row.
428 */
429 public function alterDisplay(&$rows) {
430 $type = substr($this->_params['relationship_type_id_value'], -3);
431
432 $entryFound = FALSE;
433 $flagOrganization = $flagContact = 0;
434
435 foreach ($rows as $rowNum => $row) {
436
437 //replace retionship id by relationship name
438 if (array_key_exists('civicrm_relationship_relationship_type_id', $row)) {
439 if ($value = $row['civicrm_relationship_relationship_type_id']) {
440 $rows[$rowNum]['civicrm_relationship_relationship_type_id'] = $this->relationTypes[$value . '_' . $type];
441 $entryFound = TRUE;
442 }
443 }
444
445 //remove duplicate Organization names
446 if (array_key_exists('civicrm_contact_organization_id', $row) && $this->_outputMode != 'csv') {
447 if ($value = $row['civicrm_contact_organization_id']) {
448 if ($rowNum == 0) {
449 $previousOrganization = $value;
450 }
451 else {
452 if ($previousOrganization == $value) {
453 $flagOrganization = 1;
454 $previousOrganization = $value;
455 }
456 else {
457 $flagOrganization = 0;
458 $previousOrganization = $value;
459 }
460 }
461
462 if ($flagOrganization == 1) {
463 foreach ($row as $colName => $colVal) {
464 if (in_array($colName, $this->_noRepeats)) {
465 unset($rows[$rowNum][$colName]);
466 }
467 }
468 }
469 $entryFound = TRUE;
470 }
471 }
472
473 // convert Organization display name to links
474 if (array_key_exists('civicrm_contact_organization_organization_name', $row) && !empty($rows[$rowNum]['civicrm_contact_organization_organization_name']) &&
475 array_key_exists('civicrm_contact_organization_id', $row)
476 ) {
477 $url = CRM_Utils_System::url('civicrm/contact/view',
478 'reset=1&cid=' .
479 $rows[$rowNum]['civicrm_contact_organization_id'],
480 $this->_absoluteUrl
481 );
482
483 $rows[$rowNum]['civicrm_contact_organization_organization_name_link'] = $url;
484 $rows[$rowNum]['civicrm_contact_organization_organization_name_hover'] = ts('View contact summary for this organization.');
485 }
486
487 //remove duplicate Contact names and relationship type
488 if (array_key_exists('civicrm_contact_id', $row) && $this->_outputMode != 'csv') {
489 if ($value = $row['civicrm_contact_id']) {
490 if ($rowNum == 0) {
491 $previousContact = $value;
492 }
493 else {
494 if ($previousContact == $value) {
495 $flagContact = 1;
496 $previousContact = $value;
497 }
498 else {
499 $flagContact = 0;
500 $previousContact = $value;
501 }
502 }
503
504 if ($flagContact == 1 && $flagOrganization == 1) {
505 $rows[$rowNum]['civicrm_contact_sort_name'] = "";
506 $rows[$rowNum]['civicrm_relationship_relationship_type_id'] = "";
507 }
508
509 $entryFound = TRUE;
510 }
511 }
512
513 if (array_key_exists('civicrm_contribution_contribution_status_id', $row)) {
514 if ($value = $row['civicrm_contribution_contribution_status_id']) {
515 $rows[$rowNum]['civicrm_contribution_contribution_status_id'] = CRM_Contribute_PseudoConstant::contributionStatus($value);
516 }
517 }
518
519 // handle state province
520 if (array_key_exists('civicrm_address_state_province_id', $row)) {
521 if ($value = $row['civicrm_address_state_province_id']) {
522 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value, FALSE);
523 }
524 $entryFound = TRUE;
525 }
526
527 // handle country
528 if (array_key_exists('civicrm_address_country_id', $row)) {
529 if ($value = $row['civicrm_address_country_id']) {
530 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE);
531 }
532 $entryFound = TRUE;
533 }
534
535 // convert Individual display name to links
536 if (array_key_exists('civicrm_contact_sort_name', $row) &&
537 $rows[$rowNum]['civicrm_contact_sort_name'] &&
538 array_key_exists('civicrm_contact_id', $row)
539 ) {
540 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
541 'reset=1&force=1&id_op=eq&id_value=' .
542 $row['civicrm_contact_id'],
543 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
544 );
545 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
546 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts('View contribution details for this individual');
547
548 $entryFound = TRUE;
549 }
550
551 // Contribution amount links to view contribution
552 if (($value = CRM_Utils_Array::value('civicrm_contribution_total_amount', $row)) &&
553 CRM_Core_Permission::check('access CiviContribute')
554 ) {
555 $url = CRM_Utils_System::url('civicrm/contact/view/contribution',
556 "reset=1&id=" . $row['civicrm_contribution_id'] . "&cid=" . $row['civicrm_contact_id'] .
557 "&action=view&context=contribution&selectedChild=contribute",
558 $this->_absoluteUrl
559 );
560 $rows[$rowNum]['civicrm_contribution_total_amount_link'] = $url;
561 $rows[$rowNum]['civicrm_contribution_total_amount_hover'] = ts('View this contribution.');
562 $entryFound = TRUE;
563 }
564
565 // convert campaign_id to campaign title
566 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
567 if ($value = $row['civicrm_contribution_campaign_id']) {
568 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value];
569 $entryFound = TRUE;
570 }
571 }
572
573 // skip looking further in rows, if first row itself doesn't
574 if (!$entryFound) {
575 break;
576 }
577 $lastKey = $rowNum;
578 }
579 }
580
581 }