Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of MailTest for Moodle - https://moodle.org/
3
//
4
// MailTest is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// MailTest is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with MailTest.  If not, see <https://www.gnu.org/licenses/>.
16
 
17
/**
18
 * Displays the form and processes the form submission.
19
 *
20
 * @package    local_mailtest
21
 * @copyright  2015-2024 TNG Consulting Inc. - www.tngconsulting.ca
22
 * @author     Michael Milette
23
 * @license    https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24
 */
25
 
26
// Include config.php.
27
require_once(__DIR__ . '/../../config.php');
28
require_once($CFG->libdir . '/adminlib.php');
29
 
30
// Include our function library.
31
$pluginname = 'mailtest';
32
require_once($CFG->dirroot . '/local/' . $pluginname . '/locallib.php');
33
 
34
// Globals.
35
global $CFG, $OUTPUT, $USER, $SITE, $PAGE;
36
 
37
// Ensure only administrators have access.
38
$homeurl = new moodle_url('/');
39
require_login();
40
if (!is_siteadmin()) {
41
    redirect($homeurl, "This feature is only available for site administrators.", 5);
42
}
43
 
44
// URL Parameters.
45
// There are none.
46
 
47
// Include form.
48
require_once(dirname(__FILE__) . '/classes/' . $pluginname . '_form.php');
49
 
50
// Heading ==========================================================.
51
 
52
$title = get_string('pluginname', 'local_' . $pluginname);
53
$heading = get_string('heading', 'local_' . $pluginname);
54
$url = new moodle_url('/local/' . $pluginname . '/');
55
if ($CFG->branch >= 25) { // Moodle 2.5+.
56
    $context = context_system::instance();
57
} else {
58
    $context = get_system_context();
59
}
60
 
61
$PAGE->set_pagelayout('admin');
62
$PAGE->set_url($url);
63
$PAGE->set_context($context);
64
$PAGE->set_title($title);
65
$PAGE->set_heading($heading);
66
admin_externalpage_setup('local_' . $pluginname); // Sets the navbar & expands navmenu.
67
 
68
// Setup the form.
69
 
70
$CFG->noreplyaddress = empty($CFG->noreplyaddress) ? 'noreply@' . get_host_from_url($CFG->wwwroot) : $CFG->noreplyaddress;
71
 
72
if (!empty($CFG->emailonlyfromnoreplyaddress) || $CFG->branch >= 32) { // Always send from no reply address.
73
    // Use primary administrator's name if support name has not been configured.
74
    $primaryadmin = get_admin();
75
    $CFG->supportname = empty($CFG->supportname) ? fullname($primaryadmin, true) : $CFG->supportname;
76
    // Use noreply address.
77
    $fromemail = local_mailtest_generate_email_user($CFG->noreplyaddress, format_string($CFG->supportname));
78
    $fromdefault = $CFG->noreplyaddress;
79
} else { // Otherwise defaults to send from primary admin user.
80
    $fromemail = get_admin();
81
    $fromdefault = $fromemail->email;
82
}
83
 
84
$form = new mailtest_form(null, ['fromdefault' => $fromdefault]);
85
if ($form->is_cancelled()) {
86
    redirect($homeurl);
87
}
88
 
89
echo $OUTPUT->header();
90
 
91
// Display or process the form. =====================================.
92
 
