Newsletter.php 12.3 KB
Newer Older
1 2 3 4
<?PHP
/**
 * Copyright (c) 2012, Agence Française Informatique (AFI). All rights reserved.
 *
Laurent's avatar
Laurent committed
5
 * BOKEH is free software; you can redistribute it and/or modify
6 7 8 9 10 11
 * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
 * the Free Software Foundation.
 *
 * There are special exceptions to the terms and conditions of the AGPL as it
 * is applied to this software (see README file).
 *
Laurent's avatar
Laurent committed
12
 * BOKEH is distributed in the hope that it will be useful,
13 14 15 16 17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
Laurent's avatar
Laurent committed
18
 * along with BOKEH; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
 */

/*
 * exemple des possibilités:
 *
 * $all_nl = Class_Newsletter::getLoader()->findAll();
 *
 * $nl = Class_Newsletter::getLoader()->find(3);
 * $nl->getTitre();
 * $nl->setContenu('youpi');
 * $nl->save();
 * $nl->delete();
 *
 * $nl = new Class_Newsletter();
 * $nl->setTitre('Nouveautés');
 * $nl->save();
 *
 * Mocking pour les tests:
 *
 * $mock_row =  new Zend_Db_Table_Rowset(
 *                           array('data' => array('titre' => 'test',
 *                                                  'contenu' => 'enfin des tests')));
 * $mock_tbl = this->getMock('MockTable', array('find'));
 * $mock_tbl
 *   ->expects($this->once())
 *   ->metchod('find')
 *   ->with(3)
 *   ->will($this->return($mock_row))
 *
 * Class_Newsletter::getLoader()->setTable($mock_tbl);
 *
 * $nl = Class_Newsletter::getLoader()->find(3);
 * $this->assertEquals('test', $nl->getTitre());
 *
 */

56 57 58 59 60 61 62 63
class NewsletterLoader extends Storm_Model_Loader {
  public function getPublishedNewsletters() {
    return Class_Newsletter::findAllBy(['draft' => 0]);
  }
}



64
class Class_Newsletter extends Storm_Model_Abstract {
Patrick Barroca's avatar
Patrick Barroca committed
65
  use Trait_TimeSource, Trait_Translator;
66

Patrick Barroca's avatar
Patrick Barroca committed
67
  const URL_PLACEHOLDER = '{{URL}}';
68

Patrick Barroca's avatar
Patrick Barroca committed
69
  protected $_table_name = 'newsletters';
70
  protected $_loader_class = 'NewsletterLoader';
71 72

  protected $_has_many =
73
    [
74 75 76 77
     'blacklists' => ['model' => 'Class_Newsletter_Blacklist',
                      'role' => 'newsletter',
                      'dependents' => 'delete'],

78 79 80 81
     'dispatchs' => ['model' => 'Class_Newsletter_Dispatch',
                     'role' => 'newsletter',
                     'dependents' => 'delete'],

82 83 84
     'newsletter_group_subscriptions' => ['model' => 'Class_NewsletterGroupSubscription',
                                          'role' => 'newsletter',
                                          'dependents' => 'delete'],
85

86 87
     'user_groups' => ['through' => 'newsletter_group_subscriptions'],
    ];
88

Patrick Barroca's avatar
Patrick Barroca committed
89 90
  protected $_notices_finder;
  protected $_recipent_size = 20;
91
  protected $_default_attribute_values = ['titre' => '',
92
                                          'draft' => 0,
93 94
                                          'articles_ids' => '',
                                          'articles_categories_ids' => ''];
95

96 97 98 99 100 101

