Fixes + asserts
[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 - 2013 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                         $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
160         `id`
161 FROM
162         `{?_MYSQL_PREFIX?}_user_holidays`
163 WHERE
164         `userid`=%s AND
165         `holiday_start` < UNIX_TIMESTAMP() AND
166         `holiday_end` > UNIX_TIMESTAMP()
167 LIMIT 1",
168                                                 array($holidayContent['userid']), __FILE__, __LINE__);
169                                         if (sqlNumRows($result_holiday) == 1) {
170                                                 // Exclude user who are in holiday
171                                                 $holidayContent['userid'] = '0';
172                                         } // END - if
173
174                                         // Free memory
175                                         sqlFreeResult($result_holiday);
176                                 } // END - if
177
178                                 if (isValidId($holidayContent['userid'])) {
179                                         // Add receiver
180                                         array_push($TEST, $holidayContent['userid']);
181                                         $count++;
182                                 } // END - if
183                         } // END - while
184
185                         // Free memory
186                         sqlFreeResult($result);
187
188                         // Implode array into string for the sending pool
189                         $receivers = implode($TEST, ';');
190
191                         // Count array for maximum sent
192                         $content['target_send'] = count($TEST);
193
194                         // Update receiver list
195                         sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `receive_mails`=`receive_mails`-1 WHERE `userid` IN (%s) LIMIT %s",
196                                 array(
197                                         convertReceivers($receivers),
198                                         bigintval($content['target_send'])
199                                 ), __FILE__, __LINE__);
200
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'));
204                         } // END - if
205
206                         // Calculate used points
207                         $usedPoints = $content['target_send'] * getPaymentPrice(bigintval(postRequestElement('mail_type')));
208
209                         // Fix empty zip code
210                         if (!isPostRequestElementSet('zip')) {
211                                 setPostRequestElement('zip', 0);
212                         } // END - if
213
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
219                                         $data = array(
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),
231                                         );
232
233                                         // Is ext-html_mail active?
234                                         if (isExtensionActive('html_mail')) {
235                                                 // HTML extension is active
236                                                 $data['html_msg'] = postRequestElement('html');
237                                         } // END - if
238
239                                         // Get insert id
240                                         $data['id'] = insertDataIntoPool($data);
241                                 } else {
242                                         // Update this data
243                                         $data = array(
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),
253                                         );
254
255                                         // Is ext-html_mail active?
256                                         if (isExtensionActive('html_mail')) {
257                                                 // HTML extension is active
258                                                 $data['html_msg'] = postRequestElement('html');
259                                         } // END - if
260
261                                         // Update pool data
262                                         updatePoolDataById($data['id'], NULL, $data);
263                                 }
264
265                                 // Make sure only valid id numbers can pass
266                                 assert(isValidId($data['id']), 'data[id]=' . $data['id'] . ' is not a valid id number.');
267
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&amp;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&amp;what=order&amp;code=' . getCode('MORE_RECEIVERS2');
273                         } else {
274                                 // No enougth points left!
275                                 $data['url'] = 'modules.php?module=login&amp;what=order&amp;code=' . getCode('MORE_POINTS');
276                         }
277                 } else {
278                         // Ordered more mails than he can send in this category
279                         $data['url'] = 'modules.php?module=login&amp;what=order&amp;code=' . getCode('NO_RECS_LEFT');
280                 }
281         } // END - if
282 } elseif (postRequestElement('receiver') == '0') {
283         // Not enougth receivers selected
284         $data['url'] = 'modules.php?module=login&amp;what=order&amp;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'";
291
292         // ... but all to the admin
293         if (isAdmin()) $whereStatement = '';
294
295         // Display order form
296         $result_cats = sqlQuery('SELECT
297         `id`,
298         `cat`
299 FROM
300         `{?_MYSQL_PREFIX?}_cats`
301 ' . $whereStatement . '
302 ORDER BY
303         `sort` ASC', __FILE__, __LINE__);
304
305         // Some categories found?
306         if (!ifSqlHasZeroNums($result_cats)) {
307                 // Enought points left?
308                 if ($totalPoints > 0) {
309                         // Initialize array...
310                         $categories = array(
311                                 'id'      => array(),
312                                 'name'    => array(),
313                                 'userids' => array()
314                         );
315
316                         // Enable HTML checking
317                         // @TODO Rewrite this to a filter
318                         $HTML = ''; $HOL_STRING = '';
319                         if ((isExtensionActive('html_mail')) && (postRequestElement('html') == 'Y')) {
320                                 $HTML = " AND `html`='Y'";
321                         } // END - if
322                         if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
323                                 // Extension's version is fine
324                                 $HOL_STRING = " AND `holiday_active`='N'";
325                         } // END - if
326
327                         // ... and begin loading stuff
328                         while ($categoriesContent = sqlFetchArray($result_cats)) {
329                                 $categories['id'][]   = bigintval($categoriesContent['id']);
330                                 array_push($categories['name'], $categoriesContent['cat']);
331
332                                 // Select users in current category
333                                 $result_userids = sqlQueryEscaped('SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s AND `userid` != %s ORDER BY `userid` ASC',
334                                         array(bigintval($categoriesContent['id']), getMemberId()), __FILE__, __LINE__);
335
336                                 $userid_cnt = '0';
337                                 while (list($userid) = sqlFetchRow($result_userids)) {
338                                         // Check for holiday system
339                                         $isHolidayActive = FALSE;
340                                         if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
341                                                 // Check user's holiday status
342                                                 $result_holiday = sqlQueryEscaped("SELECT
343         COUNT(`d`.`userid`) AS `cnt`
344 FROM
345         `{?_MYSQL_PREFIX?}_user_data` AS `d`
346 LEFT JOIN
347         `{?_MYSQL_PREFIX?}_user_holidays` AS `h`
348 ON
349         `d`.`userid`=`h`.`userid`
350 WHERE
351         `d`.`userid`=%s AND
352         `d`.`receive_mails` > 0 AND
353         `d`.`status`='CONFIRMED' AND
354         `d`.`holiday_active`='Y' AND
355         `h`.`holiday_start` < UNIX_TIMESTAMP() AND
356         `h`.`holiday_end` > UNIX_TIMESTAMP()
357 LIMIT 1",
358                                                         array(bigintval($userid)), __FILE__, __LINE__);
359
360                                                 // Fetch entry
361                                                 list($count) = sqlFetchRow($result_holiday);
362
363                                                 // Free memory
364                                                 sqlFreeResult($result_holiday);
365
366                                                 // Is holiday is active?
367                                                 $isHolidayActive = ($count == 1);
368                                         } // END - if
369
370                                         if ($isHolidayActive === FALSE) {
371                                                 // Check if the user want's to receive mails?
372                                                 $result_ver = sqlQueryEscaped("SELECT `zip` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s" . $HTML . " AND `receive_mails` > 0 AND `status`='CONFIRMED' LIMIT 1",
373                                                         array(bigintval($userid)), __FILE__, __LINE__);
374
375                                                 if ((sqlNumRows($result_ver) == 1) && (isPostRequestElementSet('zip')) && (isOrderMultiPageEnabled())) {
376                                                         // Get zip code
377                                                         list($zip) = sqlFetchRow($result_ver);
378                                                         if (substr($zip, 0, strlen(postRequestElement('zip'))) == postRequestElement('zip')) {
379                                                                 // Ok, ZIP code part is found
380                                                                 $userid_cnt++;
381                                                         } // END - if
382                                                 } else {
383                                                         // Count numbers up!
384                                                         $userid_cnt += sqlNumRows($result_ver);
385                                                 }
386
387                                                 // Free result
388                                                 sqlFreeResult($result_ver);
389                                         } // END - if
390                                 } // END - while
391
392                                 // Free memory
393                                 sqlFreeResult($result_userids);
394                                 array_push($categories['userids'], $userid_cnt);
395                         } // END - while
396
397                         // Free memory
398                         sqlFreeResult($result_cats);
399
400                         // Now we need to load the mail types...
401                         $result = sqlQuery("SELECT `id`, `price`, `payment`, `mail_title` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `price` > 0 AND `payment` > 0 ORDER BY `payment` ASC", __FILE__, __LINE__);
402
403                         $payments = array();
404                         if (!ifSqlHasZeroNums($result)) {
405                                 // Is the error code set?
406                                 if (isGetRequestElementSet('code')) {
407                                         // Display error message
408                                         displayMessage(getMessageFromErrorCode(getRequestElement('code')));
409                                 } // END - if
410
411                                 // Load all email types...
412                                 while ($payment = sqlFetchArray($result)) {
413                                         array_push($payments, $payment);
414                                 } // END - while
415
416                                 // Free memory
417                                 sqlFreeResult($result);
418
419                                 // Output user's points
420                                 $content['total_points'] = $totalPoints;
421
422                                 // Check how many mail orders he has placed today and how many he's allowed to send
423                                 switch (getOrderMaxFull()) {
424                                         case 'MAX': // He is allowed to send as much as possible
425                                                 $content['order_max_full'] = '{--MEMBER_ORDER_ALLOWED_MAX--}';
426                                                 break;
427
428                                         case 'ORDER': // He is allowed to send as much as he setup the receiving value
429                                                 $content['order_max_full'] = sprintf(getMessage('MEMBER_ORDER_ALLOWED_RECEIVE'), $ALLOWED, getUserData('receive_mails'));
430                                                 break;
431
432                                         default: // Unknown/invalid
433                                                 logDebugMessage(__FILE__, __LINE__, sprintf("Unknown order_mas_full config detected.", getOrderMaxFull()));
434                                                 $content['order_max_full'] = '{--MEMBER_ORDER_ALLOWED_UNKNOWN--}';
435                                                 break;
436                                 } // END - switch
437
438                                 // Load final template
439                                 loadTemplate('member_order_points', FALSE, $content);
440
441                                 // Reset variables
442                                 $OLD_ORDER = FALSE;
443                                 $subject = '';
444                                 $text = '';
445                                 $target = '';
446
447                                 // Check if we already have an order placed and make it editable
448                                 $result = sqlQueryEscaped("SELECT
449         `subject`,
450         `text`,
451         `payment_id`,
452         `timestamp`,
453         `url`,
454         `target_send`,
455         `cat_id`,
456         `zip`
457 FROM
458         `{?_MYSQL_PREFIX?}_pool`
459 WHERE
460         `sender`=%s AND
461         `data_type`='TEMP'
462 LIMIT 1",
463                                         array(getMemberId()), __FILE__, __LINE__);
464
465                                 if (sqlNumRows($result) == 1) {
466                                         // Old order found
467                                         $content = merge_array($content, sqlFetchArray($result));
468
469                                         // Fix max receivers when it is too much
470                                         if ((isset($categories['userids'][$content['cat_id']])) && ($content['target_send'] > $categories['userids'][$content['cat_id']])) {
471                                                 // Fix it
472                                                 $content['target_send'] = $categories['userids'][$content['cat_id']];
473                                         } // END - if
474
475                                         // Old order is grabbed
476                                         $OLD_ORDER = TRUE;
477                                 } else {
478                                         // Default output for that your members don't forget it...
479                                         $content['url']         = 'http://';
480                                         $content['target_send'] = '{?order_min?}';
481                                         $content['subject']     = '';
482                                         $content['text']        = '';
483                                 }
484
485                                 // Free result
486                                 sqlFreeResult($result);
487
488                                 if ((isPostRequestElementSet('data')) || ((getOrderMultiPage() != 'Y') && ((!isAdmin()) && (!isExtensionActive('html_mail'))))) {
489                                         // Pre-output categories
490                                         $content['category_selection'] = generateCategoryOptionsList(((isExtensionActive('html_mail')) && (isPostRequestElementSet('html'))) ? postRequestElement('html') : 'N', getMemberId());
491
492                                         // Mail type
493                                         $content['payment_selection'] = '';
494                                         foreach ($payments as $key => $value) {
495                                                 if (is_array($value)) {
496                                                         // Output option line
497                                                         $content['payment_selection'] .= '      <option value="' . $payments[$key]['id'] . '"';
498                                                         if (($OLD_ORDER) && ($content['payment_id'] == $payments[$key]['id'])) $content['payment_selection'] .= ' selected="selected"';
499                                                         $content['payment_selection'] .= '>{%pipe,translateComma=' . $payments[$key]['price'] . '%} {--PER_MAIL--} - ' . $payments[$key]['mail_title'] . ' - ' . round($payments[$key]['payment']) . ' {--PAYMENT--}</option>';
500                                                 } // END - if
501                                         } // END - foreach
502
503                                         // No content is default
504                                         $content['zip_content'] = '';
505
506                                         if (isPostRequestElementSet('zip')) {
507                                                 // Output entered ZIP code
508                                                 $content['zip_content'] = loadTemplate('member_order_zip2', TRUE, postRequestElement('zip'));
509                                         } // END - if
510
511                                         // No HTML extension installed by default
512                                         $content['html_extension'] = '<input type="hidden" name="html" value="N" />';
513
514                                         // HTML extension
515                                         if ((isExtensionActive('html_mail')) && (postRequestElement('html') == 'Y')) {
516                                                 // Extension is active so output valid HTML tags
517                                                 $content['html_extension'] = loadTemplate('member_order_html_ext', TRUE);
518                                         } // END - if
519
520                                         // Output form for page 2
521                                         loadTemplate('member_order_page2', FALSE, $content);
522                                 } else {
523                                         // No HTML extension installed by default
524                                         $content['html_extension'] = '<input type="hidden" name="html" value="N" />';
525
526                                         // Remember maybe entered ZIP code in constant
527                                         if (isExtensionActive('html_mail')) {
528                                                 // Add some content when html extension is active
529                                                 $content['html_extension'] = loadTemplate('member_order_html_intro', TRUE);
530                                         } // END - if
531
532                                         // Default is no ZIP code
533                                         $content['zip_content'] = '';
534
535                                         // Is sending to ZIP code enabled? (logged-in admin can always send to it)
536                                         if ((isOrderMultiPageEnabled()) || (isAdmin())) {
537                                                 // Yes
538                                                 if (postRequestElement('zip') > 0) {
539                                                         $data = array(
540                                                                 'zip' => bigintval(postRequestElement('zip'))
541                                                         );
542                                                 } else {
543                                                         $data = array(
544                                                                 'zip' => ''
545                                                         );
546                                                 }
547                                                 $content['zip_content'] = loadTemplate('member_order_zip1', TRUE, $data);
548                                         } // END - if
549
550                                         // Output form for page 1 (ZIP code or HTML)
551                                         loadTemplate('member_order_page1', FALSE, $content);
552                                 }
553                         } else {
554                                 // No mail types defined
555                                 displayMessage('<span class="bad">{--MEMBER_ORDER_NO_PAYMENTS--}</span>');
556                         }
557                 } else {
558                         // No points left
559                         displayMessage('<span class="notice">{--MEMBER_ORDER_NO_POINTS--}</span>');
560                 }
561         } else {
562                 // No cateogries are defined yet
563                 displayMessage('<span class="bad">{--MEMBER_NO_CATEGORIES--}</span>');
564         }
565 } else {
566         // Please confirm some mails first
567         displayMessage('<span class="notice">{%message,MEMBER_ORDER_LINKS_LEFT=' . getTotalUnconfirmedMails(getMemberId()) . '%}</span>');
568 }
569
570 if (!empty($data['url'])) {
571         // Redirect to requested URL
572         redirectToUrl($data['url']);
573 } // END - if
574
575 // [EOF]
576 ?>