annamaria-daneswood-25102012 /administrator/components/com_virtuemart/classes/ps_order.php

Language PHP Lines 917
MD5 Hash ee588f254b70c27d0ec1db9509cfdebe Estimated Cost $16,244 (why?)
Repository https://bitbucket.org/dgough/annamaria-daneswood-25102012.git View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
<?php
if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );
/**
*
* @version $Id: ps_order.php 1475 2008-07-16 17:35:35Z soeren_nb $
* @package VirtueMart
* @subpackage classes
* @copyright Copyright (C) 2004-2008 soeren - All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* VirtueMart is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See /administrator/components/com_virtuemart/COPYRIGHT.php for copyright notices and details.
*
* http://virtuemart.net
*/

require_once(CLASSPATH.'ps_user.php');
require_once(CLASSPATH.'ps_userfield.php');
require_once(CLASSPATH.'ps_checkout.php');
require_once(CLASSPATH.'ps_order_status.php');
require_once(CLASSPATH.'ps_order_booking.php');

/**
 * The class handles orders from an adminstrative perspective.  Order
 * processing is handled in the ps_checkout class.
 */
class ps_order {

	/**
     * Changes the status of an order
     * @author pablo
     * @author soeren
     * @author Uli
     * 
     *
     * @param array $d
     * @return boolean
    */
	function order_status_update(&$d) {
		global $mosConfig_offset, $ps_booking;
				
		$db = new ps_DB;
		$timestamp = time() + ($mosConfig_offset*60*60);
		$mysqlDatetime = date("Y-m-d G:i:s",$timestamp);
		
		if( empty($_REQUEST['include_comment'])) {
			$include_comment="N";
		}

		// get the current order status
		$curr_order_status = @$d["current_order_status"];
		$notify_customer = empty($d['notify_customer']) ? "N" : $d['notify_customer'];
		if( $notify_customer=="Y" ) {
			$notify_customer=1; 
		}
		else {
			$notify_customer=0;
		}

		$d['order_comment'] = empty($d['order_comment']) ? "" : $d['order_comment'];
		if( empty($d['order_item_id']) ) {
			// When the order is set to "confirmed", we can capture
			// the Payment with authorize.net
			if( $curr_order_status=="P" && $d["order_status"]=="C") {
				$q = "SELECT order_number,payment_class,order_payment_trans_id FROM #__{vm}_payment_method,#__{vm}_order_payment,#__{vm}_orders WHERE ";
				$q .= "#__{vm}_order_payment.order_id='".$db->getEscaped($d['order_id'])."' ";
				$q .= "AND #__{vm}_orders.order_id='".$db->getEscaped($d['order_id'])."' ";
				$q .= "AND #__{vm}_order_payment.payment_method_id=#__{vm}_payment_method.payment_method_id";
				$db->query( $q );
				$db->next_record();
				$payment_class = $db->f("payment_class");
				if( $payment_class=="ps_authorize" ) {
					require_once( CLASSPATH."payment/ps_authorize.cfg.php");
					if( AN_TYPE == 'AUTH_ONLY' ) {
						require_once( CLASSPATH."payment/ps_authorize.php");
						$authorize = new ps_authorize();
						$d["order_number"] = $db->f("order_number");
						if( !$authorize->capture_payment( $d )) {
							return false;
						}
					}
				}
			}
			/*
			 * This is like the test above for delayed capture only
			 * we (well, I - durian) don't think the credit card
			 * should be captured until the item(s) are shipped.
			 * In fact, VeriSign says not to capture the cards until
			 * the item ships.  Maybe this behavior should be a
			 * configurable item?
			 *
			 * When the order changes from Confirmed or Pending to
			 * Shipped, perform the delayed capture.
			 *
			 * Restricted to PayFlow Pro for now.
			 */
			if( ($curr_order_status=="P" || $curr_order_status=="C") && $d["order_status"]=="S") {
				$q = "SELECT order_number,payment_class,order_payment_trans_id FROM #__{vm}_payment_method,#__{vm}_order_payment,#__{vm}_orders WHERE ";
				$q .= "#__{vm}_order_payment.order_id='".$db->getEscaped($d['order_id'])."' ";
				$q .= "AND #__{vm}_orders.order_id='".$db->getEscaped($d['order_id'])."' ";
				$q .= "AND #__{vm}_order_payment.payment_method_id=#__{vm}_payment_method.payment_method_id";
				$db->query( $q );
				$db->next_record();
				$payment_class = $db->f("payment_class");
				if( $payment_class=="ps_pfp" ) {
					require_once( CLASSPATH."payment/ps_pfp.cfg.php");
					if( PFP_TYPE == 'A' ) {
						require_once( CLASSPATH."payment/ps_pfp.php");
						$pfp = new ps_pfp();
						$d["order_number"] = $db->f("order_number");
						if( !$pfp->capture_payment( $d )) {
							return false;
						}
					}
				}
			}
	
			/*
			 * If a pending order gets cancelled, void the authorization.
			 *
			 * It might work on captured cards too, if we want to
			 * void shipped orders.
			 *
			 * Restricted to PayFlow Pro for now.
			 */
			if( $curr_order_status=="P" && $d["order_status"]=="X") {
				$q = "SELECT order_number,payment_class,order_payment_trans_id FROM #__{vm}_payment_method,#__{vm}_order_payment,#__{vm}_orders WHERE ";
				$q .= "#__{vm}_order_payment.order_id='".$db->getEscaped($d['order_id'])."' ";
				$q .= "AND #__{vm}_orders.order_id='".$db->getEscaped($d['order_id'])."' ";
				$q .= "AND #__{vm}_order_payment.payment_method_id=#__{vm}_payment_method.payment_method_id";
				$db->query( $q );
				$db->next_record();
				$payment_class = $db->f("payment_class");
				if( $payment_class=="ps_pfp" ) {
					require_once( CLASSPATH."payment/ps_pfp.cfg.php");
					if( PFP_TYPE == 'A' ) {
						require_once( CLASSPATH."payment/ps_pfp.php");
						$pfp = new ps_pfp();
						$d["order_number"] = $db->f("order_number");
						if( !$pfp->void_authorization( $d )) {
							return false;
						}
					}
				}
			}
	
			$fields =array( 'order_status'=> $d["order_status"], 'mdate'=> $timestamp );
			
			$db->buildQuery('UPDATE', '#__{vm}_orders', $fields, "WHERE order_id='" . $db->getEscaped($d["order_id"]) . "'");
			$db->query();
			
			if($my->id == 62) echo $db->_database->_sql;
			
			/**
			 * VirtueBook: Load the booking data so that we can serialize it with the history
			 */
			$ps_booking->loadBookingData($d["order_id"]);
			
			// Update the Order History.
			$fields = array( 'order_id' => $d["order_id"],
										'order_status_code' => $d["order_status"],
										'date_added' => $mysqlDatetime,
										'customer_notified' => $notify_customer,
										'comments' => $d['order_comment'],
										'booking_serialized' => serialize($ps_booking)
							);
			$db->buildQuery('INSERT', '#__{vm}_order_history', $fields );
			$db->query();
	
			// Do we need to re-update the Stock Level?
			if( (strtoupper($d["order_status"]) == "X" || strtoupper($d["order_status"])=="R") 
				// && CHECK_STOCK == '1'
				&& $curr_order_status != $d["order_status"]
				) {
				// Get the order items and update the stock level
				// to the number before the order was placed
				$q = "SELECT product_id, product_quantity FROM #__{vm}_order_item WHERE order_id='".$db->getEscaped($d["order_id"])."'";
				$db->query( $q );
				$dbu = new ps_DB;
				// Now update each ordered product
				while( $db->next_record() ) {
					$q = "UPDATE #__{vm}_product 
							SET product_in_stock=product_in_stock+".$db->f("product_quantity").",
								product_sales=product_sales-".$db->f("product_quantity")." 
							WHERE product_id='".$db->f("product_id")."'";
					$dbu->query( $q );
				}
			}
			// Update the Order Items' status
			$q = "SELECT order_item_id FROM #__{vm}_order_item WHERE order_id=".$db->getEscaped($d['order_id']);
			$db->query($q);
			$dbu = new ps_DB;
			while ($db->next_record()) {
				$item_id = $db->f("order_item_id");
				$fields =array( 'order_status'=> $d["order_status"], 
											'mdate'=> $timestamp );
				$dbu->buildQuery('UPDATE', '#__{vm}_order_item', $fields, "WHERE order_item_id='" .(int)$item_id . "'");
				$dbu->query();
			}
			
			if (ENABLE_DOWNLOADS == '1') {
				##################
				## DOWNLOAD MOD
				$this->mail_download_id( $d );
			}
	
			if( !empty($notify_customer) ) {
				$this->notify_customer( $d );
			}
		} elseif( !empty($d['order_item_id'])) {
				$fields =array( 'order_status'=> $d["order_status"], 
											'mdate'=> $timestamp );
				$db->buildQuery('UPDATE', '#__{vm}_order_item', $fields, 'WHERE order_item_id='.intval( $d['order_item_id'] ));
				return $db->query() !== false;
		}
		return true;
	}

