ImportMembersTask.php 7.98 KB
Newer Older
Thomas Löffler's avatar
Thomas Löffler committed
1
<?php
Stefan Busemann's avatar
Stefan Busemann committed
2

Sebastian Diez's avatar
Sebastian Diez committed
3
4
namespace T3o\T3oMembership\Task;

Stefan Busemann's avatar
Stefan Busemann committed
5
use Dropbox\Dropbox;
6
7
8
use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Log\LogManager;
Stefan Busemann's avatar
Stefan Busemann committed
9
use TYPO3\CMS\Core\Utility\GeneralUtility;
10
use TYPO3\CMS\Extbase\Scheduler\Task;
Thomas Löffler's avatar
Thomas Löffler committed
11

Thomas Löffler's avatar
Thomas Löffler committed
12
13
14
15
16
17
18
19
20
21
22
23
/**
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */
24
class ImportMembersTask extends Task
Thomas Löffler's avatar
Thomas Löffler committed
25
{
26
27
28
29
    /**
     * @var array
     */
    protected $hookObjects = array();
Thomas Löffler's avatar
Thomas Löffler committed
30
31
32
33

    /**
     * @var string
     */
Stefan Busemann's avatar
Stefan Busemann committed
34
35
36
37
38
39
    public $importFile = '';

    /**
     * @var string
     */
    public $dropboxToken = '';
Thomas Löffler's avatar
Thomas Löffler committed
40
41
42
43

    /**
     * @var integer
     */
Stefan Busemann's avatar
Stefan Busemann committed
44
    public $membershipStoragePid = 0;
Thomas Löffler's avatar
Thomas Löffler committed
45
46
47
48
49
50
51
52
53
54
55

    /**
     * @var array
     */
    protected $memberships = array();

    /**
     * @return boolean
     */
    public function execute()
    {
Sebastian Diez's avatar
Sebastian Diez committed
56
        /** @var $logger \TYPO3\CMS\Core\Log\Logger */
57
        $logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__);
Sebastian Diez's avatar
Sebastian Diez committed
58
59
        $logger->debug('Execute');

60
61
62
63
        $membershipRecords = $this->getDatabaseConnection()
            ->getConnectionForTable('tx_t3omembership_domain_model_membership')
            ->select(['uid', 'name'], 'tx_t3omembership_domain_model_membership')
            ->fetchAll();
Thomas Löffler's avatar
Thomas Löffler committed
64
65

        foreach ($membershipRecords as $membershipRecord) {
66
            $this->memberships[$membershipRecord['name']] = (int)$membershipRecord['uid'];
Thomas Löffler's avatar
Thomas Löffler committed
67
68
69
        }

        // does the import file exist?
70
        $importFile = $this->getImportFile();
Sebastian Diez's avatar
Sebastian Diez committed
71
72
        if (!GeneralUtility::isAbsPath($importFile)) {
            $importFile = GeneralUtility::getFileAbsFileName($importFile);
73
        }
Thomas Löffler's avatar
Thomas Löffler committed
74

75
        if (!file_exists($importFile)) {
Sebastian Diez's avatar
Sebastian Diez committed
76
            $logger->debug('No importfile', array('filename' => $importFile));
Stefan Busemann's avatar
Stefan Busemann committed
77

Thomas Löffler's avatar
Thomas Löffler committed
78
            return false;
79
80
        }

81
82
        $this->initializeHookObjects();

83
84
85
86
        $fileData = file($importFile);
        array_shift($fileData);
        foreach ($fileData as $key => $line) {
            $line = iconv('ISO-8859-15', 'UTF-8', $line);
87
            /** @noinspection PhpParamsInspection */
Sebastian Diez's avatar
Sebastian Diez committed
88
            $fields = GeneralUtility::trimExplode("\t", $line);
89
90
91
92
            $membershipUid = $this->getMembershipUid($fields[12]);
            // Skip records with unknown membership types.
            if (empty($membershipUid)) {
                continue;
Thomas Löffler's avatar
Thomas Löffler committed
93
            }
94
            $subscriptionNo = (int)$fields[14];
95

96
            $endDate = $this->getMemberEndDate($fields[15]);
97

98
99
            // If the user has cancelled his membership "Gekündigt", we set the endtime enable field.
            $endTime = !empty($fields[17]) ? $endDate : 0;
100
101

            $hidden = false;
102

103
104
105
            if ($endTime > 0 && $endTime < time()) {
                $hidden = true;
            }
106

107
            $member = array(
108
                'name' => $fields[6],
109
                'subscription_no' => $subscriptionNo,
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
                'external_id' => (int)$fields[0],
                'address' => $fields[7] !== '' ? $fields[7] : $fields[8],
                'zip' => $fields[10],
                'city' => $fields[11],
                'country' => $fields[13],
                'end_date' => $endDate,
                'endtime' => $endTime,
                'hidden' => $hidden,
                'starttime' => 0,
                'membership' => $membershipUid,
                'pid' => $this->membershipStoragePid,
                'crdate' => time(),
                'tstamp' => time(),
                'invoice_email' => $fields[84],
                'email' => $fields[79],
                'url' => $fields[80],
                'firstname' => $fields[82],
                'lastname' => $fields[83]
128
            );
129

130
131
            $memberUid = $this->createOrUpdateMember($subscriptionNo, $member);

Sebastian Diez's avatar
Sebastian Diez committed
132
            foreach ($this->hookObjects as $hookObject) {
133
134
135
136
                if (method_exists($hookObject, 'postUpdateMemberData')) {
                    $hookObject->postUpdateMemberData($memberUid, $member);
                }
            }
Thomas Löffler's avatar
Thomas Löffler committed
137
138
139
140
141
        }

        return true;
    }

