Merge pull request #23159 from eileenmcnaughton/event
[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 * Provides information about the data source.
21 *
22 * @return array
23 * collection of info about this data source
24 */
25 public function getInfo(): array {
26 return [
27 'title' => ts('SQL Query'),
28 'permissions' => ['import SQL datasource'],
29 ];
30 }
31
32 /**
33 * Set variables up before form is built.
34 *
35 * @param CRM_Core_Form $form
36 */
37 public function preProcess(&$form) {
38 }
39
40 /**
41 * This is function is called by the form object to get the DataSource's
42 * form snippet. It should add all fields necesarry to get the data
43 * uploaded to the temporary table in the DB.
44 *
45 * @param CRM_Core_Form $form
46 *
47 * @return void
48 * (operates directly on form argument)
49 */
50 public function buildQuickForm(&$form) {
51 $form->add('hidden', 'hidden_dataSource', 'CRM_Import_DataSource_SQL');
52 $form->add('textarea', 'sqlQuery', ts('Specify SQL Query'), ['rows' => 10, 'cols' => 45], TRUE);
53 $form->addFormRule(['CRM_Import_DataSource_SQL', 'formRule'], $form);
54 }
55
56 /**
57 * @param $fields
58 * @param $files
59 * @param CRM_Core_Form $form
60 *
61 * @return array|bool
62 */
63 public static function formRule($fields, $files, $form) {
64 $errors = [];
65
66 // Makeshift query validation (case-insensitive regex matching on word boundaries)
67 $forbidden = ['ALTER', 'CREATE', 'DELETE', 'DESCRIBE', 'DROP', 'SHOW', 'UPDATE', 'information_schema'];
68 foreach ($forbidden as $pattern) {
69 if (preg_match("/\\b$pattern\\b/i", $fields['sqlQuery'])) {
70 $errors['sqlQuery'] = ts('The query contains the forbidden %1 command.', [1 => $pattern]);
71 }
72 }
73
74 return $errors ? $errors : TRUE;
75 }
76
77 /**
78 * Process the form submission.
79 *
80 * @param array $params
81 * @param string $db
82 * @param \CRM_Core_Form $form
83 *
84 * @throws \CRM_Core_Exception
85 */
86 public function postProcess(&$params, &$db, &$form) {
87 $importJob = new CRM_Contact_Import_ImportJob(
88 CRM_Utils_Array::value('import_table_name', $params),
89 $params['sqlQuery'], TRUE
90 );
91
92 $form->set('importTableName', $importJob->getTableName());
93 }
94
95 }