/**
  * @param Petition $petition
  * @return PetitionText
  */
 public function getPetitionTextForPetition(Petition $petition)
 {
     return PetitionTextTable::getInstance()->fetchByPetitionAndPrefLang($petition, $this->getLanguageId() ?: 'en');
 }
 public function executeEdit(sfWebRequest $request)
 {
     $route_params = $this->getRoute()->getParameters();
     if (isset($route_params['new'])) {
         // CREATE FORM OR REDIRECT TO CREATE FORM
         if (!$request->isMethod('post')) {
             return $this->redirect($this->generateUrl('dashboard'));
         }
         $petition = PetitionTable::getInstance()->findById($request->getParameter('id', $this->userIsAdmin()));
         /* @var $petition Petition */
         if (!$petition) {
             return $this->notFound();
         }
         if (!$this->getGuardUser()->isPetitionMember($petition, true)) {
             return $this->noAccess();
         }
         $widget = new Widget();
         $widget->setPetition($petition);
         $widget->setCampaignId($petition->getCampaignId());
         $widget->setUser($this->getGuardUser());
         $this->ajax()->setAlertTarget('#new_widget', 'after');
         $lang = $request->getPostParameter('lang');
         if (!$lang || !is_numeric($lang)) {
             return $this->ajax()->alert('Please select a language.')->render();
         }
         $pt = PetitionTextTable::getInstance()->find($lang);
         /* @var $pt PetitionText */
         if (!$pt || $pt->getPetitionId() != $petition->getId()) {
             return $this->notFound();
         }
         if ($pt->getStatus() != PetitionText::STATUS_ACTIVE) {
             return $this->ajax()->alert('Translation not active', 'Error')->render();
         }
         $widget->setPetitionText($pt);
         $this->form = new EditWidgetForm($widget);
         $this->lang = $pt->getId();
         if (!$request->getPostParameter($this->form->getName()) && !$request->getPostParameter('page')) {
             return $this->ajax()->redirectPostRoute('widget_create', array('id' => $petition->getId()), array('page' => 1, 'lang' => $pt->getId()))->render();
         }
     } else {
         // EDIT FORM
         $widget = WidgetTable::getInstance()->find($request->getParameter('id'));
         /* @var $widget Widget */
         if (!$widget || !($this->getGuardUser()->isPetitionMember($widget->getPetition(), true) || $widget->getUserId() == $this->getGuardUser()->getId())) {
             return $this->noAccess();
         }
         if (!$this->userIsAdmin() && ($widget->getPetition()->getStatus() == Petition::STATUS_DELETED || $widget->getCampaign()->getStatus() == CampaignTable::STATUS_DELETED)) {
             return $this->notFound();
         }
         $this->form = new EditWidgetForm($widget);
     }
     $this->petition = $widget->getPetition();
     if ($request->isMethod('post') && !$request->getPostParameter('page')) {
         $this->form->bind($request->getPostParameter($this->form->getName()));
         if ($this->form->isValid()) {
             $this->form->save();
             if ($widget->getStatus() == Widget::STATUS_ACTIVE && !$widget->getPetitionText()->getWidgetId()) {
                 $widget->getPetitionText()->setDefaultWidget($widget);
                 $widget->getPetitionText()->save();
             }
             if ($this->getGuardUser()->isPetitionMember($widget->getPetition(), true)) {
                 return $this->ajax()->redirectRotue('petition_widgets', array('id' => $this->petition->getId()))->render();
             } else {
                 return $this->ajax()->redirectRotue('widget_index')->render();
             }
         } else {
             return $this->ajax()->form($this->form)->render();
         }
     }
     $this->includeMarkdown();
     $this->includeHighlight();
 }
 protected function execute($arguments = array(), $options = array())
 {
     $context = sfContext::createInstance($this->configuration);
     $i18n = $context->getI18N();
     // initialize the database connection
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connection = $databaseManager->getDatabase($options['connection'])->getConnection();
     $petition_text_by_lang = array();
     $table = PetitionSigningTable::getInstance();
     $con = $table->getConnection();
     $con->beginTransaction();
     try {
         $petition_signing = $table->createQuery('ps')->addFrom('ps.PetitionSigningWave psw')->where('ps.wave_cron > 0')->andWhere('DATE_SUB(NOW(),INTERVAL 2 MINUTE) > ps.updated_at')->andWhere('psw.status = ?', PetitionSigning::STATUS_VERIFIED)->orderBy('ps.created_at DESC')->fetchOne();
         if (empty($petition_signing)) {
             echo "nothing pending. (stop)";
             $connection->rollback();
             return;
         }
         /* @var $petition_signing PetitionSigning */
         $petition = $petition_signing->getPetition();
         /* @var $petition Petition */
         $is_pledge = $petition->getKind() == Petition::KIND_PLEDGE;
         $waves_verified = array();
         foreach ($petition_signing->getPetitionSigningWave() as $wave) {
             if ($wave->getStatus() == PetitionSigning::STATUS_VERIFIED) {
                 $waves_verified[] = $wave->getWave();
                 $wave->setStatus(PetitionSigning::STATUS_SENT);
             }
         }
         $contacts = ContactTable::getInstance()->createQuery('c')->addFrom('c.PetitionSigningContact psc')->where('psc.petition_signing_id = ?', $petition_signing->getId())->andWhereIn('psc.wave', $waves_verified)->addFrom('c.ContactMeta cm')->addFrom('cm.MailingListMetaChoice mlmc')->fetchArray();
         $subst_fields = $petition_signing->getPetition()->getGeoSubstFields();
         $i = 0;
         foreach ($contacts as $contact) {
             $subst = $petition_signing->getSubst();
             foreach ($subst_fields as $pattern => $subst_field) {
                 switch ($subst_field['type']) {
                     case 'fix':
                         $subst[$pattern] = $contact[$subst_field['id']];
                         break;
                     case 'free':
                         $subst[$pattern] = '';
                         foreach ($contact['ContactMeta'] as $cm) {
                             if ($cm['mailing_list_meta_id'] == $subst_field['id']) {
                                 $subst[$pattern] = $cm['value'];
                             }
                         }
                         break;
                     case 'choice':
                         $subst[$pattern] = '';
                         foreach ($contact['ContactMeta'] as $cm) {
                             if ($cm['mailing_list_meta_id'] == $subst_field['id']) {
                                 $subst[$pattern] = $cm['MailingListMetaChoice']['choice'];
                             }
                         }
                         break;
                 }
             }
             $wave = $petition_signing->getWave($contact['PetitionSigningContact'][0]['wave']);
             $wave_lang_id = $wave->getLanguageId();
             if ($wave_lang_id) {
                 $i18n->setCulture($wave_lang_id);
             }
             if ($contact['gender'] == Contact::GENDER_FEMALE) {
                 $personal_salutation = $i18n->__('Dear Madam %F %L,', array('%F' => $contact['firstname'], '%L' => $contact['lastname']));
             } elseif ($contact['gender'] == Contact::GENDER_MALE) {
                 $personal_salutation = $i18n->__('Dear Sir %F %L,', array('%F' => $contact['firstname'], '%L' => $contact['lastname']));
             } else {
                 $personal_salutation = $i18n->__('Dear Sir/Madam %F %L,', array('%F' => $contact['firstname'], '%L' => $contact['lastname']));
             }
             $personal_salutation .= "\n\n";
             $subst[PetitionTable::KEYWORD_PERSONAL_SALUTATION] = $personal_salutation;
             if ($wave) {
                 if ($is_pledge) {
                     $petition_contact = PetitionContactTable::getInstance()->findOneByPetitionIdAndContactId($petition->getId(), $contact['id']);
                     if (!$petition_contact) {
                         $petition_contact = new PetitionContact();
                         $petition_contact->setPetitionId($petition->getId());
                         $petition_contact->setContactId($contact['id']);
                         $new_secret = '';
                         while (strlen($new_secret) < 15) {
                             $new_secret .= strtoupper(strtr(base_convert(mt_rand(), 10, 36), array('0' => '', 'o' => '')));
                         }
                         $petition_contact->setSecret(substr($new_secret, 0, 15));
                         $petition_contact->save();
                     }
                     $secret = $petition_contact->getSecret();
                     $subst['#PLEDGE-URL#'] = $this->getRouting()->generate('pledge_contact', array('petition_id' => $petition->getId(), 'contact_id' => $contact['id'], 'secret' => $secret), true);
                 }
                 if (array_key_exists($contact['language_id'], $petition_text_by_lang)) {
                     $petition_text = $petition_text_by_lang[$contact['language_id']];
                 } else {
                     $petition_text = PetitionTextTable::getInstance()->fetchByPetitionAndPrefLang($petition, $contact['language_id'], Doctrine_Core::HYDRATE_ARRAY);
                     $petition_text_by_lang[$contact['language_id']] = $petition_text;
                 }
                 if ($petition->getKind() == Petition::KIND_PLEDGE) {
                     if ($petition_text) {
                         $subject = $petition_text['email_subject'];
                         $body = $petition_text['email_body'];
                     } else {
                         $subject = $body = '';
                     }
                 } else {
                     $subject = $wave->getField(Petition::FIELD_EMAIL_SUBJECT);
                     $body = $wave->getField(Petition::FIELD_EMAIL_BODY);
                 }
                 if ($petition_text) {
                     UtilMail::appendMissingKeywords($body, $petition_text['email_body'], PetitionSigningTable::$KEYWORDS);
                 }
                 $i++;
                 try {
                     /* Email to target  */
                     UtilMail::send(null, $wave->getEmailContact($petition->getFromEmail(), true), array($contact['email'] => $contact['firstname'] . ' ' . $contact['lastname']), $subject, $body, null, $subst, null, $wave->getEmailContact());
                     /* email problem */
                 } catch (Swift_RfcComplianceException $e) {
                     // ignore invalid emails
                 }
             }
         }
         $id = $petition_signing->getId();
         $waves_sent = implode(',', $waves_verified);
         $petition_signing->setWaveSent($petition_signing->getWaveCron());
         $petition_signing->setWaveCron(0);
         $petition_signing->save();
         echo "{$i} mails sent. [{$id}:{$waves_sent}] (continue)";
         $con->commit();
     } catch (Exception $e) {
         $con->rollback();
         print $e;
         echo 'exception in transaction. (stop)';
     }
 }
 public function executeTranslationEdit(sfWebRequest $request)
 {
     $route_params = $this->getRoute()->getParameters();
     $copy = null;
     if (isset($route_params['new'])) {
         $petition = PetitionTable::getInstance()->findById($request->getParameter('id'), $this->userIsAdmin());
         /* @var $petition Petition */
         if (!$petition) {
             return $this->notFound();
         }
         $translation = new PetitionText();
         $translation->setPetition($petition);
         $copy_id = $request->getGetParameter('copy');
         if (is_numeric($copy_id)) {
             $copy = PetitionTextTable::getInstance()->find($copy_id);
             /* @var $copy PetitionText */
             if ($copy && $copy->getPetitionId() != $petition->getId()) {
                 $copy = null;
             }
         }
     } else {
         $translation = PetitionTextTable::getInstance()->find($request->getParameter('id'));
         /* @var $translation PetitionText */
         if (!$translation) {
             return $this->notFound();
         }
         $petition = $translation->getPetition();
         if ($petition->getStatus() == Petition::STATUS_DELETED && !$this->userIsAdmin()) {
             return $this->notFound();
         }
         if (!$this->userIsAdmin() && $petition->getCampaign()->getStatus() == CampaignTable::STATUS_DELETED) {
             return $this->notFound();
         }
     }
     if (!$petition->isEditableBy($this->getGuardUser())) {
         return $this->noAccess();
     }
     $this->form = new TranslationForm($translation, array('copy' => $copy));
     if ($request->isMethod('post')) {
         $this->form->bind($request->getPostParameter($this->form->getName()));
         if ($this->form->isValid()) {
             $this->form->save();
             if ($request->getPostParameter('go_translation')) {
                 if ($translation->getStatus() == PetitionText::STATUS_ACTIVE) {
                     return $this->ajax()->redirectPostRoute('widget_create', array('id' => $petition->getId()), array('page' => 1, 'lang' => $translation->getId()))->render();
                 } else {
                     return $this->ajax()->redirectRotue('petition_translations', array('id' => $petition->getId()), array('a' => 1))->render();
                 }
             }
             return $this->ajax()->redirectRotue('petition_translations', array('id' => $petition->getId()))->render();
         }
         return $this->ajax()->form($this->form)->render();
     }
     $this->translation = $translation;
     $this->petition = $petition;
     $this->includeMarkdown();
     $this->includeHighlight();
 }
 public function configure()
 {
     $this->widgetSchema->setFormFormatterName('bootstrapInline');
     $this->widgetSchema->setNameFormat('%s');
     $this->setWidget('lang', new sfWidgetFormDoctrineChoice(array('model' => 'PetitionText', 'query' => PetitionTextTable::getInstance()->queryByPetitionAndActive($this->getOption(self::OPTION_PETITION), true), 'method' => 'getLanguage', 'add_empty' => 'select language', 'label' => false)));
 }