batch_tools.php 6.59 KB
Newer Older
1
2
<?php

3
4
5
6
7
8
/**
* 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.
*
*/
9
10
11
12
13

/**
 * @brief API to manage batchs
 *
 * @file
14
 * @author <dev@maarch.org>
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
 * @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);
        }
45
        Bt_writeLog(['level' => 'ERROR', 'message' => $message]);
46
47
        Bt_logInDataBase($GLOBALS['totalProcessedResources'], 1, $message.' (return code: '. $returnCode.')');
    } elseif ($message <> '') {
48
        Bt_writeLog(['level' => 'INFO', 'message' => $message]);
49
50
51
52
53
54
55
56
57
58
59
60
61
62
        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='')
{
63
64
65
66
67
68
69
    \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
    ]);
70
71
}

72
73
74
75
76
77

/**
* Insert in the database a line for history
*/
function Bt_history($aArgs = [])
{
78
79
80
81
82
83
    $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'],
84
        'userId'       => $user[0]['id'],
85
86
        'info'         => $aArgs['info']
    ]);
87
88
}

89
90
91
92
93
94
95
/**
 * Get the batch if of the batch
 *
 * @return nothing
 */
function Bt_getWorkBatch()
{
96
97
98
99
100
    $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]);
101
102
103
104
105
106
107
108
109
110
111
        $GLOBALS['wb'] = 1;
    }
}

/**
 * Update the database with the new batch id of the batch
 *
 * @return nothing
 */
function Bt_updateWorkBatch()
{
112
    \Parameter\models\ParameterModel::update(['id' => $GLOBALS['batchName']."_id", 'param_value_int' => $GLOBALS['wb']]);
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
}

/**
 * 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);
    }
}

130
131
132
133
134
135
136
137
138
139
140
141
142
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']
    ]);
}

143
function Bt_createNote($aArgs = [])
144
{
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
    if (!empty($aArgs['notes'])) {
        foreach ($aArgs['notes'] as $note) {
            if (!empty(trim($note['content']))) {
                $creatorName = '';
                if (!empty($note['creatorId'])) {
                    $creatorId = $note['creatorId'];
                } else {
                    $users = \User\models\UserModel::get(['select' => ['id'], 'orderBy' => ["user_id='superadmin' desc"], 'limit' => 1]);
                    $creatorId = $users[0]['id'];
                }
                if (!empty($note['creatorName'])) {
                    $creatorName = $note['creatorName'] . ' (Maarch Parapheur) : ';
                }
                \Note\models\NoteModel::create([
                    'resId'     => $aArgs['resId'],
                    'user_id'   => $creatorId,
                    'note_text' => $creatorName . $note['content'],
                ]);
            }
164
        }
Nathan Cheval's avatar
Nathan Cheval committed
165
    }
166
}
Nathan Cheval's avatar
Nathan Cheval committed
167

168
169
function Bt_createAttachment($args = [])
{
170
    $opts = [
171
        CURLOPT_URL => rtrim($GLOBALS['applicationUrl'], "/") . '/rest/attachments',
172
173
        CURLOPT_HTTPHEADER => [
            'accept:application/json',
174
175
            'content-type:application/json',
            'Authorization: Basic ' . base64_encode($GLOBALS['userWS']. ':' .$GLOBALS['passwordWS']),
176
177
        ],
        CURLOPT_RETURNTRANSFER => true,
178
        CURLOPT_SSL_VERIFYPEER => false,
179
        CURLOPT_POSTFIELDS => json_encode($args),
180
181
182
183
184
185
        CURLOPT_POST => true
    ];

    $curl = curl_init();
    curl_setopt_array($curl, $opts);
    $rawResponse = curl_exec($curl);
186
    $error       = curl_error($curl);
187
188
189
190
191
192
193
    
    $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    if ($code == 404) {
        Bt_writeLog(['level' => 'ERROR', 'message' => 'maarchUrl is not correct']);
        exit;
    }

Florian Azizian's avatar
Florian Azizian committed
194
    if (!empty($error)) {
195
        Bt_writeLog(['level' => 'ERROR', 'message' => $error]);
Florian Azizian's avatar
Florian Azizian committed
196
197
        exit;
    }
198

199
200
    $return = json_decode($rawResponse, true);
    if (!empty($return['errors'])) {
201
        Bt_writeLog(['level' => 'ERROR', 'message' => $return['errors']]);
202
        exit;
203
    }
204

205
    return $return;
206
}
207

208
209
function Bt_validatedMail($aArgs = [])
{
210
211
212
213
214
215
216
    $attachments = \Attachment\models\AttachmentModel::get(['select' => ['count(1)'], 'where' => ['res_id_master = ?', 'status = ?'], 'data' => [$aArgs['resId'], 'FRZ']]);
    if ($attachments[0]['count'] == 0) {
        \Resource\models\ResModel::update([
            'set'     => ['status' => $aArgs['status']],
            'where'   => ['res_id = ?'],
            'data'    => [$aArgs['resId']]
        ]);
217
218
    }
}