  public function describeAssociationsOn($associations) {
		$associations
			->add(new Class_Newsletter_DedicatedGroupAssociation('dedicated_group'));
	}

102

Patrick Barroca's avatar
Patrick Barroca committed
103
  public function send() {
104 105 106 107
    return (new Class_Batch_SendNewsletters($this->_getOrCreateDispatchToRun()))
      ->run();
  }

108 109 110 111 112 113 114
  public function getDispatchIfNotEnded() {
    return (($dispatch = $this->getLastDispatch()) &&
          $dispatch->isRunnable())
      ? $dispatch : false;

  }

115

116
  protected function _getOrCreateDispatchToRun() {
117 118 119
    if ($dispatch = $this->getDispatchIfNotEnded())
          return $dispatch->resetError();
    return Class_Newsletter_Dispatch::newFrom($this);
Patrick Barroca's avatar
Patrick Barroca committed
120
  }
121 122


Patrick Barroca's avatar
Patrick Barroca committed
123 124 125 126 127
  public function setLastDistributionDateWithFormat() {
    $now = date('Y-m-d H:i:s', self::getTimeSource()->time());
    $this->setLastDistributionDate($now);
    $this->save();
  }
128 129


Patrick Barroca's avatar
Patrick Barroca committed
130 131 132 133 134
  public function getExpediteur() {
    if ($this->isAttributeEmpty('expediteur'))
      return $this->_getMailPortail();
    return $this->_get('expediteur');
  }
135 136


Patrick Barroca's avatar
Patrick Barroca committed
137 138
  public function newTemplate() {
    $template = new Class_Entity();
139

Patrick Barroca's avatar
Patrick Barroca committed
140
    $notices = $this->getNotices();
141
    $articles = $this->getArticles();
142

Patrick Barroca's avatar
Patrick Barroca committed
143 144
    $template
      ->setTitre($this->getTitre())
145 146
      ->setBodyText($this->_getBodyText($notices, $articles))
      ->setBodyHTML($this->_getBodyHTML($notices, $articles))
Patrick Barroca's avatar
Patrick Barroca committed
147
      ->setExpediteur($this->getExpediteur());
148

Patrick Barroca's avatar
Patrick Barroca committed
149 150
    return $template;
  }
151

152

Patrick Barroca's avatar
Patrick Barroca committed
153
  public function getNumberOfUsers() {
154 155 156 157 158
    return sprintf('%05d', count($this->getRecipientsUsersIds()));
  }