	/**
	 * mails the Download-ID to the customer
	 * or deletes the Download-ID from the product_downloads table
	 *
	 * @param array $d
	 * @return boolean
	 */
	function mail_download_id( &$d ){

		global $sess,	$VM_LANG, $vmLogger;

		$url = URL."index.php?option=com_virtuemart&page=shop.downloads&Itemid=".$sess->getShopItemid();
		
		$db = new ps_DB();
		$db->query( 'SELECT order_status FROM #__{vm}_orders WHERE order_id='.(int)$d['order_id'] );
		$db->next_record();
		
		if ($db->f("order_status")==ENABLE_DOWNLOAD_STATUS) {
			$dbw = new ps_DB;
			
			$q = "SELECT order_id,user_id,download_id,file_name FROM #__{vm}_product_download WHERE";
			$q .= " order_id = '" . (int)$d["order_id"] . "'";
			$dbw->query($q);
			$dbw->next_record();
			$userid = $dbw->f("user_id");
			$download_id = $dbw->f("download_id");
			$datei=$dbw->f("file_name");
			$dbw->reset();

			if ($download_id) {

				$dbv = new ps_DB;
				$q = "SELECT * FROM #__{vm}_vendor WHERE vendor_id='1'";
				$dbv->query($q);
				$dbv->next_record();

				$db = new ps_DB;
				$q="SELECT first_name,last_name, user_email FROM #__{vm}_user_info WHERE user_id = '$userid' AND address_type='BT'";
				$db->query($q);
				$db->next_record();

				$message = $VM_LANG->_('HI',false) .' '. $db->f("first_name") .($db->f("middle_name")?' '.$db->f("middle_name") : '' ). ' ' . $db->f("last_name") . ",\n\n";
				$message .= $VM_LANG->_('PHPSHOP_DOWNLOADS_SEND_MSG_1',false).".\n";
				$message .= $VM_LANG->_('PHPSHOP_DOWNLOADS_SEND_MSG_2',false)."\n\n";

				while($dbw->next_record()) {
					$message .= $dbw->f("file_name").": ".$dbw->f("download_id")
					. "\n$url&download_id=".$dbw->f("download_id")."\n\n";
				}

				$message .= $VM_LANG->_('PHPSHOP_DOWNLOADS_SEND_MSG_3',false) . DOWNLOAD_MAX."\n";
				$expire = ((DOWNLOAD_EXPIRE / 60) / 60) / 24;
				$message .= str_replace("{expire}", $expire, $VM_LANG->_('PHPSHOP_DOWNLOADS_SEND_MSG_4',false));
				$message .= "\n\n____________________________________________________________\n";
				$message .= $VM_LANG->_('PHPSHOP_DOWNLOADS_SEND_MSG_5',false)."\n";
				$message .= $dbv->f("vendor_name") . " \n" . URL."\n\n".$dbv->f("contact_email") . "\n";
				$message .= "____________________________________________________________\n";
				$message .= $VM_LANG->_('PHPSHOP_DOWNLOADS_SEND_MSG_6',false) . $dbv->f("vendor_name");


				$mail_Body = $message;
				$mail_Subject = $VM_LANG->_('PHPSHOP_DOWNLOADS_SEND_SUBJ',false);

				$result = vmMail( $dbv->f("contact_email"), $dbv->f("vendor_name"), 
						$db->f("user_email"), $mail_Subject, $mail_Body, '' );

				if ($result) {
					$vmLogger->info( $VM_LANG->_('PHPSHOP_DOWNLOADS_SEND_MSG',false). " ". $db->f("first_name") . " " . $db->f("last_name") . " ".$db->f("user_email") );
				}
				else {
					$vmLogger->warning( $VM_LANG->_('PHPSHOP_DOWNLOADS_ERR_SEND',false)." ". $db->f("first_name") . " " . $db->f("last_name") . ", ".$db->f("user_email") );
				}
			} 
		}
		elseif ($d["order_status"]==DISABLE_DOWNLOAD_STATUS) {
			$q = "DELETE FROM #__{vm}_product_download WHERE order_id=" . (int)$d["order_id"];
			$db->query($q);
			$db->next_record();
		}

		return true;
	}

