<?php
/**
  * Ahead WebSoft Technologies Pvt Ltd.
  * @copyright  Copyright 2006-2026 Ahead WebSoft Technologies Pvt Ltd.
  * @license    https://www.socialengine.com/policies
*/
class Core_AdminMailController extends Core_Controller_Action_Admin
{

  public function settingsAction()
  {
    // Get navigation
    $this->view->navigation = Engine_Api::_()->getApi('menus', 'core')->getNavigation('core_admin_main_emailsettings', array(), 'core_admin_main_settings_mailsettings');

    // Get mail config
    $mailConfigFile = APPLICATION_PATH . '/application/settings/mail.php';
    $mailConfig = array();
    if (file_exists($mailConfigFile)) {
      $mailConfig = include $mailConfigFile;
    }

    // Get form
    $this->view->form = $form = new Core_Form_Admin_Mail_Settings();

    // Populate form
    $form->populate((array) Engine_Api::_()->getApi('settings', 'core')->core_mail);

    if ('Zend_Mail_Transport_Smtp' === @$mailConfig['class'] && !_ENGINE_ADMIN_NEUTER) {
      $form->populate(
        array_filter(
          array(
            'mail_smtp' => ('Zend_Mail_Transport_Smtp' == @$mailConfig['class']),
            'mail_smtp_server' => @$mailConfig['args'][0],
            'mail_smtp_ssl' => @$mailConfig['args'][1]['ssl'],
            'mail_smtp_authentication' => !empty($mailConfig['args'][1]['username']),
            'mail_smtp_port' => @$mailConfig['args'][1]['port'],
            'mail_smtp_username' => @$mailConfig['args'][1]['username'],
            'mail_smtp_password' => @$mailConfig['args'][1]['password'],
          )
        )
      );
    }

    // Check method/valid
    if (!$this->getRequest()->isPost()) {
      return;
    }
    if (!$form->isValid($this->getRequest()->getPost())) {
      return;
    }

    // Process
    $values = $form->getValues();

    // Special case for auth
    if ($values['mail_smtp']) {
      // re-assign existing password if form password is left blank
      if (empty($values['mail_smtp_password'])) {
        if (!empty($mailConfig['args'][1]['password'])) {
          $values['mail_smtp_password'] = $mailConfig['args'][1]['password'];
        }
      }
    }

    // Save smtp settings
    if ($values['mail_smtp']) {
      $args = array();

      $args['port'] = (int) $values['mail_smtp_port'];

      if (!empty($values['mail_smtp_ssl'])) {
        $args['ssl'] = $values['mail_smtp_ssl'];
      }

      if (!empty($values['mail_smtp_authentication'])) {
        $args['auth'] = 'login';
        $args['username'] = $values['mail_smtp_username'];
        $args['password'] = $values['mail_smtp_password'];
      }

      $mailConfig = array(
        'class' => 'Zend_Mail_Transport_Smtp',
        'args' => array(
          $values['mail_smtp_server'],
          $args,
        )
      );

    } else {
      $mailConfig = array(
        'class' => 'Zend_Mail_Transport_Sendmail',
        'args' => array(),
      );
    }

    // Write contents to file
    if (
      (is_file($mailConfigFile) && is_writable($mailConfigFile)) ||
      (is_dir(dirname($mailConfigFile)) && is_writable(dirname($mailConfigFile)))
    ) {
      $contents = "<?php defined('_ENGINE') or die('Access Denied'); return ";
      $contents .= var_export($mailConfig, true);
      $contents .= "; ?>";

      file_put_contents($mailConfigFile, $contents);
    } else {
      return $form->addError('Unable to change mail settings due to the file ' .
        '/application/settings/mail.php not having the correct permissions.' .
        'Please CHMOD (change the permissions of) that file to 666, then try again.');
    }

    // save the name and email address
    Engine_Api::_()->getApi('settings', 'core')->core_mail = array(
      'from' => $values['from'],
      'name' => $values['name'],
      'queueing' => $values['queueing'],
      'contact' => $values['contact'],
      'count' => $values['count'],
      'signature' => $values['signature'],
			'facebook_url' => $values['facebook_url'],
			'twitter_url' => $values['twitter_url'],
			'linkedin_url' => $values['linkedin_url'],
			'instagram_url' => $values['instagram_url'],
			'pinterest_url' => $values['pinterest_url'],
			'flickr_url' => $values['flickr_url'],
    );
    $form->addNotice('Your changes have been saved.');
  }

