6f3bc4fc4d545245cf091ade63c420d024cc7ad6
[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((isset($data['id'])) && (isValidId($data['id'])));
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 = '';
319                         if ((isExtensionActive('html_mail')) && (postRequestElement('html') == 'Y')) {
320                                 $HTML = " AND `html`='Y'";
321                         } // END - if
322
323                         // ... and begin loading stuff
324                         while ($categoriesContent = sqlFetchArray($result_cats)) {
325                                 $categories['id'][]   = bigintval($categoriesContent['id']);
326                                 array_push($categories['name'], $categoriesContent['cat']);
327
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__);
331
332                                 $userid_cnt = '0';
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`
340 FROM
341         `{?_MYSQL_PREFIX?}_user_data` AS `d`
342 LEFT JOIN
343         `{?_MYSQL_PREFIX?}_user_holidays` AS `h`
344 ON
345         `d`.`userid`=`h`.`userid`
346 WHERE
347         `d`.`userid`=%s AND
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()
353 LIMIT 1",
354                                                         array(bigintval($userid)), __FILE__, __LINE__);
355
356                                                 // Fetch entry
357                                                 list($count) = sqlFetchRow($result_holiday);
358
359                                                 // Free memory
360                                                 sqlFreeResult($result_holiday);
361
362                                                 // Is holiday is active?
363                                                 $isHolidayActive = ($count == 1);
364                                         } // END - if
365
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__);
370
371                                                 if ((sqlNumRows($result_ver) == 1) && (isPostRequestElementSet('zip')) && (isOrderMultiPageEnabled())) {
372                                                         // Get zip code
373                                                         list($zip) = sqlFetchRow($result_ver);
374                                                         if (substr($zip, 0, strlen(postRequestElement('zip'))) == postRequestElement('zip')) {
375                                                                 // Ok, ZIP code part is found
376                                                                 $userid_cnt++;
377                                                         } // END - if
378                                                 } else {
379                                                         // Count numbers up!
380                                                         $userid_cnt += sqlNumRows($result_ver);
381                                                 }
382
383                                                 // Free result
384                                                 sqlFreeResult($result_ver);
385                                         } // END - if
386                                 } // END - while
387
388                                 // Free memory
389                                 sqlFreeResult($result_userids);
390                                 array_push($categories['userids'], $userid_cnt);
391                         } // END - while
392
393                         // Free memory
394                         sqlFreeResult($result_cats);
395
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__);
398
399                         $payments = array();
400                         if (!ifSqlHasZeroNums($result)) {
401                                 // Is the error code set?
402                                 if (isGetRequestElementSet('code')) {
403                                         // Display error message
404                                         displayMessage(getMessageFromErrorCode(getRequestElement('code')));
405                                 } // END - if
406
407                                 // Load all email types...
408                                 while ($payment = sqlFetchArray($result)) {
409                                         array_push($payments, $payment);
410                                 } // END - while
411
412                                 // Free memory
413                                 sqlFreeResult($result);
414
415                                 // Output user's points
416                                 $content['total_points'] = $totalPoints;
417
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--}';
422                                                 break;
423
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'));
426                                                 break;
427
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--}';
431                                                 break;
432                                 } // END - switch
433
434                                 // Load final template
435                                 loadTemplate('member_order_points', FALSE, $content);
436
437                                 // Reset variables
438                                 $OLD_ORDER = FALSE;
439                                 $subject = '';
440                                 $text = '';
441                                 $target = '';
442
443                                 // Check if we already have an order placed and make it editable
444                                 $result = sqlQueryEscaped("SELECT
445         `subject`,
446         `text`,
447         `payment_id`,
448         `timestamp`,
449         `url`,
450         `target_send`,
451         `cat_id`,
452         `zip`
453 FROM
454         `{?_MYSQL_PREFIX?}_pool`
455 WHERE
456         `sender`=%s AND
457         `data_type`='TEMP'
458 LIMIT 1",
459                                         array(getMemberId()), __FILE__, __LINE__);
460
461                                 if (sqlNumRows($result) == 1) {
462                                         // Old order found
463                                         $content = merge_array($content, sqlFetchArray($result));
464
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']])) {
467                                                 // Fix it
468                                                 $content['target_send'] = $categories['userids'][$content['cat_id']];
469                                         } // END - if
470
471                                         // Old order is grabbed
472                                         $OLD_ORDER = TRUE;
473                                 } else {
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']        = '';
479                                 }
480
481                                 // Free result
482                                 sqlFreeResult($result);
483
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());
487
488                                         // Mail type
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>';
496                                                 } // END - if
497                                         } // END - foreach
498
499                                         // No content is default
500                                         $content['zip_content'] = '';
501
502                                         if (isPostRequestElementSet('zip')) {
503                                                 // Output entered ZIP code
504                                                 $content['zip_content'] = loadTemplate('member_order_zip2', TRUE, postRequestElement('zip'));
505                                         } // END - if
506
507                                         // No HTML extension installed by default
508                                         $content['html_extension'] = '<input type="hidden" name="html" value="N" />';
509
510                                         // HTML extension
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);
514                                         } // END - if
515
516                                         // Output form for page 2
517                                         loadTemplate('member_order_page2', FALSE, $content);
518                                 } else {
519                                         // No HTML extension installed by default
520                                         $content['html_extension'] = '<input type="hidden" name="html" value="N" />';
521
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);
526                                         } // END - if
527
528                                         // Default is no ZIP code
529                                         $content['zip_content'] = '';
530
531                                         // Is sending to ZIP code enabled? (logged-in admin can always send to it)
532                                         if ((isOrderMultiPageEnabled()) || (isAdmin())) {
533                                                 // Yes
534                                                 if (postRequestElement('zip') > 0) {
535                                                         $data = array(
536                                                                 'zip' => bigintval(postRequestElement('zip'))
537                                                         );
538                                                 } else {
539                                                         $data = array(
540                                                                 'zip' => ''
541                                                         );
542                                                 }
543                                                 $content['zip_content'] = loadTemplate('member_order_zip1', TRUE, $data);
544                                         } // END - if
545
546                                         // Output form for page 1 (ZIP code or HTML)
547                                         loadTemplate('member_order_page1', FALSE, $content);
548                                 }
549                         } else {
550                                 // No mail types defined
551                                 displayMessage('<span class="bad">{--MEMBER_ORDER_NO_PAYMENTS--}</span>');
552                         }
553                 } else {
554                         // No points left
555                         displayMessage('<span class="notice">{--MEMBER_ORDER_NO_POINTS--}</span>');
556                 }
557         } else {
558                 // No cateogries are defined yet
559                 displayMessage('<span class="bad">{--MEMBER_NO_CATEGORIES--}</span>');
560         }
561 } else {
562         // Please confirm some mails first
563         displayMessage('<span class="notice">{%message,MEMBER_ORDER_LINKS_LEFT=' . getTotalUnconfirmedMails(getMemberId()) . '%}</span>');
564 }
565
566 if (!empty($data['url'])) {
567         // Redirect to requested URL
568         redirectToUrl($data['url']);
569 } // END - if
570
571 // [EOF]
572 ?>