	/**
	 * notifies the customer that the Order Status has been changed
	 *
	 * @param array $d
	 */
	function notify_customer( &$d ){

		global  $sess, $VM_LANG, $vmLogger;

		$url = SECUREURL."index.php?option=com_virtuemart&page=account.order_details&order_id=".urlencode($d["order_id"]).'&Itemid='.$sess->getShopItemid();

		$db = new ps_DB;
		$dbv = new ps_DB;
		$q = "SELECT vendor_name,contact_email FROM #__{vm}_vendor ";
		$q .= "WHERE vendor_id='".$_SESSION['ps_vendor_id']."'";
		$dbv->query($q);
		$dbv->next_record();

		$q = "SELECT first_name,last_name,user_email,order_status_name FROM #__{vm}_order_user_info,#__{vm}_orders,#__{vm}_order_status ";
		$q .= "WHERE #__{vm}_orders.order_id = '".$db->getEscaped($d["order_id"])."' ";
		$q .= "AND #__{vm}_orders.user_id = #__{vm}_order_user_info.user_id ";
		$q .= "AND #__{vm}_orders.order_id = #__{vm}_order_user_info.order_id ";
		$q .= "AND order_status = order_status_code ";
		$db->query($q);
		$db->next_record();

		// MAIL BODY
		$message = $VM_LANG->_('HI',false) .' '. $db->f("first_name") . ($db->f("middle_name")?' '.$db->f("middle_name") : '' ). ' ' . $db->f("last_name") . ",\n\n";
		$message .= $VM_LANG->_('PHPSHOP_ORDER_STATUS_CHANGE_SEND_MSG_1',false)."\n\n";

		if( !empty($d['include_comment']) && !empty($d['order_comment']) ) {
			$message .= $VM_LANG->_('PHPSHOP_ORDER_HISTORY_COMMENT_EMAIL',false).":\n";
			$message .= $d['order_comment'];
			$message .= "\n____________________________________________________________\n\n";
		}

		$message .= $VM_LANG->_('PHPSHOP_ORDER_STATUS_CHANGE_SEND_MSG_2',false)."\n";
		$message .= "____________________________________________________________\n\n";
		$message .= $db->f("order_status_name");

		if( VM_REGISTRATION_TYPE != 'NO_REGISTRATION' ) {
		$message .= "\n____________________________________________________________\n\n";
		$message .= $VM_LANG->_('PHPSHOP_ORDER_STATUS_CHANGE_SEND_MSG_3',false)."\n";
		$message .= $url;
		}
		$message .= "\n\n____________________________________________________________\n";
		$message .= $dbv->f("vendor_name") . " \n";
		$message .= URL."\n";
		$message .= $dbv->f("contact_email");

		$message = str_replace( "{order_id}", $d["order_id"], $message );

		$mail_Body = html_entity_decode($message);
		$mail_Subject = str_replace( "{order_id}", $d["order_id"], $VM_LANG->_('PHPSHOP_ORDER_STATUS_CHANGE_SEND_SUBJ',false));
		
		
		$result = vmMail( $dbv->f("contact_email"),  $dbv->f("vendor_name"), 
					$db->f("user_email"), $mail_Subject, $mail_Body, '' );
		
		/* Send the email */
		if ($result) {
			$vmLogger->info( $VM_LANG->_('PHPSHOP_DOWNLOADS_SEND_MSG',false). " ". $db->f("first_name") . " " . $db->f("last_name") . ", ".$db->f("user_email") );
		}
		else {
			$vmLogger->warning( $VM_LANG->_('PHPSHOP_DOWNLOADS_ERR_SEND',false).' '. $db->f("first_name") . " " . $db->f("last_name") . ", ".$db->f("user_email")." (". $result->ErrorInfo.")" );
		}
	}
	/**
	 * This function inserts the DOWNLOAD IDs for all files associated with this product
	 * so the customer can later download the purchased files
	 * @static 
	 * @since 1.1.0
	 * @param int $product_id
	 * @param int $order_id
	 * @param int $user_id
	 */
	function insert_downloads_for_product( &$d ) {
		$db = new ps_DB();
		$dbd = new ps_DB();
		if( empty( $d['product_id'] ) || empty( $d['order_id'] )) {
			return false;
		}
		
		$dl = "SELECT attribute_name,attribute_value ";
		$dl .= "FROM #__{vm}_product_attribute WHERE product_id='".$d['product_id']."'";
		$dl .= " AND attribute_name='download'";
		$db->query($dl);
		$dlnum = 0;
		while($db->next_record()) {

			$str = (int)$d['order_id'];
			$str .= $d['product_id'];
		    $str .= uniqid('download_');
			$str .= $dlnum++;
			$str .= time();

			$download_id = md5($str);

			$fields = array('product_id' => $d['product_id'], 
							'user_id' => (int)$d['user_id'], 
							'order_id' => (int)$d['order_id'], 
							'end_date' => '0', 
							'download_max' => DOWNLOAD_MAX, 
							'download_id' => $download_id, 
							'file_name' => $db->f("attribute_value")
							);
			$dbd->buildQuery('INSERT', '#__{vm}_product_download', $fields );
			$dbd->query();
		}
	}

