process_email_stack.php 8.56 KB
Newer Older
Giovannoni Laurent's avatar
Giovannoni Laurent committed
1
2
<?php

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
$options = getopt("c:n:", ["config:", "notif:"]);

controlOptions($options);

$txt = '';
foreach (array_keys($options) as $key) {
    if (isset($options[$key]) && $options[$key] == false) {
        $txt .= $key . '=false,';
    } else {
        $txt .= $key . '=' . $options[$key] . ',';
    }
}
printf("{$txt}\n");

if (!is_file($options['config'])) {
    printf("Configuration file does not exist\n");
    exit();
}

$file = file_get_contents($options['config']);
$file = json_decode($file, true);

$customID   = $file['config']['customID'] ?? null;
$maarchUrl  = $file['config']['maarchUrl'];

chdir($file['config']['maarchDirectory']);

require 'vendor/autoload.php';


\SrcCore\models\DatabasePDO::reset();
new \SrcCore\models\DatabasePDO(['customId' => $customID]);

$GLOBALS['lckFile'] = "{$file['config']['maarchDirectory']}/bin/notification/{$customID}process_email_stack.lck";

$lockFile = @fopen($GLOBALS['lckFile'], 'x');
if (!$lockFile) {
    writeLog(['message' => "An instance of process_email_stack is already in progress", 'level' => 'INFO']);
    exit();
}
fwrite($lockFile, '1');
fclose($lockFile);


setBatchNumber();

49
50
51
52
53
54
55
56
$language = \SrcCore\models\CoreConfigModel::getLanguage();

if (file_exists("custom/{$customID}/src/core/lang/lang-{$language}.php")) {
    require_once("custom/{$customID}/src/core/lang/lang-{$language}.php");
}
require_once("src/core/lang/lang-{$language}.php");

\User\controllers\UserController::setAbsences();
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

//=========================================================================================================================================
//FIRST STEP
$emails = \Notification\models\NotificationsEmailsModel::get(['select' => ['*'], 'where' => ['exec_date is NULL']]);
$totalEmailsToProcess = count($emails);
if ($totalEmailsToProcess === 0) {
    writeLog(['message' => "No notifications to send", 'level' => 'INFO']);
    unlink($GLOBALS['lckFile']);
    exit();
}
$emailsInError = 0;
writeLog(['message' => "{$totalEmailsToProcess} notification(s) to send", 'level' => 'INFO']);


