HomeHelpTrac

source: trunk/administration/notifies.php @ 16098

Revision 16098, 18.8 KB checked in by Alexander Trofimov, 2 months ago (diff)

Email templates engine redesign

Line 
1<?php
2
3// TODO: remake according to new design and principles, site setup part leave in admin and remake other functionality move to user part
4
5/***************************************************************************
6*                            Dolphin Smart Community Builder
7*                              -----------------
8*     begin                : Mon Mar 23 2006
9*     copyright            : (C) 2006 BoonEx Group
10*     website              : http://www.boonex.com/
11* This file is part of Dolphin - Smart Community Builder
12*
13* Dolphin is free software. This work is licensed under a Creative Commons Attribution 3.0 License.
14* http://creativecommons.org/licenses/by/3.0/
15*
16* Dolphin is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
17* without even the implied warranty of  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
18* See the Creative Commons Attribution 3.0 License for more details.
19* You should have received a copy of the Creative Commons Attribution 3.0 License along with Dolphin,
20* see license.txt file; if not, write to marketing@boonex.com
21***************************************************************************/
22
23define('BX_SECURITY_EXCEPTIONS', true);
24$aBxSecurityExceptions = array(
25    'POST.body',
26    'REQUEST.body',
27);
28
29require_once( '../inc/header.inc.php' );
30require_once( BX_DIRECTORY_PATH_INC . 'design.inc.php' );
31require_once( BX_DIRECTORY_PATH_INC . 'admin_design.inc.php' );
32require_once( BX_DIRECTORY_PATH_INC . 'utils.inc.php' );
33require_once( BX_DIRECTORY_PATH_INC . 'prof.inc.php' );
34
35bx_import('BxTemplFormView');
36bx_import('BxDolEmailTemplates');
37
38$logged['admin'] = member_auth(1, true, true);
39
40if($_POST['queue_message'] && $_POST['msgs_id'])
41    $sActionResult = QueueMessage();
42if ($_POST['add_message'])
43    $action = 'add';
44if($_POST['delete_message'] && $_POST['msgs_id'])
45    $sActionResult = DeleteMessage() ? _t('_adm_mmail_Message_was_deleted') : _t('_adm_mmail_Message_was_not_deleted');
46if($_POST['preview_message'] && $_POST['msgs_id'])
47    $action = 'preview';
48if(bx_get('action') == 'empty' )
49    $sActionResult = EmptyQueue() ? _t('_adm_mmail_Queue_empty') : _t('_adm_mmail_Queue_emptying_failed');
50
51$iNameIndex = 13;
52$_page = array(
53    'name_index' => $iNameIndex,
54    'css_name' => array('forms_adv.css'),
55    'header' => _t('_adm_mmail_title')
56);
57
58$_page_cont[$iNameIndex] = array(
59    'page_code_status' => PrintStatus($sActionResult),
60    'page_code_new_message' => getEmailMessage($action),
61    'page_code_preview_message' => $action == 'preview' && strlen($_POST['body']) ? PreviewMessage() : '',
62    'page_code_all_messages' => getAllMessagesBox(),
63    'page_code_queue_message' => getQueueMessage()
64);
65
66PageCodeAdmin();
67
68function PrintStatus($sActionResult) {
69    $sSubjC = _t('_Subject');
70    $sEmailsC = _t('_adm_mmail_emails');
71    $sEmptyQueueC = _t('_adm_mmail_Empty_Queue');
72    $sCupidStatusC = _t('_adm_mmail_Cupid_mails_status');
73
74    $sSingleEmailsTRs = '';
75
76    // Select count of emails in queue per one message
77    $iCount = (int)$GLOBALS['MySQL']->getOne("SELECT COUNT(`id`) AS `count` FROM `sys_sbs_queue`");
78    if ($iCount <= 0)
79        $sSingleEmailsTRs .= "<tr><td align=center><b><font color=red>" . _t('_adm_mmail_no_emails_in_queue') . "</font></b></td></tr>";
80    else
81       $sSingleEmailsTRs .= "<tr><td align=center>" . _t('_adm_mmail_mails_in_queue', $iCount) . "</td></tr>";
82
83    $sEmptyQueueTable = '';
84    // If queue is not empty then show link to clear it
85    if($iCount > 0) {
86        $sEmptyQueueTable = "<hr>
87        <table class=\"text\" width=\"50%\" style=\"height: 30px;\">
88            <tr class=\"table\">
89                <td align=\"center\" colspan=\"3\">
90                    <a href=\"" . BX_DOL_URL_ADMIN . "notifies.php?action=empty\">{$sEmptyQueueC}</a>
91                </td>
92            </tr>
93        </table>
94        <hr>";
95    }
96
97    ob_start();
98?>
99<div style="margin:9px;">
100    <center>
101        <table cellspacing=2 cellpadding=2 class=text border=0>
102            <tr class=header align="center"><td><?=_t('_adm_mmail_Queue_status');?>:</td></tr>
103            <?=$sSingleEmailsTRs;?>
104        </table>
105        <?=$sEmptyQueueTable;?>
106    </center>
107</div>
108<?
109    $sResult = ob_get_clean();
110
111    if(!empty($sActionResult))
112       $sResult = MsgBox($sActionResult, 3) . $sResult;
113
114    return DesignBoxContent(_t('_Status'), $sResult, 1);
115}
116
117function getAllMessagesBox() {
118    $aMessages = $GLOBALS['MySQL']->getAll("SELECT `id`, `subject`, (`id`=". (int)$_POST['msgs_id'] ." OR `subject`='". process_db_input($_POST['Subj']) ."' ) AS `selected` FROM `sys_sbs_messages`");
119
120    $sAllMessagesOptions = '';
121    foreach($aMessages as $aMessage)
122        $sAllMessagesOptions .= "<option value=\"" . $aMessage['id'] . "\" " . ($aMessage['selected'] ? "selected=\"selected\"" : "") . ">" . $aMessage['subject'] . "</option>";
123
124    ob_start();
125?>
126<form name="form_messages" method="POST" action="<?=$GLOBALS['site']['url_admin'] . 'notifies.php';?>">
127    <input type="hidden" name="action" value="view">
128    <center class="text"><?= _t('_Messages'); ?>:&nbsp;
129        <select name=msgs_id onChange="javascript: document.forms['form_messages'].submit();">
130            <option value=0><?=_t('_None');?></option>
131            <?=$sAllMessagesOptions;?>
132        </select>
133    </center>
134</form>
135<?
136    $sResult = ob_get_clean();
137
138    return DesignBoxContent(_t('_adm_mmail_All_Messages'), '<div style="margin:9px;">' . $sResult . '</div>', 1);
139}
140
141function getEmailMessage($sAction) {
142    $sErrorC = _t('_Error Occured');
143    $sApplyChangesC = _t('_Submit');
144    $sSubjectC = _t('_Subject');
145    $sBodyC = _t('_adm_mmail_Body');
146    $sTextBodyC = _t('_adm_mmail_Text_email_body');
147    $sPreviewMessageC = _t('_Preview');
148    $sDeleteC = _t('_Delete');
149
150    $sMessageID = (int)$_POST['msgs_id'];
151
152    $sSubject = $sBody = "";
153    if($_POST['body'] && $_POST['action'] != 'delete' ) {
154        $sSubject = process_pass_data( $_POST['subject'] );
155        $sBody = process_pass_data( $_POST['body'] );
156    } elseif ( $sMessageID )
157        list($sSubject, $sBody) = $GLOBALS['MySQL']->getRow("SELECT `subject`, `body` FROM `sys_sbs_messages` WHERE `id`='". $sMessageID . "' LIMIT 1", MYSQL_NUM);
158
159    $sSubject = htmlspecialchars($sSubject);
160
161    $aForm = array(
162        'form_attrs' => array(
163            'name' => 'sys_sbs_messages',
164            'action' => $GLOBALS['site']['url_admin'] . 'notifies.php',
165            'method' => 'post',
166        ),
167        'params' => array (
168            'db' => array(
169                'table' => 'sys_sbs_messages',
170                'key' => 'ID',
171                'submit_name' => 'add_message',
172            ),
173        ),
174        'inputs' => array(
175            'subject' => array(
176                'type' => 'text',
177                'name' => 'subject',
178                'value' => $sSubject,
179                'caption' => $sSubjectC,
180                'required' => true,
181                'checker' => array (
182                    'func' => 'length',
183                    'params' => array(2,128),
184                    'error' => $sErrorC,
185                ),
186                'db' => array (
187                    'pass' => 'Xss',
188                ),
189            ),
190            'body' => array(
191                'type' => 'textarea',
192                'name' => 'body',
193                'value' => $sBody,
194                'caption' => $sBodyC,
195                'required' => true,
196                'html' => 1,
197                'checker' => array (
198                    'func' => 'length',
199                    'params' => array(10,32000),
200                    'error' => $sErrorC,
201                ),
202                'db' => array (
203                    'pass' => 'XssHtml',
204                ),
205            ),
206            'msgs_id' => array(
207                'type' => 'hidden',
208                'name' => 'msgs_id',
209                'value' => $sMessageID,
210            ),
211            'control' => array (
212                'type' => 'input_set',
213                array(
214                    'type' => 'submit',
215                    'name' => 'add_message',
216                    'caption' => $sApplyChangesC,
217                    'value' => $sApplyChangesC,
218                ),
219                array(
220                    'type' => 'submit',
221                    'name' => 'preview_message',
222                    'caption' => $sPreviewMessageC,
223                    'value' => $sPreviewMessageC,
224                ),
225            )
226        ),
227    );
228    if($sMessageID) {
229        $aForm['inputs']['control'][] = array (
230            'type' => 'submit',
231            'name' => 'delete_message',
232            'caption' => $sDeleteC,
233            'value' => $sDeleteC,
234        );
235    }
236
237    $sResult = '';
238    $oForm = new BxTemplFormView($aForm);
239    $oForm->initChecker();
240    if ($oForm->isSubmittedAndValid()) {
241        if ($sAction == 'add') {
242            if ($sMessageID > 0) {
243                $oForm->update($sMessageID);
244            } else {
245                $sMessageID = $oForm->insert();
246            }
247        }
248
249        $sResult = $sMessageID > 0 ? MsgBox(_t('_Success'), 3) : MsgBox($sErrorC);
250    }
251
252    return DesignBoxContent(_t('_adm_mmail_Email_message'), '<div style="margin:9px;">' . $sResult . $oForm->getCode() . '</div>', 1);
253}
254
255function getQueueMessage() {
256    global $aPreValues;
257
258    if ( $_POST['msgs_id'] ) {
259        $aSexValues = getFieldValues('Sex');
260        foreach($aSexValues as $sKey => $sValue)
261            $aSexValues[$sKey] = _t($sValue);
262
263        $aStartAgesOptions = array();
264        $aEndAgesOptions = array();
265        $gl_search_start_age = (int)getParam('search_start_age');
266        $gl_search_end_age = (int)getParam('search_end_age');
267        for ( $i = $gl_search_start_age ; $i <= $gl_search_end_age ; $i++ ) {
268            $aStartAgesOptions[$i] = $i;
269        }
270        for ( $i = $gl_search_start_age ; $i <= $gl_search_end_age ; $i++ ) {
271            $aEndAgesOptions[$i] = $i;
272        }
273
274        $aCountryOptions = array('all' => _t('_All'));
275        foreach ( $aPreValues['Country'] as $key => $value ) {
276            $aCountryOptions[$key] = _t($value['LKey']);
277        }
278
279        $aMembershipOptions = array('all' => _t('_All'));
280        $memberships_arr = getMemberships();
281        foreach ( $memberships_arr as $membershipID => $membershipName ) {
282            if ($membershipID == MEMBERSHIP_ID_NON_MEMBER) continue;
283            $aMembershipOptions[$membershipID] = $membershipName;
284        }
285
286        $iRecipientMembers = (int)$GLOBALS['MySQL']->getOne("SELECT COUNT(`ID`) AS `count` FROM `Profiles` WHERE `Status`<>'Unconfirmed' AND `EmailNotify` = 1 LIMIT 1");
287        $aForm = array(
288            'form_attrs' => array(
289                'name' => 'form_queue',
290                'class' => 'form_queue_form',
291                'action' => $GLOBALS['site']['url_admin'] . 'notifies.php',
292                'method' => 'post',
293            ),
294            'inputs' => array (
295                'Send1' => array(
296                    'type' => 'checkbox',
297                    'name' => 'send_to_subscribers',
298                    'label' => _t('_adm_mmail_Send_to_subscribers'),
299                    'value' => 'non',
300                    'checked' => true
301                ),
302                'Send2' => array(
303                    'type' => 'checkbox',
304                    'name' => 'send_to_members',
305                    'label' => _t('_adm_mmail_Send_to_members'),
306                    'value' => 'memb',
307                    'checked' => true,
308                    'attrs' => array(
309                        'onClick' => 'setControlsState();',
310                    ),
311                    'info' => _t('_adm_mmail_Send_to_members_info', $iRecipientMembers),
312                ),
313                'sex' => array (
314                    'type' => 'checkbox_set',
315                    'name' => 'sex',
316                    'values' => $aSexValues,
317                    'value' => array_keys($aSexValues)
318                ),
319                'StartAge' => array (
320                    'type' => 'select',
321                    'name' => 'age_start',
322                    'caption' => _t('_adm_mmail_Age') . ' ' . _t('_from'),
323                    'values' => $aStartAgesOptions,
324                    'value' => $gl_search_start_age,
325                ),
326                'EndAge' => array (
327                    'type' => 'select',
328                    'name' => 'age_end',
329                    'caption' => _t('_to'),
330                    'values' => $aEndAgesOptions,
331                    'value' => $gl_search_end_age,
332                ),
333                'Country' => array (
334                    'type' => 'select',
335                    'name' => 'country',
336                    'caption' => _t('_Country'),
337                    'values' => $aCountryOptions,
338                    'value' => 'all',
339                ),
340                'Membership' => array (
341                    'type' => 'select',
342                    'name' => 'membership',
343                    'caption' => _t('_adm_mmi_membership_levels'),
344                    'values' => $aMembershipOptions,
345                    'value' => 'all',
346                ),
347                'msgs_id' => array (
348                    'type' => 'hidden',
349                    'name' => 'msgs_id',
350                    'value' => (int)$_POST['msgs_id'],
351                ),
352                'submit' => array (
353                    'type' => 'submit',
354                    'name' => 'queue_message',
355                    'value' => _t('_Submit'),
356                )
357            )
358        );
359
360        $oForm = new BxTemplFormView($aForm);
361        $sTmplResult = $GLOBALS['oAdmTemplate']->parseHtmlByName('notifies_filter.html', array());
362        return DesignBoxContent(_t('_adm_mmail_Queue_message'), '<div style="margin:9px;">' . $oForm->getCode() . $sTmplResult . '</div>', 1);
363    }
364}
365
366function QueueMessage() {
367    global $MySQL;
368
369    $iEmails = 0;
370    $sReturn = "";
371    $iMsgId = (int)$_POST['msgs_id'];
372
373    $aOriginalMessage = $MySQL->getRow("SELECT `id`, `subject`, `body` FROM `sys_sbs_messages` WHERE `id`='" . $iMsgId . "' LIMIT 1");
374    if(!is_array($aOriginalMessage) || empty($aOriginalMessage)) {
375        return _t('_adm_mmail_Failed_to_queue_emails_X', $iMsgId);
376    }
377
378    //--- Send to all subscribers
379    $oEmailTemplates = new BxDolEmailTemplates();
380    if($_POST['send_to_subscribers'] == 'non') {
381        $sSql = "SELECT
382                    `tsu`.`name` AS `user_name`,
383                    `tsu`.`email` AS `user_email`,
384                    `tst`.`template` AS `template_name`
385                FROM `sys_sbs_types` AS `tst`
386                INNER JOIN `sys_sbs_entries` AS `tse` ON `tst`.`id`=`tse`.`subscription_id` AND `tse`.`subscriber_type`='" . BX_DOL_SBS_TYPE_VISITOR . "'
387                INNER JOIN `sys_sbs_users` AS `tsu` ON `tse`.`subscriber_id`=`tsu`.`id`
388                WHERE
389                    `tst`.`unit`='system' AND
390                    `tst`.`action`='mass_mailer'";
391        $aSubscribers = $MySQL->getAll($sSql);
392
393        foreach($aSubscribers as $aSubscriber) {
394            if(empty($aSubscriber['user_email']))
395                continue;
396
397            $aMessage = $oEmailTemplates->parseTemplate($aSubscriber['template_name'], array(
398                'RealName' => $aSubscriber['user_name'],
399                'Email' => $aSubscriber['user_email'],
400                'MessageSubject' => $aOriginalMessage['subject'],
401                'MessageText' => $aOriginalMessage['body']
402            ));
403
404            $mixedResult = $MySQL->query("INSERT INTO `sys_sbs_queue`(`email`, `subject`, `body`) VALUES('" . $aSubscriber['user_email'] . "', '" . process_db_input($aMessage['Subject'], BX_TAGS_STRIP) . "', '" . process_db_input($aMessage['Body'], BX_TAGS_VALIDATE) . "')");
405            if($mixedResult === false) {
406                $sReturn .= _t('_adm_mmail_Email_not_added_to_queue_X', $aSubscriber['user_email']);
407                continue;
408            }
409            $iEmails++;
410        }
411    }
412
413    //--- Send to all profiles
414    if($_POST['send_to_members'] == 'memb') {
415        //--- Sex filter
416        $sex_filter_sql = '';
417        if(is_array($_POST['sex']) && !empty($_POST['sex']))
418            $sex_filter_sql = "AND `Sex` IN ('" . implode("','", $_POST['sex']) . "')";
419
420        //--- Age filter
421        $age_filter_sql = '';
422        $age_start = (int)$_POST['age_start'];
423        $age_end = (int)$_POST['age_end'];
424        if ( $age_start && $age_end ) {
425            $date_start = (int)( date( "Y" ) - $age_start );
426            $date_end = (int)( date( "Y" ) - $age_end - 1 );
427            $date_start = $date_start . date( "-m-d" );
428            $date_end = $date_end . date( "-m-d" );
429            $age_filter_sql = "AND (TO_DAYS(`DateOfBirth`) BETWEEN TO_DAYS('{$date_end}') AND (TO_DAYS('{$date_start}')+1))";
430        }
431
432        //--- Country filter
433        $country_filter_sql = '';
434        if($_POST['country'] != 'all') {
435            $country = process_db_input($_POST['country']);
436            $country_filter_sql = "AND `Country` = '{$country}'";
437        }
438
439        //--- Membership filter
440        $membershipID = $_POST['membership'] != 'all' ? (int)$_POST['membership'] : -1;
441
442        $aMembers = $MySQL->getAll("SELECT `ID` AS `id`, `Email` AS `email` FROM `Profiles` WHERE `Status` <> 'Unconfirmed' AND `EmailNotify` = 1 AND (`Couple` = '0' OR `Couple` > `ID`) {$sex_filter_sql} {$age_filter_sql} {$country_filter_sql}");
443        foreach($aMembers as $aMember) {
444            if(empty($aMember['email']))
445                continue;
446
447            //--- Dynamic membership filter
448            $membership_info = getMemberMembershipInfo($aMember['id']);
449            if ($membershipID != -1 && $membership_info['ID'] != $membershipID )
450                continue;
451
452            $aMessage = $oEmailTemplates->parseTemplate('t_AdminEmail', array(
453                'MessageSubject' => $aOriginalMessage['subject'],
454                'MessageText' => $aOriginalMessage['body']
455            ), $aMember['id']);
456
457            $mixedResult = $MySQL->query("INSERT INTO `sys_sbs_queue`(`email`, `subject`, `body`) VALUES('" . $aMember['email'] . "', '" . process_db_input($aMessage['Subject'], BX_TAGS_STRIP) . "', '" . process_db_input($aMessage['Body'], BX_TAGS_VALIDATE) . "')");
458            if($mixedResult === false) {
459                $sReturn .= _t('_adm_mmail_Email_not_added_to_queue_X', $aMember['email']);
460                continue;
461            }
462            $iEmails++;
463        }
464    }
465
466    $sReturn .= _t('_adm_mmail_X_emails_was_succ_added_to_queue', (int)$iEmails);
467    return $sReturn;
468}
469
470function PreviewMessage() {
471    $oEmailTemplate = new BxDolEmailTemplates();
472    $aMessage = $oEmailTemplate->parseTemplate('t_AdminEmail', array(
473        'MessageText' => process_pass_data($_POST['body'])
474    ));
475
476    $sPreview = '<div style="margin:9px;">' . $aMessage['Body'] . '</div>';
477    return DesignBoxContent(_t('_Preview'), $sPreview, 1);
478}
479
480function DeleteMessage() {
481    $mixedResult = $GLOBALS['MySQL']->query("DELETE FROM `sys_sbs_messages` WHERE `id`='". (int)$_POST['msgs_id'] . "' LIMIT 1");
482    if($mixedResult === false)
483        return $mixedResult;
484
485    $_POST['msgs_id'] = 0;
486    return true;
487}
488
489function EmptyQueue() {
490    return db_res("TRUNCATE TABLE `sys_sbs_queue`");
491}
492
493?>
Note: See TracBrowser for help on using the repository browser.