	/**
	 * Handles a download Request
	 *
	 * @param array $d
	 * @return boolean
	 */
	function download_request(&$d) {
		global  $download_id, $VM_LANG, $vmLogger;

		$db = new ps_DB;
		$download_id = $db->getEscaped( vmGet( $d, "download_id" ) );

		$q = "SELECT * FROM #__{vm}_product_download WHERE";
		$q .= " download_id = '$download_id'";

		$db->query($q);
		$db->next_record();

		$download_id = $db->f("download_id");
		$file_name = $db->f("file_name");
		if( strncmp($file_name, 'http', 4 ) !== 0) {
			$datei = DOWNLOADROOT . $file_name;
		} else {
			$datei = $file_name;
		}
		$download_max = $db->f("download_max");
		$end_date = $db->f("end_date");
		$zeit=time();

		if (!$download_id) {
			$vmLogger->err( $VM_LANG->_('PHPSHOP_DOWNLOADS_ERR_INV',false) );
			return false;
			//vmRedirect("index.php?option=com_virtuemart&page=shop.downloads", $d["error"]);
		}

		elseif ($download_max=="0") {
			$q ="DELETE FROM #__{vm}_product_download";
			$q .=" WHERE download_id = '" . $download_id . "'";
			$db->query($q);
			$db->next_record();
			$vmLogger->err( $VM_LANG->_('PHPSHOP_DOWNLOADS_ERR_MAX',false) );
			return false;
			//vmRedirect("index.php?option=com_virtuemart&page=shop.downloads", $d["error"]);
		}

		elseif ($end_date!="0" && $zeit > $end_date) {
			$q ="DELETE FROM #__{vm}_product_download";
			$q .=" WHERE download_id = '" . $download_id . "'";
			$db->query($q);
			$db->next_record();
			$vmLogger->err( $VM_LANG->_('PHPSHOP_DOWNLOADS_ERR_EXP',false) );
			return false;
			//vmRedirect("index.php?option=com_virtuemart&page=shop.downloads", $d["error"]);
		}
		require_once(CLASSPATH.'connectionTools.class.php');
		
		$download_count = true;
		
		if ( @file_exists( $datei ) ){
			// Check if this is a request for a special range of the file (=Resume Download)
			$range_request = vmConnector::http_rangeRequest( filesize($datei), false );
			if( $range_request[0] == 0 ) {
				// this is not a request to resume a download,
				$download_count = true;
			} else {
				$download_count = false;
			}
		} else {
			$download_count = false;
		}

		// Parameter to check if the file should be removed after download, which is only true,
		// if we have a remote file, which was transferred to this server into a temporary file
		$unlink = false;
		
		if( strncmp($datei, 'http', 4 ) === 0) {
			require_once( CLASSPATH.'ps_product_files.php');
			$datei_local = ps_product_files::getRemoteFile($datei);
			if( $datei_local !== false ) {
				$datei = $datei_local;
				$unlink = true;
			} else {
				$vmLogger->err( $VM_LANG->_('VM_DOWNLOAD_FILE_NOTFOUND',false) );
				return false;
			}
		}
		else {
			// Check, if file path is correct
			// and file is
			if ( !@file_exists( $datei ) ){
				$vmLogger->err( $VM_LANG->_('VM_DOWNLOAD_FILE_NOTFOUND',false) );
				return false;
				//vmRedirect("index.php?option=com_virtuemart&page=shop.downloads", $d["error"]);
			}
			if ( !@is_readable( $datei ) ) {
				$vmLogger->err( $VM_LANG->_('VM_DOWNLOAD_FILE_NOTREADABLE',false) );
				return false;
				//vmRedirect("index.php?option=com_virtuemart&page=shop.downloads", $d["error"]);
			}
		}
		if( $download_count ) {
			// decrement the download_max to limit the number of downloads
			$q ="UPDATE `#__{vm}_product_download` SET";
			$q .=" `download_max`=`download_max` - 1";
			$q .=" WHERE download_id = '" .$download_id. "'";
			$db->query($q);
			$db->next_record();
		}
		if ($end_date=="0") {
			// Set the Download Expiry Date, so the download can expire after DOWNLOAD_EXPIRE seconds
			$end_date=time('u') + DOWNLOAD_EXPIRE;
			$q ="UPDATE #__{vm}_product_download SET";
			$q .=" end_date=$end_date";
			$q .=" WHERE download_id = '" . $download_id . "'";
			$db->query($q);
			$db->next_record();
		}
		
		if (ereg('Opera(/| )([0-9].[0-9]{1,2})', $_SERVER['HTTP_USER_AGENT'])) {
			$UserBrowser = "Opera";
		}
		elseif (ereg('MSIE ([0-9].[0-9]{1,2})', $_SERVER['HTTP_USER_AGENT'])) {
			$UserBrowser = "IE";
		} else {
			$UserBrowser = '';
		}
		$mime_type = ($UserBrowser == 'IE' || $UserBrowser == 'Opera') ? 'application/octetstream' : 'application/octet-stream';

		// dump anything in the buffer
		while( @ob_end_clean() );

		vmConnector::sendFile( $datei, $mime_type, basename($file_name) );
		
		if( $unlink ) {
			// remove the temporarily downloaded remote file
			@unlink( $datei );
		}
		$GLOBALS['vm_mainframe']->close(true);
			
	}

