[ Index ]

MailPress 544

[ Index ]     [ Classes ]     [ Functions ]     [ Variables ]     [ Constants ]     [ Statistics ]    

title

Body

[close]

/mp-includes/class/ -> MP_Mail.class.php (source)

   1  <?php
   2  class MP_Mail extends MP_mail_
   3  {
   4      const status_deleted = 'deleted';
   5  
   6      const name_required = true;
   7      const get8BitEncoding = true; // setting this to false can have an impact on perf see http://forums.devnetwork.net/viewtopic.php?f=52&t=96933
   8  
   9  	function __construct( $plug = MP_FOLDER )
  10      {
  11          $this->plug = $plug;
  12  
  13          $this->theme = new MP_Themes();
  14  
  15          $this->message     = null;
  16  
  17          $this->args = new stdClass();
  18      }
  19  
  20  ////    MP_Mail send functions    ////
  21  
  22  	function send($args)
  23      {
  24          if (is_numeric($args))
  25          {
  26              $this->args = MP_Mail::get($args);
  27          }
  28          else
  29          {
  30              $this->args = $args ;
  31          }
  32          return $this->end( $this->start() );
  33      }
  34  
  35  	function start()
  36      {
  37          MP_::no_abort_limit();
  38  
  39          $this->row  = new stdClass();
  40          $this->mail = new stdClass();
  41  
  42          global $mp_general;
  43          $mp_general = get_option(MailPress::option_name_general);
  44  
  45  ////  Log it  ////
  46  
  47          $this->trace = new MP_Log('mp_mail', array('force' => (isset($this->args->forcelog))));
  48  
  49          if (!$this->args)    
  50          {
  51              $this->trace->log('MAILPRESS [ERROR] - Sorry invalid arguments in MP_Mail::send');
  52              return false;
  53          }
  54  
  55  ////  Build it  ////
  56  
  57          if (!isset($this->args->id))
  58          {
  59              $this->row->id = $this->args->id = MP_Mail::get_id( 'MP_Mail::start' );
  60          }
  61          else
  62              $this->row->id = $this->args->id;
  63  
  64      // charset //
  65          $this->row->charset = (isset($this->args->charset)) ? $this->args->charset : get_option('blog_charset');
  66  
  67      // fromemail & fromname //
  68          $this->row->fromemail     = (empty($this->args->fromemail)) ? $mp_general['fromemail'] : $this->args->fromemail;
  69          $this->row->fromname     = (empty($this->args->fromname))  ? $mp_general['fromname']  : $this->args->fromname;
  70          $this->row->fromname     = (empty($this->row->fromname))   ? self::display_name($mp_general['fromemail']) : $this->row->fromname;
  71  
  72      // recipients & replacements //
  73          self::get_mail_replacements();
  74  
  75          $this->mail->recipients_count = $this->manage_recipients();
  76          if (!$this->mail->recipients_count)
  77          {
  78              $this->trace->log((0 === $this->mail->recipients_count) ? 'MAILPRESS [ERROR] - No recipient' : 'MAILPRESS [ERROR] - problems with recipients & replacements');
  79              return $this->mail->recipients_count;
  80          }
  81  
  82      // subject //
  83          $this->row->subject     = (isset($this->args->subject)) ? $this->args->subject : false;
  84          if (isset($this->args->Template)) 
  85          {
  86              $theme = (isset($this->args->Theme)) ? $this->args->Theme : $this->theme->themes[$this->theme->current_theme]['Stylesheet'];
  87              if (!$pt = $this->theme->get_page_templates($theme)) $pt = $this->theme->get_page_templates($theme, true);
  88              if (isset($pt[$this->args->Template]['subject'])) $this->row->subject = $pt[$this->args->Template]['subject'];
  89          }
  90          $this->row->subject     = ($this->row->subject) ? trim($this->html_entity_decode($this->do_eval($this->row->subject))) : '';
  91  
  92      // html //
  93          $this->row->html        = $this->build_mail_content('html', 'the_content');
  94  
  95      // plaintext //
  96          $this->row->plaintext     = $this->build_mail_content('plaintext');
  97  
  98      // attachements //
  99          $this->mail->attachements = false;
 100          if (isset($this->args->main_id))
 101          {
 102              $metas = MP_Mail_meta::has( $this->args->main_id, '_MailPress_attached_file');
 103              if ($metas)
 104              {
 105                  foreach($metas as $meta)
 106                  {
 107                      $meta_value = unserialize( $meta['meta_value'] );
 108                      if (!is_file($meta_value['file_fullpath'])) continue;
 109                      $this->mail->attachements = true;
 110                      MP_Mail_meta::add( $this->row->id, '_MailPress_attached_file', $meta_value );
 111                  }
 112              }
 113          }
 114  
 115          unset($this->theme);
 116  
 117      // mail empty ? //
 118          if (!$this->row->subject && !$this->row->plaintext && !$this->row->html && !$this->mail->attachements)
 119          {
 120              $this->trace->log(__('MAILPRESS [WARNING] - Mail is empty', MP_TXTDOM));
 121              return false;
 122          }
 123  
 124          $this->row->theme        = $this->mail->theme;
 125          $this->row->themedir    = $this->mail->themedir;
 126          $this->row->template     = $this->mail->template;
 127  
 128      // no tracking on unknown recipient ! //
 129          if (!isset($this->mail->external_recipient))
 130          {
 131              $this->row = apply_filters('MailPress_mail', $this->row);
 132              $this->replace_mail_urls();
 133          }
 134  
 135      // only one recipient //
 136          if (1 == $this->mail->recipients_count)
 137          {
 138              $toname = '';
 139              if (isset($this->row->recipients[0])) $toemail = $this->row->recipients[0]; else foreach($this->row->recipients as $toemail => $toname) {};
 140              $this->row->toemail = $toemail;
 141              $this->row->toname  = $toname;
 142  
 143              $this->row->replacements[$toemail] = array_merge($this->row->replacements[$toemail], $this->mail->replacements);
 144  
 145              foreach($this->row->replacements[$toemail] as $k => $v) 
 146              {
 147                  $this->row->subject     = str_replace($k, $v, $this->row->subject, $cs);
 148                  $this->row->plaintext     = str_replace($k, $v, $this->row->plaintext, $cp);
 149                  $this->row->html         = str_replace($k, $v, $this->row->html, $ch);
 150              }
 151  
 152              if (isset($this->row->replacements[$toemail]['{{_user_id}}'])) $this->row->mp_user_id = $this->row->replacements[$toemail]['{{_user_id}}'];
 153              MP_Mail_meta::delete_by_id($this->mail->mmid);
 154              unset($this->row->replacements, $this->row->recipients, $this->mail->replacements, $this->mail->mmid);
 155          }
 156  
 157  /*trace*/    $x  = " \n\n ------------------- start of mail -------------------  ";
 158  /*trace*/    $x .= " \n From : " . $this->row->fromname  . " <" . $this->row->fromemail . "> ";
 159  /*trace*/    if (isset($this->row->toemail))
 160  /*trace*/        if (!empty($this->row->toname))
 161  /*trace*/    $x .= " \n To   : " . $this->row->toname . " <" . $this->row->toemail . "> ";
 162  /*trace*/        else
 163  /*trace*/    $x .= " \n To   : " . $this->row->toemail;
 164  /*trace*/    $x .= " \n Subject : " . $this->row->subject;
 165  /*trace*/    if ($this->row->plaintext)     $x .= " \n   ------------------- plaintext -------------------  \n " . $this->row->plaintext;
 166  /*trace*/    if ($this->row->html)         $x .= " \n\n ------------------- text/html -------------------  \n " . $this->row->html;
 167  /*trace*/    $x .= " \n\n ------------------ end of mail ------------------  \n\n";
 168  /*trace*/    $this->trace->log($x, $this->trace->levels[512]);
 169  
 170          $this->mail->swift_batchSend         = (1 < $this->mail->recipients_count);
 171          $this->mail->mailpress_batch_send    = ($this->mail->swift_batchSend) ? class_exists('MailPress_batch_send') : false;
 172          $this->mail->mailpress_batch_spool_send = ($this->mail->swift_batchSend) ? class_exists('MailPress_batch_spool_send') : false;
 173  
 174  ////  Send it  ////
 175  
 176      // no mail ? //
 177          if (isset($this->args->nomail))
 178          {
 179              $this->trace->log('MAILPRESS [NOTICE] - :::: Mail not sent as required ::::');
 180          }
 181          elseif ($this->mail->mailpress_batch_send)
 182          {
 183              $this->trace->log('MAILPRESS [NOTICE] - :::: Mail batch processing as required ::::');
 184              do_action('MailPress_schedule_batch_send');
 185          }
 186          else
 187          {
 188              if (!$this->swift_processing())
 189              {
 190                  $this->trace->log('');
 191                  $this->trace->log('MAILPRESS [ERROR] - *** Mail could not be sent ***');
 192                  $this->trace->log('');
 193                  unset($this->message, $this->swift); 
 194                  return false;
 195              }
 196          }
 197          unset($this->message, $this->swift); 
 198  
 199  ////  Archive it  ////
 200  
 201          if (isset($this->args->noarchive))
 202          {
 203              $this->trace->log('MAILPRESS [NOTICE] - :::: Mail not saved as required ::::');
 204              MP_Mail::delete($this->row->id);
 205          }
 206          else
 207          { 
 208              global $wpdb;
 209  
 210              if (!isset($this->args->nostats)) new MP_Stat('t', isset($this->args->Template) ? $this->args->Template : '', $this->mail->recipients_count);
 211  
 212              $now        = current_time( 'mysql' );
 213              $user_id     = (empty($this->args->wp_user_id)) ?  MP_WP_User::get_id() : $this->args->wp_user_id;
 214  
 215              if ($this->mail->swift_batchSend) 
 216              {
 217                  foreach ($this->row->replacements as $email => $r)
 218                  {
 219                      if (isset($this->row->recipients[$email]))
 220                          $this->row->toemail[$email] = $this->row->replacements[$email];
 221                      unset($this->row->recipients[$email], $this->row->replacements[$email]);
 222                  }
 223                  foreach ($this->row->recipients as $k => $email)
 224                  {
 225                      $this->row->toemail[$email] = $this->row->replacements[$email];
 226                      unset($this->row->recipients[$k], $this->row->replacements[$email]);
 227                  }
 228                  unset($this->row->recipients, $this->row->replacements);
 229                  $this->row->toemail = serialize($this->row->toemail);
 230              }
 231  
 232      // status //
 233              $this->row->status = ($this->mail->swift_batchSend) ? (apply_filters('MailPress_status_mail', 'sent')) : 'sent';
 234              if (!isset($this->row->toname)) $this->row->toname = '';
 235  
 236              wp_cache_delete($this->row->id, 'mp_mail');
 237  
 238              $data = $format = $where = $where_format = array();
 239  
 240              $data['status']         = $this->row->status;     $format[] = '%s';
 241              $data['theme']         = $this->row->theme;     $format[] = '%s';
 242              $data['themedir']     = $this->row->themedir; $format[] = '%s';
 243              $data['template']     = $this->row->template; $format[] = '%s';
 244              $data['fromemail']     = $this->row->fromemail;$format[] = '%s';
 245              $data['fromname']     = $this->row->fromname;    $format[] = '%s';
 246              $data['toemail']         = $this->row->toemail;     $format[] = '%s';
 247              $data['toname']         = $this->row->toname;     $format[] = '%s';
 248              $data['charset']         = $this->row->charset;     $format[] = '%s';
 249              $data['subject']         = $this->row->subject;    $format[] = '%s';
 250              $data['html']         = $this->row->html;     $format[] = '%s';
 251              $data['plaintext']     = $this->row->plaintext;$format[] = '%s';
 252              $data['created']         = $now;             $format[] = '%s';
 253              $data['created_user_id']= $user_id;         $format[] = '%d';
 254              $data['sent']         = $now;             $format[] = '%s';
 255              $data['sent_user_id']     = $user_id;         $format[] = '%d';
 256  
 257              $where['id']         = (int) $this->row->id;        $where_format[] = '%d';
 258  
 259              if ( !$wpdb->update( $wpdb->mp_mails, $data, $where, $format, $where_format ) )
 260              {
 261                  $this->trace->log(sprintf('MAILPRESS [ERROR] - *** Database error, Mail not saved : %1$s '."\n".'%2$s', $wpdb->last_error, $wpdb->last_query));
 262                  return false;
 263              }
 264              $this->trace->log('MAILPRESS [NOTICE] - :::: MAIL SAVED ::::');
 265          }
 266  
 267          return $this->mail->recipients_count;
 268      }
 269  
 270  	function end($rc)
 271      {
 272          $this->trace->end($rc);
 273          return $rc;
 274      }
 275  
 276  
 277  ////  Build it  ////
 278  
 279  
 280   // mail replacements //
 281  
 282  	function get_mail_replacements()
 283      {
 284          $mail_replacements = $this->convert_all($this->args);
 285          $unsets = array( '{{subject}}', '{{content}}', '{{html}}', '{{plaintext}}', '{{id}}', '{{main_id}}', '{{recipients_query}}', '{{draft}}', '{{advanced}}' );
 286          foreach ($unsets as $unset) unset($mail_replacements[$unset]);
 287  
 288          $mail_main_id = (!isset($this->args->main_id)) ? 0 : $this->args->main_id;
 289          $_mail_id = ($mail_main_id) ? $mail_main_id : $this->row->id;
 290          $m = MP_Mail_meta::get_replacements($_mail_id);
 291          if (!is_array($m)) $m = array();
 292  
 293          $this->mail->replacements = array_merge($m, $mail_replacements);
 294  
 295          $this->mail->mmid = MP_Mail_meta::add( $this->row->id, '_MailPress_replacements', $this->mail->replacements );
 296      }
 297  
 298  	function convert_all($x='', $sepb='{{', $sepa='}}', $before='', $first=0, $array=array())
 299      {
 300          if (is_object($x)) $x = get_object_vars($x);
 301          if (empty($x)) return array();
 302          foreach($x as $key => $value)
 303          {
 304              if (!(is_object($value) || is_array($value)))
 305              {
 306                  $x = (0 == $first) ? $key : $before . '[' . $key . ']'; 
 307                  $array[$sepb . $x . $sepa] = $this->html_entity_decode($value);
 308              }
 309              else 
 310              {
 311                  $abefore= (!$first) ? $key : $before . '[' . $key . ']'; 
 312                  $array = array_merge($array, $this->convert_all($value , $sepb , $sepa , $abefore , $first + 1 ) );
 313              }
 314          }
 315          return $array;
 316      }
 317  
 318   // recipients & replacements //
 319  
 320  	function manage_recipients()
 321      {
 322          if (isset($this->args->replacements))
 323          {
 324              if (isset($this->args->recipients))
 325              {
 326                  $this->row->replacements = $this->args->replacements;
 327                  $this->row->recipients   = $this->args->recipients;
 328                  return count($this->row->recipients);
 329              }
 330              else
 331              {
 332                  $this->get_old_recipients();
 333                  return count($this->row->recipients);
 334              }
 335          }
 336  
 337          if (!isset($this->args->recipients_query))
 338          {
 339              if (is_email($this->args->toemail))
 340              {
 341                  $mp_user_id = MP_User::get_id_by_email($this->args->toemail);
 342                  if ($mp_user_id)
 343                  {
 344                      global $wpdb;
 345                      $this->args->recipients_query = "SELECT DISTINCT id, email, name, status, confkey FROM $wpdb->mp_users WHERE id = $mp_user_id ;";
 346                  }
 347              }
 348          }
 349  
 350          if (isset($this->args->recipients_query))
 351          {
 352              $this->get_recipients($this->args->recipients_query);
 353  
 354              $this->args->viewhtml = MP_User::get_view_url('{{_confkey}}', $this->row->id);
 355              if (isset($this->args->subscribe))     $this->args->subscribe   = MP_User::get_subscribe_url('{{_confkey}}');
 356              else                        $this->args->unsubscribe = MP_User::get_unsubscribe_url('{{_confkey}}');
 357  
 358              return count($this->row->recipients);
 359          }
 360  
 361          if (is_email($this->args->toemail))
 362          {
 363              $this->mail->external_recipient = true;
 364              $this->get_external_recipient();
 365              return 1;
 366          }
 367  
 368          return false;
 369      }
 370  
 371  	function get_recipients($query)
 372      {
 373          global $wpdb;
 374          $mp_users = $wpdb->get_results( $query );
 375  
 376          $this->row->recipients = array();
 377          if ($mp_users)
 378          {
 379              foreach ($mp_users as $mp_user)
 380              {
 381                  $this->row->replacements[$mp_user->email] = $this->get_user_replacements($mp_user);
 382  
 383                  if (isset($this->args->toname)) if (count($mp_users) == 1) $mp_user->name = $this->args->toname;
 384                  if ( empty($mp_user->name) )
 385                      if (self::name_required)
 386                          $this->row->recipients[$mp_user->email]     = trim(str_replace('.', ' ', substr($mp_user->email, 0, strpos($mp_user->email, '@'))));
 387                      else
 388                          $this->row->recipients[]             = $mp_user->email;
 389                  else
 390                      $this->row->recipients[$mp_user->email]         = $mp_user->name;
 391              }
 392          }
 393      }
 394  
 395  	function get_external_recipient()
 396      {
 397          $this->trace->log('MAILPRESS [NOTICE] - :::: external recipient ::::');
 398          $this->row->replacements[$this->args->toemail] = array();
 399  
 400          if (isset($this->args->toname))
 401              if (!empty($this->args->toname))
 402                  $this->row->recipients[$this->args->toemail] = $this->args->toname;
 403              else
 404                  if (self::name_required)
 405                      $this->row->recipients[$this->args->toemail]     = trim(str_replace('.', ' ', substr($this->args->toemail, 0, strpos($this->args->toemail, '@'))));
 406                  else
 407                      $this->row->recipients[] = $this->args->toemail;
 408          else
 409              $this->row->recipients[] = $this->args->toemail;
 410      }
 411  
 412  	function get_old_recipients()
 413      {
 414          $this->row->replacements = $this->args->replacements;
 415  
 416          foreach($this->row->replacements as $email => $v)
 417          {
 418              if (isset($v['{{toname}}']) && !empty($v['{{toname}}']))
 419                  $this->row->recipients[$email] = $v['{{toname}}'];
 420              else
 421              {
 422                  if (!self::name_required)
 423                      $this->row->recipients[] = $email;
 424                  else
 425                  {
 426                      $name = trim(str_replace('.', ' ', substr($email, 0, strpos($email, '@'))));
 427                      $this->row->recipients[$email] = $this->row->replacements[$email]['{{toname}}'] =  $name;
 428                  }
 429              }
 430          }
 431      }
 432  
 433  	function get_user_replacements($mp_user)
 434      {
 435          if (!$mp_user) return array();
 436  
 437          if (is_numeric($mp_user))
 438          {
 439              $mp_user = MP_User::get($mp_user);
 440              if (!$mp_user) return array();
 441          }
 442  
 443          $replacements = MP_User_meta::get_replacements($mp_user->id);
 444  
 445          $replacements ['{{toemail}}']    = $mp_user->email;
 446          $replacements ['{{toname}}']    = $mp_user->name;
 447          $replacements ['{{_user_id}}']= $mp_user->id;
 448  
 449      // always last //
 450          $replacements ['{{_confkey}}']= $mp_user->confkey;
 451          return $replacements;
 452      }
 453  
 454  	function replace_mail_urls()
 455      {
 456          $r = array();
 457          if (isset($this->args->viewhtml))     $r['{{viewhtml}}']     = $this->args->viewhtml;
 458          if (isset($this->args->subscribe))    $r['{{subscribe}}']     = $this->args->subscribe;
 459          if (isset($this->args->unsubscribe))$r['{{unsubscribe}}']     = $this->args->unsubscribe;
 460  
 461          foreach($r as $k => $v)
 462          {
 463              $this->row->subject     = str_replace($k, $v, $this->row->subject, $cs);
 464              $this->row->plaintext     = str_replace($k, $v, $this->row->plaintext, $cp);
 465              $this->row->html         = str_replace($k, $v, $this->row->html, $ch);
 466          }
 467      }
 468  
 469   // plaintext, html //
 470  
 471  	function build_mail_content($type, $filter=false)
 472      {
 473          $this->build = new stdClass();
 474          $this->build->plaintext = ('plaintext' == $type);
 475          $this->build->filter = $filter;
 476  
 477          if (!isset($this->mail)) $this->mail = new stdClass();
 478          $this->mail->theme = $this->mail->themedir = $this->mail->template = null;
 479  
 480      // find the theme and themedir //
 481  
 482          $this->mail->theme     = $this->theme->themes[$this->theme->current_theme]['Stylesheet'];
 483          $this->mail->themedir    = $this->theme->themes[$this->theme->current_theme]['Stylesheet Dir'];
 484          if (isset($this->args->Theme) && !empty($this->args->Theme))
 485          {
 486              $x = $this->theme->get_theme_by_stylesheet($this->args->Theme);
 487              if (!empty($x))
 488              {
 489                  $this->theme->current_theme     = $x['Name'];
 490                  $this->mail->theme        = $this->args->Theme;
 491                  $this->mail->themedir        = $x['Stylesheet Dir'];
 492              }
 493              elseif (isset($this->trace)) $this->trace->log(sprintf('MAILPRESS [WARNING] - Missing theme : >> %1$s << Type : %2$s ', $this->args->Theme, $type), $this->trace->levels[512]);
 494          }
 495  
 496      // find the template //
 497  
 498          $template_name = '';
 499          $pt = $this->theme->get_page_templates($this->mail->theme, $this->build->plaintext);
 500  
 501          $this->build->stylesheetpath  = ABSPATH . $this->theme->themes[$this->theme->current_theme] [ ( ($this->build->plaintext) ? 'Plaintext Stylesheet Dir' : 'Stylesheet Dir' ) ] . '/' ;
 502          $this->build->templatepath    = ABSPATH . $this->theme->themes[$this->theme->current_theme] [ ( ($this->build->plaintext) ? 'Plaintext Template Dir'   : 'Template Dir' ) ]   . '/' ;
 503          if ($this->build->plaintext)
 504                      if ( $t = $this->theme->get_theme_by_stylesheet('plaintext') ) $this->build->plaintextpath = ABSPATH . $t['Stylesheet Dir'] . '/';
 505                      elseif (isset($this->trace)) $this->trace->log('MAILPRESS [ERROR] - Missing theme : plaintext theme has been deleted.', $this->trace->levels[512]);
 506          $this->build->dir         = $this->build->stylesheetpath;
 507  
 508          if (isset($this->args->Template) && isset($pt[$this->args->Template])) $template_name = $this->locate_template($pt[$this->args->Template]['file']);
 509          if (empty($template_name)) $template_name = $this->locate_template(); // call default.php //
 510          else $this->mail->template = $this->args->Template;
 511  
 512      // build the content //
 513  
 514          $content = '';
 515      // call functions.php //
 516          foreach($this->get_template_paths('functions.php', true) as $file)
 517              if (is_file($file)) $content .= "<?php require_once ('{$file}'); ?>";
 518      // call any start action after functions.php //
 519          $content .= "<?php do_action('MailPress_build_mail_content_start', '$type');?>";
 520      // call template or default //
 521          $content .= (is_file($template_name)) ? '<?php $this->load_template(\'' . $template_name . '\'); ?>' : '<?php $this->get_header(); $this->the_content(); $this->get_footer(); ?>';
 522          $content .= "<?php do_action('MailPress_build_mail_content_end', '$type');?>";
 523  
 524      // build the mail //
 525          $x = $this->do_eval($content);
 526  
 527          unset($this->build);
 528          return ( '<br />' == trim($x) ) ? '' : trim($x);
 529      }
 530  
 531  	function do_eval($x)
 532      {
 533          $x = 'global $posts, $post, $wp_did_header, $wp_did_template_redirect, $wp_query, $wp_rewrite, $wpdb, $wp_version, $wp, $id, $comment, $user_ID; ?>' . "\n $x";
 534          ob_start();
 535              echo(eval($x));
 536              $r = ob_get_contents();
 537          ob_end_clean();
 538          return $r;
 539      }
 540  
 541  
 542  ////  Send it  ////
 543  
 544  
 545  	function swift_processing()
 546      {
 547          require_once  (MP_ABSPATH . 'mp-includes/Swiftmailer/swift_required.php');
 548  
 549      // Swift message //
 550          try 
 551          {
 552              $this->build_swift_message();
 553          }
 554          catch (Swift_SwiftException $e) 
 555          {
 556              $this->trace->log('SWIFTMAILER [ERROR] - ' . "There was an unexpected problem building the mail:\n\n" . $e->getMessage() . "\n\n");    
 557              return false;
 558          }
 559  
 560      // Swift connection //
 561  
 562          if ($this->mail->mailpress_batch_spool_send)         new MP_Connection_spool();
 563          if (!has_filter('MailPress_Swift_Connection_type'))     new MP_Connection_smtp();
 564  
 565          try 
 566          {
 567              $Swift_Connection_type = apply_filters('MailPress_Swift_Connection_type', null);
 568  
 569              $conn = apply_filters('MailPress_Swift_Connection_' . $Swift_Connection_type , $this->row->id, $this->trace );
 570  
 571              $this->swift = Swift_Mailer::newInstance($conn);
 572          }
 573          catch (Swift_SwiftException $e) 
 574          {
 575              $this->trace->log('SWIFTMAILER [ERROR] - ' . "There was a problem connecting with $Swift_Connection_type :\n\n" . $e->getMessage() . "\n\n");    
 576              $this->mysql_connect(__CLASS__ . ' connect error :  ' . $Swift_Connection_type);
 577              return false;
 578          } 
 579  
 580          Swift_Preferences::getInstance()->setTempDir(MP_ABSPATH . "tmp")->setCacheType('disk');
 581  
 582      // Swift sending ... //
 583          try 
 584          {
 585              $this->swift = apply_filters('MailPress_swift_registerPlugin', $this->swift);
 586          // batch processing //
 587              if ($this->mail->mailpress_batch_send)
 588                  return apply_filters('MailPress_swift_send', $this);
 589  
 590              $this->mysql_disconnect(__CLASS__);
 591  
 592          // swift batchSend //
 593              if ($this->mail->swift_batchSend)
 594              {
 595                  $this->swift->registerPlugin(new Swift_Plugins_DecoratorPlugin($this->row->replacements));
 596                  if (!$this->swift_batchSend())
 597                  {
 598                      $this->mysql_connect(__CLASS__ . ' batchSend');
 599                      return false;
 600                  }
 601              }
 602  
 603          // swift send //
 604              else
 605              {
 606                  if (!$this->swift->send($this->message)) 
 607                  {
 608                      $this->mysql_connect(__CLASS__ . ' send');
 609                      return false;
 610                  }
 611              }
 612          }
 613          catch (Swift_SwiftException $e) 
 614          {
 615              $this->trace->log('SWIFTMAILER [ERROR] - ' . "There was a problem sending with $Swift_Connection_type :\n\n" . $e->getMessage() . "\n\n");    
 616              $this->mysql_connect(__CLASS__ . ' sending error : ' . $Swift_Connection_type);
 617              return false;
 618          }
 619  
 620          $this->mysql_connect(__CLASS__);
 621                          
 622          if ($this->mail->mailpress_batch_spool_send) do_action('MailPress_schedule_batch_spool_send');
 623  
 624          return true;
 625      }
 626  
 627  	function swift_batchSend(&$failedRecipients = null)
 628      {
 629          $this->message->setCc(array());
 630          $this->message->setBcc(array());
 631  
 632          $sent = 0;
 633  
 634          foreach ($this->message->getTo() as $address => $name)
 635          {
 636              $this->message->setTo(array($address => $name));
 637              $sent += $this->swift->send($this->message, $failedRecipients);
 638          }
 639  
 640          return $sent;
 641      }
 642  
 643  	function build_swift_message()
 644      {
 645  
 646      // charset //
 647          Swift_Preferences::getInstance()->setCharset($this->row->charset);
 648  
 649      // message //
 650          $this->message      = Swift_Message::newInstance();
 651  
 652          //$this->message->setLanguage(substr(WPLANG, 0, 2));
 653          if (self::get8BitEncoding) $this->message->setEncoder(Swift_Encoding::get8BitEncoding());
 654  
 655      // from //
 656          $this->message->setFrom(array($this->row->fromemail => $this->row->fromname));
 657  
 658      // to & replacements //
 659          if (!$this->mail->swift_batchSend) 
 660          {
 661              try
 662              {
 663                  $this->message->addTo($this->row->toemail, $this->row->toname);
 664              }
 665              catch (Swift_RfcComplianceException $e)
 666              {
 667                  $this->trace->log('SWIFTMAILER [ERROR] - ' . "Recipient do not comply RFC rules (discarded) :\n\n" . $e->getMessage() . "\n\n");
 668                  return false;
 669              }
 670          }
 671          else
 672          {
 673              foreach($this->row->recipients as $toemail => $toname)
 674              {
 675                  try
 676                  {
 677                      $this->message->addTo($toemail, $toname);
 678                  }
 679                  catch (Swift_RfcComplianceException $e)
 680                  {
 681                      $this->trace->log('SWIFTMAILER [WARNING] - ' . "Recipient do not comply RFC rules (discarded) :\n\n" . $e->getMessage() . "\n\n");    
 682                      unset($this->row->replacements[$toemail]);
 683                  }
 684              }
 685              foreach($this->row->replacements as $k => $v) $this->row->replacements[$k] = array_merge($this->mail->replacements, $this->row->replacements[$k]);
 686          }
 687  
 688      // subject //
 689          $this->message->setSubject($this->row->subject);
 690  
 691      // filter headers //
 692          $this->message    = apply_filters('MailPress_swift_message_headers', $this->message, $this->row);
 693  
 694      // html //
 695          if ($this->row->html)
 696          {
 697              $this->message->setBody($this->process_img( $this->row->html, $this->row->themedir ), 'text/html');
 698          }
 699  
 700      // plaintext //
 701          if ($this->row->plaintext)
 702          {
 703              if ($this->row->html)
 704                  $this->message->addPart($this->row->plaintext);
 705              else
 706                  $this->message->setBody($this->row->plaintext);
 707          }
 708  
 709      // attachements //
 710          $metas = MP_Mail_meta::has( $this->row->id, '_MailPress_attached_file');
 711          if ($metas)
 712          {
 713              foreach($metas as $meta)
 714              {
 715                  $meta_value = unserialize( $meta['meta_value'] );
 716                  if (!is_file($meta_value['file_fullpath'])) continue;
 717                  $this->message->attach(Swift_Attachment::fromPath($meta_value['file_fullpath'], $meta_value['mime_type'])->setFilename($meta_value['name']));
 718              }
 719          }
 720      }
 721  
 722  	function process_img($html, $path, $dest='mail')
 723      {
 724          $x        = $matches = $imgtags = array();
 725          $masks     = array ('', $path . '/images/', $path . '/');
 726  
 727          $keepurl    = apply_filters('MailPress_img_mail_keepurl', false);
 728  
 729          $siteurl     = site_url() . '/';
 730          $fprefix     = ('mail' == $dest) ? ABSPATH : $siteurl;
 731  
 732          $output = preg_match_all('/<img[^>]*>/Ui', $html, $imgtags, PREG_SET_ORDER); // all img tag
 733  
 734          if (empty($imgtags)) return $html;
 735  
 736          foreach ($imgtags as $imgtag)
 737          {
 738              $output = preg_match_all('/src=[\'"]([^\'"]+)[\'"]/Ui', $imgtag[0], $src, PREG_SET_ORDER); // for src attribute
 739              $matches[] = array(0 => $imgtag[0], 1 => $src[0][1]);
 740          }
 741  
 742          $imgs = array();
 743          foreach ($matches as $match)
 744          {
 745              $f = $u = false;
 746  
 747              if (!MP_::is_image($match[1])) continue;
 748  
 749              if ( $keepurl && stristr($match[1], $siteurl) )
 750              {
 751                  $imgs[$match[1]] = $match[1];
 752                  continue;
 753              }
 754              elseif (stristr($match[1], $siteurl)) $u = true;
 755              elseif ((stristr($match[1], 'http://')) || (stristr($match[1], 'https://')))
 756              {
 757                  $imgs[$match[1]] = $match[1];
 758                  continue;
 759              }
 760  
 761              foreach ($masks as $mask)
 762              {
 763                  if ($u)     $file = str_ireplace($siteurl, '', $match[1]);
 764                  else        $file = $mask . $match[1];
 765  
 766                  if (is_file(ABSPATH . $file)) 
 767                  {
 768                      $f = true;
 769                      $x[$match[1]] = $fprefix . $file;        // we can have the src/url image in different img tags ... so we embed it one time only
 770                      if (isset($this->trace)) if ('mail' == $dest) $this->trace->log('MAILPRESS [NOTICE] - Image found : ' . $file, $this->trace->levels[512]);
 771                  }
 772                  if ($f) break;
 773                  
 774              }
 775          }
 776  
 777          if ('mail' == $dest)
 778          {
 779              foreach ($x as $key => $file)
 780              {
 781                  try 
 782                  {
 783                      $imgs[$key] = $this->message->embed(Swift_Image::fromPath($file));
 784                  }
 785                  catch (Swift_SwiftException $e) 
 786                  {
 787                      if (isset($this->trace)) $this->trace->log('SWIFTMAILER [ERROR] - ' . "There was a problem with this image: $file \n\n" . $e->getMessage() . "\n\n");
 788                  } 
 789              }
 790          }
 791          else
 792          {
 793              foreach ($x as $key => $file)
 794              {
 795                  $imgs[$key] = $file;
 796              }
 797          }
 798          foreach ($matches as $match)
 799          {
 800              $match[3]    = (isset($imgs[$match[1]])) ? str_replace($match[1], $imgs[$match[1]], $match[0]) : $match[0]; // and we retrieve it now with the proper <img ... />
 801              if ('html' != $dest) $match[3] = apply_filters('MailPress_img_mail', $match[3]); // apply_filters for 'mail', 'draft'
 802              $html        = str_replace($match[0], $match[3], $html);
 803          }
 804          return $html;
 805      }
 806  
 807  /// DISPLAYING MAILS ///
 808  
 809  
 810  	function get_replacements($id, $main_id = false, $mp_user_id = false)
 811      {
 812          $mail_r = MP_Mail_meta::get( $id, '_MailPress_replacements' );
 813          if (!$mail_r && $main_id) $mail_r = MP_Mail_meta::get( $main_id, '_MailPress_replacements' );
 814          if (!$mail_r) $mail_r = array();
 815  
 816          if (!$mp_user_id) return $mail_r;
 817  
 818          $mail = MP_Mail::get($id);
 819  
 820          if (!$mail) return $mail_r;
 821          if (is_email($mail->toemail)) return $mail_r;
 822  
 823          $mail->toemail = unserialize($mail->toemail);
 824  
 825          $mp_user = MP_User::get($mp_user_id);
 826  
 827          if (!$mp_user) return $mail_r;
 828          if (!isset($mail->toemail[$mp_user->email])) return $mail_r;
 829  
 830          return array_merge($mail_r, $mail->toemail[$mp_user->email]);
 831      }
 832  
 833  	function viewsubject($subject, $id, $main_id, $mp_user_id = false)
 834      {
 835          $replacements = $this->get_replacements($id, $main_id, $mp_user_id);
 836          foreach($replacements as $k => $v) 
 837              $subject = str_replace($k, $v, $subject, $ch);
 838          return $subject;
 839      }
 840  
 841  	function view($args)
 842      {
 843          $defaults = array( 'type' => 'html', 'id' => 0, 'main_id' => 0, 'theme' => 0, 'template' => 0, 'mp_user_id' => 0 );
 844          $r = wp_parse_args( $args, $defaults );
 845          extract( $r );
 846  
 847          $x = MP_Mail::get($id);
 848          $y = array('sent', 'unsent', 'archived');
 849          if (!in_array($x->status, $y))
 850          {
 851              $this->args         = new stdClass();
 852              $this->args->id        = $id;
 853              $this->args->main_id    = $main_id;
 854  
 855              if ($theme)         $this->args->Theme = $theme;
 856              if ($template)         $this->args->Template = $template;
 857  
 858              if (!isset($this->row)) $this->row = new stdClass();
 859              $this->row->subject     = $x->subject;
 860  
 861              $this->args->{$type}     = $x->{$type};
 862              $x->{$type}         = $this->build_mail_content($type, ('html' == $type) ? 'the_content' : false);
 863              $x->themedir         = $this->mail->themedir;
 864          }
 865          $$type = ('html' == $type)? $this->process_img($x->html, $x->themedir, 'draft') : $x->plaintext;
 866  
 867          $replacements = $this->get_replacements($id, $main_id, $mp_user_id);
 868          foreach($replacements as $k => $v) $$type = str_replace($k, $v, $$type, $ch);
 869  
 870          include MP_ABSPATH . "mp-includes/html/{$type}.php";
 871      }
 872  
 873  /// Get & Status ///
 874  
 875  	public static function get($mail, $output = OBJECT) 
 876      {
 877          switch (true)
 878          {
 879              case ( empty($mail) ) :
 880                  if ( isset($GLOBALS['mp_mail']) )     $_mail = & $GLOBALS['mp_mail'];
 881                  else                        return null;
 882              break;
 883              case ( is_object($mail) ) :
 884                  wp_cache_add($mail->id, $mail, 'mp_mail');
 885                  $_mail = $mail;
 886              break;
 887              default :
 888                  if ( isset($GLOBALS['mp_mail']) && ($GLOBALS['mp_mail']->id == $mail) ) 
 889                  {
 890                      $_mail = & $GLOBALS['mp_mail'];
 891                  } 
 892                  elseif ( ! $_mail = wp_cache_get($mail, 'mp_mail') ) 
 893                  {
 894                      global $wpdb;
 895                      $_mail = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->mp_mails WHERE id = %d LIMIT 1", $mail));
 896                      if ($_mail) wp_cache_add($_mail->id, $_mail, 'mp_mail');
 897                  }
 898              break;
 899          }
 900  
 901          if ( $output == OBJECT ) {
 902              return $_mail;
 903          } elseif ( $output == ARRAY_A ) {
 904              return get_object_vars($_mail);
 905          } elseif ( $output == ARRAY_N ) {
 906              return array_values(get_object_vars($_mail));
 907          } else {
 908              return $_mail;
 909          }
 910      }
 911  
 912  	public static function get_id($from = 'inconnu')
 913      {
 914          $wp_user = 
 915  
 916          $data = $format = array();
 917  
 918          $data['status']         = '';                     $format[] = '%s';
 919          $data['created']         = current_time( 'mysql' );        $format[] = '%s';
 920          $data['created_user_id']= MP_WP_User::get_id();            $format[] = '%d';
 921          // longtext
 922          $data['toemail']         = '';                     $format[] = '%s';
 923          $data['html']         = '';                     $format[] = '%s';
 924          $data['plaintext']     = '';                     $format[] = '%s';
 925  
 926          global $wpdb;
 927          $wpdb->insert($wpdb->mp_mails, $data, $format);
 928  
 929          return $wpdb->insert_id;
 930      }
 931  
 932  	public static function get_var($var, $key_col, $key, $format = '%s') 
 933      {
 934          global $wpdb;
 935          return $wpdb->get_var( $wpdb->prepare("SELECT $var FROM $wpdb->mp_mails WHERE $key_col = $format LIMIT 1;", $key) );
 936      }
 937  
 938  	public static function get_status($id) 
 939      {
 940          $result = self::get_var('status', 'id', $id);
 941          return ($result == NULL) ? self::status_deleted : $result;
 942      }
 943  
 944  	public static function update_status($id, $status)
 945      {
 946          wp_cache_delete($id, 'mp_mail');
 947  
 948          $data = $format = $where = $where_format = array();
 949  
 950          $data['status']             = $status;                             $format[] = '%s';
 951  
 952          $where['id']             = (int) $id;                        $where_format[] = '%d';
 953  
 954          global $wpdb;
 955          return $wpdb->update( $wpdb->mp_mails, $data, $where, $format, $where_format );
 956      }
 957  
 958  	public static function set_status($id, $status) 
 959      {
 960          switch($status) 
 961          {
 962              case 'sent':
 963                  if ('archived' == self::get_status($id)) return self::update_status($id, 'sent');
 964                  return false;
 965              break;
 966              case 'archived':
 967                  if ('sent' == self::get_status($id)) return self::update_status($id, 'archived');
 968                  return false;
 969              break;
 970              case 'paused':
 971                  if ('unsent' == self::get_status($id)) return self::update_status($id, 'paused');
 972                  return false;
 973              break;
 974              case 'unsent':
 975                  if ('paused' == self::get_status($id)) return self::update_status($id, 'unsent');
 976                  return false;
 977              break;
 978              case 'delete':
 979                  return self::delete($id);
 980              break;
 981          }
 982          wp_cache_delete($id, 'mp_mail');
 983          return true;
 984      }
 985  
 986  	public static function delete($id)
 987      {
 988          global $wpdb;
 989          do_action('MailPress_delete_mail', $id);
 990  
 991          $metas = MP_Mail_meta::has( $id, '_MailPress_mail_revisions' );
 992          if ($metas) {
 993              foreach($metas as $meta) {
 994                  foreach(maybe_unserialize($meta['meta_value']) as $rev_id) {
 995                      $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->mp_mails WHERE id = %d ; ", $rev_id ) );
 996          }}}
 997          wp_clear_scheduled_hook( 'mp_process_send_draft', array( $id ) );
 998  
 999          MP_Mail_meta::delete( $id );
1000  
1001          wp_cache_delete($id, 'mp_mail');
1002  
1003          return $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->mp_mails WHERE id = %d ; ", $id ) );
1004      }
1005  
1006  
1007  /// DISPLAYING E-MAILS & NAMES ///
1008  
1009  	public static function display_toemail($toemail, $toname, $tolist='', $selected=false)
1010      {
1011          $return = '';
1012          $draft_dest = MP_User::get_mailinglists();
1013  
1014          if         (!empty($tolist)  && isset($draft_dest[$tolist]))    return "<b>" . $draft_dest[$tolist] . "</b>"; 
1015          elseif     (!empty($toemail) && isset($draft_dest[$toemail]))    return "<b>" . $draft_dest[$toemail] . "</b>"; 
1016          elseif     (is_email($toemail))
1017          {
1018                  return self::display_name_email($toname, $toemail);
1019          }
1020          else
1021          {
1022              $y = unserialize($toemail);
1023              unset($y['MP_Mail']);
1024              if (is_array($y))
1025              {
1026                  $return = $s = '';
1027                  foreach ($y as $k => $v)
1028                  {
1029                      if ((int) $selected == (int) $v['{{_user_id}}']) $s = ' selected="selected"';
1030                      $return .= "<option$s>$k</option>";
1031                      if (!empty($s)) $selected = -1;
1032                      $s = '';
1033                  }
1034                  $selected = ($selected == -1) ? ' disabled="disabled"' : '';
1035                  $return = "<select{$selected}>{$return}</select>";
1036                  return $return;
1037              }
1038          }
1039          return false;
1040      }
1041  
1042  	public static function display_name_email($name, $email)
1043      {
1044          if (empty($name)) return $email;
1045          return self::display_name(esc_attr($name), false) . " &lt;$email&gt;";
1046      }
1047  
1048  	public static function display_name($name, $for_mail = true)
1049      {
1050          $default = '_';
1051          if ( is_email($name) )    $name = trim(str_replace('.', ' ', substr($name, 0, strpos($name, '@'))));
1052          if ( $for_mail ) 
1053          { if ( empty($name) )     $name = $default; }
1054          else
1055          { if ($default == $name)$name = '';}
1056          return $name;                                    
1057      }
1058  
1059  //// attachements
1060  
1061  	public static function get_attachement_link($meta, $mail_status)
1062      {
1063          $meta_value = unserialize( $meta['meta_value'] );
1064          $href = esc_url(add_query_arg( array('action' => 'attach_download', 'id' => $meta['meta_id']), MP_Action_url ));
1065  
1066          if (in_array($mail_status, array('sent', 'archived')))
1067          {
1068              if (is_file($meta_value['file_fullpath']))
1069              {
1070                  return "<a href='" . $href . "' style='text-decoration:none;'>" . $meta_value['name'] . "</a>";
1071              }
1072              else
1073              {
1074                  return "<span>" . $meta_value['name'] . "</span>";
1075              }
1076          }
1077          else
1078          {
1079              if (is_file($meta_value['file_fullpath']))
1080              {
1081                  return "<a href='" . $href . "' style='text-decoration:none;'>" . $meta_value['name'] . "</a>";
1082              }
1083          }
1084      }
1085  }


Generated: Thu Apr 28 18:38:52 2016 Cross-referenced by PHPXref 0.7.1