  public function templatesAction()
  {
    // Get navigation
    $this->view->navigation = Engine_Api::_()->getApi('menus', 'core')->getNavigation('core_admin_main_emailsettings', array(), 'core_admin_main_settings_mailtemplates');

    $this->view->form = $form = new Core_Form_Admin_Mail_Templates();

    // Get language
    $this->view->language = $language = preg_replace('/[^a-zA-Z_-]/', '', $this->_getParam('language', 'en'));
    if (!Zend_Locale::isLocale($language)) {
      $form->removeElement('submit');
      return $form->addError('Please select a valid language.');
    }

    // Check dir for exist/write
    $languageDir = APPLICATION_PATH . '/application/languages/' . $language;
    $languageFile = $languageDir . '/custom.csv';
    if (!is_dir($languageDir)) {
      $form->removeElement('submit');
      return $form->addError('The language does not exist, please create it first');
    }
    if (!is_writable($languageDir)) {
      $form->removeElement('submit');
      return $form->addError('The language directory is not writable. Please set CHMOD -R 0777 on the application/languages folder.');
    }
    if (is_file($languageFile) && !is_writable($languageFile)) {
      $form->removeElement('submit');
      return $form->addError('The custom language file exists, but is not writable. Please set CHMOD -R 0777 on the application/languages folder.');
    }



    // Get template
    $this->view->template = $template = $this->_getParam('template', '1');
    $this->view->templateObject = $templateObject = Engine_Api::_()->getItem('core_mail_template', $template);
    if (!$templateObject) {
      $templateObject = Engine_Api::_()->getDbtable('MailTemplates', 'core')->fetchRow();
      $template = $templateObject->mailtemplate_id;
    }

    // Populate form
    $description = $this->view->translate(strtoupper("_email_" . $templateObject->type . "_description"));
    $description .= '<br /><br />';
    $description .= $this->view->translate('Available Placeholders:');
    $description .= '<br />';
    $description .= join(', ', explode(',', $templateObject->vars));

    $form->getElement('template')
      ->setDescription($description)
      ->getDecorator('Description')
      ->setOption('escape', false)
    ;

    // Get translate
    $translate = Zend_Registry::get('Zend_Translate');


    // Get stuff
    $subjectKey = strtoupper("_email_" . $templateObject->type . "_subject");
    $subject = $translate->_($subjectKey, $language);
    if ($subject == $subjectKey) {
      $subject = $translate->_($subjectKey, 'en');
    }

    $bodyHTMLKey = strtoupper("_email_" . $templateObject->type . "_bodyhtml");
    $bodyHTML = $translate->_($bodyHTMLKey, $language);
    if ($bodyHTML == $bodyHTMLKey) {
      $bodyHTML = $translate->_($bodyHTMLKey, 'en');
    }

    // get body from email body key if not found by bodyhtml key
    if ($bodyHTML == $bodyHTMLKey) {
      $bodyKey = strtoupper("_email_" . $templateObject->type . "_body");
      $body = $translate->_($bodyKey, $language);
      if ($body == $bodyKey) {
        $body = $translate->_($bodyKey, 'en');
      }
      $bodyHTML = nl2br($body);
    }
    $form->populate(
      array(
        'language' => $language,
        'template' => $template,
        'subject' => $subject,
        'bodyhtml' => $bodyHTML,
        'default' => $templateObject->default,
      )
    );

    $enabledMemberLevel = false;
    if (!engine_in_array($templateObject->module, array("core", "user", "payment", "invite"))) {
      if (!is_null($templateObject->member_level)) {
        $memberLevel = @explode(",", $templateObject->member_level);
        $form->member_level->setValue($memberLevel);
      }
      $enabledMemberLevel = true;
    } else {
      $form->removeElement("member_level");
    }
    // Check method/valid
    if (!$this->getRequest()->isPost()) {
      return;
    }
    if (!$form->isValid($this->getRequest()->getPost())) {
      return;
    }

    // Process
    $values = $form->getValues();

    /*Feature Improvement - Add Member Level Settings for Emailed Notifications #971 */
    if ($enabledMemberLevel) {
      $templateObject->member_level = implode(",", (array) $values['member_level']);
      $templateObject->save();
    }
    $templateObject->default = $values['default'];
    $templateObject->save();

    $writer = new Engine_Translate_Writer_Csv();
    // Try to write to a file
    $targetFile = APPLICATION_PATH . '/application/languages/' . $language . '/custom.csv';
    if (!file_exists($targetFile)) {
      touch($targetFile);
      chmod($targetFile, 0777);
    }

    // set the local folder depending on the language_id
    $writer->read(APPLICATION_PATH . '/application/languages/' . $language . '/custom.csv');

    // write new subject
    $writer->removeTranslation(strtoupper("_email_" . $templateObject->type . "_subject"));
    $writer->setTranslation(strtoupper("_email_" . $templateObject->type . "_subject"), $values['subject']);

    // write new body
    $writer->removeTranslation(strtoupper("_email_" . $templateObject->type . "_bodyhtml"));
    $writer->setTranslation(strtoupper("_email_" . $templateObject->type . "_bodyhtml"), $values['bodyhtml']);

    $writer->write();


    // Clear cache?
    $translate->clearCache();


    $form->addNotice('Your changes have been saved.');

    // Check which Translation Adapter has been selected
    $db = Engine_Db_Table::getDefaultAdapter();
    $translationAdapter = $db->select()
      ->from('engine4_core_settings', 'value')
      ->where('`name` = ?', 'core.translate.adapter')
      ->query()
      ->fetchColumn();
    if ($translationAdapter == 'array') {
      $form->addNotice('You have enabled the "Translation Performance" setting from \"<a href="admin/core/settings/performance">Performance and Caching</a>\" section of administration. For your email template changes to be effective by re-generation of updated translation PHP array, please click on "Save Changes" button of \"<a href="admin/core/settings/performance">Performance and Caching</a>\" section, with "Flush cache?" enabled, after completing all your changes in email templates.');
    }
  }