  public function getRecipientsUsersIds() {
159
    $ids = [];
160
    foreach($this->getRecipientsGroups() as $group)
161
      foreach($group->getUsersIdsOptimized() as $id)
162 163
        $ids[] = $id;

164
    return array_unique($ids);
Patrick Barroca's avatar
Patrick Barroca committed
165
  }
166

167

168
  public function hasRecipient($user, $with_blacklist = true) {
169
    if ($with_blacklist && $this->isBlackListed($user))
170 171
      return false;

172
    foreach($this->getRecipientsGroups() as $group)
173 174
      if ($group->hasUser($user))
        return true;
175 176 177 178

    return false;
  }

179

180 181 182 183 184
  public function isBlackListed($user) {
    return Class_Newsletter_Blacklist::isBlackListed($user->getMail(), $this->getId());
  }


185 186 187 188 189
  public function getBlackListedMails() {
    return Class_Newsletter_Blacklist::getMailsForNewsletter($this->getId());
  }


190 191 192 193 194 195 196 197 198
  public function getRecipientsGroups() {
    $groups = [$this->getDedicatedGroup()];
    foreach($this->getUserGroups() as $group)
      $groups[] = $group;

    return $groups;
  }


Patrick Barroca's avatar
Patrick Barroca committed
199 200 201
  public function getReceivers($recipient_size) {
    return Class_Users::getNewslettersReceivers($this->getId(), $recipient_size);
  }
202 203


Patrick Barroca's avatar
Patrick Barroca committed
204
  protected function _getMailPortail() {
205
    $portail = Class_Profil::find(1);
Patrick Barroca's avatar
Patrick Barroca committed
206 207
    return $portail->getMailSite();
  }
208 209


Patrick Barroca's avatar
Patrick Barroca committed
210 211 212
  public function getNotices() {
    if (!$this->getIdPanier() and !$this->getIdCatalogue())
      return array();
213

Patrick Barroca's avatar
Patrick Barroca committed
214 215 216 217 218 219
    $preferences = array( 'id_catalogue' => $this->getIdCatalogue(),
                          'id_panier' => $this->getIdPanier(),
                          'nb_notices' => $this->getNbNotices(),
                          'only_img' => false,
                          'aleatoire' => 0,
                          'tri' => 1);
220

Patrick Barroca's avatar
Patrick Barroca committed
221 222
    return Class_Notice::getNoticesFromPreferences($preferences);
  }
223 224


225
  public function getArticles() {
226 227 228 229 230 231 232 233
    $articles = [];

    foreach (Class_ArticleCategorie::findAllBy(['id_cat' => $this->getArticlesCategoriesIds()]) as $categorie)
      $articles = array_merge($articles,
                              $categorie->getArticles());

    return array_merge($articles,
                       Class_Article::findAllBy(['id_article' => $this->getArticlesIds()]));
234 235 236
  }


Patrick Barroca's avatar
Patrick Barroca committed
237 238 239
  protected function _htmlToText($html) {
    return strip_tags(preg_replace('/<br[^>]*>/i', "\n", $html));
  }
240 241


Patrick Barroca's avatar
Patrick Barroca committed
242
  public function getUnsubscribeUrl() {
243 244 245
    return Class_Url::absolute(['controller' => 'newsletter',
                                'action' => 'unsubscribe',
                                'newsletter' =>  $this->getId()], null, true)
Patrick Barroca's avatar
Patrick Barroca committed
246 247 248
      . (($profil = Class_AdminVar::get('NEWSLETTER_ID_PROFIL')) ? '/id_profil/' . $profil : '')
      . '/user/%user.id%/hash/%hash%';
  }
249 250


Patrick Barroca's avatar
Patrick Barroca committed
251 252 253 254
  protected function _getUnsubscribeText() {
    return str_replace(self::URL_PLACEHOLDER, $this->getUnsubscribeUrl(),
                       Class_AdminVar::getValueOrDefault('NEWSLETTER_UNSUBSCRIBE_TEXT'));
  }
255

256

Patrick Barroca's avatar
Patrick Barroca committed
257 258 259 260 261
  protected function _getUnsubscribeHTML() {
    return '<br/><a href="' . $this->getUnsubscribeUrl() . '">'
      . Class_AdminVar::getValueOrDefault('NEWSLETTER_UNSUBSCRIBE_HTML')
      . '</a>';
  }
262 263


264
  protected function _getBodyText($records, $articles) {
265
    $lines = [$this->_htmlToText($this->getContenu())];
266

267
    $renderer = new Class_Notice_MailRenderer();
268
    foreach($records as $record)
269
      $renderer->renderTextInto($record, $lines);
270

271
    $renderer = new Class_Article_MailRenderer();
272
    foreach($articles as $article)
273
      $renderer->renderTextInto($article, $lines);
274

Patrick Barroca's avatar
Patrick Barroca committed
275
    $lines[] = $this->_getUnsubscribeText();
276

Patrick Barroca's avatar
Patrick Barroca committed
277 278
    return implode("\n", $lines);
  }
279

280

Patrick Barroca's avatar
Patrick Barroca committed
281 282 283 284
  /**
   * @return string
   */
  public function getContenu() {
285
    return (new Class_CmsUrlTransformer())->imgUrlRelativeToAbsolute(parent::getContenu());
Patrick Barroca's avatar
Patrick Barroca committed
286
  }
287 288


Patrick Barroca's avatar
Patrick Barroca committed
289
  /**
290 291 292 293
   * /!\ maybe in cli context : cannot rely on view helpers
   * @see scripts/sendNewsletter.php
   *
   * @param array $records
Patrick Barroca's avatar
Patrick Barroca committed
294 295
   * @return string
   */
296
  protected function _getBodyHTML($records, $articles) {
Patrick Barroca's avatar
Patrick Barroca committed
297
    $html = $this->getContenu();
298

299
    $renderer = new Class_Notice_MailRenderer();
300
    foreach($records as $record)
301
      $html .= $renderer->renderHtml($record);
302

303
    $renderer = new Class_Article_MailRenderer();
304
    foreach($articles as $article)
305
      $html .= $renderer->renderHtml($article);
306

307 308
    $html .= $this->_getUnsubscribeHTML();

Patrick Barroca's avatar
Patrick Barroca committed
309
    return $html;
310 311 312
  }


313 314 315 316
  public function unsubscribeUser($user) {
    $this->unsubscribeByMail($user->getMail());
  }

317

318
  public function subscribeToDedicatedGroup($user) {
Patrick Barroca's avatar
Patrick Barroca committed
319
    $this->getDedicatedGroup()->addUserOptimized($user);
320 321 322 323 324
    return $this;
  }


