2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 10/19/2003 *
4 * =================== Last change: 08/26/2004 *
6 * -------------------------------------------------------------------- *
7 * File : what-order.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Order mails here *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Hier koennen Ihre Mitglieder Mails buchen *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * -------------------------------------------------------------------- *
18 * Copyright (c) 2003 - 2009 by Roland Haeder *
19 * Copyright (c) 2009 - 2013 by Mailer Developer Team *
20 * For more information visit: http://mxchange.org *
22 * This program is free software; you can redistribute it and/or modify *
23 * it under the terms of the GNU General Public License as published by *
24 * the Free Software Foundation; either version 2 of the License, or *
25 * (at your option) any later version. *
27 * This program is distributed in the hope that it will be useful, *
28 * GNU General Public License for more details. *
30 * You should have received a copy of the GNU General Public License *
31 * along with this program; if not, write to the Free Software *
32 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
34 ************************************************************************/
36 // Some security stuff...
37 if (!defined('__SECURITY')) {
39 } elseif (!isMember()) {
40 redirectToIndexMemberOnlyModule();
43 // Add description as navigation point
44 addYouAreHereLink('member', __FILE__);
46 if ((!isExtensionActive('order')) && (!isAdmin())) {
47 displayMessage('{%pipe,generateExtensionInactiveNotInstalledMessage=order%}');
54 'data_type' => 'TEMP',
58 $ALLOWED = getUserData('receive_mails') - getUserData('mail_orders');
59 if (getOrderMaxFull() == 'MAX') $ALLOWED = getUserData('receive_mails');
61 // Now check his points amount
62 $totalPoints = getTotalPoints(getMemberId());
64 // Admin can always book
65 if ((isExtensionInstalledAndNewer('holiday', '0.1.3')) && (isUserDataEnabled('holiday_active')) && (!isAdmin())) {
67 displayMessage('{--MEMBER_HOLIDAY_ORDER_NOT_POSSIBLE--}');
68 } elseif ((isPostRequestElementSet('frametester')) && ($ALLOWED > 0) && (postRequestElement('receiver') > 0)) {
69 // Continue with the frametester, we first need to store the data temporary in the pool
71 // First we would like to store the data and get it's pool position back...
72 // @TODO Try to move out url_tlock to a filter for extra SQL statements
73 $result = sqlQueryEscaped("SELECT
77 `{?_MYSQL_PREFIX?}_pool`
81 (UNIX_TIMESTAMP() - `timestamp`) >= {?url_tlock?}
85 postRequestElement('url')
86 ), __FILE__, __LINE__);
88 if (sqlNumRows($result) == 1) {
89 // Load id and mail type
90 $data = sqlFetchArray($result);
94 sqlFreeResult($result);
96 if ($data['data_type'] == 'TEMP') {
97 // Prepare data for filter chain
99 'url' => postRequestElement('url'),
100 'text' => postRequestElement('text'),
101 'subject' => postRequestElement('subject'),
102 'receiver' => bigintval(postRequestElement('receiver')),
103 'mail_type' => bigintval(postRequestElement('mail_type')),
104 'html' => postRequestElement('html'),
105 'id' => bigintval($data['id']),
109 // Run the filter chain
110 $filterData = runFilterChain('pre_mail_order', $filterData);
112 // Copy field redirect->url
113 $data['url'] = $filterData['redirect'];
115 // Is there an error?
116 if (empty($data['url'])) {
117 // Copy all filter data -> POST
118 foreach ($filterData as $key => $value) {
120 setPostRequestElement($key, $value);
123 } elseif (!isAdmin()) {
124 // He has already sent a mail within a specific time
125 $data['url'] = 'modules.php?module=login&what=order&code=' . getCode('URL_TIME_LOCK') . '&id=' . $data['id'];
129 if (empty($data['url'])) {
131 $result = sqlQueryEscaped("SELECT
134 `{?_MYSQL_PREFIX?}_user_cats` AS `c`
136 `{?_MYSQL_PREFIX?}_user_data` AS `d`
138 `c`.`userid`=`d`.`userid`
141 `c`.`userid` != %s AND
142 `d`.`status`='CONFIRMED'
143 " . runFilterChain('user_exclusion_sql', ' ') . " AND
144 `d`.`receive_mails` > 0
146 `d`.`{?order_select?}` {?order_mode?}",
148 bigintval(postRequestElement('cat')),
150 ), __FILE__, __LINE__);
152 // Are there still receivers left?
153 if (sqlNumRows($result) >= postRequestElement('receiver')) {
154 // Load receivers from database
155 $TEST = array(); $count = '0';
156 while ($holidayContent = sqlFetchArray($result)) {
157 if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
158 // Check for his holiday status
159 $result_holiday = sqlQueryEscaped("SELECT
162 `{?_MYSQL_PREFIX?}_user_holidays`
165 `holiday_start` < UNIX_TIMESTAMP() AND
166 `holiday_end` > UNIX_TIMESTAMP()
168 array($holidayContent['userid']), __FILE__, __LINE__);
169 if (sqlNumRows($result_holiday) == 1) {
170 // Exclude user who are in holiday
171 $holidayContent['userid'] = '0';
175 sqlFreeResult($result_holiday);
178 if (isValidId($holidayContent['userid'])) {
180 array_push($TEST, $holidayContent['userid']);
186 sqlFreeResult($result);
188 // Implode array into string for the sending pool
189 $receivers = implode($TEST, ';');
191 // Count array for maximum sent
192 $content['target_send'] = count($TEST);
194 // Update receiver list
195 sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `receive_mails`=`receive_mails`-1 WHERE `userid` IN (%s) LIMIT %s",
197 convertReceivers($receivers),
198 bigintval($content['target_send'])
199 ), __FILE__, __LINE__);
201 // Is calculated max receivers larger than wanted receivers then reset it
202 if ($content['target_send'] > postRequestElement('receiver')) {
203 $content['target_send'] = bigintval(postRequestElement('receiver'));
206 // Calculate used points
207 $usedPoints = $content['target_send'] * getPaymentPrice(bigintval(postRequestElement('mail_type')));
209 // Fix empty zip code
210 if (!isPostRequestElementSet('zip')) {
211 setPostRequestElement('zip', 0);
214 // Check if he has enougth points for this order and selected more than 0 receivers
215 if (($usedPoints > 0) && ($usedPoints <= $totalPoints) && ($content['target_send'] > 0)) {
216 // Gettings points is okay, so we can add $usedPoints later from
217 if ((!isValidId($data['id'])) || ($data['data_type'] != 'TEMP')) {
218 // New order, init data array elements
220 'sender' => getMemberId(),
221 'subject' => postRequestElement('subject'),
222 'text' => postRequestElement('text'),
223 'receivers' => $receivers,
224 'payment_id' => bigintval(postRequestElement('mail_type')),
225 'data_type' => 'TEMP',
226 'timestamp' => 'UNIX_TIMESTAMP()',
227 'url' => postRequestElement('url'),
228 'cat_id' => bigintval(postRequestElement('cat')),
229 'target_send' => bigintval($content['target_send']),
230 'zip' => bigintval(postRequestElement('zip'), TRUE, FALSE),
233 // Is ext-html_mail active?
234 if (isExtensionActive('html_mail')) {
235 // HTML extension is active
236 $data['html_msg'] = postRequestElement('html');
240 $data['id'] = insertDataIntoPool($data);
244 'subject' => postRequestElement('subject'),
245 'text' => postRequestElement('text'),
246 'receivers' => $receivers,
247 'payment_id' => bigintval(postRequestElement('mail_type')),
248 'timestamp' => 'UNIX_TIMESTAMP()',
249 'url' => postRequestElement('url'),
250 'cat_id' => bigintval(postRequestElement('cat')),
251 'target_send' => bigintval($content['target_send']),
252 'zip' => bigintval(postRequestElement('zip'), TRUE, FALSE),
255 // Is ext-html_mail active?
256 if (isExtensionActive('html_mail')) {
257 // HTML extension is active
258 $data['html_msg'] = postRequestElement('html');
262 updatePoolDataById($data['id'], NULL, $data);
265 // Make sure only valid id numbers can pass
266 assert(isValidId($data['id']), 'data[id]=' . $data['id'] . ' is not a valid id number.');
268 // Id is received so we can redirect the user, used points will be added when he send's out the mail
269 $data['url'] = 'modules.php?module=frametester&order=' . bigintval($data['id']);
270 } elseif ($content['target_send'] == '0') {
271 // Not enougth receivers found which can receive mails
272 $data['url'] = 'modules.php?module=login&what=order&code=' . getCode('MORE_RECEIVERS2');
274 // No enougth points left!
275 $data['url'] = 'modules.php?module=login&what=order&code=' . getCode('MORE_POINTS');
278 // Ordered more mails than he can send in this category
279 $data['url'] = 'modules.php?module=login&what=order&code=' . getCode('NO_RECS_LEFT');
282 } elseif (postRequestElement('receiver') == '0') {
283 // Not enougth receivers selected
284 $data['url'] = 'modules.php?module=login&what=order&code=' . getCode('MORE_RECEIVERS1');
285 } elseif (($ALLOWED == '0') && (getOrderMaxFull() == 'ORDER')) {
286 // No more mail orders allowed
287 displayMessage('{--MEMBER_ORDER_ALLOWED_EXHAUSTED--}');
288 } elseif (getTotalUnconfirmedMails(getMemberId()) < getConfig('max_unconfirmed')) {
289 // Show only enabled categories to the user ...
290 $whereStatement = " WHERE `visible`='Y'";
292 // ... but all to the admin
293 if (isAdmin()) $whereStatement = '';
295 // Display order form
296 $result_cats = sqlQuery('SELECT
300 `{?_MYSQL_PREFIX?}_cats`
301 ' . $whereStatement . '
303 `sort` ASC', __FILE__, __LINE__);
305 // Some categories found?
306 if (!ifSqlHasZeroNums($result_cats)) {
307 // Enought points left?
308 if ($totalPoints > 0) {
309 // Initialize array...
316 // Enable HTML checking
317 // @TODO Rewrite this to a filter
319 if ((isExtensionActive('html_mail')) && (postRequestElement('html') == 'Y')) {
320 $HTML = " AND `html`='Y'";
323 // ... and begin loading stuff
324 while ($categoriesContent = sqlFetchArray($result_cats)) {
325 $categories['id'][] = bigintval($categoriesContent['id']);
326 array_push($categories['name'], $categoriesContent['cat']);
328 // Select users in current category
329 $result_userids = sqlQueryEscaped('SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s AND `userid` != %s ORDER BY `userid` ASC',
330 array(bigintval($categoriesContent['id']), getMemberId()), __FILE__, __LINE__);
333 while (list($userid) = sqlFetchRow($result_userids)) {
334 // Check for holiday system
335 $isHolidayActive = FALSE;
336 if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
337 // Check user's holiday status
338 $result_holiday = sqlQueryEscaped("SELECT
339 COUNT(`d`.`userid`) AS `cnt`
341 `{?_MYSQL_PREFIX?}_user_data` AS `d`
343 `{?_MYSQL_PREFIX?}_user_holidays` AS `h`
345 `d`.`userid`=`h`.`userid`
348 `d`.`receive_mails` > 0 AND
349 `d`.`status`='CONFIRMED' AND
350 `d`.`holiday_active`='Y' AND
351 `h`.`holiday_start` < UNIX_TIMESTAMP() AND
352 `h`.`holiday_end` > UNIX_TIMESTAMP()
354 array(bigintval($userid)), __FILE__, __LINE__);
357 list($count) = sqlFetchRow($result_holiday);
360 sqlFreeResult($result_holiday);
362 // Is holiday is active?
363 $isHolidayActive = ($count == 1);
366 if ($isHolidayActive === FALSE) {
367 // Check if the user want's to receive mails?
368 $result_ver = sqlQueryEscaped("SELECT `zip` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s" . $HTML . " AND `receive_mails` > 0 AND `status`='CONFIRMED' LIMIT 1",
369 array(bigintval($userid)), __FILE__, __LINE__);
371 if ((sqlNumRows($result_ver) == 1) && (isPostRequestElementSet('zip')) && (isOrderMultiPageEnabled())) {
373 list($zip) = sqlFetchRow($result_ver);
374 if (substr($zip, 0, strlen(postRequestElement('zip'))) == postRequestElement('zip')) {
375 // Ok, ZIP code part is found
380 $userid_cnt += sqlNumRows($result_ver);
384 sqlFreeResult($result_ver);
389 sqlFreeResult($result_userids);
390 array_push($categories['userids'], $userid_cnt);
394 sqlFreeResult($result_cats);
396 // Now we need to load the mail types...
397 $result = sqlQuery("SELECT `id`, `price`, `payment`, `mail_title` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `price` > 0 AND `payment` > 0 ORDER BY `payment` ASC", __FILE__, __LINE__);
400 if (!ifSqlHasZeroNums($result)) {
401 // Is the error code set?
402 if (isGetRequestElementSet('code')) {
403 // Display error message
404 displayMessage(getMessageFromErrorCode(getRequestElement('code')));
407 // Load all email types...
408 while ($payment = sqlFetchArray($result)) {
409 array_push($payments, $payment);
413 sqlFreeResult($result);
415 // Output user's points
416 $content['total_points'] = $totalPoints;
418 // Check how many mail orders he has placed today and how many he's allowed to send
419 switch (getOrderMaxFull()) {
420 case 'MAX': // He is allowed to send as much as possible
421 $content['order_max_full'] = '{--MEMBER_ORDER_ALLOWED_MAX--}';
424 case 'ORDER': // He is allowed to send as much as he setup the receiving value
425 $content['order_max_full'] = sprintf(getMessage('MEMBER_ORDER_ALLOWED_RECEIVE'), $ALLOWED, getUserData('receive_mails'));
428 default: // Unknown/invalid
429 logDebugMessage(__FILE__, __LINE__, sprintf("Unknown order_mas_full config detected.", getOrderMaxFull()));
430 $content['order_max_full'] = '{--MEMBER_ORDER_ALLOWED_UNKNOWN--}';
434 // Load final template
435 loadTemplate('member_order_points', FALSE, $content);
443 // Check if we already have an order placed and make it editable
444 $result = sqlQueryEscaped("SELECT
454 `{?_MYSQL_PREFIX?}_pool`
459 array(getMemberId()), __FILE__, __LINE__);
461 if (sqlNumRows($result) == 1) {
463 $content = merge_array($content, sqlFetchArray($result));
465 // Fix max receivers when it is too much
466 if ((isset($categories['userids'][$content['cat_id']])) && ($content['target_send'] > $categories['userids'][$content['cat_id']])) {
468 $content['target_send'] = $categories['userids'][$content['cat_id']];
471 // Old order is grabbed
474 // Default output for that your members don't forget it...
475 $content['url'] = 'http://';
476 $content['target_send'] = '{?order_min?}';
477 $content['subject'] = '';
478 $content['text'] = '';
482 sqlFreeResult($result);
484 if ((isPostRequestElementSet('data')) || ((getOrderMultiPage() != 'Y') && ((!isAdmin()) && (!isExtensionActive('html_mail'))))) {
485 // Pre-output categories
486 $content['category_selection'] = generateCategoryOptionsList(((isExtensionActive('html_mail')) && (isPostRequestElementSet('html'))) ? postRequestElement('html') : 'N', getMemberId());
489 $content['payment_selection'] = '';
490 foreach ($payments as $key => $value) {
491 if (is_array($value)) {
492 // Output option line
493 $content['payment_selection'] .= ' <option value="' . $payments[$key]['id'] . '"';
494 if (($OLD_ORDER) && ($content['payment_id'] == $payments[$key]['id'])) $content['payment_selection'] .= ' selected="selected"';
495 $content['payment_selection'] .= '>{%pipe,translateComma=' . $payments[$key]['price'] . '%} {--PER_MAIL--} - ' . $payments[$key]['mail_title'] . ' - ' . round($payments[$key]['payment']) . ' {--PAYMENT--}</option>';
499 // No content is default
500 $content['zip_content'] = '';
502 if (isPostRequestElementSet('zip')) {
503 // Output entered ZIP code
504 $content['zip_content'] = loadTemplate('member_order_zip2', TRUE, postRequestElement('zip'));
507 // No HTML extension installed by default
508 $content['html_extension'] = '<input type="hidden" name="html" value="N" />';
511 if ((isExtensionActive('html_mail')) && (postRequestElement('html') == 'Y')) {
512 // Extension is active so output valid HTML tags
513 $content['html_extension'] = loadTemplate('member_order_html_ext', TRUE);
516 // Output form for page 2
517 loadTemplate('member_order_page2', FALSE, $content);
519 // No HTML extension installed by default
520 $content['html_extension'] = '<input type="hidden" name="html" value="N" />';
522 // Remember maybe entered ZIP code in constant
523 if (isExtensionActive('html_mail')) {
524 // Add some content when html extension is active
525 $content['html_extension'] = loadTemplate('member_order_html_intro', TRUE);
528 // Default is no ZIP code
529 $content['zip_content'] = '';
531 // Is sending to ZIP code enabled? (logged-in admin can always send to it)
532 if ((isOrderMultiPageEnabled()) || (isAdmin())) {
534 if (postRequestElement('zip') > 0) {
536 'zip' => bigintval(postRequestElement('zip'))
543 $content['zip_content'] = loadTemplate('member_order_zip1', TRUE, $data);
546 // Output form for page 1 (ZIP code or HTML)
547 loadTemplate('member_order_page1', FALSE, $content);
550 // No mail types defined
551 displayMessage('<span class="bad">{--MEMBER_ORDER_NO_PAYMENTS--}</span>');
555 displayMessage('<span class="notice">{--MEMBER_ORDER_NO_POINTS--}</span>');
558 // No cateogries are defined yet
559 displayMessage('<span class="bad">{--MEMBER_NO_CATEGORIES--}</span>');
562 // Please confirm some mails first
563 displayMessage('<span class="notice">{%message,MEMBER_ORDER_LINKS_LEFT=' . getTotalUnconfirmedMails(getMemberId()) . '%}</span>');
566 if (!empty($data['url'])) {
567 // Redirect to requested URL
568 redirectToUrl($data['url']);