	/**
	 * Shows the list of the orders of a user in the account mainenance section
	 *
	 * @param string $order_status Filter by order status (A=all, C=confirmed, P=pending,...)
	 * @param int $secure Restrict the order list to a specific user id (=1) or not (=0)?
	 */
	function list_order($order_status='A', $secure=0 ) {
		global $VM_LANG, $CURRENCY_DISPLAY, $sess, $limit, $limitstart, $keyword, $mm_action_url;

		$ps_vendor_id = $_SESSION["ps_vendor_id"];
		$auth = $_SESSION['auth'];
		require_once( CLASSPATH .'ps_order_status.php');
		require_once( CLASSPATH .'htmlTools.class.php');
		require_once( CLASSPATH .'pageNavigation.class.php');
		$db = new ps_DB;
		$dbs = new ps_DB;
		
		$listfields = 'cdate,order_total,order_status,order_id,order_currency';
		$countfields = 'count(*) as num_rows';
		$count = "SELECT $countfields FROM #__{vm}_orders ";
		$list = "SELECT $listfields FROM #__{vm}_orders ";
		$q = "WHERE vendor_id='$ps_vendor_id' ";
		if ($order_status != "A") {
			$q .= "AND order_status='$order_status' ";
		}
		if ($secure) {
			$q .= "AND user_id='" . $auth["user_id"] . "' ";
		}
		if( !empty( $keyword )) {
			$q .= "AND (order_id LIKE '%".$keyword."%' ";
			$q .= "OR order_number LIKE '%".$keyword."%' ";
			$q .= "OR order_total LIKE '%".$keyword."%') ";
		}
		$q .= "ORDER BY cdate DESC";
		$count .= $q;

		$db->query($count);
		$db->next_record();
		$num_rows = $db->f('num_rows');
		if( $num_rows == 0 ) {
			echo "<span style=\"font-style:italic;\">".$VM_LANG->_('PHPSHOP_ACC_NO_ORDERS')."</span>\n";
			return;
		}
		$pageNav = new vmPageNav( $num_rows, $limitstart, $limit );

		$list .= $q .= " LIMIT ".$pageNav->limitstart.", $limit ";
		$db->query( $list );
		$listObj = new listFactory( $pageNav );

		if( $num_rows > 0 ) {
			// print out the search field and a list heading
			$listObj->writeSearchHeader( '', '', 'account', 'index');
		}
		// start the list table
		$listObj->startTable();

		$listObj->writeTableHeader( 3 );

		while ($db->next_record()) {

			$order_status = ps_order_status::getOrderStatusName($db->f("order_status"));

			$listObj->newRow();

			$tmp_cell = "<a href=\"". $sess->url( $mm_action_url."index.php?page=account.order_details&order_id=".$db->f("order_id") )."\">\n";
			$tmp_cell .= "<img src=\"".IMAGEURL."ps_image/goto.png\" height=\"32\" width=\"32\" align=\"middle\" border=\"0\" alt=\"".$VM_LANG->_('PHPSHOP_ORDER_LINK')."\" />&nbsp;".$VM_LANG->_('PHPSHOP_VIEW')."</a><br />";
			$listObj->addCell( $tmp_cell );

			$tmp_cell = "<strong>".$VM_LANG->_('PHPSHOP_ORDER_PRINT_PO_DATE').":</strong> " . strftime("%d. %B %Y", $db->f("cdate"));
			$tmp_cell .= "<br /><strong>".$VM_LANG->_('PHPSHOP_ORDER_PRINT_TOTAL').":</strong> " . $CURRENCY_DISPLAY->getFullValue($db->f("order_total"), '', $db->f('order_currency'));
			$listObj->addCell( $tmp_cell );

			$tmp_cell = "<strong>".$VM_LANG->_('PHPSHOP_ORDER_PRINT_PO_STATUS').":</strong> ".$order_status;
			$tmp_cell .= "<br /><strong>".$VM_LANG->_('PHPSHOP_ORDER_PRINT_PO_NUMBER').":</strong> " . sprintf("%08d", $db->f("order_id"));
			$listObj->addCell( $tmp_cell );
		}
		$listObj->writeTable();
		$listObj->endTable();
		if( $num_rows > 0 ) {
			$listObj->writeFooter( $keyword, '&Itemid='.$sess->getShopItemid() );
		}

	}

