Completed
Pull Request — master (#12)
by
unknown
20:54
created

InsertUpdateTable::salt_password()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 15
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
        if ($this->getConfiguration()["salt_password"] == 1) {
155
            $field_values["password"] = $this->salt_password($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
        if ($this->getConfiguration()["salt_password"] == 1) {
187
            $tmp_arr['password'] = $this->salt_password($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 salt_password($password)
228
    {       
229
        if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('saltedpasswords')) {
230
          // @see tx_saltedpasswords_Tasks_BulkUpdate::updatePasswords()
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
231
          $saltedpasswordsInstance = \TYPO3\CMS\Saltedpasswords\Salt\SaltFactory::getSaltingInstance(NULL, 'FE');
232
233
          $password = $saltedpasswordsInstance->getHashedPassword($password);
234
          
235
          if ($this->isValidMd5($password)) {
236
            $password = 'M' . $password;
237
          }
238
        }
239
240
        return $password;
241
    }
242
    
243
    /**
244
    * This function checks if a password is in md5 format.
245
    *
246
    * @param string $md5
247
    *
248
    * @return int
249
    */
250
    protected function isValidMd5($md5 ='')
251
    {
252
        return preg_match('/^[a-f0-9]{32}$/', $md5);
253
    }
254
255
    /**
256
     *
257
     */
258
    public function end()
259
    {
260
        parent::end();
261
    }
262
}