0) { MGENIUS_Settings::set_notification_emails([]); } MGENIUS_Main::unlock('subscribers'); } else { self::$busy = true; } MGENIUS_Main::unlock('notify'); return $count; } /** * Adds entries to the queue. Called under the sending lock. * * An address is skipped only when it is still waiting in the queue: one * already written to (or given back after a failure) is queued again. * * @param array $entries Subscriber entries ({email, date, ip_hash}). * @param string $by Origin. * @return int Number of addresses waiting in the queue, 0 if it could not be saved. */ private static function enqueue($entries, $by) { $queue = self::raw_get(self::QUEUE, null); if (!is_array($queue) || !isset($queue['emails']) || !is_array($queue['emails'])) { $queue = ['emails' => [], 'by' => (string) $by, 'time' => time(), 'id' => wp_generate_password(12, false)]; } $queue['emails'] = array_values($queue['emails']); $pos = 0; $progress = self::raw_get(self::PROGRESS, null); if (is_array($progress) && isset($progress['id'], $queue['id']) && (string) $progress['id'] === (string) $queue['id']) { $pos = max(0, (int) $progress['pos']); } $known = []; foreach ($queue['emails'] as $index => $entry) { if ($index >= $pos && is_array($entry) && isset($entry['email'])) { $known[strtolower((string) $entry['email'])] = true; } } $added = 0; foreach ((array) $entries as $entry) { $email = is_array($entry) && isset($entry['email']) ? (string) $entry['email'] : ''; if ('' === $email || !is_email($email) || isset($known[strtolower($email)])) { continue; } $known[strtolower($email)] = true; $queue['emails'][] = $entry; $added++; } $waiting = max(0, count($queue['emails']) - $pos); if ($added > 0 && !self::raw_set(self::QUEUE, $queue)) { return 0; } return $waiting; } /** * A queue is waiting: makes sure WP-Cron will come back to it. */ private static function ensure_continuation() { if (!wp_next_scheduled('mgenius_notify_continue')) { wp_schedule_single_event(time() + 2 * MINUTE_IN_SECONDS, 'mgenius_notify_continue'); } } /** * Sends the next batch of the queue. * * v2.9.183 — nothing is sent while maintenance is on again (checked * before each email; the unsent addresses go back into the subscriber * list); WP-Cron is asked to come back before the first email and again * after each unfinished batch, so a request cut in the middle is * resumed; one batch per request; addresses that failed go back into the * list at the end of each batch; the lock is renewed while sending. * * @return array|null Null when nothing is waiting, another request is * sending, or maintenance is on again; else * ['sent', 'failed', 'remaining', 'done']. */ public static function process() { $queue = self::raw_get(self::QUEUE, null); if (!is_array($queue) || empty($queue['emails']) || !is_array($queue['emails'])) { return null; } if (self::$ran || !MGENIUS_Main::lock('notify')) { // Not this time: WP-Cron comes back to the queue. self::ensure_continuation(); return null; } // Read again under the lock: another request may have finished it. $queue = self::raw_get(self::QUEUE, null); if (!is_array($queue) || empty($queue['emails']) || !is_array($queue['emails'])) { MGENIUS_Main::unlock('notify'); return null; } self::$ran = true; $emails = array_values($queue['emails']); $total = count($emails); $queue_id = isset($queue['id']) ? (string) $queue['id'] : ''; $progress = self::raw_get(self::PROGRESS, null); // A progress line left by another queue does not apply to this one. if (!is_array($progress) || !isset($progress['id']) || (string) $progress['id'] !== $queue_id) { $progress = ['id' => $queue_id, 'pos' => 0, 'sent' => 0, 'failed' => [], 'failed_count' => 0]; } $progress['failed'] = isset($progress['failed']) && is_array($progress['failed']) ? $progress['failed'] : []; $pos = min($total, max(0, (int) $progress['pos'])); // Failures of a batch that was cut before its end. $progress = self::give_back_failed($emails, $progress); if (!empty($progress['failed'])) { // The list could not be written: nothing is lost, tried again later. self::ensure_continuation(); MGENIUS_Main::unlock('notify'); return null; } // Maintenance is on again: « now online » would be false. The // addresses not written to yet go back into the subscriber list. if (MGENIUS_Settings::stored_maintenance_state()) { self::stop_and_give_back($queue, $emails, $progress); MGENIUS_Main::unlock('notify'); return null; } // Scheduled before sending: a request cut in the middle is resumed. self::ensure_continuation(); $site_name = get_bloginfo('name'); /* translators: %s: site name */ $subject = sprintf(__('🎉 %s is now online!', '1001web-maintenance-launch-pages'), $site_name); $message = sprintf( /* translators: 1: site name, 2: site URL */ __("Hello,\n\nGreat news! The site %1\$s is now online.\n\nYou can visit it right now:\n%2\$s\n\nThank you for your patience!\n\n---\nThis email was sent automatically because you requested to be notified.", '1001web-maintenance-launch-pages'), $site_name, home_url() ); $headers = [ 'Content-Type: text/plain; charset=UTF-8', 'From: ' . $site_name . ' <' . get_option('admin_email') . '>', ]; $end = min($total, $pos + self::BATCH); $stopped = false; $lost = false; for ($i = $pos; $i < $end; $i++) { // Before each email: the lock is still ours (renewed, so a slow // mail server does not let another request start the same // batch), and maintenance has not come back on. if ($i > $pos) { if (!MGENIUS_Main::renew_lock('notify')) { $lost = true; break; } if (MGENIUS_Settings::stored_maintenance_state()) { $stopped = true; break; } } $email = isset($emails[$i]['email']) ? (string) $emails[$i]['email'] : ''; if ('' !== $email && is_email($email)) { $mailed = wp_mail($email, $subject, $message, $headers); // A mail server can hold one email for minutes: if the lock // was taken over meanwhile, the other request owns the // queue and nothing more is written from here. if (!MGENIUS_Main::renew_lock('notify')) { $lost = true; break; } if ($mailed) { $progress['sent']++; } else { $progress['failed'][] = $i; } } $progress['pos'] = $i + 1; // Saved after each email: a cut request does not send again. self::raw_set(self::PROGRESS, $progress); } if ($lost) { // Another request took the lock over: it carries on from the // saved position. Nothing more is written here. self::ensure_continuation(); MGENIUS_Main::unlock('notify'); return null; } $progress = self::give_back_failed($emails, $progress); if ($stopped) { self::stop_and_give_back($queue, $emails, $progress); MGENIUS_Main::unlock('notify'); return null; } if ($progress['pos'] < $total || !empty($progress['failed'])) { self::ensure_continuation(); MGENIUS_Main::unlock('notify'); return [ 'sent' => (int) $progress['sent'], 'failed' => (int) $progress['failed_count'], 'remaining' => $total - (int) $progress['pos'], 'done' => false, ]; } self::finish($queue, $progress, false); MGENIUS_Main::unlock('notify'); return [ 'sent' => (int) $progress['sent'], 'failed' => (int) $progress['failed_count'], 'remaining' => 0, 'done' => true, ]; } /** * Maintenance is on again: the addresses not written to yet go back into * the subscriber list and the queue ends. When the list cannot be * written, the queue is kept: nothing is lost, it is tried again later. * * @param array $queue Queue. * @param array $emails Queue entries. * @param array $progress Progress line. */ private static function stop_and_give_back($queue, $emails, $progress) { if (!empty($progress['failed']) || !self::give_back(array_slice($emails, (int) $progress['pos']))) { self::ensure_continuation(); return; } self::finish($queue, $progress, true); } /** * Plugin deactivated (or activated again with a queue left by a * deactivation made while a batch was going out): the addresses still * waiting go back into the list and the queue is removed. */ public static function abandon() { $queue = self::raw_get(self::QUEUE, null); if (!is_array($queue) || empty($queue['emails']) || !is_array($queue['emails'])) { return; } if (!MGENIUS_Main::lock('notify', 5)) { return; } // Read again under the lock: a batch may have finished in between, // and its subscribers, already written to, must not come back. $queue = self::raw_get(self::QUEUE, null); if (!is_array($queue) || empty($queue['emails']) || !is_array($queue['emails'])) { MGENIUS_Main::unlock('notify'); return; } $emails = array_values($queue['emails']); $progress = self::raw_get(self::PROGRESS, null); $same = is_array($progress) && isset($progress['id'], $queue['id']) && (string) $progress['id'] === (string) $queue['id']; $pos = $same ? max(0, (int) $progress['pos']) : 0; $back = array_slice($emails, $pos); if ($same && !empty($progress['failed']) && is_array($progress['failed'])) { foreach ($progress['failed'] as $index) { if (isset($emails[$index])) { $back[] = $emails[$index]; } } } if (self::give_back($back)) { self::raw_delete(self::QUEUE); self::raw_delete(self::PROGRESS); } MGENIUS_Main::unlock('notify'); } /** * Puts the addresses that failed back into the subscriber list and * counts them. Called under the sending lock. When the list cannot be * written, 'failed' is left as it is and tried again next time. * * @param array $emails Queue entries. * @param array $progress Progress line. * @return array Progress line, saved. */ private static function give_back_failed($emails, $progress) { if (empty($progress['failed'])) { return $progress; } $back = []; foreach ((array) $progress['failed'] as $index) { if (isset($emails[$index])) { $back[] = $emails[$index]; } } if (!self::give_back($back)) { return $progress; } $progress['failed_count'] = (int) (isset($progress['failed_count']) ? $progress['failed_count'] : 0) + count($back); $progress['failed'] = []; self::raw_set(self::PROGRESS, $progress); return $progress; } /** * Adds entries to the subscriber list (no duplicate address), under the * list lock. * * @param array $entries Subscriber entries. * @return bool False when the list could not be written. */ private static function give_back($entries) { if (empty($entries)) { return true; } if (!MGENIUS_Main::lock('subscribers', 3)) { return false; } $current = MGENIUS_Settings::get_notification_emails(); $known = []; foreach ($current as $entry) { if (is_array($entry) && isset($entry['email'])) { $known[strtolower((string) $entry['email'])] = true; } } foreach ((array) $entries as $entry) { $email = is_array($entry) && isset($entry['email']) ? strtolower((string) $entry['email']) : ''; if ('' !== $email && !isset($known[$email])) { $known[$email] = true; $current[] = $entry; } } $done = (bool) MGENIUS_Settings::set_notification_emails($current); MGENIUS_Main::unlock('subscribers'); return $done; } /** * End of a queue: result kept for the administrator, queue removed. * * @param array $queue Queue. * @param array $progress Progress line. * @param bool $stopped True when maintenance came back on before the end. */ private static function finish($queue, $progress, $stopped) { if ((int) $progress['sent'] > 0 || (int) $progress['failed_count'] > 0) { self::raw_set(self::RESULT, [ 'sent' => (int) $progress['sent'], 'failed' => (int) $progress['failed_count'], 'by' => isset($queue['by']) ? (string) $queue['by'] : 'manual', 'time' => time(), 'stopped' => $stopped ? 1 : 0, ]); } self::raw_delete(self::QUEUE); self::raw_delete(self::PROGRESS); wp_clear_scheduled_hook('mgenius_notify_continue'); } /** * v2.9.183 — « Clear list »: the addresses waiting to be written to are * removed as well. * * @return bool False when a batch is being sent right now. */ public static function clear_queue() { if (!MGENIUS_Main::lock('notify', 5)) { return false; } self::raw_delete(self::QUEUE); self::raw_delete(self::PROGRESS); wp_clear_scheduled_hook('mgenius_notify_continue'); MGENIUS_Main::unlock('notify'); return true; } /** * Administrator visit: continues a queue that WP-Cron did not finish. */ public static function maybe_continue() { if (wp_doing_ajax() || !current_user_can('manage_options')) { return; } if (null !== self::raw_get(self::QUEUE, null)) { self::process(); } } /** * Text for the administrator, from a process() result. * * @param array|null $result Result. * @return string Empty when there was nobody to notify. */ public static function result_message($result) { if (!is_array($result)) { return ''; } $sent = (int) $result['sent']; $failed = (int) $result['failed']; /* translators: %d: number of emails */ $text = sprintf(_n('Subscribers notified: %d email sent.', 'Subscribers notified: %d emails sent.', $sent, '1001web-maintenance-launch-pages'), $sent); if ($failed > 0) { /* translators: %d: number of emails */ $text .= ' ' . sprintf(_n('%d email could not be sent: that address was put back in the subscriber list.', '%d emails could not be sent: those addresses were put back in the subscriber list.', $failed, '1001web-maintenance-launch-pages'), $failed); } if (!empty($result['stopped'])) { $text .= ' ' . __('Sending stopped because maintenance was switched on again: the subscribers not written to yet are back in the list.', '1001web-maintenance-launch-pages'); } if (!empty($result['remaining'])) { /* translators: %d: number of emails */ $text .= ' ' . sprintf(_n('%d more email will be sent in the next few minutes.', '%d more emails will be sent in the next few minutes.', (int) $result['remaining'], '1001web-maintenance-launch-pages'), (int) $result['remaining']); } return $text; } /** * Last finished result, shown once to the administrator, then removed. * * @return string */ public static function take_result_message() { $result = self::raw_get(self::RESULT, null); if (!is_array($result)) { return ''; } self::raw_delete(self::RESULT); $result['remaining'] = 0; return self::result_message($result); } /** * Option read straight from the database (a persistent object cache may * still serve an old value). * * @param string $name Option name. * @param mixed $default Value when missing. * @return mixed */ public static function raw_get($name, $default = null) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Read-through bypassing a possibly stale object cache. $row = $wpdb->get_var($wpdb->prepare("SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1", $name)); return null === $row ? $default : maybe_unserialize($row); } /** * Option written straight to the database, autoload off, cache cleared. * * @param string $name Option name. * @param mixed $value Value. * @return bool */ public static function raw_set($name, $value) { global $wpdb; $serialized = maybe_serialize($value); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Direct write, object cache cleared below. $exists = $wpdb->get_var($wpdb->prepare("SELECT option_id FROM {$wpdb->options} WHERE option_name = %s LIMIT 1", $name)); if (null === $exists) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Direct insert, autoload off. $done = $wpdb->insert($wpdb->options, ['option_name' => $name, 'option_value' => $serialized, 'autoload' => 'no'], ['%s', '%s', '%s']); } else { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Direct update, object cache cleared below. $done = $wpdb->update($wpdb->options, ['option_value' => $serialized], ['option_name' => $name], ['%s'], ['%s']); } wp_cache_delete($name, 'options'); wp_cache_delete('alloptions', 'options'); wp_cache_delete('notoptions', 'options'); return false !== $done; } /** * @param string $name Option name. */ public static function raw_delete($name) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Direct delete, object cache cleared below. $wpdb->delete($wpdb->options, ['option_name' => $name], ['%s']); wp_cache_delete($name, 'options'); wp_cache_delete('alloptions', 'options'); wp_cache_delete('notoptions', 'options'); } }