307b27b7075ef6a84fab34bfd869b5a5f0b9ed52
[mailer.git] / inc / modules / member / what-order.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 10/19/2003 *
4  * ===================                          Last change: 08/26/2004 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : what-order.php                                   *
8  * -------------------------------------------------------------------- *
9  * Short description : Order mails here                                 *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Hier koennen Ihre Mitglieder Mails buchen        *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2015 by Mailer Developer Team                   *
20  * For more information visit: http://mxchange.org                      *
21  *                                                                      *
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.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * GNU General Public License for more details.                         *
29  *                                                                      *
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,               *
33  * MA  02110-1301  USA                                                  *
34  ************************************************************************/
35
36 // Some security stuff...
37 if (!defined('__SECURITY')) {
38         exit();
39 } elseif (!isMember()) {
40         redirectToIndexMemberOnlyModule();
41 }
42
43 // Add description as navigation point
44 addYouAreHereLink('member', __FILE__);
45
46 if ((!isExtensionActive('order')) && (!isAdmin())) {
47         displayMessage('{%pipe,generateExtensionInactiveNotInstalledMessage=order%}');
48         return;
49 } // END - if
50
51 // Init data
52 $data = array(
53         'id'        => '0',
54         'data_type' => 'TEMP',
55         'url'       => '',
56 );
57
58 $ALLOWED = getUserData('receive_mails') - getUserData('mail_orders');
59 if (getOrderMaxFull() == 'MAX') $ALLOWED = getUserData('receive_mails');
60
61 // Now check his points amount
62 $totalPoints = getTotalPoints(getMemberId());
63
64 // Admin can always book
65 if ((isExtensionInstalledAndNewer('holiday', '0.1.3')) && (isUserDataEnabled('holiday_active')) && (!isAdmin())) {
66         // Holiday is active!
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
70         //
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
74         `id`,
75         `data_type`
76 FROM
77         `{?_MYSQL_PREFIX?}_pool`
78 WHERE
79         `sender`=%s AND
80         `url`='%s' AND
81         (UNIX_TIMESTAMP() - `timestamp`) >= {?url_tlock?}
82 LIMIT 1",
83                 array(
84                         getMemberId(),
85                         postRequestElement('url')
86                 ), __FILE__, __LINE__);
87
88         if (sqlNumRows($result) == 1) {
89                 // Load id and mail type
90                 $data = sqlFetchArray($result);
91         } // END - if
92
93         // Free result
94         sqlFreeResult($result);
95
96         if ($data['data_type'] == 'TEMP') {
97                 // Prepare data for filter chain
98                 $filterData = array(
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']),
106                         'redirect'  => '',
107                 );
108
109                 // Run the filter chain
110                 $filterData = runFilterChain('pre_mail_order', $filterData);
111
112                 // Copy field redirect->url
113                 $data['url'] = $filterData['redirect'];
114
115                 // Is there an error?
116                 if (empty($data['url'])) {
117                         // Copy all filter data -> POST
118                         foreach ($filterData as $key => $value) {
119                                 // Set it
120                                 setPostRequestElement($key, $value);
121                         } // END - foreach
122                 } // END - if
123         } elseif (!isAdmin()) {
124                 // He has already sent a mail within a specific time
125                 $data['url'] = 'modules.php?module=login&amp;what=order&amp;code=' . getCode('URL_TIME_LOCK') . '&amp;id=' . $data['id'];
126         }
127
128         // Still no error?
129         if (empty($data['url'])) {
130                 // Check for userids
131                 $result = sqlQueryEscaped("SELECT
132         `c`.`userid`
133 FROM
134         `{?_MYSQL_PREFIX?}_user_cats` AS `c`
135 INNER JOIN
136         `{?_MYSQL_PREFIX?}_user_data` AS `d`
137 ON
138         `c`.`userid`=`d`.`userid`
139 WHERE
140         `c`.`cat_id`=%s AND
141         `c`.`userid` != %s AND
142         `d`.`status`='CONFIRMED'
143         " . runFilterChain('user_exclusion_sql', ' ') . " AND
144         `d`.`receive_mails` > 0
145 ORDER BY
146         `d`.`{?order_select?}` {?order_mode?}",
147                         array(
148                                 bigintval(postRequestElement('cat')),
149                                 getMemberId()
150                         ), __FILE__, __LINE__);
151
152                 // Are there still receivers left?
153                 if (sqlNumRows($result) >= postRequestElement('receiver')) {
154                         // Load receivers from database
155                         $receiverArray = array(); $count = '0';
156                         while ($holidayContent = sqlFetchArray($result)) {
157                                 // Run fetched data through pre filter chain
158                                 $holidayContent = runFilterChain('pre_mail_recipient_check', $holidayContent);
159
160                                 // Is still valid id?
161                                 if (isValidId($holidayContent['userid'])) {
162                                         // Add receiver then
163                                         array_push($receiverArray, $holidayContent['userid']);
164                                         $count++;
165                                 } // END - if
166                         } // END - while
167
168                         // Free memory
169                         sqlFreeResult($result);
170
171                         // Implode array into string for the sending pool
172                         $receivers = implode($receiverArray, ';');
173
174                         // Count array for maximum sent
175                         $content['target_send'] = count($receiverArray);
176
177                         // Update receiver list
178                         sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `receive_mails`=`receive_mails`-1 WHERE `userid` IN (%s) LIMIT %s",
179                                 array(
180                                         convertReceivers($receivers),
181                                         bigintval($content['target_send'])
182                                 ), __FILE__, __LINE__);
183
184                         // Is calculated max receivers larger than wanted receivers then reset it
185                         if ($content['target_send'] > postRequestElement('receiver')) {
186                                 $content['target_send'] = bigintval(postRequestElement('receiver'));
187                         } // END - if
188
189                         // Calculate used points
190                         $usedPoints = $content['target_send'] * getPaymentPrice(bigintval(postRequestElement('mail_type')));
191
192                         // Fix empty zip code
193                         if (!isPostRequestElementSet('zip')) {
194                                 setPostRequestElement('zip', 0);
195                         } // END - if
196
197                         // Check if he has enougth points for this order and selected more than 0 receivers
198                         if (($usedPoints > 0) && ($usedPoints <= $totalPoints) && ($content['target_send'] > 0)) {
199                                 // Gettings points is okay, so we can add $usedPoints later from
200                                 if ((!isValidId($data['id'])) || ($data['data_type'] != 'TEMP')) {
201                                         // New order, init data array elements
202                                         $data = array(
203                                                 'sender'      => getMemberId(),
204                                                 'subject'     => postRequestElement('subject'),
205                                                 'text'        => postRequestElement('text'),
206                                                 'receivers'   => $receivers,
207                                                 'payment_id'  => bigintval(postRequestElement('mail_type')),
208                                                 'data_type'   => 'TEMP',
209                                                 'timestamp'   => 'UNIX_TIMESTAMP()',
210                                                 'url'         => postRequestElement('url'),
211                                                 'cat_id'      => bigintval(postRequestElement('cat')),
212                                                 'target_send' => bigintval($content['target_send']),
213                                                 'zip'         => bigintval(postRequestElement('zip'), TRUE, FALSE),
214                                         );
215
216                                         // Is ext-html_mail active?
217                                         if (isExtensionActive('html_mail')) {
218                                                 // HTML extension is active
219                                                 $data['html_msg'] = postRequestElement('html');
220                                         } // END - if
221
222                                         // Get insert id
223                                         $data['id'] = insertDataIntoPool($data);
224                                 } else {
225                                         // Update this data
226                                         $data = array(
227                                                 'subject'     => postRequestElement('subject'),
228                                                 'text'        => postRequestElement('text'),
229                                                 'receivers'   => $receivers,
230                                                 'payment_id'  => bigintval(postRequestElement('mail_type')),
231                                                 'timestamp'   => 'UNIX_TIMESTAMP()',
232                                                 'url'         => postRequestElement('url'),
233                                                 'cat_id'      => bigintval(postRequestElement('cat')),
234                                                 'target_send' => bigintval($content['target_send']),
235                                                 'zip'         => bigintval(postRequestElement('zip'), TRUE, FALSE),
236                                         );
237
238                                         // Is ext-html_mail active?
239                                         if (isExtensionActive('html_mail')) {
240                                                 // HTML extension is active
241                                                 $data['html_msg'] = postRequestElement('html');
242                                         } // END - if
243
244                                         // Update pool data
245                                         updatePoolDataById($data['id'], NULL, $data);
246                                 }
247
248                                 // Make sure only valid id numbers can pass
249                                 assert((isset($data['id'])) && (isValidId($data['id'])));
250
251                                 // Id is received so we can redirect the user, used points will be added when he send's out the mail
252                                 $data['url'] = 'modules.php?module=frametester&amp;order=' . bigintval($data['id']);
253                         } elseif ($content['target_send'] == '0') {
254                                 // Not enougth receivers found which can receive mails
255                                 $data['url'] = 'modules.php?module=login&amp;what=order&amp;code=' . getCode('MORE_RECEIVERS2');
256                         } else {
257                                 // No enougth points left!
258                                 $data['url'] = 'modules.php?module=login&amp;what=order&amp;code=' . getCode('MORE_POINTS');
259                         }
260                 } else {
261                         // Ordered more mails than he can send in this category
262                         $data['url'] = 'modules.php?module=login&amp;what=order&amp;code=' . getCode('NO_RECS_LEFT');
263                 }
264         } // END - if
265 } elseif (postRequestElement('receiver') == '0') {
266         // Not enougth receivers selected
267         $data['url'] = 'modules.php?module=login&amp;what=order&amp;code=' . getCode('MORE_RECEIVERS1');
268 } elseif (($ALLOWED == '0') && (getOrderMaxFull() == 'ORDER')) {
269         // No more mail orders allowed
270         displayMessage('{--MEMBER_ORDER_ALLOWED_EXHAUSTED--}');
271 } elseif (getTotalUnconfirmedMails(getMemberId()) < getConfig('max_unconfirmed')) {
272         // Show only enabled categories to the user ...
273         $whereStatement = " WHERE `visible`='Y'";
274
275         // ... but all to the admin
276         if (isAdmin()) $whereStatement = '';
277
278         // Display order form
279         $result_cats = sqlQuery('SELECT
280         `id`,
281         `cat`
282 FROM
283         `{?_MYSQL_PREFIX?}_cats`
284 ' . $whereStatement . '
285 ORDER BY
286         `sort` ASC', __FILE__, __LINE__);
287
288         // Some categories found?
289         if (!ifSqlHasZeroNums($result_cats)) {
290                 // Enought points left?
291                 if ($totalPoints > 0) {
292                         // Initialize array...
293                         $categories = array(
294                                 'id'      => array(),
295                                 'name'    => array(),
296                                 'userids' => array()
297                         );
298
299                         // Enable HTML checking
300                         // @TODO Rewrite this to a filter
301                         $HTML = '';
302                         if ((isExtensionActive('html_mail')) && (postRequestElement('html') == 'Y')) {
303                                 $HTML = " AND `html`='Y'";
304                         } // END - if
305
306                         // ... and begin loading stuff
307                         while ($categoriesContent = sqlFetchArray($result_cats)) {
308                                 $categories['id'][]   = bigintval($categoriesContent['id']);
309                                 array_push($categories['name'], $categoriesContent['cat']);
310
311                                 // Select users in current category
312                                 $result_userids = sqlQueryEscaped('SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s AND `userid` != %s ORDER BY `userid` ASC',
313                                         array(bigintval($categoriesContent['id']), getMemberId()), __FILE__, __LINE__);
314
315                                 $userid_cnt = '0';
316                                 while (list($userid) = sqlFetchRow($result_userids)) {
317                                         // Init filter data array
318                                         $filterData = array(
319                                                 'userid'   => $userid,
320                                                 'pre_okay' => TRUE,
321                                         );
322
323                                         // Check for holiday system
324                                         $filterData = runFilterChain('pre_category_mail_order_check', $filterData);
325
326                                         // Still all fine?
327                                         if ($filterData['pre_okay'] === TRUE) {
328                                                 // Check if the user want's to receive mails?
329                                                 $result_ver = sqlQueryEscaped("SELECT `zip` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s" . $HTML . " AND `receive_mails` > 0 AND `status`='CONFIRMED' LIMIT 1",
330                                                         array(bigintval($userid)), __FILE__, __LINE__);
331
332                                                 // Is an entry found?
333                                                 if ((sqlNumRows($result_ver) == 1) && (isPostRequestElementSet('zip')) && (isOrderMultiPageEnabled())) {
334                                                         // Get zip code
335                                                         list($zip) = sqlFetchRow($result_ver);
336                                                         if (substr($zip, 0, strlen(postRequestElement('zip'))) == postRequestElement('zip')) {
337                                                                 // Ok, ZIP code part is found
338                                                                 $userid_cnt++;
339                                                         } // END - if
340                                                 } else {
341                                                         // Count numbers up!
342                                                         $userid_cnt += sqlNumRows($result_ver);
343                                                 }
344
345                                                 // Free result
346                                                 sqlFreeResult($result_ver);
347                                         } // END - if
348                                 } // END - while
349
350                                 // Free memory
351                                 sqlFreeResult($result_userids);
352                                 array_push($categories['userids'], $userid_cnt);
353                         } // END - while
354
355                         // Free memory
356                         sqlFreeResult($result_cats);
357
358                         // Now we need to load the mail types...
359                         $result = sqlQuery("SELECT `id`, `price`, `payment`, `mail_title` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `price` > 0 AND `payment` > 0 ORDER BY `payment` ASC", __FILE__, __LINE__);
360
361                         $payments = array();
362                         if (!ifSqlHasZeroNums($result)) {
363                                 // Is the error code set?
364                                 if (isGetRequestElementSet('code')) {
365                                         // Display error message
366                                         displayMessage(getMessageFromErrorCode(getRequestElement('code')));
367                                 } // END - if
368
369                                 // Load all email types...
370                                 while ($payment = sqlFetchArray($result)) {
371                                         array_push($payments, $payment);
372                                 } // END - while
373
374                                 // Free memory
375                                 sqlFreeResult($result);
376
377                                 // Output user's points
378                                 $content['total_points'] = $totalPoints;
379
380                                 // Check how many mail orders he has placed today and how many he's allowed to send
381                                 switch (getOrderMaxFull()) {
382                                         case 'MAX': // He is allowed to send as much as possible
383                                                 $content['order_max_full'] = '{--MEMBER_ORDER_ALLOWED_MAX--}';
384                                                 break;
385
386                                         case 'ORDER': // He is allowed to send as much as he setup the receiving value
387                                                 $content['order_max_full'] = sprintf(getMessage('MEMBER_ORDER_ALLOWED_RECEIVE'), $ALLOWED, getUserData('receive_mails'));
388                                                 break;
389
390                                         default: // Unknown/invalid
391                                                 logDebugMessage(__FILE__, __LINE__, sprintf("Unknown order_mas_full config detected.", getOrderMaxFull()));
392                                                 $content['order_max_full'] = '{--MEMBER_ORDER_ALLOWED_UNKNOWN--}';
393                                                 break;
394                                 } // END - switch
395
396                                 // Load final template
397                                 loadTemplate('member_order_points', FALSE, $content);
398
399                                 // Reset variables
400                                 $OLD_ORDER = FALSE;
401                                 $subject = '';
402                                 $text = '';
403                                 $target = '';
404
405                                 // Check if we already have an order placed and make it editable
406                                 $result = sqlQueryEscaped("SELECT
407         `subject`,
408         `text`,
409         `payment_id`,
410         `timestamp`,
411         `url`,
412         `target_send`,
413         `cat_id`,
414         `zip`
415 FROM
416         `{?_MYSQL_PREFIX?}_pool`
417 WHERE
418         `sender`=%s AND
419         `data_type`='TEMP'
420 LIMIT 1",
421                                         array(getMemberId()), __FILE__, __LINE__);
422
423                                 if (sqlNumRows($result) == 1) {
424                                         // Old order found
425                                         $content = merge_array($content, sqlFetchArray($result));
426
427                                         // Fix max receivers when it is too much
428                                         if ((isset($categories['userids'][$content['cat_id']])) && ($content['target_send'] > $categories['userids'][$content['cat_id']])) {
429                                                 // Fix it
430                                                 $content['target_send'] = $categories['userids'][$content['cat_id']];
431                                         } // END - if
432
433                                         // Old order is grabbed
434                                         $OLD_ORDER = TRUE;
435                                 } else {
436                                         // Default output for that your members don't forget it...
437                                         $content['url']         = 'http://';
438                                         $content['target_send'] = '{?order_min?}';
439                                         $content['subject']     = '';
440                                         $content['text']        = '';
441                                 }
442
443                                 // Free result
444                                 sqlFreeResult($result);
445
446                                 if ((isPostRequestElementSet('data')) || ((getOrderMultiPage() != 'Y') && ((!isAdmin()) && (!isExtensionActive('html_mail'))))) {
447                                         // Pre-output categories
448                                         $content['category_selection'] = generateCategoryOptionsList(((isExtensionActive('html_mail')) && (isPostRequestElementSet('html'))) ? postRequestElement('html') : 'N', getMemberId());
449
450                                         // Mail type
451                                         $content['payment_selection'] = '';
452                                         foreach ($payments as $key => $value) {
453                                                 if (is_array($value)) {
454                                                         // Output option line
455                                                         $content['payment_selection'] .= '      <option value="' . $payments[$key]['id'] . '"';
456                                                         if (($OLD_ORDER) && ($content['payment_id'] == $payments[$key]['id'])) $content['payment_selection'] .= ' selected="selected"';
457                                                         $content['payment_selection'] .= '>{%pipe,translateComma=' . $payments[$key]['price'] . '%} {--PER_MAIL--} - ' . $payments[$key]['mail_title'] . ' - ' . round($payments[$key]['payment']) . ' {--PAYMENT--}</option>';
458                                                 } // END - if
459                                         } // END - foreach
460
461                                         // No content is default
462                                         $content['zip_content'] = '';
463
464                                         if (isPostRequestElementSet('zip')) {
465                                                 // Output entered ZIP code
466                                                 $content['zip_content'] = loadTemplate('member_order_zip2', TRUE, postRequestElement('zip'));
467                                         } // END - if
468
469                                         // No HTML extension installed by default
470                                         $content['html_extension'] = '<input type="hidden" name="html" value="N" />';
471
472                                         // HTML extension
473                                         if ((isExtensionActive('html_mail')) && (postRequestElement('html') == 'Y')) {
474                                                 // Extension is active so output valid HTML tags
475                                                 $content['html_extension'] = loadTemplate('member_order_html_ext', TRUE);
476                                         } // END - if
477
478                                         // Output form for page 2
479                                         loadTemplate('member_order_page2', FALSE, $content);
480                                 } else {
481                                         // No HTML extension installed by default
482                                         $content['html_extension'] = '<input type="hidden" name="html" value="N" />';
483
484                                         // Remember maybe entered ZIP code in constant
485                                         if (isExtensionActive('html_mail')) {
486                                                 // Add some content when html extension is active
487                                                 $content['html_extension'] = loadTemplate('member_order_html_intro', TRUE);
488                                         } // END - if
489
490                                         // Default is no ZIP code
491                                         $content['zip_content'] = '';
492
493                                         // Is sending to ZIP code enabled? (logged-in admin can always send to it)
494                                         if ((isOrderMultiPageEnabled()) || (isAdmin())) {
495                                                 // Yes
496                                                 if (postRequestElement('zip') > 0) {
497                                                         $data = array(
498                                                                 'zip' => bigintval(postRequestElement('zip'))
499                                                         );
500                                                 } else {
501                                                         $data = array(
502                                                                 'zip' => ''
503                                                         );
504                                                 }
505                                                 $content['zip_content'] = loadTemplate('member_order_zip1', TRUE, $data);
506                                         } // END - if
507
508                                         // Output form for page 1 (ZIP code or HTML)
509                                         loadTemplate('member_order_page1', FALSE, $content);
510                                 }
511                         } else {
512                                 // No mail types defined
513                                 displayMessage('<span class="bad">{--MEMBER_ORDER_NO_PAYMENTS--}</span>');
514                         }
515                 } else {
516                         // No points left
517                         displayMessage('<span class="notice">{--MEMBER_ORDER_NO_POINTS--}</span>');
518                 }
519         } else {
520                 // No cateogries are defined yet
521                 displayMessage('<span class="bad">{--MEMBER_NO_CATEGORIES--}</span>');
522         }
523 } else {
524         // Please confirm some mails first
525         displayMessage('<span class="notice">{%message,MEMBER_ORDER_LINKS_LEFT=' . getTotalUnconfirmedMails(getMemberId()) . '%}</span>');
526 }
527
528 if (!empty($data['url'])) {
529         // Redirect to requested URL
530         redirectToUrl($data['url']);
531 } // END - if
532
533 // [EOF]
534 ?>