  public function manageAction()
  {
    // Get navigation
    $this->view->navigation = Engine_Api::_()->getApi('menus', 'core')->getNavigation('core_admin_main_emailsettings', array(), 'core_admin_main_settings_managetemplates');

    $params = array();
    $params['is_active'] = $this->_getParam('is_active', null);
    $this->view->paginator = $paginator = Engine_Api::_()->getDbtable('emailtemplates', 'core')->getTemplates($params);

    if ($this->getRequest()->isPost()) {
      $db = Engine_Db_Table::getDefaultAdapter();
      $values = $this->getRequest()->getPost();
      foreach ($values as $key => $value) {
        if ($key == 'delete_' . $value) {
          $template = Engine_Api::_()->getItem('core_emailtemplate', $value);
          if ($template) {
            $template->delete();
          }
        }
      }
    }
    $paginator->setItemCountPerPage(50);
    $paginator->setCurrentPageNumber($this->_getParam('page', 1));
  }


  public function createAction()
  {
    $this->view->navigation = Engine_Api::_()->getApi('menus', 'core')->getNavigation('core_admin_main_emailsettings', array(), 'core_admin_main_settings_managetemplates');

    $viewer = Engine_Api::_()->user()->getViewer();

    $template_id = $this->_getParam('template_id', null);

    $this->view->form = $form = new Core_Form_Admin_Mail_Emailtemplate();

    if ($this->_getParam('duplicate', '0')) {

      $this->view->duplicateTemplate = $duplicateTemplate = Engine_Api::_()->getItem('core_emailtemplate', $this->_getParam('duplicate', '0'));

      $form->save->setLabel('Save Changes');
      $form->setTitle("Edit Templates");
      $form->setDescription("Edit the details below for the Templates.");
      $values = $duplicateTemplate->toArray();
      $form->populate($values);
    }

    if ($template_id) {
      $this->view->template = $template = Engine_Api::_()->getItem('core_emailtemplate', $template_id);
      $form->save->setLabel('Save Changes');
      $form->setTitle("Edit Templates");
      $form->setDescription("Edit the details below for the Templates.");
      $values = $template->toArray();
      if ($template->is_active) {
        $values['activate_thistemplate'] = $template->is_active;
      }
      $form->populate($values);
    }

    if (!$this->getRequest()->isPost()) {
      return;
    }

    if (!$form->isValid($this->getRequest()->getPost())) {
      return;
    }

    // test mail
    $values = $form->getValues();
    if ($values['test_email_check'] && !$_POST['test_email']) {
      $form->addError("Test Email not available.");
      return;
    }

    // test mail
    $templateTable = Engine_Api::_()->getDbTable('emailtemplates', 'core');
    $db = $templateTable->getAdapter();
    $db->beginTransaction();
    try {

      $values = $form->getValues();

      if (empty($template))
        $template = $templateTable->createRow();

      $values['user_id'] = $viewer->getIdentity();
      if ($values['activate_thistemplate']) {
        $values['is_active'] = '1';
        $dbb = Zend_Db_Table_Abstract::getDefaultAdapter();
        $dbb->query('UPDATE `engine4_core_emailtemplates` SET `is_active` = "0" WHERE `engine4_core_emailtemplates`.`is_active` = "1";');

      } else {
        $values['is_active'] = '0';
      }

      $template->setFromArray($values);
      $template->save();

      $db->commit();
      
      if (!empty($_POST['test_email_check'])) {
        $description = '<p><span style="font-weight: 400;">Hello,</span></p><p><span style="font-weight: 400;">This is a test email which you can send to your site users.</span></p><p>&nbsp;</p><p><span style="font-weight: 400;">Thank You</span></p>';
        $search = array(
          '/\>[^\S ]+/s', // strip whitespaces after tags, except space
          '/[^\S ]+\</s', // strip whitespaces before tags, except space
          '/(\s)+/s'       // shorten multiple whitespace sequences
        );
        $replace = array(
          '>',
          '<',
          '\\1'
        );

        //check uploaded content images
        $doc = new DOMDocument();
        @$doc->loadHTML($description);
        $tags = $doc->getElementsByTagName('img');
        foreach ($tags as $tag) {
          $src = $tag->getAttribute('src');
          if (strpos($src, 'http://') === FALSE && strpos($src, 'https://') === FALSE) {
            $imageGetFullURL = (!empty($_SERVER["HTTPS"]) && strtolower($_SERVER["HTTPS"] == 'on')) ? "https://" . $_SERVER['HTTP_HOST'] . $src : "http://" . $_SERVER['HTTP_HOST'] . $src;
            $tag->setAttribute('src', $imageGetFullURL);
          }
        }

        $description = $doc->saveHTML();
        $description = preg_replace($search, $replace, $description);
        Engine_Api::_()->getApi('mail', 'core')->sendSystem($values['test_email'], 'core_test_mailtemplate', array('host' => $_SERVER['HTTP_HOST'], 'emailtemplate_content' => $description, 'emailtemplate_subject' => 'Email Templates Test Subject', 'queue' => false, 'recipient_title' => $viewer->getTitle(), 'template_id' => $template->emailtemplate_id));
        $form->addNotice('Test email sent successfully.');
      } else {
        unset($_POST['test_email_check']);
      }
    } catch (Exception $e) {
      $db->rollback();
      throw $e;
    }
    if (isset($_POST['save']))
      return $this->_helper->redirector->gotoRoute(array('module' => 'core', 'controller' => 'mail', 'action' => 'create', 'template_id' => $template->getIdentity()), 'admin_default', true);
    else
      return $this->_helper->redirector->gotoRoute(array('module' => 'core', 'controller' => 'mail', "action" => "manage"), 'admin_default', true);
  }
  public function testmailAction()
  {
    $templateId = $this->_getParam('template_id');

    $this->_helper->layout->setLayout('admin-simple');
    
    $this->view->form = $form = new Core_Form_Admin_Mail_Testemail();

    $viewer = Engine_Api::_()->user()->getViewer();

    if ($_POST) {
      if (!$_POST['email']) {
        $form->addError("Email not available.");
        return;
      }

      $description = '<p><span style="font-weight: 400;">Hello,</span></p><p><span style="font-weight: 400;">This is a test email which you can send to your site users.</span></p><p>&nbsp;</p><p><span style="font-weight: 400;">Thank You</span></p>';
      $search = array(
        '/\>[^\S ]+/s', // strip whitespaces after tags, except space
        '/[^\S ]+\</s', // strip whitespaces before tags, except space
        '/(\s)+/s'       // shorten multiple whitespace sequences
      );
      $replace = array(
        '>',
        '<',
        '\\1'
      );

      //check uploaded content images
      $doc = new DOMDocument();
      @$doc->loadHTML($description);
      $tags = $doc->getElementsByTagName('img');
      foreach ($tags as $tag) {
        $src = $tag->getAttribute('src');
        if (strpos($src, 'http://') === FALSE && strpos($src, 'https://') === FALSE) {
          $imageGetFullURL = (!empty($_SERVER["HTTPS"]) && strtolower($_SERVER["HTTPS"] == 'on')) ? "https://" . $_SERVER['HTTP_HOST'] . $src : "http://" . $_SERVER['HTTP_HOST'] . $src;
          $tag->setAttribute('src', $imageGetFullURL);
        }
      }
      $description = $doc->saveHTML();

      //get all background url tags
      $description = preg_replace($search, $replace, $description);
      Engine_Api::_()->getApi('mail', 'core')->sendSystem($_POST['email'], 'core_test_mailtemplate', array('host' => $_SERVER['HTTP_HOST'], 'emailtemplate_content' => $description, 'emailtemplate_subject' => 'Email Templates Test Subject', 'queue' => false, 'recipient_title' => $viewer->getTitle(), 'template_id' => $templateId));
      
      $form->addNotice('Test email sent successfully.');

      $this->_forward('success', 'utility', 'core', array(
        'smoothboxClose' => true,
        'parentRefresh' => true,
        'messages' => array($this->view->translate('Test email sent successfully.')),
      ));
    }
  }

  public function deleteEmailtemplateAction()
  {
    // In smoothbox
    $this->_helper->layout->setLayout('admin-simple');
    $this->view->item_id = $id = $this->_getParam('template_id');

    // Check post
    if ($this->getRequest()->isPost()) {
      $template = Engine_Api::_()->getItem('core_emailtemplate', $id);
      if ($template) {
        $template->delete();
      }
      $this->_forward('success', 'utility', 'core', array(
        'smoothboxClose' => 20,
        'parentRefresh' => 20,
        'messages' => array($this->view->translate('Email Template Deleted Successfully.'))
      ));
    }
    // Output
    $this->renderScript('admin-mail/delete-emailtemplate.tpl');
  }
  public function enabledAction()
  {
    $template_id = $this->_getParam('template_id', 0);
    $db = Zend_Db_Table_Abstract::getDefaultAdapter();
    $db->query('UPDATE `engine4_core_emailtemplates` SET `is_active` = "0" WHERE `engine4_core_emailtemplates`.`is_active` = "1";');

    if (!empty($template_id)) {
      $item = Engine_Api::_()->getItem('core_emailtemplate', $template_id);
      $item->is_active = !$item->is_active;
      $item->save();
    }
    $this->_redirect('admin/mail/manage');
  }
}
