PageRenderTime 59ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/cli-sendmail.php

https://github.com/alugo/Goteo
PHP | 183 lines | 153 code | 6 blank | 24 comment | 1 complexity | 206d50027be1231eb9f9c655d4c5e328 MD5 | raw file
Possible License(s): AGPL-1.0
  1. <?php
  2. /*
  3. * Copyright (C) 2012 Platoniq y Fundación Fuentes Abiertas (see README for details)
  4. * This file is part of Goteo.
  5. *
  6. * Goteo is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Goteo 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 Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with Goteo. If not, see <http://www.gnu.org/licenses/agpl.txt>.
  18. *
  19. */
  20. /**
  21. * Este es el proceso que envia un email al usuario especificado
  22. * version linea de comandos
  23. **/
  24. if (PHP_SAPI !== 'cli') {
  25. die("Acceso solo por linea de comandos!");
  26. }
  27. error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
  28. ini_set("display_errors",1);
  29. //system timezone
  30. date_default_timezone_set("Europe/Madrid");
  31. use Goteo\Core\Resource,
  32. Goteo\Core\Error,
  33. Goteo\Core\Redirection,
  34. Goteo\Core\Model,
  35. Goteo\Library\Feed,
  36. Goteo\Library\Mail,
  37. Goteo\Library\Sender;
  38. require_once 'config.php';
  39. require_once 'core/common.php';
  40. // Autoloader
  41. spl_autoload_register(
  42. function ($cls) {
  43. $file = __DIR__ . '/' . implode('/', explode('\\', strtolower(substr($cls, 6)))) . '.php';
  44. $file = realpath($file);
  45. if ($file === false) {
  46. // Try in library
  47. $file = __DIR__ . '/library/' . strtolower($cls) . '.php';
  48. }
  49. if ($file !== false) {
  50. include $file;
  51. }
  52. }
  53. );
  54. // set Lang
  55. define('LANG', 'es');
  56. $debug = true;
  57. $id = $argv[1];
  58. if(empty($id)) {
  59. die("Se necesita un identificador de sender como argumento del script!");
  60. }
  61. $list = array();
  62. $sql = "SELECT
  63. mailer_send.id,
  64. mailer_send.user,
  65. mailer_send.name,
  66. mailer_send.email,
  67. mailer_content.id as mailing_id
  68. FROM mailer_send
  69. RIGHT JOIN mailer_content ON mailer_content.id=mailer_send.mailing AND mailer_content.active=1
  70. WHERE mailer_send.id = ?
  71. AND mailer_send.sended IS NULL
  72. AND mailer_send.blocked IS NULL
  73. ";
  74. if ($query = Model::query($sql, array($id))) {
  75. $user = $query->fetchObject();
  76. }
  77. if(!is_object($user)) {
  78. die("No se ha encontrado un usuario válido para el mailer_send.id=$id\n");
  79. }
  80. //si estamos aqui sabemos que el usuari es valido i el mailing tambien
  81. if($debug) echo "dbg: Fecha inicio " .date("Y-m-d H:i:s"). "\n";
  82. // cogemos el siguiente envío a tratar
  83. $mailing = Sender::getSending($user->mailing_id);
  84. // print_r($mailing);
  85. // si no está activa fin
  86. if (!$mailing->active) {
  87. die("Mailing {$user->mailing_id} inactivo!\n");
  88. }
  89. // cogemos el contenido y la plantilla desde el historial
  90. $query = Model::query('SELECT html, template FROM mail WHERE id = ?', array($mailing->mail));
  91. $data = $query->fetch(\PDO::FETCH_ASSOC);
  92. $content = $data['html'];
  93. $template = $data['template'];
  94. if (empty($content)) {
  95. die("Mailing {$user->mailing_id} sin contenido!\n");
  96. }
  97. if($debug) echo "dbg: Bloqueando registro {$user->id} ({$user->email}) mailing: {$user->mailing_id}\n";
  98. //bloquear usuario
  99. Model::query("UPDATE mailer_send SET blocked = 1 WHERE id = '{$user->id}' AND mailing = '{$user->mailing_id}'");
  100. //enviar email
  101. $itime = microtime(true);
  102. try {
  103. $mailHandler = new Mail($debug);
  104. // reply, si es especial
  105. if (!empty($mailing->reply)) {
  106. $mailHandler->reply = $mailing->reply;
  107. if (!empty($mailing->reply_name)) {
  108. $mailHandler->replyName = $mailing->reply_name;
  109. }
  110. }
  111. $mailHandler->to = \trim($user->email);
  112. $mailHandler->toName = $user->name;
  113. $mailHandler->subject = $mailing->subject;
  114. $mailHandler->content = str_replace(
  115. array('%USERID%', '%USEREMAIL%', '%USERNAME%'),
  116. array($user->user, $user->email, $user->name),
  117. $content);
  118. $mailHandler->html = true;
  119. $mailHandler->template = $template;
  120. $mailHandler->massive = true;
  121. $errors = array();
  122. if ($mailHandler->send($errors)) {
  123. // Envio correcto
  124. Model::query("UPDATE mailer_send SET sended = 1, datetime = NOW() WHERE id = '{$user->id}' AND mailing = '{$user->mailing_id}'");
  125. if ($debug) echo "dbg: Enviado OK a $user->email\n";
  126. } else {
  127. // falló al enviar
  128. $sql = "UPDATE mailer_send
  129. SET sended = 0 , error = ? , datetime = NOW()
  130. WHERE id = '{$user->id}' AND mailing = '{$user->mailing_id}'
  131. ";
  132. Model::query($sql, array(implode(',', $errors)));
  133. if ($debug) echo "dbg: Fallo ERROR a {$user->email} ".implode(',', $errors)."\n";
  134. }
  135. unset($mailHandler);
  136. // tiempo de ejecución
  137. $now = (microtime(true) - $itime);
  138. if ($debug) echo "dbg: Tiempo de envio: $now segundos\n";
  139. } catch (phpmailerException $e) {
  140. die ($e->errorMessage());
  141. }
  142. //desbloquear usuario
  143. if($debug) echo "dbg: Desbloqueando registro {$user->id} ({$user->email}) mailing: {$user->mailing_id}\n";
  144. Model::query("UPDATE mailer_send SET blocked = NULL WHERE id = '{$user->id}' AND mailing = '{$user->mailing_id}'");