3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
18 use Civi\Api4\UserJob
;
19 use League\Csv\Writer
;
22 * This class helps the forms within the import flow access submitted & parsed values.
24 class CRM_Import_Forms
extends CRM_Core_Form
{
29 * This is the primary key of the civicrm_user_job table which is used to
39 public function getUserJobID(): ?
int {
40 if (!$this->userJobID
&& $this->get('user_job_id')) {
41 $this->userJobID
= $this->get('user_job_id');
43 return $this->userJobID
;
49 * @param int $userJobID
51 public function setUserJobID(int $userJobID): void
{
52 $this->userJobID
= $userJobID;
53 // This set allows other forms in the flow ot use $this->get('user_job_id').
54 $this->set('user_job_id', $userJobID);
60 * This is the relevant row from civicrm_user_job.
67 * @var \CRM_Import_Parser
74 * API call to retrieve the userJob row.
78 * @throws \API_Exception
80 protected function getUserJob(): array {
81 if (!$this->userJob
) {
82 $this->userJob
= UserJob
::get()
83 ->addWhere('id', '=', $this->getUserJobID())
87 return $this->userJob
;
91 * Get submitted values stored in the user job.
94 * @throws \API_Exception
96 protected function getUserJobSubmittedValues(): array {
97 return $this->getUserJob()['metadata']['submitted_values'];
101 * Fields that may be submitted on any form in the flow.
105 protected $submittableFields = [
106 // Skip column header is actually a field that would be added from the
107 // datasource - but currently only in contact, it is always there for
108 // other imports, ditto uploadFile.
109 'skipColumnHeader' => 'DataSource',
110 'fieldSeparator' => 'DataSource',
111 'uploadFile' => 'DataSource',
112 'contactType' => 'DataSource',
113 'contactSubType' => 'DataSource',
114 'dateFormats' => 'DataSource',
115 'savedMapping' => 'DataSource',
116 'dataSource' => 'DataSource',
117 'dedupe_rule_id' => 'DataSource',
118 'onDuplicate' => 'DataSource',
119 'disableUSPS' => 'DataSource',
120 'doGeocodeAddress' => 'DataSource',
121 // Note we don't add the save mapping instructions for MapField here
122 // (eg 'updateMapping') - as they really are an action for that form
123 // rather than part of the mapping config.
124 'mapper' => 'MapField',
128 * Get the submitted value, accessing it from whatever form in the flow it is
131 * @param string $fieldName
134 * @throws \CRM_Core_Exception
136 public function getSubmittedValue(string $fieldName) {
137 if ($fieldName === 'dataSource') {
138 // Hard-coded handling for DataSource as it affects the contents of
139 // getSubmittableFields and can cause a loop.
140 // Note that the non-contact imports are not currently sharing the DataSource.tpl
141 // that adds the CSV/SQL options & hence fall back on this hidden field.
142 // - todo - switch to the same DataSource.tpl for all.
143 return $this->controller
->exportValue('DataSource', 'dataSource') ??
$this->controller
->exportValue('DataSource', 'hidden_dataSource');
145 $mappedValues = $this->getSubmittableFields();
146 if (array_key_exists($fieldName, $mappedValues)) {
147 return $this->controller
->exportValue($mappedValues[$fieldName], $fieldName);
149 return parent
::getSubmittedValue($fieldName);
154 * Get values submitted on any form in the multi-page import flow.
158 public function getSubmittedValues(): array {
160 foreach (array_keys($this->getSubmittableFields()) as $key) {
161 $values[$key] = $this->getSubmittedValue($key);
167 * Get the available datasource.
169 * Permission dependent, this will look like
171 * 'CRM_Import_DataSource_CSV' => 'Comma-Separated Values (CSV)',
172 * 'CRM_Import_DataSource_SQL' => 'SQL Query',
175 * The label is translated.
179 protected function getDataSources(): array {
181 foreach (['CRM_Import_DataSource_SQL', 'CRM_Import_DataSource_CSV'] as $dataSourceClass) {
182 $object = new $dataSourceClass();
183 if ($object->checkPermission()) {
184 $dataSources[$dataSourceClass] = $object->getInfo()['title'];
191 * Get the name of the datasource class.
193 * This function prioritises retrieving from GET and POST over 'submitted'.
194 * The reason for this is the submitted array will hold the previous submissions
195 * data until after buildForm is called.
197 * This is problematic in the forward->back flow & option changing flow. As in....
199 * 1) Load DataSource form - initial default datasource is set to CSV and the
200 * form is via ajax (this calls DataSourceConfig to get the data).
201 * 2) User changes the source to SQL - the ajax updates the html but the
202 * form was built with the expectation that the csv-specific fields would be
204 * 3) When the user submits Quickform calls preProcess and buildForm and THEN
205 * retrieves the submitted values based on what has been added in buildForm.
206 * Only the submitted values for fields added in buildForm are available - but
207 * these have to be added BEFORE the submitted values are determined. Hence
208 * we look in the POST or GET to get the updated value.
210 * Note that an imminent refactor will involve storing the values in the
211 * civicrm_user_job table - this will hopefully help with a known (not new)
212 * issue whereby the previously submitted values (eg. skipColumnHeader has
213 * been checked or sql has been filled in) are not loaded via the ajax request.
215 * @return string|null
217 * @throws \CRM_Core_Exception
219 protected function getDataSourceClassName(): string {
220 $className = CRM_Utils_Request
::retrieveValue(
225 $className = $this->getSubmittedValue('dataSource');
228 $className = $this->getDefaultDataSource();
230 if ($this->getDataSources()[$className]) {
233 throw new CRM_Core_Exception('Invalid data source');
237 * Allow the datasource class to add fields.
239 * This is called as a snippet in DataSourceConfig and
240 * also from DataSource::buildForm to add the fields such
241 * that quick form picks them up.
243 * @throws \CRM_Core_Exception
245 protected function buildDataSourceFields(): void
{
246 $dataSourceClass = $this->getDataSourceObject();
247 if ($dataSourceClass) {
248 $dataSourceClass->buildQuickForm($this);
253 * Flush datasource on re-submission of the form.
255 * If the form has been re-submitted the datasource might have changed.
256 * We tell the dataSource class to remove any tables (and potentially files)
257 * created last form submission.
259 * If the DataSource in use is unchanged (ie still CSV or still SQL)
260 * we also pass in the new variables. In theory it could decide that they
261 * have not actually changed and it doesn't need to do any cleanup.
263 * In practice the datasource classes blast away as they always have for now
264 * - however, the sql class, for example, might realise the fields it cares
265 * about are unchanged and not flush the table.
267 * @throws \API_Exception
268 * @throws \CRM_Core_Exception
270 protected function flushDataSource(): void
{
271 // If the form has been resubmitted the datasource might have changed.
272 // We give the datasource a chance to clean up any tables it might have
273 // created. If we are still using the same type of datasource (e.g still
275 $oldDataSource = $this->getUserJobSubmittedValues()['dataSource'];
276 $oldDataSourceObject = new $oldDataSource($this->getUserJobID());
277 $newParams = $this->getSubmittedValue('dataSource') === $oldDataSource ?
$this->getSubmittedValues() : [];
278 $oldDataSourceObject->purge($newParams);
282 * Get the relevant datasource object.
284 * @return \CRM_Import_DataSource|null
286 * @throws \CRM_Core_Exception
288 protected function getDataSourceObject(): ?CRM_Import_DataSource
{
289 $className = $this->getDataSourceClassName();
291 /* @var CRM_Import_DataSource $dataSource */
292 return new $className($this->getUserJobID());
298 * Allow the datasource class to add fields.
300 * This is called as a snippet in DataSourceConfig and
301 * also from DataSource::buildForm to add the fields such
302 * that quick form picks them up.
304 * @throws \CRM_Core_Exception
306 protected function getDataSourceFields(): array {
307 $className = $this->getDataSourceClassName();
309 /* @var CRM_Import_DataSource $dataSourceClass */
310 $dataSourceClass = new $className();
311 return $dataSourceClass->getSubmittableFields();
317 * Get the default datasource.
321 protected function getDefaultDataSource(): string {
322 return 'CRM_Import_DataSource_CSV';
326 * Get the fields that can be submitted in the Import form flow.
328 * These could be on any form in the flow & are accessed the same way from
332 * @throws \CRM_Core_Exception
334 protected function getSubmittableFields(): array {
335 $dataSourceFields = array_fill_keys($this->getDataSourceFields(), 'DataSource');
336 return array_merge($this->submittableFields
, $dataSourceFields);
340 * Get the contact type selected for the import (on the datasource form).
343 * e.g Individual, Organization, Household.
345 * @throws \CRM_Core_Exception
347 protected function getContactType(): string {
348 $contactTypeMapping = [
349 CRM_Import_Parser
::CONTACT_INDIVIDUAL
=> 'Individual',
350 CRM_Import_Parser
::CONTACT_HOUSEHOLD
=> 'Household',
351 CRM_Import_Parser
::CONTACT_ORGANIZATION
=> 'Organization',
353 return $contactTypeMapping[$this->getSubmittedValue('contactType')];
357 * Get the contact sub type selected for the import (on the datasource form).
359 * @return string|null
362 * @throws \CRM_Core_Exception
364 protected function getContactSubType(): ?
string {
365 return $this->getSubmittedValue('contactSubType');
369 * Create a user job to track the import.
373 * @throws \API_Exception
375 protected function createUserJob(): int {
376 $id = UserJob
::create(FALSE)
378 'created_id' => CRM_Core_Session
::getLoggedInContactID(),
379 'type_id:name' => $this->getUserJobType(),
380 'status_id:name' => 'draft',
381 // This suggests the data could be cleaned up after this.
382 'expires_date' => '+ 1 week',
384 'submitted_values' => $this->getSubmittedValues(),
389 $this->setUserJobID($id);
397 * @throws \API_Exception
398 * @throws \Civi\API\Exception\UnauthorizedException
400 protected function updateUserJobMetadata(string $key, array $data): void
{
401 $metaData = array_merge(
402 $this->getUserJob()['metadata'],
405 UserJob
::update(FALSE)
406 ->addWhere('id', '=', $this->getUserJobID())
407 ->setValues(['metadata' => $metaData])
409 $this->userJob
['metadata'] = $metaData;
413 * Get column headers for the datasource or empty array if none apply.
415 * This would be the first row of a csv or the fields in an sql query.
417 * If the csv does not have a header row it will be empty.
421 * @throws \API_Exception
422 * @throws \CRM_Core_Exception
424 protected function getColumnHeaders(): array {
425 return $this->getDataSourceObject()->getColumnHeaders();
429 * Get the number of importable columns in the data source.
433 * @throws \API_Exception
434 * @throws \CRM_Core_Exception
436 protected function getNumberOfColumns(): int {
437 return $this->getDataSourceObject()->getNumberOfColumns();
441 * Get x data rows from the datasource.
443 * At this stage we are fetching from what has been stored in the form
444 * during `postProcess` on the DataSource form.
446 * In the future we will use the dataSource object, likely
447 * supporting offset as well.
450 * One or more of the statues available - e.g
451 * CRM_Import_Parser::VALID
452 * or [CRM_Import_Parser::ERROR, CRM_Import_Parser::VALID]
454 * @throws \CRM_Core_Exception
455 * @throws \API_Exception
457 protected function getDataRows($statuses = [], int $limit = 0): array {
458 $statuses = (array) $statuses;
459 return $this->getDataSourceObject()->setLimit($limit)->setStatuses($statuses)->getRows();
463 * Get the number of rows with the specified status.
465 * @param array|int $statuses
469 * @throws \API_Exception
470 * @throws \CRM_Core_Exception
472 protected function getRowCount($statuses = []) {
473 $statuses = (array) $statuses;
474 return $this->getDataSourceObject()->getRowCount($statuses);
478 * Outputs and downloads the csv of outcomes from an import job.
480 * This gets the rows from the temp table that match the relevant status
481 * and output them as a csv.
483 * @throws \API_Exception
484 * @throws \League\Csv\CannotInsertRecord
485 * @throws \CRM_Core_Exception
487 public static function outputCSV(): void
{
488 $userJobID = CRM_Utils_Request
::retrieveValue('user_job_id', 'Integer', NULL, TRUE);
489 $status = CRM_Utils_Request
::retrieveValue('status', 'String', NULL, TRUE);
490 $saveFileName = CRM_Import_Parser
::saveFileName($status);
492 $form = new CRM_Import_Forms();
493 $form->controller
= new CRM_Core_Controller();
494 $form->set('user_job_id', $userJobID);
497 $writer = Writer
::createFromFileObject(new SplTempFileObject());
498 $headers = $form->getColumnHeaders();
500 array_unshift($headers, ts('Reason'));
501 array_unshift($headers, ts('Line Number'));
502 $writer->insertOne($headers);
504 $writer->addFormatter(['CRM_Import_Forms', 'reorderOutput']);
505 // Note this might be more inefficient that iterating the result
506 // set & doing insertOne - possibly something to explore later.
507 $writer->insertAll($form->getDataRows($status));
509 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
510 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
511 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv; charset=UTF-8');
512 $writer->output($saveFileName);
513 CRM_Utils_System
::civiExit();
517 * When outputting the row as a csv, more the last 2 rows to the start.
519 * This is because the id and status message fields are at the end. It may make sense
520 * to move them to the start later, when order code cleanup has happened...
522 * @param array $record
524 public static function reorderOutput(array $record): array {
525 $rowNumber = array_pop($record);
526 $message = array_pop($record);
527 // Also pop off the status - but we are not going to use this at this stage.
533 array_unshift($record, $message);
534 array_unshift($record, $rowNumber);
539 * Get the url to download the relevant csv file.
540 * @param string $status
544 protected function getDownloadURL(string $status): string {
545 return CRM_Utils_System
::url('civicrm/import/outcome', [
546 'user_job_id' => $this->get('user_job_id'),
553 * Get the fields available for import selection.
556 * e.g ['first_name' => 'First Name', 'last_name' => 'Last Name'....
558 * @throws \API_Exception
560 protected function getAvailableFields(): array {
561 return $this->getParser()->getAvailableFields();
565 * Get an instance of the parser class.
567 * @return \CRM_Contact_Import_Parser_Contact|\CRM_Contribute_Import_Parser_Contribution
569 protected function getParser() {
574 * Get the mapped fields as an array of labels.
577 * ['First Name', 'Employee Of - First Name', 'Home - Street Address']
580 * @throws \API_Exception
581 * @throws \CRM_Core_Exception
583 protected function getMappedFieldLabels(): array {
585 $parser = $this->getParser();
586 foreach ($this->getSubmittedValue('mapper') as $columnNumber => $mappedField) {
587 $mapper[$columnNumber] = $parser->getMappedFieldLabel($parser->getMappingFieldFromMapperInput($mappedField, 0, $columnNumber));
593 * Assign variables required for the MapField form.
595 * @throws \API_Exception
596 * @throws \CRM_Core_Exception
598 protected function assignMapFieldVariables(): void
{
599 $this->addExpectedSmartyVariable('highlightedRelFields');
600 $this->_columnCount
= $this->getNumberOfColumns();
601 $this->_columnNames
= $this->getColumnHeaders();
602 $this->_dataValues
= array_values($this->getDataRows([], 2));
603 $this->assign('columnNames', $this->getColumnHeaders());
604 $this->assign('highlightedFields', $this->getHighlightedFields());
605 $this->assign('columnCount', $this->_columnCount
);
606 $this->assign('dataValues', $this->_dataValues
);
610 * Get the fields to be highlighted in the UI.
612 * The highlighted fields are those used to match
613 * to an existing entity.
617 * @throws \CRM_Core_Exception
619 protected function getHighlightedFields(): array {
624 * Get the data patterns to pattern match the incoming data.
628 public function getDataPatterns(): array {
629 return $this->getParser()->getDataPatterns();
633 * Get the data patterns to pattern match the incoming data.
637 public function getHeaderPatterns(): array {
638 return $this->getParser()->getHeaderPatterns();