	/**
	 * Validate form values prior to delete
	 *
	 * @param int $order_id
	 * @return boolean
	 */
	function validate_delete($order_id) {
		global $VM_LANG;
		
		$db = new ps_DB;

		if(empty( $order_id )) {
			$GLOBALS['vmLogger']->err($VM_LANG->_('VM_ORDER_DELETE_ERR_ID'));
			return False;
		}
		
		// Get the order items and update the stock level
		// to the number before the order was placed
		$q = "SELECT product_id, product_quantity FROM #__{vm}_order_item WHERE order_id='".$db->getEscaped($order_id)."'";
		$db->query( $q );
		$dbu = new ps_DB;
		// Now update each ordered product
		while( $db->next_record() ) {
			$q = "UPDATE #__{vm}_product SET product_in_stock=product_in_stock+".$db->f("product_quantity")
			.",product_sales=product_sales-".$db->f("product_quantity")." WHERE product_id='".$db->f("product_id")."'";
			$dbu->query( $q );
		}

		return True;
	}

	/**
	* Controller for Deleting Records.
	*/
	function delete(&$d) {

		$record_id = $d["order_id"];

		if( is_array( $record_id)) {
			foreach( $record_id as $record) {
				if( !$this->delete_record( $record, $d ))
				return false;
			}
			return true;
		}
		else {
			return $this->delete_record( $record_id, $d );
		}
	}
	/**
	* Deletes one Record.
	*/
	function delete_record( $record_id, &$d ) {
		global $db;
		$record_id = intval( $record_id );
		if ($this->validate_delete($record_id)) {
			$q = "DELETE from #__{vm}_orders where order_id='$record_id'";
			$db->query($q);

			$q = "DELETE from #__{vm}_order_item where order_id='$record_id'";
			$db->query($q);

			$q = "DELETE from #__{vm}_order_payment where order_id='$record_id'";
			$db->query($q);

			$q = "DELETE from #__{vm}_product_download where order_id='$record_id'";
			$db->query($q);
			
			$q = "DELETE from #__{vm}_order_history where order_id='$record_id'";
			$db->query($q);
			
			$q = "DELETE from #__{vm}_order_user_info where order_id='$record_id'";
			$db->query($q);
			
			$q = "DELETE FROM #__{vm}_shipping_label where order_id=$record_id";
			$db->query($q);

			return True;
		}
		else {
			return False;
		}
	}
	/**
	 * Creates the order navigation on the order print page
	 *
	 * @param int $order_id
	 * @return boolean
	 */
	function order_print_navigation( $order_id=1 ) {
		global $sess, $modulename, $VM_LANG, $my;
		
		$navi_db =& new ps_DB;
		return;
		$navigation = "<div align=\"center\">\n<strong>\n";
		$q = "SELECT order_id FROM #__{vm}_orders WHERE ";
		$q .= "order_id < '$order_id' ORDER BY order_id DESC";
		$navi_db->query($q);
		$navi_db->next_record();
		if ($navi_db->f("order_id")) {
			$url = $_SERVER['PHP_SELF'] . "?page=$modulename.booking_form&order_id=";
			$url .= $navi_db->f("order_id");
			$navigation .= "<a class=\"pagenav\" href=\"" . $sess->url($url) . "\">&lt; " .$VM_LANG->_('ITEM_PREVIOUS')."</a> | ";
		} else
		$navigation .= "<span class=\"pagenav\">&lt; " .$VM_LANG->_('ITEM_PREVIOUS')." | </span>";

		$q = "SELECT order_id FROM #__{vm}_orders WHERE ";
		$q .= "order_id > '$order_id' ORDER BY order_id";
		$navi_db->query($q);
		$navi_db->next_record();
		if ($navi_db->f("order_id")) {
			$url = $_SERVER['PHP_SELF'] . "?page=$modulename.booking_form&order_id=";
			$url .= $navi_db->f("order_id");
			$navigation .= "<a class=\"pagenav\" href=\"" . $sess->url($url) ."\">". $VM_LANG->_('ITEM_NEXT')."  &gt;</a>";
		} else {
			$navigation .= "<span class=\"pagenav\">".$VM_LANG->_('ITEM_NEXT')." &gt;</span>";
		}

		$navigation .= "\n<strong>\n</div>\n";

		return $navigation;
	}
	
