예제 #1
0
 public function pruebaMailing()
 {
     $mailing = new MailingList('55c10856a8269769ac822f9a');
     $mailing->getData();
     $view = $mailing->getView();
     return view($view, ['data' => $mailing->getData()]);
 }
예제 #2
0
 /**
  * Set the subject line, from email, and from name, and reply
  * email according to the passed settings and the list defaults.
  * @return array Revised settings
  */
 protected function getCampaignSettings()
 {
     // get list defaults
     $list = new MailingList($this->api, $this->settings["list_id"]);
     $listInfo = $list->get();
     $listDefaults = $listInfo->campaign_defaults;
     // compile settings based on passed settings and list defaults
     $settings = array("title" => $this->settings["title"], "subject_line" => isset($this->settings["subject"]) ? $this->settings["subject"] : $listDefaults->subject, "from_email" => isset($this->settings["from_email"]) ? $this->settings["from_email"] : $listDefaults->from_email, "from_name" => isset($this->settings["from_name"]) ? $this->settings["from_name"] : $listDefaults->from_name);
     $settings["reply_to"] = $settings["from_email"];
     return $settings;
 }
예제 #3
0
파일: ml.inc.php 프로젝트: Ekleog/platal
 public function Prepare($page)
 {
     parent::Prepare($page);
     $res = XDB::iterRow("SELECT  sub, domain\n                               FROM  register_subs\n                              WHERE  uid = {?} AND type = 'list'\n                           ORDER BY  domain", S::i('uid'));
     $lists = array();
     while (list($sub, $domain) = $res->next()) {
         $mlist = new MailingList($sub, $domain);
         list($details, ) = $mlist->getMembers();
         $lists["{$sub}@{$domain}"] = $details;
     }
     $page->assign_by_ref('lists', $lists);
 }
 public function getCMSFields()
 {
     $fields = parent::getCMSFields();
     $fields->addFieldToTab("Root", $subscriptionTab = new Tab(_t('Newsletter.SUBSCRIPTIONFORM', 'SubscriptionForm')));
     Requirements::javascript('newsletter/javascript/SubscriptionPage.js');
     Requirements::css('newsletter/css/SubscriptionPage.css');
     $subscriptionTab->push(new HeaderField("SubscriptionFormConfig", _t('Newsletter.SUBSCRIPTIONFORMCONFIGURATION', "Subscription Form Configuration")));
     $subscriptionTab->push(new TextField('CustomisedHeading', 'Heading at the top of the form'));
     //Fields selction
     $frontFields = singleton('Recipient')->getFrontEndFields()->dataFields();
     $fieldCandidates = array();
     if (count($frontFields)) {
         foreach ($frontFields as $fieldName => $dataField) {
             $fieldCandidates[$fieldName] = $dataField->Title() ? $dataField->Title() : $dataField->Name();
         }
     }
     //Since Email field is the Recipient's identifier,
     //and newsletters subscription is non-sence if no email is given by the user,
     //we should force that email to be checked and required.
     //FisrtName should be checked as default, though it might not be required
     $defaults = array("Email", "FirstName");
     $extra = array('CustomLabel' => "Varchar", "ValidationMessage" => "Varchar", "Required" => "Boolean");
     $extraValue = array('CustomLabel' => $this->CustomLabel, "ValidationMessage" => $this->ValidationMessage, "Required" => $this->Required);
     $subscriptionTab->push($fieldsSelection = new CheckboxSetWithExtraField("Fields", _t('Newsletter.SelectFields', "Select the fields to display on the subscription form"), $fieldCandidates, $extra, $defaults, $extraValue));
     $fieldsSelection->setCellDisabled(array("Email" => array("Value", "Required")));
     //Mailing Lists selection
     $mailinglists = MailingList::get();
     $newsletterSelection = $mailinglists && $mailinglists->count() ? new CheckboxSetField("MailingLists", _t("Newsletter.SubscribeTo", "Newsletters to subscribe to"), $mailinglists->map('ID', 'FullTitle'), $mailinglists) : new LiteralField("NoMailingList", sprintf('<p>%s</p>', sprintf('You haven\'t defined any mailing list yet, please go to ' . '<a href=\\"%s\\">the newsletter administration area</a> ' . 'to define a mailing list.', singleton('NewsletterAdmin')->Link())));
     $subscriptionTab->push($newsletterSelection);
     $subscriptionTab->push(new TextField("SubmissionButtonText", "Submit Button Text"));
     $subscriptionTab->push(new LiteralField('BottomTaskSelection', sprintf('<div id="SendNotificationControlls" class="field actions">' . '<label class="left">%s</label>' . '<ul><li class="ss-ui-button no" data-panel="no">%s</li>' . '<li class="ss-ui-button yes" data-panel="yes">%s</li>' . '</ul></div>', _t('Newsletter.SendNotif', 'Send notification email to the subscriber'), _t('Newsletter.No', 'No'), _t('Newsletter.Yes', 'Yes'))));
     $subscriptionTab->push(CompositeField::create(new HiddenField("SendNotification", "Send Notification"), new TextField("NotificationEmailSubject", _t('Newsletter.NotifSubject', "Notification Email Subject Line")), new TextField("NotificationEmailFrom", _t('Newsletter.FromNotif', "From Email Address for Notification Email")))->addExtraClass('SendNotificationControlledPanel'));
     $subscriptionTab->push(new HtmlEditorField('OnCompleteMessage', _t('Newsletter.OnCompletion', 'Message shown on subscription completion')));
     return $fields;
 }
