Xataface Email Module  0.3.2
Email/Mailmerge Module for Xataface
 All Data Structures Files Functions Variables Pages
email.php
Go to the documentation of this file.
1 <?php
2 /*-------------------------------------------------------------------------------
3  * Xataface Web Application Framework
4  * Copyright (C) 2005-2008 Web Lite Solutions Corp (shannah@sfu.ca)
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *-------------------------------------------------------------------------------
20  */
21 
22 
34 
35  var $messages = array();
40 
44  function handle(&$params){
45  $action =& $params['action'];
46  //print_r($params);
47  $app =& Dataface_Application::getInstance();
48  $query =& $app->getQuery();
49  $query['-skip'] = 0;
50  $query['-limit'] = 9999999;
51 
52  // Let's validate some of the parameters first
53 
54  // The actions.ini file should define an email_column and email_table parameters
55  // to indicate:
56  // a. the name of the column from the current table that should be used
57  // as the "send to" email address.
58  // b. the name of the table that should store the email messages.
59 
60 
61  import('Dataface/Ontology.php');
62  Dataface_Ontology::registerType('Person', 'Dataface/Ontology/Person.php', 'Dataface_Ontology_Person');
63  $ontology =& Dataface_Ontology::newOntology('Person', $query['-table']);
64  $action['email_column'] = $ontology->getFieldname('email');
65 
66 
67 
68  if ( !@$action['email_column'] ) return PEAR::raiseError("No email column specified in actions.ini", DATAFACE_E_WARNING);
69  if ( !@$action['email_table'] ) return PEAR::raiseError("No email table specified in actions.ini", DATAFACE_E_WARNING);
70 
71  // Make sure the table and column names are not malicious.
72  $this->emailColumn = $col = $action['email_column'];
73  if ( strpos($col, '`') !== false ) return PEAR::raiseError("Invalid email column name: '$col'", DATAFACE_E_WARNING);
74 
75  $this->emailTable = $table = 'xataface__email_newsletters';//$action['email_table'];
76  if ( strpos($table, '`') !== false ) return PEAR::raiseError("Invalid email table name: '$table'", DATAFACE_E_WARNING);
77 
78  $this->joinTable = $join_table = 'xataface__email_log';//$query['-table'].'__email';
79  $join_table = $this->joinTable;
80  $this->recipientsTable = $query['-table'];
81  // The name of the table that tracks which records have had email sent.
82 
83  // Next make sure that the email table(s) exist(s)
84  if ( !Dataface_Table::tableExists($table, false) || !Dataface_Table::tableExists($join_table, false) ){
85  $this->createEmailTables($table, $join_table);
86  }
87 
88  $emailTableObj =& Dataface_Table::loadTable($this->emailTable);
89  $contentField =& $emailTableObj->getField('content');
90  $contentField['widget']['atts']['rows'] = 20;
91  $contentField['widget']['atts']['cols'] = 60;
92  $contentField['widget']['label'] = 'Message body';
93  $contentField['widget']['description'] = 'Please enter your message content in plain text.';
94  $contentField['widget']['type'] = 'ckeditor';
95  $contentField['widget']['ckeditor']['toolbar'] = 'XBasic';
96  $contentField['widget']['ckeditor']['extraPlugins'] = 'SchemaBrowser';
97  //$contentField['widget']['atts']['data-xf-schemabrowser-tablename'] = $query['-table'];
98  Dataface_JavascriptTool::getInstance()->import('xataface/modules/ckeditor/plugins/SchemaBrowser.js');
99 
100  //$contentField['widget']['editor'] = 'ckeditor';
101 
102  $subjectField =& $emailTableObj->getField('subject');
103  $subjectField['widget']['atts']['size'] = 60;
104 
105  $fromField =& $emailTableObj->getField('from');
106  $fromField['widget']['atts']['size'] = 60;
107  $fromField['widget']['description'] = 'e.g. Web Lite Solutions &lt;info@weblite.ca&gt;';
108 
109 
110  $ccField =& $emailTableObj->getField('cc');
111  $ccField['widget']['atts']['size'] = 60;
112  $ccField['widget']['label'] = 'Bcc';
113  $ccField['widget']['description'] = 'e.g. youremail@example.com. Attention: Copies of every email sent in this batch will be sent to this bcc address if added. This may result in quite a large number of emails being sent to this single address. Use this feature carefully.';
114 
115  $ignoreBlacklistField =& $emailTableObj->getField('ignore_blacklist');
116  $ignoreBlacklistField['widget']['type'] = 'checkbox';
117  $ignoreBlacklistField['widget']['description'] = 'The black list is a list of email addresses that have opted out of receiving email. I.e. Users on the black list do not want to receive email. Check this box if you want to send to blacklisted addresses despite their wish to be left alone.';
118 
119 
120  $templateField =& $emailTableObj->getField('template_id');
121  $templateField['widget']['filters']['table_name'] = $query['-table'];
122 
123  $form = df_create_new_record_form($table);
124  $form->_build();
125 
126  $form->addElement('hidden','-action');
127  $form->addElement('hidden','-table');
128  $form->setDefaults(array('-action'=>$query['-action'], '-table'=>$query['-table']));
129  $form->insertElementBefore($form->createElement('checkbox', 'send_now', '','Send now (leave this box unchecked if you wish these emails to be queued for later sending by the daily cron job. Recommended to leave this box unchecked for large found sets (&gt;100 records).)'),'submit_new_newsletters_record');
130  $form->addElement('hidden', '-query_string');
131  $form->setDefaults(array('-query_string'=>base64_encode(serialize($query))));
132  $form->setSubmitLabel("Add to Mail Queue");
133  if ( @$app->_conf['from_email'] ){
134  $form->setDefaults(array('from'=>$app->_conf['from_email']));
135  }
136 
137 
138 
139  if ( $form->validate() ){
140  $res = $form->process(array(&$form,'save'), true);
141  if ( PEAR::isError($res) ) return $res;
142 
143  // The form saved ok.. so we can send the emails.
144  $vals = $form->exportValues();
145  $q2 = unserialize(base64_decode($vals['-query_string']));
146  $qb = new Dataface_QueryBuilder($query['-table'], $q2);
147  $recTable = Dataface_Table::loadTable($query['-table']);
148 
149  $tkeys = $recTable->keys();
150  $keyCol = null;
151  foreach ($tkeys as $key=>$val){
152  $keyCol = $key;
153  break;
154  }
155  $sql = "insert ignore into `$join_table` (recipient_email,messageid,date_created,primary_key) select distinct (`".$col."`) `".$col."`, '".$form->_record->val('id')."' as messageid, now() as date_created, `".$keyCol."` as primary_key ".$qb->_from()." ".$qb->_secure($qb->_where());
156 
157  //echo $sql;exit;
158  $sres = df_q($sql);
159 
160 
161  //if ( !$sres ) trigger_error(mysql_error(df_db()), E_USER_ERROR);
162  $jobId = $this->postJob($form->_record->val('id'), $this->emailTable, $this->joinTable, $this->recipientsTable, $this->emailColumn);
163  $q2['-action'] = 'email_progress';
164  $q2['-job-id'] = $jobId;
165  unset($q2['-limit']);
166  header('Location: '.$app->url($q2).'&--msg='.urlencode("The message has been queued for delivery"));
167  exit;
168 
169 
170  }
171 
172  $addresses = array();
173 
174  ob_start();
175  $form->display();
176  $context = array();
177  $context['email_form'] = ob_get_contents();
178  $profileTable =& Dataface_Table::loadTable($query['-table']);
179 
180  $context['fields'] = array_keys($profileTable->fields(false,true,true));
181  $modurl = DATAFACE_SITE_URL.'/modules/Email';
182  if ( realpath(__FILE__) == realpath(DATAFACE_PATH.'/modules/Email/email.php') ){
183  $modurl = DATAFACE_URL.'/modules/Email';
184  }
185 
186  $context['EMAIL_ROOT'] = $modurl;
187 
188  ob_end_clean();
189  df_register_skin('email', dirname(__FILE__).'/../templates');
190  df_display($context, 'email_form.html');
191 
192 
193  }
194 
195  function isBlackListed($email){
196  $app = Dataface_Application::getInstance();
197  $method = 'Email__isBlackListed';
198  $del = $app->getDelegate();
199  if ( isset($del) and method_exists($del, $method) ){
200  $res = $del->$method($email);
201  if ( isset($res) and is_bool($res) ){
202  return $res;
203  }
204  }
205  if ( !Dataface_Table::tableExists('dataface__email_blacklist') ) $this->createEmailTables(null,null);
206  $res = mysql_query("select email from dataface__email_blacklist where email='".addslashes($email)."' limit 1", df_db());
207  if ( !$res ) trigger_error(mysql_error(df_db()), E_USER_ERROR);
208  list($num) = mysql_fetch_row($res);
209  @mysql_free_result($res);
210  return $num;
211  }
212 
213  function getBlackListed($emails){
214  if ( !Dataface_Table::tableExists('dataface__email_blacklist') ) $this->createEmailTables(null,null);
215  if ( !is_array($emails) ) $emails = array($emails);
216  $res = mysql_query("select email from dataface__email_blacklist where email in ('".implode("','", array_map('addslashes',$emails))."')", df_db());
217  $out = array();
218  if (!$res ) trigger_error(mysql_error(df_db()), E_USER_ERROR);
219  while ($row = mysql_fetch_row($res) ) $out[] = $row[0];
220  @mysql_free_result($res);
221  return $out;
222  }
223 
232  function createEmailTables($tablename, $join_table){
233  $app =& Dataface_Application::getInstance();
234 
235  $sql = array();
236  if ( isset($tablename) ){
237  $sql[] = "create table if not exists `{$tablename}` (
238  `id` int(11) not null auto_increment,
239  `template_id` int(11) default null,
240  `subject` varchar(128) not null,
241  `cc` varchar(128) default null,
242  `from` varchar(128) default null,
243  `content` text,
244  `ignore_blacklist` tinyint(1) default 0,
245  posted_by varchar(255) default null,
246  primary key (`id`)) DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
247  }
248  if ( isset($join_table) ){
249  $sql[] = "create table if not exists `{$join_table}` (
250  `messageid` int(11) not null,
251  `recipient_email` varchar(128) not null,
252  `sent` tinyint(1) default 0,
253  `date_created` datetime default null,
254  `date_sent` datetime default null,
255  `success` tinyint(1) default null,
256  `comment` varchar(255) default null,
257  primary key (`messageid`,`recipient_email`))";
258  }
259 
260 
261  $sql[] = "create table if not exists `dataface__email_blacklist` (
262  `email` varchar(255) not null primary key
263  )";
264 
265  foreach ($sql as $q ){
266  $res = mysql_query($q, $app->db());
267  if ( !$res ) trigger_error(mysql_error($app->db()), E_USER_ERROR);
268  }
269 
270  try {
271  // The comment field was added in version 2.0... adding it now
272  // just in case there was a legacy table that we are adding to.
273  df_q("alter table `{$join_table}` add `comment` varchar(255) after `success`");
274  } catch (Exception $ex){}
275  return true;
276 
277 
278 
279  }
280 
281 
282  private $_tempRecipientRecord;
288  function _replaceFieldCallback($matches){
289  return $this->_tempRecipientRecord->display($matches[1]);
290  }
291 
292 
293  function getAttachments($emailId){
294  $res = df_q("select file from xataface__email_attachments where email_id='".addslashes($emailId)."'");
295 
296  $out = array();
297 
298  $field =& Dataface_Table::loadTable('xataface__email_attachments')->getField('file');
299  $savepath = $field['savepath'];
300  if ( !$savepath || !is_dir($savepath) ){
301  return array();
302  }
303  $ajaxUploadMod = Dataface_ModuleTool::getInstance()->loadModule('modules_ajax_upload');
304  if ( !$ajaxUploadMod || PEAR::isError($ajaxUploadMod) ){
305  error_log("Could not send attachments because the ajax_upload module is not loaded.");
306  return array();
307  }
308 
309  while ($row = mysql_fetch_row($res) ){
310 
311  $fileName = basename($row[0]);
312  $filePath = $savepath . DIRECTORY_SEPARATOR. $fileName;
313  if ( !file_exists($filePath) ){
314  error_log("Failed to attach file $filePath because it could not be found.");
315  continue;
316  }
317  $contents = file_get_contents($filePath);
318  $mimetype = $ajaxUploadMod->getMimeType($filePath);
319  $attachment = MIME::message($contents, $mimetype, $fileName, 'ISO-8859-1', 'base64', 'attachment');
320  $out[] = $attachment;
321  }
322  @mysql_free_result($res);
323  return $out;
324  }
325 
326 
335  function sendMail($emailId, $emailTable=null, $joinTable = null, $recipientsTable = null , $emailColumn = null){
336  require_once dirname(__FILE__).'/../lib/XPM/MIME.php';
337  if ( isset($emailTable) ) $this->emailTable = $emailTable;
338  if ( isset($joinTable) ) $this->joinTable = $joinTable;
339  if ( isset($recipientsTable) ) $this->recipientsTable = $recipientsTable;
340  if ( isset($emailColumn) ) $this->emailColumn = $emailColumn;
341  $app =& Dataface_Application::getInstance();
342  $conf =& $app->_conf;
343 
344  // We want to be able to override the replacement context
345  // via a delegate class method.
346  $decorateEmailContextFunc = 'decorateEmailContext';
347  $recipientsTableObj = Dataface_Table::loadTable($this->recipientsTable);
348  $recipientsTableDelegate =& $recipientsTableObj->getDelegate();
349  $appDelegate =& $app->getDelegate();
350  $tableDecorateEmailContextFuncExists = (isset($recipientsTableDelegate) and method_exists($recipientsTableDelegate, $decorateEmailContextFunc) );
351 
352  $onSuccessFunc = 'Email__onSuccess';
353  $onSuccessAppFuncExists = (isset($appDelegate) and method_exists($appDelegate, $onSuccessFunc));
354  $onSuccessTableFuncExists = (isset($recipientsTableDelegate) and method_exists($recipientsTableDelegate, $onSuccessFunc) );
355 
356  $onFailFunc = 'Email__onFail';
357  $onFailAppFuncExists = (isset($appDelegate) and method_exists($appDelegate, $onFailFunc));
358  $onFailTableFuncExists = (isset($recipientsTableDelegate) and method_exists($recipientsTableDelegate, $onFailFunc) );
359 
360 
361  $appDecorateEmailContextFuncExists = (isset($appDelegate) and method_exists($appDelegate, $decorateEmailContextFunc));
362  $optOutMessageFunc = 'getEmailOptOutMessage';
363  $appOptOutMessageFuncExists = (isset($appDelegate) and method_exists($appDelegate, $optOutMessageFunc));
364  $tableOptOutMessageFuncExists = (isset($recipientsTableDelegate) and method_exists($recipientsTableDelegate, $optOutMessageFunc));
365 
366  $defaultEmailOptOutHtml= null;
367  $defaultEmailOptOutText = null;
368  if ( @$conf['modules_Email'] ){
369  $emailConf =& $conf['modules_Email'];
370  if ( @$emailConf['opt_out_html'] ){
371  $defaultEmailOptOutHtml = $emailConf['opt_out_html'];
372  }
373  if ( @$emailConf['opt_out_text'] ){
374  $defaultEmailOptOutText = $emailConf['opt_out_text'];
375  }
376  }
377 
378 
379 
380  if ( @$conf['_mail']['func'] ) $mail_func = $conf['_mail']['func'];
381  else $mail_func = 'mail';
382 
383  $emailTableObj =& Dataface_Table::loadTable($this->emailTable);
384 
385  $recTable = Dataface_Table::loadTable($this->recipientsTable);
386 
387  $tkeys = $recTable->keys();
388  $keyCol = null;
389  foreach ($tkeys as $key=>$val){
390  $keyCol = $key;
391  break;
392  }
393 
394  $emailTableObj->addRelationship('recipients',
395  array('__sql__' => 'select * from `'.$this->recipientsTable.'` r inner join `'.$this->joinTable.'` j on (`r`.`'.$this->emailColumn.'` = j.recipient_email and `r`.`'.$keyCol.'`= j.primary_key) inner join `'.$this->emailTable.'` e on e.id = j.messageid where e.id=\''.addslashes($emailId).'\'')
396  );
397 
398 
399  $email = df_get_record($this->emailTable, array('id'=>$emailId));
400  if ( !$email) return PEAR::raiseError("Failed to send email because no message with id {$emailId} could be found.", DATAFACE_E_ERROR);
401 
402  $jres = df_q("select job_id from xataface__email_jobs where email_id='".addslashes($emailId)."'");
403  if ( mysql_num_rows($jres) == 0 ){
404  throw new Exception("Could not find job associated with email.");
405  }
406  list($jobId) = mysql_fetch_row($jres);
407  @mysql_free_result($jres);
408 
409  $template = null;
410  if ( $email->val('template_id') ){
411  $template = df_get_record('xataface__email_templates', array('template_id'=>'='.$email->val('template_id')));
412  }
413 
414  // Let's update the count
415  $totalRecipients = $email->numRelatedRecords('recipients');
416  $res = df_q("update xataface__email_jobs set total_emails='".addslashes($totalRecipients)."' where email_id='".addslashes($emailId)."'");
417 
418 
419  $recipients = $email->getRelatedRecordObjects('recipients', 0,500, 'sent=0');
420  foreach ($recipients as $recipient ){
421 
422 
423  // Check to make sure that job hasn't been cancelled.
424  $jres = df_q("select cancelled from xataface__email_jobs where job_id='".addslashes($jobId)."'");
425  if ( mysql_num_rows($jres) == 0 ){
426  throw new Exception("Could not find job record. Must have been cancelled.");
427  }
428  list($cancelled) = mysql_fetch_row($jres);
429  @mysql_free_result($res);
430  if ( $cancelled ){
431  return false;
432  }
433  //sleep(5);
434 
435 
436  $recipientObj = $recipient->toRecord($this->recipientsTable);
437 
438 
439  //$values = $recipient->strvals();
440  if ( $appDecorateEmailContextFuncExists ){
441  $appDelegate->$decorateEmailContextFunc($email, $template, $recipientObj);
442  }
443 
444  if ( $tableDecorateEmailContextFuncExists ){
445  $recipientsTableDelegate->$decorateEmailContextFunc($email, $template, $recipientObj);
446  }
447 
448 
449 
450 
451  $keys = array();
452  //foreach ($values as $key=>$val) $keys[] = '/%'.$key.'%/';
453  //$values = array_values($values);
454  //$content = preg_replace($keys, $values, $recipient->strval('content'));
455  $this->_tempRecipientRecord = $recipientObj;
456  $content = preg_replace_callback('/\{\$([^\}]+)\}/', array($this, '_replaceFieldCallback'), $recipient->strval('content'));
457 
458  $uniqid = uniqid();
459  df_q("update xataface__email_log set uniqid='".addslashes($uniqid)."' where log_id='".addslashes($recipient->val('log_id'))."'");
460 
461 
462  $opt_out_url = df_absolute_url(DATAFACE_SITE_HREF.'?-action=email_opt_out&email='.urlencode($uniqid));
463 
464  $opt_out_html = <<<END
465  <hr />
466 <p>If you don't want to receive email updates from us, you can opt out of our mailing list by clicking <a href="$opt_out_url">here</a> .</p>
467 END;
468 
469  if ( $defaultEmailOptOutHtml ){
470  $opt_out_html = str_replace('$url', $opt_out_url, $defaultEmailOptOutHtml);
471  }
472 
473  if ( $defaultEmailOptOutText ){
474  $opt_out_text = str_replace('$url', $opt_out_url, $defaultEmailOptOutText);
475  }
476 
477 
478 
479  $opt_out_text = <<<END
480 
481 ------------------------------------------------------------------
482 If you don't want to receive email updates from us, you can opt out of our mailing list by going to $opt_out_url .
483 END;
484 
485 
486  if ( $defaultEmailOptOutText ){
487  $opt_out_text = str_replace('$url', $opt_out_url, $defaultEmailOptOutText);
488  }
489 
490 
491  $opt_out_params = array();
492  if ( $appOptOutMessageFuncExists ){
493  $opt_out_paramsa = $appDelegate->$optOutMessageFunc($recipientObj, $opt_out_url);
494  if ( is_array($opt_out_paramsa) ){
495  $opt_out_params = $opt_out_paramsa;
496  }
497  }
498  if ( $tableOptOutMessageFuncExists ){
499  $opt_out_paramst = $recipientsTableDelegate->$optOutMessageFunc($recipientObj, $opt_out_url);
500  if ( is_array($opt_out_paramst) ){
501  $opt_out_params = array_merge($opt_out_params, $opt_out_paramst);
502  }
503  }
504 
505  if ( @$opt_out_params['html'] ){
506  $opt_out_html = $opt_out_params['html'];
507  }
508 
509  if ( @$opt_out_params['text'] ){
510  $opt_out_text = $opt_out_params['text'];
511  }
512 
513  $html_content = $content . $opt_out_html;
514 
515  $content .= $opt_out_text;
516 
517  $headers = array();
518 
519  if ( trim($email->strval('cc')) ){
520  $headers[] = "Bcc: ".$email->strval('cc');
521  }
522 
523  if ( trim($email->strval('from')) ){
524  $headers[] = "From: ".$email->strval('from');
525  $headers[] = "Reply-to: ".$email->strval('from');
526  }
527 
528  if ( @$app->_conf['mail_host'] ){
529  $headers[] = 'Message-ID: <' . md5(uniqid(time())) . '@'.$app->_conf['mail_host'].'>';
530  }
531  //$headers[] = "Content-Type: text/plain; charset=".$app->_conf['oe'];
532 
533  $joinRecord = $recipient->toRecord($this->joinTable);
534 
535  if ( !trim($recipient->val('recipient_email')) ){
536  $joinRecord->setValue('success',0);
537  $joinRecord->setValue('sent',1);
538  $joinRecord->setValue('comment', 'Blank address');
539  $joinRecord->save();
540 
541  if( $onFailAppFuncExists ){
542  $appDelegate->$onFailFunc($recipientObj, $email);
543  }
544 
545  if ( $onFailTableFuncExists ){
546  $recipientsTableDelegate->$decorateEmailContextFunc($recipientObj, $email);
547  }
548 
549  unset($joinRecord);
550  unset($recipient);
551  continue;
552  }
553 
554 
555  // path to 'MIME.php' file from XPM4 package
556 
557 
558  // get ID value (random) for the embed image
559  $id = MIME::unique();
560 
561  // set text/plain version of message
562  $text = MIME::message(htmlspecialchars_decode(strip_tags(preg_replace(array('/<br[^>]*>/i','/<div[^>]*>/i','/<p[^>]*>/i', '/<table[^>]*>/i'), array("\r\n","\r\n","\r\n","\r\n"),$content))), 'text/plain', null, $app->_conf['oe']);
563  // set text/html version of message
564  $html = MIME::message($html_content, 'text/html', null, $app->_conf['oe']);
565  // add attachment with name 'file.txt'
566  //$at[] = MIME::message('source file', 'text/plain', 'file.txt', 'ISO-8859-1', 'base64', 'attachment');
567  $at = $this->getAttachments($emailId);
568  //$file = 'xpertmailer.gif';
569  // add inline attachment '$file' with name 'XPM.gif' and ID '$id'
570  //$at[] = MIME::message(file_get_contents($file), FUNC::mime_type($file), 'XPM.gif', null, 'base64', 'inline', $id);
571 
572  // compose mail message in MIME format
573  //print_r($html);
574  //print_r($text);
575  //exit;
576  $mess = MIME::compose($text, $html, $at);
577 
578  $le = defined('PHP_EOL') ? PHP_EOL : "\n";
579 
580 
581  if ( !$email->val('ignore_blacklist') and $this->isBlackListed($recipient->val('recipient_email')) ){
582  error_log("\nEmail address '".$recipient->val('recipient_email')."' is black listed so we do not send email to this address...");
583  $joinRecord->setValue('success',0);
584  $joinRecord->setValue('sent',1);
585  $joinRecord->setValue('comment', 'Black listed');
586  df_q("update xataface__email_jobs set sent_emails=sent_emails+1, blacklisted_emails=blacklisted_emails+1 where email_id='".addslashes($emailId)."'");
587 
588  if( $onFailAppFuncExists ){
589  $appDelegate->$onFailFunc($recipientObj, $email);
590  }
591 
592  if ( $onFailTableFuncExists ){
593  $recipientsTableDelegate->$onFailFunc($recipientObj, $email);
594  }
595 
596  }
597 
598  else if ( $mail_func($recipient->strval('recipient_email'), $email->strval('subject'), $mess['content'], implode($le, $headers).$le.$mess['header']) ){
599  $joinRecord->setValue('success',1);
600  $joinRecord->setValue('sent',1);
601  df_q("update xataface__email_jobs set sent_emails=sent_emails+1, successful_emails=successful_emails+1 where email_id='".addslashes($emailId)."'");
602  //echo "Successfully sent email to ".$recipient->val('recipient_email');
603  //echo "Successfully sent email to {$recipient->strval('recipient_email')}" ;
604  //exit;
605 
606  if( $onSuccessAppFuncExists ){
607  $appDelegate->$onSuccessFunc($recipientObj, $email);
608  }
609 
610  if ( $onSuccessTableFuncExists ){
611  $recipientsTableDelegate->$onSuccessFunc($recipientObj, $email);
612  }
613  } else {
614  $joinRecord->setValue('success',0);
615  $joinRecord->setValue('sent',1);
616  $this->messages[] = "Failed to send email to ".$email->val('recipient_email');
617  error_log("Failed to send email to ".$email->val('recipient_email'));
618  df_q("update xataface__email_jobs set sent_emails=sent_emails+1, failed_emails=failed_emails+1 where email_id='".addslashes($emailId)."'");
619  //echo "Failed to send";
620  //exit;
621 
622  if( $onSuccessAppFuncExists ){
623  $appDelegate->$onSuccessFunc($recipientObj, $email);
624  }
625 
626  if ( $onSuccessTableFuncExists ){
627  $recipientsTableDelegate->$onSuccessFunc($recipientObj, $email);
628  }
629  }
630 
631  $joinRecord->setValue('date_sent',date('Y-m-d H:i:s'));
632  $joinRecord->save();
633 
634  unset($joinRecord);
635  unset($recipient);
636 
637 
638  }
639 
640  }
641 
642  function postJob($emailId, $emailTable=null, $joinTable = null, $recipientsTable = null , $emailColumn = null){
643 
644  $res = df_q("select count(*) from `$joinTable` where messageid='".addslashes($emailId)."'");
645  list($count) = mysql_fetch_row($res);
646  //echo "Posting job to join table: $joinTable with count ".$count;exit;
647 
648  $res = df_q(
649  "insert into xataface__email_jobs (
650  email_id,
651  email_table,
652  join_table,
653  recipients_table,
654  email_column,
655  active,
656  total_emails,
657  start_time
658  )
659  values (
660  '".addslashes($emailId)."',
661  '".addslashes($emailTable)."',
662  '".addslashes($joinTable)."',
663  '".addslashes($recipientsTable)."',
664  '".addslashes($emailColumn)."',
665  1,
666  '".addslashes($count)."',
667  '".time()."'
668  )");
669  return mysql_insert_id(df_db());
670 
671 
672  }
673 }
674 
675 
676 ?>