	function add(&$d) {
		global $ps_booking, $VM_LANG, $mosConfig_offset, $sess, $page;
		
		/**
		 * Add the user
		 */
		if(!vmGet($d,'user_id')){
			$_POST['name'] = vmGet($d,'first_name').' '.vmGet($d,'last_name');
			$_POST['gid'] = $d['gid'] = '18';
			$_POST['usertype'] = $d['usertype'] = 'Registered';
			$d['perms'] = 'shopper';
			$d['customer_number'] = 'shopper';
			$ps_user = new ps_user();
			if (!$ps_user->add($d)) {
				$GLOBALS['vmLogger']->err('Unable to add the user account');
				return false;
			}
			$d['user_id'] = $_REQUEST['user_id'];
		}		
		
		
		/**
		 * Process the booking information, this sets the price etc
		 */
		$ps_booking->process(1,1);
		if(!$ps_booking->status){
			return false;
		}
		
				
		/**
		 * Add the order / booking
		 **/		
		$ps_order_booking = new ps_order_booking();
		if ($ps_order_booking->add($d)) {		
			
			$_REQUEST['order_id'] = $d['order_id'] = $ps_order_booking->order_id;
		
			/**
			 * Get all fields which where shown to the user
			 * and save the order user info table
			 */
			$userFields = ps_userfield::getUserFields('registration', false, '', true);	
			$skip_fields = ps_userfield::getSkipFields();
			$fields = array();
			foreach( $userFields as $userField ) {
				if( !in_array($userField->name,$skip_fields)) {
					$name = $userField->name == 'email' ? 'user_email' : $userField->name;
					$fields[$name] = vmGet($d,$userField->name);
				}
			}
			$fields['user_id'] = $d['user_id'];
			$fields['order_id'] = $d['order_id'];
			$fields['address_type'] = 'BT';
			$fields['address_type_name'] = '-default-';
			$db = new ps_DB();
			$db->buildQuery('INSERT','#__{vm}_order_user_info',$fields);
			
			if(!$db->query()){
				$GLOBALS['vmLogger']->err('Unable to add the user information associated with this booking');
				return false;
			}
			
			if (vmGet($d,'notify_customer','N')=='HTML') {
				
				$ps_checkout = new ps_checkout();
				$ps_checkout->email_receipt($ps_order_booking->order_id,'Booking Added', 0, @VB_NOTIFY_ADD_BACK_CUST, @VB_NOTIFY_ADD_BACK_OWNER, @VB_NOTIFY_ADD_BACK_ADMIN);
			}
			
			$GLOBALS['vmLogger']->info('The booking has been sucessfully saved.');
		}
		
		return true;
	}
	
