PageRenderTime 48ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/controller/admin/mailing.php

https://github.com/alugo/Goteo
PHP | 333 lines | 249 code | 48 blank | 36 comment | 37 complexity | 515742c07fbb546ea7459e8b73eb3284 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. namespace Goteo\Controller\Admin {
  21. use Goteo\Core\View,
  22. Goteo\Core\Redirection,
  23. Goteo\Core\Error,
  24. Goteo\Library\Message,
  25. Goteo\Library\Feed,
  26. Goteo\Library\Template,
  27. Goteo\Library\Mail,
  28. Goteo\Library\Newsletter,
  29. Goteo\Model;
  30. class Mailing {
  31. public static function process ($action = 'list', $id = null, $filters = array()) {
  32. // año fiscal
  33. $year = Model\User\Donor::$currYear;
  34. $year0 = $year;
  35. $year1 = $year-1;
  36. $errors = array();
  37. $node = isset($_SESSION['admin_node']) ? $_SESSION['admin_node'] : \GOTEO_NODE;
  38. // Valores de filtro
  39. $interests = Model\User\Interest::getAll();
  40. $status = Model\Project::status();
  41. $methods = Model\Invest::methods();
  42. $types = array(
  43. 'investor' => 'Cofinanciadores',
  44. 'owner' => 'Autores',
  45. 'user' => 'Usuarios'
  46. );
  47. $roles = array(
  48. 'admin' => 'Administrador',
  49. 'checker' => 'Revisor',
  50. 'translator' => 'Traductor'
  51. );
  52. // una variable de sesion para mantener los datos de todo esto
  53. if (!isset($_SESSION['mailing'])) {
  54. $_SESSION['mailing'] = array();
  55. }
  56. switch ($action) {
  57. case 'edit':
  58. $_SESSION['mailing']['receivers'] = array();
  59. $values = array();
  60. $sqlFields = '';
  61. $sqlInner = '';
  62. $sqlFilter = '';
  63. // cargamos los destiantarios
  64. //----------------------------
  65. // por tipo de usuario
  66. switch ($filters['type']) {
  67. case 'investor':
  68. $sqlInner .= "INNER JOIN invest
  69. ON invest.user = user.id
  70. AND (invest.status = 0 OR invest.status = 1 OR invest.status = 3 OR invest.status = 4)
  71. INNER JOIN project
  72. ON project.id = invest.project
  73. ";
  74. $sqlFields .= ", project.name as project";
  75. $sqlFields .= ", project.id as projectId";
  76. break;
  77. case 'owner':
  78. $sqlInner .= "INNER JOIN project
  79. ON project.owner = user.id
  80. ";
  81. $sqlFields .= ", project.name as project";
  82. $sqlFields .= ", project.id as projectId";
  83. break;
  84. default :
  85. break;
  86. }
  87. $_SESSION['mailing']['filters_txt'] = 'los <strong>' . $types[$filters['type']] . '</strong> ';
  88. if (!empty($filters['project']) && !empty($sqlInner)) {
  89. $sqlFilter .= " AND project.name LIKE (:project) ";
  90. $values[':project'] = '%'.$filters['project'].'%';
  91. $_SESSION['mailing']['filters_txt'] .= 'de proyectos que su nombre contenga <strong>\'' . $filters['project'] . '\'</strong> ';
  92. } elseif (empty($filters['project']) && !empty($sqlInner)) {
  93. $_SESSION['mailing']['filters_txt'] .= 'de cualquier proyecto ';
  94. }
  95. if (isset($filters['status']) && $filters['status'] > -1 && !empty($sqlInner)) {
  96. $sqlFilter .= "AND project.status = :status ";
  97. $values[':status'] = $filters['status'];
  98. $_SESSION['mailing']['filters_txt'] .= 'en estado <strong>' . $status[$filters['status']] . '</strong> ';
  99. } elseif ($filters['status'] < 0 && !empty($sqlInner)) {
  100. $_SESSION['mailing']['filters_txt'] .= 'en cualquier estado ';
  101. }
  102. if ($filters['type'] == 'investor') {
  103. if (!empty($filters['method']) && !empty($sqlInner)) {
  104. $sqlFilter .= "AND invest.method = :method ";
  105. $values[':method'] = $filters['method'];
  106. $_SESSION['mailing']['filters_txt'] .= 'mediante <strong>' . $methods[$filters['method']] . '</strong> ';
  107. } elseif (empty($filters['method']) && !empty($sqlInner)) {
  108. $_SESSION['mailing']['filters_txt'] .= 'mediante cualquier metodo ';
  109. }
  110. }
  111. if (!empty($filters['interest'])) {
  112. $sqlInner .= "INNER JOIN user_interest
  113. ON user_interest.user = user.id
  114. AND user_interest.interest = :interest
  115. ";
  116. $values[':interest'] = $filters['interest'];
  117. if ($filters['interest'] == 15) {
  118. $_SESSION['mailing']['filters_txt'] .= 'del grupo de testeo ';
  119. } else {
  120. $_SESSION['mailing']['filters_txt'] .= 'interesados en fin <strong>' . $interests[$filters['interest']] . '</strong> ';
  121. }
  122. }
  123. if (!empty($filters['role'])) {
  124. $sqlInner .= "INNER JOIN user_role
  125. ON user_role.user_id = user.id
  126. AND user_role.role_id = :role
  127. ";
  128. $values[':role'] = $filters['role'];
  129. $_SESSION['mailing']['filters_txt'] .= 'que sean <strong>' . $roles[$filters['role']] . '</strong> ';
  130. }
  131. if (!empty($filters['name'])) {
  132. $sqlFilter .= " AND ( user.name LIKE (:name) OR user.email LIKE (:name) ) ";
  133. $values[':name'] = '%'.$filters['name'].'%';
  134. $_SESSION['mailing']['filters_txt'] .= 'que su nombre o email contenga <strong>\'' . $filters['name'] . '\'</strong> ';
  135. }
  136. if (!empty($filters['donant'])) {
  137. if ($filters['type'] == 'investor') {
  138. $sqlFilter .= " AND invest.resign = 1
  139. AND invest.status IN (1, 3)
  140. AND invest.charged >= '{$year0}-01-01'
  141. AND invest.charged < '{$year1}-01-01'
  142. AND (project.passed IS NOT NULL AND project.passed != '0000-00-00')
  143. ";
  144. $_SESSION['mailing']['filters_txt'] .= 'que haya hecho algun donativo ';
  145. } else {
  146. Message::Error('Solo se filtran donantes si se envia "A los: Cofinanciadores"');
  147. }
  148. }
  149. if ($node != \GOTEO_NODE) {
  150. $sqlFilter .= " AND user.node = :node";
  151. $values[':node'] = $node;
  152. if (!empty($sqlInner)) {
  153. $sqlFilter .= " AND project.node = :node";
  154. }
  155. }
  156. $sql = "SELECT
  157. user.id as id,
  158. user.id as user,
  159. user.name as name,
  160. user.email as email
  161. $sqlFields
  162. FROM user
  163. $sqlInner
  164. WHERE user.active = 1
  165. $sqlFilter
  166. GROUP BY user.id
  167. ORDER BY user.name ASC
  168. ";
  169. // die('<pre>'.$sql . '<br />'.print_r($values, 1).'</pre>');
  170. if ($query = Model\User::query($sql, $values)) {
  171. foreach ($query->fetchAll(\PDO::FETCH_OBJ) as $receiver) {
  172. $_SESSION['mailing']['receivers'][$receiver->id] = $receiver;
  173. }
  174. } else {
  175. Message::Error('Fallo el SQL!!!!! <br />' . $sql . '<pre>'.print_r($values, 1).'</pre>');
  176. }
  177. // si no hay destinatarios, salta a la lista con mensaje de error
  178. if (empty($_SESSION['mailing']['receivers'])) {
  179. Message::Error('No se han encontrado destinatarios para ' . $_SESSION['mailing']['filters_txt']);
  180. throw new Redirection('/admin/mailing/list');
  181. }
  182. // si hay, mostramos el formulario de envio
  183. return new View(
  184. 'view/admin/index.html.php',
  185. array(
  186. 'folder' => 'mailing',
  187. 'file' => 'edit',
  188. 'filters' => $filters,
  189. 'interests' => $interests,
  190. 'status' => $status,
  191. 'types' => $types,
  192. 'roles' => $roles
  193. )
  194. );
  195. break;
  196. case 'send':
  197. // die(\trace($_POST));
  198. $URL = (NODE_ID != GOTEO_NODE) ? NODE_URL : SITE_URL;
  199. // Enviando contenido recibido a destinatarios recibidos
  200. $receivers = array();
  201. $subject = $_POST['subject'];
  202. $templateId = !empty($_POST['template']) ? $_POST['template'] : 11;
  203. $content = \str_replace('%SITEURL%', $URL, $_POST['content']);
  204. // quito usuarios desmarcados
  205. foreach ($_SESSION['mailing']['receivers'] as $usr=>$userData) {
  206. $errors = array();
  207. $campo = 'receiver_'.$usr;
  208. if (!isset($_POST[$campo])) {
  209. $_SESSION['mailing']['receivers'][$usr]->ok = null;
  210. } else {
  211. $receivers[] = $userData;
  212. }
  213. }
  214. // montamos el mailing
  215. // - se crea un registro de tabla mail
  216. $sql = "INSERT INTO mail (id, email, html, template, node) VALUES ('', :email, :html, :template, :node)";
  217. $values = array (
  218. ':email' => 'any',
  219. ':html' => $content,
  220. ':template' => $templateId,
  221. ':node' => $node
  222. );
  223. $query = \Goteo\Core\Model::query($sql, $values);
  224. $mailId = \Goteo\Core\Model::insertId();
  225. // - se usa el metodo initializeSending para grabar el envío (parametro para autoactivar)
  226. // - initiateSending ($mailId, $subject, $receivers, $autoactive = 0)
  227. if (\Goteo\Library\Sender::initiateSending($mailId, $subject, $receivers, 1)) {
  228. $ok = true;
  229. // Evento Feed
  230. $log = new Feed();
  231. $log->populate('comunicación masiva a usuarios (admin)', '/admin/mailing',
  232. \vsprintf("El admin %s ha iniciado una %s a %s", array(
  233. Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id),
  234. Feed::item('relevant', 'Comunicacion masiva'),
  235. $_SESSION['mailing']['filters_txt']
  236. )));
  237. $log->doAdmin('admin');
  238. unset($log);
  239. } else {
  240. $ok = false;
  241. // Evento Feed
  242. $log = new Feed();
  243. $log->populate('comunicación masiva a usuarios (admin)', '/admin/mailing',
  244. \vsprintf("El admin %s le ha %s una %s a %s", array(
  245. Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id),
  246. Feed::item('relevant', 'fallado'),
  247. Feed::item('relevant', 'Comunicacion masiva'),
  248. $_SESSION['mailing']['filters_txt']
  249. )));
  250. $log->doAdmin('admin');
  251. unset($log);
  252. }
  253. return new View(
  254. 'view/admin/index.html.php',
  255. array(
  256. 'folder' => 'mailing',
  257. 'file' => 'send',
  258. 'subject' => $subject,
  259. 'interests' => $interests,
  260. 'status' => $status,
  261. 'methods' => $methods,
  262. 'types' => $types,
  263. 'roles' => $roles,
  264. 'users' => $receivers,
  265. 'ok' => $ok
  266. )
  267. );
  268. break;
  269. }
  270. return new View(
  271. 'view/admin/index.html.php',
  272. array(
  273. 'folder' => 'mailing',
  274. 'file' => 'list',
  275. 'interests' => $interests,
  276. 'status' => $status,
  277. 'methods' => $methods,
  278. 'types' => $types,
  279. 'roles' => $roles,
  280. 'filters' => $filters
  281. )
  282. );
  283. }
  284. }
  285. }