Completed
Push — master ( dd98a7...a98764 )
by diego
10s
created

InsertUpdateTable::saltPassword()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 0
cts 7
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 3
nop 1
crap 12
1
<?php
2
namespace HDNET\Importr\Service\Targets;
3
4
use HDNET\Importr\Domain\Model\Strategy;
5
use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;
6
use HDNET\Importr\Utility;
7
8
/**
9
 * Imports records from a .CSV file into the target table which you
10
 * can specify on the target section in your strategy.
11
 * If a record does not exist in the table, it will be inserted,
12
 * otherwise it will be just updated. No duplicates are created.
13
 *
14
 * complete example (strategy target):
15
 *
16
 * HDNET\Importr\Service\Targets\InsertUpdateTable:
17
 *   target_table: fe_users
18
 *   exclude_from_update:
19
 *     0: password
20
 *     1: first_name
21
 *     2: zip
22
 *   pid: 324
23
 *   identifier: username
24
 *   salt_password: 1
25
 *   mapping:
26
 *     0: username
27
 *     1: password
28
 *     2: usergroup
29
 *     3: name
30
 *     4: first_name
31
 *     5: address
32
 *     6: telephone
33
 *     7: email
34
 *     8: zip
35
 *     9: city
36
 *     10: company
37
 *
38
 * Example CSV:
39
 *
40
 * username;password;usergroup;name;first_name;address;telephone;email;zip;city;company
41
 * EduardFekete;PW123;3;Fekete;Eduard; Example 21; +049123456789;[email protected];91550;Feuchtwangen;MB Connect Line GmbH
42
 * HansVader;PW1234;3;Vader;Hans; Example 22; +049123456710;[email protected];99900;Universe;Hollywood Studios
43
 *
44
 * ------------------------------------------------------------------------------------------------
45
 *
46
 *   exclude_from_update:    the elements specified in this array, are never being updated
47
 *
48
 *   salt_password:          if set to 1 then passwords are being salted before they are stored in the database
49
 *
50
 * ------------------------------------------------------------------------------------------------
51
 * @author Eduard Fekete
52
 */
53
class InsertUpdateTable extends DbRecord implements TargetInterface
54
{
55
    /**
56
     * @var int
57
     */
58
    protected $identifierField;
59
60
    /**
61
     * @param Strategy $strategy
62
     */
63
    public function start(Strategy $strategy)
64
    {
65
        parent::start($strategy);
66
        if (!isset($this->getConfiguration()['identifier'])) {
67
            throw new \RuntimeException('Identifier field is missing!');
68
        }
69
        $identifier = $this->getConfiguration()['identifier'];
70
        $identifierField = array_search($identifier, $this->getConfiguration()['mapping']);
71
        if ($identifierField === false) {
72
            throw new \RuntimeException('Identifier field not found in mapping.');
73
        }
74
        $this->identifierField = $identifierField;
75
    }
76
77
    /**
78
     * Process every entry in the .csv
79
     *
80
     * @param array $entry
81
     *
82
     * @return int|void
83
     */
84
    public function processEntry(array $entry)
85
    {
86
        $record_exists = false;
87
        $entry_identifier = $entry[$this->identifierField];
88
        $records = $this->getRecords("*");
89
        $fieldName = $this->getConfiguration()['mapping'][$this->identifierField];
90
91
        foreach ($records as $record) {
0 ignored issues
show
Bug introduced by
The expression $records of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
92
            if ($record['deleted'] == 0) {
93
                if ($record[$fieldName] == $entry_identifier) {
94
                    $record_exists = true;
95
                    break;
96
                }
97
            } else {
98
                continue;
99
            }
100
        }
101
102
        if ($record_exists) {
103
            $this->updateRecord($entry);
104
            return TargetInterface::RESULT_UPDATE;
105
        }
106
107
        $this->insertRecord($entry);
108
        return TargetInterface::RESULT_INSERT;
109
    }
110
111
    /**
112
     *
113
     * Fetch all records from the target table, where the PID equals the PID specified
114
     * in the target section of the strategy
115
     *
116
     * @param $selectFields
117
     * @return array
118
     */
119
    protected function getRecords($selectFields)
120
    {
121
        static $records = [];
122
        if ($records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
123
            return $records;
124
        }
125
126
        $fromTable = $this->getConfiguration()['target_table'];
127
        $whereStatement = "pid = '" . $this->getConfiguration()['pid'] . "'";
128
129
        $records = Utility::getDatabaseConnection()->exec_SELECTgetRows(
130
            $selectFields,
131
            $fromTable,
132
            $whereStatement
133
        );
134
135
        return $records;
136
    }
137
138
    /**
139
     * Insert record into the target table which you have specified in the target section of the strategy
140
     *
141
     * @param array $entry
142
     *
143
     * @return void
144
     */
145
    protected function insertRecord(array $entry)
146
    {
147
        $field_values = [];
148
        $into_table = $this->getConfiguration()['target_table'];
149
150
        foreach ($this->getConfiguration()["mapping"] as $key => $value) {
151
            $field_values[$value] = $entry[$key];
152
        }
153
        
154 View Code Duplication
        if ($this->getConfiguration()["salt_password"] == 1) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
155
            $field_values["password"] = $this->saltPassword($field_values["password"]);
156
        }
157
158
        $field_values['pid'] = $this->getConfiguration()['pid'];
159
        $time = time();
160
        $field_values['tstamp'] = $time;
161
        $field_values['crdate'] = $time;
162
        
163
        Utility::getDatabaseConnection()->exec_INSERTquery($into_table, $field_values);
164
    }
