batch_tools.php 13.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
<?php

/**
* Copyright Maarch since 2008 under licence GPLv3.
* See LICENCE.txt file at the root folder for more details.
* This file is part of Maarch software.
*
*/

/**
 * @brief API to manage batchs
 *
 * @file
 * @author <dev@maarch.org>
 * @date $date$
 * @version $Revision$
 */

/**
 * Exit the batch with a return code, message in the log and
 * in the database if necessary
 *
 * @param int $returnCode code to exit (if > O error)
 * @param string $message message to the log and the DB
 * @return nothing exit the program
 */
function Bt_exitBatch($returnCode, $message='')
{
    if (file_exists($GLOBALS['lckFile'])) {
        unlink($GLOBALS['lckFile']);
    }
    if ($returnCode > 0) {
        $GLOBALS['totalProcessedResources']--;
        if ($GLOBALS['totalProcessedResources'] == -1) {
            $GLOBALS['totalProcessedResources'] = 0;
        }
        if ($returnCode < 100) {
            if (file_exists($GLOBALS['errorLckFile'])) {
                unlink($GLOBALS['errorLckFile']);
            }
            $semaphore = fopen($GLOBALS['errorLckFile'], "a");
            fwrite($semaphore, '1');
            fclose($semaphore);
        }
        Bt_writeLog(['level' => 'ERROR', 'message' => $message]);
        Bt_logInDataBase($GLOBALS['totalProcessedResources'], 1, $message.' (return code: '. $returnCode.')');
    } elseif ($message <> '') {
        Bt_writeLog(['level' => 'INFO', 'message' => $message]);
        Bt_logInDataBase($GLOBALS['totalProcessedResources'], 0, $message.' (return code: '. $returnCode.')');
    }
    Bt_updateWorkBatch();
    exit($returnCode);
}

/**
* Insert in the database the report of the batch
* @param long $totalProcessed total of resources processed in the batch
* @param long $totalErrors total of errors in the batch
* @param string $info message in db
*/
function Bt_logInDataBase($totalProcessed=0, $totalErrors=0, $info='')
{
    \History\models\BatchHistoryModel::create([
        'module_name'     => $GLOBALS['batchName'],
        'batch_id'        => $GLOBALS['wb'],
        'info'            => substr(str_replace('\\', '\\\\', str_replace("'", "`", $info)), 0, 999),
        'total_processed' => $totalProcessed,
        'total_errors'    => $totalErrors
    ]);
}


/**
* Insert in the database a line for history
*/
function Bt_history($aArgs = [])
{
    $user = \User\models\UserModel::get(['select' => ['id'], 'orderBy' => ["user_id='superadmin' desc"], 'limit' => 1]);
    \History\controllers\HistoryController::add([
        'tableName'    => $aArgs['table_name'],
        'recordId'     => $aArgs['record_id'],
        'eventType'    => $aArgs['event_type'],
        'eventId'      => $aArgs['event_id'],
        'userId'       => $user[0]['id'],
        'info'         => $aArgs['info']
    ]);
}

/**
 * Get the batch if of the batch
 *
 * @return nothing
 */
function Bt_getWorkBatch()
{
    $parameter = \Parameter\models\ParameterModel::getById(['select' => ['param_value_int'], 'id' => $GLOBALS['batchName']."_id"]);
    if (!empty($parameter)) {
        $GLOBALS['wb'] = $parameter['param_value_int'] + 1;
    } else {
        \Parameter\models\ParameterModel::create(['id' => $GLOBALS['batchName']."_id", 'param_value_int' => 1]);
        $GLOBALS['wb'] = 1;
    }
}

/**
 * Update the database with the new batch id of the batch
 *
 * @return nothing
 */
function Bt_updateWorkBatch()
{
    \Parameter\models\ParameterModel::update(['id' => $GLOBALS['batchName']."_id", 'param_value_int' => $GLOBALS['wb']]);
}

/**
 * Include the file requested if exists
 *
 * @param string $file path of the file to include
 * @return nothing
 */
function Bt_myInclude($file)
{
    if (file_exists($file)) {
        include_once($file);
    } else {
        throw new IncludeFileError($file);
    }
}

function Bt_writeLog($args = [])
{
    \SrcCore\controllers\LogsController::add([
        'isTech'    => true,
        'moduleId'  => $GLOBALS['batchName'],
        'level'     => $args['level'],
        'tableName' => '',
        'recordId'  => $GLOBALS['batchName'],
        'eventType' => $GLOBALS['batchName'],
        'eventId'   => $args['message']
    ]);
}

