<?php if (!defined('HTTP_SERVER')) die('You can not access this file directly!');
/**
  @licence GPL 2005-2011  The osCSS developers - osCSS Open Source E-commerce
  @portion code Copyright (c) 2002 osCommerce
  @package osCSS-2 <www http://www.oscss.org>
  @version 2.1.0
  @date  22/03/11, 16:16
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
  @class emailUtility
*/

class emailUtility {



  /**
    Send email (text/html) using MIME
    This is the central mail function. The SMTP Server should be configured correct in php.ini
  @Param
    $to_name           The name of the recipient, e.g. "Jan Wildeboer"
    $to_email_address  The eMail address of the recipient,
    e.g. jan.wildeboer@gmx.de
    $email_subject     The subject of the eMail
    $email        The text of the eMail, may contain HTML entities
    $from_email_name   The name of the sender, e.g. Shop Administration
    $from_email_adress The eMail address of the sender,
    e.g. info@mytepshop.com

  @return boolean true /false
  */
 public static function tep_mail($to_name, $to_email_address, $email_subject, $email_array, $from_email_name='', $from_email_address='') {

    if (!_cst_bool('SEND_EMAILS')) return false;
    // Instantiate a new mail object
    $message = new PHPMailer();

    if (EMAIL_TRANSPORT == 'smtp'){
      $message->IsSMTP(); // telling the class to use SMTP

      if( !tep_not_null($from_email_address) ) $from_email_address = SMTP_SENDMAIL_FROM;
      if( !tep_not_null($from_email_name) ) $from_email_name = SMTP_FROMEMAIL_NAME;
      $message->Host = SMTP_MAIL_SERVER; // SMTP server
    }else{
      $message->IsSendmail();
      //////(EMAIL_TRANSPORT == 'sendmail')
      //////You need to implement here if you are using sendmail
      if(empty($from_email_address))$from_email_address=EMAIL_FROM;
      if(empty($from_email_name))$from_email_name=STORE_OWNER;
    }

    // Config

    $message->From = $from_email_address;
    $message->FromName = $from_email_name;

    $message->CharSet = CHARSET;

    if( !tep_not_null($to_name) ) $to_name = '';

    if( !tep_not_null($to_email_address) ) return false;


    $message->AddAddress($to_email_address, $to_name);
    $message->Subject = $email_subject;

    // Build the text version

     $text = iconv ( 'ISO-8859-1',strtoupper(CHARSET ), strip_tags(html_entity_decode($email_array['text'] ,ENT_QUOTES, strtoupper(CHARSET ) ) ,"\n\r"));

    if (EMAIL_USE_HTML == 'true') {
      $message->Body = stripslashes($email_array['html']);// tep_convert_linefeeds(array("\r\n", "\n", "\r"), '<br>', $email_text);
      $message->AltBody = $text;
      $message->IsHTML(true);
    } else {
      $message->Body = $text;
      $message->IsHTML(false);
    }

    // Send message
    if(!$message->Send()){
      /*echo 'Email was not sent.';
      echo 'Mailer error: ' . $message->ErrorInfo;*/


      return false;
    }
    else return true;

  }


  /**
    @package oscss-Rv
    @author oscim - OscssTeam
    @version 1.0
    Construteur de mise en forme des email avant envoi; remplace les code raccouris et ajoute si necessaire l'entete html
  */
  public static function replace_for_mail($txt_mail,$subject,$html_reg,$text_reg,$mode='HTML'){
      /* Code raccourcis autorisé */
	$array_code_racc=array('genre','firstname','lastname', 'email_address', 'numero_client', 'signature','license','desinscription');

      foreach ($array_code_racc as $item) {
	  if ($mode == 'HTML'){
	      if (preg_match('/\['.$item.'\]/i',$txt_mail) && isset($html_reg[$item]))  $txt_mail = preg_replace('/\['.$item.'\]/i',$html_reg[$item],$txt_mail);
	  } else {
	      if (preg_match('/\['.$item.'\]/i',$txt_mail) && isset($text_reg[$item])) $txt_mail = preg_replace('/\['.$item.'\]/i',$text_reg[$item],$txt_mail);
	  }
      }
      return $txt_mail;
  }


  /**
    Construteur de mise en forme des email avant envoi; remplace les code raccouris et ajoute si necessaire l'entete html
    @param
      @a string nom du template
      @a string path du language utilis pour le mail
      @a array $myarray key/value des var perso
      @a boolean return / print
  */
  public static function post_prepare_email($template,$language,$myarray,$print=false){

    global $title_email,$messageStack;
    $template=(tep_not_null($template) && file_exists(DIR_FS_ADMIN.DIR_WS_MODULES.'template_email/'.$template))? $template : 'defaut.tpl' ;
    @include(DIR_WS_LANGUAGES . $language .'/modules/template_email/'.substr($template, 0, strlen($template)-4) .'.txt');


    $tpl = &Template::singleton();
    if (!empty($tpl->error)) {
      $messageStack->add_session($tpl->error, 'error');
      return false;
    }
    $tpl->template_dir =  DIR_WS_MODULES . 'template_email/';
    $tpl->assign("STORE_LOGO_PRINT",STORE_LOGO_PRINT);
    $tpl->assign("DIR_WS_CATALOG", DIR_WS_CATALOG);
    $tpl->assign("DIR_WS_ADMIN", DIR_WS_ADMIN);
    $tpl->assign("HTTP_CATALOG_SERVER", HTTP_CATALOG_SERVER);
    $tpl->assign("DIR_WS_IMAGES", DIR_WS_IMAGES.'mail/');
    $tpl->assign("DIR_WS_LANGUAGES", DIR_WS_LANGUAGES);
    $tpl->assign("CHARSET", CHARSET);
    $tpl->assign("STORE_NAME", STORE_NAME);
    $tpl->assign("myarray", $myarray);
    $tpl->assign("TPL_CONTENT", addslashes($myarray['message']));
    if (isset($lang) && is_array($lang)){
      $title_email=$lang['EMAIL_TEXT_SUBJECT'];
      if(!defined('EMAIL_TEXT_SUBJECT'))define('EMAIL_TEXT_SUBJECT',$lang['EMAIL_TEXT_SUBJECT']);

      $tpl->assign("lg", $lang);
    }


    if(!$print) {
      $mess['html']=$tpl->get($template);

      // force calcul txt
      $myarray['email_use_html']=false;
      $tpl->assign("myarray", $myarray);

      $mess['text']= strip_tags(str_replace(array('<br>','<br />'),array("\n"), $tpl->get($template) ));

      return $mess;
    }
    else return $tpl->display($template);
  }

  /**
      Recup element dirs
    @package oscss-Rv
    @author oscim
    @version 1.0
  */
  public static function recup_template_mail(){
    $dirs = dir( DIR_WS_MODULES . 'template_email/');
    $t[]=array('id'=>'', 'text'=>TEXT_TPL_AUCUN );
    while ($file = $dirs->read()) {
      if (substr("$file", -4) == '.tpl') {
	$name=substr("$file",0,strlen($file)-4);
	$t[]=array('id'=>$file, 'text'=>$name );
      }
    }
    $dirs->close();
    return $t;
  }

}
?>