165
166
    /**
167
     * Update a record in the target table which you have specified in the
168
     * target section of the strategy (don't update the password)
169
     *
170
     * @param array $entry
171
     *
172
     * @return void
173
     */
174
    protected function updateRecord(array $entry)
175
    {
176
        $into_table = $this->getConfiguration()['target_table'];
177
        $fieldName = $this->getConfiguration()['mapping'][$this->identifierField];
178
        $whereStatement = "pid = '" . $this->getConfiguration()['pid'] . "' AND " . $fieldName . " = '" . $entry[$this->identifierField] . "'";
179
180
        $tmp_arr = [];
181
182
        foreach ($this->getConfiguration()["mapping"] as $key => $value) {
183
            $tmp_arr[$value] = $entry[$key];
184
        }
185
        
186 View Code Duplication
        if ($this->getConfiguration()["salt_password"] == 1) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
187
            $tmp_arr['password'] = $this->saltPassword($tmp_arr['password']);
188
        }
189
        
190
        $field_values = $this->duplicateArray($tmp_arr, $this->getConfiguration()['exclude_from_update']);
191
        $field_values['tstamp'] = time();
192
193
        Utility::getDatabaseConnection()->exec_UPDATEquery($into_table, $whereStatement, $field_values);
194
    }
195
196
    /**
197
     * This function creates a duplicate of a associative array and optionally removes
198
     * any entries which are also elements of a second array
199
     *
200
     * @param array $arr
201
     * @param array $exclude_arr
202
     *
203
     * @return array
204
     */
205
    protected function duplicateArray(array $arr, array $exclude_arr = null)
206
    {
207
        if (!is_array($exclude_arr)) {
208
            return $arr;
209
        }
210
211
        foreach ($arr as $key => $_) {
212
            if (in_array($key, $exclude_arr)) {
213
                unset($arr[$key]);
214
            }
215
        }
216
217
        return $arr;
218
    }
219
    
220
    /**
221
    * This function takes a password as argument, salts it and returns the new password.
222
    *
223
    * @param string $password
224
    *
225
    * @return string
226
    */
227
    protected function saltPassword($password)
228
    {
229
        if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('saltedpasswords')) {
230
            $saltedpasswordsInstance = \TYPO3\CMS\Saltedpasswords\Salt\SaltFactory::getSaltingInstance(null, 'FE');
231
            $password = $saltedpasswordsInstance->getHashedPassword($password);
232
233
            if ($this->isValidMd5($password)) {
234
                $password = 'M' . $password;
235
            }
236
        }
237
238
        return $password;
239
    }
240
    
241
    /**
242
    * This function checks if a password is in md5 format.
243
    *
244
    * @param string $md5
245
    *
246
    * @return int
247
    */
248
    protected function isValidMd5($md5 = '')
249
    {
250
        return preg_match('/^[a-f0-9]{32}$/', $md5);
251
    }
252
253
    /**
254
     *
255
     */
256
    public function end()
257
    {
258
        parent::end();
259
    }
260
}
261