function Bt_getReply($args = [])
{
    $refEncode = str_replace('.', '%2E', urlencode($args['reference']));
146
    $curlResponse = \SrcCore\models\CurlModel::exec([
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
        'url'     => rtrim($GLOBALS['urlSAEService'], '/') . '/medona/message/reference?reference=' . $refEncode,
        'method'  => 'GET',
        'cookie'  => 'LAABS-AUTH=' . urlencode($GLOBALS['token']),
        'headers' => [
            'Accept: application/json',
            'Content-Type: application/json',
            'User-Agent: ' . $GLOBALS['userAgent']
        ]
    ]);

    if (!empty($curlResponse['errors'])) {
        return ['errors' => 'Error returned by the route /organization/organization/Search : ' . $curlResponse['errors']];
    } elseif ($curlResponse['code'] != 200) {
        return ['errors' => 'Error returned by the route /organization/organization/Search : ' . $curlResponse['response']['message']];
    }

163
    if (!in_array($curlResponse['response']['status'], ['rejected', 'processed'])) {
164
165
166
167
168
        return [];
    }

    $messageId = $curlResponse['response']['replyMessage']['messageId'];

169
    $curlResponse = \SrcCore\models\CurlModel::exec([
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
        'url'     => rtrim($GLOBALS['urlSAEService'], '/') . '/medona/message/'.urlencode($messageId).'/Export',
        'method'  => 'GET',
        'cookie'  => 'LAABS-AUTH=' . urlencode($GLOBALS['token']),
        'headers' => [
            'Accept: application/zip',
            'Content-Type: application/json',
            'User-Agent: ' . $GLOBALS['userAgent']
        ]
    ]);

    if (!empty($curlResponse['errors'])) {
        return ['errors' => 'Error returned by the route /medona/message/{messageId}/Export : ' . $curlResponse['errors']];
    } elseif ($curlResponse['code'] != 200) {
        return ['errors' => 'Error returned by the route /medona/message/{messageId}/Export : ' . $curlResponse['response']['message']];
    }

186
    $reply = \ExportSeda\controllers\ExportSEDATrait::getXmlFromZipMessage([
187
188
189
        'encodedZipDocument' => base64_encode($curlResponse['response']),
        'messageId'          => $messageId
    ]);
190
191
    if (!empty($reply['errors'])) {
        return ['errors' => 'Error during getXmlFromZipMessage process : ' . $reply['errors']];
192
193
    }

194
    return ['encodedReply' => $reply['encodedDocument'], 'xmlContent' => $reply['xmlContent']];
195
}
196
197
198
199
200
201
202
203

