Merge pull request #23824 from totten/mixin-refresh
[civicrm-core.git] / CRM / Import / DataSource / SQL.php
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 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Import_DataSource_SQL extends CRM_Import_DataSource {
18
19 /**
20 * Form fields declared for this datasource.
21 *
22 * @var string[]
23 */
24 protected $submittableFields = ['sqlQuery'];
25
26 /**
27 * Provides information about the data source.
28 *
29 * @return array
30 * collection of info about this data source
31 */
32 public function getInfo(): array {
33 return [
34 'title' => ts('SQL Query'),
35 'permissions' => ['import SQL datasource'],
36 ];
37 }
38
39 /**
40 * This is function is called by the form object to get the DataSource's
41 * form snippet. It should add all fields necesarry to get the data
42 * uploaded to the temporary table in the DB.
43 *
44 * @param CRM_Core_Form $form
45 *
46 * @return void
47 * (operates directly on form argument)
48 */
49 public function buildQuickForm(&$form) {
50 $form->add('hidden', 'hidden_dataSource', 'CRM_Import_DataSource_SQL');
51 $form->add('textarea', 'sqlQuery', ts('Specify SQL Query'), ['rows' => 10, 'cols' => 45], TRUE);
52 $form->addFormRule(['CRM_Import_DataSource_SQL', 'formRule'], $form);
53 }
54
55 /**
56 * @param $fields
57 * @param $files
58 * @param CRM_Core_Form $form
59 *
60 * @return array|bool
61 */
62 public static function formRule($fields, $files, $form) {
63 $errors = [];
64
65 // Makeshift query validation (case-insensitive regex matching on word boundaries)
66 $forbidden = ['ALTER', 'CREATE', 'DELETE', 'DESCRIBE', 'DROP', 'SHOW', 'UPDATE', 'REPLACE', 'information_schema'];
67 foreach ($forbidden as $pattern) {
68 if (preg_match("/\\b$pattern\\b/i", $fields['sqlQuery'])) {
69 $errors['sqlQuery'] = ts('The query contains the forbidden %1 command.', [1 => $pattern]);
70 }
71 }
72
73 return $errors ?: TRUE;
74 }
75
76 /**
77 * Initialize the datasource, based on the submitted values stored in the user job.
78 *
79 * @throws \API_Exception
80 * @throws \CRM_Core_Exception
81 */
82 public function initialize(): void {
83 $table = CRM_Utils_SQL_TempTable::build()->setDurable();
84 $tableName = $table->getName();
85 $table->createWithQuery($this->getSubmittedValue('sqlQuery'));
86
87 // Get the names of the fields to be imported. Any fields starting with an
88 // underscore are considered to be internal to the import process)
89 $columnsResult = CRM_Core_DAO::executeQuery(
90 'SHOW FIELDS FROM ' . $tableName . "
91 WHERE Field NOT LIKE '\_%'");
92
93 $columnNames = [];
94 while ($columnsResult->fetch()) {
95 if (strpos($columnsResult->Field, ' ') !== FALSE) {
96 // Remove spaces as the Database object does this
97 // $keys = str_replace(array(".", " "), "_", array_keys($array));
98 // https://lab.civicrm.org/dev/core/-/issues/1337
99 $usableColumnName = str_replace(' ', '_', $columnsResult->Field);
100 CRM_Core_DAO::executeQuery('ALTER TABLE ' . $tableName . ' CHANGE `' . $columnsResult->Field . '` ' . $usableColumnName . ' ' . $columnsResult->Type);
101 $columnNames[] = $usableColumnName;
102 }
103 else {
104 $columnNames[] = $columnsResult->Field;
105 }
106 }
107
108 $this->addTrackingFieldsToTable($tableName);
109 $this->updateUserJobMetadata('DataSource', [
110 'table_name' => $tableName,
111 'column_headers' => $columnNames,
112 'number_of_columns' => count($columnNames),
113 ]);
114 }
115
116 }