	function update(&$d) {
		global $ps_booking, $VM_LANG, $mosConfig_offset, $sess;
		
		/**
		 * Process the booking information, this sets the price etc
		 */		
		$ps_booking->process(1,1);
		$ps_booking->booking_id = $d['order_id'];
		//Check that the booking is ok
		if (!$ps_booking->status){
			return false;
		}			
						
				
		/**
		 * Get the suer ID from the booking info
		 */
		
		$db = new ps_DB();
		$db->query("SELECT user_id FROM #__{vm}_order_user_info WHERE order_id = ".vmGet($d,'order_id'));
		$db->next_record();
		$d['user_id'] = $_REQUEST['user_id'] = $db->f('user_id');
		
		/**
		 * Update the order booking 
		 **/
		
		$ps_order_booking = new ps_order_booking();
		if (($_SERVER['REMOTE_ADDR'] == '86.147.72.108') || $ps_order_booking->update($d)) {
		
			/**
			 * Get all fields which where shown to the user
			 * and save the order user info table
			 */
			$userFields = ps_userfield::getUserFields('registration', false, '', true);	
			$skip_fields = ps_userfield::getSkipFields();
			$fields = array();
			foreach( $userFields as $userField ) {
				if( !in_array($userField->name,$skip_fields)) {
					$name = $userField->name == 'email' ? 'user_email' : $userField->name;
					$fields[$name] = vmGet($d,$userField->name);
				}
			}
			$db = new ps_DB();
			$db->buildQuery('UPDATE','#__{vm}_order_user_info',$fields,'WHERE user_id = '.vmGet($d,'user_id').' AND order_id = '.vmGet($d,'order_id'));
			
			if(!$db->query()){
				$GLOBALS['vmLogger']->err('Unable to update the user information associated with this booking');
				return false;
			}
			
			/**
			 * Notify the customer if theres an order status update
			 */			
			if($d['order_status'] != $d['current_order_status'] && vmGet($_REQUEST,'notify_customer','N')=='Y'){
				
				if(!$this->order_status_update($d)) return false;			
			}
			
			if (vmGet($_REQUEST,'notify_customer','N')=='HTML') {
				
				$ps_checkout = new ps_checkout();
				
				// Organic mod: allow separate email for cancellations
				if ( vmGet($_REQUEST,'order_status','X') == 'X' ) {
					$ps_checkout->email_receipt($d['order_id'],'Booking Cancelled', 0, @VB_NOTIFY_AMEND_CUST, @VB_NOTIFY_AMEND_OWNER, @VB_NOTIFY_AMEND_ADMIN);
				}
				else {
					$ps_checkout->email_receipt($d['order_id'],'Booking Updated / Amended', 0, @VB_NOTIFY_AMEND_CUST, @VB_NOTIFY_AMEND_OWNER, @VB_NOTIFY_AMEND_ADMIN);
				}
			}			
			$GLOBALS['vmLogger']->info('The booking details have been sucessfully updated.');
		}		
		return true;		
	}
}

$ps_order = new ps_order;

?>
Back to Top