예제 #5
0
 public static function IsCandidate(User $user, $candidate)
 {
     $profile = $user->profile();
     if (!$profile) {
         return false;
     }
     // We only test if the user is in her promotion group for it is too
     // expensive to check if she is in the corresponding ML as well.
     $res = XDB::query('SELECT  COUNT(*)
                          FROM  group_members
                         WHERE  uid = {?} AND asso_id = (SELECT  id
                                                           FROM  groups
                                                          WHERE  diminutif = {?})', $user->id(), $user->profile()->yearPromo());
     $mlCount = $res->fetchOneCell();
     if ($mlCount) {
         Reminder::MarkCandidateAsAccepted($user->id(), $candidate);
     }
     if ($mlCount == 0) {
         $mlist = MailingList::promo($user->profile()->yearPromo());
         try {
             $mlist->getMembersLimit(0, 0);
         } catch (Exception $e) {
             return false;
         }
     }
     return false;
 }
예제 #6
0
 /**
  * Create a new instance and populate its properties with JSON data
  * @param array $jsonData
  * @return \moosend\Models\Campaign
  */
 public static function withJSON(array $jsonData)
 {
     $instance = new self();
     $instance->ID = $jsonData['ID'];
     $instance->Name = $jsonData['Name'];
     $instance->Subject = $jsonData['Subject'];
     $instance->WebLocation = $jsonData['WebLocation'];
     $instance->HTMLContent = $jsonData['HTMLContent'];
     $instance->PlainContent = $jsonData['PlainContent'];
     $instance->Sender = Sender::withJSON($jsonData['Sender']);
     $instance->DeliveredOn = $jsonData['DeliveredOn'];
     $instance->ReplyToEmail = Sender::withJSON($jsonData['ReplyToEmail']);
     $instance->CreatedOn = $jsonData['CreatedOn'];
     $instance->UpdatedOn = $jsonData['UpdatedOn'];
     $instance->ScheduledFor = $jsonData['ScheduledFor'];
     $instance->Timezone = $jsonData['Timezone'];
     $instance->FormatType = $jsonData['FormatType'];
     $instance->ABCampaignData = ABCampaignData::withJSON($jsonData['ABCampaignData']);
     $instance->MailingList = MailingList::withJSON($jsonData['MailingList']);
     $instance->ConfirmationTo = $jsonData['ConfirmationTo'];
     $instance->Status = $jsonData['Status'];
     if (isset($jsonData['Segment'])) {
         $instance->Segment = Segment::withJSON($jsonData['Segment']);
     }
     $instance->IsTransactional = $jsonData['IsTransactional'];
     return $instance;
 }
 public function getCMSFields()
 {
     $fields = parent::getCMSFields();
     $fields->addFieldToTab("Root.Main", new HeaderField("InformAdminAboutNewsletter", _t("OrderStep.EMAILDETAILSTO", "Email details to"), 3), "SendMessageToAdmin");
     $fields->replaceField("SendCopyTo", new EmailField("SendCopyTo", _t("OrderStep.SENDCOPYTO", "Send a copy (another e-mail) to ...")));
     $mailingLists = MailingList::get()->map();
     $fields->addFieldToTab("Root.MailingLists", new CheckboxSetField("MailingLists", _t("OrderForm.SIGNUPTONEWSLETTER", "Sign up"), $mailingLists));
     return $fields;
 }
 /**
  * @Given /^I add the "([^"]*)" mailinglist to the "([^"]*)" page$/
  */
 public function iAddTheMailinglistToThePage($mailinglistTitle, $pageUrl)
 {
     $mailinglist = \MailingList::get()->filter('Title', $mailinglistTitle)->First();
     assertNotNull($mailinglist, 'Could not find MailingList with ' . $mailinglistTitle);
     $page = \SubscriptionPage::get()->filter('URLSegment', $pageUrl)->First();
     assertNotNull($page);
     $lists = $page->MailingLists ? explode(',', $page->MailingLists) : array();
     $lists[] = $mailinglist->ID;
     $page->MailingLists = implode(',', $lists);
     $page->write();
     $page->publish('Stage', 'Live');
 }
 public function getCMSFields()
 {
     $fields = new FieldList();
     $fields->push(new TabSet("Root", $mainTab = new Tab("Main")));
     $mainTab->setTitle(_t('SiteTree.TABMAIN', "Main"));
     $fields->addFieldToTab('Root.Main', new TextField('Email', $this->fieldLabel('Email')));
     $fields->addFieldsToTab('Root.Main', array(Object::create('TextField', 'Salutation', $this->fieldLabel('Salutation')), Object::create('TextField', 'FirstName', $this->fieldLabel('First Name')), Object::create('TextField', 'MiddleName', $this->fieldLabel('Middle Name')), Object::create('TextField', 'Surname', $this->fieldLabel('Surname'))));
     if (!empty($this->ID)) {
         $fields->addFieldToTab('Root.Main', Object::create('CheckboxSetField', 'MailingLists', $this->fieldLabel('MailingLists'), MailingList::get()->map('ID', 'FullTitle')));
     }
     $fields->addFieldsToTab('Root.Main', array(Object::create('ReadonlyField', 'BouncedCount', $this->fieldLabel('BouncedCount')), Object::create('CheckboxField', 'Verified', $this->fieldLabel('Verified'))->setDescription(_t('Newsletter.VerifiedDesc', 'Has this user verified his subscription?')), Object::create('CheckboxField', 'Blacklisted', $this->fieldLabel('Blacklisted'))->setDescription(_t('Newsletter.BlacklistedDesc', 'Excluded from emails, either by automated process or manually. ' . 'An invalid address or undeliverable email will eventually result in blacklisting.')), Object::create('ReadonlyField', 'ReceivedCount', $this->fieldLabel('ReceivedCount'))->setDescription(_t('Newsletter.ReceivedCountDesc', 'Number of emails sent without undeliverable errors. ' . 'Only one indication that an email has actually been received and read.'))));
     $this->extend('updateCMSFields', $fields);
     return $fields;
 }
예제 #10
0
파일: register.php 프로젝트: Ekleog/platal
 function handler_end($page, $hash = null)
 {
     global $globals;
     $_SESSION['subState'] = array('step' => 5);
     // Reject registration requests from unsafe IP addresses (and remove the
     // registration information from the database, to prevent IP changes).
     if (check_ip('unsafe')) {
         send_warning_mail('Une IP surveillée a tenté de finaliser son inscription.');
         XDB::execute("DELETE FROM  register_pending\n                                WHERE  hash = {?} AND hash != 'INSCRIT'", $hash);
         return PL_FORBIDDEN;
     }
     // Retrieve the pre-registration information using the url-provided
     // authentication token.
     $res = XDB::query("SELECT  r.uid, p.pid, r.forlife, r.bestalias, r.mailorg2,\n                                   r.password, r.email, r.services, r.naissance,\n                                   ppn.lastname_initial, ppn.firstname_initial, pe.promo_year,\n                                   pd.promo, p.sex, p.birthdate_ref, a.type, a.email AS old_account_email\n                             FROM  register_pending AS r\n                       INNER JOIN  accounts         AS a   ON (r.uid = a.uid)\n                       INNER JOIN  account_profiles AS ap  ON (a.uid = ap.uid AND FIND_IN_SET('owner', ap.perms))\n                       INNER JOIN  profiles         AS p   ON (p.pid = ap.pid)\n                       INNER JOIN  profile_public_names AS ppn ON (ppn.pid = p.pid)\n                       INNER JOIN  profile_display  AS pd  ON (p.pid = pd.pid)\n                       INNER JOIN  profile_education AS pe ON (pe.pid = p.pid AND FIND_IN_SET('primary', pe.flags))\n                            WHERE  hash = {?} AND hash != 'INSCRIT' AND a.state = 'pending'", $hash);
     if (!$hash || $res->numRows() == 0) {
         $page->kill("<p>Cette adresse n'existe pas, ou plus, sur le serveur.</p>\n                         <p>Causes probables&nbsp;:</p>\n                         <ol>\n                           <li>Vérifie que tu visites l'adresse du dernier\n                               email reçu s'il y en a eu plusieurs.</li>\n                           <li>Tu as peut-être mal copié l'adresse reçue par\n                               email, vérifie-la à la main.</li>\n                           <li>Tu as peut-être attendu trop longtemps pour\n                               confirmer. Les pré-inscriptions sont annulées\n                               tous les 30 jours.</li>\n                           <li>Tu es en fait déjà inscrit.</li>\n                        </ol>");
     }
     list($uid, $pid, $forlife, $bestalias, $emailXorg2, $password, $email, $services, $birthdate, $lastname, $firstname, $yearpromo, $promo, $sex, $birthdate_ref, $type, $old_account_email) = $res->fetchOneRow();
     $isX = $type == 'x';
     $mail_domain = User::$sub_mail_domains[$type] . $globals->mail->domain;
     // Prepare the template for display.
     $page->changeTpl('register/end.tpl');
     $page->assign('forlife', $forlife);
     $page->assign('firstname', $firstname);
     // Check if the user did enter a valid password; if not (or if none is found),
     // get her an information page.
     if (Post::has('response')) {
         $expected_response = sha1("{$forlife}:{$password}:" . S::v('challenge'));
         if (Post::v('response') != $expected_response) {
             $page->trigError("Mot de passe invalide.");
             S::logger($uid)->log('auth_fail', 'bad password (register/end)');
             return;
         }
     } else {
         return;
     }
     //
     // Create the user account.
     //
     XDB::startTransaction();
     XDB::execute("UPDATE  accounts\n                         SET  password = {?}, state = 'active',\n                              registration_date = NOW(), email = NULL\n                       WHERE  uid = {?}", $password, $uid);
     XDB::execute("UPDATE  profiles\n                         SET  birthdate = {?}, last_change = NOW()\n                       WHERE  pid = {?}", $birthdate, $pid);
     XDB::execute('INSERT INTO  email_source_account (email, uid, type, flags, domain)
                        SELECT  {?}, {?}, \'forlife\', \'\', id
                          FROM  email_virtual_domains
                         WHERE  name = {?}', $forlife, $uid, $mail_domain);
     XDB::execute('INSERT INTO  email_source_account (email, uid, type, flags, domain)
                        SELECT  {?}, {?}, \'alias\', \'bestalias\', id
                          FROM  email_virtual_domains
                         WHERE  name = {?}', $bestalias, $uid, $mail_domain);
     if ($emailXorg2) {
         XDB::execute('INSERT INTO  email_source_account (email, uid, type, flags, domain)
                            SELECT  {?}, {?}, \'alias\', \'\', id
                              FROM  email_virtual_domains
                             WHERE  name = {?}', $emailXorg2, $uid, $mail_domain);
     }
     XDB::commit();
     // Try to start a session (so the user don't have to log in); we will use
     // the password available in Post:: to authenticate the user.
     Platal::session()->start(AUTH_PASSWD);
     // Add the registration email address as first and only redirection.
     require_once 'emails.inc.php';
     $user = User::getSilentWithUID($uid);
     $redirect = new Redirect($user);
     $redirect->add_email($email);
     fix_bestalias($user);
     // If the user was registered to some aliases and MLs, we must change
     // the subscription to her forlife email.
     if ($old_account_email) {
         $listClient = new MMList($user);
         $listClient->change_user_email($old_account_email, $user->forlifeEmail());
         update_alias_user($old_account_email, $user->forlifeEmail());
     }
     // Subscribe the user to the services she did request at registration time.
     require_once 'newsletter.inc.php';
     foreach (explode(',', $services) as $service) {
         switch ($service) {
             case 'ax_letter':
                 /* This option is deprecated by 'com_letters' */
                 NewsLetter::forGroup(NewsLetter::GROUP_AX)->subscribe($user);
                 break;
             case 'com_letters':
                 NewsLetter::forGroup(NewsLetter::GROUP_AX)->subscribe($user);
                 NewsLetter::forGroup(NewsLetter::GROUP_EP)->subscribe($user);
                 NewsLetter::forGroup(NewsLetter::GROUP_FX)->subscribe($user);
                 break;
             case 'nl':
                 NewsLetter::forGroup(NewsLetter::GROUP_XORG)->subscribe($user);
                 break;
             case 'imap':
                 Email::activate_storage($user, 'imap', Bogo::IMAP_DEFAULT);
                 break;
             case 'ml_promo':
                 if ($isX) {
                     $r = XDB::query('SELECT id FROM groups WHERE diminutif = {?}', $yearpromo);
                     if ($r->numRows()) {
                         $asso_id = $r->fetchOneCell();
                         XDB::execute('INSERT IGNORE INTO  group_members (uid, asso_id)
                                                   VALUES  ({?}, {?})', $uid, $asso_id);
                         try {
                             MailingList::subscribePromo($yearpromo, $user);
                         } catch (Exception $e) {
                             PlErrorReport::report($e);
                             $page->trigError("L'inscription à la liste promo" . $yearpromo . " a échouée.");
                         }
                     }
                 }
                 break;
         }
     }
     // Log the registration in the user session.
     S::logger($uid)->log('inscription', $email);
     XDB::execute("UPDATE  register_pending\n                         SET  hash = 'INSCRIT'\n                       WHERE  uid = {?}", $uid);
     // Congratulate our newly registered user by email.
     $mymail = new PlMailer('register/success.mail.tpl');
     $mymail->addTo("\"{$user->fullName()}\" <{$user->forlifeEmail()}>");
     if ($isX) {
         $mymail->setSubject('Bienvenue parmi les X sur le web !');
     } else {
         $mymail->setSubject('Bienvenue sur Polytechnique.org !');
     }
     $mymail->assign('forlife', $forlife);
     $mymail->assign('firstname', $firstname);
     $mymail->send();
     // Index the user, to allow her to appear in searches.
     Profile::rebuildSearchTokens($pid);
     // Notify other users which were watching for her arrival.
     XDB::execute('INSERT INTO  contacts (uid, contact)
                        SELECT  uid, {?}
                          FROM  watch_nonins
                         WHERE  ni_id = {?}', $pid, $uid);
     XDB::execute('DELETE FROM  watch_nonins
                         WHERE  ni_id = {?}', $uid);
     Platal::session()->updateNbNotifs();
     // Forcibly register the new user on default forums.
     $registeredForums = array('xorg.general', 'xorg.pa.divers', 'xorg.pa.logements');
     if ($isX) {
         $promoForum = 'xorg.promo.' . strtolower($promo);
         $exists = XDB::fetchOneCell('SELECT  COUNT(*)
                                        FROM  forums
                                       WHERE  name = {?}', $promoForum);
         if ($exists == 0) {
             // Notify the newsgroup admin of the promotion forum needs be created.
             $promoFull = new UserFilter(new UFC_Promo('=', UserFilter::DISPLAY, $promo));
             $promoRegistered = new UserFilter(new PFC_And(new UFC_Promo('=', UserFilter::DISPLAY, $promo), new UFC_Registered(true), new PFC_Not(new UFC_Dead())));
             if ($promoRegistered->getTotalCount() > 0.2 * $promoFull->getTotalCount()) {
                 $mymail = new PlMailer('admin/forums-promo.mail.tpl');
                 $mymail->assign('promo', $promo);
                 $mymail->send();
             }
         } else {
             $registeredForums[] = $promoForum;
         }
     }
     foreach ($registeredForums as $forum) {
         XDB::execute("INSERT INTO  forum_subs (fid, uid)\n                               SELECT  fid, {?}\n                                 FROM  forums\n                                WHERE  name = {?}", $uid, $val);
     }
     // Update the global registration count stats.
     $globals->updateNbIns();
     //
     // Update collateral data sources, and inform watchers by email.
     //
     // Email the referrer(s) of this new user.
     $res = XDB::iterRow("SELECT  sender, GROUP_CONCAT(email SEPARATOR ', ') AS mails, MAX(last) AS lastDate\n                               FROM  register_marketing\n                              WHERE  uid = {?}\n                           GROUP BY  sender\n                           ORDER BY  lastDate DESC", $uid);
     XDB::execute("UPDATE  register_mstats\n                         SET  success = NOW()\n                       WHERE  uid = {?}", $uid);
     $market = array();
     while (list($senderid, $maketingEmails, $lastDate) = $res->next()) {
         $sender = User::getWithUID($senderid);
         $market[] = " - par {$sender->fullName()} sur {$maketingEmails} (le plus récemment le {$lastDate})";
         $mymail = new PlMailer('register/marketer.mail.tpl');
         $mymail->setSubject("{$firstname} {$lastname} s'est inscrit à Polytechnique.org !");
         $mymail->setTo($sender);
         $mymail->assign('sender', $sender);
         $mymail->assign('firstname', $firstname);
         $mymail->assign('lastname', $lastname);
         $mymail->assign('promo', $promo);
         $mymail->assign('sex', $sex);
         $mymail->setTxtBody(wordwrap($msg, 72));
         $mymail->send();
     }
     // Email the plat/al administrators about the registration.
     if ($globals->register->notif) {
         $mymail = new PlMailer('register/registration.mail.tpl');
         $mymail->setSubject("Inscription de {$firstname} {$lastname} ({$promo})");
         $mymail->assign('firstname', $firstname);
         $mymail->assign('lastname', $lastname);
         $mymail->assign('promo', $promo);
         $mymail->assign('sex', $sex);
         $mymail->assign('birthdate', $birthdate);
         $mymail->assign('birthdate_ref', $birthdate_ref);
         $mymail->assign('forlife', $forlife);
         $mymail->assign('email', $email);
         $mymail->assign('logger', S::logger());
         if (count($market) > 0) {
             $mymail->assign('market', implode("\n", $market));
         }
         $mymail->setTxtBody($msg);
         $mymail->send();
     }
     // Remove old pending marketing requests for the new user.
     Marketing::clear($uid);
     pl_redirect('profile/edit');
 }
예제 #11
0
 * Check for a community category to proceed (via POST) to help prevent against CSRF attacks.
 */
if (isset($_POST["community_id"]) && (int) trim($_POST["community_id"])) {
    $COMMUNITY_ID = (int) trim($_POST["community_id"]);
}
/**
 * Ensure that the selected community is editable by you.
 */
if ($COMMUNITY_ID) {
    $query = "SELECT * FROM `communities` WHERE `community_id` = " . $db->qstr($COMMUNITY_ID) . " AND `community_active` = '1'";
    $community_details = $db->GetRow($query);
    if ($community_details) {
        if ($ENTRADA_ACL->amIAllowed(new CommunityResource($COMMUNITY_ID), 'delete')) {
            if (@$db->AutoExecute("communities", array("community_active" => 0), "UPDATE", "`community_id` = " . $db->qstr($COMMUNITY_ID))) {
                if ($MAILING_LISTS["active"]) {
                    $list = new MailingList($COMMUNITY_ID);
                    $list->mode_change("inactive");
                }
                communities_log_history($COMMUNITY_ID, 0, $COMMUNITY_ID, "community_history_deactivate_page", 1);
                $SUCCESS++;
                $SUCCESSSTR[] = "<strong>You have just deactiviated " . html_encode($community_details["community_title"]) . ".</strong><br /><br />If there has been a mistake please contact the MEdTech unit directly for assistance.<br /><br />You will now be redirected back to the communities section; this will happen <strong>automatically</strong> in 5 seconds or <a href=\"" . $url . "\" style=\"font-weight: bold\">click here</a> to continue.";
                application_log("success", "Community ID [" . $COMMUNITY_ID . "] has been deactivated.");
            } else {
                $ERROR++;
                $ERRORSTR[] = "<strong>Unable to deactive " . html_encode($community_details["community_title"]) . ".</strong><br /><br />The MEdTech unit has been informed of this error, please try again later. You will now be redirected back to the communities section; this will happen <strong>automatically</strong> in 5 seconds or <a href=\"" . $url . "\" style=\"font-weight: bold\">click here</a> to continue.";
            }
        } else {
            $ERROR++;
            $ERRORSTR[] = "You are not listed as an active administrator of this community, or the community has already been deactivated. If you are having trouble, please contact a community administrator or the MEdTech Unit directly.";
            application_log("error", "The proxy_id [" . $ENTRADA_USER->getActiveId() . " / " . $ENTRADA_USER->getID() . "] is not an administrator of community_id [" . $COMMUNITY_ID . "] was not found or was already deactivated.");
        }
 function getCMSFields()
 {
     $fields = parent::getCMSFields();
     $fields->addFieldToTab("Root.Newsletter", new CheckboxSetField("MailingLists", "Show Mailing Lists", MailingList::get()->map()));
     return $fields;
 }
예제 #13
0
파일: lists.php 프로젝트: Ekleog/platal
 function handler_lists($page)
 {
     function filter_owner($list)
     {
         return $list['own'];
     }
     function filter_member($list)
     {
         return $list['sub'];
     }
     $page->changeTpl('lists/index.tpl');
     $page->setTitle('Listes de diffusion');
     if (Get::has('del')) {
         S::assert_xsrf_token();
         $mlist = $this->prepare_list(Get::v('del'));
         $mlist->unsubscribe();
         pl_redirect('lists');
     }
     if (Get::has('add')) {
         S::assert_xsrf_token();
         $mlist = $this->prepare_list(Get::v('add'));
         $mlist->subscribe();
         pl_redirect('lists');
     }
     if (Post::has('promo_add')) {
         S::assert_xsrf_token();
         $promo = Post::i('promo_add');
         if ($promo >= 1900 and $promo < 2100) {
             $mlist = MailingList::promo($promo);
             $mlist->subscribe();
         } else {
             $page->trigError("promo incorrecte, il faut une promo sur 4 chiffres.");
         }
     }
     $client = $this->prepare_client();
     if (!is_null($listes = $client->get_lists())) {
         $owner = array_filter($listes, 'filter_owner');
         $listes = array_diff_key($listes, $owner);
         $member = array_filter($listes, 'filter_member');
         $listes = array_diff_key($listes, $member);
         foreach ($owner as $key => $liste) {
             $mlist = $this->prepare_list($liste['list']);
             list($subs, $mails) = $this->get_pending_ops($mlist);
             $owner[$key]['subscriptions'] = $subs;
             $owner[$key]['mails'] = $mails;
         }
         $page->register_modifier('hdc', 'list_header_decode');
         $page->assign_by_ref('owner', $owner);
         $page->assign_by_ref('member', $member);
         $page->assign_by_ref('public', $listes);
     }
 }
예제 #14
0
 }
 $COMMUNITY_ID = 0;
 /**
  * Check for a community category to proceed.
  */
 if (isset($_GET["community"]) && (int) trim($_GET["community"])) {
     $COMMUNITY_ID = (int) trim($_GET["community"]);
 } elseif (isset($_POST["community_id"]) && (int) trim($_POST["community_id"])) {
     $COMMUNITY_ID = (int) trim($_POST["community_id"]);
 }
 /**
  * Ensure that the selected community is editable by you.
  */
 if ($COMMUNITY_ID) {
     if ($MAILING_LISTS["active"]) {
         $mailing_list = new MailingList($COMMUNITY_ID);
         $list_mode = $mailing_list->type;
         $query = "  SELECT a.*, b.`list_type`\n\t\t\t\t\t\tFROM `communities` AS a\n\t\t\t\t\t\tJOIN `community_mailing_lists` AS b\n\t\t\t\t\t\tON a.`community_id` = b.`community_id`\n\t\t\t\t\t\tWHERE a.`community_id` = " . $db->qstr($COMMUNITY_ID) . "\n\t\t\t\t\t\tAND a.`community_active` = '1'";
     } else {
         $query = "  SELECT *\n\t\t\t\t\t\tFROM `communities`\n\t\t\t\t\t\tWHERE `community_id` = " . $db->qstr($COMMUNITY_ID) . "\n\t\t\t\t\t\tAND `community_active` = '1'";
     }
     $community_details = $db->GetRow($query);
     if ($community_details) {
         $BREADCRUMB[] = array("url" => ENTRADA_URL . "/community" . $community_details["community_url"], "title" => limit_chars($community_details["community_title"], 50));
         $BREADCRUMB[] = array("url" => ENTRADA_URL . "/communities?" . replace_query(array("section" => "modify")), "title" => "Manage Community");
         $community_resource = new CommunityResource($COMMUNITY_ID);
         if ($ENTRADA_ACL->amIAllowed($community_resource, 'update')) {
             $CATEGORY_ID = $community_details["category_id"];
             echo "<h1>" . html_encode($community_details["community_title"]) . "</h1>\n";
             // Error Checking
             switch ($STEP) {
             }
         }
     } else {
         if ($community_member["member_active"]) {
             $PROCESSED_MAIL_LIST_MEMBER["community_id"] = $community_member["community_id"];
             $PROCESSED_MAIL_LIST_MEMBER["proxy_id"] = $community_member["proxy_id"];
             $PROCESSED_MAIL_LIST_MEMBER["email"] = $community_member["email"];
             $PROCESSED_MAIL_LIST_MEMBER["member_active"] = 0;
             $PROCESSED_MAIL_LIST_MEMBER["list_administrator"] = $community_member["member_acl"] ? 1 : 0;
             if (!$db->AutoExecute("`community_mailing_list_members`", $PROCESSED_MAIL_LIST_MEMBER, "INSERT")) {
                 application_log("error", "Unable to insert new `community_mailing_list_members` record. DB said: " . $db->ErrorMsg());
             }
         }
     }
 }
 $google_list = new MailingList($list["community_id"]);
 $google_list->fetch_current_list();
 $google_list_members = $google_list->current_members;
 $google_list_owners = $google_list->current_owners;
 $query = "SELECT * FROM `community_mailing_list_members`\n                                    WHERE `community_id` = " . $db->qstr($list["community_id"]);
 $local_list_members = $db->GetAll($query);
 if ($local_list_members) {
     foreach ($local_list_members as $member) {
         $add_member = false;
         $set_owner = false;
         $PROCESSED_MAIL_LIST_MEMBER = array();
         $PROCESSED_MAIL_LIST_MEMBER["community_id"] = $member["community_id"];
         $PROCESSED_MAIL_LIST_MEMBER["proxy_id"] = $member["proxy_id"];
         $PROCESSED_MAIL_LIST_MEMBER["email"] = $member["email"];
         $PROCESSED_MAIL_LIST_MEMBER["member_active"] = $member["member_active"];
         $PROCESSED_MAIL_LIST_MEMBER["list_administrator"] = $member["list_administrator"];
          */
         if (!--$limit) {
             if (!@unlink(COMMUNITY_MAIL_LIST_MEMBERS_LOCK)) {
                 application_log("error", "Unable to delete mail-list member lock file: " . COMMUNITY_MAIL_LIST_MEMBERS_LOCK);
             }
             exit;
         }
     }
 }
 $community_id = 0;
 $query = "\tSELECT a.* FROM `community_mailing_list_members` AS a\n\t\t\t\t\t\t\t\t\t\tJOIN `community_mailing_lists` AS b\n\t\t\t\t\t\t\t\t\t\tON a.`community_id` = b.`community_id`\n\t\t\t\t\t\t\t\t\t\tWHERE a.`list_administrator` = '-1'\n\t\t\t\t\t\t\t\t\t\tAND a.`member_active` = '1'\n\t\t\t\t\t\t\t\t\t\tAND b.`list_type` != 'inactive'\n\t\t\t\t\t\t\t\t\t\tORDER BY a.`community_id` ASC";
 if ($members = $db->GetAll($query)) {
     foreach ($members as $member) {
         if ($community_id != (int) $member["community_id"]) {
             $community_id = (int) $member["community_id"];
             $list = new MailingList($community_id);
             $list->fetch_current_list();
             $current_users = array_merge($list->current_owners, $list->current_members);
         }
         echo "Demote: " . $member["email"] . " -> " . $community_id . "<br/>";
         if (in_array($member["email"], $current_users)) {
             try {
                 $list->remove($member["email"]);
                 $list->add($member["email"]);
                 $list->base_edit_member($member["proxy_id"], "0", "1");
             } catch (Exception $e) {
                 echo $e->getMessage();
                 if ($e->getCode() == "502") {
                     exit;
                 }
                 application_log("notice", "An issue was encountered while attempting to demote a user's email [" . $member["email"] . "] to owner on a community [" . $community_id . "] mailing list. The server said: " . $e->getCode() . " - " . $e->getMessage());
예제 #17
0
 public function executeEdit(sfWebRequest $request)
 {
     $route_params = $this->getRoute()->getParameters();
     $this->csrf_token = UtilCSRF::gen('target_activate');
     if (isset($route_params['type']) && $route_params['type'] == 'new') {
         // CREATE
         $campaign = CampaignTable::getInstance()->findById($request->getParameter('id'), $this->userIsAdmin());
         /* @var $campaign Campaign */
         if (!$campaign) {
             return $this->notFound();
         }
         if (!$this->getGuardUser()->isCampaignMember($campaign)) {
             return $this->noAccess();
         }
         $target_list = new MailingList();
         $target_list->setCampaign($campaign);
         $target_list->setStatus(MailingListTable::STATUS_DRAFT);
     } else {
         $target_list = $this->findTargetList();
         /* @var $target_list MailingList */
         if (!$target_list) {
             return $this->notFound();
         }
         if (!$this->getGuardUser()->isTargetListMember($target_list, true)) {
             return $this->noAccess();
         }
         $this->metas = $target_list->getMailingListMeta();
     }
     if ($target_list->getCampaignId()) {
         $this->campaign = $target_list->getCampaign();
         if (!$this->userIsAdmin() && $this->campaign->getStatus() == CampaignTable::STATUS_DELETED) {
             return $this->notFound();
         }
     }
     $this->target_list = $target_list;
     $this->form = new MailingListForm($target_list);
     if ($request->isMethod('post')) {
         $form_data = $request->getPostParameter($this->form->getName());
         if ($form_data) {
             $this->form->bind($form_data);
             if ($this->form->isValid()) {
                 $was_new = $target_list->isNew();
                 $this->form->save();
                 $target_list->refresh();
                 if ($was_new) {
                     if (!$this->getGuardUser()->isCampaignAdmin($target_list->getCampaign())) {
                         $tr = new TargetListRights();
                         $tr->setUser($this->getGuardUser());
                         $tr->setMailingList($target_list);
                         $tr->setActive(1);
                         $tr->save();
                     }
                     return $this->ajax()->redirectRotue('target_edit', array('id' => $target_list->getId()))->render();
                 } else {
                     return $this->ajax()->replaceWithPartial('#form', 'form', array('form' => new MailingListForm($target_list)))->alert('Name updated', '', '#form', 'after')->render();
                 }
             } else {
                 return $this->ajax()->form($this->form)->render();
             }
         }
     }
     $this->includeIframeTransport();
     $this->includeChosen();
 }
예제 #18
0
 /**
  *
  * @param MailingList $ml
  * @param Petition $pledges_by_petition
  * @return Doctrine_Query
  */
 public function queryByMailingList(MailingList $ml, $pledges_by_petition = null)
 {
     $query = $this->createQuery('c INDEXBY c.id')->where('c.mailing_list_id = ?', $ml->getId())->orderBy('c.id');
     if ($pledges_by_petition) {
         $query->leftJoin('c.Pledges p INDEXBY p.pledge_item_id');
         $query->select('c.*, p.*');
         $query->andWhere('p.contact_id IS NULL OR (p.pledge_item_id IN (SELECT pi.id FROM PledgeItem pi WHERE pi.petition_id = ?))', $pledges_by_petition->getId());
     } else {
         $query->select('c.*');
     }
     return $query;
 }
예제 #19
0
require_once $gfwww . 'mail/admin/../mail_utils.php';
require_once $gfcommon . 'mail/MailingList.class.php';
$group_id = getIntFromRequest('group_id');
$feedback = '';
if (!$group_id) {
    exit_no_group();
}
$Group =& group_get_object($group_id);
if (!$Group || !is_object($Group) || $Group->isError()) {
    exit_no_group();
}
$perm =& $Group->getPermission(session_get_user());
if (!$perm || !is_object($perm) || $perm->isError() || !$perm->isAdmin()) {
    exit_permission_denied();
}
$ml = new MailingList($Group, getIntFromGet('group_list_id'));
if (getStringFromPost('submit')) {
    $sure = getStringFromPost('sure');
    $really_sure = getStringFromPost('really_sure');
    if (!$ml->delete($sure, $really_sure)) {
        exit_error('Error', $ml->getErrorMessage());
    } else {
        header("Location: index.php?group_id={$group_id}&feedback=DELETED");
    }
}
mail_header(array('title' => _('Permanently Delete List')));
?>
<h3><?php 
echo $ml->getName();
?>
</h3>
예제 #20
0
 * Ensure that the selected community is editable by you.
 */
if ($COMMUNITY_ID) {
    $query = "SELECT * FROM `communities` WHERE `community_id` = " . $db->qstr($COMMUNITY_ID) . " AND `community_active` = '1'";
    $community_details = $db->GetRow($query);
    if ($community_details) {
        $query = "\n\t\t\t\tSELECT * FROM `community_members`\n\t\t\t\tWHERE `community_id` = " . $db->qstr($COMMUNITY_ID) . "\n\t\t\t\tAND `proxy_id` = " . $db->qstr($ENTRADA_USER->getActiveId());
        $result = $db->GetRow($query);
        if ($result) {
            if ((int) $result["member_active"]) {
                switch ($STEP) {
                    case 2:
                        $query = "DELETE FROM `community_members` WHERE `community_id` = " . $db->qstr($COMMUNITY_ID) . " AND `proxy_id` = " . $db->qstr($ENTRADA_USER->getActiveId()) . " AND `member_active` = '1' LIMIT 1";
                        if ($db->Execute($query)) {
                            if ($MAILING_LISTS["active"]) {
                                $mail_list = new MailingList($COMMUNITY_ID);
                                $mail_list->remove_member($result["proxy_id"]);
                            }
                            if (COMMUNITY_NOTIFICATIONS_ACTIVE) {
                                community_notify($COMMUNITY_ID, $ENTRADA_USER->getActiveId(), "leave", ENTRADA_URL . "/people?id=" . $ENTRADA_USER->getActiveId(), $COMMUNITY_ID);
                            }
                            application_log("success", "Removed proxy_id [" . $ENTRADA_USER->getActiveId() . "] from community_id [" . $COMMUNITY_ID . "].");
                        } else {
                            application_log("error", "Unable to remove proxy_id [" . $ENTRADA_USER->getActiveId() . "] from community_id [" . $COMMUNITY_ID . "]. Database said: " . $db->ErrorMsg());
                        }
                        if ($_SESSION['details']['group'] == 'guest') {
                            $query = "SELECT COUNT(*) AS total FROM `community_members`\n\t\t\t\t\t\t\t\t\tWHERE `community_members`.`proxy_id` = {$result['ID']} AND `community_members`.`member_active` = 1";
                            $community_result = $db->GetRow($query);
                            if (!isset($community_result) || $community_result['total'] == 0) {
                                header("Location: " . ENTRADA_URL . "?action=logout");
                            }
 public function processValues($values)
 {
     $values = parent::processValues($values);
     if (isset($values['mailing_list_id'])) {
         $ml_id = $values['mailing_list_id'];
         if ($ml_id) {
             if (strpos($ml_id, 'c') === 0) {
                 $ml_id = substr($ml_id, 1);
                 $source_target_list = MailingListTable::getInstance()->findById($ml_id, true);
                 $copy_target_list = MailingListTable::getInstance()->copy($source_target_list, $this->getObject()->getCampaign(), $source_target_list->getName() . ' copy ' . gmdate('Y-m-d H:i'));
                 if ($copy_target_list) {
                     $user = $this->getOption(self::USER, null);
                     /* @var $user sfGuardUser */
                     $tr = new TargetListRights();
                     $tr->setMailingListId($copy_target_list->getId());
                     $tr->setUserId($user->getId());
                     $tr->setActive(1);
                     $tr->save();
                     $this->getObject()->setMailingList($copy_target_list);
                     $values['mailing_list_id'] = $copy_target_list->getId();
                 } else {
                     throw new Exception('target list copy error');
                 }
             } else {
                 $this->getObject()->setMailingList(MailingListTable::getInstance()->findById($ml_id, true));
             }
         } else {
             $ml = new MailingList();
             $ml->setCampaignId($this->getObject()->getCampaignId());
             $ml->setStatus(MailingListTable::STATUS_DRAFT);
             $ml->setName($this->getObject()->getName() . ' Target-List ' . gmdate('Y-m-d H:i'));
             $this->getObject()->setMailingList($ml);
         }
     }
     if ($this->getObject()->isGeoKind()) {
         $target_choices = $target_choices = $this->getObject()->getMailingList()->getTargetChoices();
         $set = array();
         foreach (array($this->getValue('target_selector_1'), $this->getValue('target_selector_2')) as $ts) {
             if ($ts && array_key_exists($ts, $target_choices)) {
                 $set[] = $ts;
             }
         }
         $values['email_targets'] = json_encode($set);
     }
     return $values;
 }
예제 #22
0
             foreach ($PROXY_IDS as $proxy_id) {
                 $mail_list->deactivate_member($proxy_id);
             }
         }
         $SUCCESS++;
         $SUCCESSSTR[] = "You have successfully deactivated <strong>" . $total_updated . " member" . ($total_updated != 1 ? "s" : "") . "</strong> in the <strong>" . html_encode($community_details["community_title"]) . "</strong> community.<br /><br />You will now be redirected back to the Manage Members page; this will happen <strong>automatically</strong> in 5 seconds or <a href=\"" . ENTRADA_URL . "/" . $MODULE . "?section=members&community=" . $COMMUNITY_ID . "\" style=\"font-weight: bold\">click here</a> to continue.";
     } else {
         $ERROR++;
         $ERRORSTR[] = "There was a problem deactivating these community members in the system; the MEdTech Unit has been informed of this error, please try again later.";
         application_log("error", "Unable to deactivate members from community_id [" . $COMMUNITY_ID . "]. Database said: " . $db->ErrorMsg());
     }
     break;
 case "promote":
     if ($db->AutoExecute("community_members", array("member_acl" => 1), "UPDATE", "`community_id` = " . $db->qstr($COMMUNITY_ID) . " AND `proxy_id` IN ('" . implode("', '", $PROXY_IDS) . "') AND `member_active` = '1' AND `member_acl` = '0'") && ($total_updated = $db->Affected_Rows())) {
         if ($MAILING_LISTS["active"]) {
             $mail_list = new MailingList($COMMUNITY_ID);
             if ($mail_list) {
                 foreach ($PROXY_IDS as $proxy_id) {
                     $mail_list->promote_administrator($proxy_id);
                 }
             }
         }
         $SUCCESS++;
         $SUCCESSSTR[] = "You have successfully promoted <strong>" . $total_updated . " member" . ($total_updated != 1 ? "s" : "") . "</strong> in the <strong>" . html_encode($community_details["community_title"]) . "</strong> community to community administrators. They will now be able to perform all of the same actions as you in this community.<br /><br />You will now be redirected back to the Manage Members page; this will happen <strong>automatically</strong> in 5 seconds or <a href=\"" . ENTRADA_URL . "/" . $MODULE . "?section=members&community=" . $COMMUNITY_ID . "\" style=\"font-weight: bold\">click here</a> to continue.";
     } else {
         $ERROR++;
         $ERRORSTR[] = "There was a problem promoting these community members; the MEdTech Unit has been informed of this error, please try again later.";
         application_log("error", "Unable to promote members from community_id [" . $COMMUNITY_ID . "]. Database said: " . $db->ErrorMsg());
     }
     break;
 default:
 /**
  *
  * @param MailingList $source
  * @param Campaign $campaign
  * @param string $name
  * @return MailingList|null
  */
 public function copy(MailingList $source, Campaign $campaign = null, $name = null)
 {
     $con = $this->getConnection();
     $con->beginTransaction();
     try {
         $target = new MailingList();
         $target->setStatus(MailingListTable::STATUS_DRAFT);
         if ($name) {
             $target->setName($name);
         } else {
             $target->setName($source->getName() . ' copy ' . gmdate('Y-M-d H:i'));
         }
         if ($campaign) {
             $target->setCampaign($campaign);
         }
         $target->save();
         $meta_ids = array();
         $choice_ids = array();
         foreach ($source->getMailingListMeta() as $meta_source) {
             /* @var $meta_source MailingListMeta */
             $meta = new MailingListMeta();
             $meta->setMailingList($target);
             $meta->setKind($meta_source->getKind());
             $meta->setName($meta_source->getName());
             $meta->setSubst($meta_source->getSubst());
             $meta->save();
             $meta_ids[$meta_source->getId()] = $meta->getId();
             foreach ($meta_source->getMailingListMetaChoice() as $choice_source) {
                 /* @var $choice_source MailingListMetaChoice */
                 $choice = new MailingListMetaChoice();
                 $choice->setMailingListMeta($meta);
                 $choice->setChoice($choice_source->getChoice());
                 $choice->save();
                 $choice_ids[$choice_source->getId()] = $choice->getId();
             }
         }
         foreach ($source->getContact() as $contact_source) {
             /* @var $contact_source Contact */
             $contact = new Contact();
             $contact->setMailingList($target);
             $contact->setStatus($contact_source->getStatus());
             $contact->setEmail($contact_source->getEmail());
             $contact->setGender($contact_source->getGender());
             $contact->setFirstname($contact_source->getFirstname());
             $contact->setLastname($contact_source->getLastname());
             $contact->setCountry($contact_source->getCountry());
             $contact->save();
             foreach ($contact_source->getContactMeta() as $contact_meta_source) {
                 /* @var $contact_meta_source ContactMeta */
                 $contact_meta = new ContactMeta();
                 $contact_meta->setContact($contact);
                 $contact_meta->setValue($contact_meta_source->getValue());
                 $contact_meta->setMailingListMetaId($meta_ids[$contact_meta_source->getMailingListMetaId()]);
                 if ($contact_meta_source->getMailingListMetaChoiceId()) {
                     $contact_meta->setMailingListMetaChoiceId($choice_ids[$contact_meta_source->getMailingListMetaChoiceId()]);
                 }
                 $contact_meta->save();
             }
         }
         $con->commit();
         return $target;
     } catch (Exception $e) {
         $con->rollback();
     }
     return null;
 }
예제 #24
0
 /**
  *	approve - Approve pending project.
  *
  *	@param	object	The User object who is doing the updating.
  *	@access public
  */
 function approve(&$user)
 {
     if ($this->getStatus() == 'A') {
         $this->setError(_("Group already active"));
         return false;
     }
     db_begin();
     // Step 1: Activate group and create LDAP entries
     if (!$this->setStatus($user, 'A')) {
         db_rollback();
         return false;
     }
     //
     //
     //	Tracker Integration
     //
     //
     $ats = new ArtifactTypes($this);
     if (!$ats || !is_object($ats)) {
         $this->setError(_('Error creating ArtifactTypes object'));
         db_rollback();
         return false;
     } else {
         if ($ats->isError()) {
             $this->setError(sprintf(_('ATS%d: %s'), 1, $ats->getErrorMessage()));
             db_rollback();
             return false;
         }
     }
     if (!$ats->createTrackers()) {
         $this->setError(sprintf(_('ATS%d: %s'), 2, $ats->getErrorMessage()));
         db_rollback();
         return false;
     }
     //
     //
     //	Forum Integration
     //
     //
     $f = new Forum($this);
     if (!$f->create('Open-Discussion', 'General Discussion', 1, '', 1, 0)) {
         $this->setError(sprintf(_('F%d: %s'), 1, $f->getErrorMessage()));
         db_rollback();
         return false;
     }
     $f = new Forum($this);
     if (!$f->create('Help', 'Get Public Help', 1, '', 1, 0)) {
         $this->setError(sprintf(_('F%d: %s'), 2, $f->getErrorMessage()));
         db_rollback();
         return false;
     }
     $f = new Forum($this);
     if (!$f->create('Developers', 'Project Developer Discussion', 0, '', 1, 0)) {
         $this->setError(sprintf(_('F%d: %s'), 3, $f->getErrorMessage()));
         db_rollback();
         return false;
     }
     //
     //
     //	Doc Mgr Integration
     //
     //
     $dg = new DocumentGroup($this);
     if (!$dg->create('Uncategorized Submissions')) {
         $this->setError(sprintf(_('DG: %s'), $dg->getErrorMessage()));
         db_rollback();
         return false;
     }
     //
     //
     //	FRS integration
     //
     //
     $frs = new FRSPackage($this);
     if (!$frs->create($this->getUnixName())) {
         $this->setError(sprintf(_('FRSP: %s'), $frs->getErrorMessage()));
         db_rollback();
         return false;
     }
     //
     //
     //	PM Integration
     //
     //
     $pg = new ProjectGroup($this);
     if (!$pg->create('To Do', 'Things We Have To Do', 1)) {
         $this->setError(sprintf(_('PG%d: %s'), 1, $pg->getErrorMessage()));
         db_rollback();
         return false;
     }
     $pg = new ProjectGroup($this);
     if (!$pg->create('Next Release', 'Items For Our Next Release', 1)) {
         $this->setError(sprintf(_('PG%d: %s'), 2, $pg->getErrorMessage()));
         db_rollback();
         return false;
     }
     //
     //
     //	Set Default Roles
     //
     //
     $role = new Role($this);
     $todo = array_keys($role->defaults);
     for ($c = 0; $c < count($todo); $c++) {
         $role = new Role($this);
         if (!$role->createDefault($todo[$c])) {
             $this->setError(sprintf(_('R%d: %s'), $c, $role->getErrorMessage()));
             db_rollback();
             return false;
         }
     }
     $admin_group = db_query("SELECT user_id FROM user_group \n\t\tWHERE group_id=" . $this->getID() . " AND admin_flags='A'");
     if (db_numrows($admin_group) > 0) {
         $idadmin_group = db_result($admin_group, 0, 'user_id');
     } else {
         $idadmin_group = 1;
     }
     //
     //
     //	Create MailingList
     //
     //
     if ($GLOBALS['sys_use_mail']) {
         $mlist = new MailingList($this);
         if (!$mlist->create('commits', 'Commits', 1, $idadmin_group)) {
             $this->setError(sprintf(_('ML: %s'), $mlist->getErrorMessage()));
             db_rollback();
             return false;
         }
     }
     db_commit();
     $this->sendApprovalEmail();
     $this->addHistory('Approved', 'x');
     //plugin webcal
     //change assistant for webcal
     $params[0] = $idadmin_group;
     $params[1] = $this->getID();
     plugin_hook('change_cal_permission_default', $params);
     return true;
 }
 /**
  * Delete mailing list
  * - list and archives are deleted
  * - backup first in temp directory
  * @return true on success, false otherwise
  */
 public function deleteList($group_list_id)
 {
     $dar = $this->_getMailingListDao()->searchByGroupListId($group_list_id);
     if ($row = $dar->getRow()) {
         $list = new MailingList($row);
         $list_dir = $GLOBALS['mailman_list_dir'] . "/" . $list->getListName();
         if (is_dir($list_dir) && $list->getIsPublic() == 9) {
             // Archive first
             $list_archive_dir = $GLOBALS['mailman_list_dir'] . "/../archives/private/" . $list->getListName();
             // Does it work? TODO
             $backupfile = ForgeConfig::get('sys_project_backup_path') . "/" . $list->getListName() . "-mailman.tgz";
             system("tar cfz {$backupfile} {$list_dir} {$list_archive_dir}");
             chmod($backupfile, 0600);
             // Delete the mailing list if asked to and the mailing exists (archive deleted as well)
             system($GLOBALS['mailman_bin_dir'] . '/rmlist -a ' . $list->getListName() . ' >/dev/null');
             return $this->_getMailingListDao()->deleteListDefinitively($group_list_id);
         }
     }
     return false;
 }
 /**
  * Returns a FieldSet with which to create the CMS editing form.
  * You can use the extend() method of FieldSet to create customised forms for your other
  * data objects.
  *
  * @param Controller
  * @return FieldSet
  */
 function getCMSFields()
 {
     $fields = parent::getCMSFields();
     $fields->removeByName('Status');
     $fields->addFieldToTab('Root.Main', new ReadonlyField('Status', $this->fieldLabel('Status')), 'Subject');
     $fields->removeByName("SentDate");
     if ($this->Status == "Sent") {
         $fields->addFieldToTab('Root.Main', new ReadonlyField('SentDate', $this->fieldLabel('SentDate')), 'Subject');
     }
     $fields->dataFieldByName('SendFrom')->setValue(Email::getAdminEmail())->setAttribute('placeholder', 'My Name <*****@*****.**>');
     $fields->dataFieldByName('ReplyTo')->setValue(Email::getAdminEmail())->setAttribute('placeholder', '*****@*****.**')->setDescription(_t('Newsletter.ReplyToDesc', 'Any undeliverable emails will be collected in this mailbox'));
     $fields->removeFieldFromTab('Root.SendRecipientQueue', "SendRecipientQueue");
     $fields->removeByName('SendRecipientQueue');
     $fields->removeByName('TrackedLinks');
     if ($this->Status != 'Sent') {
         $contentHelp = '<strong>' . _t('Newsletter.FormattingHelp', 'Formatting Help') . '</strong><br />';
         $contentHelp .= '<ul>';
         foreach ($this->getAvailablePlaceholders() as $title => $description) {
             $contentHelp .= sprintf('<li><em>$%s</em>: %s</li>', $title, $description);
         }
         $contentHelp .= '</ul>';
         $contentField = $fields->dataFieldByName('Content');
         if ($contentField) {
             $contentField->setDescription($contentHelp);
         }
     }
     // Only show template selection if there's more than one template set
     $templateSource = $this->templateSource();
     if (count($templateSource) > 1) {
         $fields->replaceField("RenderTemplate", new DropdownField("RenderTemplate", _t('NewsletterAdmin.RENDERTEMPLATE', 'Template the newsletter render to'), $templateSource));
         $explanationTitle = _t("Newletter.TemplateExplanationTitle", "Select a styled template (.ss template) that this newsletter renders with");
         $fields->insertBefore(LiteralField::create("TemplateExplanationTitle", "<h5>{$explanationTitle}</h5>"), "RenderTemplate");
         if (!$this->ID) {
             $explanation1 = _t("Newletter.TemplateExplanation1", 'You should make your own styled SilverStripe templates	make sure your templates have a' . '$Body coded so the newletter\'s content could be clearly located in your templates');
             $explanation2 = _t("Newletter.TemplateExplanation2", "Make sure your newsletter templates could be looked up in the dropdown list below by\n\t\t\t\t\teither placing them under your theme directory,\te.g. themes/mytheme/templates/email/\n\t\t\t\t\t");
             $explanation3 = _t("Newletter.TemplateExplanation3", "or under your project directory e.g. mysite/templates/email/\n\t\t\t\t\t");
             $fields->insertBefore(LiteralField::create("TemplateExplanation1", "<p class='help'>{$explanation1}</p>"), "RenderTemplate");
             $fields->insertBefore(LiteralField::create("TemplateExplanation2", "<p class='help'>{$explanation2}<br />{$explanation3}</p>"), "RenderTemplate");
         }
     } else {
         $fields->replaceField("RenderTemplate", new HiddenField('RenderTemplate', false, key($templateSource)));
     }
     if ($this && $this->exists()) {
         $fields->removeByName("MailingLists");
         $mailinglists = MailingList::get();
         $fields->addFieldToTab("Root.Main", new CheckboxSetField("MailingLists", _t('Newsletter.SendTo', "Send To", 'Selects mailing lists from set of checkboxes'), $mailinglists->map('ID', 'FullTitle')));
     }
     if ($this->Status === 'Sending' || $this->Status === 'Sent') {
         //make the whole field read-only
         $fields = $fields->transform(new ReadonlyTransformation());
         $fields->push(new HiddenField("NEWSLETTER_ORIGINAL_ID", "", $this->ID));
         $gridFieldConfig = GridFieldConfig::create()->addComponents(new GridFieldNewsletterSummaryHeader(), new GridFieldSortableHeader(), new GridFieldDataColumns(), new GridFieldFilterHeader(), new GridFieldPageCount(), new GridFieldPaginator(30));
         //Create the Sent To Queue grid
         if (class_exists("GridFieldAjaxRefresh") && $this->SendRecipientQueue()->exists()) {
             //only use auto-refresh if there is a send out currently in-progress, otherwise no-point
             if ($this->SendRecipientQueue()->filter(array('Status' => array('Scheduled', 'InProgress')))->count() > 0) {
                 $gridFieldConfig->addComponent(new GridFieldAjaxRefresh(5000, true));
             }
         }
         $sendRecipientGrid = GridField::create('SendRecipientQueue', _t('NewsletterAdmin.SentTo', 'Sent to'), $this->SendRecipientQueue(), $gridFieldConfig);
         $fields->addFieldToTab('Root.SentTo', $sendRecipientGrid);
         //only show restart queue button if the newsletter is stuck in "sending"
         //only show the restart queue button if the user can run the build task (i.e. has full admin permissions)
         if ($this->Status == "Sending" && Permission::check('ADMIN')) {
             $restartLink = Controller::join_links(Director::absoluteBaseURL(), 'dev/tasks/NewsletterSendController?newsletter=' . $this->ID);
             $fields->addFieldToTab('Root.SentTo', new LiteralField('RestartQueue', sprintf('<a href="%s" class="ss-ui-button" data-icon="arrow-circle-double">%s</a>', $restartLink, _t('Newsletter.RestartQueue', 'Restart queue processing'))));
         }
         //only show the TrackedLinks tab, if there are tracked links in the newsletter and the status is "Sent"
         if ($this->TrackedLinks()->count() > 0) {
             $fields->addFieldToTab('Root.TrackedLinks', GridField::create('TrackedLinks', _t('NewsletterAdmin.TrackedLinks', 'Tracked Links'), $this->TrackedLinks(), $gridFieldConfig));
         }
     }
     return $fields;
 }
예제 #27
0
 public static function sendAdminCopy($subject, $message, $lists = array())
 {
     $sendcopy = Config::get('send_admin_copies');
     if ($sendcopy) {
         //$lists = cleanArray($lists);
         $mails = array();
         if (sizeof($lists) && Config::get('SEND_LISTADMIN_COPY')) {
             foreach ($lists as $list) {
                 $tmp_list = MailingList::getListById($list);
                 $mails[] = Admin::getAdmin($tmp_list->id)->email;
             }
         }
         ## hmm, do we want to be exclusive? Either listadmin or main ones
         ## could do all instead
         if (!sizeof($mails)) {
             $admin_mail = Config::get('admin_address');
             if ($c = Config::get('admin_addresses')) {
                 $mails = explode(',', $c);
             }
             $mails[] = $admin_mail;
         }
         $sent = array();
         foreach ($mails as $admin_mail) {
             $admin_mail = trim($admin_mail);
             if (!isset($sent[$admin_mail]) && !empty($admin_mail)) {
                 phpListMailer::sendMail($admin_mail, $subject, $message, phpListMailer::systemMessageHeaders($admin_mail));
                 phpList::log()->notice(s('Sending admin copy to') . ' ' . $admin_mail);
                 $sent[$admin_mail] = 1;
             }
         }
     }
 }
예제 #28
0
 // take a lock on a mail
 XDB::execute('UPDATE  email_list_moderate
                  SET  handler = {?}
                WHERE  handler IS NULL
             ORDER BY  ts
             LIMIT  1', $handler);
 if (XDB::affectedRows() == 0) {
     break;
 }
 $query = XDB::query('SELECT  uid, ml, domain, mid, action, message
                        FROM  email_list_moderate
                       WHERE  handler = {?}', $handler);
 list($uid, $list, $domain, $mid, $action, $reason) = $query->fetchOneRow();
 $user = User::get($uid);
 $fullname = $user->fullName();
 $mlist = new MailingList($list, $domain, $user);
 // send the mail
 $mail = $mlist->getPendingMail($mid);
 list($det, $mem, $own) = $mlist->getMembers();
 $count = 0;
 switch ($action) {
     case 'accept':
         $action = MailingList::REQ_ACCEPT;
         $subject = "Message accepté";
         $append = "a été accepté par {$fullname}.\n";
         $type = 'nonspam';
         $count += count($mem) + count($own);
         break;
     case 'refuse':
         $action = MailingList::REQ_REJECT;
         $subject = "Message refusé";
 public function countActionsDeletedByTargetList(MailingList $ml)
 {
     return $this->queryAll(true)->where('p.mailing_list_id = ?', $ml->getId())->andWhere('p.status = ?', Petition::STATUS_DELETED)->count();
 }
예제 #30
0
 public function isTargetListMember(MailingList $mailing_list, $orCampaignAdmin = false, $andCampaignMember = true)
 {
     if ($orCampaignAdmin && $this->isCampaignAdmin($mailing_list->getCampaign())) {
         return true;
     }
     if ($andCampaignMember && !$this->isCampaignMember($mailing_list->getCampaign())) {
         return false;
     }
     $tr = $this->getTargetListRights($mailing_list);
     return $tr && $tr->getActive();
 }