Current path: home/webdevt/www/cryptoimpot.fr/wp-content/plugins/divi-contact-form-helper/app/Admin/Cron/
?? Go up: /home/webdevt/www/cryptoimpot.fr/wp-content/plugins/divi-contact-form-helper/app/Admin
<?php
namespace KS_PAC_DCFH\Admin\Cron;
use WP_Query;
use ZipArchive;
if (!defined('ABSPATH')) {
exit;
}
class Entries_Auto_Backup
{
private $email_to;
private $hook;
private $recurrence;
public function init(): void
{
if (ks_pac_dcfh_db()::is_setting_enabled('pwh_dcfh_backup_enabled')) {
$this->email_to = ks_pac_dcfh_db()::get_setting('pwh_dcfh_backup_email');
$schedule = ks_pac_dcfh_db()::get_setting('pwh_dcfh_backup_schedule');
$this->hook = 'dcfh_entries_backup_'.$schedule;
$this->recurrence = $schedule;
add_action('init', [$this, 'maybe_schedule_event']);
add_action($this->hook, [$this, 'maybe_process_cron']);
add_action('wp_mail_failed', [$this, 'maybe_log_error'], 999);
}
}
public function maybe_schedule_event(): void
{
if (!wp_next_scheduled($this->hook)) {
wp_schedule_event(time(), $this->recurrence, $this->hook);
}
}
public function maybe_process_cron(): void
{
$zipFileDir = $this->create_backup();
if ($zipFileDir !== false && !empty($zipFileDir['path']) && !empty($zipFileDir['url'])) {
$subject = wp_strip_all_tags(apply_filters('pwh_dcfh_f_auto_backup_email_subject', __('Divi Contact Form Entries Backup', 'divi-contact-form-helper')));
$heading = wp_strip_all_tags(apply_filters('pwh_dcfh_f_auto_backup_email_heading', __('Contact Form Entries Backup Completed', 'divi-contact-form-helper')));
$headers = ['Content-Type: text/html; charset=UTF-8'];
$file_path = $zipFileDir['path'];
$message = strtr($this->get_message_tpl(), [
'%%site_title%%' => get_bloginfo('name'),
'%%heading%%' => $heading,
'%%filename%%' => basename($file_path),
'%%filesize%%' => size_format(filesize($file_path)),
'%%date%%' => date_i18n('l, F j, Y \a\t g:i A'),
'%%download%%' => esc_url($zipFileDir['url']),
]);
/*$from_email = 'noreply@localhost.com';
$remote_address = sanitize_text_field($_SERVER['REMOTE_ADDR'] ?? '');
if (!in_array($remote_address, ['127.0.0.1', '::1'])) {
$from_email = wp_parse_url(get_bloginfo('url'), PHP_URL_HOST);
}
add_filter('wp_mail_from', static function ($wp_mail) use ($from_email) {
return $from_email;
}, PHP_INT_MAX);*/
if (wp_mail($this->email_to, $subject, $message, $headers, [$file_path])) {
$log_msg = [
'sent' => true,
'datetime' => current_time('mysql'),
'message' => __('Email sent successfully with attachment.', 'divi-contact-form-helper'),
];
} else {
$log_msg = [
'sent' => false,
'datetime' => current_time('mysql'),
'message' => get_option('pwh_dcfh_auto_backup_mail_failed'),
];
}
if (file_exists($file_path)) {
wp_delete_file($file_path);
}
$this->log_message($log_msg);
}
}
public function maybe_log_error($wp_error): void
{
if (empty($wp_error)) {
return;
}
$error_data = $wp_error->get_error_data();
$subject = $error_data['subject'];
if (strtolower($subject) !== 'divi contact form helper backup') {
return;
}
update_option('pwh_dcfh_auto_backup_mail_failed', $wp_error->get_error_message(), 'no');
}
private function create_backup()
{
if (!class_exists('ZipArchive')) {
$message = [
'sent' => false,
'datetime' => current_time('mysql'),
'message' => __('PHP needs to have the zip extension installed. If you are using cpanel you may have zip extension installed but not activated. You need to activate it. Please contact your hosting provider to activate it.', 'divi-contact-form-helper'),
];
$this->log_message($message);
return false;
}
$contact_forms = ks_pac_dcfh_db()::get_contact_forms_list();
if (!empty($contact_forms)) {
$wp_upload_dir = wp_upload_dir();
$upload_path = $wp_upload_dir['basedir'];
$upload_url = $wp_upload_dir['baseurl'];
$zip_file_name = 'divi-contact-form-helper-backup-'.time().'.zip';
$zip_file_dir = wp_normalize_path($upload_path.DIRECTORY_SEPARATOR.$zip_file_name);
$zip_file_url = wp_normalize_path($upload_url.DIRECTORY_SEPARATOR.$zip_file_name);
$zip = new ZipArchive();
$total_files_zipped = 0;
foreach ($contact_forms as $contact_form) {
$contact_form_id = $contact_form['unique_id'];
$contact_form_title = sanitize_file_name($contact_form['title']); // Sanitize file name
$csv_file_name = $contact_form_title.'.csv';
$csv_file_dir = wp_normalize_path($upload_path.DIRECTORY_SEPARATOR.$csv_file_name);
if (false === ($f_handle = fopen($csv_file_dir, 'wb'))) { // phpcs:ignore
$message = [
'sent' => false,
'datetime' => current_time('mysql'),
'message' => __('Backup needs to create a CSV file. Server is not allowed to create file.', 'divi-contact-form-helper'),
];
$this->log_message($message);
continue; // Skip to the next contact form
}
fwrite($f_handle, chr(0xEF).chr(0xBB).chr(0xBF)); // phpcs:ignore
$total_posts_obj = new WP_Query([
'post_type' => 'pwh_dcfh',
'post_status' => 'any',
'meta_key' => '_pwh_dcfh_contact_form_id', // phpcs:ignore
'meta_value' => $contact_form_id // phpcs:ignore
]);
$total_posts = $total_posts_obj->found_posts;
$posts_per_page = 200;
$counter = 0;
$form_data = [];
$csv_headers = [];
$csv_rows = [];
for ($i = 0; $i < ceil($total_posts / $posts_per_page); ++$i) {
$post_obj = new WP_Query([
'post_type' => 'pwh_dcfh',
'post_status' => 'any',
'posts_per_page' => $posts_per_page,
'offset' => $i * $posts_per_page,
'meta_key' => '_pwh_dcfh_contact_form_id', // phpcs:ignore
'meta_value' => $contact_form_id // phpcs:ignore
]);
foreach ($post_obj->posts as $post) {
$counter++;
$post_id = $post->ID;
$post_excerpt = $post->post_excerpt;
if (is_serialized($post_excerpt)) {
$page_id = ks_pac_dcfh_post_meta()::get_page_id_meta_value($post_id);
$form_entries = ks_pac_dcfh_general_helper()::maybe_unserialize($post_excerpt);
if (!empty($form_entries) && is_array($form_entries)) {
foreach ($form_entries as $form_entry) {
$field_id = $form_entry['id'];
$field_label = $form_entry['label'];
$field_type = $form_entry['type'];
$form_data[$contact_form_id][$field_id] = $field_id;
$csv_headers[$contact_form_id][$field_id] = $field_label;
$wp_subdir = $form_entry['subdir'] ?? '';
$wp_basedir = rtrim($wp_upload_dir['basedir'], '/').'/'.$wp_subdir;
$wp_baseurl = rtrim($wp_upload_dir['baseurl'], '/').'/'.$wp_subdir;
if ('file' === $field_type || 'signature_pad' === $field_type) {
$attachments = array_filter(explode(',', $form_entry['value']));
if (!empty($attachments)) {
$attachments_list = [];
foreach ($attachments as $attachment) {
if (!empty($form_entry['is_media_library'])) {
$upload_dir = path_join($wp_basedir, $attachment);
$upload_url = path_join($wp_baseurl, $attachment);
} else {
$upload_dir = ks_pac_dcfh_file_helper()::get_form_upload_dir($contact_form_id, $wp_subdir, $attachment);
$upload_url = ks_pac_dcfh_file_helper()::get_form_upload_url($contact_form_id, $wp_subdir, $attachment);
}
if (et_()->WPFS()->is_file($upload_dir) && et_()->WPFS()->exists($upload_dir)) {
$attachments_list[] = $upload_url;
}
}
$csv_rows[$contact_form_id][$counter][$field_id] = implode(',', $attachments_list);
}
} else {
$csv_rows[$contact_form_id][$counter][$field_id] = !empty($form_entry['value']) ? $form_entry['value'] : '-';
}
}
$csv_rows[$contact_form_id][$counter] = array_merge($csv_rows[$contact_form_id][$counter], [
'entry_number' => $post_id,
'read_by' => '0000-00-00 00:00:00' !== $post->post_modified ? ks_pac_dcfh_wp_helper()::get_author_name(ks_pac_dcfh_post_meta()::get_read_by_meta_value($post_id)) : '-',
'submitter' => ks_pac_dcfh_wp_helper()::get_submitter_name($post->post_author),
'page_title' => get_the_title($page_id),
'page_url' => get_the_permalink($page_id),
'entry_date' => ks_pac_dcfh_wp_helper()::datetime($post->post_date),
'ip_address' => !empty(ks_pac_dcfh_post_meta()::get_ip_address_meta_value($post_id)) ? ks_pac_dcfh_post_meta()::get_ip_address_meta_value($post_id) : '-',
'browser' => isset($user_agent_meta['browser']) ? ucfirst($user_agent_meta['browser']) : null,
'platform' => isset($user_agent_meta['platform']) ? ucfirst($user_agent_meta['platform']) : null,
]);
}
}
}
}
if (!empty($csv_rows)) {
$form_data[$contact_form_id] = wp_parse_args(array_keys(ks_pac_dcfh_constant()::form_placeholders()), $form_data[$contact_form_id]);
$csv_headers[$contact_form_id] = wp_parse_args(array_values(ks_pac_dcfh_constant()::form_placeholders()), array_values($csv_headers[$contact_form_id]));
fputcsv($f_handle, $csv_headers[$contact_form_id], ',', '"');
foreach ($csv_rows[$contact_form_id] as $value) {
$csv_row_data = [];
foreach ($form_data[$contact_form_id] as $header) {
$csv_row_data[] = $value[$header] ?? '-';
}
fputcsv($f_handle, $csv_row_data, ',', '"');
}
$csv_footer = [
["path" => "\n\n"],
["path" => __("Total Entries: ".$total_posts, 'divi-contact-form-helper')],
["path" => __("Generated on: ".date_i18n("F j, Y, g:i a"), 'divi-contact-form-helper')],
["path" => __("Auto Generated", 'divi-contact-form-helper')],
];
foreach ($csv_footer as $footer) {
fputcsv($f_handle, $footer, ',', '"');
}
fclose($f_handle); // phpcs:ignore
// Zipped CSV
if ($zip->open($zip_file_dir, ZipArchive::CREATE)) {
$zip->addFile($csv_file_dir, $csv_file_name);
@$zip->close(); // phpcs:ignore
if (file_exists($csv_file_dir)) {
wp_delete_file($csv_file_dir);
$total_files_zipped++;
}
}
}
}
if ($total_files_zipped > 0) {
return ['path' => $zip_file_dir, 'url' => $zip_file_url, 'total_files' => $total_files_zipped];
}
}
return false;
}
private function get_message_tpl(): string
{
ob_start();
?>
<div style="margin: 0; padding: 30px; font-family: Arial, sans-serif; background-color: #f7f7f7;">
<div style="max-width: 500px; margin: 0 auto; background: #ffffff; border: 1px solid #dcdcdc; padding: 30px;">
<!-- Heading -->
<h2 style="margin-top: 0; color: #2c3e50; font-size: 24px; font-weight: 600;">%%heading%%</h2>
<!-- Greeting with dynamic site title -->
<p style="font-size: 16px; color: #34495e;">Dear %%site_title%% Admin,</p>
<!-- Introduction text -->
<p style="font-size: 16px; color: #34495e;">
The automatic backup of your contact form entries has been completed successfully. Please find the
backup file attached for your reference.
</p>
<!-- Backup details -->
<div style="margin: 20px 0; padding: 20px; background-color: #f8f8f8; border-radius: 8px;">
<p style="margin: 8px 0; font-size: 14px; color: #34495e;"><strong>File:</strong> %%filename%%</p>
<p style="margin: 8px 0; font-size: 14px; color: #34495e;"><strong>Size:</strong> %%filesize%%</p>
<p style="margin: 8px 0; font-size: 14px; color: #34495e;"><strong>Created:</strong> %%date%%</p>
</div>
<!-- Final message and footer -->
<p style="font-size: 12px; color: #7f8c8d; text-align: center; margin-top: 40px;">
This is an automated notification. Please do not reply directly to this email.
</p>
</div>
</div>
<?php
return ob_get_clean();
}
private function log_message(array $message): void
{
update_option('pwh_dcfh_entries_auto_backup_status', $message, 'no');
}
}