function Bt_purgeAll($args = [])
{
    if (!empty($args['resources'])) {
        $resources = \SrcCore\models\DatabaseModel::select([
            'select'    => ['d.path_template', 'r.path', 'r.filename'],
            'table'     => ['res_letterbox r', 'docservers d'],
            'left_join' => ['r.docserver_id = d.docserver_id'],
204
            'where'     => ['res_id in (?)', 'filename is not null'],
205
206
207
208
209
210
211
212
213
214
            'data'      => [$args['resources']]
        ]);
        foreach ($resources as $resource) {
            $pathToDocument = $resource['path_template'] . str_replace('#', DIRECTORY_SEPARATOR, $resource['path']) . $resource['filename'];
            if (is_file($pathToDocument)) {
                unlink($pathToDocument);
            }
        }
    
        $resources = \SrcCore\models\DatabaseModel::select([
215
            'select'    => ['d.path_template', 'r.path', 'r.filename', 'r.res_id'],
216
217
            'table'     => ['res_attachments r', 'docservers d'],
            'left_join' => ['r.docserver_id = d.docserver_id'],
218
            'where'     => ['res_id_master in (?)', 'filename is not null'],
219
220
            'data'      => [$args['resources']]
        ]);
221
        $attachmentIds = array_column($resources, 'res_id');
222
223
224
225
226
227
228
229
        foreach ($resources as $resource) {
            $pathToDocument = $resource['path_template'] . str_replace('#', DIRECTORY_SEPARATOR, $resource['path']) . $resource['filename'];
            if (is_file($pathToDocument)) {
                unlink($pathToDocument);
            }
        }
    
        $resources = \SrcCore\models\DatabaseModel::select([
230
            'select'    => ['d.path_template', 'adr.path', 'adr.filename'],
231
            'table'     => ['adr_letterbox adr', 'docservers d'],
232
            'left_join' => ['adr.docserver_id = d.docserver_id'],
233
234
235
236
237
238
239
240
241
242
            'where'     => ['res_id in (?)'],
            'data'      => [$args['resources']]
        ]);
        foreach ($resources as $resource) {
            $pathToDocument = $resource['path_template'] . str_replace('#', DIRECTORY_SEPARATOR, $resource['path']) . $resource['filename'];
            if (is_file($pathToDocument)) {
                unlink($pathToDocument);
            }
        }
    
243
244
245
246
247
248
249
250
251
252
253
254
255
        if (!empty($attachmentIds)) {
            $resources = \SrcCore\models\DatabaseModel::select([
                'select'    => ['d.path_template', 'adr.path', 'adr.filename'],
                'table'     => ['adr_attachments adr', 'docservers d'],
                'left_join' => ['adr.docserver_id = d.docserver_id'],
                'where'     => ['res_id in (?)'],
                'data'      => [$attachmentIds]
            ]);
            foreach ($resources as $resource) {
                $pathToDocument = $resource['path_template'] . str_replace('#', DIRECTORY_SEPARATOR, $resource['path']) . $resource['filename'];
                if (is_file($pathToDocument)) {
                    unlink($pathToDocument);
                }
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
            }
        }
    
        \SrcCore\models\DatabaseModel::delete([
            'table' => 'adr_letterbox',
            'where' => ['res_id in (?)'],
            'data'  => [$args['resources']]
        ]);
        \SrcCore\models\DatabaseModel::delete([
            'table' => 'acknowledgement_receipts',
            'where' => ['res_id in (?)'],
            'data'  => [$args['resources']]
        ]);
        \SrcCore\models\DatabaseModel::delete([
            'table' => 'listinstance',
            'where' => ['res_id in (?)'],
            'data'  => [$args['resources']]
        ]);
        \SrcCore\models\DatabaseModel::delete([
            'table' => 'listinstance_history',
            'where' => ['res_id in (?)'],
            'data'  => [$args['resources']]
        ]);
        \SrcCore\models\DatabaseModel::delete([
            'table' => 'listinstance_history_details',
            'where' => ['res_id in (?)'],
            'data'  => [$args['resources']]
        ]);
        \SrcCore\models\DatabaseModel::delete([
            'table' => 'registered_mail_resources',
            'where' => ['res_id in (?)'],
            'data'  => [$args['resources']]
        ]);
        \SrcCore\models\DatabaseModel::delete([
            'table' => 'res_letterbox',
            'where' => ['res_id in (?)'],
            'data'  => [$args['resources']]
        ]);
        \SrcCore\models\DatabaseModel::delete([
            'table' => 'res_mark_as_read',
            'where' => ['res_id in (?)'],
            'data'  => [$args['resources']]
        ]);
        \SrcCore\models\DatabaseModel::delete([
            'table' => 'resource_contacts',
            'where' => ['res_id in (?)'],
            'data'  => [$args['resources']]
        ]);
        \SrcCore\models\DatabaseModel::delete([
            'table' => 'resources_folders',
            'where' => ['res_id in (?)'],
            'data'  => [$args['resources']]
        ]);
        \SrcCore\models\DatabaseModel::delete([
            'table' => 'resources_tags',
            'where' => ['res_id in (?)'],
            'data'  => [$args['resources']]
        ]);
        \SrcCore\models\DatabaseModel::delete([
            'table' => 'unit_identifier',
            'where' => ['res_id in (?)'],
            'data'  => [$args['resources']]
        ]);
        \SrcCore\models\DatabaseModel::delete([
            'table' => 'users_followed_resources',
            'where' => ['res_id in (?)'],
            'data'  => [$args['resources']]
        ]);
        \SrcCore\models\DatabaseModel::delete([
            'table' => 'message_exchange',
            'where' => ['res_id_master in (?)'],
            'data'  => [$args['resources']]
        ]);
        \SrcCore\models\DatabaseModel::delete([
            'table' => 'res_attachments',
            'where' => ['res_id_master in (?)'],
            'data'  => [$args['resources']]
        ]);
        \SrcCore\models\DatabaseModel::delete([
            'table' => 'shippings',
336
337
338
339
340
341
342
            'where' => ['document_id in (?)', 'document_type = ?'],
            'data'  => [$args['resources'], 'resource']
        ]);
        \SrcCore\models\DatabaseModel::delete([
            'table' => 'shippings',
            'where' => ['document_id in (select res_id from res_attachments where res_id_master in (?))', 'document_type = ?'],
            'data'  => [$args['resources'], 'attachment']
343
344
345
346
347
348
349
350
351
352
353
        ]);
        \SrcCore\models\DatabaseModel::delete([
            'table' => 'notes',
            'where' => ['identifier in (?)'],
            'data'  => [$args['resources']]
        ]);
        \SrcCore\models\DatabaseModel::delete([
            'table' => 'note_entities',
            'where' => ['note_id in (select id from notes where identifier in (?))'],
            'data'  => [$args['resources']]
        ]);
354
355
356
357
358
359
360
361
362

        $linkedResources = implode("' - '", $args['resources']);
        \SrcCore\models\DatabaseModel::update([
            'table'     => 'res_letterbox',
            'postSet'   => ['linked_resources' => "linked_resources - '{$linkedResources}'"],
            'where'     => ['linked_resources != ?'],
            'data'      => ['[]']
        ]);

363
364
365
366
367
368
369
        \SrcCore\models\DatabaseModel::delete([
            'table' => 'adr_attachments',
            'where' => ['res_id in (select res_id from res_attachments where res_id_master in (?))'],
            'data'  => [$args['resources']]
        ]);
        \SrcCore\models\DatabaseModel::delete([
            'table' => 'emails',
370
371
            'where' => ['document->>\'id\' in (?)'],
            'data'  => [$args['resources']]
372
373
374
        ]);
    }
}