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