93
$data = $form->get_data();
94
if (!$data) { // Display the form.
95
    echo $OUTPUT->heading($heading);
96
 
97
    // Display a warning if Cron hasn't run in a while. =============.
98
 
99
    $cronwarning = '';
100
    if ($CFG->branch >= 37) {
101
        defined('MINSECS') || define('MINSECS', 200); // For pre-Moodle 3.9 compatibility.
102
        $lastcron = get_config('tool_task', 'lastcronstart');
103
        $cronoverdue = ($lastcron < time() - 3600 * 24);
104
        $check = $PAGE->get_renderer('core', 'admin');
105
        if ($cronoverdue) {
106
            $cronwarning .= $check->cron_overdue_warning($cronoverdue);
107
        }
108
 
109
        $lastcroninterval = get_config('tool_task', 'lastcroninterval');
110
        $expectedfrequency = $CFG->expectedcronfrequency ?? MINSECS;
111
        $croninfrequent = !$cronoverdue && ($lastcroninterval > ($expectedfrequency + MINSECS)
112
                || $lastcron < time() - $expectedfrequency);
113
        if ($croninfrequent) {
114
            $cronwarning .= $check->cron_infrequent_warning($croninfrequent);
115
        }
116
    } else { // Up to and including Moodle 3.6.
117
        if ($CFG->branch >= 27) { // Moodle 2.7+.
118
            $sql = 'SELECT MAX(lastruntime) FROM {task_scheduled}';
119
        } else {
120
            $sql = 'SELECT MAX(lastcron) FROM {modules}';
121
        }
122
        $lastcron = $DB->get_field_sql($sql);
123
        $cronoverdue = ($lastcron < time() - 3600 * 24);
124
        if ($cronoverdue) { // Cron is overdue.
125
            if (empty($CFG->cronclionly)) {
126
                // Determine build link to run cron.
127
                $cronurl = new moodle_url('/admin/cron.php');
128
                if (!empty($CFG->cronremotepassword)) {
129
                    $cronurl = new moodle_url('/admin/cron.php', ['password' => $CFG->cronremotepassword]);
130
                }
131
                $cronwarning .= get_string('cronwarning', 'admin', $cronurl->out());
132
            } else {
133
                $cronwarning .= get_string('cronwarningcli', 'admin');
134
            }
135
        }
136
    }
137
 
138
    if ($cronoverdue) { // Cron is overdue.
139
        $msg = '';
140
        $msg .= '<h3 class="alert-heading">' . get_string('warning') . '</h3>';
141
        $msg .= $cronwarning;
142
        $msg .= '<p>' . get_string('cron_help', 'admin');
143
        if (!empty($CFG->branch)) {
144
            $icon = $OUTPUT->pix_icon('help', get_string('moreinfo'));
145
            $link = $CFG->docroot . '/' . $CFG->branch . '/' . substr(current_language(), 0, 2) . '/Cron';
146
            $msg .= html_writer::link($link, $icon, ['class' => 'helplink', 'target' => '_blank', 'rel' => 'external']);
147
        }
148
        $msg .= '</p>';
149
        $msg .= '<button type="button" class="close" data-dismiss="alert" aria-label="' . get_string('closebuttontitle') . '">'
150
                . '<span aria-hidden="true">&times;</span></button>';
151
        local_mailtest_msgbox($msg, null, 3, 'alert alert-danger alert-block alert-dismissible fade show');
152
    }
153
 
154
    // Display the form. ============================================.
155
 
156
    $form->display();
157
} else {
158
    // Send test email.
159
    if (!isset($data->sender)) {
160
        $data->sender = $CFG->noreplyaddress;
161
    }
162
    $fromemail = local_mailtest_generate_email_user($data->sender);
163
 
164
    if ($CFG->branch >= 26) {
165
        $toemail = core_text::strtolower($data->recipient);
166
    } else {
167
        $toemail = textlib::strtolower($data->recipient);
168
    }
169
    if ($toemail !== clean_param($toemail, PARAM_EMAIL)) {
170
        local_mailtest_msgbox(get_string('invalidemail'), get_string('error'), 2, 'errorbox', $url->out());
171
    }
172
    $toemail = local_mailtest_generate_email_user($toemail, '');
173
    if (email_should_be_diverted($toemail->email)) {
174
        $toemail->email = $toemail->email . ' <strong>(' .
175
                get_string('divertedto', 'local_' . $pluginname, $CFG->divertallemailsto) . ')</strong>';
176
    }
177
 
178
    $subject = format_string($SITE->fullname, true, ['escape' => false]);
179
 
180
    // Add some system information.
181
    $a = new stdClass();
182
    if (isloggedin()) {
183
        $a->regstatus = get_string('registered', 'local_' . $pluginname, $USER->username);
184
    } else {
185
        $a->regstatus = get_string('notregistered', 'local_' . $pluginname);
186
    }
187
    $a->lang = current_language();
188
    $a->browser = $_SERVER['HTTP_USER_AGENT'];
189
    $a->referer = $_SERVER['HTTP_REFERER'];
190
    $a->release = $CFG->release;
191
    $a->ip = local_mailtest_getuserip();
192
    $messagehtml = get_string('message', 'local_' . $pluginname, $a);
193
    $messagetext = html_to_text($messagehtml);
194
 
195
    ob_end_flush();
196
    ob_implicit_flush(true);
197
    echo '<h2 class="alert-heading">' . get_string('testing', 'local_' . $pluginname) . '</h2>';
198
    echo '<p>' . get_string('from') . ' : ' . $fromemail->email . '<br>
199
        &#129095; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &#129095; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &#129095;<br>
200
        ' . get_string('server', 'local_' . $pluginname, (empty($CFG->smtphosts) ? 'PHPMailer' : $CFG->smtphosts)) . '<br>
201
        &#129095; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &#129095; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &#129095;<br>
202
        ' . get_string('to') . ' : ' . $toemail->email . '</p>';
203
    ob_implicit_flush(false);
204
 
205
    // Manage Moodle SMTP debugging display.
206
    $debuglevel = $CFG->debug;
207
    $debugdisplay = $CFG->debugdisplay;
208
    $debugsmtp = isset($CFG->debugsmtp) && $CFG->debugsmtp;
209
    $showlog = !empty($data->alwaysshowlog) || ($debugdisplay && $debugsmtp);
210
    // Set debug level to a minimum of NORMAL: Show errors, warnings and notices.
211
    if ($CFG->debug < 15) {
212
        $CFG->debug = 15;
213
    }
214
    $CFG->debugdisplay = true;
215
    $CFG->debugsmtp = true;
216
    if (empty($CFG->smtphosts)) {
217
        $success = email_to_user($toemail, $fromemail, $subject, $messagetext, $messagehtml, '', '', true, $fromemail->email);
218
        $smtplog = get_string('nologavailable', 'local_' . $pluginname);
219
        if (!empty($phplog = ini_get('mail.log'))) {
220
            if ($phplog == 'syslog' && strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
221
                $smtplog .= '<pre>mail.log : ' . get_string('winsyslog', 'local_' . $pluginname) . '</pre>';
222
            } else {
223
                $smtplog .= '<pre>mail.log : ' . $phplog . '</pre>';
224
            }
225
        }
226
    } else {
227
        ob_start();
228
        $success = email_to_user($toemail, $fromemail, $subject, $messagetext, $messagehtml, '', '', true, $fromemail->email);
229
        $smtplog = ob_get_contents();
230
        ob_end_clean();
231
        $smtplog = '<figure class="border border-dark p-2">' . $smtplog . '</figure>';
232
    }
233
 
234
    $CFG->debug = $debuglevel;
235
    $CFG->debugdisplay = $debugdisplay;
236
    $CFG->debugsmtp = $debugsmtp;
237
 
238
    if ($success) { // Success.
239
        $title = get_string('success');
240
        $msg = '<p>';
241
        if (empty($CFG->smtphosts)) {
242
            $msg .= get_string('sentmailphp', 'local_' . $pluginname);
243
        } else {
244
            $msg .= get_string('sentmail', 'local_' . $pluginname);
245
        }
246
 
247
        // Display a list of common reasons the email may not have been delivered.
248
        if (empty($CFG->smtphosts)) {
249
            $extrainfo = '<li>' . get_string('failphpmailerconfig', 'local_' . $pluginname) . '</li>';
250
        } else {
251
            $extrainfo = '';
252
        }
253
        $msg .= ' ' . get_string('commondeliveryissues', 'local_' . $pluginname, $extrainfo);
254
 
255
        local_mailtest_msgbox($msg, $title, 2, 'infobox', $url->out());
256
        if ($showlog) {
257
            // Display debugging info if settings were already on before the test or user wants to force display.
258
            echo $smtplog;
259
        }
260
    } else if (!empty($CFG->smtphosts)) {
261
        // Failed to deliver message using SMTP.
262
        $errtype = 'errorunknown';
263
 
264
        // Diagnose failed SMTP connection issues.
265
 
266
        $issues = '';
267
        if (strpos($smtplog, '220') === false) { // Missing 220 code, connection failed.
268
            $errtype = 'errorcommunications';
269
 
270
            // Check for domain, security protocol and port issues for each specified mail server.
271
            $hosts = explode(';', $CFG->smtphosts);
272
            foreach ($hosts as $host) {
273
                if (empty($host)) {
274
                    continue; // Skip if blank.
275
                }
276
 
277
                // Split the host and the port.
278
                $host = explode(':', $host . ':25'); // Set default port to 25 in case none was specified.
279
                [$host, $port] = $host;
280
                $port = (int)$port;
281
 
282
                // Check for DNS record lookup failure. Skip if host is an IP address.
283
                if (
284
                    filter_var($host, FILTER_VALIDATE_IP) === false // Not an IP address.
285
                    && empty(@dns_get_record($host)) // The address does not have a DNS record.
286
                    && gethostbyname($host) == $host
287
                ) { // Address does not resolve to an IP address (e.g. localhost).
288
                        $issues .= '<li>' . get_string('faildnslookup', 'local_' . $pluginname, $host) . '</li>';
289
                        break;
290
                }
291
 
292
                // If using SSL or TLS, port is not usually 25.
293
                if ($port == 25 && !empty($CFG->smtpsecure)) {
294
                    // No port or port 25 was specified for a SSL/TLS connection.
295
                    $issues .= '<li>' . get_string('failmissingport', 'local_' . $pluginname, $CFG->smtpsecure) . '</li>';
296
                }
297
 
298
                // Port is not 25 but a secure protocol was not specified.
299
                if ($port != 25 && empty($CFG->smtpsecure)) {
300
                    // Non default port specified for a non SSL/TLS connection.
301
                    $issues .= '<li>';
302
                    $issues .= get_string('failmissingprotocol', 'local_' . $pluginname, $port);
303
                    $issues .= '</li>';
304
                }
305
 
306
                // The port and protocol don't match. Although it can, the SSL port is rarely 587, and TLS is rarely 465.
307
                if ($port == 587 && $CFG->smtpsecure == 'ssl' || $port == 465 && $CFG->smtpsecure == 'tls') {
308
                    $issues .= '<li>' . get_string(
309
                        'failprotocolmismatch',
310
                        'local_' . $pluginname,
311
                        ['port' => $port, 'protocol' => $CFG->smtpsecure]
312
                    ) . '</li>';
313
                }
314
 
315
                // Connection timeout issues.
316
                $fp = @fsockopen($host, $port, $errno, $errstr, 10);
317
                if (!$fp) {
318
                    if (stripos($errstr, 'Connection timed out') !== false) {
319
                        // Connection timed out due to possible issues such as ISP blocking outbound SMTP connections.
320
                        $issues .= '<li>' . get_string('failoutboundsmtpblocked', 'local_' . $pluginname) . '</li>';
321
                    } else {
322
                        // Server's port was closed.
323
                        $issues .= '<li>' . get_string('failclosedport', 'local_' . $pluginname, $port) . '</li>';
324
                    }
325
                    // Add a list common issues.
326
                    $issues .= get_string('commoncommissues', 'local_' . $pluginname);
327
                    break;
328
                } else {
329
                    fclose($fp);
330
                }
331
            }
332
        } else if (strpos($smtplog, '250') === false) { // No 250 code.
333
            // No or very limited communication between Moodle and the SMTP server.
334
            $errtype = 'errorcommunications';
335
            $issues .= get_string('failaccessdenied', 'local_' . $pluginname);
336
        } else {
337
            // SMTP mail server refused the email.
338
            $errtype = 'errorsend';
339
 
340
            // Diagnose possible authentication issues.
341
 
342
            // Invalid credentials - username and/or password are incorrect.
343
            if (strpos($smtplog, '530') !== false || strpos($smtplog, '535') !== false || strpos($smtplog, '235') === false) {
344
                $issues .= get_string('failcredentials', 'local_' . $pluginname);
345
            }
346
 
347
            // No-reply address is probably fake or contains a typo.
348
            // Your mail server requires a real email address with a real mailbox.
349
            if (strpos($smtplog, '550') !== false) {
350
                $issues .= get_string('failunknownmailbox', 'local_' . $pluginname);
351
            }
352
        }
353
        $smtplog = '<h4>' . get_string('connectionlog', 'local_' . $pluginname) . '</h4>' . $smtplog;
354
 
355
        $continuelink = ($CFG->branch >= 32) ? 'outgoingmailconfig' : 'messagesettingemail';
356
        $msg = get_string($errtype, 'local_' . $pluginname, '../../admin/settings.php?section=' . $continuelink);
357
 
358
        // Display diagnostic information, if available.
359
        if (!empty($issues)) {
360
            $title = get_string('additionalinfo', 'local_' . $pluginname);
361
            $msg .= '<p>' . $title . '</p><ul>' . $issues . '</ul>' . $smtplog;
362
        }
363
 
364
        // Also display the results of the dialogue between Moodle and the SMTP server.
365
        local_mailtest_msgbox($msg, get_string('emailfail', 'local_' . $pluginname), 3, 'errorbox', $url->out());
366
    } else {
367
        // Failed to send message using PHPMailer.
368
        $title = get_string('emailfail', 'local_' . $pluginname);
369
        $msg = get_string('failphpmailer', 'local_' . $pluginname);
370
        local_mailtest_msgbox($msg, $title, 3, 'errorbox', $url->out());
371
    }
372
}
373
 
374
// Footing  =========================================================.
375
 
376
echo $OUTPUT->footer();