//=========================================================================================================================================
//SECOND STEP
$configuration = \Configuration\models\ConfigurationModel::getByPrivilege(['privilege' => 'admin_email_server', 'select' => ['value']]);
$configuration = json_decode($configuration['value'], true);
foreach ($emails as $key => $email) {
    if (empty($configuration)) {
        writeLog(['message' => "Configuration admin_email_server is missing", 'level' => 'INFO', 'history' => true]);
        unlink($GLOBALS['lckFile']);
        exit();
    }

    $phpmailer = new \PHPMailer\PHPMailer\PHPMailer();
    $phpmailer->setFrom($configuration['from'], $configuration['from']);
    if (in_array($configuration['type'], ['smtp', 'mail'])) {
        if ($configuration['type'] == 'smtp') {
            $phpmailer->isSMTP();
        } elseif ($configuration['type'] == 'mail') {
            $phpmailer->isMail();
        }

        $phpmailer->Host = $configuration['host'];
        $phpmailer->Port = $configuration['port'];
        $phpmailer->SMTPAutoTLS = false;
        if (!empty($configuration['secure'])) {
            $phpmailer->SMTPSecure = $configuration['secure'];
        }
        $phpmailer->SMTPAuth = $configuration['auth'];
        if ($configuration['auth']) {
            $phpmailer->Username = $configuration['user'];
            if (!empty($configuration['password'])) {
                $phpmailer->Password = \SrcCore\models\PasswordModel::decrypt(['cryptedPassword' => $configuration['password']]);
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
146
147
148
149
        }
    } elseif ($configuration['type'] == 'sendmail') {
        $phpmailer->isSendmail();
    } elseif ($configuration['type'] == 'qmail') {
        $phpmailer->isQmail();
    }

    $phpmailer->CharSet = $configuration['charset'];

    $phpmailer->addAddress($email['recipient']);

    $phpmailer->isHTML(true);

    $email['html_body'] = str_replace('#and#', '&', $email['html_body']);
    $email['html_body'] = str_replace("\''", "'", $email['html_body']);
    $email['html_body'] = str_replace("\'", "'", $email['html_body']);
    $email['html_body'] = str_replace("''", "'", $email['html_body']);

    $dom = new \DOMDocument();
    $internalErrors = libxml_use_internal_errors(true);
    $dom->loadHTML($email['html_body'], LIBXML_NOWARNING);
    libxml_use_internal_errors($internalErrors);
    $images = $dom->getElementsByTagName('img');

    foreach ($images as $imageKey => $image) {
        $originalSrc = $image->getAttribute('src');
        if (preg_match('/^data:image\/(\w+);base64,/', $originalSrc)) {
            $encodedImage = substr($originalSrc, strpos($originalSrc, ',') + 1);
            $imageFormat = substr($originalSrc, 11, strpos($originalSrc, ';') - 11);
            $phpmailer->addStringEmbeddedImage(base64_decode($encodedImage), "embeded{$key}", "embeded{$key}.{$imageFormat}");
            $email['html_body'] = str_replace($originalSrc, "cid:embeded{$key}", $email['html_body']);
        }
    }

    $phpmailer->Subject = $email['subject'];
    $phpmailer->Body = $email['html_body'];
    if (empty($email['html_body'])) {
        $phpmailer->AllowEmpty = true;
    }

    if (!empty($email['attachments'])) {
        $attachments = explode(',', $email['attachments']);
        foreach ($attachments as $num => $attachment) {
            if (is_file($attachment)) {
                $ext  = strrchr($attachment, '.');
                $name = str_pad(($num + 1), 4, '0', STR_PAD_LEFT) . $ext;
                $phpmailer->addStringAttachment(file_get_contents($attachment), $name);
150
            }
151
        }
152
    }
Giovannoni Laurent's avatar
Giovannoni Laurent committed
153

154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
    $phpmailer->Timeout = 30;
    $phpmailer->SMTPDebug = 1;
    $phpmailer->Debugoutput = function ($str) {
        if (strpos($str, 'SMTP ERROR') !== false) {
            $user = \User\models\UserModel::get(['select' => ['id'], 'orderBy' => ["user_id='superadmin' desc"], 'limit' => 1]);
            \History\controllers\HistoryController::add([
                'tableName'    => 'emails',
                'recordId'     => 'email',
                'eventType'    => 'ERROR',
                'eventId'      => 'sendEmail',
                'userId'       => $user[0]['id'],
                'info'         => $str
            ]);
        }
    };

    $isSent = $phpmailer->send();
    if ($isSent) {
        writeLog(['message' => "Notification sent", 'level' => 'INFO']);
        $result = 'SENT';
    } else {
        writeLog(['message' => "SENDING EMAIL ERROR ! ({$phpmailer->ErrorInfo})", 'level' => 'ERROR', 'history' => true]);

        $emailsInError++;
        $errTxt = ' (Last Error : '.$phpmailer->ErrorInfo.')';
        $result = 'FAILED';
    }

    \Notification\models\NotificationsEmailsModel::update([
        'set'   => ['exec_date' => 'CURRENT_TIMESTAMP', 'exec_result' => $result],
        'where' => ['email_stack_sid = ?'],
        'data'  => [$email['email_stack_sid']]
    ]);
}
Alex ORLUC's avatar
Alex ORLUC committed
188

189
190
191
192
193
$emailsSent = $totalEmailsToProcess - $emailsInError;
if (!empty($emailsInError)) {
    writeLog(['message' => "{$emailsInError}/{$totalEmailsToProcess} notification(s) in error", 'level' => 'ERROR', 'history' => true]);
}
writeLog(['message' => "{$emailsSent} notification(s) sent, end of process", 'level' => 'INFO']);
Florian Azizian's avatar
Florian Azizian committed
194

195
unlink($GLOBALS['lckFile']);
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
updateBatchNumber();


function controlOptions(array &$options)
{
    if (empty($options['c']) && empty($options['config'])) {
        printf("Configuration file missing\n");
        exit();
    } elseif (!empty($options['c']) && empty($options['config'])) {
        $options['config'] = $options['c'];
        unset($options['c']);
    }
}

function setBatchNumber()
{
    $parameter = \Parameter\models\ParameterModel::getById(['select' => ['param_value_int'], 'id' => "process_email_stack_id"]);
    if (!empty($parameter)) {
        $GLOBALS['wb'] = $parameter['param_value_int'] + 1;
    } else {
        \Parameter\models\ParameterModel::create(['id' => 'process_email_stack_id', 'param_value_int' => 1]);
        $GLOBALS['wb'] = 1;
    }
}

function updateBatchNumber()
{
    \Parameter\models\ParameterModel::update(['id' => 'process_email_stack_id', 'param_value_int' => $GLOBALS['wb']]);
}

function writeLog(array $args)
{
    \SrcCore\controllers\LogsController::add([
        'isTech'    => true,
        'moduleId'  => 'Notification',
        'level'     => $args['level'] ?? 'INFO',
        'tableName' => '',
        'recordId'  => 'processEmailStack',
        'eventType' => 'Notification',
        'eventId'   => $args['message']
    ]);

    if (!empty($args['history'])) {
        \History\models\BatchHistoryModel::create(['info' => $args['message'], 'module_name' => 'Notification']);
    }
}