| 1 | <?php |
| 2 | /* |
| 3 | +--------------------------------------------------------------------+ |
| 4 | | Copyright CiviCRM LLC. All rights reserved. | |
| 5 | | | |
| 6 | | This work is published under the GNU AGPLv3 license with some | |
| 7 | | permitted exceptions and without any warranty. For full license | |
| 8 | | and copyright information, see https://civicrm.org/licensing | |
| 9 | +--------------------------------------------------------------------+ |
| 10 | */ |
| 11 | |
| 12 | /** |
| 13 | * Class CRM_Report_Form |
| 14 | */ |
| 15 | class CRM_Report_Form extends CRM_Core_Form { |
| 16 | /** |
| 17 | * Variables smarty expects to have set. |
| 18 | * |
| 19 | * We ensure these are assigned (value = NULL) when Smarty is instantiated in |
| 20 | * order to avoid e-notices / having to use empty or isset in the template layer. |
| 21 | * |
| 22 | * @var string[] |
| 23 | */ |
| 24 | public $expectedSmartyVariables = ['pager', 'skip', 'sections', 'grandStat']; |
| 25 | |
| 26 | /** |
| 27 | * Deprecated constant, Reports should be updated to use the getRowCount function. |
| 28 | */ |
| 29 | const ROW_COUNT_LIMIT = 50; |
| 30 | |
| 31 | /** |
| 32 | * Operator types - used for displaying filter elements |
| 33 | */ |
| 34 | const |
| 35 | OP_INT = 1, |
| 36 | OP_STRING = 2, |
| 37 | OP_DATE = 4, |
| 38 | OP_DATETIME = 5, |
| 39 | OP_FLOAT = 8, |
| 40 | OP_SELECT = 64, |
| 41 | OP_MULTISELECT = 65, |
| 42 | OP_MULTISELECT_SEPARATOR = 66, |
| 43 | OP_MONTH = 128, |
| 44 | OP_ENTITYREF = 256; |
| 45 | |
| 46 | /** |
| 47 | * The id of the report instance |
| 48 | * |
| 49 | * @var int |
| 50 | */ |
| 51 | protected $_id; |
| 52 | |
| 53 | /** |
| 54 | * The Number of rows to display on screen |
| 55 | * @var int |
| 56 | */ |
| 57 | protected $_rowCount; |
| 58 | |
| 59 | /** |
| 60 | * The id of the report template |
| 61 | * |
| 62 | * @var int |
| 63 | */ |
| 64 | protected $_templateID; |
| 65 | |
| 66 | /** |
| 67 | * The report title |
| 68 | * |
| 69 | * @var string |
| 70 | */ |
| 71 | protected $_title; |
| 72 | protected $_noFields = FALSE; |
| 73 | |
| 74 | /** |
| 75 | * The set of all columns in the report. An associative array |
| 76 | * with column name as the key and attributes as the value |
| 77 | * |
| 78 | * @var array |
| 79 | */ |
| 80 | protected $_columns = []; |
| 81 | |
| 82 | /** |
| 83 | * The set of filters in the report |
| 84 | * |
| 85 | * @var array |
| 86 | */ |
| 87 | protected $_filters = []; |
| 88 | |
| 89 | /** |
| 90 | * The set of optional columns in the report |
| 91 | * |
| 92 | * @var array |
| 93 | */ |
| 94 | public $_options = []; |
| 95 | |
| 96 | /** |
| 97 | * By default most reports hide contact id. |
| 98 | * Setting this to true makes it available |
| 99 | * @var bool |
| 100 | */ |
| 101 | protected $_exposeContactID = TRUE; |
| 102 | |
| 103 | /** |
| 104 | * Set of statistic fields |
| 105 | * |
| 106 | * @var array |
| 107 | */ |
| 108 | protected $_statFields = []; |
| 109 | |
| 110 | /** |
| 111 | * Set of statistics data |
| 112 | * |
| 113 | * @var array |
| 114 | */ |
| 115 | protected $_statistics = []; |
| 116 | |
| 117 | /** |
| 118 | * List of fields not to be repeated during display |
| 119 | * |
| 120 | * @var array |
| 121 | */ |
| 122 | protected $_noRepeats = []; |
| 123 | |
| 124 | /** |
| 125 | * List of fields not to be displayed |
| 126 | * |
| 127 | * @var array |
| 128 | */ |
| 129 | protected $_noDisplay = []; |
| 130 | |
| 131 | /** |
| 132 | * Object type that a custom group extends |
| 133 | * |
| 134 | * @var null |
| 135 | */ |
| 136 | protected $_customGroupExtends = NULL; |
| 137 | protected $_customGroupExtendsJoin = []; |
| 138 | protected $_customGroupFilters = TRUE; |
| 139 | protected $_customGroupGroupBy = FALSE; |
| 140 | protected $_customGroupJoin = 'LEFT JOIN'; |
| 141 | |
| 142 | /** |
| 143 | * Build tags filter |
| 144 | * @var bool |
| 145 | */ |
| 146 | protected $_tagFilter = FALSE; |
| 147 | |
| 148 | /** |
| 149 | * specify entity table for tags filter |
| 150 | * @var string |
| 151 | */ |
| 152 | protected $_tagFilterTable = 'civicrm_contact'; |
| 153 | |
| 154 | /** |
| 155 | * Build groups filter. |
| 156 | * |
| 157 | * @var bool |
| 158 | */ |
| 159 | protected $_groupFilter = FALSE; |
| 160 | |
| 161 | /** |
| 162 | * Has the report been optimised for group filtering. |
| 163 | * |
| 164 | * The functionality for group filtering has been improved but not |
| 165 | * all reports have been adjusted to take care of it. |
| 166 | * |
| 167 | * This property exists to highlight the reports which are still using the |
| 168 | * slow method & allow group filtering to still work for them until they |
| 169 | * can be migrated. |
| 170 | * |
| 171 | * In order to protect extensions we have to default to TRUE - but I have |
| 172 | * separately marked every class with a groupFilter in the hope that will trigger |
| 173 | * people to fix them as they touch them. |
| 174 | * |
| 175 | * @var bool |
| 176 | * @see https://issues.civicrm.org/jira/browse/CRM-19170 |
| 177 | */ |
| 178 | protected $groupFilterNotOptimised = TRUE; |
| 179 | |
| 180 | /** |
| 181 | * Navigation fields |
| 182 | * |
| 183 | * @var array |
| 184 | */ |
| 185 | public $_navigation = []; |
| 186 | |
| 187 | public $_drilldownReport = []; |
| 188 | |
| 189 | /** |
| 190 | * Array of tabs to display on report. |
| 191 | * |
| 192 | * E.g we define the tab title, the tpl and the tab-specific part of the css or html link. |
| 193 | * |
| 194 | * $this->tabs['OrderBy'] = array( |
| 195 | * 'title' => ts('Sorting'), |
| 196 | * 'tpl' => 'OrderBy', |
| 197 | * 'div_label' => 'order-by', |
| 198 | * ); |
| 199 | * |
| 200 | * @var array |
| 201 | */ |
| 202 | protected $tabs = []; |
| 203 | |
| 204 | /** |
| 205 | * Should we add paging. |
| 206 | * |
| 207 | * @var bool |
| 208 | */ |
| 209 | protected $addPaging = TRUE; |
| 210 | |
| 211 | protected $isForceGroupBy = FALSE; |
| 212 | |
| 213 | protected $groupConcatTested = FALSE; |
| 214 | |
| 215 | /** |
| 216 | * Are we in print mode. Can be set by another outputMode, ex: sendmail. |
| 217 | * |
| 218 | * @var bool |
| 219 | */ |
| 220 | public $printOnly = FALSE; |
| 221 | |
| 222 | /** |
| 223 | * An attribute for checkbox/radio form field layout |
| 224 | * |
| 225 | * @var array |
| 226 | */ |
| 227 | protected $_fourColumnAttribute = [ |
| 228 | '</td><td width="25%">', |
| 229 | '</td><td width="25%">', |
| 230 | '</td><td width="25%">', |
| 231 | '</tr><tr><td>', |
| 232 | ]; |
| 233 | |
| 234 | protected $_force = 1; |
| 235 | |
| 236 | protected $_params = NULL; |
| 237 | protected $_formValues = NULL; |
| 238 | protected $_instanceValues = NULL; |
| 239 | |
| 240 | protected $_instanceForm = FALSE; |
| 241 | protected $_criteriaForm = FALSE; |
| 242 | |
| 243 | protected $_instanceButtonName = NULL; |
| 244 | protected $_createNewButtonName = NULL; |
| 245 | protected $_groupButtonName = NULL; |
| 246 | protected $_chartButtonName = NULL; |
| 247 | protected $_csvSupported = TRUE; |
| 248 | protected $_add2groupSupported = TRUE; |
| 249 | protected $_groups = NULL; |
| 250 | protected $_grandFlag = FALSE; |
| 251 | protected $_rowsFound = NULL; |
| 252 | protected $_selectAliases = []; |
| 253 | protected $_rollup = NULL; |
| 254 | |
| 255 | /** |
| 256 | * Table containing list of contact IDs within the group filter. |
| 257 | * |
| 258 | * @var string |
| 259 | */ |
| 260 | protected $groupTempTable = ''; |
| 261 | |
| 262 | /** |
| 263 | * @var array |
| 264 | */ |
| 265 | protected $_aliases = []; |
| 266 | |
| 267 | /** |
| 268 | * @var string |
| 269 | */ |
| 270 | protected $_where; |
| 271 | |
| 272 | /** |
| 273 | * @var string |
| 274 | */ |
| 275 | protected $_from; |
| 276 | |
| 277 | /** |
| 278 | * SQL Limit clause |
| 279 | * @var string |
| 280 | */ |
| 281 | protected $_limit = NULL; |
| 282 | |
| 283 | /** |
| 284 | * This can be set to specify a limit to the number of rows |
| 285 | * Since it is currently envisaged as part of the api usage it is only being applied |
| 286 | * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part |
| 287 | * of the code (see limit() fn. |
| 288 | * |
| 289 | * @var int |
| 290 | */ |
| 291 | protected $_limitValue = NULL; |
| 292 | |
| 293 | /** |
| 294 | * This can be set to specify row offset |
| 295 | * See notes on _limitValue |
| 296 | * |
| 297 | * @var int |
| 298 | */ |
| 299 | protected $_offsetValue = NULL; |
| 300 | |
| 301 | /** |
| 302 | * @var array |
| 303 | */ |
| 304 | protected $_sections = []; |
| 305 | |
| 306 | protected $_autoIncludeIndexedFieldsAsOrderBys = 0; |
| 307 | |
| 308 | /** |
| 309 | * Whether to generate absolute URLs (ex: in report emails). |
| 310 | * |
| 311 | * @var bool |
| 312 | */ |
| 313 | public $_absoluteUrl = FALSE; |
| 314 | |
| 315 | /** |
| 316 | * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method. |
| 317 | * |
| 318 | * @var bool |
| 319 | */ |
| 320 | protected $_storeResultSet = FALSE; |
| 321 | |
| 322 | /** |
| 323 | * When _storeResultSet Flag is set use this var to store result set in form of array |
| 324 | * |
| 325 | * @var bool |
| 326 | */ |
| 327 | protected $_resultSet = []; |
| 328 | |
| 329 | /** |
| 330 | * To what frequency group-by a date column |
| 331 | * |
| 332 | * @var array |
| 333 | */ |
| 334 | protected $_groupByDateFreq = [ |
| 335 | 'MONTH' => 'Month', |
| 336 | 'YEARWEEK' => 'Week', |
| 337 | 'QUARTER' => 'Quarter', |
| 338 | 'YEAR' => 'Year', |
| 339 | ]; |
| 340 | |
| 341 | /** |
| 342 | * Variables to hold the acl inner join and where clause |
| 343 | * @var string|null |
| 344 | */ |
| 345 | protected $_aclFrom = NULL; |
| 346 | protected $_aclWhere = NULL; |
| 347 | |
| 348 | /** |
| 349 | * Array of DAO tables having columns included in SELECT or ORDER BY clause. |
| 350 | * |
| 351 | * Where has also been added to this although perhaps the 'includes both' array should have a different name. |
| 352 | * |
| 353 | * @var array |
| 354 | */ |
| 355 | protected $_selectedTables = []; |
| 356 | |
| 357 | /** |
| 358 | * Array of DAO tables having columns included in WHERE or HAVING clause |
| 359 | * |
| 360 | * @var array |
| 361 | */ |
| 362 | protected $filteredTables; |
| 363 | |
| 364 | /** |
| 365 | * Output mode e.g 'print', 'csv', 'pdf'. |
| 366 | * |
| 367 | * @var string |
| 368 | */ |
| 369 | protected $_outputMode; |
| 370 | |
| 371 | /** |
| 372 | * Format of any chart in use. |
| 373 | * |
| 374 | * (it's unclear if this could be merged with outputMode at this stage) |
| 375 | * |
| 376 | * @var string|null |
| 377 | */ |
| 378 | protected $_format; |
| 379 | |
| 380 | public $_having = NULL; |
| 381 | public $_select = NULL; |
| 382 | public $_selectClauses = []; |
| 383 | public $_columnHeaders = []; |
| 384 | public $_orderBy = NULL; |
| 385 | public $_orderByFields = []; |
| 386 | public $_orderByArray = []; |
| 387 | /** |
| 388 | * Array of clauses to group by. |
| 389 | * |
| 390 | * @var array |
| 391 | */ |
| 392 | protected $_groupByArray = []; |
| 393 | public $_groupBy = NULL; |
| 394 | public $_whereClauses = []; |
| 395 | public $_havingClauses = []; |
| 396 | |
| 397 | /** |
| 398 | * DashBoardRowCount Dashboard row count. |
| 399 | * |
| 400 | * @var int |
| 401 | */ |
| 402 | public $_dashBoardRowCount; |
| 403 | |
| 404 | /** |
| 405 | * Is this being called without a form controller (ie. the report is being render outside the normal form |
| 406 | * - e.g the api is retrieving the rows. |
| 407 | * |
| 408 | * @var bool |
| 409 | */ |
| 410 | public $noController = FALSE; |
| 411 | |
| 412 | /** |
| 413 | * Variable to hold the currency alias. |
| 414 | * |
| 415 | * @var string|null |
| 416 | */ |
| 417 | protected $_currencyColumn = NULL; |
| 418 | |
| 419 | /** |
| 420 | * @var string |
| 421 | */ |
| 422 | protected $_interval; |
| 423 | |
| 424 | /** |
| 425 | * @var bool |
| 426 | */ |
| 427 | protected $_sendmail; |
| 428 | |
| 429 | /** |
| 430 | * @var int |
| 431 | */ |
| 432 | protected $_chartId; |
| 433 | |
| 434 | /** |
| 435 | * @var int |
| 436 | */ |
| 437 | public $_section; |
| 438 | |
| 439 | /** |
| 440 | * Report description. |
| 441 | * |
| 442 | * @var string |
| 443 | */ |
| 444 | public $_description; |
| 445 | |
| 446 | /** |
| 447 | * Is an address field selected. |
| 448 | * |
| 449 | * @var bool |
| 450 | * This was intended to determine if the address table should be joined in |
| 451 | * The isTableSelected function is now preferred for this purpose |
| 452 | */ |
| 453 | protected $_addressField; |
| 454 | |
| 455 | /** |
| 456 | * Is an email field selected. |
| 457 | * |
| 458 | * @var bool |
| 459 | * This was intended to determine if the email table should be joined in |
| 460 | * The isTableSelected function is now preferred for this purpose |
| 461 | */ |
| 462 | protected $_emailField; |
| 463 | |
| 464 | /** |
| 465 | * Is a phone field selected. |
| 466 | * |
| 467 | * @var bool |
| 468 | * This was intended to determine if the phone table should be joined in |
| 469 | * The isTableSelected function is now preferred for this purpose |
| 470 | */ |
| 471 | protected $_phoneField; |
| 472 | |
| 473 | /** |
| 474 | * Create new report instance? (or update existing) on save. |
| 475 | * |
| 476 | * @var bool |
| 477 | */ |
| 478 | protected $_createNew; |
| 479 | |
| 480 | /** |
| 481 | * When a grand total row has calculated the status we pop it off to here. |
| 482 | * |
| 483 | * This allows us to access it from the stats function and avoid recalculating. |
| 484 | * |
| 485 | * @var array |
| 486 | */ |
| 487 | protected $rollupRow = []; |
| 488 | |
| 489 | /** |
| 490 | * Database attributes - character set and collation. |
| 491 | * |
| 492 | * @var string |
| 493 | */ |
| 494 | protected $_databaseAttributes = ' DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci'; |
| 495 | |
| 496 | /** |
| 497 | * SQL being run in this report. |
| 498 | * |
| 499 | * The sql in the report is stored in this variable in order to be displayed on the developer tab. |
| 500 | * |
| 501 | * @var string |
| 502 | */ |
| 503 | |
| 504 | protected $sql; |
| 505 | |
| 506 | /** |
| 507 | * An instruction not to add a Group By. |
| 508 | * |
| 509 | * This is relevant where the group by might be otherwise added after the code that determines the group by array. |
| 510 | * |
| 511 | * e.g. where stat fields are being added but other settings cause it to not be desirable to add a group by |
| 512 | * such as in pivot charts when no row header is set |
| 513 | * |
| 514 | * @var bool |
| 515 | */ |
| 516 | protected $noGroupBy = FALSE; |
| 517 | |
| 518 | /** |
| 519 | * SQL being run in this report as an array. |
| 520 | * |
| 521 | * The sql in the report is stored in this variable in order to be returned to api & test calls. |
| 522 | * |
| 523 | * @var string |
| 524 | */ |
| 525 | |
| 526 | protected $sqlArray; |
| 527 | |
| 528 | /** |
| 529 | * Tables created for the report that need removal afterwards. |
| 530 | * |
| 531 | * ['civicrm_temp_report_x' => ['temporary' => TRUE, 'name' => 'civicrm_temp_report_x'] |
| 532 | * @var array |
| 533 | */ |
| 534 | protected $temporaryTables = []; |
| 535 | |
| 536 | /** |
| 537 | * Can this report use the sql mode ONLY_FULL_GROUP_BY. |
| 538 | * @var bool |
| 539 | */ |
| 540 | public $optimisedForOnlyFullGroupBy = TRUE; |
| 541 | |
| 542 | /** |
| 543 | * Determines which chart types are supported for this report |
| 544 | * @var string[] |
| 545 | */ |
| 546 | protected $_charts = []; |
| 547 | |
| 548 | /** |
| 549 | * Get the number of rows to show |
| 550 | * @return int |
| 551 | */ |
| 552 | public function getRowCount(): int { |
| 553 | return $this->_rowCount; |
| 554 | } |
| 555 | |
| 556 | /** |
| 557 | * set the number of rows to show |
| 558 | * @param int $rowCount |
| 559 | */ |
| 560 | public function setRowCount($rowCount): void { |
| 561 | $this->_rowCount = $rowCount; |
| 562 | } |
| 563 | |
| 564 | /** |
| 565 | * Class constructor. |
| 566 | */ |
| 567 | public function __construct() { |
| 568 | parent::__construct(); |
| 569 | |
| 570 | $this->setRowCount(\Civi::settings()->get('default_pager_size')); |
| 571 | |
| 572 | $this->addClass('crm-report-form'); |
| 573 | |
| 574 | if ($this->_tagFilter) { |
| 575 | $this->buildTagFilter(); |
| 576 | } |
| 577 | if ($this->_exposeContactID) { |
| 578 | if (array_key_exists('civicrm_contact', $this->_columns)) { |
| 579 | $this->_columns['civicrm_contact']['fields']['exposed_id'] = [ |
| 580 | 'name' => 'id', |
| 581 | 'title' => ts('Contact ID'), |
| 582 | 'no_repeat' => TRUE, |
| 583 | ]; |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | if ($this->_groupFilter) { |
| 588 | $this->buildGroupFilter(); |
| 589 | } |
| 590 | |
| 591 | // Get all custom groups |
| 592 | $allGroups = CRM_Core_PseudoConstant::get('CRM_Core_DAO_CustomField', 'custom_group_id'); |
| 593 | |
| 594 | // Get the custom groupIds for which the user has VIEW permission |
| 595 | // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty |
| 596 | // and addCustomDataToColumns() will allow access to all custom groups. |
| 597 | $permCustomGroupIds = []; |
| 598 | if (!CRM_Core_Permission::check('access all custom data')) { |
| 599 | $permCustomGroupIds = CRM_ACL_API::group(CRM_Core_Permission::VIEW, NULL, 'civicrm_custom_group', $allGroups, NULL); |
| 600 | // do not allow custom data for reports if user doesn't have |
| 601 | // permission to access custom data. |
| 602 | if (!empty($this->_customGroupExtends) && empty($permCustomGroupIds)) { |
| 603 | $this->_customGroupExtends = []; |
| 604 | } |
| 605 | } |
| 606 | |
| 607 | // merge custom data columns to _columns list, if any |
| 608 | $this->addCustomDataToColumns(TRUE, $permCustomGroupIds); |
| 609 | |
| 610 | // add / modify display columns, filters ..etc |
| 611 | CRM_Utils_Hook::alterReportVar('columns', $this->_columns, $this); |
| 612 | |
| 613 | //assign currencyColumn variable to tpl |
| 614 | $this->assign('currencyColumn', $this->_currencyColumn); |
| 615 | } |
| 616 | |
| 617 | /** |
| 618 | * Shared pre-process function. |
| 619 | * |
| 620 | * If overriding preProcess function this should still be called. |
| 621 | * |
| 622 | * @throws \Exception |
| 623 | */ |
| 624 | public function preProcessCommon() { |
| 625 | $this->_force = CRM_Utils_Request::retrieve('force', 'Boolean'); |
| 626 | // Ensure smarty variables are assigned here since this function is called from |
| 627 | // the report api and the main buildForm is not. |
| 628 | self::$_template->ensureVariablesAreAssigned($this->expectedSmartyVariables); |
| 629 | $this->_dashBoardRowCount = CRM_Utils_Request::retrieve('rowCount', 'Integer'); |
| 630 | |
| 631 | $this->_section = CRM_Utils_Request::retrieve('section', 'Integer'); |
| 632 | |
| 633 | $this->assign('section', $this->_section); |
| 634 | CRM_Core_Region::instance('page-header')->add([ |
| 635 | 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))), |
| 636 | ]); |
| 637 | if (!$this->noController) { |
| 638 | $this->setID($this->get('instanceId')); |
| 639 | |
| 640 | if (!$this->_id) { |
| 641 | $this->setID(CRM_Report_Utils_Report::getInstanceID()); |
| 642 | if (!$this->_id) { |
| 643 | $this->setID(CRM_Report_Utils_Report::getInstanceIDForPath()); |
| 644 | } |
| 645 | } |
| 646 | |
| 647 | // set qfkey so that pager picks it up and use it in the "Next > Last >>" links. |
| 648 | // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING |
| 649 | if (!isset($_SERVER['QUERY_STRING'])) { |
| 650 | // in php 7.4 can do this with less lines with ??= |
| 651 | $_SERVER['QUERY_STRING'] = ''; |
| 652 | } |
| 653 | $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}"; |
| 654 | } |
| 655 | |
| 656 | if ($this->_id) { |
| 657 | $this->assign('instanceId', $this->_id); |
| 658 | $params = ['id' => $this->_id]; |
| 659 | $this->_instanceValues = []; |
| 660 | CRM_Core_DAO::commonRetrieve('CRM_Report_DAO_ReportInstance', |
| 661 | $params, |
| 662 | $this->_instanceValues |
| 663 | ); |
| 664 | if (empty($this->_instanceValues)) { |
| 665 | CRM_Core_Error::statusBounce("Report could not be loaded."); |
| 666 | } |
| 667 | $this->_title = $this->_instanceValues['title']; |
| 668 | if (!empty($this->_instanceValues['permission']) && |
| 669 | (!(CRM_Core_Permission::check($this->_instanceValues['permission']) || |
| 670 | CRM_Core_Permission::check('administer Reports') |
| 671 | )) |
| 672 | ) { |
| 673 | CRM_Utils_System::permissionDenied(); |
| 674 | CRM_Utils_System::civiExit(); |
| 675 | } |
| 676 | |
| 677 | $formValues = $this->_instanceValues['form_values'] ?? NULL; |
| 678 | if ($formValues) { |
| 679 | $this->_formValues = CRM_Utils_String::unserialize($formValues); |
| 680 | } |
| 681 | else { |
| 682 | $this->_formValues = NULL; |
| 683 | } |
| 684 | |
| 685 | $this->setOutputMode(); |
| 686 | |
| 687 | if ($this->_outputMode == 'copy') { |
| 688 | $this->_createNew = TRUE; |
| 689 | $this->_params = $this->_formValues; |
| 690 | $this->_params['view_mode'] = 'criteria'; |
| 691 | $this->_params['title'] = $this->getTitle() . ts(' (copy created by %1 on %2)', [ |
| 692 | CRM_Core_Session::singleton()->getLoggedInContactDisplayName(), |
| 693 | CRM_Utils_Date::customFormat(date('Y-m-d H:i')), |
| 694 | ]); |
| 695 | // Do not pass go. Do not collect another chance to re-run the same query. |
| 696 | CRM_Report_Form_Instance::postProcess($this); |
| 697 | } |
| 698 | |
| 699 | // lets always do a force if reset is found in the url. |
| 700 | // Hey why not? see CRM-17225 for more about this. The use of reset to be force is historical for reasons stated |
| 701 | // in the comment line above these 2. |
| 702 | if (!empty($_REQUEST['reset']) |
| 703 | && !in_array(CRM_Utils_Request::retrieve('output', 'String'), ['save', 'criteria'])) { |
| 704 | $this->_force = 1; |
| 705 | } |
| 706 | |
| 707 | // set the mode |
| 708 | $this->assign('mode', 'instance'); |
| 709 | } |
| 710 | elseif (!$this->noController) { |
| 711 | [$optionValueID, $optionValue] = CRM_Report_Utils_Report::getValueIDFromUrl(); |
| 712 | $instanceCount = CRM_Report_Utils_Report::getInstanceCount($optionValue); |
| 713 | if (($instanceCount > 0) && $optionValueID) { |
| 714 | $this->assign('instanceUrl', |
| 715 | CRM_Utils_System::url('civicrm/report/list', |
| 716 | "reset=1&ovid=$optionValueID" |
| 717 | ) |
| 718 | ); |
| 719 | } |
| 720 | if ($optionValueID) { |
| 721 | $this->_description = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description'); |
| 722 | } |
| 723 | |
| 724 | // set the mode |
| 725 | $this->assign('mode', 'template'); |
| 726 | } |
| 727 | |
| 728 | // lets display the Report Settings section |
| 729 | $this->_instanceForm = $this->_force || $this->_id || (!empty($_POST)); |
| 730 | |
| 731 | // Do not display Report Settings section if administer Reports permission is absent OR |
| 732 | // if report instance is reserved and administer reserved reports absent |
| 733 | if (!CRM_Core_Permission::check('administer Reports') || |
| 734 | (!empty($this->_instanceValues['is_reserved']) && |
| 735 | !CRM_Core_Permission::check('administer reserved reports')) |
| 736 | ) { |
| 737 | $this->_instanceForm = FALSE; |
| 738 | } |
| 739 | |
| 740 | $this->assign('criteriaForm', FALSE); |
| 741 | // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved |
| 742 | if (CRM_Core_Permission::check('administer Reports') || |
| 743 | CRM_Core_Permission::check('access Report Criteria') |
| 744 | ) { |
| 745 | if (empty($this->_instanceValues['is_reserved']) || |
| 746 | CRM_Core_Permission::check('administer reserved reports') |
| 747 | ) { |
| 748 | $this->assign('criteriaForm', TRUE); |
| 749 | $this->_criteriaForm = TRUE; |
| 750 | } |
| 751 | } |
| 752 | |
| 753 | // Special permissions check for private instance if it's not the current contact instance |
| 754 | if ($this->_id && |
| 755 | (CRM_Report_BAO_ReportInstance::reportIsPrivate($this->_id) && |
| 756 | !CRM_Report_BAO_ReportInstance::contactIsOwner($this->_id))) { |
| 757 | if (!CRM_Core_Permission::check('access all private reports')) { |
| 758 | $this->_instanceForm = FALSE; |
| 759 | $this->assign('criteriaForm', FALSE); |
| 760 | } |
| 761 | } |
| 762 | |
| 763 | $this->_instanceButtonName = $this->getButtonName('submit', 'save'); |
| 764 | $this->_createNewButtonName = $this->getButtonName('submit', 'next'); |
| 765 | $this->_groupButtonName = $this->getButtonName('submit', 'group'); |
| 766 | $this->_chartButtonName = $this->getButtonName('submit', 'chart'); |
| 767 | } |
| 768 | |
| 769 | /** |
| 770 | * Add bread crumb. |
| 771 | */ |
| 772 | public function addBreadCrumb() { |
| 773 | $breadCrumbs |
| 774 | = [ |
| 775 | [ |
| 776 | 'title' => ts('Report Templates'), |
| 777 | 'url' => CRM_Utils_System::url('civicrm/admin/report/template/list', 'reset=1'), |
| 778 | ], |
| 779 | ]; |
| 780 | |
| 781 | CRM_Utils_System::appendBreadCrumb($breadCrumbs); |
| 782 | } |
| 783 | |
| 784 | /** |
| 785 | * Pre process function. |
| 786 | * |
| 787 | * Called prior to build form. |
| 788 | */ |
| 789 | public function preProcess() { |
| 790 | $this->preProcessCommon(); |
| 791 | |
| 792 | if (!$this->_id) { |
| 793 | $this->addBreadCrumb(); |
| 794 | } |
| 795 | |
| 796 | foreach ($this->_columns as $tableName => $table) { |
| 797 | $this->setTableAlias($table, $tableName); |
| 798 | |
| 799 | $expFields = []; |
| 800 | // higher preference to bao object |
| 801 | $daoOrBaoName = CRM_Utils_Array::value('bao', $table, CRM_Utils_Array::value('dao', $table)); |
| 802 | |
| 803 | if ($daoOrBaoName) { |
| 804 | if (method_exists($daoOrBaoName, 'exportableFields')) { |
| 805 | $expFields = $daoOrBaoName::exportableFields(); |
| 806 | } |
| 807 | else { |
| 808 | $expFields = $daoOrBaoName::export(); |
| 809 | } |
| 810 | } |
| 811 | |
| 812 | $doNotCopy = ['required', 'default']; |
| 813 | |
| 814 | $fieldGroups = ['fields', 'filters', 'group_bys', 'order_bys']; |
| 815 | foreach ($fieldGroups as $fieldGrp) { |
| 816 | if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) { |
| 817 | foreach ($table[$fieldGrp] as $fieldName => $field) { |
| 818 | // $name is the field name used to reference the BAO/DAO export fields array |
| 819 | $name = $field['name'] ?? $fieldName; |
| 820 | |
| 821 | // Sometimes the field name key in the BAO/DAO export fields array is |
| 822 | // different from the actual database field name. |
| 823 | // Unset $field['name'] so that actual database field name can be obtained |
| 824 | // from the BAO/DAO export fields array. |
| 825 | unset($field['name']); |
| 826 | |
| 827 | if (array_key_exists($name, $expFields)) { |
| 828 | foreach ($doNotCopy as $dnc) { |
| 829 | // unset the values we don't want to be copied. |
| 830 | unset($expFields[$name][$dnc]); |
| 831 | } |
| 832 | if (empty($field)) { |
| 833 | $this->_columns[$tableName][$fieldGrp][$fieldName] = $expFields[$name]; |
| 834 | } |
| 835 | else { |
| 836 | foreach ($expFields[$name] as $property => $val) { |
| 837 | if (!array_key_exists($property, $field)) { |
| 838 | $this->_columns[$tableName][$fieldGrp][$fieldName][$property] = $val; |
| 839 | } |
| 840 | } |
| 841 | } |
| 842 | } |
| 843 | |
| 844 | // fill other vars |
| 845 | if (!empty($field['no_repeat'])) { |
| 846 | $this->_noRepeats[] = "{$tableName}_{$fieldName}"; |
| 847 | } |
| 848 | if (!empty($field['no_display'])) { |
| 849 | $this->_noDisplay[] = "{$tableName}_{$fieldName}"; |
| 850 | } |
| 851 | |
| 852 | // set alias = table-name, unless already set |
| 853 | $alias = $field['alias'] ?? ( |
| 854 | $this->_columns[$tableName]['alias'] ?? $tableName |
| 855 | ); |
| 856 | $this->_columns[$tableName][$fieldGrp][$fieldName]['alias'] = $alias; |
| 857 | |
| 858 | // set name = fieldName, unless already set |
| 859 | if (!isset($this->_columns[$tableName][$fieldGrp][$fieldName]['name'])) { |
| 860 | $this->_columns[$tableName][$fieldGrp][$fieldName]['name'] = $name; |
| 861 | } |
| 862 | |
| 863 | if (!isset($this->_columns[$tableName][$fieldGrp][$fieldName]['table_name'])) { |
| 864 | $this->_columns[$tableName][$fieldGrp][$fieldName]['table_name'] = $tableName; |
| 865 | } |
| 866 | |
| 867 | // set dbAlias = alias.name, unless already set |
| 868 | if (!isset($this->_columns[$tableName][$fieldGrp][$fieldName]['dbAlias'])) { |
| 869 | $this->_columns[$tableName][$fieldGrp][$fieldName]['dbAlias'] |
| 870 | = $alias . '.' . |
| 871 | $this->_columns[$tableName][$fieldGrp][$fieldName]['name']; |
| 872 | } |
| 873 | |
| 874 | // a few auto fills for filters |
| 875 | if ($fieldGrp == 'filters') { |
| 876 | // fill operator types |
| 877 | if (!array_key_exists('operatorType', $this->_columns[$tableName][$fieldGrp][$fieldName])) { |
| 878 | switch (CRM_Utils_Array::value('type', $this->_columns[$tableName][$fieldGrp][$fieldName])) { |
| 879 | case CRM_Utils_Type::T_MONEY: |
| 880 | case CRM_Utils_Type::T_FLOAT: |
| 881 | $this->_columns[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form::OP_FLOAT; |
| 882 | break; |
| 883 | |
| 884 | case CRM_Utils_Type::T_INT: |
| 885 | $this->_columns[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form::OP_INT; |
| 886 | break; |
| 887 | |
| 888 | case CRM_Utils_Type::T_DATE: |
| 889 | $this->_columns[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form::OP_DATE; |
| 890 | break; |
| 891 | |
| 892 | case CRM_Utils_Type::T_BOOLEAN: |
| 893 | $this->_columns[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form::OP_SELECT; |
| 894 | if (!array_key_exists('options', $this->_columns[$tableName][$fieldGrp][$fieldName])) { |
| 895 | $this->_columns[$tableName][$fieldGrp][$fieldName]['options'] |
| 896 | = [ |
| 897 | '' => ts('Any'), |
| 898 | '0' => ts('No'), |
| 899 | '1' => ts('Yes'), |
| 900 | ]; |
| 901 | } |
| 902 | break; |
| 903 | |
| 904 | default: |
| 905 | if ($daoOrBaoName && |
| 906 | array_key_exists('pseudoconstant', $this->_columns[$tableName][$fieldGrp][$fieldName]) |
| 907 | ) { |
| 908 | // with multiple options operator-type is generally multi-select |
| 909 | $this->_columns[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT; |
| 910 | if (!array_key_exists('options', $this->_columns[$tableName][$fieldGrp][$fieldName])) { |
| 911 | // fill options |
| 912 | $this->_columns[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant::get($daoOrBaoName, $fieldName); |
| 913 | } |
| 914 | } |
| 915 | break; |
| 916 | } |
| 917 | } |
| 918 | } |
| 919 | if (!isset($this->_columns[$tableName]['metadata'][$fieldName])) { |
| 920 | $this->_columns[$tableName]['metadata'][$fieldName] = $this->_columns[$tableName][$fieldGrp][$fieldName]; |
| 921 | } |
| 922 | else { |
| 923 | $this->_columns[$tableName]['metadata'][$fieldName] = array_merge($this->_columns[$tableName][$fieldGrp][$fieldName], $this->_columns[$tableName]['metadata'][$fieldName]); |
| 924 | } |
| 925 | } |
| 926 | } |
| 927 | } |
| 928 | |
| 929 | // copy filters to a separate handy variable |
| 930 | if (array_key_exists('filters', $table)) { |
| 931 | $this->_filters[$tableName] = $this->_columns[$tableName]['filters']; |
| 932 | } |
| 933 | |
| 934 | if (array_key_exists('group_bys', $table)) { |
| 935 | $groupBys[$tableName] = $this->_columns[$tableName]['group_bys']; |
| 936 | } |
| 937 | |
| 938 | if (array_key_exists('fields', $table)) { |
| 939 | $reportFields[$tableName] = $this->_columns[$tableName]['fields']; |
| 940 | } |
| 941 | } |
| 942 | |
| 943 | if ($this->_force) { |
| 944 | $this->setDefaultValues(FALSE); |
| 945 | } |
| 946 | |
| 947 | CRM_Report_Utils_Get::processFilter($this->_filters, $this->_defaults); |
| 948 | CRM_Report_Utils_Get::processGroupBy($groupBys, $this->_defaults); |
| 949 | CRM_Report_Utils_Get::processFields($reportFields, $this->_defaults); |
| 950 | CRM_Report_Utils_Get::processChart($this->_defaults); |
| 951 | |
| 952 | if ($this->_force) { |
| 953 | $this->_formValues = $this->_defaults; |
| 954 | $this->postProcess(); |
| 955 | } |
| 956 | } |
| 957 | |
| 958 | /** |
| 959 | * Set default values. |
| 960 | * |
| 961 | * @param bool $freeze |
| 962 | * |
| 963 | * @return array |
| 964 | */ |
| 965 | public function setDefaultValues($freeze = TRUE) { |
| 966 | $freezeGroup = []; |
| 967 | |
| 968 | // FIXME: generalizing form field naming conventions would reduce |
| 969 | // Lots of lines below. |
| 970 | foreach ($this->_columns as $tableName => $table) { |
| 971 | if (array_key_exists('fields', $table)) { |
| 972 | foreach ($table['fields'] as $fieldName => $field) { |
| 973 | if (empty($field['no_display'])) { |
| 974 | if (!empty($field['required'])) { |
| 975 | // set default |
| 976 | $this->_defaults['fields'][$fieldName] = 1; |
| 977 | |
| 978 | if ($freeze) { |
| 979 | // find element object, so that we could use quickform's freeze method |
| 980 | // for required elements |
| 981 | $obj = $this->getElementFromGroup("fields", $fieldName); |
| 982 | if ($obj) { |
| 983 | $freezeGroup[] = $obj; |
| 984 | } |
| 985 | } |
| 986 | } |
| 987 | elseif (isset($field['default'])) { |
| 988 | $this->_defaults['fields'][$fieldName] = $field['default']; |
| 989 | } |
| 990 | } |
| 991 | } |
| 992 | } |
| 993 | |
| 994 | if (array_key_exists('group_bys', $table)) { |
| 995 | foreach ($table['group_bys'] as $fieldName => $field) { |
| 996 | if (isset($field['default'])) { |
| 997 | if (!empty($field['frequency'])) { |
| 998 | $this->_defaults['group_bys_freq'][$fieldName] = 'MONTH'; |
| 999 | } |
| 1000 | $this->_defaults['group_bys'][$fieldName] = $field['default']; |
| 1001 | } |
| 1002 | } |
| 1003 | } |
| 1004 | if (array_key_exists('filters', $table)) { |
| 1005 | foreach ($table['filters'] as $fieldName => $field) { |
| 1006 | if (isset($field['default'])) { |
| 1007 | if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE |
| 1008 | ) { |
| 1009 | if (is_array($field['default'])) { |
| 1010 | $this->_defaults["{$fieldName}_from"] = $field['default']['from'] ?? NULL; |
| 1011 | $this->_defaults["{$fieldName}_to"] = $field['default']['to'] ?? NULL; |
| 1012 | $this->_defaults["{$fieldName}_relative"] = 0; |
| 1013 | } |
| 1014 | else { |
| 1015 | $this->_defaults["{$fieldName}_relative"] = $field['default']; |
| 1016 | } |
| 1017 | } |
| 1018 | else { |
| 1019 | if ((CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_INT) && is_array($field['default'])) { |
| 1020 | $this->_defaults["{$fieldName}_min"] = $field['default']['min'] ?? NULL; |
| 1021 | $this->_defaults["{$fieldName}_max"] = $field['default']['max'] ?? NULL; |
| 1022 | } |
| 1023 | $this->_defaults["{$fieldName}_value"] = $field['default']; |
| 1024 | } |
| 1025 | } |
| 1026 | //assign default value as "in" for multiselect |
| 1027 | //operator, To freeze the select element |
| 1028 | if (CRM_Utils_Array::value('operatorType', $field) == |
| 1029 | CRM_Report_Form::OP_MULTISELECT |
| 1030 | ) { |
| 1031 | $this->_defaults["{$fieldName}_op"] = 'in'; |
| 1032 | } |
| 1033 | if (CRM_Utils_Array::value('operatorType', $field) == |
| 1034 | CRM_Report_Form::OP_ENTITYREF |
| 1035 | ) { |
| 1036 | $this->_defaults["{$fieldName}_op"] = 'in'; |
| 1037 | } |
| 1038 | elseif (CRM_Utils_Array::value('operatorType', $field) == |
| 1039 | CRM_Report_Form::OP_MULTISELECT_SEPARATOR |
| 1040 | ) { |
| 1041 | $this->_defaults["{$fieldName}_op"] = 'mhas'; |
| 1042 | } |
| 1043 | elseif ($op = CRM_Utils_Array::value('default_op', $field)) { |
| 1044 | $this->_defaults["{$fieldName}_op"] = $op; |
| 1045 | } |
| 1046 | } |
| 1047 | } |
| 1048 | |
| 1049 | if ( |
| 1050 | empty($this->_formValues['order_bys']) && |
| 1051 | (array_key_exists('order_bys', $table) && |
| 1052 | is_array($table['order_bys'])) |
| 1053 | ) { |
| 1054 | if (!array_key_exists('order_bys', $this->_defaults)) { |
| 1055 | $this->_defaults['order_bys'] = []; |
| 1056 | } |
| 1057 | foreach ($table['order_bys'] as $fieldName => $field) { |
| 1058 | if (!empty($field['default']) || !empty($field['default_order']) || |
| 1059 | CRM_Utils_Array::value('default_is_section', $field) || |
| 1060 | !empty($field['default_weight']) |
| 1061 | ) { |
| 1062 | $order_by = [ |
| 1063 | 'column' => $fieldName, |
| 1064 | 'order' => CRM_Utils_Array::value('default_order', $field, 'ASC'), |
| 1065 | 'section' => CRM_Utils_Array::value('default_is_section', $field, 0), |
| 1066 | ]; |
| 1067 | |
| 1068 | if (!empty($field['default_weight'])) { |
| 1069 | $this->_defaults['order_bys'][(int) $field['default_weight']] = $order_by; |
| 1070 | } |
| 1071 | else { |
| 1072 | array_unshift($this->_defaults['order_bys'], $order_by); |
| 1073 | } |
| 1074 | } |
| 1075 | } |
| 1076 | } |
| 1077 | |
| 1078 | foreach ($this->_options as $fieldName => $field) { |
| 1079 | if (isset($field['default'])) { |
| 1080 | $this->_defaults['options'][$fieldName] = $field['default']; |
| 1081 | } |
| 1082 | } |
| 1083 | } |
| 1084 | |
| 1085 | if (!empty($this->_submitValues)) { |
| 1086 | $this->preProcessOrderBy($this->_submitValues); |
| 1087 | } |
| 1088 | else { |
| 1089 | $this->preProcessOrderBy($this->_defaults); |
| 1090 | } |
| 1091 | |
| 1092 | // lets finish freezing task here itself |
| 1093 | if (!empty($freezeGroup)) { |
| 1094 | foreach ($freezeGroup as $elem) { |
| 1095 | $elem->freeze(); |
| 1096 | } |
| 1097 | } |
| 1098 | |
| 1099 | if ($this->_formValues) { |
| 1100 | $this->_defaults = array_merge($this->_defaults, $this->_formValues); |
| 1101 | } |
| 1102 | |
| 1103 | if ($this->_instanceValues) { |
| 1104 | $this->_defaults = array_merge($this->_defaults, $this->_instanceValues); |
| 1105 | } |
| 1106 | |
| 1107 | CRM_Report_Form_Instance::setDefaultValues($this, $this->_defaults); |
| 1108 | |
| 1109 | return $this->_defaults; |
| 1110 | } |
| 1111 | |
| 1112 | /** |
| 1113 | * Get element from group. |
| 1114 | * |
| 1115 | * @param string $group |
| 1116 | * @param string $grpFieldName |
| 1117 | * |
| 1118 | * @return object|bool |
| 1119 | */ |
| 1120 | public function getElementFromGroup($group, $grpFieldName) { |
| 1121 | $eleObj = $this->getElement($group); |
| 1122 | foreach ($eleObj->_elements as $index => $obj) { |
| 1123 | if ($grpFieldName == $obj->_attributes['name']) { |
| 1124 | return $obj; |
| 1125 | } |
| 1126 | } |
| 1127 | return FALSE; |
| 1128 | } |
| 1129 | |
| 1130 | /** |
| 1131 | * Setter for $_params. |
| 1132 | * |
| 1133 | * @param array $params |
| 1134 | */ |
| 1135 | public function setParams($params) { |
| 1136 | $this->_params = $params; |
| 1137 | } |
| 1138 | |
| 1139 | /** |
| 1140 | * Getter for $_params. |
| 1141 | * |
| 1142 | * @return void|array $params |
| 1143 | */ |
| 1144 | public function getParams() { |
| 1145 | return $this->_params; |
| 1146 | } |
| 1147 | |
| 1148 | /** |
| 1149 | * Setter for $_id. |
| 1150 | * |
| 1151 | * @param int $instanceID |
| 1152 | */ |
| 1153 | public function setID($instanceID) { |
| 1154 | $this->_id = $instanceID; |
| 1155 | } |
| 1156 | |
| 1157 | /** |
| 1158 | * Getter for $_id. |
| 1159 | * |
| 1160 | * @return int |
| 1161 | */ |
| 1162 | public function getID() { |
| 1163 | return $this->_id; |
| 1164 | } |
| 1165 | |
| 1166 | /** |
| 1167 | * Getter for _outputMode |
| 1168 | * |
| 1169 | * Note you can implement hook_civicrm_alterReportVar('actions', ...) |
| 1170 | * which indirectly allows setting _outputMode if the user chooses |
| 1171 | * your action. |
| 1172 | * |
| 1173 | * @return string |
| 1174 | */ |
| 1175 | public function getOutputMode():string { |
| 1176 | return $this->_outputMode; |
| 1177 | } |
| 1178 | |
| 1179 | /** |
| 1180 | * Getter for report header form field value |
| 1181 | * |
| 1182 | * @return string |
| 1183 | */ |
| 1184 | public function getReportHeader():string { |
| 1185 | return $this->_formValues['report_header'] ?? ''; |
| 1186 | } |
| 1187 | |
| 1188 | /** |
| 1189 | * Getter for report footer form field value |
| 1190 | * |
| 1191 | * @return string |
| 1192 | */ |
| 1193 | public function getReportFooter():string { |
| 1194 | return $this->_formValues['report_footer'] ?? ''; |
| 1195 | } |
| 1196 | |
| 1197 | /** |
| 1198 | * Setter for $_force. |
| 1199 | * |
| 1200 | * @param bool $isForce |
| 1201 | */ |
| 1202 | public function setForce($isForce) { |
| 1203 | $this->_force = $isForce; |
| 1204 | } |
| 1205 | |
| 1206 | /** |
| 1207 | * Setter for $_limitValue. |
| 1208 | * |
| 1209 | * @param int $_limitValue |
| 1210 | */ |
| 1211 | public function setLimitValue($_limitValue) { |
| 1212 | $this->_limitValue = $_limitValue; |
| 1213 | } |
| 1214 | |
| 1215 | /** |
| 1216 | * Setter for $_offsetValue. |
| 1217 | * |
| 1218 | * @param int $_offsetValue |
| 1219 | */ |
| 1220 | public function setOffsetValue($_offsetValue) { |
| 1221 | $this->_offsetValue = $_offsetValue; |
| 1222 | } |
| 1223 | |
| 1224 | /** |
| 1225 | * Setter for $addPaging. |
| 1226 | * |
| 1227 | * @param bool $value |
| 1228 | */ |
| 1229 | public function setAddPaging($value) { |
| 1230 | $this->addPaging = $value; |
| 1231 | } |
| 1232 | |
| 1233 | /** |
| 1234 | * Getter for $_defaultValues. |
| 1235 | * |
| 1236 | * @return array |
| 1237 | */ |
| 1238 | public function getDefaultValues() { |
| 1239 | return $this->_defaults; |
| 1240 | } |
| 1241 | |
| 1242 | /** |
| 1243 | * Remove any temporary tables. |
| 1244 | */ |
| 1245 | public function cleanUpTemporaryTables() { |
| 1246 | foreach ($this->temporaryTables as $temporaryTable) { |
| 1247 | CRM_Core_DAO::executeQuery('DROP ' . ($temporaryTable['temporary'] ? 'TEMPORARY' : '') . ' TABLE IF EXISTS ' . $temporaryTable['name']); |
| 1248 | } |
| 1249 | } |
| 1250 | |
| 1251 | /** |
| 1252 | * Create a temporary table. |
| 1253 | * |
| 1254 | * This function creates a table AND adds the details to the developer tab & $this->>temporary tables. |
| 1255 | * |
| 1256 | * @param string $identifier |
| 1257 | * This is the key that will be used for the table in the temporaryTables property. |
| 1258 | * @param string $sql |
| 1259 | * Sql select statement or column description (the latter requires the columns flag) |
| 1260 | * @param bool $isColumns |
| 1261 | * Is the sql describing columns to create (rather than using a select query). |
| 1262 | * @param bool $isMemory |
| 1263 | * Create a memory table rather than a normal INNODB table. |
| 1264 | * |
| 1265 | * @return string |
| 1266 | */ |
| 1267 | public function createTemporaryTable($identifier, $sql, $isColumns = FALSE, $isMemory = FALSE) { |
| 1268 | $tempTable = CRM_Utils_SQL_TempTable::build(); |
| 1269 | if ($isMemory) { |
| 1270 | $tempTable->setMemory(); |
| 1271 | } |
| 1272 | if ($isColumns) { |
| 1273 | $tempTable->createWithColumns($sql); |
| 1274 | } |
| 1275 | else { |
| 1276 | $tempTable->createWithQuery($sql); |
| 1277 | } |
| 1278 | $name = $tempTable->getName(); |
| 1279 | // Developers may force tables to be durable to assist in debugging so lets check. |
| 1280 | $isNotTrueTemporary = $tempTable->isDurable(); |
| 1281 | $this->addToDeveloperTab($tempTable->getCreateSql()); |
| 1282 | $this->temporaryTables[$identifier] = ['temporary' => !$isNotTrueTemporary, 'name' => $name]; |
| 1283 | return $name; |
| 1284 | } |
| 1285 | |
| 1286 | /** |
| 1287 | * Add columns to report. |
| 1288 | */ |
| 1289 | public function addColumns() { |
| 1290 | $options = []; |
| 1291 | $colGroups = NULL; |
| 1292 | foreach ($this->_columns as $tableName => $table) { |
| 1293 | if (array_key_exists('fields', $table)) { |
| 1294 | foreach ($table['fields'] as $fieldName => $field) { |
| 1295 | $groupTitle = ''; |
| 1296 | if (empty($field['no_display'])) { |
| 1297 | foreach (['table', 'field'] as $var) { |
| 1298 | if (!empty(${$var}['grouping'])) { |
| 1299 | if (!is_array(${$var}['grouping'])) { |
| 1300 | $tableName = ${$var}['grouping']; |
| 1301 | } |
| 1302 | else { |
| 1303 | $tableName = array_keys(${$var}['grouping']); |
| 1304 | $tableName = $tableName[0]; |
| 1305 | $groupTitle = array_values(${$var}['grouping']); |
| 1306 | $groupTitle = $groupTitle[0]; |
| 1307 | } |
| 1308 | } |
| 1309 | } |
| 1310 | |
| 1311 | if (!$groupTitle && isset($table['group_title'])) { |
| 1312 | $groupTitle = $table['group_title']; |
| 1313 | // Having a group_title is secret code for being a custom group |
| 1314 | // which cryptically translates to needing an accordion. |
| 1315 | // here we make that explicit. |
| 1316 | $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE; |
| 1317 | } |
| 1318 | |
| 1319 | $colGroups[$tableName]['fields'][$fieldName] = $field['title'] ?? NULL; |
| 1320 | if ($groupTitle && empty($colGroups[$tableName]['group_title'])) { |
| 1321 | $colGroups[$tableName]['group_title'] = $groupTitle; |
| 1322 | } |
| 1323 | $options[$fieldName] = $field['title'] ?? NULL; |
| 1324 | } |
| 1325 | } |
| 1326 | } |
| 1327 | } |
| 1328 | |
| 1329 | $this->addCheckBox("fields", ts('Select Columns'), $options, NULL, |
| 1330 | NULL, NULL, NULL, $this->_fourColumnAttribute, TRUE |
| 1331 | ); |
| 1332 | if (!empty($colGroups)) { |
| 1333 | $this->tabs['FieldSelection'] = [ |
| 1334 | 'title' => ts('Columns'), |
| 1335 | 'tpl' => 'FieldSelection', |
| 1336 | 'div_label' => 'col-groups', |
| 1337 | ]; |
| 1338 | |
| 1339 | // Note this assignment is only really required in buildForm. It is being 'over-called' |
| 1340 | // to reduce risk of being missed due to overridden functions. |
| 1341 | $this->assign('tabs', $this->tabs); |
| 1342 | } |
| 1343 | |
| 1344 | $this->assign('colGroups', $colGroups); |
| 1345 | } |
| 1346 | |
| 1347 | /** |
| 1348 | * Add filters to report. |
| 1349 | */ |
| 1350 | public function addFilters() { |
| 1351 | $filters = $filterGroups = []; |
| 1352 | |
| 1353 | foreach ($this->_filters as $table => $attributes) { |
| 1354 | $groupingKey = $this->_columns[$table]['grouping'] ?? ''; |
| 1355 | $filterGroups[$groupingKey]['tables'][$table] = []; |
| 1356 | // If a prior table hasn't set group title then set it. |
| 1357 | if (empty($filterGroups[$groupingKey]['group_title'])) { |
| 1358 | $filterGroups[$groupingKey]['group_title'] = $this->_columns[$table]['group_title'] ?? ''; |
| 1359 | } |
| 1360 | // The presence of 'group_title' is secret code for 'display in an accordion' |
| 1361 | // here we make this explicit. |
| 1362 | if (!isset($filterGroups[$groupingKey]['use_accordion_for_field_selection'])) { |
| 1363 | if (isset($this->_columns[$table]['use_accordion_for_field_selection'])) { |
| 1364 | $filterGroups[$groupingKey]['use_accordion_for_field_selection'] = $this->_columns[$table]['use_accordion_for_field_selection']; |
| 1365 | } |
| 1366 | else { |
| 1367 | $filterGroups[$groupingKey]['use_accordion_for_field_selection'] = isset($this->_columns[$table]['group_title']); |
| 1368 | } |
| 1369 | } |
| 1370 | |
| 1371 | foreach ($attributes as $fieldName => $field) { |
| 1372 | $filterGroups[$groupingKey]['tables'][$table][$fieldName] = $field; |
| 1373 | // Filters is deprecated in favour of filterGroups. |
| 1374 | $filters[$table][$fieldName] = $field; |
| 1375 | // get ready with option value pair |
| 1376 | // @ todo being able to specific options for a field (e.g a date field) in the field spec as an array rather than an override |
| 1377 | // would be useful |
| 1378 | $operations = $this->getOperationPair( |
| 1379 | CRM_Utils_Array::value('operatorType', $field), |
| 1380 | $fieldName); |
| 1381 | |
| 1382 | switch (CRM_Utils_Array::value('operatorType', $field)) { |
| 1383 | case CRM_Report_Form::OP_MONTH: |
| 1384 | if (!array_key_exists('options', $field) || |
| 1385 | !is_array($field['options']) || empty($field['options']) |
| 1386 | ) { |
| 1387 | // If there's no option list for this filter, define one. |
| 1388 | $field['options'] = CRM_Utils_Date::getFullMonthNames(); |
| 1389 | |
| 1390 | // Add this option list to this column _columns. This is |
| 1391 | // required so that filter statistics show properly. |
| 1392 | $this->_columns[$table]['filters'][$fieldName]['options'] = $field['options']; |
| 1393 | } |
| 1394 | case CRM_Report_Form::OP_MULTISELECT: |
| 1395 | case CRM_Report_Form::OP_MULTISELECT_SEPARATOR: |
| 1396 | // assume a multi-select field |
| 1397 | if (!empty($field['options']) || |
| 1398 | $fieldName == 'state_province_id' || $fieldName == 'county_id' |
| 1399 | ) { |
| 1400 | $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations, |
| 1401 | array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );") |
| 1402 | ); |
| 1403 | |
| 1404 | if (count($operations) <= 1) { |
| 1405 | $element->freeze(); |
| 1406 | } |
| 1407 | if ($fieldName == 'state_province_id' || |
| 1408 | $fieldName == 'county_id' |
| 1409 | ) { |
| 1410 | $this->addChainSelect($fieldName . '_value', [ |
| 1411 | 'multiple' => TRUE, |
| 1412 | 'label' => NULL, |
| 1413 | 'class' => 'huge', |
| 1414 | ]); |
| 1415 | } |
| 1416 | else { |
| 1417 | $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], [ |
| 1418 | 'style' => 'min-width:250px', |
| 1419 | 'class' => 'crm-select2 huge', |
| 1420 | 'multiple' => TRUE, |
| 1421 | 'placeholder' => ts('- select -'), |
| 1422 | ]); |
| 1423 | } |
| 1424 | } |
| 1425 | break; |
| 1426 | |
| 1427 | case CRM_Report_Form::OP_SELECT: |
| 1428 | // assume a select field |
| 1429 | $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations); |
| 1430 | if (!empty($field['options'])) { |
| 1431 | $this->addElement('select', "{$fieldName}_value", NULL, $field['options']); |
| 1432 | } |
| 1433 | break; |
| 1434 | |
| 1435 | case CRM_Report_Form::OP_ENTITYREF: |
| 1436 | $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations); |
| 1437 | $this->setEntityRefDefaults($field, $table); |
| 1438 | $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']); |
| 1439 | break; |
| 1440 | |
| 1441 | case CRM_Report_Form::OP_DATE: |
| 1442 | // build datetime fields |
| 1443 | $this->addDatePickerRange($fieldName, $field['title'], FALSE, FALSE, 'From', 'To', $operations, '_to', '_from'); |
| 1444 | break; |
| 1445 | |
| 1446 | case CRM_Report_Form::OP_DATETIME: |
| 1447 | // build datetime fields |
| 1448 | $this->addDatePickerRange($fieldName, $field['title'], TRUE, FALSE, 'From', 'To', $operations, '_to', '_from'); |
| 1449 | break; |
| 1450 | |
| 1451 | case CRM_Report_Form::OP_INT: |
| 1452 | case CRM_Report_Form::OP_FLOAT: |
| 1453 | // and a min value input box |
| 1454 | $this->add('text', "{$fieldName}_min", ts('Min')); |
| 1455 | // and a max value input box |
| 1456 | $this->add('text', "{$fieldName}_max", ts('Max')); |
| 1457 | default: |
| 1458 | // default type is string |
| 1459 | $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations, |
| 1460 | ['onchange' => "return showHideMaxMinVal( '$fieldName', this.value );"] |
| 1461 | ); |
| 1462 | // we need text box for value input |
| 1463 | $this->add('text', "{$fieldName}_value", NULL, ['class' => 'huge']); |
| 1464 | break; |
| 1465 | } |
| 1466 | } |
| 1467 | } |
| 1468 | if (!empty($filterGroups)) { |
| 1469 | $this->tabs['Filters'] = [ |
| 1470 | 'title' => ts('Filters'), |
| 1471 | 'tpl' => 'Filters', |
| 1472 | 'div_label' => 'set-filters', |
| 1473 | ]; |
| 1474 | } |
| 1475 | $this->assign('filterGroups', $filterGroups); |
| 1476 | // Filters is deprecated in favour of filterGroups. |
| 1477 | $this->assign('filters', $filters); |
| 1478 | } |
| 1479 | |
| 1480 | /** |
| 1481 | * Function to assign the tabs to the template in the correct order. |
| 1482 | * |
| 1483 | * We want the tabs to wind up in this order (if not overridden). |
| 1484 | * |
| 1485 | * - Field Selection |
| 1486 | * - Group Bys |
| 1487 | * - Order Bys |
| 1488 | * - Other Options |
| 1489 | * - Filters |
| 1490 | */ |
| 1491 | protected function assignTabs() { |
| 1492 | $order = [ |
| 1493 | 'FieldSelection', |
| 1494 | 'GroupBy', |
| 1495 | 'OrderBy', |
| 1496 | 'ReportOptions', |
| 1497 | 'Filters', |
| 1498 | ]; |
| 1499 | $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs); |
| 1500 | $order = array_merge($order, $this->tabs); |
| 1501 | $this->assign('tabs', $order); |
| 1502 | } |
| 1503 | |
| 1504 | /** |
| 1505 | * The intent is to add a tab for developers to view the sql. |
| 1506 | * |
| 1507 | * Currently using dpm. |
| 1508 | * |
| 1509 | * @param string $sql |
| 1510 | */ |
| 1511 | public function addToDeveloperTab($sql) { |
| 1512 | if (!CRM_Core_Permission::check('view report sql')) { |
| 1513 | return; |
| 1514 | } |
| 1515 | $ignored_output_modes = ['pdf', 'csv', 'print']; |
| 1516 | if (in_array($this->_outputMode, $ignored_output_modes)) { |
| 1517 | return; |
| 1518 | } |
| 1519 | $this->tabs['Developer'] = [ |
| 1520 | 'title' => ts('Developer'), |
| 1521 | 'tpl' => 'Developer', |
| 1522 | 'div_label' => 'set-developer', |
| 1523 | ]; |
| 1524 | |
| 1525 | $this->assignTabs(); |
| 1526 | $this->sqlFormattedArray = []; |
| 1527 | $this->sqlArray[] = $sql; |
| 1528 | foreach ($this->sqlArray as $sql) { |
| 1529 | foreach (['LEFT JOIN'] as $term) { |
| 1530 | $sql = str_replace($term, '<br> ' . $term, $sql); |
| 1531 | } |
| 1532 | foreach (['FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';'] as $term) { |
| 1533 | $sql = str_replace($term, '<br><br>' . $term, $sql); |
| 1534 | } |
| 1535 | $this->sqlFormattedArray[] = $sql; |
| 1536 | $this->assign('sql', implode(';<br><br><br><br>', $this->sqlFormattedArray)); |
| 1537 | } |
| 1538 | $this->assign('sqlModes', $sqlModes = CRM_Utils_SQL::getSqlModes()); |
| 1539 | |
| 1540 | } |
| 1541 | |
| 1542 | /** |
| 1543 | * Add options defined in $this->_options to the report. |
| 1544 | */ |
| 1545 | public function addOptions() { |
| 1546 | if (!empty($this->_options)) { |
| 1547 | // FIXME: For now lets build all elements as checkboxes. |
| 1548 | // Once we clear with the format we can build elements based on type |
| 1549 | |
| 1550 | foreach ($this->_options as $fieldName => $field) { |
| 1551 | $options = []; |
| 1552 | |
| 1553 | if ($field['type'] == 'select') { |
| 1554 | $this->addElement('select', "{$fieldName}", $field['title'], $field['options']); |
| 1555 | } |
| 1556 | elseif ($field['type'] == 'checkbox') { |
| 1557 | $options[$field['title']] = $fieldName; |
| 1558 | $this->addCheckBox($fieldName, NULL, |
| 1559 | $options, NULL, |
| 1560 | NULL, NULL, NULL, $this->_fourColumnAttribute |
| 1561 | ); |
| 1562 | } |
| 1563 | } |
| 1564 | } |
| 1565 | if (!empty($this->_options) && |
| 1566 | (!$this->_id |
| 1567 | || ($this->_id && CRM_Report_BAO_ReportInstance::contactCanAdministerReport($this->_id))) |
| 1568 | ) { |
| 1569 | $this->tabs['ReportOptions'] = [ |
| 1570 | 'title' => ts('Display Options'), |
| 1571 | 'tpl' => 'ReportOptions', |
| 1572 | 'div_label' => 'other-options', |
| 1573 | ]; |
| 1574 | } |
| 1575 | $this->assign('otherOptions', $this->_options); |
| 1576 | } |
| 1577 | |
| 1578 | /** |
| 1579 | * Add chart options to the report. |
| 1580 | */ |
| 1581 | public function addChartOptions() { |
| 1582 | if (!empty($this->_charts)) { |
| 1583 | $this->addElement('select', "charts", ts('Chart'), $this->_charts); |
| 1584 | $this->assign('charts', $this->_charts); |
| 1585 | $this->addElement('xbutton', $this->_chartButtonName, ts('View'), ['type' => 'submit']); |
| 1586 | } |
| 1587 | } |
| 1588 | |
| 1589 | /** |
| 1590 | * Add group by options to the report. |
| 1591 | */ |
| 1592 | public function addGroupBys() { |
| 1593 | $options = $freqElements = []; |
| 1594 | |
| 1595 | foreach ($this->_columns as $tableName => $table) { |
| 1596 | if (array_key_exists('group_bys', $table)) { |
| 1597 | foreach ($table['group_bys'] as $fieldName => $field) { |
| 1598 | if (!empty($field) && empty($field['no_display'])) { |
| 1599 | $options[$field['title']] = $fieldName; |
| 1600 | if (!empty($field['frequency'])) { |
| 1601 | $freqElements[$field['title']] = $fieldName; |
| 1602 | } |
| 1603 | } |
| 1604 | } |
| 1605 | } |
| 1606 | } |
| 1607 | $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL, |
| 1608 | NULL, NULL, NULL, $this->_fourColumnAttribute |
| 1609 | ); |
| 1610 | $this->assign('groupByElements', $options); |
| 1611 | if (!empty($options)) { |
| 1612 | $this->tabs['GroupBy'] = [ |
| 1613 | 'title' => ts('Grouping'), |
| 1614 | 'tpl' => 'GroupBy', |
| 1615 | 'div_label' => 'group-by-elements', |
| 1616 | ]; |
| 1617 | } |
| 1618 | |
| 1619 | foreach ($freqElements as $name) { |
| 1620 | $this->addElement('select', "group_bys_freq[$name]", |
| 1621 | ts('Frequency'), $this->_groupByDateFreq |
| 1622 | ); |
| 1623 | } |
| 1624 | } |
| 1625 | |
| 1626 | /** |
| 1627 | * Add data for order by tab. |
| 1628 | */ |
| 1629 | public function addOrderBys() { |
| 1630 | $options = []; |
| 1631 | foreach ($this->_columns as $tableName => $table) { |
| 1632 | |
| 1633 | // Report developer may define any column to order by; include these as order-by options. |
| 1634 | if (array_key_exists('order_bys', $table)) { |
| 1635 | foreach ($table['order_bys'] as $fieldName => $field) { |
| 1636 | if (!empty($field)) { |
| 1637 | $options[$fieldName] = $field['title']; |
| 1638 | } |
| 1639 | } |
| 1640 | } |
| 1641 | |
| 1642 | // Add searchable custom fields as order-by options, if so requested |
| 1643 | // (These are already indexed, so allowing to order on them is cheap.) |
| 1644 | |
| 1645 | if ($this->_autoIncludeIndexedFieldsAsOrderBys && |
| 1646 | array_key_exists('extends', $table) && !empty($table['extends']) |
| 1647 | ) { |
| 1648 | foreach ($table['fields'] as $fieldName => $field) { |
| 1649 | if (empty($field['no_display'])) { |
| 1650 | $options[$fieldName] = $field['title']; |
| 1651 | } |
| 1652 | } |
| 1653 | } |
| 1654 | } |
| 1655 | |
| 1656 | asort($options); |
| 1657 | |
| 1658 | $this->assign('orderByOptions', $options); |
| 1659 | if (!empty($options)) { |
| 1660 | $this->tabs['OrderBy'] = [ |
| 1661 | 'title' => ts('Sorting'), |
| 1662 | 'tpl' => 'OrderBy', |
| 1663 | 'div_label' => 'order-by-elements', |
| 1664 | ]; |
| 1665 | } |
| 1666 | |
| 1667 | if (!empty($options)) { |
| 1668 | $options = [ |
| 1669 | '-' => ts(' - none - '), |
| 1670 | ] + $options; |
| 1671 | for ($i = 1; $i <= 5; $i++) { |
| 1672 | $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options); |
| 1673 | $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), [ |
| 1674 | 'ASC' => ts('Ascending'), |
| 1675 | 'DESC' => ts('Descending'), |
| 1676 | ]); |
| 1677 | $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, ['id' => "order_by_section_$i"]); |
| 1678 | $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, ['id' => "order_by_pagebreak_$i"]); |
| 1679 | } |
| 1680 | } |
| 1681 | } |
| 1682 | |
| 1683 | /** |
| 1684 | * This adds the tab referred to as Title and Format, rendered through Instance.tpl. |
| 1685 | * |
| 1686 | * @todo call this tab into the report template in the same way as OrderBy etc, ie |
| 1687 | * by adding a description of the tab to $this->tabs, causing the tab to be added in |
| 1688 | * Criteria.tpl. |
| 1689 | */ |
| 1690 | public function buildInstanceAndButtons() { |
| 1691 | CRM_Report_Form_Instance::buildForm($this); |
| 1692 | $this->_actionButtonName = $this->getButtonName('submit'); |
| 1693 | $this->addTaskMenu($this->getActions($this->_id)); |
| 1694 | |
| 1695 | $this->assign('instanceForm', $this->_instanceForm); |
| 1696 | |
| 1697 | // CRM-16274 Determine if user has 'edit all contacts' or equivalent |
| 1698 | $permission = CRM_Core_Permission::getPermission(); |
| 1699 | if ($this->_instanceForm && $permission == CRM_Core_Permission::EDIT && |
| 1700 | $this->_add2groupSupported |
| 1701 | ) { |
| 1702 | $this->addElement('select', 'groups', ts('Group'), |
| 1703 | ['' => ts('Add Contacts to Group')] + |
| 1704 | CRM_Core_PseudoConstant::nestedGroup(), |
| 1705 | ['class' => 'crm-select2 crm-action-menu fa-plus huge'] |
| 1706 | ); |
| 1707 | $this->assign('group', TRUE); |
| 1708 | } |
| 1709 | |
| 1710 | $this->addElement('xbutton', $this->_groupButtonName, '', [ |
| 1711 | 'type' => 'submit', |
| 1712 | 'style' => 'display: none;', |
| 1713 | ]); |
| 1714 | |
| 1715 | $this->addChartOptions(); |
| 1716 | $showResultsLabel = $this->getResultsLabel(); |
| 1717 | $this->addButtons([ |
| 1718 | [ |
| 1719 | 'type' => 'submit', |
| 1720 | 'name' => $showResultsLabel, |
| 1721 | 'isDefault' => TRUE, |
| 1722 | ], |
| 1723 | ]); |
| 1724 | } |
| 1725 | |
| 1726 | /** |
| 1727 | * Has this form been submitted already? |
| 1728 | * |
| 1729 | * @return bool |
| 1730 | */ |
| 1731 | public function resultsDisplayed() { |
| 1732 | $buttonName = $this->controller->getButtonName(); |
| 1733 | return ($buttonName || $this->_outputMode); |
| 1734 | } |
| 1735 | |
| 1736 | /** |
| 1737 | * Get the actions for this report instance. |
| 1738 | * |
| 1739 | * @param int $instanceId |
| 1740 | * |
| 1741 | * @return array |
| 1742 | */ |
| 1743 | protected function getActions($instanceId) { |
| 1744 | $actions = CRM_Report_BAO_ReportInstance::getActionMetadata(); |
| 1745 | if (empty($instanceId)) { |
| 1746 | $actions['report_instance.save'] = [ |
| 1747 | 'title' => ts('Create Report'), |
| 1748 | 'data' => [ |
| 1749 | 'is_confirm' => TRUE, |
| 1750 | 'confirm_title' => ts('Create Report'), |
| 1751 | 'confirm_refresh_fields' => json_encode([ |
| 1752 | 'title' => ['selector' => '.crm-report-instanceForm-form-block-title', 'prepend' => ''], |
| 1753 | 'description' => ['selector' => '.crm-report-instanceForm-form-block-description', 'prepend' => ''], |
| 1754 | ]), |
| 1755 | ], |
| 1756 | ]; |
| 1757 | unset($actions['report_instance.delete']); |
| 1758 | } |
| 1759 | |
| 1760 | if (!$this->_csvSupported) { |
| 1761 | unset($actions['report_instance.csv']); |
| 1762 | } |
| 1763 | |
| 1764 | CRM_Utils_Hook::alterReportVar('actions', $actions, $this); |
| 1765 | |
| 1766 | return $actions; |
| 1767 | } |
| 1768 | |
| 1769 | /** |
| 1770 | * Main build form function. |
| 1771 | */ |
| 1772 | public function buildQuickForm() { |
| 1773 | $this->addColumns(); |
| 1774 | |
| 1775 | $this->addFilters(); |
| 1776 | |
| 1777 | $this->addOptions(); |
| 1778 | |
| 1779 | $this->addGroupBys(); |
| 1780 | |
| 1781 | $this->addOrderBys(); |
| 1782 | |
| 1783 | $this->buildInstanceAndButtons(); |
| 1784 | |
| 1785 | // Add form rule for report. |
| 1786 | if (is_callable([ |
| 1787 | $this, |
| 1788 | 'formRule', |
| 1789 | ])) { |
| 1790 | $this->addFormRule([get_class($this), 'formRule'], $this); |
| 1791 | } |
| 1792 | $this->assignTabs(); |
| 1793 | } |
| 1794 | |
| 1795 | /** |
| 1796 | * A form rule function for custom data. |
| 1797 | * |
| 1798 | * The rule ensures that fields selected in group_by if any) should only be the ones |
| 1799 | * present in display/select fields criteria; |
| 1800 | * note: works if and only if any custom field selected in group_by. |
| 1801 | * |
| 1802 | * @param array $fields |
| 1803 | * @param array $ignoreFields |
| 1804 | * |
| 1805 | * @return array |
| 1806 | */ |
| 1807 | public function customDataFormRule($fields, $ignoreFields = []) { |
| 1808 | $errors = []; |
| 1809 | if (!empty($this->_customGroupExtends) && $this->_customGroupGroupBy && |
| 1810 | !empty($fields['group_bys']) |
| 1811 | ) { |
| 1812 | foreach ($this->_columns as $tableName => $table) { |
| 1813 | if ((substr($tableName, 0, 13) == 'civicrm_value' || |
| 1814 | substr($tableName, 0, 12) == 'custom_value') && |
| 1815 | !empty($this->_columns[$tableName]['fields']) |
| 1816 | ) { |
| 1817 | foreach ($this->_columns[$tableName]['fields'] as $fieldName => $field) { |
| 1818 | if (array_key_exists($fieldName, $fields['group_bys']) && |
| 1819 | !array_key_exists($fieldName, $fields['fields']) |
| 1820 | ) { |
| 1821 | $errors['fields'] = ts("Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section."); |
| 1822 | } |
| 1823 | elseif (array_key_exists($fieldName, $fields['group_bys'])) { |
| 1824 | foreach ($fields['fields'] as $fld => $val) { |
| 1825 | if (!array_key_exists($fld, $fields['group_bys']) && |
| 1826 | !in_array($fld, $ignoreFields) |
| 1827 | ) { |
| 1828 | $errors['fields'] = ts("Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section."); |
| 1829 | } |
| 1830 | } |
| 1831 | } |
| 1832 | } |
| 1833 | } |
| 1834 | } |
| 1835 | } |
| 1836 | return $errors; |
| 1837 | } |
| 1838 | |
| 1839 | /** |
| 1840 | * Get operators to display on form. |
| 1841 | * |
| 1842 | * Note: $fieldName param allows inheriting class to build operationPairs specific to a field. |
| 1843 | * |
| 1844 | * @param int|string $type |
| 1845 | * @param string $fieldName |
| 1846 | * |
| 1847 | * @return array |
| 1848 | */ |
| 1849 | public function getOperationPair($type = "string", $fieldName = NULL) { |
| 1850 | // FIXME: At some point we should move these key-val pairs |
| 1851 | // to option_group and option_value table. |
| 1852 | switch ($type) { |
| 1853 | case CRM_Report_Form::OP_INT: |
| 1854 | case CRM_Report_Form::OP_FLOAT: |
| 1855 | |
| 1856 | $result = [ |
| 1857 | 'lte' => ts('Is less than or equal to'), |
| 1858 | 'gte' => ts('Is greater than or equal to'), |
| 1859 | 'bw' => ts('Is between'), |
| 1860 | 'eq' => ts('Is equal to'), |
| 1861 | 'lt' => ts('Is less than'), |
| 1862 | 'gt' => ts('Is greater than'), |
| 1863 | 'neq' => ts('Is not equal to'), |
| 1864 | 'nbw' => ts('Is not between'), |
| 1865 | 'nll' => ts('Is empty (Null)'), |
| 1866 | 'nnll' => ts('Is not empty (Null)'), |
| 1867 | ]; |
| 1868 | return $result; |
| 1869 | |
| 1870 | case CRM_Report_Form::OP_SELECT: |
| 1871 | $result = [ |
| 1872 | 'eq' => ts('Is equal to'), |
| 1873 | ]; |
| 1874 | return $result; |
| 1875 | |
| 1876 | case CRM_Report_Form::OP_MONTH: |
| 1877 | case CRM_Report_Form::OP_MULTISELECT: |
| 1878 | case CRM_Report_Form::OP_ENTITYREF: |
| 1879 | |
| 1880 | $result = [ |
| 1881 | 'in' => ts('Is one of'), |
| 1882 | 'notin' => ts('Is not one of'), |
| 1883 | 'nll' => ts('Is empty (Null)'), |
| 1884 | 'nnll' => ts('Is not empty (Null)'), |
| 1885 | ]; |
| 1886 | return $result; |
| 1887 | |
| 1888 | case CRM_Report_Form::OP_DATE: |
| 1889 | |
| 1890 | $result = [ |
| 1891 | 'nll' => ts('Is empty (Null)'), |
| 1892 | 'nnll' => ts('Is not empty (Null)'), |
| 1893 | ]; |
| 1894 | return $result; |
| 1895 | |
| 1896 | case CRM_Report_Form::OP_MULTISELECT_SEPARATOR: |
| 1897 | // use this operator for the values, concatenated with separator. For e.g if |
| 1898 | // multiple options for a column is stored as ^A{val1}^A{val2}^A |
| 1899 | $result = [ |
| 1900 | 'mhas' => ts('Is one of'), |
| 1901 | 'mnot' => ts('Is not one of'), |
| 1902 | 'nll' => ts('Is empty (Null)'), |
| 1903 | 'nnll' => ts('Is not empty (Null)'), |
| 1904 | ]; |
| 1905 | return $result; |
| 1906 | |
| 1907 | default: |
| 1908 | // type is string |
| 1909 | $result = [ |
| 1910 | 'has' => ts('Contains'), |
| 1911 | 'sw' => ts('Starts with'), |
| 1912 | 'ew' => ts('Ends with'), |
| 1913 | 'nhas' => ts('Does not contain'), |
| 1914 | 'eq' => ts('Is equal to'), |
| 1915 | 'neq' => ts('Is not equal to'), |
| 1916 | 'nll' => ts('Is empty (Null)'), |
| 1917 | 'nnll' => ts('Is not empty (Null)'), |
| 1918 | ]; |
| 1919 | return $result; |
| 1920 | } |
| 1921 | } |
| 1922 | |
| 1923 | /** |
| 1924 | * Build the tag filter field to display on the filters tab. |
| 1925 | */ |
| 1926 | public function buildTagFilter() { |
| 1927 | $contactTags = CRM_Core_BAO_Tag::getTags($this->_tagFilterTable); |
| 1928 | if (!empty($contactTags)) { |
| 1929 | $this->_columns['civicrm_tag'] = [ |
| 1930 | 'dao' => 'CRM_Core_DAO_Tag', |
| 1931 | 'filters' => [ |
| 1932 | 'tagid' => [ |
| 1933 | 'name' => 'tag_id', |
| 1934 | 'title' => ts('Tag'), |
| 1935 | 'type' => CRM_Utils_Type::T_INT, |
| 1936 | 'tag' => TRUE, |
| 1937 | 'operatorType' => CRM_Report_Form::OP_MULTISELECT, |
| 1938 | 'options' => $contactTags, |
| 1939 | ], |
| 1940 | ], |
| 1941 | ]; |
| 1942 | } |
| 1943 | } |
| 1944 | |
| 1945 | /** |
| 1946 | * Adds group filters to _columns (called from _Construct). |
| 1947 | */ |
| 1948 | public function buildGroupFilter() { |
| 1949 | $this->_columns['civicrm_group']['filters'] = [ |
| 1950 | 'gid' => [ |
| 1951 | 'name' => 'group_id', |
| 1952 | 'title' => ts('Group'), |
| 1953 | 'type' => CRM_Utils_Type::T_INT, |
| 1954 | 'operatorType' => CRM_Report_Form::OP_MULTISELECT, |
| 1955 | 'group' => TRUE, |
| 1956 | 'options' => CRM_Core_PseudoConstant::nestedGroup(), |
| 1957 | ], |
| 1958 | ]; |
| 1959 | if (empty($this->_columns['civicrm_group']['dao'])) { |
| 1960 | $this->_columns['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact'; |
| 1961 | } |
| 1962 | if (empty($this->_columns['civicrm_group']['alias'])) { |
| 1963 | $this->_columns['civicrm_group']['alias'] = 'cgroup'; |
| 1964 | } |
| 1965 | } |
| 1966 | |
| 1967 | /** |
| 1968 | * Get SQL operator from form text version. |
| 1969 | * |
| 1970 | * @param string $operator |
| 1971 | * |
| 1972 | * @return string |
| 1973 | */ |
| 1974 | public function getSQLOperator($operator = "like") { |
| 1975 | switch ($operator) { |
| 1976 | case 'eq': |
| 1977 | return '='; |
| 1978 | |
| 1979 | case 'lt': |
| 1980 | return '<'; |
| 1981 | |
| 1982 | case 'lte': |
| 1983 | return '<='; |
| 1984 | |
| 1985 | case 'gt': |
| 1986 | return '>'; |
| 1987 | |
| 1988 | case 'gte': |
| 1989 | return '>='; |
| 1990 | |
| 1991 | case 'ne': |
| 1992 | case 'neq': |
| 1993 | return '!='; |
| 1994 | |
| 1995 | case 'nhas': |
| 1996 | return 'NOT LIKE'; |
| 1997 | |
| 1998 | case 'in': |
| 1999 | return 'IN'; |
| 2000 | |
| 2001 | case 'notin': |
| 2002 | return 'NOT IN'; |
| 2003 | |
| 2004 | case 'nll': |
| 2005 | return 'IS NULL'; |
| 2006 | |
| 2007 | case 'nnll': |
| 2008 | return 'IS NOT NULL'; |
| 2009 | |
| 2010 | default: |
| 2011 | // type is string |
| 2012 | return 'LIKE'; |
| 2013 | } |
| 2014 | } |
| 2015 | |
| 2016 | /** |
| 2017 | * Generate where clause. |
| 2018 | * |
| 2019 | * This can be overridden in reports for special treatment of a field |
| 2020 | * |
| 2021 | * @param array $field Field specifications |
| 2022 | * @param string $op Query operator (not an exact match to sql) |
| 2023 | * @param mixed $value |
| 2024 | * @param float $min |
| 2025 | * @param float $max |
| 2026 | * |
| 2027 | * @return null|string |
| 2028 | */ |
| 2029 | public function whereClause(&$field, $op, $value, $min, $max) { |
| 2030 | |
| 2031 | $type = CRM_Utils_Type::typeToString(CRM_Utils_Array::value('type', $field)); |
| 2032 | |
| 2033 | // CRM-18010: Ensure type of each report filters |
| 2034 | if (!$type) { |
| 2035 | trigger_error('Type is not defined for field ' . $field['name'], E_USER_WARNING); |
| 2036 | } |
| 2037 | $clause = NULL; |
| 2038 | |
| 2039 | switch ($op) { |
| 2040 | case 'bw': |
| 2041 | case 'nbw': |
| 2042 | if (($min !== NULL && strlen($min) > 0) || |
| 2043 | ($max !== NULL && strlen($max) > 0) |
| 2044 | ) { |
| 2045 | $clauses = []; |
| 2046 | if ($min) { |
| 2047 | $min = CRM_Utils_Type::escape($min, $type); |
| 2048 | if ($op == 'bw') { |
| 2049 | $clauses[] = "( {$field['dbAlias']} >= $min )"; |
| 2050 | } |
| 2051 | else { |
| 2052 | $clauses[] = "( {$field['dbAlias']} < $min OR {$field['dbAlias']} IS NULL )"; |
| 2053 | } |
| 2054 | } |
| 2055 | if ($max) { |
| 2056 | $max = CRM_Utils_Type::escape($max, $type); |
| 2057 | if ($op == 'bw') { |
| 2058 | $clauses[] = "( {$field['dbAlias']} <= $max )"; |
| 2059 | } |
| 2060 | else { |
| 2061 | $clauses[] = "( {$field['dbAlias']} > $max )"; |
| 2062 | } |
| 2063 | } |
| 2064 | |
| 2065 | if (!empty($clauses)) { |
| 2066 | if ($op == 'bw') { |
| 2067 | $clause = implode(' AND ', $clauses); |
| 2068 | } |
| 2069 | else { |
| 2070 | $clause = '(' . implode('OR', $clauses) . ')'; |
| 2071 | } |
| 2072 | } |
| 2073 | } |
| 2074 | break; |
| 2075 | |
| 2076 | case 'has': |
| 2077 | case 'nhas': |
| 2078 | if ($value !== NULL && strlen($value) > 0) { |
| 2079 | $value = CRM_Utils_Type::escape($value, $type); |
| 2080 | if (strpos($value, '%') === FALSE) { |
| 2081 | $value = "'%{$value}%'"; |
| 2082 | } |
| 2083 | else { |
| 2084 | $value = "'{$value}'"; |
| 2085 | } |
| 2086 | $sqlOP = $this->getSQLOperator($op); |
| 2087 | $clause = "( {$field['dbAlias']} $sqlOP $value )"; |
| 2088 | } |
| 2089 | break; |
| 2090 | |
| 2091 | case 'in': |
| 2092 | case 'notin': |
| 2093 | if ((is_string($value) || is_numeric($value)) && strlen($value)) { |
| 2094 | $value = explode(',', $value); |
| 2095 | } |
| 2096 | if ($value !== NULL && is_array($value) && count($value) > 0) { |
| 2097 | $sqlOP = $this->getSQLOperator($op); |
| 2098 | if (CRM_Utils_Array::value('type', $field) == |
| 2099 | CRM_Utils_Type::T_STRING |
| 2100 | ) { |
| 2101 | //cycle through selections and escape values |
| 2102 | foreach ($value as $key => $selection) { |
| 2103 | $value[$key] = CRM_Utils_Type::escape($selection, $type); |
| 2104 | } |
| 2105 | $clause |
| 2106 | = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . |
| 2107 | "') )"; |
| 2108 | } |
| 2109 | else { |
| 2110 | // for numerical values |
| 2111 | $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . |
| 2112 | ")"; |
| 2113 | } |
| 2114 | if ($op == 'notin') { |
| 2115 | $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )"; |
| 2116 | } |
| 2117 | else { |
| 2118 | $clause = "( " . $clause . " )"; |
| 2119 | } |
| 2120 | } |
| 2121 | break; |
| 2122 | |
| 2123 | case 'mhas': |
| 2124 | case 'mnot': |
| 2125 | // multiple has or multiple not |
| 2126 | if ($value !== NULL && count($value) > 0) { |
| 2127 | $value = CRM_Utils_Type::escapeAll($value, $type); |
| 2128 | $operator = $op == 'mnot' ? 'NOT' : ''; |
| 2129 | $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', (array) $value) . "([[:cntrl:]]|$)"; |
| 2130 | $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'"; |
| 2131 | } |
| 2132 | break; |
| 2133 | |
| 2134 | case 'sw': |
| 2135 | case 'ew': |
| 2136 | if ($value !== NULL && strlen($value) > 0) { |
| 2137 | $value = CRM_Utils_Type::escape($value, $type); |
| 2138 | if (strpos($value, '%') === FALSE) { |
| 2139 | if ($op == 'sw') { |
| 2140 | $value = "'{$value}%'"; |
| 2141 | } |
| 2142 | else { |
| 2143 | $value = "'%{$value}'"; |
| 2144 | } |
| 2145 | } |
| 2146 | else { |
| 2147 | $value = "'{$value}'"; |
| 2148 | } |
| 2149 | $sqlOP = $this->getSQLOperator($op); |
| 2150 | $clause = "( {$field['dbAlias']} $sqlOP $value )"; |
| 2151 | } |
| 2152 | break; |
| 2153 | |
| 2154 | case 'nll': |
| 2155 | if ($type == 'String') { |
| 2156 | $sqlOP = $this->getSQLOperator($op); |
| 2157 | $clause = "( {$field['dbAlias']} $sqlOP OR {$field['dbAlias']} = '' )"; |
| 2158 | } |
| 2159 | else { |
| 2160 | $sqlOP = $this->getSQLOperator($op); |
| 2161 | $clause = "( {$field['dbAlias']} $sqlOP )"; |
| 2162 | } |
| 2163 | break; |
| 2164 | |
| 2165 | case 'nnll': |
| 2166 | if ($type == 'String') { |
| 2167 | $sqlOP = $this->getSQLOperator($op); |
| 2168 | $clause = "( {$field['dbAlias']} $sqlOP AND {$field['dbAlias']} <> '' )"; |
| 2169 | } |
| 2170 | else { |
| 2171 | $sqlOP = $this->getSQLOperator($op); |
| 2172 | $clause = "( {$field['dbAlias']} $sqlOP )"; |
| 2173 | } |
| 2174 | break; |
| 2175 | |
| 2176 | case 'eq': |
| 2177 | case 'neq': |
| 2178 | case 'ne': |
| 2179 | //CRM-18457: some custom field passes value in array format against binary operator |
| 2180 | if (is_array($value) && count($value)) { |
| 2181 | $value = $value[0]; |
| 2182 | } |
| 2183 | |
| 2184 | default: |
| 2185 | if ($value !== NULL && $value !== '') { |
| 2186 | if (isset($field['clause'])) { |
| 2187 | // FIXME: we not doing escape here. Better solution is to use two |
| 2188 | // different types - data-type and filter-type |
| 2189 | $clause = $field['clause']; |
| 2190 | } |
| 2191 | elseif (!is_array($value)) { |
| 2192 | $value = CRM_Utils_Type::escape($value, $type); |
| 2193 | $sqlOP = $this->getSQLOperator($op); |
| 2194 | if ($field['type'] == CRM_Utils_Type::T_STRING) { |
| 2195 | $value = "'{$value}'"; |
| 2196 | } |
| 2197 | $clause = "( {$field['dbAlias']} $sqlOP $value )"; |
| 2198 | } |
| 2199 | } |
| 2200 | break; |
| 2201 | } |
| 2202 | |
| 2203 | //dev/core/544 Add report support for multiple contact subTypes |
| 2204 | if ($field['name'] == 'contact_sub_type' && $clause) { |
| 2205 | $clause = $this->whereSubtypeClause($field, $value, $op); |
| 2206 | } |
| 2207 | if (!empty($field['group']) && $clause) { |
| 2208 | $clause = $this->whereGroupClause($field, $value, $op); |
| 2209 | } |
| 2210 | elseif (!empty($field['tag']) && $clause) { |
| 2211 | // not using left join in query because if any contact |
| 2212 | // belongs to more than one tag, results duplicate |
| 2213 | // entries. |
| 2214 | $clause = $this->whereTagClause($field, $value, $op); |
| 2215 | } |
| 2216 | elseif (!empty($field['membership_org']) && $clause) { |
| 2217 | $clause = $this->whereMembershipOrgClause($value, $op); |
| 2218 | } |
| 2219 | elseif (!empty($field['membership_type']) && $clause) { |
| 2220 | $clause = $this->whereMembershipTypeClause($value, $op); |
| 2221 | } |
| 2222 | return $clause; |
| 2223 | } |
| 2224 | |
| 2225 | /** |
| 2226 | * Get SQL where clause for contact subtypes |
| 2227 | * @param array $field Field specifications |
| 2228 | * @param mixed $value |
| 2229 | * @param string $op SQL Operator |
| 2230 | * |
| 2231 | * @return string |
| 2232 | */ |
| 2233 | public function whereSubtypeClause($field, $value, $op) { |
| 2234 | // Get the correct SQL operator. |
| 2235 | $orNull = FALSE; |
| 2236 | switch ($op) { |
| 2237 | case 'notin': |
| 2238 | $op = 'nhas'; |
| 2239 | $clauseSeparator = ' AND '; |
| 2240 | $orNull = TRUE; |
| 2241 | break; |
| 2242 | |
| 2243 | case 'in': |
| 2244 | $op = 'has'; |
| 2245 | $clauseSeparator = ' OR '; |
| 2246 | break; |
| 2247 | } |
| 2248 | $sqlOp = $this->getSQLOperator($op); |
| 2249 | if ($sqlOp == 'IS NULL' || $sqlOp == 'IS NOT NULL') { |
| 2250 | $clause = "{$field['dbAlias']} $sqlOp"; |
| 2251 | } |
| 2252 | else { |
| 2253 | $subclauses = []; |
| 2254 | foreach ($value as $item) { |
| 2255 | $subclauses[] = "( {$field['dbAlias']} $sqlOp '%" . CRM_Core_DAO::VALUE_SEPARATOR . $item . CRM_Core_DAO::VALUE_SEPARATOR . "%' )"; |
| 2256 | } |
| 2257 | $clause = implode($clauseSeparator, $subclauses); |
| 2258 | } |
| 2259 | $clause = "( $clause )"; |
| 2260 | if ($orNull) { |
| 2261 | $clause = "( ( {$field['dbAlias']} IS NULL ) OR $clause )"; |
| 2262 | } |
| 2263 | return $clause; |
| 2264 | } |
| 2265 | |
| 2266 | /** |
| 2267 | * Get SQL where clause for a date field. |
| 2268 | * |
| 2269 | * @param string $fieldName |
| 2270 | * @param string $relative |
| 2271 | * @param string $from |
| 2272 | * @param string $to |
| 2273 | * @param string $type |
| 2274 | * @param string $fromTime |
| 2275 | * @param string $toTime |
| 2276 | * |
| 2277 | * @return null|string |
| 2278 | */ |
| 2279 | public function dateClause( |
| 2280 | $fieldName, |
| 2281 | $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL |
| 2282 | ) { |
| 2283 | $clauses = []; |
| 2284 | if (array_key_exists($relative, $this->getOperationPair(CRM_Report_Form::OP_DATE))) { |
| 2285 | $sqlOP = $this->getSQLOperator($relative); |
| 2286 | return "( {$fieldName} {$sqlOP} )"; |
| 2287 | } |
| 2288 | if (strlen($to) === 10) { |
| 2289 | // If we just have the date we assume the end of that day. |
| 2290 | $to .= ' 23:59:59'; |
| 2291 | } |
| 2292 | |
| 2293 | if ($relative) { |
| 2294 | [$from, $to] = $this->getFromTo($relative, $from, $to, $fromTime, $toTime); |
| 2295 | } |
| 2296 | |
| 2297 | if ($from) { |
| 2298 | $clauses[] = "( {$fieldName} >= " . date('YmdHis', strtotime($from)) . ')'; |
| 2299 | } |
| 2300 | |
| 2301 | if ($to) { |
| 2302 | $clauses[] = "( {$fieldName} <= " . date('YmdHis', strtotime($to)) . ')'; |
| 2303 | } |
| 2304 | if (!empty($clauses)) { |
| 2305 | return implode(' AND ', $clauses); |
| 2306 | } |
| 2307 | |
| 2308 | return NULL; |
| 2309 | } |
| 2310 | |
| 2311 | /** |
| 2312 | * Get values for from and to for date ranges. |
| 2313 | * |
| 2314 | * @deprecated |
| 2315 | * |
| 2316 | * @param bool $relative |
| 2317 | * @param string $from |
| 2318 | * @param string $to |
| 2319 | * @param string $fromTime |
| 2320 | * @param string $toTime |
| 2321 | * |
| 2322 | * @return array |
| 2323 | */ |
| 2324 | public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) { |
| 2325 | if (!empty($fromTime) || !empty($toTime)) { |
| 2326 | throw new CRM_Core_Exception('Report template needs to be updated as getFromTo no longer supports fromTime or ToTime Parameters'); |
| 2327 | } |
| 2328 | return CRM_Utils_Date::getFromTo($relative, $from, $to); |
| 2329 | } |
| 2330 | |
| 2331 | /** |
| 2332 | * Alter display of rows. |
| 2333 | * |
| 2334 | * Iterate through the rows retrieved via SQL and make changes for display purposes, |
| 2335 | * such as rendering contacts as links. |
| 2336 | * |
| 2337 | * @param array $rows |
| 2338 | * Rows generated by SQL, with an array for each row. |
| 2339 | */ |
| 2340 | public function alterDisplay(&$rows) { |
| 2341 | } |
| 2342 | |
| 2343 | /** |
| 2344 | * Alter the way in which custom data fields are displayed. |
| 2345 | * |
| 2346 | * @param array $rows |
| 2347 | */ |
| 2348 | public function alterCustomDataDisplay(&$rows) { |
| 2349 | // custom code to alter rows having custom values |
| 2350 | if (empty($this->_customGroupExtends)) { |
| 2351 | return; |
| 2352 | } |
| 2353 | |
| 2354 | $customFields = []; |
| 2355 | $customFieldIds = []; |
| 2356 | foreach ($this->_params['fields'] as $fieldAlias => $value) { |
| 2357 | if ($fieldId = CRM_Core_BAO_CustomField::getKeyID($fieldAlias)) { |
| 2358 | $customFieldIds[$fieldAlias] = $fieldId; |
| 2359 | } |
| 2360 | } |
| 2361 | if (empty($customFieldIds)) { |
| 2362 | return; |
| 2363 | } |
| 2364 | |
| 2365 | // skip for type date and ContactReference since date format is already handled |
| 2366 | $query = " |
| 2367 | SELECT cg.table_name, cf.id |
| 2368 | FROM civicrm_custom_field cf |
| 2369 | INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id |
| 2370 | WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends) . "') AND |
| 2371 | cg.is_active = 1 AND |
| 2372 | cf.is_active = 1 AND |
| 2373 | cf.is_searchable = 1 AND |
| 2374 | cf.data_type NOT IN ('ContactReference', 'Date') AND |
| 2375 | cf.id IN (" . implode(",", $customFieldIds) . ")"; |
| 2376 | |
| 2377 | $dao = CRM_Core_DAO::executeQuery($query); |
| 2378 | while ($dao->fetch()) { |
| 2379 | $customFields[$dao->table_name . '_custom_' . $dao->id] = $dao->id; |
| 2380 | } |
| 2381 | |
| 2382 | $entryFound = FALSE; |
| 2383 | foreach ($rows as $rowNum => $row) { |
| 2384 | foreach ($row as $tableCol => $val) { |
| 2385 | if (array_key_exists($tableCol, $customFields)) { |
| 2386 | $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField::displayValue($val, $customFields[$tableCol]); |
| 2387 | $entryFound = TRUE; |
| 2388 | } |
| 2389 | } |
| 2390 | |
| 2391 | // skip looking further in rows, if first row itself doesn't |
| 2392 | // have the column we need |
| 2393 | if (!$entryFound) { |
| 2394 | break; |
| 2395 | } |
| 2396 | } |
| 2397 | } |
| 2398 | |
| 2399 | /** |
| 2400 | * Remove duplicate rows. |
| 2401 | * |
| 2402 | * @param array $rows |
| 2403 | */ |
| 2404 | public function removeDuplicates(&$rows) { |
| 2405 | if (empty($this->_noRepeats)) { |
| 2406 | return; |
| 2407 | } |
| 2408 | $checkList = []; |
| 2409 | |
| 2410 | foreach ($rows as $key => $list) { |
| 2411 | foreach ($list as $colName => $colVal) { |
| 2412 | if (array_key_exists($colName, $checkList) && |
| 2413 | $checkList[$colName] == $colVal |
| 2414 | ) { |
| 2415 | $rows[$key][$colName] = ""; |
| 2416 | } |
| 2417 | if (in_array($colName, $this->_noRepeats)) { |
| 2418 | $checkList[$colName] = $colVal; |
| 2419 | } |
| 2420 | } |
| 2421 | } |
| 2422 | } |
| 2423 | |
| 2424 | /** |
| 2425 | * Fix subtotal display. |
| 2426 | * |
| 2427 | * @param array $row |
| 2428 | * @param array $fields |
| 2429 | * @param bool $subtotal |
| 2430 | */ |
| 2431 | public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) { |
| 2432 | foreach ($row as $colName => $colVal) { |
| 2433 | if (in_array($colName, $fields)) { |
| 2434 | } |
| 2435 | elseif (isset($this->_columnHeaders[$colName])) { |
| 2436 | if ($subtotal) { |
| 2437 | $row[$colName] = 'Subtotal'; |
| 2438 | $subtotal = FALSE; |
| 2439 | } |
| 2440 | else { |
| 2441 | unset($row[$colName]); |
| 2442 | } |
| 2443 | } |
| 2444 | } |
| 2445 | } |
| 2446 | |
| 2447 | /** |
| 2448 | * Calculate grant total. |
| 2449 | * |
| 2450 | * @param array $rows |
| 2451 | * |
| 2452 | * @return bool |
| 2453 | */ |
| 2454 | public function grandTotal(&$rows) { |
| 2455 | if (!$this->_rollup || count($rows) == 1) { |
| 2456 | return FALSE; |
| 2457 | } |
| 2458 | |
| 2459 | $this->moveSummaryColumnsToTheRightHandSide(); |
| 2460 | |
| 2461 | if ($this->_limit && count($rows) >= $this->getRowCount()) { |
| 2462 | return FALSE; |
| 2463 | } |
| 2464 | |
| 2465 | $this->rollupRow = array_pop($rows); |
| 2466 | |
| 2467 | foreach ($this->_columnHeaders as $fld => $val) { |
| 2468 | if (!in_array($fld, $this->_statFields)) { |
| 2469 | if (!$this->_grandFlag) { |
| 2470 | $this->rollupRow[$fld] = ts('Grand Total'); |
| 2471 | $this->_grandFlag = TRUE; |
| 2472 | } |
| 2473 | else { |
| 2474 | $this->rollupRow[$fld] = ""; |
| 2475 | } |
| 2476 | } |
| 2477 | } |
| 2478 | |
| 2479 | $this->assign('grandStat', $this->rollupRow); |
| 2480 | return TRUE; |
| 2481 | } |
| 2482 | |
| 2483 | /** |
| 2484 | * Format display output. |
| 2485 | * |
| 2486 | * @param array $rows |
| 2487 | * @param bool $pager |
| 2488 | */ |
| 2489 | public function formatDisplay(&$rows, $pager = TRUE) { |
| 2490 | // set pager based on if any limit was applied in the query. |
| 2491 | if ($pager) { |
| 2492 | $this->setPager(); |
| 2493 | } |
| 2494 | $chartEnabled = !empty($this->_params['charts']) && !empty($rows); |
| 2495 | $this->assign('chartEnabled', $chartEnabled); |
| 2496 | // allow building charts if any |
| 2497 | if ($chartEnabled) { |
| 2498 | $this->buildChart($rows); |
| 2499 | $this->_chartId = "{$this->_params['charts']}_" . |
| 2500 | ($this->_id ? $this->_id : substr(get_class($this), 16)) . '_' . |
| 2501 | CRM_Core_Config::singleton()->userSystem->getSessionId(); |
| 2502 | $this->assign('chartId', $this->_chartId); |
| 2503 | } |
| 2504 | |
| 2505 | // unset columns not to be displayed. |
| 2506 | foreach ($this->_columnHeaders as $key => $value) { |
| 2507 | if (!empty($value['no_display'])) { |
| 2508 | unset($this->_columnHeaders[$key]); |
| 2509 | } |
| 2510 | foreach (['colspan', 'type'] as $expectedKey) { |
| 2511 | if (!isset($this->_columnHeaders[$key][$expectedKey])) { |
| 2512 | // Ensure it is set to prevent smarty notices. |
| 2513 | $this->_columnHeaders[$key][$expectedKey] = FALSE; |
| 2514 | } |
| 2515 | } |
| 2516 | } |
| 2517 | |
| 2518 | // unset columns not to be displayed. |
| 2519 | if (!empty($rows)) { |
| 2520 | foreach ($this->_noDisplay as $noDisplayField) { |
| 2521 | foreach ($rows as $rowNum => $row) { |
| 2522 | unset($this->_columnHeaders[$noDisplayField]); |
| 2523 | $expectedKeys = ['class']; |
| 2524 | foreach ($expectedKeys as $expectedKey) { |
| 2525 | if (!array_key_exists($expectedKey, $row)) { |
| 2526 | $rows[$rowNum][$expectedKey] = NULL; |
| 2527 | } |
| 2528 | } |
| 2529 | } |
| 2530 | } |
| 2531 | } |
| 2532 | |
| 2533 | // Find alter display functions. |
| 2534 | $firstRow = reset($rows); |
| 2535 | if ($firstRow) { |
| 2536 | $selectedFields = array_keys($firstRow); |
| 2537 | $alterFunctions = $alterMap = $alterSpecs = []; |
| 2538 | foreach ($this->_columns as $tableName => $table) { |
| 2539 | if (array_key_exists('metadata', $table)) { |
| 2540 | foreach ($table['metadata'] as $field => $specs) { |
| 2541 | if (in_array($tableName . '_' . $field, $selectedFields)) { |
| 2542 | if (array_key_exists('alter_display', $specs)) { |
| 2543 | $alterFunctions[$tableName . '_' . $field] = $specs['alter_display']; |
| 2544 | $alterMap[$tableName . '_' . $field] = $field; |
| 2545 | $alterSpecs[$tableName . '_' . $field] = NULL; |
| 2546 | } |
| 2547 | // Add any alters that can be intuited from the field specs. |
| 2548 | // So far only boolean but a lot more could be. |
| 2549 | if (empty($alterSpecs[$tableName . '_' . $field]) && isset($specs['type']) && $specs['type'] == CRM_Utils_Type::T_BOOLEAN) { |
| 2550 | $alterFunctions[$tableName . '_' . $field] = 'alterBoolean'; |
| 2551 | $alterMap[$tableName . '_' . $field] = $field; |
| 2552 | $alterSpecs[$tableName . '_' . $field] = NULL; |
| 2553 | } |
| 2554 | } |
| 2555 | } |
| 2556 | } |
| 2557 | } |
| 2558 | |
| 2559 | // Run the alter display functions |
| 2560 | foreach ($rows as $index => & $row) { |
| 2561 | foreach ($row as $selectedField => $value) { |
| 2562 | if (array_key_exists($selectedField, $alterFunctions) && isset($value)) { |
| 2563 | $rows[$index][$selectedField] = $this->{$alterFunctions[$selectedField]}($value, $row, $selectedField, $alterMap[$selectedField], $alterSpecs[$selectedField]); |
| 2564 | } |
| 2565 | } |
| 2566 | } |
| 2567 | } |
| 2568 | |
| 2569 | // use this method for formatting rows for display purpose. |
| 2570 | $this->alterDisplay($rows); |
| 2571 | CRM_Utils_Hook::alterReportVar('rows', $rows, $this); |
| 2572 | |
| 2573 | // build array of section totals |
| 2574 | $this->sectionTotals(); |
| 2575 | |
| 2576 | // process grand-total row |
| 2577 | $this->grandTotal($rows); |
| 2578 | |
| 2579 | // use this method for formatting custom rows for display purpose. |
| 2580 | $this->alterCustomDataDisplay($rows); |
| 2581 | } |
| 2582 | |
| 2583 | /** |
| 2584 | * @param $value |
| 2585 | * @param $row |
| 2586 | * @param $selectedfield |
| 2587 | * @param $criteriaFieldName |
| 2588 | * |
| 2589 | * @return array |
| 2590 | */ |
| 2591 | protected function alterStateProvinceID($value, &$row, $selectedfield, $criteriaFieldName) { |
| 2592 | $url = CRM_Utils_System::url(CRM_Utils_System::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl); |
| 2593 | $row[$selectedfield . '_link'] = $url; |
| 2594 | $row[$selectedfield . '_hover'] = ts("%1 for this state.", [ |
| 2595 | 1 => $value, |
| 2596 | ]); |
| 2597 | |
| 2598 | $states = CRM_Core_PseudoConstant::stateProvince($value, FALSE); |
| 2599 | if (!is_array($states)) { |
| 2600 | return $states; |
| 2601 | } |
| 2602 | } |
| 2603 | |
| 2604 | /** |
| 2605 | * @param $value |
| 2606 | * @param $row |
| 2607 | * @param $selectedField |
| 2608 | * @param $criteriaFieldName |
| 2609 | * |
| 2610 | * @return array |
| 2611 | */ |
| 2612 | protected function alterCountryID($value, &$row, $selectedField, $criteriaFieldName) { |
| 2613 | $url = CRM_Utils_System::url(CRM_Utils_System::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl); |
| 2614 | $row[$selectedField . '_link'] = $url; |
| 2615 | $row[$selectedField . '_hover'] = ts("%1 for this country.", [ |
| 2616 | 1 => $value, |
| 2617 | ]); |
| 2618 | $countries = CRM_Core_PseudoConstant::country($value, FALSE); |
| 2619 | if (!is_array($countries)) { |
| 2620 | return $countries; |
| 2621 | } |
| 2622 | } |
| 2623 | |
| 2624 | /** |
| 2625 | * @param $value |
| 2626 | * @param $row |
| 2627 | * @param $selectedfield |
| 2628 | * @param $criteriaFieldName |
| 2629 | * |
| 2630 | * @return array |
| 2631 | */ |
| 2632 | protected function alterCountyID($value, &$row, $selectedfield, $criteriaFieldName) { |
| 2633 | $url = CRM_Utils_System::url(CRM_Utils_System::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl); |
| 2634 | $row[$selectedfield . '_link'] = $url; |
| 2635 | $row[$selectedfield . '_hover'] = ts("%1 for this county.", [ |
| 2636 | 1 => $value, |
| 2637 | ]); |
| 2638 | $counties = CRM_Core_PseudoConstant::county($value, FALSE); |
| 2639 | if (!is_array($counties)) { |
| 2640 | return $counties; |
| 2641 | } |
| 2642 | } |
| 2643 | |
| 2644 | /** |
| 2645 | * @param $value |
| 2646 | * @param $row |
| 2647 | * @param $selectedfield |
| 2648 | * @param $criteriaFieldName |
| 2649 | * |
| 2650 | * @return mixed |
| 2651 | */ |
| 2652 | protected function alterLocationTypeID($value, &$row, $selectedfield, $criteriaFieldName) { |
| 2653 | return CRM_Core_PseudoConstant::getLabel('CRM_Core_DAO_Address', 'location_type_id', $value); |
| 2654 | } |
| 2655 | |
| 2656 | /** |
| 2657 | * @param $value |
| 2658 | * @param $row |
| 2659 | * @param $fieldname |
| 2660 | * |
| 2661 | * @return mixed |
| 2662 | */ |
| 2663 | protected function alterContactID($value, &$row, $fieldname) { |
| 2664 | $nameField = substr($fieldname, 0, -2) . 'name'; |
| 2665 | static $first = TRUE; |
| 2666 | static $viewContactList = FALSE; |
| 2667 | if ($first) { |
| 2668 | $viewContactList = CRM_Core_Permission::check('access CiviCRM'); |
| 2669 | $first = FALSE; |
| 2670 | } |
| 2671 | if (!$viewContactList) { |
| 2672 | return $value; |
| 2673 | } |
| 2674 | if (array_key_exists($nameField, $row)) { |
| 2675 | $row[$nameField . '_link'] = CRM_Utils_System::url("civicrm/contact/view", 'reset=1&cid=' . $value, $this->_absoluteUrl); |
| 2676 | } |
| 2677 | else { |
| 2678 | $row[$fieldname . '_link'] = CRM_Utils_System::url("civicrm/contact/view", 'reset=1&cid=' . $value, $this->_absoluteUrl); |
| 2679 | } |
| 2680 | return $value; |
| 2681 | } |
| 2682 | |
| 2683 | /** |
| 2684 | * @param $value |
| 2685 | * @param $row |
| 2686 | * @param $fieldname |
| 2687 | * |
| 2688 | * @return mixed |
| 2689 | */ |
| 2690 | protected function alterCommunicationtMethod($value, &$row, $fieldname) { |
| 2691 | $communicationMethods = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method'); |
| 2692 | |
| 2693 | // Explode padded values. |
| 2694 | $values = CRM_utils_array::explodePadded($value); |
| 2695 | // Flip values, compute intersection with $communicationMethods, and implode with commas. |
| 2696 | $value = implode(', ', array_intersect_key($communicationMethods, array_flip($values))); |
| 2697 | return $value; |
| 2698 | } |
| 2699 | |
| 2700 | /** |
| 2701 | * @param $value |
| 2702 | * |
| 2703 | * @return mixed |
| 2704 | */ |
| 2705 | protected function alterBoolean($value) { |
| 2706 | $options = [0 => '', 1 => ts('Yes')]; |
| 2707 | if (isset($options[$value])) { |
| 2708 | return $options[$value]; |
| 2709 | } |
| 2710 | return $value; |
| 2711 | } |
| 2712 | |
| 2713 | /** |
| 2714 | * Build chart. |
| 2715 | * |
| 2716 | * @param array $rows |
| 2717 | */ |
| 2718 | public function buildChart(&$rows) { |
| 2719 | // override this method for building charts. |
| 2720 | } |
| 2721 | |
| 2722 | // select() method below has been added recently (v3.3), and many of the report templates might |
| 2723 | // still be having their own select() method. We should fix them as and when encountered and move |
| 2724 | // towards generalizing the select() method below. |
| 2725 | |
| 2726 | /** |
| 2727 | * Generate the SELECT clause and set class variable $_select. |
| 2728 | */ |
| 2729 | public function select() { |
| 2730 | $select = $this->_selectAliases = []; |
| 2731 | $this->storeGroupByArray(); |
| 2732 | |
| 2733 | foreach ($this->_columns as $tableName => $table) { |
| 2734 | if (array_key_exists('fields', $table)) { |
| 2735 | foreach ($table['fields'] as $fieldName => $field) { |
| 2736 | if ($tableName == 'civicrm_address') { |
| 2737 | // deprecated, use $this->isTableSelected. |
| 2738 | $this->_addressField = TRUE; |
| 2739 | } |
| 2740 | if ($tableName == 'civicrm_email') { |
| 2741 | $this->_emailField = TRUE; |
| 2742 | } |
| 2743 | if ($tableName == 'civicrm_phone') { |
| 2744 | $this->_phoneField = TRUE; |
| 2745 | } |
| 2746 | |
| 2747 | if (!empty($field['required']) || |
| 2748 | !empty($this->_params['fields'][$fieldName]) |
| 2749 | ) { |
| 2750 | |
| 2751 | // 1. In many cases we want select clause to be built in slightly different way |
| 2752 | // for a particular field of a particular type. |
| 2753 | // 2. This method when used should receive params by reference and modify $this->_columnHeaders |
| 2754 | // as needed. |
| 2755 | $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field); |
| 2756 | if ($selectClause) { |
| 2757 | $select[] = $selectClause; |
| 2758 | continue; |
| 2759 | } |
| 2760 | |
| 2761 | // include statistics columns only if set |
| 2762 | if (!empty($field['statistics']) && !empty($this->_groupByArray)) { |
| 2763 | $select = $this->addStatisticsToSelect($field, $tableName, $fieldName, $select); |
| 2764 | } |
| 2765 | else { |
| 2766 | |
| 2767 | $selectClause = $this->getSelectClauseWithGroupConcatIfNotGroupedBy($tableName, $fieldName, $field); |
| 2768 | if ($selectClause) { |
| 2769 | $select[] = $selectClause; |
| 2770 | } |
| 2771 | else { |
| 2772 | $select = $this->addBasicFieldToSelect($tableName, $fieldName, $field, $select); |
| 2773 | } |
| 2774 | } |
| 2775 | } |
| 2776 | } |
| 2777 | } |
| 2778 | |
| 2779 | // select for group bys |
| 2780 | if (array_key_exists('group_bys', $table)) { |
| 2781 | foreach ($table['group_bys'] as $fieldName => $field) { |
| 2782 | |
| 2783 | if ($tableName == 'civicrm_address') { |
| 2784 | $this->_addressField = TRUE; |
| 2785 | } |
| 2786 | if ($tableName == 'civicrm_email') { |
| 2787 | $this->_emailField = TRUE; |
| 2788 | } |
| 2789 | if ($tableName == 'civicrm_phone') { |
| 2790 | $this->_phoneField = TRUE; |
| 2791 | } |
| 2792 | // 1. In many cases we want select clause to be built in slightly different way |
| 2793 | // for a particular field of a particular type. |
| 2794 | // 2. This method when used should receive params by reference and modify $this->_columnHeaders |
| 2795 | // as needed. |
| 2796 | $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field); |
| 2797 | if ($selectClause) { |
| 2798 | $select[] = $selectClause; |
| 2799 | continue; |
| 2800 | } |
| 2801 | |
| 2802 | if (!empty($this->_params['group_bys']) && |
| 2803 | !empty($this->_params['group_bys'][$fieldName]) && |
| 2804 | !empty($this->_params['group_bys_freq']) |
| 2805 | ) { |
| 2806 | switch (CRM_Utils_Array::value($fieldName, $this->_params['group_bys_freq'])) { |
| 2807 | case 'YEARWEEK': |
| 2808 | $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start"; |
| 2809 | $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal"; |
| 2810 | $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval"; |
| 2811 | $field['title'] = 'Week'; |
| 2812 | break; |
| 2813 | |
| 2814 | case 'YEAR': |
| 2815 | $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start"; |
| 2816 | $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal"; |
| 2817 | $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval"; |
| 2818 | $field['title'] = 'Year'; |
| 2819 | break; |
| 2820 | |
| 2821 | case 'MONTH': |
| 2822 | $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start"; |
| 2823 | $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal"; |
| 2824 | $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval"; |
| 2825 | $field['title'] = 'Month'; |
| 2826 | break; |
| 2827 | |
| 2828 | case 'QUARTER': |
| 2829 | $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start"; |
| 2830 | $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal"; |
| 2831 | $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval"; |
| 2832 | $field['title'] = 'Quarter'; |
| 2833 | break; |
| 2834 | } |
| 2835 | // for graphs and charts - |
| 2836 | if (!empty($this->_params['group_bys_freq'][$fieldName])) { |
| 2837 | $this->_interval = $field['title']; |
| 2838 | $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['title'] |
| 2839 | = $field['title'] . ' Beginning'; |
| 2840 | $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['type'] = $field['type']; |
| 2841 | $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params['group_bys_freq'][$fieldName]; |
| 2842 | |
| 2843 | // just to make sure these values are transferred to rows. |
| 2844 | // since we 'll need them for calculation purpose, |
| 2845 | // e.g making subtotals look nicer or graphs |
| 2846 | $this->_columnHeaders["{$tableName}_{$fieldName}_interval"] = ['no_display' => TRUE]; |
| 2847 | $this->_columnHeaders["{$tableName}_{$fieldName}_subtotal"] = ['no_display' => TRUE]; |
| 2848 | } |
| 2849 | } |
| 2850 | } |
| 2851 | } |
| 2852 | } |
| 2853 | |
| 2854 | if (empty($select)) { |
| 2855 | // CRM-21412 Do not give fatal error on report when no fields selected |
| 2856 | $select = [1]; |
| 2857 | } |
| 2858 | |
| 2859 | $this->_selectClauses = $select; |
| 2860 | $this->_select = "SELECT " . implode(', ', $select) . " "; |
| 2861 | } |
| 2862 | |
| 2863 | /** |
| 2864 | * Build select clause for a single field. |
| 2865 | * |
| 2866 | * @param string $tableName |
| 2867 | * @param string $tableKey |
| 2868 | * @param string $fieldName |
| 2869 | * @param string $field |
| 2870 | * |
| 2871 | * @return bool |
| 2872 | */ |
| 2873 | public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) { |
| 2874 | if (!empty($field['pseudofield'])) { |
| 2875 | $alias = "{$tableName}_{$fieldName}"; |
| 2876 | $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'] ?? NULL; |
| 2877 | $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = $field['type'] ?? NULL; |
| 2878 | $this->_columnHeaders["{$tableName}_{$fieldName}"]['dbAlias'] = $field['dbAlias'] ?? NULL; |
| 2879 | $this->_selectAliases[] = $alias; |
| 2880 | return ' 1 as ' . $alias; |
| 2881 | } |
| 2882 | return FALSE; |
| 2883 | } |
| 2884 | |
| 2885 | /** |
| 2886 | * Build where clause. |
| 2887 | */ |
| 2888 | public function where() { |
| 2889 | $this->storeWhereHavingClauseArray(); |
| 2890 | |
| 2891 | if (empty($this->_whereClauses)) { |
| 2892 | $this->_where = "WHERE ( 1 ) "; |
| 2893 | $this->_having = ""; |
| 2894 | } |
| 2895 | else { |
| 2896 | $this->_where = "WHERE " . implode(' AND ', $this->_whereClauses); |
| 2897 | } |
| 2898 | |
| 2899 | if ($this->_aclWhere) { |
| 2900 | $this->_where .= " AND {$this->_aclWhere} "; |
| 2901 | } |
| 2902 | |
| 2903 | if (!empty($this->_havingClauses)) { |
| 2904 | // use this clause to construct group by clause. |
| 2905 | $this->_having = "HAVING " . implode(' AND ', $this->_havingClauses); |
| 2906 | } |
| 2907 | } |
| 2908 | |
| 2909 | /** |
| 2910 | * Store Where clauses into an array. |
| 2911 | * |
| 2912 | * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a |
| 2913 | * temp table that may not be part of the final where clause or added |
| 2914 | * in other functions |
| 2915 | */ |
| 2916 | public function storeWhereHavingClauseArray() { |
| 2917 | foreach ($this->_columns as $tableName => $table) { |
| 2918 | if (array_key_exists('filters', $table)) { |
| 2919 | foreach ($table['filters'] as $fieldName => $field) { |
| 2920 | // respect pseudofield to filter spec so fields can be marked as |
| 2921 | // not to be handled here |
| 2922 | if (!empty($field['pseudofield'])) { |
| 2923 | continue; |
| 2924 | } |
| 2925 | $clause = $this->generateFilterClause($field, $fieldName); |
| 2926 | |
| 2927 | if (!empty($clause)) { |
| 2928 | if (!empty($field['having'])) { |
| 2929 | $this->_havingClauses[] = $clause; |
| 2930 | } |
| 2931 | else { |
| 2932 | $this->_whereClauses[] = $clause; |
| 2933 | } |
| 2934 | } |
| 2935 | } |
| 2936 | } |
| 2937 | } |
| 2938 | |
| 2939 | } |
| 2940 | |
| 2941 | /** |
| 2942 | * Set output mode. |
| 2943 | */ |
| 2944 | public function processReportMode() { |
| 2945 | $this->setOutputMode(); |
| 2946 | |
| 2947 | $this->_sendmail |
| 2948 | = CRM_Utils_Request::retrieve( |
| 2949 | 'sendmail', |
| 2950 | 'Boolean', |
| 2951 | CRM_Core_DAO::$_nullObject |
| 2952 | ); |
| 2953 | |
| 2954 | if ($this->_sendmail && !$this->_outputMode) { |
| 2955 | // If we're here from the mail_report job, then the default there gets |
| 2956 | // set to pdf before we get here, but if we're somehow here and sending |
| 2957 | // by email and don't have a format set, then use print. |
| 2958 | // @todo Is this on purpose - why would they be different defaults? |
| 2959 | $this->_outputMode = 'print'; |
| 2960 | } |
| 2961 | |
| 2962 | // _outputMode means multiple things and can cover export to file formats, |
| 2963 | // like csv, or actions with no output, like save. So this will only set |
| 2964 | // a handler if it's one of the former. But it's also possible we have a |
| 2965 | // really interesting handler out there. But the point is we don't need to |
| 2966 | // know, just to know that a handler doesn't always get set by this call. |
| 2967 | $this->setOutputHandler(); |
| 2968 | |
| 2969 | if (!empty($this->outputHandler)) { |
| 2970 | if ($this->_sendmail) { |
| 2971 | // If we're sending by email these are the only options that make |
| 2972 | // sense. |
| 2973 | $this->printOnly = TRUE; |
| 2974 | $this->addPaging = FALSE; |
| 2975 | $this->_absoluteUrl = TRUE; |
| 2976 | } |
| 2977 | else { |
| 2978 | // otherwise ask the handler |
| 2979 | $this->printOnly = $this->outputHandler->isPrintOnly(); |
| 2980 | $this->addPaging = $this->outputHandler->isAddPaging(); |
| 2981 | $this->_absoluteUrl = $this->outputHandler->isAbsoluteUrl(); |
| 2982 | } |
| 2983 | } |
| 2984 | elseif ($this->_outputMode == 'copy' && $this->_criteriaForm) { |
| 2985 | $this->_createNew = TRUE; |
| 2986 | } |
| 2987 | |
| 2988 | $this->assign('outputMode', $this->_outputMode); |
| 2989 | $this->assign('printOnly', $this->printOnly); |
| 2990 | // Get today's date to include in printed reports |
| 2991 | if ($this->printOnly) { |
| 2992 | $reportDate = CRM_Utils_Date::customFormat(date('Y-m-d H:i')); |
| 2993 | $this->assign('reportDate', $reportDate); |
| 2994 | } |
| 2995 | } |
| 2996 | |
| 2997 | /** |
| 2998 | * Post Processing function for Form. |
| 2999 | * |
| 3000 | * postProcessCommon should be used to set other variables from input as the api accesses that function. |
| 3001 | * This function is not accessed when the api calls the report. |
| 3002 | */ |
| 3003 | public function beginPostProcess() { |
| 3004 | $this->setParams($this->controller->exportValues($this->_name)); |
| 3005 | if (empty($this->_params) && |
| 3006 | $this->_force |
| 3007 | ) { |
| 3008 | $this->setParams($this->_formValues); |
| 3009 | } |
| 3010 | |
| 3011 | // hack to fix params when submitted from dashboard, CRM-8532 |
| 3012 | // fields array is missing because form building etc is skipped |
| 3013 | // in dashboard mode for report |
| 3014 | //@todo - this could be done in the dashboard no we have a setter |
| 3015 | if (empty($this->_params['fields']) && !$this->_noFields) { |
| 3016 | $this->setParams($this->_formValues); |
| 3017 | } |
| 3018 | |
| 3019 | $this->processReportMode(); |
| 3020 | |
| 3021 | if ($this->_outputMode == 'save' || $this->_outputMode == 'copy') { |
| 3022 | $this->_createNew = ($this->_outputMode == 'copy'); |
| 3023 | CRM_Report_Form_Instance::postProcess($this); |
| 3024 | } |
| 3025 | if ($this->_outputMode == 'delete') { |
| 3026 | CRM_Report_BAO_ReportInstance::doFormDelete($this->_id, 'civicrm/report/list?reset=1', 'civicrm/report/list?reset=1'); |
| 3027 | } |
| 3028 | |
| 3029 | $this->_formValues = $this->_params; |
| 3030 | |
| 3031 | $this->beginPostProcessCommon(); |
| 3032 | } |
| 3033 | |
| 3034 | /** |
| 3035 | * BeginPostProcess function run in both report mode and non-report mode (api). |
| 3036 | */ |
| 3037 | public function beginPostProcessCommon() { |
| 3038 | } |
| 3039 | |
| 3040 | /** |
| 3041 | * Build the report query. |
| 3042 | * |
| 3043 | * @param bool $applyLimit |
| 3044 | * |
| 3045 | * @return string |
| 3046 | */ |
| 3047 | public function buildQuery($applyLimit = TRUE) { |
| 3048 | $this->buildGroupTempTable(); |
| 3049 | $this->select(); |
| 3050 | $this->from(); |
| 3051 | $this->customDataFrom(); |
| 3052 | $this->buildPermissionClause(); |
| 3053 | $this->where(); |
| 3054 | $this->groupBy(); |
| 3055 | $this->orderBy(); |
| 3056 | |
| 3057 | foreach ($this->unselectedOrderByColumns() as $alias => $field) { |
| 3058 | $clause = $this->getSelectClauseWithGroupConcatIfNotGroupedBy($field['table_name'], $field['name'], $field); |
| 3059 | if (!$clause) { |
| 3060 | $clause = "{$field['dbAlias']} as {$alias}"; |
| 3061 | } |
| 3062 | $this->_select .= ", $clause "; |
| 3063 | } |
| 3064 | |
| 3065 | if ($applyLimit && empty($this->_params['charts'])) { |
| 3066 | $this->limit(); |
| 3067 | } |
| 3068 | CRM_Utils_Hook::alterReportVar('sql', $this, $this); |
| 3069 | |
| 3070 | $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}"; |
| 3071 | $this->addToDeveloperTab($sql); |
| 3072 | return $sql; |
| 3073 | } |
| 3074 | |
| 3075 | /** |
| 3076 | * Build group by clause. |
| 3077 | */ |
| 3078 | public function groupBy() { |
| 3079 | $this->storeGroupByArray(); |
| 3080 | |
| 3081 | if (!empty($this->_groupByArray)) { |
| 3082 | if ($this->optimisedForOnlyFullGroupBy) { |
| 3083 | // We should probably deprecate this code path. What happens here is that |
| 3084 | // the group by is amended to reflect the select columns. This often breaks the |
| 3085 | // results. Retrofitting group strict group by onto existing report classes |
| 3086 | // went badly. |
| 3087 | $this->_groupBy = CRM_Contact_BAO_Query::getGroupByFromSelectColumns($this->_selectClauses, $this->_groupByArray); |
| 3088 | } |
| 3089 | else { |
| 3090 | $this->_groupBy = ' GROUP BY ' . implode($this->_groupByArray); |
| 3091 | } |
| 3092 | } |
| 3093 | } |
| 3094 | |
| 3095 | /** |
| 3096 | * Build order by clause. |
| 3097 | */ |
| 3098 | public function orderBy() { |
| 3099 | $this->_orderBy = ""; |
| 3100 | $this->_sections = []; |
| 3101 | $this->storeOrderByArray(); |
| 3102 | if (!empty($this->_orderByArray) && !$this->_rollup == 'WITH ROLLUP') { |
| 3103 | $this->_orderBy = "ORDER BY " . implode(', ', $this->_orderByArray); |
| 3104 | } |
| 3105 | $this->assign('sections', $this->_sections); |
| 3106 | } |
| 3107 | |
| 3108 | /** |
| 3109 | * Extract order by fields and store as an array. |
| 3110 | * |
| 3111 | * In some cases other functions want to know which fields are selected for ordering by |
| 3112 | * Separating this into a separate function allows it to be called separately from constructing |
| 3113 | * the order by clause |
| 3114 | */ |
| 3115 | public function storeOrderByArray() { |
| 3116 | $orderBys = []; |
| 3117 | |
| 3118 | if (!empty($this->_params['order_bys']) && |
| 3119 | is_array($this->_params['order_bys']) && |
| 3120 | !empty($this->_params['order_bys']) |
| 3121 | ) { |
| 3122 | |
| 3123 | // Process order_bys in user-specified order |
| 3124 | foreach ($this->_params['order_bys'] as $orderBy) { |
| 3125 | $orderByField = []; |
| 3126 | foreach ($this->_columns as $tableName => $table) { |
| 3127 | if (array_key_exists('order_bys', $table)) { |
| 3128 | // For DAO columns defined in $this->_columns |
| 3129 | $fields = $table['order_bys']; |
| 3130 | } |
| 3131 | elseif (array_key_exists('extends', $table)) { |
| 3132 | // For custom fields referenced in $this->_customGroupExtends |
| 3133 | $fields = CRM_Utils_Array::value('fields', $table, []); |
| 3134 | } |
| 3135 | else { |
| 3136 | continue; |
| 3137 | } |
| 3138 | if (!empty($fields) && is_array($fields)) { |
| 3139 | foreach ($fields as $fieldName => $field) { |
| 3140 | if ($fieldName == $orderBy['column']) { |
| 3141 | $orderByField = array_merge($field, $orderBy); |
| 3142 | $orderByField['tplField'] = "{$tableName}_{$fieldName}"; |
| 3143 | break 2; |
| 3144 | } |
| 3145 | } |
| 3146 | } |
| 3147 | } |
| 3148 | |
| 3149 | if (!empty($orderByField)) { |
| 3150 | $this->_orderByFields[$orderByField['tplField']] = $orderByField; |
| 3151 | if ($this->groupConcatTested) { |
| 3152 | $orderBys[$orderByField['tplField']] = "{$orderByField['tplField']} {$orderBy['order']}"; |
| 3153 | } |
| 3154 | else { |
| 3155 | // Not sure when this is preferable to using tplField (which has |
| 3156 | // definitely been tested to work in cases then this does not. |
| 3157 | // in caution not switching unless report has been tested for |
| 3158 | // group concat functionality. |
| 3159 | $orderBys[$orderByField['tplField']] = "{$orderByField['dbAlias']} {$orderBy['order']}"; |
| 3160 | } |
| 3161 | |
| 3162 | // Record any section headers for assignment to the template |
| 3163 | if (!empty($orderBy['section'])) { |
| 3164 | $orderByField['pageBreak'] = $orderBy['pageBreak'] ?? NULL; |
| 3165 | $this->_sections[$orderByField['tplField']] = $orderByField; |
| 3166 | } |
| 3167 | } |
| 3168 | } |
| 3169 | } |
| 3170 | |
| 3171 | $this->_orderByArray = $orderBys; |
| 3172 | |
| 3173 | $this->assign('sections', $this->_sections); |
| 3174 | } |
| 3175 | |
| 3176 | /** |
| 3177 | * Determine unselected columns. |
| 3178 | * |
| 3179 | * @return array |
| 3180 | */ |
| 3181 | public function unselectedOrderByColumns() { |
| 3182 | return array_diff_key($this->_orderByFields, $this->getSelectColumns()); |
| 3183 | } |
| 3184 | |
| 3185 | /** |
| 3186 | * Determine unselected columns. |
| 3187 | * |
| 3188 | * @return array |
| 3189 | */ |
| 3190 | public function unselectedSectionColumns() { |
| 3191 | if (is_array($this->_sections)) { |
| 3192 | return array_diff_key($this->_sections, $this->getSelectColumns()); |
| 3193 | } |
| 3194 | else { |
| 3195 | return []; |
| 3196 | } |
| 3197 | } |
| 3198 | |
| 3199 | /** |
| 3200 | * Build output rows. |
| 3201 | * |
| 3202 | * @param string $sql |
| 3203 | * @param array $rows |
| 3204 | */ |
| 3205 | public function buildRows($sql, &$rows) { |
| 3206 | if (!$this->optimisedForOnlyFullGroupBy) { |
| 3207 | CRM_Core_DAO::disableFullGroupByMode(); |
| 3208 | } |
| 3209 | $dao = CRM_Core_DAO::executeQuery($sql); |
| 3210 | if (stristr($this->_select, 'SQL_CALC_FOUND_ROWS')) { |
| 3211 | $this->_rowsFound = CRM_Core_DAO::singleValueQuery('SELECT FOUND_ROWS()'); |
| 3212 | } |
| 3213 | CRM_Core_DAO::reenableFullGroupByMode(); |
| 3214 | if (!is_array($rows)) { |
| 3215 | $rows = []; |
| 3216 | } |
| 3217 | |
| 3218 | // use this method to modify $this->_columnHeaders |
| 3219 | $this->modifyColumnHeaders(); |
| 3220 | |
| 3221 | $unselectedSectionColumns = $this->unselectedSectionColumns(); |
| 3222 | |
| 3223 | while ($dao->fetch()) { |
| 3224 | $row = []; |
| 3225 | foreach ($this->_columnHeaders as $key => $value) { |
| 3226 | if (property_exists($dao, $key)) { |
| 3227 | $row[$key] = $dao->$key; |
| 3228 | } |
| 3229 | } |
| 3230 | |
| 3231 | // section headers not selected for display need to be added to row |
| 3232 | foreach ($unselectedSectionColumns as $key => $values) { |
| 3233 | if (property_exists($dao, $key)) { |
| 3234 | $row[$key] = $dao->$key; |
| 3235 | } |
| 3236 | } |
| 3237 | |
| 3238 | $rows[] = $row; |
| 3239 | } |
| 3240 | } |
| 3241 | |
| 3242 | /** |
| 3243 | * Calculate section totals. |
| 3244 | * |
| 3245 | * When "order by" fields are marked as sections, this assigns to the template |
| 3246 | * an array of total counts for each section. This data is used by the Smarty |
| 3247 | * plugin {sectionTotal}. |
| 3248 | */ |
| 3249 | public function sectionTotals() { |
| 3250 | |
| 3251 | // Reports using order_bys with sections must populate $this->_selectAliases in select() method. |
| 3252 | if (empty($this->_selectAliases)) { |
| 3253 | return; |
| 3254 | } |
| 3255 | |
| 3256 | if (!empty($this->_sections)) { |
| 3257 | // build the query with no LIMIT clause |
| 3258 | $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select); |
| 3259 | $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}"; |
| 3260 | |
| 3261 | // pull section aliases out of $this->_sections |
| 3262 | $sectionAliases = array_keys($this->_sections); |
| 3263 | |
| 3264 | $ifnulls = []; |
| 3265 | foreach (array_merge($sectionAliases, $this->_selectAliases) as $alias) { |
| 3266 | $ifnulls[] = "ifnull($alias, '') as $alias"; |
| 3267 | } |
| 3268 | $this->_select = "SELECT " . implode(", ", $ifnulls); |
| 3269 | $this->_select = CRM_Contact_BAO_Query::appendAnyValueToSelect($ifnulls, $sectionAliases); |
| 3270 | |
| 3271 | // Group (un-limited) report by all aliases and get counts. This might |
| 3272 | // be done more efficiently when the contents of $sql are known, ie. by |
| 3273 | // overriding this method in the report class. |
| 3274 | |
| 3275 | $query = $this->_select . |
| 3276 | ", count(*) as ct from ($sql) as subquery group by " . |
| 3277 | implode(", ", $sectionAliases); |
| 3278 | |
| 3279 | // initialize array of total counts |
| 3280 | $totals = []; |
| 3281 | $dao = CRM_Core_DAO::executeQuery($query); |
| 3282 | while ($dao->fetch()) { |
| 3283 | |
| 3284 | // let $this->_alterDisplay translate any integer ids to human-readable values. |
| 3285 | $rows[0] = $dao->toArray(); |
| 3286 | $this->alterDisplay($rows); |
| 3287 | $this->alterCustomDataDisplay($rows); |
| 3288 | $row = $rows[0]; |
| 3289 | |
| 3290 | // add totals for all permutations of section values |
| 3291 | $values = []; |
| 3292 | $i = 1; |
| 3293 | $aliasCount = count($sectionAliases); |
| 3294 | foreach ($sectionAliases as $alias) { |
| 3295 | $values[] = $row[$alias]; |
| 3296 | $key = implode(CRM_Core_DAO::VALUE_SEPARATOR, $values); |
| 3297 | if ($i == $aliasCount) { |
| 3298 | // the last alias is the lowest-level section header; use count as-is |
| 3299 | $totals[$key] = $dao->ct; |
| 3300 | } |
| 3301 | else { |
| 3302 | // other aliases are higher level; roll count into their total |
| 3303 | $totals[$key] += $dao->ct; |
| 3304 | } |
| 3305 | } |
| 3306 | } |
| 3307 | $this->assign('sectionTotals', $totals); |
| 3308 | } |
| 3309 | } |
| 3310 | |
| 3311 | /** |
| 3312 | * Modify column headers. |
| 3313 | */ |
| 3314 | public function modifyColumnHeaders() { |
| 3315 | // use this method to modify $this->_columnHeaders |
| 3316 | } |
| 3317 | |
| 3318 | /** |
| 3319 | * Move totals columns to the right edge of the table. |
| 3320 | * |
| 3321 | * It seems like a more logical layout to have any totals columns on the far right regardless of |
| 3322 | * the location of the rest of their table. |
| 3323 | */ |
| 3324 | public function moveSummaryColumnsToTheRightHandSide() { |
| 3325 | $statHeaders = (array_intersect_key($this->_columnHeaders, array_flip($this->_statFields))); |
| 3326 | $this->_columnHeaders = array_merge(array_diff_key($this->_columnHeaders, $statHeaders), $this->_columnHeaders, $statHeaders); |
| 3327 | } |
| 3328 | |
| 3329 | /** |
| 3330 | * Assign rows to the template. |
| 3331 | * |
| 3332 | * @param array $rows |
| 3333 | */ |
| 3334 | public function doTemplateAssignment(&$rows) { |
| 3335 | $this->assign('columnHeaders', $this->_columnHeaders); |
| 3336 | $this->assign_by_ref('rows', $rows); |
| 3337 | $this->assign('statistics', $this->statistics($rows)); |
| 3338 | } |
| 3339 | |
| 3340 | /** |
| 3341 | * Build report statistics. |
| 3342 | * |
| 3343 | * Override this method to build your own statistics. |
| 3344 | * |
| 3345 | * @param array $rows |
| 3346 | * |
| 3347 | * @return array |
| 3348 | */ |
| 3349 | public function statistics(&$rows) { |
| 3350 | $statistics = []; |
| 3351 | |
| 3352 | $count = count($rows); |
| 3353 | // Why do we increment the count for rollup seems to artificially inflate the count. |
| 3354 | // It seems perhaps intentional to include the summary row in the count of results - although |
| 3355 | // this just seems odd. |
| 3356 | if ($this->_rollup && ($this->_rollup != '') && $this->_grandFlag) { |
| 3357 | $count++; |
| 3358 | } |
| 3359 | |
| 3360 | $this->countStat($statistics, $count); |
| 3361 | |
| 3362 | $this->groupByStat($statistics); |
| 3363 | |
| 3364 | $this->filterStat($statistics); |
| 3365 | |
| 3366 | return $statistics; |
| 3367 | } |
| 3368 | |
| 3369 | /** |
| 3370 | * Add count statistics. |
| 3371 | * |
| 3372 | * @param array $statistics |
| 3373 | * @param int $count |
| 3374 | */ |
| 3375 | public function countStat(&$statistics, $count) { |
| 3376 | $statistics['counts']['rowCount'] = [ |
| 3377 | 'title' => ts('Row(s) Listed'), |
| 3378 | 'value' => $count, |
| 3379 | 'type' => CRM_Utils_Type::T_INT, |
| 3380 | ]; |
| 3381 | |
| 3382 | if ($this->_rowsFound && ($this->_rowsFound > $count)) { |
| 3383 | $statistics['counts']['rowsFound'] = [ |
| 3384 | 'title' => ts('Total Row(s)'), |
| 3385 | 'value' => $this->_rowsFound, |
| 3386 | 'type' => CRM_Utils_Type::T_INT, |
| 3387 | ]; |
| 3388 | } |
| 3389 | } |
| 3390 | |
| 3391 | /** |
| 3392 | * Add group by statistics. |
| 3393 | * |
| 3394 | * @param array $statistics |
| 3395 | */ |
| 3396 | public function groupByStat(&$statistics) { |
| 3397 | if (!empty($this->_params['group_bys']) && |
| 3398 | is_array($this->_params['group_bys']) && |
| 3399 | !empty($this->_params['group_bys']) |
| 3400 | ) { |
| 3401 | foreach ($this->_columns as $tableName => $table) { |
| 3402 | if (array_key_exists('group_bys', $table)) { |
| 3403 | foreach ($table['group_bys'] as $fieldName => $field) { |
| 3404 | if (!empty($this->_params['group_bys'][$fieldName])) { |
| 3405 | $combinations[] = $field['title']; |
| 3406 | } |
| 3407 | } |
| 3408 | } |
| 3409 | } |
| 3410 | $statistics['groups'][] = [ |
| 3411 | 'title' => ts('Grouping(s)'), |
| 3412 | 'value' => implode(' & ', $combinations), |
| 3413 | ]; |
| 3414 | } |
| 3415 | else { |
| 3416 | // prevents an e-notice in statistics.tpl. |
| 3417 | $statistics['groups'] = []; |
| 3418 | } |
| 3419 | } |
| 3420 | |
| 3421 | /** |
| 3422 | * Filter statistics. |
| 3423 | * |
| 3424 | * @param array $statistics |
| 3425 | */ |
| 3426 | public function filterStat(&$statistics) { |
| 3427 | foreach ($this->_columns as $tableName => $table) { |
| 3428 | if (array_key_exists('filters', $table)) { |
| 3429 | foreach ($table['filters'] as $fieldName => $field) { |
| 3430 | if ((CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE || |
| 3431 | CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_TIME) && |
| 3432 | CRM_Utils_Array::value('operatorType', $field) != |
| 3433 | CRM_Report_Form::OP_MONTH |
| 3434 | ) { |
| 3435 | $from = $this->_params["{$fieldName}_from"] ?? NULL; |
| 3436 | $to = $this->_params["{$fieldName}_to"] ?? NULL; |
| 3437 | if (!empty($this->_params["{$fieldName}_relative"])) { |
| 3438 | [$from, $to] = CRM_Utils_Date::getFromTo($this->_params["{$fieldName}_relative"], NULL, NULL); |
| 3439 | } |
| 3440 | if (strlen($to) === 10) { |
| 3441 | // If we just have the date we assume the end of that day. |
| 3442 | $to .= ' 23:59:59'; |
| 3443 | } |
| 3444 | if ($from || $to) { |
| 3445 | if ($from) { |
| 3446 | $from = date('l j F Y, g:iA', strtotime($from)); |
| 3447 | } |
| 3448 | if ($to) { |
| 3449 | $to = date('l j F Y, g:iA', strtotime($to)); |
| 3450 | } |
| 3451 | $statistics['filters'][] = [ |
| 3452 | 'title' => $field['title'], |
| 3453 | 'value' => ts("Between %1 and %2", [1 => $from, 2 => $to]), |
| 3454 | ]; |
| 3455 | } |
| 3456 | elseif (in_array($rel = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params), |
| 3457 | array_keys($this->getOperationPair(CRM_Report_Form::OP_DATE)) |
| 3458 | )) { |
| 3459 | $pair = $this->getOperationPair(CRM_Report_Form::OP_DATE); |
| 3460 | $statistics['filters'][] = [ |
| 3461 | 'title' => $field['title'], |
| 3462 | 'value' => $pair[$rel], |
| 3463 | ]; |
| 3464 | } |
| 3465 | } |
| 3466 | else { |
| 3467 | $op = $this->_params["{$fieldName}_op"] ?? NULL; |
| 3468 | $value = NULL; |
| 3469 | if ($op) { |
| 3470 | $pair = $this->getOperationPair( |
| 3471 | CRM_Utils_Array::value('operatorType', $field), |
| 3472 | $fieldName |
| 3473 | ); |
| 3474 | $min = $this->_params["{$fieldName}_min"] ?? NULL; |
| 3475 | $max = $this->_params["{$fieldName}_max"] ?? NULL; |
| 3476 | $val = $this->_params["{$fieldName}_value"] ?? NULL; |
| 3477 | if (in_array($op, ['bw', 'nbw']) && ($min || $max)) { |
| 3478 | $value = "{$pair[$op]} $min " . ts('and') . " $max"; |
| 3479 | } |
| 3480 | elseif ($val && CRM_Utils_Array::value('operatorType', $field) & self::OP_ENTITYREF) { |
| 3481 | $this->setEntityRefDefaults($field, $tableName); |
| 3482 | $result = civicrm_api3($field['attributes']['entity'], 'getlist', |
| 3483 | ['id' => $val] + |
| 3484 | CRM_Utils_Array::value('api', $field['attributes'], [])); |
| 3485 | $values = []; |
| 3486 | foreach ($result['values'] as $v) { |
| 3487 | $values[] = $v['label']; |
| 3488 | } |
| 3489 | $value = "{$pair[$op]} " . implode(', ', $values); |
| 3490 | } |
| 3491 | elseif ($op == 'nll' || $op == 'nnll') { |
| 3492 | $value = $pair[$op]; |
| 3493 | } |
| 3494 | elseif (is_array($val) && (!empty($val))) { |
| 3495 | $options = CRM_Utils_Array::value('options', $field, []); |
| 3496 | foreach ($val as $key => $valIds) { |
| 3497 | if (isset($options[$valIds])) { |
| 3498 | $val[$key] = $options[$valIds]; |
| 3499 | } |
| 3500 | } |
| 3501 | $pair[$op] = (count($val) == 1) ? (($op == 'notin' || $op == |
| 3502 | 'mnot') ? ts('Is Not') : ts('Is')) : CRM_Utils_Array::value($op, $pair); |
| 3503 | $val = implode(', ', $val); |
| 3504 | $value = "{$pair[$op]} " . $val; |
| 3505 | } |
| 3506 | elseif (!is_array($val) && (!empty($val) || $val == '0') && |
| 3507 | isset($field['options']) && |
| 3508 | is_array($field['options']) && !empty($field['options']) |
| 3509 | ) { |
| 3510 | $value = CRM_Utils_Array::value($op, $pair) . " " . |
| 3511 | CRM_Utils_Array::value($val, $field['options'], $val); |
| 3512 | } |
| 3513 | elseif ($val) { |
| 3514 | $value = CRM_Utils_Array::value($op, $pair) . " " . $val; |
| 3515 | } |
| 3516 | } |
| 3517 | if ($value && empty($field['no_display'])) { |
| 3518 | $statistics['filters'][] = [ |
| 3519 | 'title' => $field['title'] ?? NULL, |
| 3520 | 'value' => CRM_Utils_String::htmlToText($value), |
| 3521 | ]; |
| 3522 | } |
| 3523 | } |
| 3524 | } |
| 3525 | } |
| 3526 | else { |
| 3527 | // Prevents an e-notice in statistics.tpl. |
| 3528 | $statistics['filters'] = []; |
| 3529 | } |
| 3530 | } |
| 3531 | } |
| 3532 | |
| 3533 | /** |
| 3534 | * End post processing. |
| 3535 | * |
| 3536 | * @param array|null $rows |
| 3537 | */ |
| 3538 | public function endPostProcess(&$rows = NULL) { |
| 3539 | $this->assign('report_class', get_class($this)); |
| 3540 | |
| 3541 | // This is used by unit tests, where _outputMode is intentionally blank. |
| 3542 | // Is there a reason it couldn't just always do this? It effectively does |
| 3543 | // the same thing anyway by assigning it to the template (in |
| 3544 | // doTemplateAssignment()). |
| 3545 | if ($this->_storeResultSet) { |
| 3546 | $this->_resultSet = $rows; |
| 3547 | } |
| 3548 | |
| 3549 | // Add contacts to group |
| 3550 | if ($this->_outputMode == 'group') { |
| 3551 | $group = $this->_params['groups']; |
| 3552 | $this->add2group($group); |
| 3553 | } |
| 3554 | else { |
| 3555 | if ($this->_sendmail) { |
| 3556 | $this->sendEmail(); |
| 3557 | } |
| 3558 | elseif (!empty($this->outputHandler)) { |
| 3559 | $this->outputHandler->download(); |
| 3560 | CRM_Utils_System::civiExit(); |
| 3561 | } |
| 3562 | // else we don't need to do anything here since it must have been |
| 3563 | // outputMode=save or something like that |
| 3564 | } |
| 3565 | } |
| 3566 | |
| 3567 | /** |
| 3568 | * Set store result set indicator to TRUE. |
| 3569 | * |
| 3570 | * This is used by unit tests, along with getResultSet(), to get just |
| 3571 | * the output rows unformatted. |
| 3572 | */ |
| 3573 | public function storeResultSet() { |
| 3574 | $this->_storeResultSet = TRUE; |
| 3575 | } |
| 3576 | |
| 3577 | /** |
| 3578 | * Get result set. |
| 3579 | * |
| 3580 | * @return bool |
| 3581 | */ |
| 3582 | public function getResultSet() { |
| 3583 | return $this->_resultSet; |
| 3584 | } |
| 3585 | |
| 3586 | /** |
| 3587 | * Get the sql used to generate the report. |
| 3588 | * |
| 3589 | * @return string |
| 3590 | */ |
| 3591 | public function getReportSql() { |
| 3592 | return $this->sqlArray; |
| 3593 | } |
| 3594 | |
| 3595 | /** |
| 3596 | * Use the form name to create the tpl file name. |
| 3597 | * |
| 3598 | * @return string |
| 3599 | */ |
| 3600 | public function getTemplateFileName() { |
| 3601 | $defaultTpl = parent::getTemplateFileName(); |
| 3602 | $template = CRM_Core_Smarty::singleton(); |
| 3603 | if (!$template->template_exists($defaultTpl)) { |
| 3604 | $defaultTpl = 'CRM/Report/Form.tpl'; |
| 3605 | } |
| 3606 | return $defaultTpl; |
| 3607 | } |
| 3608 | |
| 3609 | /** |
| 3610 | * Compile the report content. |
| 3611 | * |
| 3612 | * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes. |
| 3613 | * |
| 3614 | * @return string |
| 3615 | */ |
| 3616 | public function compileContent() { |
| 3617 | $templateFile = $this->getHookedTemplateFileName(); |
| 3618 | return CRM_Utils_Array::value('report_header', $this->_formValues) . |
| 3619 | CRM_Core_Form::$_template->fetch($templateFile) . |
| 3620 | CRM_Utils_Array::value('report_footer', $this->_formValues); |
| 3621 | } |
| 3622 | |
| 3623 | /** |
| 3624 | * Post process function. |
| 3625 | */ |
| 3626 | public function postProcess() { |
| 3627 | // get ready with post process params |
| 3628 | $this->beginPostProcess(); |
| 3629 | |
| 3630 | // build query |
| 3631 | $sql = $this->buildQuery(); |
| 3632 | |
| 3633 | // build array of result based on column headers. This method also allows |
| 3634 | // modifying column headers before using it to build result set i.e $rows. |
| 3635 | $rows = []; |
| 3636 | $this->buildRows($sql, $rows); |
| 3637 | |
| 3638 | // format result set. |
| 3639 | $this->formatDisplay($rows); |
| 3640 | |
| 3641 | // assign variables to templates |
| 3642 | $this->doTemplateAssignment($rows); |
| 3643 | |
| 3644 | // do print / pdf / instance stuff if needed |
| 3645 | $this->endPostProcess($rows); |
| 3646 | } |
| 3647 | |
| 3648 | /** |
| 3649 | * Set limit. |
| 3650 | * |
| 3651 | * @param int|null $rowCount |
| 3652 | * |
| 3653 | * @return array |
| 3654 | */ |
| 3655 | public function limit($rowCount = NULL) { |
| 3656 | $rowCount = $rowCount ?? $this->getRowCount(); |
| 3657 | // lets do the pager if in html mode |
| 3658 | $this->_limit = NULL; |
| 3659 | |
| 3660 | // CRM-14115, over-ride row count if rowCount is specified in URL |
| 3661 | if ($this->_dashBoardRowCount) { |
| 3662 | $rowCount = $this->_dashBoardRowCount; |
| 3663 | } |
| 3664 | if ($this->addPaging) { |
| 3665 | $this->_select = preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select); |
| 3666 | |
| 3667 | $pageId = CRM_Utils_Request::retrieve('crmPID', 'Integer'); |
| 3668 | |
| 3669 | // @todo all http vars should be extracted in the preProcess |
| 3670 | // - not randomly in the class |
| 3671 | if (!$pageId && !empty($_POST)) { |
| 3672 | if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) { |
| 3673 | $pageId = max((int) $_POST['crmPID_B'], 1); |
| 3674 | } |
| 3675 | elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) { |
| 3676 | $pageId = max((int) $_POST['crmPID'], 1); |
| 3677 | } |
| 3678 | unset($_POST['crmPID_B'], $_POST['crmPID']); |
| 3679 | } |
| 3680 | |
| 3681 | $pageId = $pageId ? $pageId : 1; |
| 3682 | $this->set(CRM_Utils_Pager::PAGE_ID, $pageId); |
| 3683 | $offset = ($pageId - 1) * $rowCount; |
| 3684 | |
| 3685 | $offset = CRM_Utils_Type::escape($offset, 'Int'); |
| 3686 | $rowCount = CRM_Utils_Type::escape($rowCount, 'Int'); |
| 3687 | |
| 3688 | $this->_limit = " LIMIT $offset, $rowCount"; |
| 3689 | return [$offset, $rowCount]; |
| 3690 | } |
| 3691 | if ($this->_limitValue) { |
| 3692 | if ($this->_offsetValue) { |
| 3693 | $this->_limit = " LIMIT {$this->_offsetValue}, {$this->_limitValue} "; |
| 3694 | } |
| 3695 | else { |
| 3696 | $this->_limit = " LIMIT " . $this->_limitValue; |
| 3697 | } |
| 3698 | } |
| 3699 | } |
| 3700 | |
| 3701 | /** |
| 3702 | * Set pager. |
| 3703 | * |
| 3704 | * @param int|null $rowCount |
| 3705 | */ |
| 3706 | public function setPager($rowCount = NULL) { |
| 3707 | $rowCount = $rowCount ?? $this->getRowCount(); |
| 3708 | // CRM-14115, over-ride row count if rowCount is specified in URL |
| 3709 | if ($this->_dashBoardRowCount) { |
| 3710 | $rowCount = $this->_dashBoardRowCount; |
| 3711 | } |
| 3712 | |
| 3713 | if ($this->_limit && ($this->_limit != '')) { |
| 3714 | if (!$this->_rowsFound) { |
| 3715 | $sql = "SELECT FOUND_ROWS();"; |
| 3716 | $this->_rowsFound = CRM_Core_DAO::singleValueQuery($sql); |
| 3717 | } |
| 3718 | $params = [ |
| 3719 | 'total' => $this->_rowsFound, |
| 3720 | 'rowCount' => $rowCount, |
| 3721 | 'status' => ts('Records') . ' %%StatusMessage%%', |
| 3722 | 'buttonBottom' => 'PagerBottomButton', |
| 3723 | 'buttonTop' => 'PagerTopButton', |
| 3724 | ]; |
| 3725 | if (!empty($this->controller)) { |
| 3726 | // This happens when being called from the api Really we want the api to be able to |
| 3727 | // pass paging parameters, but at this stage just preventing test crashes. |
| 3728 | $params['pageID'] = $this->get(CRM_Utils_Pager::PAGE_ID); |
| 3729 | } |
| 3730 | |
| 3731 | $pager = new CRM_Utils_Pager($params); |
| 3732 | $this->assign_by_ref('pager', $pager); |
| 3733 | $this->ajaxResponse['totalRows'] = $this->_rowsFound; |
| 3734 | } |
| 3735 | } |
| 3736 | |
| 3737 | /** |
| 3738 | * Build a group filter with contempt for large data sets. |
| 3739 | * |
| 3740 | * This function has been retained as it takes time to migrate the reports over |
| 3741 | * to the new method which will not crash on large datasets. |
| 3742 | * |
| 3743 | * @deprecated |
| 3744 | * |
| 3745 | * @param array $field |
| 3746 | * @param mixed $value |
| 3747 | * @param string $op |
| 3748 | * |
| 3749 | * @return string |
| 3750 | */ |
| 3751 | public function legacySlowGroupFilterClause($field, $value, $op) { |
| 3752 | $smartGroupQuery = ""; |
| 3753 | |
| 3754 | $group = new CRM_Contact_DAO_Group(); |
| 3755 | $group->is_active = 1; |
| 3756 | $group->find(); |
| 3757 | $smartGroups = []; |
| 3758 | while ($group->fetch()) { |
| 3759 | if (in_array($group->id, (array) $this->_params['gid_value']) && |
| 3760 | $group->saved_search_id |
| 3761 | ) { |
| 3762 | $smartGroups[] = $group->id; |
| 3763 | } |
| 3764 | } |
| 3765 | |
| 3766 | CRM_Contact_BAO_GroupContactCache::check($smartGroups); |
| 3767 | |
| 3768 | $smartGroupQuery = ''; |
| 3769 | if (!empty($smartGroups)) { |
| 3770 | $smartGroups = implode(',', $smartGroups); |
| 3771 | $smartGroupQuery = " UNION DISTINCT |
| 3772 | SELECT DISTINCT smartgroup_contact.contact_id |
| 3773 | FROM civicrm_group_contact_cache smartgroup_contact |
| 3774 | WHERE smartgroup_contact.group_id IN ({$smartGroups}) "; |
| 3775 | } |
| 3776 | |
| 3777 | $sqlOp = $this->getSQLOperator($op); |
| 3778 | if (!is_array($value)) { |
| 3779 | $value = [$value]; |
| 3780 | } |
| 3781 | //include child groups if any |
| 3782 | $value = array_merge($value, CRM_Contact_BAO_Group::getChildGroupIds($value)); |
| 3783 | |
| 3784 | $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")"; |
| 3785 | |
| 3786 | $contactAlias = $this->_aliases['civicrm_contact']; |
| 3787 | if (!empty($this->relationType) && $this->relationType == 'b_a') { |
| 3788 | $contactAlias = $this->_aliases['civicrm_contact_b']; |
| 3789 | } |
| 3790 | return " {$contactAlias}.id {$sqlOp} ( |
| 3791 | SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id |
| 3792 | FROM civicrm_group_contact {$this->_aliases['civicrm_group']} |
| 3793 | WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added' |
| 3794 | {$smartGroupQuery} ) "; |
| 3795 | } |
| 3796 | |
| 3797 | /** |
| 3798 | * Build where clause for groups. |
| 3799 | * |
| 3800 | * @param array $field |
| 3801 | * @param mixed $value |
| 3802 | * @param string $op |
| 3803 | * |
| 3804 | * @return string |
| 3805 | */ |
| 3806 | public function whereGroupClause($field, $value, $op) { |
| 3807 | if ($this->groupFilterNotOptimised) { |
| 3808 | return $this->legacySlowGroupFilterClause($field, $value, $op); |
| 3809 | } |
| 3810 | if ($op === 'notin') { |
| 3811 | return " group_temp_table.contact_id IS NULL "; |
| 3812 | } |
| 3813 | // We will have used an inner join instead. |
| 3814 | return "1"; |
| 3815 | } |
| 3816 | |
| 3817 | /** |
| 3818 | * Create a table of the contact ids included by the group filter. |
| 3819 | * |
| 3820 | * This function is called by both the api (tests) and the UI. |
| 3821 | * |
| 3822 | * @throws \CiviCRM_API3_Exception |
| 3823 | */ |
| 3824 | public function buildGroupTempTable(): void { |
| 3825 | if (!empty($this->groupTempTable) || empty($this->_params['gid_value']) || $this->groupFilterNotOptimised) { |
| 3826 | return; |
| 3827 | } |
| 3828 | $this->groupTempTable = $this->createTemporaryTable('groups', 'contact_id INT', TRUE); |
| 3829 | $filteredGroups = (array) $this->_params['gid_value']; |
| 3830 | CRM_Contact_BAO_GroupContactCache::populateTemporaryTableWithContactsInGroups($filteredGroups, $this->groupTempTable); |
| 3831 | CRM_Core_DAO::executeQuery("ALTER TABLE $this->groupTempTable ADD INDEX contact_id(contact_id)"); |
| 3832 | } |
| 3833 | |
| 3834 | /** |
| 3835 | * Execute query and add it to the developer tab. |
| 3836 | * |
| 3837 | * @param string $query |
| 3838 | * @param array $params |
| 3839 | * |
| 3840 | * @return \CRM_Core_DAO|object |
| 3841 | */ |
| 3842 | protected function executeReportQuery($query, $params = []) { |
| 3843 | $this->addToDeveloperTab($query); |
| 3844 | return CRM_Core_DAO::executeQuery($query, $params); |
| 3845 | } |
| 3846 | |
| 3847 | /** |
| 3848 | * Build where clause for tags. |
| 3849 | * |
| 3850 | * @param array $field |
| 3851 | * @param mixed $value |
| 3852 | * @param string $op |
| 3853 | * |
| 3854 | * @return string |
| 3855 | */ |
| 3856 | public function whereTagClause($field, $value, $op) { |
| 3857 | // not using left join in query because if any contact |
| 3858 | // belongs to more than one tag, results duplicate |
| 3859 | // entries. |
| 3860 | $sqlOp = $this->getSQLOperator($op); |
| 3861 | if (!is_array($value)) { |
| 3862 | $value = [$value]; |
| 3863 | } |
| 3864 | $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")"; |
| 3865 | $entity_table = $this->_tagFilterTable; |
| 3866 | return " {$this->_aliases[$entity_table]}.id {$sqlOp} ( |
| 3867 | SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id |
| 3868 | FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']} |
| 3869 | WHERE entity_table = '$entity_table' AND {$clause} ) "; |
| 3870 | } |
| 3871 | |
| 3872 | /** |
| 3873 | * Generate membership organization clause. |
| 3874 | * |
| 3875 | * @param mixed $value |
| 3876 | * @param string $op SQL Operator |
| 3877 | * |
| 3878 | * @return string |
| 3879 | */ |
| 3880 | public function whereMembershipOrgClause($value, $op) { |
| 3881 | $sqlOp = $this->getSQLOperator($op); |
| 3882 | if (!is_array($value)) { |
| 3883 | $value = [$value]; |
| 3884 | } |
| 3885 | |
| 3886 | $tmp_membership_org_sql_list = implode(', ', $value); |
| 3887 | return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} ( |
| 3888 | SELECT DISTINCT mem.contact_id |
| 3889 | FROM civicrm_membership mem |
| 3890 | LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id |
| 3891 | LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id |
| 3892 | WHERE mt.member_of_contact_id IN (" . |
| 3893 | $tmp_membership_org_sql_list . ") |
| 3894 | AND mt.is_active = '1' |
| 3895 | AND mem_status.is_current_member = '1' |
| 3896 | AND mem_status.is_active = '1' ) "; |
| 3897 | } |
| 3898 | |
| 3899 | /** |
| 3900 | * Generate Membership Type SQL Clause. |
| 3901 | * |
| 3902 | * @param mixed $value |
| 3903 | * @param string $op |
| 3904 | * |
| 3905 | * @return string |
| 3906 | * SQL query string |
| 3907 | */ |
| 3908 | public function whereMembershipTypeClause($value, $op) { |
| 3909 | $sqlOp = $this->getSQLOperator($op); |
| 3910 | if (!is_array($value)) { |
| 3911 | $value = [$value]; |
| 3912 | } |
| 3913 | |
| 3914 | $tmp_membership_sql_list = implode(', ', $value); |
| 3915 | return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} ( |
| 3916 | SELECT DISTINCT mem.contact_id |
| 3917 | FROM civicrm_membership mem |
| 3918 | LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id |
| 3919 | LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id |
| 3920 | WHERE mem.membership_type_id IN (" . |
| 3921 | $tmp_membership_sql_list . ") |
| 3922 | AND mt.is_active = '1' |
| 3923 | AND mem_status.is_current_member = '1' |
| 3924 | AND mem_status.is_active = '1' ) "; |
| 3925 | } |
| 3926 | |
| 3927 | /** |
| 3928 | * Build contact acl clause |
| 3929 | * @deprecated in favor of buildPermissionClause |
| 3930 | * |
| 3931 | * Note that if the buildPermissionClause function is called (which most reports do from |
| 3932 | * buildQuery then the results of this function are re-calculated and overwritten. |
| 3933 | * |
| 3934 | * @param string $tableAlias |
| 3935 | */ |
| 3936 | public function buildACLClause($tableAlias = 'contact_a') { |
| 3937 | [$this->_aclFrom, $this->_aclWhere] = CRM_Contact_BAO_Contact_Permission::cacheClause($tableAlias); |
| 3938 | } |
| 3939 | |
| 3940 | /** |
| 3941 | * Build the permission clause for all entities in this report |
| 3942 | */ |
| 3943 | public function buildPermissionClause() { |
| 3944 | $ret = []; |
| 3945 | foreach ($this->selectedTables() as $tableName) { |
| 3946 | $baoName = str_replace('_DAO_', '_BAO_', CRM_Core_DAO_AllCoreTables::getClassForTable($tableName)); |
| 3947 | if ($baoName && class_exists($baoName) && !empty($this->_columns[$tableName]['alias'])) { |
| 3948 | $tableAlias = $this->_columns[$tableName]['alias']; |
| 3949 | $clauses = array_filter($baoName::getSelectWhereClause($tableAlias)); |
| 3950 | foreach ($clauses as $field => $clause) { |
| 3951 | // Skip contact_id field if redundant |
| 3952 | if ($field != 'contact_id' || !in_array('civicrm_contact', $this->selectedTables())) { |
| 3953 | $ret["$tableName.$field"] = $clause; |
| 3954 | } |
| 3955 | } |
| 3956 | } |
| 3957 | } |
| 3958 | // Override output from buildACLClause |
| 3959 | $this->_aclFrom = NULL; |
| 3960 | $this->_aclWhere = implode(' AND ', $ret); |
| 3961 | } |
| 3962 | |
| 3963 | /** |
| 3964 | * Add custom data to the columns. |
| 3965 | * |
| 3966 | * @param bool $addFields |
| 3967 | * @param array $permCustomGroupIds |
| 3968 | */ |
| 3969 | public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = []) { |
| 3970 | if (empty($this->_customGroupExtends)) { |
| 3971 | return; |
| 3972 | } |
| 3973 | if (!is_array($this->_customGroupExtends)) { |
| 3974 | $this->_customGroupExtends = [$this->_customGroupExtends]; |
| 3975 | } |
| 3976 | $customGroupWhere = ''; |
| 3977 | if (!empty($permCustomGroupIds)) { |
| 3978 | $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) . |
| 3979 | ") AND"; |
| 3980 | } |
| 3981 | $sql = " |
| 3982 | SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label, |
| 3983 | cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format, |
| 3984 | cf.serialize as serialize |
| 3985 | FROM civicrm_custom_group cg |
| 3986 | INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id |
| 3987 | WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends) . "') AND |
| 3988 | {$customGroupWhere} |
| 3989 | cg.is_active = 1 AND |
| 3990 | cf.is_active = 1 AND |
| 3991 | cf.is_searchable = 1 |
| 3992 | ORDER BY cg.weight, cf.weight"; |
| 3993 | $customDAO = CRM_Core_DAO::executeQuery($sql); |
| 3994 | |
| 3995 | $curTable = NULL; |
| 3996 | while ($customDAO->fetch()) { |
| 3997 | if ($customDAO->table_name != $curTable) { |
| 3998 | $curTable = $customDAO->table_name; |
| 3999 | $curFields = $curFilters = []; |
| 4000 | |
| 4001 | // dummy dao object |
| 4002 | $this->_columns[$curTable]['dao'] = 'CRM_Contact_DAO_Contact'; |
| 4003 | $this->_columns[$curTable]['extends'] = $customDAO->extends; |
| 4004 | $this->_columns[$curTable]['grouping'] = $customDAO->table_name; |
| 4005 | $this->_columns[$curTable]['group_title'] = $customDAO->title; |
| 4006 | |
| 4007 | foreach (['fields', 'filters', 'group_bys'] as $colKey) { |
| 4008 | if (!array_key_exists($colKey, $this->_columns[$curTable])) { |
| 4009 | $this->_columns[$curTable][$colKey] = []; |
| 4010 | } |
| 4011 | } |
| 4012 | } |
| 4013 | $fieldName = 'custom_' . $customDAO->cf_id; |
| 4014 | |
| 4015 | if ($addFields) { |
| 4016 | // this makes aliasing work in favor |
| 4017 | $curFields[$fieldName] = [ |
| 4018 | 'name' => $customDAO->column_name, |
| 4019 | 'title' => $customDAO->label, |
| 4020 | 'dataType' => $customDAO->data_type, |
| 4021 | 'htmlType' => $customDAO->html_type, |
| 4022 | ]; |
| 4023 | } |
| 4024 | if ($this->_customGroupFilters) { |
| 4025 | // this makes aliasing work in favor |
| 4026 | $curFilters[$fieldName] = [ |
| 4027 | 'name' => $customDAO->column_name, |
| 4028 | 'title' => $customDAO->label, |
| 4029 | 'dataType' => $customDAO->data_type, |
| 4030 | 'htmlType' => $customDAO->html_type, |
| 4031 | ]; |
| 4032 | } |
| 4033 | |
| 4034 | switch ($customDAO->data_type) { |
| 4035 | case 'Date': |
| 4036 | // filters |
| 4037 | $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_DATE; |
| 4038 | $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_DATE; |
| 4039 | // CRM-6946, show time part for datetime date fields |
| 4040 | if ($customDAO->time_format) { |
| 4041 | $curFields[$fieldName]['type'] = CRM_Utils_Type::T_TIMESTAMP; |
| 4042 | } |
| 4043 | break; |
| 4044 | |
| 4045 | case 'Boolean': |
| 4046 | $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_SELECT; |
| 4047 | $curFilters[$fieldName]['options'] = ['' => ts('- select -')] + CRM_Core_PseudoConstant::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id, [], 'search'); |
| 4048 | $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_INT; |
| 4049 | break; |
| 4050 | |
| 4051 | case 'Int': |
| 4052 | $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_INT; |
| 4053 | $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_INT; |
| 4054 | break; |
| 4055 | |
| 4056 | case 'Money': |
| 4057 | $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_FLOAT; |
| 4058 | $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_MONEY; |
| 4059 | // Use T_FLOAT instead of T_MONEY as the money number format happens |
| 4060 | // by calling CRM_Core_BAO_CustomField::displayValue in alterCustomDataDisplay |
| 4061 | $curFields[$fieldName]['type'] = CRM_Utils_Type::T_FLOAT; |
| 4062 | break; |
| 4063 | |
| 4064 | case 'Float': |
| 4065 | $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_FLOAT; |
| 4066 | $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_FLOAT; |
| 4067 | break; |
| 4068 | |
| 4069 | case 'String': |
| 4070 | case 'StateProvince': |
| 4071 | case 'Country': |
| 4072 | $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING; |
| 4073 | |
| 4074 | $options = CRM_Core_PseudoConstant::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id, [], 'search'); |
| 4075 | if ((is_array($options) && count($options) != 0) || (!is_array($options) && $options !== FALSE)) { |
| 4076 | $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField::isSerialized($customDAO) ? CRM_Report_Form::OP_MULTISELECT_SEPARATOR : CRM_Report_Form::OP_MULTISELECT; |
| 4077 | $curFilters[$fieldName]['options'] = $options; |
| 4078 | } |
| 4079 | break; |
| 4080 | |
| 4081 | case 'ContactReference': |
| 4082 | $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING; |
| 4083 | $curFilters[$fieldName]['name'] = 'display_name'; |
| 4084 | $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport"; |
| 4085 | |
| 4086 | $curFields[$fieldName]['type'] = CRM_Utils_Type::T_STRING; |
| 4087 | $curFields[$fieldName]['name'] = 'display_name'; |
| 4088 | $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport"; |
| 4089 | break; |
| 4090 | |
| 4091 | default: |
| 4092 | $curFields[$fieldName]['type'] = CRM_Utils_Type::T_STRING; |
| 4093 | $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING; |
| 4094 | } |
| 4095 | |
| 4096 | // CRM-19401 fix |
| 4097 | if ($customDAO->html_type == 'Select' && !array_key_exists('options', $curFilters[$fieldName])) { |
| 4098 | $options = CRM_Core_PseudoConstant::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id, [], 'search'); |
| 4099 | if ($options !== FALSE) { |
| 4100 | $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField::isSerialized($customDAO) ? CRM_Report_Form::OP_MULTISELECT_SEPARATOR : CRM_Report_Form::OP_MULTISELECT; |
| 4101 | $curFilters[$fieldName]['options'] = $options; |
| 4102 | } |
| 4103 | } |
| 4104 | |
| 4105 | if (!array_key_exists('type', $curFields[$fieldName])) { |
| 4106 | $curFields[$fieldName]['type'] = CRM_Utils_Array::value('type', $curFilters[$fieldName], []); |
| 4107 | } |
| 4108 | |
| 4109 | if ($addFields) { |
| 4110 | $this->_columns[$curTable]['fields'] = array_merge($this->_columns[$curTable]['fields'], $curFields); |
| 4111 | } |
| 4112 | if ($this->_customGroupFilters) { |
| 4113 | $this->_columns[$curTable]['filters'] = array_merge($this->_columns[$curTable]['filters'], $curFilters); |
| 4114 | } |
| 4115 | if ($this->_customGroupGroupBy) { |
| 4116 | $this->_columns[$curTable]['group_bys'] = array_merge($this->_columns[$curTable]['group_bys'], $curFields); |
| 4117 | } |
| 4118 | } |
| 4119 | } |
| 4120 | |
| 4121 | /** |
| 4122 | * Build custom data from clause. |
| 4123 | * |
| 4124 | * @param bool $joinsForFiltersOnly |
| 4125 | * Only include joins to support filters. This would be used if creating a table of contacts to include first. |
| 4126 | */ |
| 4127 | public function customDataFrom($joinsForFiltersOnly = FALSE) { |
| 4128 | if (empty($this->_customGroupExtends)) { |
| 4129 | return; |
| 4130 | } |
| 4131 | $mapper = CRM_Core_BAO_CustomQuery::$extendsMap; |
| 4132 | //CRM-18276 GROUP_CONCAT could be used with singleValueQuery and then exploded, |
| 4133 | //but by default that truncates to 1024 characters, which causes errors with installs with lots of custom field sets |
| 4134 | $customTables = []; |
| 4135 | $customTablesDAO = CRM_Core_DAO::executeQuery("SELECT table_name FROM civicrm_custom_group"); |
| 4136 | while ($customTablesDAO->fetch()) { |
| 4137 | $customTables[] = $customTablesDAO->table_name; |
| 4138 | } |
| 4139 | |
| 4140 | foreach ($this->_columns as $table => $prop) { |
| 4141 | if (in_array($table, $customTables)) { |
| 4142 | $extendsTable = $mapper[$prop['extends']]; |
| 4143 | // Check field is required for rendering the report. |
| 4144 | if ((!$this->isFieldSelected($prop)) || ($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) { |
| 4145 | continue; |
| 4146 | } |
| 4147 | $baseJoin = CRM_Utils_Array::value($prop['extends'], $this->_customGroupExtendsJoin, "{$this->_aliases[$extendsTable]}.id"); |
| 4148 | |
| 4149 | $customJoin = is_array($this->_customGroupJoin) ? $this->_customGroupJoin[$table] : $this->_customGroupJoin; |
| 4150 | $this->_from .= " |
| 4151 | {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}"; |
| 4152 | // handle for ContactReference |
| 4153 | if (array_key_exists('fields', $prop)) { |
| 4154 | foreach ($prop['fields'] as $fieldName => $field) { |
| 4155 | if (CRM_Utils_Array::value('dataType', $field) == |
| 4156 | 'ContactReference' |
| 4157 | ) { |
| 4158 | $columnName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField::getKeyID($fieldName), 'column_name'); |
| 4159 | $this->_from .= " |
| 4160 | LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} "; |
| 4161 | } |
| 4162 | } |
| 4163 | } |
| 4164 | } |
| 4165 | } |
| 4166 | } |
| 4167 | |
| 4168 | /** |
| 4169 | * Check if the field is selected. |
| 4170 | * |
| 4171 | * @param string $prop |
| 4172 | * |
| 4173 | * @return bool |
| 4174 | */ |
| 4175 | public function isFieldSelected($prop) { |
| 4176 | if (empty($prop)) { |
| 4177 | return FALSE; |
| 4178 | } |
| 4179 | |
| 4180 | if (!empty($this->_params['fields'])) { |
| 4181 | foreach (array_keys($prop['fields']) as $fieldAlias) { |
| 4182 | $customFieldId = CRM_Core_BAO_CustomField::getKeyID($fieldAlias); |
| 4183 | if ($customFieldId) { |
| 4184 | if (array_key_exists($fieldAlias, $this->_params['fields'])) { |
| 4185 | return TRUE; |
| 4186 | } |
| 4187 | |
| 4188 | //might be survey response field. |
| 4189 | if (!empty($this->_params['fields']['survey_response']) && |
| 4190 | !empty($prop['fields'][$fieldAlias]['isSurveyResponseField']) |
| 4191 | ) { |
| 4192 | return TRUE; |
| 4193 | } |
| 4194 | } |
| 4195 | } |
| 4196 | } |
| 4197 | |
| 4198 | if (!empty($this->_params['group_bys']) && $this->_customGroupGroupBy) { |
| 4199 | foreach (array_keys($prop['group_bys']) as $fieldAlias) { |
| 4200 | if (array_key_exists($fieldAlias, $this->_params['group_bys']) && |
| 4201 | CRM_Core_BAO_CustomField::getKeyID($fieldAlias) |
| 4202 | ) { |
| 4203 | return TRUE; |
| 4204 | } |
| 4205 | } |
| 4206 | } |
| 4207 | |
| 4208 | if (!empty($this->_params['order_bys'])) { |
| 4209 | foreach (array_keys($prop['fields']) as $fieldAlias) { |
| 4210 | foreach ($this->_params['order_bys'] as $orderBy) { |
| 4211 | if ($fieldAlias == $orderBy['column'] && |
| 4212 | CRM_Core_BAO_CustomField::getKeyID($fieldAlias) |
| 4213 | ) { |
| 4214 | return TRUE; |
| 4215 | } |
| 4216 | } |
| 4217 | } |
| 4218 | } |
| 4219 | return $this->isFieldFiltered($prop); |
| 4220 | |
| 4221 | } |
| 4222 | |
| 4223 | /** |
| 4224 | * Check if the field is used as a filter. |
| 4225 | * |
| 4226 | * @param string $prop |
| 4227 | * |
| 4228 | * @return bool |
| 4229 | */ |
| 4230 | protected function isFieldFiltered($prop) { |
| 4231 | if (!empty($prop['filters']) && $this->_customGroupFilters) { |
| 4232 | foreach ($prop['filters'] as $fieldAlias => $val) { |
| 4233 | foreach ([ |
| 4234 | 'value', |
| 4235 | 'min', |
| 4236 | 'max', |
| 4237 | 'relative', |
| 4238 | 'from', |
| 4239 | 'to', |
| 4240 | ] as $attach) { |
| 4241 | if (isset($this->_params[$fieldAlias . '_' . $attach]) && |
| 4242 | (!empty($this->_params[$fieldAlias . '_' . $attach]) |
| 4243 | || ($attach != 'relative' && |
| 4244 | $this->_params[$fieldAlias . '_' . $attach] == '0') |
| 4245 | ) |
| 4246 | ) { |
| 4247 | return TRUE; |
| 4248 | } |
| 4249 | } |
| 4250 | if (!empty($this->_params[$fieldAlias . '_op']) && |
| 4251 | in_array($this->_params[$fieldAlias . '_op'], ['nll', 'nnll']) |
| 4252 | ) { |
| 4253 | return TRUE; |
| 4254 | } |
| 4255 | } |
| 4256 | } |
| 4257 | |
| 4258 | return FALSE; |
| 4259 | } |
| 4260 | |
| 4261 | /** |
| 4262 | * Check for empty order_by configurations and remove them. |
| 4263 | * |
| 4264 | * Also set template to hide them. |
| 4265 | * |
| 4266 | * @param array $formValues |
| 4267 | */ |
| 4268 | public function preProcessOrderBy(&$formValues) { |
| 4269 | // Object to show/hide form elements |
| 4270 | $_showHide = new CRM_Core_ShowHideBlocks(); |
| 4271 | |
| 4272 | $_showHide->addShow('optionField_1'); |
| 4273 | |
| 4274 | // Cycle through order_by options; skip any empty ones, and hide them as well |
| 4275 | $n = 1; |
| 4276 | |
| 4277 | if (!empty($formValues['order_bys'])) { |
| 4278 | foreach ($formValues['order_bys'] as $order_by) { |
| 4279 | if ($order_by['column'] && $order_by['column'] != '-') { |
| 4280 | $_showHide->addShow('optionField_' . $n); |
| 4281 | $orderBys[$n] = $order_by; |
| 4282 | $n++; |
| 4283 | } |
| 4284 | } |
| 4285 | } |
| 4286 | for ($i = $n; $i <= 5; $i++) { |
| 4287 | if ($i > 1) { |
| 4288 | $_showHide->addHide('optionField_' . $i); |
| 4289 | } |
| 4290 | } |
| 4291 | |
| 4292 | // overwrite order_by options with modified values |
| 4293 | if (!empty($orderBys)) { |
| 4294 | $formValues['order_bys'] = $orderBys; |
| 4295 | } |
| 4296 | else { |
| 4297 | $formValues['order_bys'] = [1 => ['column' => '-']]; |
| 4298 | } |
| 4299 | |
| 4300 | // assign show/hide data to template |
| 4301 | $_showHide->addToTemplate(); |
| 4302 | } |
| 4303 | |
| 4304 | /** |
| 4305 | * Check if table name has columns in SELECT clause. |
| 4306 | * |
| 4307 | * @param string $tableName |
| 4308 | * Name of table (index of $this->_columns array). |
| 4309 | * |
| 4310 | * @return bool |
| 4311 | */ |
| 4312 | public function isTableSelected($tableName) { |
| 4313 | return in_array($tableName, $this->selectedTables()); |
| 4314 | } |
| 4315 | |
| 4316 | /** |
| 4317 | * Check if table name has columns in WHERE or HAVING clause. |
| 4318 | * |
| 4319 | * @param string $tableName |
| 4320 | * Name of table (index of $this->_columns array). |
| 4321 | * |
| 4322 | * @return bool |
| 4323 | */ |
| 4324 | public function isTableFiltered($tableName) { |
| 4325 | // Cause the array to be generated if not previously done. |
| 4326 | if (!$this->_selectedTables && !$this->filteredTables) { |
| 4327 | $this->selectedTables(); |
| 4328 | } |
| 4329 | return in_array($tableName, $this->filteredTables); |
| 4330 | } |
| 4331 | |
| 4332 | /** |
| 4333 | * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause. |
| 4334 | * |
| 4335 | * If the array is unset it will be built. |
| 4336 | * |
| 4337 | * @return array |
| 4338 | * selectedTables |
| 4339 | */ |
| 4340 | public function selectedTables() { |
| 4341 | if (!$this->_selectedTables) { |
| 4342 | $orderByColumns = []; |
| 4343 | if (array_key_exists('order_bys', $this->_params) && |
| 4344 | is_array($this->_params['order_bys']) |
| 4345 | ) { |
| 4346 | foreach ($this->_params['order_bys'] as $orderBy) { |
| 4347 | $orderByColumns[] = $orderBy['column']; |
| 4348 | } |
| 4349 | } |
| 4350 | |
| 4351 | foreach ($this->_columns as $tableName => $table) { |
| 4352 | if (array_key_exists('fields', $table)) { |
| 4353 | foreach ($table['fields'] as $fieldName => $field) { |
| 4354 | if (!empty($field['required']) || |
| 4355 | !empty($this->_params['fields'][$fieldName]) |
| 4356 | ) { |
| 4357 | $this->_selectedTables[] = $tableName; |
| 4358 | break; |
| 4359 | } |
| 4360 | } |
| 4361 | } |
| 4362 | if (array_key_exists('order_bys', $table)) { |
| 4363 | foreach ($table['order_bys'] as $orderByName => $orderBy) { |
| 4364 | if (in_array($orderByName, $orderByColumns)) { |
| 4365 | $this->_selectedTables[] = $tableName; |
| 4366 | break; |
| 4367 | } |
| 4368 | } |
| 4369 | } |
| 4370 | if (array_key_exists('filters', $table)) { |
| 4371 | foreach ($table['filters'] as $filterName => $filter) { |
| 4372 | $filterOp = $this->_params["{$filterName}_op"] ?? ''; |
| 4373 | if ((isset($this->_params["{$filterName}_value"]) |
| 4374 | && !CRM_Utils_System::isNull($this->_params["{$filterName}_value"])) |
| 4375 | || !empty($this->_params["{$filterName}_relative"]) |
| 4376 | || $filterOp === 'nll' |
| 4377 | || $filterOp === 'nnll' |
| 4378 | ) { |
| 4379 | $this->_selectedTables[] = $tableName; |
| 4380 | $this->filteredTables[] = $tableName; |
| 4381 | break; |
| 4382 | } |
| 4383 | } |
| 4384 | } |
| 4385 | } |
| 4386 | } |
| 4387 | return $this->_selectedTables; |
| 4388 | } |
| 4389 | |
| 4390 | /** |
| 4391 | * Add campaign fields. |
| 4392 | * @param string $entityTable |
| 4393 | * @param bool $groupBy |
| 4394 | * Add GroupBy? Not appropriate for detail report. |
| 4395 | * @param bool $orderBy |
| 4396 | * Add OrderBy? Not appropriate for detail report. |
| 4397 | * @param bool $filters |
| 4398 | * |
| 4399 | */ |
| 4400 | public function addCampaignFields($entityTable = 'civicrm_contribution', $groupBy = FALSE, $orderBy = FALSE, $filters = TRUE) { |
| 4401 | // Check if CiviCampaign is a) enabled and b) has active campaigns |
| 4402 | $config = CRM_Core_Config::singleton(); |
| 4403 | $campaignEnabled = in_array('CiviCampaign', $config->enableComponents); |
| 4404 | if ($campaignEnabled) { |
| 4405 | $getCampaigns = CRM_Campaign_BAO_Campaign::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, TRUE); |
| 4406 | // If we have a campaign, build out the relevant elements |
| 4407 | if (!empty($getCampaigns['campaigns'])) { |
| 4408 | $this->campaigns = $getCampaigns['campaigns']; |
| 4409 | asort($this->campaigns); |
| 4410 | $this->_columns[$entityTable]['fields']['campaign_id'] = ['title' => ts('Campaign'), 'default' => 'false']; |
| 4411 | if ($filters) { |
| 4412 | $this->_columns[$entityTable]['filters']['campaign_id'] = [ |
| 4413 | 'title' => ts('Campaign'), |
| 4414 | 'operatorType' => CRM_Report_Form::OP_MULTISELECT, |
| 4415 | 'options' => $this->campaigns, |
| 4416 | 'type' => CRM_Utils_Type::T_INT, |
| 4417 | ]; |
| 4418 | } |
| 4419 | |
| 4420 | if ($groupBy) { |
| 4421 | $this->_columns[$entityTable]['group_bys']['campaign_id'] = ['title' => ts('Campaign')]; |
| 4422 | } |
| 4423 | |
| 4424 | if ($orderBy) { |
| 4425 | $this->_columns[$entityTable]['order_bys']['campaign_id'] = ['title' => ts('Campaign')]; |
| 4426 | } |
| 4427 | } |
| 4428 | } |
| 4429 | } |
| 4430 | |
| 4431 | /** |
| 4432 | * Add address fields. |
| 4433 | * |
| 4434 | * @deprecated - use getAddressColumns which is a more accurate description |
| 4435 | * and also accepts an array of options rather than a long list |
| 4436 | * |
| 4437 | * adding address fields to construct function in reports |
| 4438 | * |
| 4439 | * @param bool $groupBy |
| 4440 | * Add GroupBy? Not appropriate for detail report. |
| 4441 | * @param bool $orderBy |
| 4442 | * Add GroupBy? Not appropriate for detail report. |
| 4443 | * @param bool $filters |
| 4444 | * @param array $defaults |
| 4445 | * |
| 4446 | * @return array |
| 4447 | * address fields for construct clause |
| 4448 | */ |
| 4449 | public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = ['country_id' => TRUE]) { |
| 4450 | $defaultAddressFields = [ |
| 4451 | 'street_address' => ts('Street Address'), |
| 4452 | 'supplemental_address_1' => ts('Supplementary Address Field 1'), |
| 4453 | 'supplemental_address_2' => ts('Supplementary Address Field 2'), |
| 4454 | 'supplemental_address_3' => ts('Supplementary Address Field 3'), |
| 4455 | 'street_number' => ts('Street Number'), |
| 4456 | 'street_name' => ts('Street Name'), |
| 4457 | 'street_unit' => ts('Street Unit'), |
| 4458 | 'city' => ts('City'), |
| 4459 | 'postal_code' => ts('Postal Code'), |
| 4460 | 'postal_code_suffix' => ts('Postal Code Suffix'), |
| 4461 | 'country_id' => ts('Country'), |
| 4462 | 'state_province_id' => ts('State/Province'), |
| 4463 | 'county_id' => ts('County'), |
| 4464 | ]; |
| 4465 | $addressFields = [ |
| 4466 | 'civicrm_address' => [ |
| 4467 | 'dao' => 'CRM_Core_DAO_Address', |
| 4468 | 'fields' => [ |
| 4469 | 'address_name' => [ |
| 4470 | 'title' => ts('Address Name'), |
| 4471 | 'default' => $defaults['name'] ?? FALSE, |
| 4472 | 'name' => 'name', |
| 4473 | ], |
| 4474 | ], |
| 4475 | 'grouping' => 'location-fields', |
| 4476 | ], |
| 4477 | ]; |
| 4478 | foreach ($defaultAddressFields as $fieldName => $fieldLabel) { |
| 4479 | $addressFields['civicrm_address']['fields'][$fieldName] = [ |
| 4480 | 'title' => $fieldLabel, |
| 4481 | 'default' => $defaults[$fieldName] ?? FALSE, |
| 4482 | ]; |
| 4483 | } |
| 4484 | |
| 4485 | $street_address_filters = $general_address_filters = []; |
| 4486 | if ($filters) { |
| 4487 | // Address filter depends on whether street address parsing is enabled. |
| 4488 | // (CRM-18696) |
| 4489 | $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, |
| 4490 | 'address_options' |
| 4491 | ); |
| 4492 | if ($addressOptions['street_address_parsing']) { |
| 4493 | $street_address_filters = [ |
| 4494 | 'street_number' => [ |
| 4495 | 'title' => ts('Street Number'), |
| 4496 | 'type' => CRM_Utils_Type::T_INT, |
| 4497 | 'name' => 'street_number', |
| 4498 | ], |
| 4499 | 'street_name' => [ |
| 4500 | 'title' => ts('Street Name'), |
| 4501 | 'name' => 'street_name', |
| 4502 | 'type' => CRM_Utils_Type::T_STRING, |
| 4503 | ], |
| 4504 | ]; |
| 4505 | } |
| 4506 | else { |
| 4507 | $street_address_filters = [ |
| 4508 | 'street_address' => [ |
| 4509 | 'title' => ts('Street Address'), |
| 4510 | 'type' => CRM_Utils_Type::T_STRING, |
| 4511 | 'name' => 'street_address', |
| 4512 | ], |
| 4513 | ]; |
| 4514 | } |
| 4515 | $general_address_filters = [ |
| 4516 | 'postal_code' => [ |
| 4517 | 'title' => ts('Postal Code'), |
| 4518 | 'type' => CRM_Utils_Type::T_STRING, |
| 4519 | 'name' => 'postal_code', |
| 4520 | ], |
| 4521 | 'city' => [ |
| 4522 | 'title' => ts('City'), |
| 4523 | 'type' => CRM_Utils_Type::T_STRING, |
| 4524 | 'name' => 'city', |
| 4525 | ], |
| 4526 | 'country_id' => [ |
| 4527 | 'name' => 'country_id', |
| 4528 | 'title' => ts('Country'), |
| 4529 | 'type' => CRM_Utils_Type::T_INT, |
| 4530 | 'operatorType' => CRM_Report_Form::OP_MULTISELECT, |
| 4531 | 'options' => CRM_Core_PseudoConstant::country(), |
| 4532 | ], |
| 4533 | 'state_province_id' => [ |
| 4534 | 'name' => 'state_province_id', |
| 4535 | 'title' => ts('State/Province'), |
| 4536 | 'type' => CRM_Utils_Type::T_INT, |
| 4537 | 'operatorType' => CRM_Report_Form::OP_MULTISELECT, |
| 4538 | 'options' => [], |
| 4539 | ], |
| 4540 | 'county_id' => [ |
| 4541 | 'name' => 'county_id', |
| 4542 | 'title' => ts('County'), |
| 4543 | 'type' => CRM_Utils_Type::T_INT, |
| 4544 | 'operatorType' => CRM_Report_Form::OP_MULTISELECT, |
| 4545 | 'options' => [], |
| 4546 | ], |
| 4547 | ]; |
| 4548 | } |
| 4549 | $addressFields['civicrm_address']['filters'] = array_merge( |
| 4550 | $street_address_filters, |
| 4551 | $general_address_filters); |
| 4552 | |
| 4553 | if ($orderBy) { |
| 4554 | $addressFields['civicrm_address']['order_bys'] = [ |
| 4555 | 'street_name' => ['title' => ts('Street Name')], |
| 4556 | 'street_number' => ['title' => ts('Odd / Even Street Number')], |
| 4557 | 'street_address' => NULL, |
| 4558 | 'city' => NULL, |
| 4559 | 'postal_code' => NULL, |
| 4560 | ]; |
| 4561 | } |
| 4562 | |
| 4563 | if ($groupBy) { |
| 4564 | $addressFields['civicrm_address']['group_bys'] = [ |
| 4565 | 'street_address' => NULL, |
| 4566 | 'city' => NULL, |
| 4567 | 'postal_code' => NULL, |
| 4568 | 'state_province_id' => [ |
| 4569 | 'title' => ts('State/Province'), |
| 4570 | ], |
| 4571 | 'country_id' => [ |
| 4572 | 'title' => ts('Country'), |
| 4573 | ], |
| 4574 | 'county_id' => [ |
| 4575 | 'title' => ts('County'), |
| 4576 | ], |
| 4577 | ]; |
| 4578 | } |
| 4579 | return $addressFields; |
| 4580 | } |
| 4581 | |
| 4582 | /** |
| 4583 | * Do AlterDisplay processing on Address Fields. |
| 4584 | * If there are multiple address field values then |
| 4585 | * on basis of provided separator the code values are translated into respective labels |
| 4586 | * |
| 4587 | * @param array $row |
| 4588 | * @param array $rows |
| 4589 | * @param int $rowNum |
| 4590 | * @param string|null $baseUrl |
| 4591 | * @param string|null $linkText |
| 4592 | * @param string $separator |
| 4593 | * |
| 4594 | * @return bool |
| 4595 | */ |
| 4596 | public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText, $separator = ',') { |
| 4597 | $criteriaQueryParams = CRM_Report_Utils_Report::getPreviewCriteriaQueryParams($this->_defaults, $this->_params); |
| 4598 | $entryFound = FALSE; |
| 4599 | $columnMap = [ |
| 4600 | 'civicrm_address_country_id' => 'country', |
| 4601 | 'civicrm_address_county_id' => 'county', |
| 4602 | 'civicrm_address_state_province_id' => 'stateProvince', |
| 4603 | ]; |
| 4604 | foreach ($columnMap as $fieldName => $fnName) { |
| 4605 | if (array_key_exists($fieldName, $row)) { |
| 4606 | if ($values = $row[$fieldName]) { |
| 4607 | $values = (array) explode($separator, $values); |
| 4608 | $rows[$rowNum][$fieldName] = []; |
| 4609 | $addressField = $fnName == 'stateProvince' ? 'state' : $fnName; |
| 4610 | foreach ($values as $value) { |
| 4611 | $rows[$rowNum][$fieldName][] = CRM_Core_PseudoConstant::$fnName($value); |
| 4612 | } |
| 4613 | $rows[$rowNum][$fieldName] = implode($separator, $rows[$rowNum][$fieldName]); |
| 4614 | if ($baseUrl) { |
| 4615 | $url = CRM_Report_Utils_Report::getNextUrl($baseUrl, |
| 4616 | sprintf("reset=1&force=1&%s&%s_op=in&%s_value=%s", |
| 4617 | $criteriaQueryParams, |
| 4618 | str_replace('civicrm_address_', '', $fieldName), |
| 4619 | str_replace('civicrm_address_', '', $fieldName), |
| 4620 | implode(',', $values) |
| 4621 | ), $this->_absoluteUrl, $this->_id |
| 4622 | ); |
| 4623 | $rows[$rowNum]["{$fieldName}_link"] = $url; |
| 4624 | $rows[$rowNum]["{$fieldName}_hover"] = ts("%1 for this %2.", [1 => $linkText, 2 => $addressField]); |
| 4625 | } |
| 4626 | } |
| 4627 | $entryFound = TRUE; |
| 4628 | } |
| 4629 | } |
| 4630 | |
| 4631 | return $entryFound; |
| 4632 | } |
| 4633 | |
| 4634 | /** |
| 4635 | * Do AlterDisplay processing on Address Fields. |
| 4636 | * |
| 4637 | * @param array $row |
| 4638 | * @param array $rows |
| 4639 | * @param int $rowNum |
| 4640 | * @param string|null $baseUrl |
| 4641 | * @param string|null $linkText |
| 4642 | * |
| 4643 | * @return bool |
| 4644 | */ |
| 4645 | public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) { |
| 4646 | $entryFound = FALSE; |
| 4647 | // There is no reason not to add links for all fields but it seems a bit odd to be able to click on |
| 4648 | // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks. |
| 4649 | $addLinks = ['gender_id' => 'Gender']; |
| 4650 | foreach (['prefix_id', 'suffix_id', 'gender_id', 'contact_sub_type', 'preferred_language'] as $fieldName) { |
| 4651 | if (array_key_exists('civicrm_contact_' . $fieldName, $row)) { |
| 4652 | if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) { |
| 4653 | $rowValues = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value); |
| 4654 | $rowLabels = []; |
| 4655 | foreach ($rowValues as $rowValue) { |
| 4656 | if ($rowValue) { |
| 4657 | $rowLabels[] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_BAO_Contact', $fieldName, $rowValue); |
| 4658 | } |
| 4659 | } |
| 4660 | $rows[$rowNum]['civicrm_contact_' . $fieldName] = implode(', ', $rowLabels); |
| 4661 | if ($baseUrl && ($title = CRM_Utils_Array::value($fieldName, $addLinks)) != FALSE) { |
| 4662 | $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title); |
| 4663 | } |
| 4664 | } |
| 4665 | $entryFound = TRUE; |
| 4666 | } |
| 4667 | } |
| 4668 | $yesNoFields = [ |
| 4669 | 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'do_not_trade', 'is_opt_out', |
| 4670 | ]; |
| 4671 | foreach ($yesNoFields as $fieldName) { |
| 4672 | if (array_key_exists('civicrm_contact_' . $fieldName, $row)) { |
| 4673 | // Since these are essentially 'negative fields' it feels like it |
| 4674 | // makes sense to only highlight the exceptions hence no 'No'. |
| 4675 | $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ? ts('Yes') : ''; |
| 4676 | $entryFound = TRUE; |
| 4677 | } |
| 4678 | } |
| 4679 | |
| 4680 | // Handle employer id |
| 4681 | if (array_key_exists('civicrm_contact_employer_id', $row)) { |
| 4682 | $employerId = $row['civicrm_contact_employer_id']; |
| 4683 | if ($employerId) { |
| 4684 | $rows[$rowNum]['civicrm_contact_employer_id'] = CRM_Contact_BAO_Contact::displayName($employerId); |
| 4685 | $rows[$rowNum]['civicrm_contact_employer_id_link'] = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $employerId, $this->_absoluteUrl); |
| 4686 | $rows[$rowNum]['civicrm_contact_employer_id_hover'] = ts('View Contact Summary for Employer.'); |
| 4687 | $entryFound = TRUE; |
| 4688 | } |
| 4689 | } |
| 4690 | |
| 4691 | return $entryFound; |
| 4692 | } |
| 4693 | |
| 4694 | /** |
| 4695 | * Adjusts dates passed in to YEAR() for fiscal year. |
| 4696 | * |
| 4697 | * @param string $fieldName |
| 4698 | * |
| 4699 | * @return string |
| 4700 | */ |
| 4701 | public function fiscalYearOffset($fieldName) { |
| 4702 | $config = CRM_Core_Config::singleton(); |
| 4703 | $fy = $config->fiscalYearStart; |
| 4704 | if (CRM_Utils_Array::value('yid_op', $this->_params) == 'calendar' || |
| 4705 | ($fy['d'] == 1 && $fy['M'] == 1) |
| 4706 | ) { |
| 4707 | return "YEAR( $fieldName )"; |
| 4708 | } |
| 4709 | return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . |
| 4710 | ($fy['d'] > 1 ? (" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )"; |
| 4711 | } |
| 4712 | |
| 4713 | /** |
| 4714 | * Add Address into From Table if required. |
| 4715 | * |
| 4716 | * Prefix will be added to both tables as |
| 4717 | * it is assumed you are using it to get address of a secondary contact. |
| 4718 | * |
| 4719 | * @param string $prefix |
| 4720 | * @param array $extra Additional options. |
| 4721 | * Not currently used in core but may be used in override extensions. |
| 4722 | */ |
| 4723 | protected function joinAddressFromContact($prefix = '', $extra = []) { |
| 4724 | $defaults = ['primary_only' => TRUE]; |
| 4725 | $params = array_merge($defaults, $extra); |
| 4726 | $addressTables = ['civicrm_address', 'civicrm_country', 'civicrm_worldregion', 'civicrm_state_province']; |
| 4727 | $isJoinRequired = $this->_addressField; |
| 4728 | foreach ($addressTables as $addressTable) { |
| 4729 | if ($this->isTableSelected($prefix . $addressTable)) { |
| 4730 | $isJoinRequired = TRUE; |
| 4731 | } |
| 4732 | } |
| 4733 | if ($isJoinRequired) { |
| 4734 | $fromJoin = " |
| 4735 | LEFT JOIN civicrm_address {$this->_aliases[$prefix . 'civicrm_address']} |
| 4736 | ON ({$this->_aliases[$prefix . 'civicrm_contact']}.id = |
| 4737 | {$this->_aliases[$prefix . 'civicrm_address']}.contact_id)"; |
| 4738 | if ($params['primary_only']) { |
| 4739 | $fromJoin .= " AND |
| 4740 | {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1\n"; |
| 4741 | } |
| 4742 | $this->_from .= $fromJoin; |
| 4743 | } |
| 4744 | } |
| 4745 | |
| 4746 | /** |
| 4747 | * Add Country into From Table if required. |
| 4748 | * |
| 4749 | * Prefix will be added to both tables as |
| 4750 | * it is assumed you are using it to get address of a secondary contact. |
| 4751 | * |
| 4752 | * @param string $prefix |
| 4753 | * @param array $extra Additional options. |
| 4754 | * Not currently used in core but may be used in override extensions. |
| 4755 | */ |
| 4756 | protected function joinCountryFromAddress($prefix = '', $extra = []) { |
| 4757 | $defaults = ['primary_only' => TRUE]; |
| 4758 | $params = array_merge($defaults, $extra); |
| 4759 | // include country field if country column is to be included |
| 4760 | if ($this->isTableSelected($prefix . 'civicrm_country') || $this->isTableSelected($prefix . 'civicrm_worldregion')) { |
| 4761 | if (empty($this->_aliases[$prefix . 'civicrm_country'])) { |
| 4762 | $this->_aliases[$prefix . 'civicrm_country'] = $prefix . '_report_country'; |
| 4763 | } |
| 4764 | $fromJoin = " |
| 4765 | LEFT JOIN civicrm_country {$this->_aliases[$prefix . 'civicrm_country']} |
| 4766 | ON {$this->_aliases[$prefix . 'civicrm_address']}.country_id = {$this->_aliases[$prefix . 'civicrm_country']}.id"; |
| 4767 | if ($params['primary_only']) { |
| 4768 | $fromJoin .= " AND |
| 4769 | {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1 "; |
| 4770 | } |
| 4771 | $this->_from .= $fromJoin; |
| 4772 | } |
| 4773 | } |
| 4774 | |
| 4775 | /** |
| 4776 | * Add Phone into From Table if required. |
| 4777 | * |
| 4778 | * Prefix will be added to both tables as |
| 4779 | * it is assumed you are using it to get address of a secondary contact. |
| 4780 | * |
| 4781 | * @param string $prefix |
| 4782 | * @param array $extra Additional options. |
| 4783 | * Not currently used in core but may be used in override extensions. |
| 4784 | */ |
| 4785 | protected function joinPhoneFromContact($prefix = '', $extra = []) { |
| 4786 | $defaults = ['primary_only' => TRUE]; |
| 4787 | $params = array_merge($defaults, $extra); |
| 4788 | // include phone field if phone column is to be included |
| 4789 | if ($this->isTableSelected($prefix . 'civicrm_phone')) { |
| 4790 | $fromJoin = " |
| 4791 | LEFT JOIN civicrm_phone {$this->_aliases[$prefix . 'civicrm_phone']} |
| 4792 | ON {$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_phone']}.contact_id"; |
| 4793 | if ($params['primary_only']) { |
| 4794 | $fromJoin .= " AND |
| 4795 | {$this->_aliases[$prefix . 'civicrm_phone']}.is_primary = 1\n"; |
| 4796 | } |
| 4797 | $this->_from .= $fromJoin; |
| 4798 | } |
| 4799 | } |
| 4800 | |
| 4801 | /** |
| 4802 | * Add Email into From Table if required. |
| 4803 | * |
| 4804 | * Prefix will be added to both tables as |
| 4805 | * it is assumed you are using it to get address of a secondary contact. |
| 4806 | * |
| 4807 | * @param string $prefix |
| 4808 | * @param array $extra Additional options. |
| 4809 | * Not currently used in core but may be used in override extensions. |
| 4810 | */ |
| 4811 | protected function joinEmailFromContact($prefix = '', $extra = []) { |
| 4812 | $defaults = ['primary_only' => TRUE]; |
| 4813 | $params = array_merge($defaults, $extra); |
| 4814 | // include email field if email column is to be included |
| 4815 | if ($this->isTableSelected($prefix . 'civicrm_email')) { |
| 4816 | $fromJoin = " |
| 4817 | LEFT JOIN civicrm_email {$this->_aliases[$prefix . 'civicrm_email']} |
| 4818 | ON {$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_email']}.contact_id"; |
| 4819 | if ($params['primary_only']) { |
| 4820 | $fromJoin .= " AND |
| 4821 | {$this->_aliases[$prefix . 'civicrm_email']}.is_primary = 1 "; |
| 4822 | } |
| 4823 | $this->_from .= $fromJoin; |
| 4824 | } |
| 4825 | } |
| 4826 | |
| 4827 | /** |
| 4828 | * Add Financial Transaction into From Table if required. |
| 4829 | */ |
| 4830 | public function addFinancialTrxnFromClause() { |
| 4831 | if ($this->isTableSelected('civicrm_financial_trxn')) { |
| 4832 | $this->_from .= " |
| 4833 | LEFT JOIN civicrm_entity_financial_trxn eftcc |
| 4834 | ON ({$this->_aliases['civicrm_contribution']}.id = eftcc.entity_id AND |
| 4835 | eftcc.entity_table = 'civicrm_contribution') |
| 4836 | LEFT JOIN civicrm_financial_trxn {$this->_aliases['civicrm_financial_trxn']} |
| 4837 | ON {$this->_aliases['civicrm_financial_trxn']}.id = eftcc.financial_trxn_id \n"; |
| 4838 | } |
| 4839 | } |
| 4840 | |
| 4841 | /** |
| 4842 | * Get phone columns to add to array. |
| 4843 | * |
| 4844 | * @param array $options |
| 4845 | * - prefix Prefix to add to table (in case of more than one instance of the table) |
| 4846 | * - prefix_label Label to give columns from this phone table instance |
| 4847 | * |
| 4848 | * @return array |
| 4849 | * phone columns definition |
| 4850 | */ |
| 4851 | public function getPhoneColumns($options = []) { |
| 4852 | $defaultOptions = [ |
| 4853 | 'prefix' => '', |
| 4854 | 'prefix_label' => '', |
| 4855 | ]; |
| 4856 | |
| 4857 | $options = array_merge($defaultOptions, $options); |
| 4858 | |
| 4859 | $fields = [ |
| 4860 | $options['prefix'] . 'civicrm_phone' => [ |
| 4861 | 'dao' => 'CRM_Core_DAO_Phone', |
| 4862 | 'fields' => [ |
| 4863 | $options['prefix'] . 'phone' => [ |
| 4864 | 'title' => $options['prefix_label'] . ts('Phone'), |
| 4865 | 'name' => 'phone', |
| 4866 | ], |
| 4867 | ], |
| 4868 | ], |
| 4869 | ]; |
| 4870 | return $fields; |
| 4871 | } |
| 4872 | |
| 4873 | /** |
| 4874 | * Get a standard set of contact fields. |
| 4875 | * @deprecated - use getColumns('Contact') instead |
| 4876 | * @return array |
| 4877 | */ |
| 4878 | public function getBasicContactFields() { |
| 4879 | return [ |
| 4880 | 'sort_name' => [ |
| 4881 | 'title' => ts('Contact Name'), |
| 4882 | 'required' => TRUE, |
| 4883 | 'default' => TRUE, |
| 4884 | ], |
| 4885 | 'id' => [ |
| 4886 | 'no_display' => TRUE, |
| 4887 | 'required' => TRUE, |
| 4888 | ], |
| 4889 | 'prefix_id' => [ |
| 4890 | 'title' => ts('Contact Prefix'), |
| 4891 | ], |
| 4892 | 'first_name' => [ |
| 4893 | 'title' => ts('First Name'), |
| 4894 | ], |
| 4895 | 'nick_name' => [ |
| 4896 | 'title' => ts('Nick Name'), |
| 4897 | ], |
| 4898 | 'middle_name' => [ |
| 4899 | 'title' => ts('Middle Name'), |
| 4900 | ], |
| 4901 | 'last_name' => [ |
| 4902 | 'title' => ts('Last Name'), |
| 4903 | ], |
| 4904 | 'suffix_id' => [ |
| 4905 | 'title' => ts('Contact Suffix'), |
| 4906 | ], |
| 4907 | 'source' => ['title' => ts('Contact Source')], |
| 4908 | 'postal_greeting_display' => ['title' => ts('Postal Greeting')], |
| 4909 | 'email_greeting_display' => ['title' => ts('Email Greeting')], |
| 4910 | 'addressee_display' => ['title' => ts('Addressee')], |
| 4911 | 'contact_type' => [ |
| 4912 | 'title' => ts('Contact Type'), |
| 4913 | ], |
| 4914 | 'contact_sub_type' => [ |
| 4915 | 'title' => ts('Contact Subtype'), |
| 4916 | ], |
| 4917 | 'gender_id' => [ |
| 4918 | 'title' => ts('Gender'), |
| 4919 | ], |
| 4920 | 'birth_date' => [ |
| 4921 | 'title' => ts('Birth Date'), |
| 4922 | ], |
| 4923 | 'age' => [ |
| 4924 | 'title' => ts('Age'), |
| 4925 | 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())', |
| 4926 | ], |
| 4927 | 'job_title' => [ |
| 4928 | 'title' => ts('Contact Job title'), |
| 4929 | ], |
| 4930 | 'organization_name' => [ |
| 4931 | 'title' => ts('Organization Name'), |
| 4932 | ], |
| 4933 | 'external_identifier' => [ |
| 4934 | 'title' => ts('Contact identifier from external system'), |
| 4935 | ], |
| 4936 | 'do_not_email' => [], |
| 4937 | 'do_not_phone' => [], |
| 4938 | 'do_not_mail' => [], |
| 4939 | 'do_not_sms' => [], |
| 4940 | 'do_not_trade' => [], |
| 4941 | 'is_opt_out' => [], |
| 4942 | 'is_deceased' => [], |
| 4943 | 'preferred_language' => [], |
| 4944 | 'employer_id' => [ |
| 4945 | 'title' => ts('Current Employer'), |
| 4946 | ], |
| 4947 | ]; |
| 4948 | } |
| 4949 | |
| 4950 | /** |
| 4951 | * Get a standard set of contact filters. |
| 4952 | * |
| 4953 | * @param array $defaults |
| 4954 | * |
| 4955 | * @return array |
| 4956 | */ |
| 4957 | public function getBasicContactFilters($defaults = []) { |
| 4958 | return [ |
| 4959 | 'sort_name' => [ |
| 4960 | 'title' => ts('Contact Name'), |
| 4961 | ], |
| 4962 | 'source' => [ |
| 4963 | 'title' => ts('Contact Source'), |
| 4964 | 'type' => CRM_Utils_Type::T_STRING, |
| 4965 | ], |
| 4966 | 'id' => [ |
| 4967 | 'title' => ts('Contact ID'), |
| 4968 | 'no_display' => TRUE, |
| 4969 | ], |
| 4970 | 'gender_id' => [ |
| 4971 | 'title' => ts('Gender'), |
| 4972 | 'operatorType' => CRM_Report_Form::OP_MULTISELECT, |
| 4973 | 'options' => CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'), |
| 4974 | ], |
| 4975 | 'birth_date' => [ |
| 4976 | 'title' => ts('Birth Date'), |
| 4977 | 'operatorType' => CRM_Report_Form::OP_DATE, |
| 4978 | ], |
| 4979 | 'contact_type' => [ |
| 4980 | 'title' => ts('Contact Type'), |
| 4981 | ], |
| 4982 | 'contact_sub_type' => [ |
| 4983 | 'title' => ts('Contact Subtype'), |
| 4984 | ], |
| 4985 | 'modified_date' => [ |
| 4986 | 'title' => ts('Contact Modified'), |
| 4987 | 'operatorType' => CRM_Report_Form::OP_DATE, |
| 4988 | 'type' => CRM_Utils_Type::T_DATE, |
| 4989 | ], |
| 4990 | 'is_deceased' => [ |
| 4991 | 'title' => ts('Deceased'), |
| 4992 | 'type' => CRM_Utils_Type::T_BOOLEAN, |
| 4993 | 'default' => CRM_Utils_Array::value('deceased', $defaults, 0), |
| 4994 | ], |
| 4995 | 'do_not_email' => [ |
| 4996 | 'title' => ts('Do not email'), |
| 4997 | 'type' => CRM_Utils_Type::T_BOOLEAN, |
| 4998 | ], |
| 4999 | 'do_not_phone' => [ |
| 5000 | 'title' => ts('Do not phone'), |
| 5001 | 'type' => CRM_Utils_Type::T_BOOLEAN, |
| 5002 | ], |
| 5003 | 'do_not_mail' => [ |
| 5004 | 'title' => ts('Do not mail'), |
| 5005 | 'type' => CRM_Utils_Type::T_BOOLEAN, |
| 5006 | ], |
| 5007 | 'do_not_sms' => [ |
| 5008 | 'title' => ts('Do not SMS'), |
| 5009 | 'type' => CRM_Utils_Type::T_BOOLEAN, |
| 5010 | ], |
| 5011 | 'do_not_trade' => [ |
| 5012 | 'title' => ts('Do not Trade'), |
| 5013 | 'type' => CRM_Utils_Type::T_BOOLEAN, |
| 5014 | ], |
| 5015 | 'is_opt_out' => [ |
| 5016 | 'title' => ts('Do not bulk email'), |
| 5017 | 'type' => CRM_Utils_Type::T_BOOLEAN, |
| 5018 | ], |
| 5019 | 'preferred_language' => [ |
| 5020 | 'title' => ts('Preferred Language'), |
| 5021 | ], |
| 5022 | 'is_deleted' => [ |
| 5023 | 'no_display' => TRUE, |
| 5024 | 'default' => 0, |
| 5025 | 'type' => CRM_Utils_Type::T_BOOLEAN, |
| 5026 | ], |
| 5027 | ]; |
| 5028 | } |
| 5029 | |
| 5030 | /** |
| 5031 | * Add contact to group. |
| 5032 | * |
| 5033 | * @param int $groupID |
| 5034 | */ |
| 5035 | public function add2group($groupID) { |
| 5036 | if (is_numeric($groupID) && isset($this->_aliases['civicrm_contact'])) { |
| 5037 | $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, "; |
| 5038 | $select = preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', $select, $this->_select); |
| 5039 | $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}"; |
| 5040 | $sql = str_replace('WITH ROLLUP', '', $sql); |
| 5041 | if (!$this->optimisedForOnlyFullGroupBy) { |
| 5042 | CRM_Core_DAO::disableFullGroupByMode(); |
| 5043 | } |
| 5044 | $dao = CRM_Core_DAO::executeQuery($sql); |
| 5045 | CRM_Core_DAO::reenableFullGroupByMode(); |
| 5046 | |
| 5047 | $contact_ids = []; |
| 5048 | // Add resulting contacts to group |
| 5049 | while ($dao->fetch()) { |
| 5050 | if ($dao->addtogroup_contact_id) { |
| 5051 | $contact_ids[$dao->addtogroup_contact_id] = $dao->addtogroup_contact_id; |
| 5052 | } |
| 5053 | } |
| 5054 | |
| 5055 | if (!empty($contact_ids)) { |
| 5056 | CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $groupID); |
| 5057 | CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success'); |
| 5058 | } |
| 5059 | else { |
| 5060 | CRM_Core_Session::setStatus(ts("The listed records(s) cannot be added to the group.")); |
| 5061 | } |
| 5062 | } |
| 5063 | } |
| 5064 | |
| 5065 | /** |
| 5066 | * Apply common settings to entityRef fields. |
| 5067 | * |
| 5068 | * @param array $field |
| 5069 | * @param string $table |
| 5070 | */ |
| 5071 | public function setEntityRefDefaults(&$field, $table) { |
| 5072 | $field['attributes'] = $field['attributes'] ? $field['attributes'] : []; |
| 5073 | $field['attributes'] += [ |
| 5074 | 'entity' => CRM_Core_DAO_AllCoreTables::getEntityNameForTable($table), |
| 5075 | 'multiple' => TRUE, |
| 5076 | 'placeholder' => ts('- select -'), |
| 5077 | ]; |
| 5078 | } |
| 5079 | |
| 5080 | /** |
| 5081 | * Add link fields to the row. |
| 5082 | * |
| 5083 | * Function adds the _link & _hover fields to the row. |
| 5084 | * |
| 5085 | * @param array $row |
| 5086 | * @param string $baseUrl |
| 5087 | * @param string $linkText |
| 5088 | * @param string $value |
| 5089 | * @param string $fieldName |
| 5090 | * @param string $tablePrefix |
| 5091 | * @param string $fieldLabel |
| 5092 | * |
| 5093 | * @return mixed |
| 5094 | */ |
| 5095 | protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) { |
| 5096 | $criteriaQueryParams = CRM_Report_Utils_Report::getPreviewCriteriaQueryParams($this->_defaults, $this->_params); |
| 5097 | $url = CRM_Report_Utils_Report::getNextUrl($baseUrl, |
| 5098 | "reset=1&force=1&{$criteriaQueryParams}&" . |
| 5099 | $fieldName . "_op=in&{$fieldName}_value={$value}", |
| 5100 | $this->_absoluteUrl, $this->_id |
| 5101 | ); |
| 5102 | $row["{$tablePrefix}_{$fieldName}_link"] = $url; |
| 5103 | $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.", |
| 5104 | [1 => $linkText, 2 => $fieldLabel] |
| 5105 | ); |
| 5106 | } |
| 5107 | |
| 5108 | /** |
| 5109 | * Get label for show results buttons. |
| 5110 | * |
| 5111 | * @return string |
| 5112 | */ |
| 5113 | public function getResultsLabel() { |
| 5114 | $showResultsLabel = $this->resultsDisplayed() ? ts('Refresh results') : ts('View results'); |
| 5115 | return $showResultsLabel; |
| 5116 | } |
| 5117 | |
| 5118 | /** |
| 5119 | * Determine the output mode from the url or input. |
| 5120 | * |
| 5121 | * Output could be |
| 5122 | * - pdf : Render as pdf |
| 5123 | * - csv : Render as csv |
| 5124 | * - print : Render in print format |
| 5125 | * - save : save the report and display the new report |
| 5126 | * - copy : save the report as a new instance and display that. |
| 5127 | * - group : go to the add to group screen. |
| 5128 | * |
| 5129 | * Potentially chart variations could also be included but the complexity |
| 5130 | * is that we might print a bar chart as a pdf. |
| 5131 | */ |
| 5132 | protected function setOutputMode() { |
| 5133 | $this->_outputMode = str_replace('report_instance.', '', CRM_Utils_Request::retrieve( |
| 5134 | 'output', |
| 5135 | 'String', |
| 5136 | CRM_Core_DAO::$_nullObject, |
| 5137 | FALSE, |
| 5138 | CRM_Utils_Array::value('task', $this->_params) |
| 5139 | )); |
| 5140 | // if contacts are added to group |
| 5141 | if (!empty($this->_params['groups']) && empty($this->_outputMode)) { |
| 5142 | $this->_outputMode = 'group'; |
| 5143 | } |
| 5144 | if (isset($this->_params['task'])) { |
| 5145 | unset($this->_params['task']); |
| 5146 | } |
| 5147 | } |
| 5148 | |
| 5149 | /** |
| 5150 | * CRM-17793 - Alter DateTime section header to group by date from the datetime field. |
| 5151 | * |
| 5152 | * @param $tempTable |
| 5153 | * @param $columnName |
| 5154 | */ |
| 5155 | public function alterSectionHeaderForDateTime($tempTable, $columnName) { |
| 5156 | // add new column with date value for the datetime field |
| 5157 | $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)"; |
| 5158 | CRM_Core_DAO::executeQuery($tempQuery); |
| 5159 | $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})"; |
| 5160 | CRM_Core_DAO::executeQuery($updateQuery); |
| 5161 | $this->_selectClauses[] = "{$columnName}_date"; |
| 5162 | $this->_select .= ", {$columnName}_date"; |
| 5163 | $this->_sections["{$columnName}_date"] = $this->_sections["{$columnName}"]; |
| 5164 | unset($this->_sections["{$columnName}"]); |
| 5165 | $this->assign('sections', $this->_sections); |
| 5166 | } |
| 5167 | |
| 5168 | /** |
| 5169 | * Get an array of the columns that have been selected for display. |
| 5170 | * |
| 5171 | * @return array |
| 5172 | */ |
| 5173 | public function getSelectColumns() { |
| 5174 | $selectColumns = []; |
| 5175 | foreach ($this->_columns as $tableName => $table) { |
| 5176 | if (array_key_exists('fields', $table)) { |
| 5177 | foreach ($table['fields'] as $fieldName => $field) { |
| 5178 | if (!empty($field['required']) || |
| 5179 | !empty($this->_params['fields'][$fieldName]) |
| 5180 | ) { |
| 5181 | |
| 5182 | $selectColumns["{$tableName}_{$fieldName}"] = 1; |
| 5183 | } |
| 5184 | } |
| 5185 | } |
| 5186 | } |
| 5187 | return $selectColumns; |
| 5188 | } |
| 5189 | |
| 5190 | /** |
| 5191 | * Add location tables to the query if they are used for filtering. |
| 5192 | * |
| 5193 | * This is for when we are running the query separately for filtering and retrieving display fields. |
| 5194 | */ |
| 5195 | public function selectivelyAddLocationTablesJoinsToFilterQuery() { |
| 5196 | if ($this->isTableFiltered('civicrm_email')) { |
| 5197 | $this->_from .= " |
| 5198 | LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']} |
| 5199 | ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id |
| 5200 | AND {$this->_aliases['civicrm_email']}.is_primary = 1"; |
| 5201 | } |
| 5202 | if ($this->isTableFiltered('civicrm_phone')) { |
| 5203 | $this->_from .= " |
| 5204 | LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']} |
| 5205 | ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id |
| 5206 | AND {$this->_aliases['civicrm_phone']}.is_primary = 1"; |
| 5207 | } |
| 5208 | if ($this->isTableFiltered('civicrm_address')) { |
| 5209 | $this->_from .= " |
| 5210 | LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']} |
| 5211 | ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id) |
| 5212 | AND {$this->_aliases['civicrm_address']}.is_primary = 1\n"; |
| 5213 | } |
| 5214 | } |
| 5215 | |
| 5216 | /** |
| 5217 | * Set the base table for the FROM clause. |
| 5218 | * |
| 5219 | * Sets up the from clause, allowing for the possibility it might be a |
| 5220 | * temp table pre-filtered by groups if a group filter is in use. |
| 5221 | * |
| 5222 | * @param string $baseTable |
| 5223 | * @param string $field |
| 5224 | * @param string|null $tableAlias |
| 5225 | */ |
| 5226 | public function setFromBase($baseTable, $field = 'id', $tableAlias = NULL) { |
| 5227 | if (!$tableAlias) { |
| 5228 | $tableAlias = $this->_aliases[$baseTable]; |
| 5229 | } |
| 5230 | $this->_from = $this->_from = " FROM $baseTable $tableAlias "; |
| 5231 | $this->joinGroupTempTable($baseTable, $field, $tableAlias); |
| 5232 | $this->_from .= " {$this->_aclFrom} "; |
| 5233 | } |
| 5234 | |
| 5235 | /** |
| 5236 | * Join the temp table contacting contacts who are members of the filtered groups. |
| 5237 | * |
| 5238 | * If we are using an IN filter we use an inner join, otherwise a left join. |
| 5239 | * |
| 5240 | * @param string $baseTable |
| 5241 | * @param string $field |
| 5242 | * @param string $tableAlias |
| 5243 | */ |
| 5244 | public function joinGroupTempTable($baseTable, $field, $tableAlias) { |
| 5245 | if ($this->groupTempTable) { |
| 5246 | if ($this->_params['gid_op'] == 'in') { |
| 5247 | $this->_from = " FROM $this->groupTempTable group_temp_table INNER JOIN $baseTable $tableAlias |
| 5248 | ON group_temp_table.contact_id = $tableAlias.{$field} "; |
| 5249 | } |
| 5250 | else { |
| 5251 | $this->_from .= " |
| 5252 | LEFT JOIN $this->groupTempTable group_temp_table |
| 5253 | ON $tableAlias.{$field} = group_temp_table.contact_id "; |
| 5254 | } |
| 5255 | } |
| 5256 | } |
| 5257 | |
| 5258 | /** |
| 5259 | * Get all labels for fields that are used in a group concat. |
| 5260 | * |
| 5261 | * @param string $options |
| 5262 | * comma separated option values. |
| 5263 | * @param string $baoName |
| 5264 | * The BAO name for the field. |
| 5265 | * @param string $fieldName |
| 5266 | * The name of the field for which labels should be retrieved. |
| 5267 | * |
| 5268 | * return string |
| 5269 | */ |
| 5270 | public function getLabels($options, $baoName, $fieldName) { |
| 5271 | $types = explode(',', $options); |
| 5272 | $labels = []; |
| 5273 | foreach ($types as $value) { |
| 5274 | $labels[$value] = CRM_Core_PseudoConstant::getLabel($baoName, $fieldName, $value); |
| 5275 | } |
| 5276 | return implode(', ', array_filter($labels)); |
| 5277 | } |
| 5278 | |
| 5279 | /** |
| 5280 | * Add statistics columns. |
| 5281 | * |
| 5282 | * If a group by is in play then add columns for the statistics fields. |
| 5283 | * |
| 5284 | * This would lead to a new field in the $row such as $fieldName_sum and a new, matching |
| 5285 | * column header field. |
| 5286 | * |
| 5287 | * @param array $field |
| 5288 | * @param string $tableName |
| 5289 | * @param string $fieldName |
| 5290 | * @param array $select |
| 5291 | * |
| 5292 | * @return array |
| 5293 | */ |
| 5294 | protected function addStatisticsToSelect($field, $tableName, $fieldName, $select) { |
| 5295 | foreach ($field['statistics'] as $stat => $label) { |
| 5296 | $alias = "{$tableName}_{$fieldName}_{$stat}"; |
| 5297 | switch (strtolower($stat)) { |
| 5298 | case 'max': |
| 5299 | case 'sum': |
| 5300 | $select[] = "$stat({$field['dbAlias']}) as $alias"; |
| 5301 | $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label; |
| 5302 | $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type']; |
| 5303 | $this->_statFields[$label] = $alias; |
| 5304 | $this->_selectAliases[] = $alias; |
| 5305 | break; |
| 5306 | |
| 5307 | case 'count': |
| 5308 | $select[] = "COUNT({$field['dbAlias']}) as $alias"; |
| 5309 | $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label; |
| 5310 | $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT; |
| 5311 | $this->_statFields[$label] = $alias; |
| 5312 | $this->_selectAliases[] = $alias; |
| 5313 | break; |
| 5314 | |
| 5315 | case 'count_distinct': |
| 5316 | $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias"; |
| 5317 | $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label; |
| 5318 | $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT; |
| 5319 | $this->_statFields[$label] = $alias; |
| 5320 | $this->_selectAliases[] = $alias; |
| 5321 | break; |
| 5322 | |
| 5323 | case 'avg': |
| 5324 | $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias"; |
| 5325 | $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label; |
| 5326 | $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type']; |
| 5327 | $this->_statFields[$label] = $alias; |
| 5328 | $this->_selectAliases[] = $alias; |
| 5329 | break; |
| 5330 | } |
| 5331 | } |
| 5332 | return $select; |
| 5333 | } |
| 5334 | |
| 5335 | /** |
| 5336 | * Add a basic field to the select clause. |
| 5337 | * |
| 5338 | * @param string $tableName |
| 5339 | * @param string $fieldName |
| 5340 | * @param array $field |
| 5341 | * @param string $select |
| 5342 | * @return array |
| 5343 | */ |
| 5344 | protected function addBasicFieldToSelect($tableName, $fieldName, $field, $select) { |
| 5345 | $alias = "{$tableName}_{$fieldName}"; |
| 5346 | $select[] = "{$field['dbAlias']} as $alias"; |
| 5347 | $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'] ?? NULL; |
| 5348 | $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = $field['type'] ?? NULL; |
| 5349 | $this->_selectAliases[] = $alias; |
| 5350 | return $select; |
| 5351 | } |
| 5352 | |
| 5353 | /** |
| 5354 | * Set table alias. |
| 5355 | * |
| 5356 | * @param array $table |
| 5357 | * @param string $tableName |
| 5358 | * |
| 5359 | * @return string |
| 5360 | * Alias for table. |
| 5361 | */ |
| 5362 | protected function setTableAlias($table, $tableName) { |
| 5363 | if (!isset($table['alias'])) { |
| 5364 | $this->_columns[$tableName]['alias'] = substr($tableName, 8) . |
| 5365 | '_civireport'; |
| 5366 | } |
| 5367 | else { |
| 5368 | $this->_columns[$tableName]['alias'] = $table['alias'] . '_civireport'; |
| 5369 | } |
| 5370 | |
| 5371 | $this->_aliases[$tableName] = $this->_columns[$tableName]['alias']; |
| 5372 | return $this->_aliases[$tableName]; |
| 5373 | } |
| 5374 | |
| 5375 | /** |
| 5376 | * Function to add columns to reports. |
| 5377 | * |
| 5378 | * This is ported from extended reports, which also adds join filters to the options. |
| 5379 | * |
| 5380 | * @param string $type |
| 5381 | * @param array $options |
| 5382 | * - prefix - A string to prepend to the table name |
| 5383 | * - prefix_label A string to prepend to the fields |
| 5384 | * - fields (bool) - should the fields for this table be made available |
| 5385 | * - group_by (bool) - should the group bys for this table be made available. |
| 5386 | * - order_by (bool) - should the group bys for this table be made available. |
| 5387 | * - filters (bool) - should the filters for this table by made available. |
| 5388 | * - fields_defaults (array) array of fields that should be displayed by default. |
| 5389 | * - filters_defaults (array) array of fields that should be filtered by default. |
| 5390 | * - join_filters (array) fields available for filtering joins (requires additional custom code). |
| 5391 | * - join_fields (array) fields available from join (requires additional custom code). |
| 5392 | * - group_by_defaults (array) array of group bys that should be applied by default. |
| 5393 | * - order_by_defaults (array) array of order bys that should be applied by default. |
| 5394 | * - custom_fields (array) array of entity types for custom fields (not usually required). |
| 5395 | * - contact_type (string) optional restriction on contact type for some tables. |
| 5396 | * - fields_excluded (array) fields that are in the generic set for the table but not in the report. |
| 5397 | * |
| 5398 | * @return array |
| 5399 | */ |
| 5400 | protected function getColumns($type, $options = []) { |
| 5401 | $defaultOptions = [ |
| 5402 | 'prefix' => '', |
| 5403 | 'prefix_label' => '', |
| 5404 | 'fields' => TRUE, |
| 5405 | 'group_bys' => FALSE, |
| 5406 | 'order_bys' => TRUE, |
| 5407 | 'filters' => TRUE, |
| 5408 | 'join_filters' => FALSE, |
| 5409 | 'fields_defaults' => [], |
| 5410 | 'filters_defaults' => [], |
| 5411 | 'group_bys_defaults' => [], |
| 5412 | 'order_bys_defaults' => [], |
| 5413 | ]; |
| 5414 | $options = array_merge($defaultOptions, $options); |
| 5415 | |
| 5416 | $fn = 'get' . $type . 'Columns'; |
| 5417 | return $this->$fn($options); |
| 5418 | } |
| 5419 | |
| 5420 | /** |
| 5421 | * Get columns for contact table. |
| 5422 | * |
| 5423 | * @param array $options |
| 5424 | * |
| 5425 | * @return array |
| 5426 | */ |
| 5427 | protected function getContactColumns($options = []) { |
| 5428 | $defaultOptions = [ |
| 5429 | 'custom_fields' => CRM_Contact_BAO_ContactType::basicTypes(), |
| 5430 | 'fields_defaults' => ['display_name', 'id'], |
| 5431 | 'order_bys_defaults' => ['sort_name ASC'], |
| 5432 | 'contact_type' => NULL, |
| 5433 | ]; |
| 5434 | |
| 5435 | $options = array_merge($defaultOptions, $options); |
| 5436 | |
| 5437 | $tableAlias = $options['prefix'] . 'contact'; |
| 5438 | |
| 5439 | $spec = [ |
| 5440 | $options['prefix'] . 'display_name' => [ |
| 5441 | 'name' => 'display_name', |
| 5442 | 'title' => $options['prefix_label'] . ts('Contact Name'), |
| 5443 | 'is_fields' => TRUE, |
| 5444 | ], |
| 5445 | $options['prefix'] . 'sort_name' => [ |
| 5446 | 'name' => 'sort_name', |
| 5447 | 'title' => $options['prefix_label'] . ts('Contact Name (in sort format)'), |
| 5448 | 'is_fields' => TRUE, |
| 5449 | 'is_filters' => TRUE, |
| 5450 | 'is_order_bys' => TRUE, |
| 5451 | ], |
| 5452 | $options['prefix'] . 'id' => [ |
| 5453 | 'name' => 'id', |
| 5454 | 'title' => $options['prefix_label'] . ts('Contact ID'), |
| 5455 | 'alter_display' => 'alterContactID', |
| 5456 | 'type' => CRM_Utils_Type::T_INT, |
| 5457 | 'is_order_bys' => TRUE, |
| 5458 | 'is_group_bys' => TRUE, |
| 5459 | 'is_fields' => TRUE, |
| 5460 | 'is_filters' => TRUE, |
| 5461 | ], |
| 5462 | $options['prefix'] . 'external_identifier' => [ |
| 5463 | 'name' => 'external_identifier', |
| 5464 | 'title' => $options['prefix_label'] . ts('External ID'), |
| 5465 | 'type' => CRM_Utils_Type::T_INT, |
| 5466 | 'is_fields' => TRUE, |
| 5467 | ], |
| 5468 | $options['prefix'] . 'contact_type' => [ |
| 5469 | 'title' => $options['prefix_label'] . ts('Contact Type'), |
| 5470 | 'name' => 'contact_type', |
| 5471 | 'operatorType' => CRM_Report_Form::OP_MULTISELECT, |
| 5472 | 'options' => CRM_Contact_BAO_Contact::buildOptions('contact_type'), |
| 5473 | 'is_fields' => TRUE, |
| 5474 | 'is_filters' => TRUE, |
| 5475 | 'is_group_bys' => TRUE, |
| 5476 | ], |
| 5477 | $options['prefix'] . 'contact_sub_type' => [ |
| 5478 | 'title' => $options['prefix_label'] . ts('Contact Sub Type'), |
| 5479 | 'name' => 'contact_sub_type', |
| 5480 | 'operatorType' => CRM_Report_Form::OP_MULTISELECT, |
| 5481 | 'options' => CRM_Contact_BAO_Contact::buildOptions('contact_sub_type'), |
| 5482 | 'is_fields' => TRUE, |
| 5483 | 'is_filters' => TRUE, |
| 5484 | 'is_group_bys' => TRUE, |
| 5485 | ], |
| 5486 | $options['prefix'] . 'is_deleted' => [ |
| 5487 | 'title' => $options['prefix_label'] . ts('Is deleted'), |
| 5488 | 'name' => 'is_deleted', |
| 5489 | 'type' => CRM_Utils_Type::T_BOOLEAN, |
| 5490 | 'is_fields' => FALSE, |
| 5491 | 'is_filters' => TRUE, |
| 5492 | 'is_group_bys' => FALSE, |
| 5493 | ], |
| 5494 | $options['prefix'] . 'external_identifier' => [ |
| 5495 | 'title' => $options['prefix_label'] . ts('Contact identifier from external system'), |
| 5496 | 'name' => 'external_identifier', |
| 5497 | 'is_fields' => TRUE, |
| 5498 | 'is_filters' => FALSE, |
| 5499 | 'is_group_bys' => FALSE, |
| 5500 | 'is_order_bys' => TRUE, |
| 5501 | ], |
| 5502 | $options['prefix'] . 'preferred_language' => [ |
| 5503 | 'title' => $options['prefix_label'] . ts('Preferred Language'), |
| 5504 | 'name' => 'preferred_language', |
| 5505 | 'is_fields' => TRUE, |
| 5506 | 'is_filters' => TRUE, |
| 5507 | 'is_group_bys' => TRUE, |
| 5508 | 'is_order_bys' => TRUE, |
| 5509 | ], |
| 5510 | $options['prefix'] . 'preferred_communication_method' => [ |
| 5511 | 'title' => $options['prefix_label'] . ts('Preferred Communication Method'), |
| 5512 | 'alter_display' => 'alterCommunicationtMethod', |
| 5513 | 'name' => 'preferred_communication_method', |
| 5514 | 'is_fields' => TRUE, |
| 5515 | 'is_filters' => FALSE, |
| 5516 | 'is_group_bys' => FALSE, |
| 5517 | 'is_order_bys' => FALSE, |
| 5518 | ], |
| 5519 | ]; |
| 5520 | foreach ([ |
| 5521 | 'postal_greeting_display' => 'Postal Greeting', |
| 5522 | 'email_greeting_display' => 'Email Greeting', |
| 5523 | 'addressee_display' => 'Addressee', |
| 5524 | ] as $field => $title) { |
| 5525 | $spec[$options['prefix'] . $field] = [ |
| 5526 | 'title' => $options['prefix_label'] . ts($title), |
| 5527 | 'name' => $field, |
| 5528 | 'is_fields' => TRUE, |
| 5529 | 'is_filters' => FALSE, |
| 5530 | 'is_group_bys' => FALSE, |
| 5531 | ]; |
| 5532 | } |
| 5533 | foreach (['do_not_email', 'do_not_phone', 'do_not_mail', 'do_not_sms', 'do_not_trade', 'is_opt_out'] as $field) { |
| 5534 | $spec[$options['prefix'] . $field] = [ |
| 5535 | 'name' => $field, |
| 5536 | 'type' => CRM_Utils_Type::T_BOOLEAN, |
| 5537 | 'is_fields' => TRUE, |
| 5538 | 'is_filters' => TRUE, |
| 5539 | 'is_group_bys' => FALSE, |
| 5540 | ]; |
| 5541 | } |
| 5542 | $individualFields = [ |
| 5543 | $options['prefix'] . 'first_name' => [ |
| 5544 | 'name' => 'first_name', |
| 5545 | 'title' => $options['prefix_label'] . ts('First Name'), |
| 5546 | 'is_fields' => TRUE, |
| 5547 | 'is_filters' => TRUE, |
| 5548 | 'is_order_bys' => TRUE, |
| 5549 | ], |
| 5550 | $options['prefix'] . 'middle_name' => [ |
| 5551 | 'name' => 'middle_name', |
| 5552 | 'title' => $options['prefix_label'] . ts('Middle Name'), |
| 5553 | 'is_fields' => TRUE, |
| 5554 | ], |
| 5555 | $options['prefix'] . 'last_name' => [ |
| 5556 | 'name' => 'last_name', |
| 5557 | 'title' => $options['prefix_label'] . ts('Last Name'), |
| 5558 | 'default_order' => 'ASC', |
| 5559 | 'is_fields' => TRUE, |
| 5560 | ], |
| 5561 | $options['prefix'] . 'nick_name' => [ |
| 5562 | 'name' => 'nick_name', |
| 5563 | 'title' => $options['prefix_label'] . ts('Nick Name'), |
| 5564 | 'is_fields' => TRUE, |
| 5565 | ], |
| 5566 | $options['prefix'] . 'prefix_id' => [ |
| 5567 | 'name' => 'prefix_id', |
| 5568 | 'title' => $options['prefix_label'] . ts('Prefix'), |
| 5569 | 'options' => CRM_Contact_BAO_Contact::buildOptions('prefix_id'), |
| 5570 | 'operatorType' => CRM_Report_Form::OP_MULTISELECT, |
| 5571 | 'is_fields' => TRUE, |
| 5572 | 'is_filters' => TRUE, |
| 5573 | ], |
| 5574 | $options['prefix'] . 'suffix_id' => [ |
| 5575 | 'name' => 'suffix_id', |
| 5576 | 'title' => $options['prefix_label'] . ts('Suffix'), |
| 5577 | 'options' => CRM_Contact_BAO_Contact::buildOptions('suffix_id'), |
| 5578 | 'operatorType' => CRM_Report_Form::OP_MULTISELECT, |
| 5579 | 'is_fields' => TRUE, |
| 5580 | 'is_filters' => TRUE, |
| 5581 | ], |
| 5582 | $options['prefix'] . 'gender_id' => [ |
| 5583 | 'name' => 'gender_id', |
| 5584 | 'title' => $options['prefix_label'] . ts('Gender'), |
| 5585 | 'options' => CRM_Contact_BAO_Contact::buildOptions('gender_id'), |
| 5586 | 'operatorType' => CRM_Report_Form::OP_MULTISELECT, |
| 5587 | 'is_fields' => TRUE, |
| 5588 | 'is_filters' => TRUE, |
| 5589 | ], |
| 5590 | 'birth_date' => [ |
| 5591 | 'title' => $options['prefix_label'] . ts('Birth Date'), |
| 5592 | 'operatorType' => CRM_Report_Form::OP_DATE, |
| 5593 | 'type' => CRM_Utils_Type::T_DATE, |
| 5594 | 'is_fields' => TRUE, |
| 5595 | 'is_filters' => TRUE, |
| 5596 | ], |
| 5597 | 'age' => [ |
| 5598 | 'title' => $options['prefix_label'] . ts('Age'), |
| 5599 | 'dbAlias' => 'TIMESTAMPDIFF(YEAR, ' . $tableAlias . '_civireport.birth_date, CURDATE())', |
| 5600 | 'type' => CRM_Utils_Type::T_INT, |
| 5601 | 'is_fields' => TRUE, |
| 5602 | ], |
| 5603 | $options['prefix'] . 'is_deceased' => [ |
| 5604 | 'title' => $options['prefix_label'] . ts('Is deceased'), |
| 5605 | 'name' => 'is_deceased', |
| 5606 | 'type' => CRM_Utils_Type::T_BOOLEAN, |
| 5607 | 'is_fields' => FALSE, |
| 5608 | 'is_filters' => TRUE, |
| 5609 | 'is_group_bys' => FALSE, |
| 5610 | ], |
| 5611 | $options['prefix'] . 'job_title' => [ |
| 5612 | 'name' => 'job_title', |
| 5613 | 'is_fields' => TRUE, |
| 5614 | 'is_filters' => FALSE, |
| 5615 | 'is_group_bys' => FALSE, |
| 5616 | ], |
| 5617 | $options['prefix'] . 'employer_id' => [ |
| 5618 | 'title' => $options['prefix_label'] . ts('Current Employer'), |
| 5619 | 'type' => CRM_Utils_Type::T_INT, |
| 5620 | 'name' => 'employer_id', |
| 5621 | 'is_fields' => TRUE, |
| 5622 | 'is_filters' => FALSE, |
| 5623 | 'is_group_bys' => TRUE, |
| 5624 | ], |
| 5625 | ]; |
| 5626 | if (!$options['contact_type'] || $options['contact_type'] === 'Individual') { |
| 5627 | $spec = array_merge($spec, $individualFields); |
| 5628 | } |
| 5629 | |
| 5630 | if (!empty($options['custom_fields'])) { |
| 5631 | $this->_customGroupExtended[$options['prefix'] . 'civicrm_contact'] = [ |
| 5632 | 'extends' => $options['custom_fields'], |
| 5633 | 'title' => $options['prefix_label'], |
| 5634 | 'filters' => $options['filters'], |
| 5635 | 'prefix' => $options['prefix'], |
| 5636 | 'prefix_label' => $options['prefix_label'], |
| 5637 | ]; |
| 5638 | } |
| 5639 | |
| 5640 | return $this->buildColumns($spec, $options['prefix'] . 'civicrm_contact', 'CRM_Contact_DAO_Contact', $tableAlias, $this->getDefaultsFromOptions($options), $options); |
| 5641 | } |
| 5642 | |
| 5643 | /** |
| 5644 | * Get address columns to add to array. |
| 5645 | * |
| 5646 | * @param array $options |
| 5647 | * - prefix Prefix to add to table (in case of more than one instance of the table) |
| 5648 | * - prefix_label Label to give columns from this address table instance |
| 5649 | * - group_bys enable these fields for group by - default false |
| 5650 | * - order_bys enable these fields for order by |
| 5651 | * - filters enable these fields for filtering |
| 5652 | * |
| 5653 | * @return array address columns definition |
| 5654 | */ |
| 5655 | protected function getAddressColumns($options = []) { |
| 5656 | $defaultOptions = [ |
| 5657 | 'prefix' => '', |
| 5658 | 'prefix_label' => '', |
| 5659 | 'fields' => TRUE, |
| 5660 | 'group_bys' => FALSE, |
| 5661 | 'order_bys' => TRUE, |
| 5662 | 'filters' => TRUE, |
| 5663 | 'join_filters' => FALSE, |
| 5664 | 'fields_defaults' => [], |
| 5665 | 'filters_defaults' => [], |
| 5666 | 'group_bys_defaults' => [], |
| 5667 | 'order_bys_defaults' => [], |
| 5668 | ]; |
| 5669 | |
| 5670 | $options = array_merge($defaultOptions, $options); |
| 5671 | $defaults = $this->getDefaultsFromOptions($options); |
| 5672 | $tableAlias = $options['prefix'] . 'address'; |
| 5673 | |
| 5674 | $spec = [ |
| 5675 | $options['prefix'] . 'name' => [ |
| 5676 | 'title' => $options['prefix_label'] . ts('Address Name'), |
| 5677 | 'name' => 'name', |
| 5678 | 'is_fields' => TRUE, |
| 5679 | ], |
| 5680 | $options['prefix'] . 'street_number' => [ |
| 5681 | 'name' => 'street_number', |
| 5682 | 'title' => $options['prefix_label'] . ts('Street Number'), |
| 5683 | 'type' => 1, |
| 5684 | 'is_fields' => TRUE, |
| 5685 | ], |
| 5686 | $options['prefix'] . 'odd_street_number' => [ |
| 5687 | 'title' => ts('Odd / Even Street Number'), |
| 5688 | 'name' => 'odd_street_number', |
| 5689 | 'type' => CRM_Utils_Type::T_INT, |
| 5690 | 'no_display' => TRUE, |
| 5691 | 'required' => TRUE, |
| 5692 | 'dbAlias' => "({$tableAlias}_civireport.street_number % 2)", |
| 5693 | 'is_fields' => TRUE, |
| 5694 | 'is_order_bys' => TRUE, |
| 5695 | ], |
| 5696 | $options['prefix'] . 'street_name' => [ |
| 5697 | 'name' => 'street_name', |
| 5698 | 'title' => $options['prefix_label'] . ts('Street Name'), |
| 5699 | 'type' => 1, |
| 5700 | 'is_fields' => TRUE, |
| 5701 | 'is_filters' => TRUE, |
| 5702 | 'operator' => 'like', |
| 5703 | 'is_order_bys' => TRUE, |
| 5704 | ], |
| 5705 | $options['prefix'] . 'street_address' => [ |
| 5706 | 'title' => $options['prefix_label'] . ts('Street Address'), |
| 5707 | 'name' => 'street_address', |
| 5708 | 'is_fields' => TRUE, |
| 5709 | 'is_filters' => TRUE, |
| 5710 | 'is_group_bys' => TRUE, |
| 5711 | ], |
| 5712 | $options['prefix'] . 'supplemental_address_1' => [ |
| 5713 | 'title' => $options['prefix_label'] . ts('Supplementary Address Field 1'), |
| 5714 | 'name' => 'supplemental_address_1', |
| 5715 | 'is_fields' => TRUE, |
| 5716 | ], |
| 5717 | $options['prefix'] . 'supplemental_address_2' => [ |
| 5718 | 'title' => $options['prefix_label'] . ts('Supplementary Address Field 2'), |
| 5719 | 'name' => 'supplemental_address_2', |
| 5720 | 'is_fields' => TRUE, |
| 5721 | ], |
| 5722 | $options['prefix'] . 'supplemental_address_3' => [ |
| 5723 | 'title' => $options['prefix_label'] . ts('Supplementary Address Field 3'), |
| 5724 | 'name' => 'supplemental_address_3', |
| 5725 | 'is_fields' => TRUE, |
| 5726 | ], |
| 5727 | $options['prefix'] . 'street_number' => [ |
| 5728 | 'name' => 'street_number', |
| 5729 | 'title' => $options['prefix_label'] . ts('Street Number'), |
| 5730 | 'type' => 1, |
| 5731 | 'is_order_bys' => TRUE, |
| 5732 | 'is_filters' => TRUE, |
| 5733 | 'is_fields' => TRUE, |
| 5734 | ], |
| 5735 | $options['prefix'] . 'street_unit' => [ |
| 5736 | 'name' => 'street_unit', |
| 5737 | 'title' => $options['prefix_label'] . ts('Street Unit'), |
| 5738 | 'type' => 1, |
| 5739 | 'is_fields' => TRUE, |
| 5740 | ], |
| 5741 | $options['prefix'] . 'city' => [ |
| 5742 | 'title' => $options['prefix_label'] . ts('City'), |
| 5743 | 'name' => 'city', |
| 5744 | 'operator' => 'like', |
| 5745 | 'is_fields' => TRUE, |
| 5746 | 'is_filters' => TRUE, |
| 5747 | 'is_group_bys' => TRUE, |
| 5748 | 'is_order_bys' => TRUE, |
| 5749 | ], |
| 5750 | $options['prefix'] . 'postal_code' => [ |
| 5751 | 'title' => $options['prefix_label'] . ts('Postal Code'), |
| 5752 | 'name' => 'postal_code', |
| 5753 | 'type' => 2, |
| 5754 | 'is_fields' => TRUE, |
| 5755 | 'is_filters' => TRUE, |
| 5756 | 'is_group_bys' => TRUE, |
| 5757 | 'is_order_bys' => TRUE, |
| 5758 | ], |
| 5759 | $options['prefix'] . 'postal_code_suffix' => [ |
| 5760 | 'title' => $options['prefix_label'] . ts('Postal Code Suffix'), |
| 5761 | 'name' => 'postal_code_suffix', |
| 5762 | 'type' => 2, |
| 5763 | 'is_fields' => TRUE, |
| 5764 | 'is_filters' => TRUE, |
| 5765 | 'is_group_bys' => TRUE, |
| 5766 | 'is_order_bys' => TRUE, |
| 5767 | ], |
| 5768 | $options['prefix'] . 'county_id' => [ |
| 5769 | 'title' => $options['prefix_label'] . ts('County'), |
| 5770 | 'alter_display' => 'alterCountyID', |
| 5771 | 'name' => 'county_id', |
| 5772 | 'type' => CRM_Utils_Type::T_INT, |
| 5773 | 'operatorType' => CRM_Report_Form::OP_MULTISELECT, |
| 5774 | 'options' => CRM_Core_PseudoConstant::county(), |
| 5775 | 'is_fields' => TRUE, |
| 5776 | 'is_filters' => TRUE, |
| 5777 | 'is_group_bys' => TRUE, |
| 5778 | ], |
| 5779 | $options['prefix'] . 'state_province_id' => [ |
| 5780 | 'title' => $options['prefix_label'] . ts('State/Province'), |
| 5781 | 'alter_display' => 'alterStateProvinceID', |
| 5782 | 'name' => 'state_province_id', |
| 5783 | 'type' => CRM_Utils_Type::T_INT, |
| 5784 | 'operatorType' => CRM_Report_Form::OP_MULTISELECT, |
| 5785 | 'options' => CRM_Core_PseudoConstant::stateProvince(), |
| 5786 | 'is_fields' => TRUE, |
| 5787 | 'is_filters' => TRUE, |
| 5788 | 'is_group_bys' => TRUE, |
| 5789 | ], |
| 5790 | $options['prefix'] . 'country_id' => [ |
| 5791 | 'title' => $options['prefix_label'] . ts('Country'), |
| 5792 | 'alter_display' => 'alterCountryID', |
| 5793 | 'name' => 'country_id', |
| 5794 | 'is_fields' => TRUE, |
| 5795 | 'is_filters' => TRUE, |
| 5796 | 'is_group_bys' => TRUE, |
| 5797 | 'type' => CRM_Utils_Type::T_INT, |
| 5798 | 'operatorType' => CRM_Report_Form::OP_MULTISELECT, |
| 5799 | 'options' => CRM_Core_PseudoConstant::country(), |
| 5800 | ], |
| 5801 | $options['prefix'] . 'location_type_id' => [ |
| 5802 | 'name' => 'location_type_id', |
| 5803 | 'title' => $options['prefix_label'] . ts('Location Type'), |
| 5804 | 'type' => CRM_Utils_Type::T_INT, |
| 5805 | 'is_fields' => TRUE, |
| 5806 | 'alter_display' => 'alterLocationTypeID', |
| 5807 | ], |
| 5808 | $options['prefix'] . 'id' => [ |
| 5809 | 'title' => $options['prefix_label'] . ts('ID'), |
| 5810 | 'name' => 'id', |
| 5811 | 'is_fields' => TRUE, |
| 5812 | ], |
| 5813 | $options['prefix'] . 'is_primary' => [ |
| 5814 | 'name' => 'is_primary', |
| 5815 | 'title' => $options['prefix_label'] . ts('Primary Address?'), |
| 5816 | 'type' => CRM_Utils_Type::T_BOOLEAN, |
| 5817 | 'is_fields' => TRUE, |
| 5818 | ], |
| 5819 | ]; |
| 5820 | return $this->buildColumns($spec, $options['prefix'] . 'civicrm_address', 'CRM_Core_DAO_Address', $tableAlias, $defaults, $options); |
| 5821 | } |
| 5822 | |
| 5823 | /** |
| 5824 | * Build the columns. |
| 5825 | * |
| 5826 | * The normal report class needs you to remember to do a few things that are often erratic |
| 5827 | * |
| 5828 | * 1) use a unique key for any field that might not be unique (e.g. start date, label) |
| 5829 | * - this class will prepend an alias to the key & set the 'name' if you don't set it yourself. |
| 5830 | * You can suppress the alias with 'no_field_disambiguation' if transitioning existing reports. This |
| 5831 | * means any saved filters / fields on saved report instances. This will mean that matching names from |
| 5832 | * different tables may be ambigious, but it will smooth any code transition. |
| 5833 | * - note that it assumes the value being passed in is the actual table field name |
| 5834 | * |
| 5835 | * 2) set the field & set it to no display if you don't want the field but you might want to use the field in other |
| 5836 | * contexts - the code looks up the fields array for data - so it both defines the field spec & the fields you want to show |
| 5837 | * |
| 5838 | * 3) this function also sets the 'metadata' array - the extended report class now uses this in place |
| 5839 | * of the fields array to reduce the issues caused when metadata is needed but 'fields' are not defined. Code in |
| 5840 | * the core classes can start to move towards that. |
| 5841 | * |
| 5842 | * @param array $specs |
| 5843 | * @param string $tableName |
| 5844 | * @param string $daoName |
| 5845 | * @param string $tableAlias |
| 5846 | * @param array $defaults |
| 5847 | * @param array $options |
| 5848 | * |
| 5849 | * @return array |
| 5850 | */ |
| 5851 | protected function buildColumns($specs, $tableName, $daoName = NULL, $tableAlias = NULL, $defaults = [], $options = []) { |
| 5852 | if (!$tableAlias) { |
| 5853 | $tableAlias = str_replace('civicrm_', '', $tableName); |
| 5854 | } |
| 5855 | $types = ['filters', 'group_bys', 'order_bys', 'join_filters']; |
| 5856 | $columns = [$tableName => array_fill_keys($types, [])]; |
| 5857 | // The code that uses this no longer cares if it is a DAO or BAO so just call it a DAO. |
| 5858 | $columns[$tableName]['dao'] = $daoName; |
| 5859 | $columns[$tableName]['alias'] = $tableAlias; |
| 5860 | |
| 5861 | foreach ($specs as $specName => $spec) { |
| 5862 | if (empty($spec['name'])) { |
| 5863 | $spec['name'] = $specName; |
| 5864 | } |
| 5865 | |
| 5866 | $fieldAlias = (empty($options['no_field_disambiguation']) ? $tableAlias . '_' : '') . $specName; |
| 5867 | $columns[$tableName]['metadata'][$fieldAlias] = $spec; |
| 5868 | $columns[$tableName]['fields'][$fieldAlias] = $spec; |
| 5869 | if (isset($defaults['fields_defaults']) && in_array($spec['name'], $defaults['fields_defaults'])) { |
| 5870 | $columns[$tableName]['fields'][$fieldAlias]['default'] = TRUE; |
| 5871 | } |
| 5872 | |
| 5873 | if (!$spec['is_fields'] || (isset($options['fields_excluded']) && in_array($specName, $options['fields_excluded']))) { |
| 5874 | $columns[$tableName]['fields'][$fieldAlias]['no_display'] = TRUE; |
| 5875 | } |
| 5876 | |
| 5877 | if (isset($options['fields_required']) && in_array($specName, $options['fields_required'])) { |
| 5878 | $columns[$tableName]['fields'][$fieldAlias]['required'] = TRUE; |
| 5879 | } |
| 5880 | |
| 5881 | foreach ($types as $type) { |
| 5882 | if ($options[$type] && !empty($spec['is_' . $type])) { |
| 5883 | $columns[$tableName][$type][$fieldAlias] = $spec; |
| 5884 | if (isset($defaults[$type . '_defaults']) && isset($defaults[$type . '_defaults'][$spec['name']])) { |
| 5885 | $columns[$tableName][$type][$fieldAlias]['default'] = $defaults[$type . '_defaults'][$spec['name']]; |
| 5886 | } |
| 5887 | } |
| 5888 | } |
| 5889 | } |
| 5890 | if (isset($options['grouping'])) { |
| 5891 | $columns[$tableName]['grouping'] = $options['grouping']; |
| 5892 | $columns[$tableName]['group_title'] = $options['group_title'] ?? ''; |
| 5893 | } |
| 5894 | return $columns; |
| 5895 | } |
| 5896 | |
| 5897 | /** |
| 5898 | * Store group bys into array - so we can check elsewhere what is grouped. |
| 5899 | */ |
| 5900 | protected function storeGroupByArray() { |
| 5901 | |
| 5902 | if (empty($this->_params['group_bys']) |
| 5903 | || !is_array($this->_params['group_bys'])) { |
| 5904 | $this->_params['group_bys'] = []; |
| 5905 | } |
| 5906 | |
| 5907 | foreach ($this->_columns as $tableName => $table) { |
| 5908 | $table = $this->_columns[$tableName]; |
| 5909 | if (array_key_exists('group_bys', $table)) { |
| 5910 | foreach ($table['group_bys'] as $fieldName => $fieldData) { |
| 5911 | $field = $this->_columns[$tableName]['metadata'][$fieldName]; |
| 5912 | if (!empty($this->_params['group_bys'][$fieldName]) || !empty($fieldData['required'])) { |
| 5913 | if (!empty($field['chart'])) { |
| 5914 | $this->assign('chartSupported', TRUE); |
| 5915 | } |
| 5916 | |
| 5917 | if (!empty($table['group_bys'][$fieldName]['frequency']) && |
| 5918 | !empty($this->_params['group_bys_freq'][$fieldName]) |
| 5919 | ) { |
| 5920 | |
| 5921 | switch ($this->_params['group_bys_freq'][$fieldName]) { |
| 5922 | case 'FISCALYEAR': |
| 5923 | $this->_groupByArray[$tableName . '_' . $fieldName . '_start'] = self::fiscalYearOffset($field['dbAlias']); |
| 5924 | break; |
| 5925 | |
| 5926 | case 'YEAR': |
| 5927 | $this->_groupByArray[$tableName . '_' . $fieldName . '_start'] = " YEAR({$field['dbAlias']})"; |
| 5928 | break; |
| 5929 | |
| 5930 | case 'QUARTER': |
| 5931 | $this->_groupByArray[$tableName . '_' . $fieldName . '_start'] = "YEAR({$field['dbAlias']}), QUARTER({$field['dbAlias']})"; |
| 5932 | break; |
| 5933 | |
| 5934 | case 'YEARWEEK': |
| 5935 | $this->_groupByArray[$tableName . '_' . $fieldName . '_start'] = "YEARWEEK({$field['dbAlias']})"; |
| 5936 | break; |
| 5937 | |
| 5938 | case 'MONTH': |
| 5939 | $this->_groupByArray[$tableName . '_' . $fieldName . '_start'] = "EXTRACT(YEAR_MONTH FROM {$field['dbAlias']})"; |
| 5940 | break; |
| 5941 | |
| 5942 | case 'DATE': |
| 5943 | $this->_groupByArray[$tableName . '_' . $fieldName . '_start'] = "DATE({$field['dbAlias']})"; |
| 5944 | break; |
| 5945 | } |
| 5946 | } |
| 5947 | else { |
| 5948 | if (!in_array($field['dbAlias'], $this->_groupByArray)) { |
| 5949 | $this->_groupByArray[$tableName . '_' . $fieldName] = $field['dbAlias']; |
| 5950 | } |
| 5951 | } |
| 5952 | } |
| 5953 | } |
| 5954 | |
| 5955 | } |
| 5956 | } |
| 5957 | } |
| 5958 | |
| 5959 | /** |
| 5960 | * @param $options |
| 5961 | * |
| 5962 | * @return array |
| 5963 | */ |
| 5964 | protected function getDefaultsFromOptions($options) { |
| 5965 | $defaults = [ |
| 5966 | 'fields_defaults' => $options['fields_defaults'], |
| 5967 | 'filters_defaults' => $options['filters_defaults'], |
| 5968 | 'group_bys_defaults' => $options['group_bys_defaults'], |
| 5969 | 'order_bys_defaults' => $options['order_bys_defaults'], |
| 5970 | ]; |
| 5971 | return $defaults; |
| 5972 | } |
| 5973 | |
| 5974 | /** |
| 5975 | * Get the select clause for a field, wrapping in GROUP_CONCAT if appropriate. |
| 5976 | * |
| 5977 | * Full group by mode dictates that a field must either be in the group by function or |
| 5978 | * wrapped in a aggregate function. Here we wrap the field in GROUP_CONCAT if it is not in the |
| 5979 | * group concat. |
| 5980 | * |
| 5981 | * @param string $tableName |
| 5982 | * @param string $fieldName |
| 5983 | * @param string $field |
| 5984 | * @return string |
| 5985 | */ |
| 5986 | protected function getSelectClauseWithGroupConcatIfNotGroupedBy($tableName, &$fieldName, &$field) { |
| 5987 | if ($this->groupConcatTested && (!empty($this->_groupByArray) || $this->isForceGroupBy)) { |
| 5988 | if ((empty($field['statistics']) || in_array('GROUP_CONCAT', $field['statistics']))) { |
| 5989 | $label = $field['title'] ?? NULL; |
| 5990 | $alias = $field['tplField'] ?? "{$tableName}_{$fieldName}"; |
| 5991 | $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $label; |
| 5992 | $this->_selectAliases[] = $alias; |
| 5993 | if (empty($this->_groupByArray[$tableName . '_' . $fieldName])) { |
| 5994 | return "GROUP_CONCAT(DISTINCT {$field['dbAlias']}) as $alias"; |
| 5995 | } |
| 5996 | return "({$field['dbAlias']}) as $alias"; |
| 5997 | } |
| 5998 | } |
| 5999 | } |
| 6000 | |
| 6001 | /** |
| 6002 | * Generate clause for the selected filter. |
| 6003 | * |
| 6004 | * @param array $field |
| 6005 | * Field specification |
| 6006 | * @param string $fieldName |
| 6007 | * Field name. |
| 6008 | * |
| 6009 | * @return string |
| 6010 | * Relevant where clause. |
| 6011 | */ |
| 6012 | protected function generateFilterClause($field, $fieldName) { |
| 6013 | if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) { |
| 6014 | if (CRM_Utils_Array::value('operatorType', $field) == |
| 6015 | CRM_Report_Form::OP_MONTH |
| 6016 | ) { |
| 6017 | $op = $this->_params["{$fieldName}_op"] ?? NULL; |
| 6018 | $value = $this->_params["{$fieldName}_value"] ?? NULL; |
| 6019 | if (is_array($value) && !empty($value)) { |
| 6020 | return "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . |
| 6021 | '))'; |
| 6022 | } |
| 6023 | } |
| 6024 | else { |
| 6025 | $relative = $this->_params["{$fieldName}_relative"] ?? NULL; |
| 6026 | $from = $this->_params["{$fieldName}_from"] ?? NULL; |
| 6027 | $to = $this->_params["{$fieldName}_to"] ?? NULL; |
| 6028 | $fromTime = $this->_params["{$fieldName}_from_time"] ?? NULL; |
| 6029 | $toTime = $this->_params["{$fieldName}_to_time"] ?? NULL; |
| 6030 | return $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime); |
| 6031 | } |
| 6032 | } |
| 6033 | else { |
| 6034 | $op = $this->_params["{$fieldName}_op"] ?? NULL; |
| 6035 | if ($op) { |
| 6036 | return $this->whereClause($field, |
| 6037 | $op, |
| 6038 | CRM_Utils_Array::value("{$fieldName}_value", $this->_params), |
| 6039 | CRM_Utils_Array::value("{$fieldName}_min", $this->_params), |
| 6040 | CRM_Utils_Array::value("{$fieldName}_max", $this->_params) |
| 6041 | ); |
| 6042 | } |
| 6043 | } |
| 6044 | return ''; |
| 6045 | } |
| 6046 | |
| 6047 | /** |
| 6048 | * Retrieve a suitable object from the factory depending on the report |
| 6049 | * parameters, which typically might just be dependent on outputMode. |
| 6050 | * |
| 6051 | * If there is no suitable output handler, e.g. if outputMode is "copy", |
| 6052 | * then this sets it to NULL. |
| 6053 | */ |
| 6054 | public function setOutputHandler() { |
| 6055 | $this->outputHandler = \Civi\Report\OutputHandlerFactory::singleton()->create($this); |
| 6056 | } |
| 6057 | |
| 6058 | /** |
| 6059 | * Send report by email |
| 6060 | */ |
| 6061 | public function sendEmail() { |
| 6062 | if (empty($this->outputHandler)) { |
| 6063 | // It's possible to end up here with outputMode unset, so we use |
| 6064 | // the "print" handler which was the default before, i.e. include |
| 6065 | // it as html in the body. |
| 6066 | $oldOutputMode = $this->_outputMode ?? NULL; |
| 6067 | $this->_outputMode = 'print'; |
| 6068 | $this->setOutputHandler(); |
| 6069 | $this->_outputMode = $oldOutputMode; |
| 6070 | } |
| 6071 | |
| 6072 | $mailBody = $this->outputHandler->getMailBody(); |
| 6073 | |
| 6074 | $attachments = []; |
| 6075 | $attachmentFileName = $this->outputHandler->getFileName(); |
| 6076 | // It's not always in the form of an attachment, e.g. for 'print' the |
| 6077 | // output ends up in $mailBody above. |
| 6078 | if ($attachmentFileName) { |
| 6079 | $fullFilename = CRM_Core_Config::singleton()->templateCompileDir . CRM_Utils_File::makeFileName($attachmentFileName); |
| 6080 | file_put_contents($fullFilename, $this->outputHandler->getOutputString()); |
| 6081 | $attachments[] = [ |
| 6082 | 'fullPath' => $fullFilename, |
| 6083 | 'mime_type' => $this->outputHandler->getMimeType(), |
| 6084 | 'cleanName' => $attachmentFileName, |
| 6085 | 'charset' => $this->outputHandler->getCharset(), |
| 6086 | ]; |
| 6087 | } |
| 6088 | |
| 6089 | // Send the email |
| 6090 | // @todo outputMode doesn't seem to get used by mailReport, which is good |
| 6091 | // since it shouldn't have any outputMode-related `if` statements in it. |
| 6092 | // Someday could remove the param from the function call. |
| 6093 | if (CRM_Report_Utils_Report::mailReport($mailBody, $this->_id, $this->_outputMode, $attachments)) { |
| 6094 | CRM_Core_Session::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success'); |
| 6095 | } |
| 6096 | else { |
| 6097 | CRM_Core_Session::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error'); |
| 6098 | } |
| 6099 | } |
| 6100 | |
| 6101 | } |