PageRenderTime 28ms CodeModel.GetById 15ms app.highlight 9ms RepoModel.GetById 1ms app.codeStats 1ms

/controller/cron/send.php

https://github.com/alugo/Goteo
PHP | 330 lines | 236 code | 45 blank | 49 comment | 23 complexity | f702808eb8a92919be3f2c0016725508 MD5 | raw file
  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
 21namespace Goteo\Controller\Cron {
 22
 23    use Goteo\Model,
 24        Goteo\Core\Redirection,
 25        Goteo\Library\Text,
 26        Goteo\Library\Feed,
 27        Goteo\Library\Template,
 28        Goteo\Library\Mail,
 29        Goteo\Core\Error;
 30
 31    class Send {
 32
 33        /**
 34         * Al autor del proyecto, se encarga de substituir variables en plantilla
 35         *
 36         * @param $type string
 37         * @param $project Object
 38         * @return bool
 39         */
 40        public static function toOwner ($type, $project) {
 41            $tpl = null;
 42            
 43            /// tipo de envio
 44            switch ($type) {
 45                // Estos son avisos de final de ronda
 46                case 'r1_pass': // template 20, proyecto supera la primera ronda
 47                    $tpl = 20;
 48                    $search  = array('%USERNAME%', '%PROJECTNAME%', '%WIDGETURL%');
 49                    $replace = array($project->user->name, $project->name, SITE_URL . '/dashboard/projects/widgets');
 50                    break;
 51
 52                case 'fail': // template 21, caduca sin conseguir el mínimo
 53                    $tpl = 21;
 54                    $search  = array('%USERNAME%', '%PROJECTNAME%', '%SUMMARYURL%');
 55                    $replace = array($project->user->name, $project->name, SITE_URL . '/dashboard/projects/summary');
 56                    break;
 57
 58                case 'r2_pass': // template 22, finaliza segunda ronda
 59                    $tpl = 22;
 60                    $search  = array('%USERNAME%', '%PROJECTNAME%', '%REWARDSURL%');
 61                    $replace = array($project->user->name, $project->name, SITE_URL . '/dashboard/projects/rewards');
 62                    break;
 63
 64                // Estos son avisos de auto-tips de /cron/daily
 65                case '8_days': // template 13, cuando faltan 8 días y no ha conseguido el mínimo
 66                    $tpl = 13;
 67                    $search  = array('%USERNAME%', '%PROJECTNAME%', '%WIDGETURL%');
 68                    $replace = array($project->user->name, $project->name, SITE_URL . '/dashboard/projects/widgets');
 69                    break;
 70
 71                case '2_days': // template 14, cuando faltan 2 días y no ha conseguido el mínimo
 72                    $tpl = 14;
 73                    $search  = array('%USERNAME%', '%PROJECTNAME%', '%WIDGETURL%');
 74                    $replace = array($project->user->name, $project->name, SITE_URL . '/dashboard/projects/widgets');
 75                    break;
 76
 77                case 'two_weeks': // template 19, "no bajes la guardia!" 25 días de campaña
 78                    $tpl = 19;
 79                    $search  = array('%USERNAME%', '%PROJECTNAME%', '%WIDGETURL%');
 80                    $replace = array($project->user->name, $project->name, SITE_URL . '/dashboard/projects/widgets');
 81                    break;
 82
 83                case 'no_updates': // template 23, 3 meses sin novedades
 84                    $tpl = 23;
 85                    $search  = array('%USERNAME%', '%PROJECTNAME%', '%UPDATESURL%');
 86                    $replace = array($project->user->name, $project->name, SITE_URL . '/dashboard/projects/updates');
 87                    break;
 88
 89                case 'any_update': // template 24, no hay posts de novedades
 90                    $tpl = 24;
 91                    $search  = array('%USERNAME%', '%PROJECTNAME%', '%UPDATESURL%', '%NOVEDADES%');
 92                    $replace = array($project->user->name, $project->name, SITE_URL . '/dashboard/projects/updates', SITE_URL.'/project/'.$project->id.'/updates');
 93                    break;
 94
 95                case '2m_after': // template 25, dos meses despues de financiado
 96                    $tpl = 25;
 97                    $search  = array('%USERNAME%', '%PROJECTNAME%', '%REWARDSURL%');
 98                    $replace = array($project->user->name, $project->name, SITE_URL . '/dashboard/projects/rewards');
 99                    break;
100
101                case '8m_after': // template 52, ocho meses despues de financiado
102                    $tpl = 52;
103                    $search  = array('%USERNAME%', '%PROJECTNAME%', '%COMMONSURL%');
104                    $replace = array($project->user->name, $project->name, SITE_URL . '/dashboard/projects/commons');
105                    break;
106
107                case '20_backers': // template 46, "Apóyate en quienes te van apoyando "  (en cuanto se llega a los 20 backers
108                    $tpl = 46;
109                    $search  = array('%USERNAME%', '%PROJECTNAME%', '%PROJECTURL%', '%NUMBACKERS%');
110                    $replace = array($project->user->name, $project->name, SITE_URL.'/project/'.$project->id, $project->num_investors);
111                    break;
112                
113                // consejos normales
114                case 'tip_1': // template 41, "Difunde, difunde, difunde"
115                    $tpl = 41;
116                    $search  = array('%USERNAME%', '%PROJECTNAME%', '%PROJECTURL%', '%PORCENTAJE%');
117                    $replace = array($project->user->name, $project->name, SITE_URL.'/project/'.$project->id, $project->percent);
118                    break;
119
120                case 'tip_2': // template 42, "Comienza por lo más próximo"
121                    $tpl = 42;
122                    $search  = array('%USERNAME%', '%PROJECTNAME%', '%PROJECTURL%', '%PORCENTAJE%');
123                    $replace = array($project->user->name, $project->name, SITE_URL.'/project/'.$project->id, $project->percent);
124                    break;
125                
126                case 'tip_3': // template 43, "Una acción a diario, por pequeña que sea"
127                    $tpl = 43;
128                    $search  = array('%USERNAME%', '%PROJECTNAME%', '%PROJECTURL%', '%AMOUNT%');
129                    $replace = array($project->user->name, $project->name, SITE_URL.'/project/'.$project->id, $project->invested);
130                    break;
131                
132                case 'tip_4': // template 44, "Llama a todas las puertas"
133                    $tpl = 44;
134                    $search  = array('%USERNAME%', '%PROJECTNAME%', '%PROJECTURL%', '%BACKERSURL%');
135                    $replace = array($project->user->name, $project->name, SITE_URL.'/project/'.$project->id, SITE_URL.'/project/'.$project->id.'/supporters');
136                    break;
137                
138                case 'tip_5': // template 45, "Busca dónde está tu comunidad"
139                    $tpl = 45;
140                    $search  = array('%USERNAME%', '%PROJECTNAME%', '%PROJECTURL%', '%AMOUNT%', '%NUMBACKERS%');
141                    $replace = array($project->user->name, $project->name, SITE_URL.'/project/'.$project->id, $project->invested, $project->num_investors);
142                    break;
143                
144                case 'tip_8': // template 47, "Agradece en público e individualmente"
145                    $tpl = 47;
146                    $search  = array('%USERNAME%', '%PROJECTNAME%', '%PROJECTURL%', '%MESSAGESURL%');
147                    $replace = array($project->user->name, $project->name, SITE_URL.'/project/'.$project->id, SITE_URL.'/project/'.$project->id.'/messages');
148                    break;
149                
150                case 'tip_9': // template 48, "Busca prescriptores e implícalos"
151                    $tpl = 48;
152                    $search  = array('%USERNAME%', '%PROJECTNAME%', '%PROJECTURL%', '%PORCENTAJE%');
153                    $replace = array($project->user->name, $project->name, SITE_URL.'/project/'.$project->id, $project->percent);
154                    break;
155                
156                case 'tip_10': // template 49, "Luce tus recompensas y retornos"
157                    $tpl = 49;
158                    $search  = array('%USERNAME%', '%PROJECTNAME%', '%PROJECTURL%', '%LOWREWARD%', '%HIGHREWARD%');
159                    $replace = array($project->user->name, $project->name, SITE_URL.'/project/'.$project->id, $project->lower, $project->higher);
160                    break;
161                
162                case 'tip_11': // template 50, "Refresca tu mensaje de motivacion"
163                    $tpl = 50;
164                    $search  = array('%USERNAME%', '%PROJECTNAME%', '%PROJECTURL%');
165                    $replace = array($project->user->name, $project->name, SITE_URL.'/project/'.$project->id);
166                    break;
167                
168                case 'tip_15': // template 51, "Sigue los avances y calcula lo que falta"
169                    $tpl = 51;
170                    $search  = array('%USERNAME%', '%PROJECTNAME%', '%PROJECTURL%', '%DIASCAMPAÑA%', '%DAYSTOGO%');
171                    $replace = array($project->user->name, $project->name, SITE_URL.'/project/'.$project->id, $project->days, $project->days);
172                    break;
173                
174            }
175
176            if (!empty($tpl)) {
177                $errors = array();
178                // Obtenemos la plantilla para asunto y contenido
179                $template = Template::get($tpl);
180                // Sustituimos los datos
181                $subject = str_replace('%PROJECTNAME%', $project->name, $template->title);
182                $content = \str_replace($search, $replace, $template->text);
183                // iniciamos mail
184                $mailHandler = new Mail();
185                $mailHandler->to = $project->user->email;
186                $mailHandler->toName = $project->user->name;
187                // monitorización solo para 'quien-manda'
188                if ($project->id == 'quien-manda' || $project->id == 'guifi-net-extremadura') 
189                    $mailHandler->bcc = array('enric@goteo.org', 'maria@goteo.org', 'olivier@goteo.org', 'jcanaves@doukeshi.org', 'info@goteo.org');
190                
191                if ($project->id == 'cervecita-fresca') 
192                    $mailHandler->bcc = array('jcanaves@doukeshi.org');
193                
194                if ($project->id == 'keinuka') 
195                    $mailHandler->bcc = array('rosa@euskadi.goteo.org', 'jcanaves@doukeshi.org');
196                
197                // si es un proyecto de nodo: reply al mail del nodo
198                // si es de centra: reply a MAIL_GOTEO
199                $mailHandler->reply = (!empty($project->nodeData->email)) ? $project->nodeData->email : \GOTEO_CONTACT_MAIL;
200                
201                $mailHandler->subject = $subject;
202                $mailHandler->content = $content;
203                $mailHandler->html = true;
204                $mailHandler->template = $template->id;
205                if ($mailHandler->send($errors)) {
206                    return true;
207                } else {
208                    echo \trace($errors);
209                    @mail(\GOTEO_FAIL_MAIL,
210                        'Fallo al enviar email automaticamente al autor ' . SITE_URL,
211                        'Fallo al enviar email automaticamente al autor: <pre>' . print_r($mailHandler, 1). '</pre>');
212                }
213            }
214
215            return false;
216        }
217
218        /* A los cofinanciadores 
219         * Se usa tambien para notificar cuando un proyecto publica una novedad.
220         * Por eso añadimos el tercer parámetro, para recibir los datos del post
221         */
222        static public function toInvestors ($type, $project, $post = null) {
223
224            // notificación
225            $notif = $type == 'update' ? 'updates' : 'rounds';
226
227            $anyfail = false;
228            $tpl = null;
229
230            // para cada inversor que no tenga bloqueado esta notificacion
231            $sql = "
232                SELECT
233                    invest.user as id,
234                    user.name as name,
235                    user.email as email,
236                    invest.method as method,
237                    IFNULL(user.lang, 'es') as lang
238                FROM  invest
239                INNER JOIN user
240                    ON user.id = invest.user
241                    AND user.active = 1
242                LEFT JOIN user_prefer
243                    ON user_prefer.user = invest.user
244                WHERE   invest.project = ?
245                AND invest.status IN ('0', '1', '3', '4')
246                AND (user_prefer.{$notif} = 0 OR user_prefer.{$notif} IS NULL)
247                GROUP BY user.id
248                ";
249            if ($query = Model\Invest::query($sql, array($project->id))) {
250                foreach ($query->fetchAll(\PDO::FETCH_OBJ) as $investor) {
251                    /// tipo de envio
252                    switch ($type) {
253                        case 'r1_pass': // template 15, proyecto supera la primera ronda
254                                $tpl = 15;
255                                $search  = array('%USERNAME%', '%PROJECTNAME%', '%PROJECTURL%');
256                                $replace = array($investor->name, $project->name, SITE_URL . '/project/' . $project->id);
257                            break;
258
259                        case 'fail': // template 17 (paypalistas) / 35 (tpvistas) , caduca sin conseguir el mínimo
260                                $tpl = ($investor->method == 'paypal') ? 17 : 35;
261                                $search  = array('%USERNAME%', '%PROJECTNAME%', '%DISCOVERURL%');
262                                $replace = array($investor->name, $project->name, SITE_URL . '/discover');
263                            break;
264
265                        case 'r2_pass': // template 16, finaliza segunda ronda
266                                $tpl = 16;
267                                $search  = array('%USERNAME%', '%PROJECTNAME%', '%PROJECTURL%');
268                                $replace = array($investor->name, $project->name, SITE_URL . '/project/' . $project->id);
269                            break;
270
271                        case 'update': // template 18, publica novedad
272                                $tpl = 18;
273                                $search  = array('%USERNAME%', '%PROJECTNAME%', '%UPDATEURL%', '%POST%', '%SHAREFACEBOOK%', '%SHARETWITTER%');
274                                $post_url = SITE_URL.'/project/'.$project->id.'/updates/'.$post->id;
275                                // contenido del post
276                                $post_content = "<p><strong>{$post->title}</strong><br />".  nl2br( Text::recorta($post->text, 500) )  ."</p>";
277                                // y preparar los enlaces para compartir en redes sociales
278                                $share_urls = Text::shareLinks($post_url, $post->title);
279                                
280                                $replace = array($investor->name, $project->name, $post_url, $post_content, $share_urls['facebook'], $share_urls['twitter']);
281                            break;
282                    }
283
284                    if (!empty($tpl)) {
285                        // Obtenemos la plantilla para asunto y contenido
286                        // en el idioma del usuario
287                        $template = Template::get($tpl, $investor->lang);
288                        // Sustituimos los datos
289                        if (!empty($post)) {
290                            $subject = str_replace(array('%PROJECTNAME%', '%OWNERNAME%', '%P_TITLE%')
291                                    , array($project->name, $project->user->name, $post->title)
292                                    , $template->title);
293                        } else {
294                            $subject = str_replace('%PROJECTNAME%', $project->name, $template->title);
295                        }
296                        $content = \str_replace($search, $replace, $template->text);
297                        // iniciamos mail
298                        $mailHandler = new Mail();
299                        $mailHandler->to = $investor->email;
300                        $mailHandler->toName = $investor->name;
301                        $mailHandler->subject = $subject;
302                        $mailHandler->content = $content;
303                        $mailHandler->html = true;
304                        $mailHandler->template = $template->id;
305                        if ($mailHandler->send()) {
306
307                        } else {
308                            $anyfail = true;
309                            @mail(\GOTEO_FAIL_MAIL,
310                                'Fallo al enviar email automaticamente al cofinanciador ' . SITE_URL,
311                                'Fallo al enviar email automaticamente al cofinanciador: <pre>' . print_r($mailHandler, 1). '</pre>');
312                        }
313                        unset($mailHandler);
314                    }
315                }
316                // fin bucle inversores
317            } else {
318                echo '<p>'.str_replace('?', $project->id, $sql).'</p>';
319                $anyfail = true;
320            }
321            
322            if ($anyfail)
323                return false;
324            else
325                return true;
326
327        }
328        
329    }
330}