|
Server : Apache/2.4.18 (Ubuntu) System : Linux canvaswebdesign 3.13.0-71-generic #114-Ubuntu SMP Tue Dec 1 02:34:22 UTC 2015 x86_64 User : oppastar ( 1041) PHP Version : 7.0.33-0ubuntu0.16.04.15 Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority, Directory : /var/www/laciasmara.com/public_html/shop/application/libraries/ |
Upload File : |
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
class Phpmailer_lib
{
private $CI;
private $mailer;
private $smtp_config;
private $default_settings;
public function __construct()
{
$this->CI = &get_instance();
// Load SMTP configuration
$this->load_smtp_config();
// Initialize PHPMailer
$this->init_phpmailer();
}
private function load_smtp_config()
{
$this->CI->load->config('email');
$config = $this->CI->config->item('smtp_settings');
// Default settings
$this->default_settings = [
'smtp_host' => $config['host'] ?? 'smtp.mailgun.org',
'smtp_port' => $config['port'] ?? 465,
'smtp_username' => $config['username'] ?? 'postmaster@mg.laciasmara.com',
'smtp_password' => $config['password'],
'smtp_encryption' => $config['encryption'],
'from_name' => $config['from_name'],
'from_email' => $config['from_email'],
'emails_per_hour' => $config['emails_per_hour']
];
$this->smtp_config = $this->default_settings;
}
private function init_phpmailer()
{
require_once APPPATH . 'third_party/phpmailer/src/Exception.php';
require_once APPPATH . 'third_party/phpmailer/src/PHPMailer.php';
require_once APPPATH . 'third_party/phpmailer/src/SMTP.php';
$this->mailer = new PHPMailer(true);
try {
// Server settings
$this->mailer->isSMTP();
$this->mailer->Host = $this->smtp_config['smtp_host'];
$this->mailer->SMTPAuth = !empty($this->smtp_config['smtp_username']);
$this->mailer->Username = $this->smtp_config['smtp_username'];
$this->mailer->Password = $this->smtp_config['smtp_password'];
// Encryption
if ($this->smtp_config['smtp_encryption'] === 'ssl') {
$this->mailer->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
} elseif ($this->smtp_config['smtp_encryption'] === 'tls') {
$this->mailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
}
$this->mailer->Port = (int)$this->smtp_config['smtp_port'];
// Default sender
$this->mailer->setFrom(
$this->smtp_config['from_email'],
$this->smtp_config['from_name']
);
// Additional settings
$this->mailer->isHTML(true);
$this->mailer->CharSet = 'UTF-8';
} catch (Exception $e) {
log_message('error', 'PHPMailer initialization failed: ' . $e->getMessage());
throw new Exception('Email configuration error: ' . $e->getMessage());
}
}
/**
* Send single email
*
* @param array $email_data Array containing email details
* @return array Result with status and message
*/
public function send_single($email_data)
{
try {
// Validate required fields
$required = ['to_email', 'subject', 'body'];
foreach ($required as $field) {
if (empty($email_data[$field])) {
throw new Exception("Missing required field: $field");
}
}
// Clear previous recipients
$this->mailer->clearAddresses();
$this->mailer->clearAttachments();
$this->mailer->clearCustomHeaders();
// Set sender (override default if provided)
if (!empty($email_data['from_email'])) {
$this->mailer->setFrom(
$email_data['from_email'],
$email_data['from_name'] ?? $this->smtp_config['from_name']
);
}
if (!$this->validate_email($email_data['to_email'])) {
throw new Exception("Invalid email address: " . $email_data['to_email']);
}
// Set recipient
$this->mailer->addAddress($email_data['to_email'], $email_data['to_name'] ?? '');
// Set reply-to
if (!empty($email_data['reply_to'])) {
$this->mailer->addReplyTo($email_data['reply_to']);
}
// Set subject and body
$this->mailer->Subject = $email_data['subject'];
$this->mailer->Body = $email_data['body'];
// Set plain text alternative if provided
if (!empty($email_data['alt_body'])) {
$this->mailer->AltBody = $email_data['alt_body'];
}
// Add tracking pixel if tracking_id provided
if (!empty($email_data['tracking_id'])) {
$this->mailer->Body = $this->add_tracking_pixel($email_data['body'], $email_data['tracking_id']);
}
// Process click tracking links
if (!empty($email_data['tracking_id'])) {
$this->mailer->Body = $this->process_tracking_links($this->mailer->Body, $email_data['tracking_id']);
}
// Send email
$sent = $this->mailer->send();
if ($sent) {
return [
'status' => 'success',
'message' => 'Email sent successfully'
];
} else {
return [
'status' => 'failed',
'message' => 'Failed to send email'
];
}
} catch (Exception $e) {
log_message('error', 'Email sending failed: ' . $e->getMessage());
return [
'status' => 'failed',
'message' => $e->getMessage()
];
}
}
/**
* Send bulk emails with rate limiting
*
* @param int $campaign_id Campaign ID
* @param array $recipients Array of recipients
* @param string $template_content Email template content
* @param array $campaign_data Campaign data (subject, from, etc)
* @return array Summary of sending results
*/
public function send_bulk($campaign_id, $recipients, $template_content, $campaign_data)
{
$results = [
'total' => count($recipients),
'sent' => 0,
'failed' => 0,
'errors' => []
];
// Rate limiting
$emails_per_hour = (int)$this->smtp_config['emails_per_hour'];
$delay_seconds = 3600 / $emails_per_hour; // Delay between emails
foreach ($recipients as $recipient) {
try {
// Process template with recipient data
$personalized_content = $this->process_template($template_content, $recipient);
$personalized_subject = $this->process_template($campaign_data['subject'], $recipient);
// Generate tracking ID
$tracking_id = $this->generate_tracking_id($campaign_id, $recipient['id']);
// Prepare email data
$email_data = [
'to_email' => $recipient['email'],
'to_name' => trim(($recipient['first_name'] ?? '') . ' ' . ($recipient['last_name'] ?? '')),
'subject' => $personalized_subject,
'body' => $personalized_content,
'from_email' => $campaign_data['from_email'],
'from_name' => $campaign_data['from_name'],
'reply_to' => $campaign_data['reply_to'] ?? null,
'tracking_id' => $tracking_id
];
// Send email
$result = $this->send_single($email_data);
// Log result
$log_status = $result['status'] === 'success' ? 'sent' : 'failed';
$this->CI->Campaign_email_log_m->insert([
'campaign_id' => $campaign_id,
'subscriber_id' => $recipient['id'],
'email' => $recipient['email'],
'status' => $log_status,
'error_message' => $result['status'] === 'failed' ? $result['message'] : null,
'tracking_id' => $tracking_id,
'sent_at' => $result['status'] === 'success' ? date('Y-m-d H:i:s') : null
]);
if ($result['status'] === 'success') {
$results['sent']++;
} else {
$results['failed']++;
$results['errors'][] = $recipient['email'] . ': ' . $result['message'];
}
// Rate limiting delay
if ($delay_seconds > 0) {
usleep($delay_seconds * 1000000);
}
} catch (Exception $e) {
$results['failed']++;
$results['errors'][] = $recipient['email'] . ': ' . $e->getMessage();
log_message('error', 'Bulk email error for ' . $recipient['email'] . ': ' . $e->getMessage());
}
}
return $results;
}
/**
* Process template variables ({{variable}} replacement)
*
* @param string $template Template content
* @param array $data Data for replacement
* @return string Processed template
*/
private function process_template($template, $data)
{
// Default variables
$variables = [
'first_name' => $data['first_name'] ?? '',
'last_name' => $data['last_name'] ?? '',
'email' => $data['email'] ?? '',
'full_name' => trim(($data['first_name'] ?? '') . ' ' . ($data['last_name'] ?? '')),
'current_date' => date('Y-m-d'),
'current_year' => date('Y')
];
// Merge with additional data
$variables = array_merge($variables, $data);
// Replace {{variable}} with actual values
foreach ($variables as $key => $value) {
$template = str_replace('{{' . $key . '}}', $value, $template);
}
// Remove unreplaced variables
$template = preg_replace('/\{\{[^}]+\}\}/', '', $template);
return $template;
}
// Helper
/**
* Add tracking pixel to email content
*/
private function add_tracking_pixel($content, $tracking_id)
{
$tracking_url = site_url('track/open/' . $tracking_id);
$tracking_pixel = '<img src="' . $tracking_url . '" width="1" height="1" border="0" style="display:none;" alt="">';
// Add pixel before closing body tag
if (stripos($content, '</body>') !== false) {
$content = str_ireplace('</body>', $tracking_pixel . '</body>', $content);
} else {
$content .= $tracking_pixel;
}
return $content;
}
/**
* Process links for click tracking
*/
private function process_tracking_links($content, $tracking_id)
{
// Find all links and replace with tracking links
$pattern = '/<a\s+[^>]*href=["\'](https?:\/\/[^"\']+)["\']/i';
return preg_replace_callback($pattern, function ($matches) use ($tracking_id) {
$original_url = $matches[1];
$tracking_url = site_url('track/click/' . $tracking_id . '?url=' . urlencode($original_url));
return str_replace($original_url, $tracking_url, $matches[0]);
}, $content);
}
/**
* Generate unique tracking ID
*/
private function generate_tracking_id($campaign_id, $subscriber_id)
{
return md5($campaign_id . '_' . $subscriber_id . '_' . time() . '_' . rand());
}
/**
* Test SMTP connection
*/
public function test_connection()
{
try {
$this->mailer->smtpConnect();
$this->mailer->smtpClose();
return [
'status' => 'success',
'message' => 'SMTP connection successful'
];
} catch (Exception $e) {
return [
'status' => 'failed',
'message' => 'SMTP connection failed: ' . $e->getMessage()
];
}
}
/**
* Send test email
*/
public function send_test_email($to_email, $to_name = '')
{
$test_data = [
'to_email' => $to_email,
'to_name' => $to_name,
'subject' => 'Test Email from ' . $this->smtp_config['from_name'],
'body' => $this->get_test_email_template(),
'tracking_id' => 'test_' . time()
];
return $this->send_single($test_data);
}
/**
* Get test email template
*/
private function get_test_email_template()
{
return '
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background-color: #f4f4f4; }
.container { max-width: 600px; margin: 0 auto; background: white; padding: 20px; border-radius: 5px; }
.header { background: #007cba; color: white; padding: 20px; text-align: center; margin: -20px -20px 20px -20px; }
.footer { margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee; font-size: 12px; color: #666; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>IT - Email Marketing Test</h1>
</div>
<div class="content">
<p>Hello there!</p>
<p>This is a test email from Email Marketing System.</p>
<p>If you received this email, SMTP configuration is working correctly.</p>
<p><strong>Test Details:</strong></p>
<ul>
<li>Sent at: ' . date('Y-m-d H:i:s') . '</li>
<li>SMTP Host: ' . $this->smtp_config['smtp_host'] . '</li>
<li>SMTP Port: ' . $this->smtp_config['smtp_port'] . '</li>
</ul>
<p><a href="https://example.com" style="color: #007cba;">Test tracking link</a></p>
<p>Thankies,</p>
<p>IT</p>
</div>
<div class="footer">
<p>This is an automated test email from Email Marketing System by IT.</p>
</div>
</div>
</body>
</html>';
}
/**
* Get current SMTP configuration (for debugging)
*/
public function get_smtp_config()
{
// Hide sensitive data
$safe_config = $this->smtp_config;
$safe_config['smtp_password'] = !empty($safe_config['smtp_password']) ? '***hidden***' : '';
return $safe_config;
}
/**
* Update SMTP configuration
*/
public function update_smtp_config($new_config)
{
$this->smtp_config = array_merge($this->smtp_config, $new_config);
$this->init_phpmailer();
}
private function validate_email($email)
{
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
}