  public function subscribeUser($user) {
325
    $is_recipient = $this->hasRecipient($user, false);
326
    $is_blacklisted = $this->isBlackListed($user);
327 328

    if ($is_blacklisted) {
329
      Class_Newsletter_Blacklist::deleteBy(['newsletter_id' => $this->getId(),
330
                                            'mail' => $user->getMail()]);
331
    }
332

333 334 335 336 337
    if (!$is_recipient)
      return $this->subscribeToDedicatedGroup($user);

    return $this;
  }
338

339

Patrick Barroca's avatar
Patrick Barroca committed
340
  public function unsubscribeByMail($mail) {
341 342 343
    return $mail
      ? Class_Newsletter_Blacklist::unsubscribeByMail($mail, $this->getId())
      : false;
Patrick Barroca's avatar
Patrick Barroca committed
344
  }
345

346 347

  public function duplicate() {
348 349 350
    if ($this->isNew())
      return false;

351 352 353 354 355 356 357
    $attributes = $this->attributesToArray();
    unset($attributes['id']);
    unset($attributes['last_distribution_date']);
    $attributes['titre'] .= ' ('. $this->_('copie').')';

    $duplicate = new Class_Newsletter();
    $duplicate->updateAttributes($attributes);
358
    $duplicate->setDraft(true);
Alex Arnaud's avatar
Alex Arnaud committed
359 360
    if (!$duplicate->save())
      return false;
361

362 363 364
    $this
      ->duplicateDedicatedGroupIn($duplicate)
      ->duplicateGroupSubscriptionsIn($duplicate);
365

Alex Arnaud's avatar
Alex Arnaud committed
366 367
    return true;
  }
368

369

370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
  protected function duplicateDedicatedGroupIn($other) {
    $my_dedicated = $this->getDedicatedGroup();
    if (!$ids = $my_dedicated->getUsersIds())
      return $this;

    $other->getDedicatedGroup()->addAllUsersByIds($ids);
    return $this;
  }


  protected function duplicateGroupSubscriptionsIn($other) {
    $other->setUserGroups($this->getUserGroups())
          ->save();

    return $this;
  }


388 389 390
  public function getLibelle() {
    return $this->getTitre();
  }
391

392

393 394 395
  public function getLastDispatchInProgress() {
    return Class_Newsletter_Dispatch::lastDispatchInProgressFor($this);
  }
396 397


398 399 400 401 402
  public function getLastDispatch() {
    return Class_Newsletter_Dispatch::lastDispatchFor($this);
  }


403 404 405 406 407 408 409 410 411 412 413 414 415 416
  public function getSortedRecipientsByDedicatedAndLabel() {
    $groups = $this->getRecipientsGroups();
    usort(
          $groups,
          function($a, $b) {
            if ($a->isDedicated())
              return -1;
            if ($b->isDedicated())
              return 1;

            return strcmp($a->getLibelle(), $b->getLibelle());
          });
    return $groups;
  }
417 418 419 420 421 422 423 424 425


  public function addUser($user) {
    $this->getDedicatedGroup()
         ->addUser($user)
         ->save();

    return $this;
  }
426
}
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441



class Class_Newsletter_DedicatedGroupAssociation extends Storm_Model_Association_Abstract{
  use Trait_Translator;

  public function canHandle($method) {
    return in_array($method, ['getDedicatedGroup']);
  }


  public function perform($model, $method, $args) {
    $params = ['model_class' => get_class($model),
               'model_id' => $model->getId()];

442
    $group = ($group = Class_UserGroup::findFirstBy($params))
443
      ? $group
444 445 446 447 448 449 450
      : Class_UserGroup::newInstance(array_merge($params, ['id_cat' => 0,
                                                           'libelle' => $this->_labelFrom($model)]));

    if ((!$model->isNew()) && $group->isNew())
      $group->save();

    return $group;
451 452 453 454 455 456
  }


  public function save($model) {
    $model
      ->getDedicatedGroup()
457
      ->setLibelle($this->_labelFrom($model))
458 459 460 461 462 463 464 465 466 467 468 469
      ->save();
  }


  public function saveBefore($model) {

  }


  public function delete($model) {
    $model->getDedicatedGroup()->delete();
  }
470 471 472 473 474


  protected function _labelFrom($model) {
    return $this->_('Groupe manuel pour la lettre "%s"', $model->getTitre());
  }
475
}