emails.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. require_once(realpath(dirname(__FILE__)).'/config.php');
  3. require_once(PATH_PHP.'database.php');
  4. require_once(PATH_PHP.'security.php');
  5. require_once(PATH_PHP.'user.php');
  6. function sendMail($template,$subject,$to=null,$from=null,$context=array()){
  7. if(is_null($to)){
  8. $to = get('email');
  9. }
  10. if(is_null($from)){
  11. $from = get('email');
  12. }
  13. if(file_exists(PATH_DATA."/emails/{$template}.template")){
  14. $message = vnsprintf(file_get_contents(PATH_DATA."/emails/{$template}.template"),$context);
  15. return @mail($to,$subject,$message,"From: {$from}\r\nMIME-Version: 1.0\r\nContent-type: text/html; charset=iso-8859-1\r\n");
  16. }else{
  17. return false;
  18. }
  19. }
  20. function sendMailAll($template,$subject,$context=array()){
  21. if($res = query("SELECT id FROM `users`")){
  22. while($user = $res->fetch_assoc()){
  23. $userobj = userObj((int)$user['id']);
  24. foreach($userobj as $k => $val){
  25. $context['user'.$k] = $val;
  26. }
  27. query("INSERT INTO `emails` (to_id,subject,template,context) VALUES (%d,'%s','%s','%s')",array($user['id'],$subject,$template,json_encode($context)));
  28. }
  29. }
  30. }
  31. function sendFromQueue($limit = 5){
  32. if($res = query("SELECT e.id,u.email,e.subject,e.template,e.context FROM `emails` e JOIN `users` u ON u.id = e.to_id LIMIT %d",array($limit))){
  33. while($email = $res->fetch_assoc()){
  34. if(sendMail($email['template'],$email['subject'],$email['email'],get('email'),json_decode($email['context'],true))){
  35. query("DELETE FROM `emails` WHERE id = %d",array($email['id']));
  36. }else{
  37. query("UPDATE `emails` SET failed=1 WHERE id = %d",array($email['id']));
  38. }
  39. }
  40. }
  41. }
  42. ?>