142
143
144
145
    /**
     * Checks if the member with the given subscription number already exists in the database.
     * If he exists, his data will be updated, otherwise a new record will be inserted.
     *
Stefan Busemann's avatar
Stefan Busemann committed
146
     * @param int $subscriptionNo
147
     * @param array $memberData
148
     * @return int The uid of the updated / inserted member.
149
     */
150
    protected function createOrUpdateMember($subscriptionNo, array $memberData)
151
    {
152
153
154
155
156
157
158
159
160
161
        $queryBuilder = $this->getDatabaseConnection()
            ->getQueryBuilderForTable('tx_t3omembership_domain_model_member');

        $statement = $queryBuilder->select('uid')
            ->from('tx_t3omembership_domain_model_member')
            ->where(
                $queryBuilder->expr()->eq('subscription_no',
                    $queryBuilder->createNamedParameter($subscriptionNo, \PDO::PARAM_INT))
            )->execute();
        $existingMember = $statement->fetch();
162
163

        if (!empty($existingMember['uid'])) {
164
            $memberUid = $existingMember['uid'];
165
166
167
168
169
170

            $this->getDatabaseConnection()
                ->getConnectionForTable('tx_t3omembership_domain_model_member')
                ->update(
                    'tx_t3omembership_domain_model_member',
                    $memberData,
171
                    ['uid' => (int)$memberUid]
172
                );
173
        } else {
174
175
176
            $datebaseConnection = $this->getDatabaseConnection()
                ->getConnectionForTable('tx_t3omembership_domain_model_member');
            $datebaseConnection->insert(
177
178
179
                'tx_t3omembership_domain_model_member',
                $memberData
            );
180
            $memberUid = (int)$datebaseConnection->lastInsertId('tx_t3omembership_domain_model_member');
181
182
        }

183
        return (int)$memberUid;
184
185
    }

186
    /**
187
     * Parses the value of the "Beginn" column to a UNIX timestamp.
188
189
     *
     * @param string $endDate
190
     * @return int
191
     */
192
    protected function getMemberEndDate($endDate)
193
    {
194
        if (empty($endDate)) {
195
196
197
            return 0;
        }

198
        $endDateTime = \DateTime::createFromFormat('d.m.Y', $endDate);
199
        $endDateTime->setTime(0, 0, 0);
200

201
202
203
        return $endDateTime->getTimestamp();
    }

Thomas Löffler's avatar
Thomas Löffler committed
204
205
    /**
     * @param string $membershipName
206
     * @return integer|null
Thomas Löffler's avatar
Thomas Löffler committed
207
208
209
210
     */
    protected function getMembershipUid($membershipName)
    {
        $membershipName = trim(str_replace('Membership', '', $membershipName));
211
212
213
        if (empty($this->memberships[$membershipName])) {
            return null;
        }
Stefan Busemann's avatar
Stefan Busemann committed
214

Thomas Löffler's avatar
Thomas Löffler committed
215
216
217
218
219
220
221
222
223
224
        return $this->memberships[$membershipName];
    }

    /**
     * Gets importFile
     *
     * @return string
     */
    public function getImportFile()
    {
Stefan Busemann's avatar
Stefan Busemann committed
225
226
        $dropbox = new Dropbox($this->dropboxToken);
        $dropbox->files->download('/TYPO3 Backoffice/Member-Lists/memberlist.txt', $this->importFile);
Thomas Löffler's avatar
Thomas Löffler committed
227

Stefan Busemann's avatar
Stefan Busemann committed
228
        return $this->importFile;
Thomas Löffler's avatar
Thomas Löffler committed
229
230
231
    }


232
233
234
235
236
    /**
     * Instantiates all configured hook objects.
     */
    protected function initializeHookObjects()
    {
Sebastian Diez's avatar
Sebastian Diez committed
237
        if (!is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['t3omembership']['importMemberTaksHooks'])) {
238
239
            return;
        }
Sebastian Diez's avatar
Sebastian Diez committed
240
241
        foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['t3omembership']['importMemberTaksHooks'] as $classData) {
            $hookObject = GeneralUtility::getUserObj($classData);
242
            if (!is_object($hookObject)) {
243
                throw new \UnexpectedValueException( // @TODO Namespace?
Sebastian Diez's avatar
Sebastian Diez committed
244
                    'The hook object class ' . $classData . ' could not be instantiated.'
245
246
247
248
249
250
                );
            }
            $this->hookObjects[] = $hookObject;
        }
    }

Thomas Löffler's avatar
Thomas Löffler committed
251
    /**
252
     * @return \TYPO3\CMS\Core\Database\ConnectionPool
Thomas Löffler's avatar
Thomas Löffler committed
253
254
255
     */
    protected function getDatabaseConnection()
    {
256
        return GeneralUtility::makeInstance(ConnectionPool::class);
Thomas Löffler's avatar
Thomas Löffler committed
257
    }
Stefan Busemann's avatar
Stefan Busemann committed
258
}