annamaria-daneswood-25102012 /components/com_sm2emailmarketing/sm2emailmarketing.php

Language PHP Lines 1311
MD5 Hash ed843758a76739f9f07e3bd4cdc2dcf1 Estimated Cost $27,102 (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
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
<?php
// $Id: sm2emailmarketing.php,v 1.34 2008/04/21 08:00:02 sm2tony Exp $
/**
 * sm2emailmarketing - Email Marketing Newsletter
 *
 * Joomla! Newsletter Component that supports multiple list mailing and message queueing
 *
 * @package Joomla!
 * @subpackage com_sm2emailmarketing
 * @copyright Copyright (C) 2006 SM2 / All Rights Reserved
 * @license commercial
 * @author SM2 <info@sm2joomla.com>
 */

/**
* Makes sure this is included by a parent file
*/
defined('_VALID_MOS') or die('Direct Access to this location is not allowed.');

// include required files
require_once($mainframe->getPath('class'));
sm2emailmarketingConfig($option);

global $emErrorHandler, $sm2emailmarketingConfig;
require_once ($mosConfig_absolute_path . '/administrator/components/'.$option.'/includes/errorhandler.admin.php');
$emErrorHandler = new emError;

// include language file, or default to english
if (file_exists ($mosConfig_absolute_path . '/components/'.$option.'/languages/'.$mosConfig_lang.'.php')) {
    include_once ($mosConfig_absolute_path . '/components/'.$option.'/languages/'.$mosConfig_lang.'.php');
} else {
    include_once ($mosConfig_absolute_path . '/components/'.$option.'/languages/english.php');
} // end if


switch( $task ) {
	case 'subscribe': //note that this is also does the first step of the unsubscribe
		sm2emailmarketingSubscribe();
		break;
	case 'unsubscribe':
		sm2emailmarketingUnsubscribe();
		break;
	case 'confirm':
		sm2emailmarketingConfirm();
		break;
	case 'image': //used for stats tracking
		sm2emailmarketingImage();
		break;
    case 'showarchivelist':
    default:
        sm2emShowArchiveList($option);
        break;
    case 'showarchivemessage':
        sm2emShowMessageArchive($option);
        break;
    case 'forward':
        sm2emForward($option);
        break;
    case 'sendforward':
        sm2emSendForward($option);
        break;
}

function sm2emailmarketingSubscribe(){
	global $database, $mosConfig_live_site, $option,
        $mosConfig_mailfrom, $mosConfig_fromname, $my, $sm2emailmarketingConfig;

    $confirmreq = $sm2emailmarketingConfig->get('require_confirmation',0); // def, get, set
    $from = $sm2emailmarketingConfig->get('confirm_fromemail',$mosConfig_mailfrom);
    $fromname = $sm2emailmarketingConfig->get('confirm_fromname',$mosConfig_fromname);
    $message = $sm2emailmarketingConfig->get('confirm_text','[CONFIRM]');
    $message_unsubscribe = $sm2emailmarketingConfig->get('unsubscribe_text', _EMKTG_UNSUBSCRIBE_CLICKTOCONFIRM);

    // see if we need to do spoofchecking
    if ($sm2emailmarketingConfig->get('spoofcheck', 0)) {
        josSpoofCheck(true, $option);
    }

	$name = mosGetParam($_POST, 'name');
	$email = mosGetParam($_POST, 'email');
	$html = mosGetParam($_POST, 'html');
	$status = mosGetParam($_POST, 'status');
	$lists = mosGetParam($_POST, 'lists');

	//check that they are not a registered user (check for email)
	//if so advise that they need to login.
    if (empty($my->id)) {
    	$sql =  'SELECT id FROM #__users WHERE email LIKE '.$database->Quote($email);
    	$database->setQuery($sql);
        $rows=null;
    	$database->loadObject($rows);
    	if (is_object($rows)) {
    		sm2emailmarketingMessage(_EMKTG_SUBSCRIBE_ISUSER);
    		return;
    	}

        //check if email is in the system
        $sql = 'SELECT subscriberid AS id, name, email, receive_html AS format, unsubscribe_reason FROM #__emktg_subscriber WHERE email LIKE '.$database->Quote($email);
    } else {
        //check if email is in the system
        $sql = 'SELECT u.id AS id, u.name, u.email, eu.receive_html AS format, eu.unsubscribe_reason'
            .' FROM #__users u INNER JOIN #__emktg_user eu ON (u.id=eu.id) WHERE u.id='.(int)$my->id;
    }

    $database->setQuery($sql);
    $rows=null;
	$database->loadObject($rows);

    $found = true;
    if (!is_object($rows)) {
        $found = false;
    } else if (empty($rows->id)) {
        $found = false;
    }

    // check first that they are allowed to subscribe
    if ($found && $rows->unsubscribe_reason > 1) {
        $msgVar = '_EMKTG_RESUBSCRIBE_ERROR_'.(int)$rows->unsubscribe_reason;
        if (defined($msgVar)) {
            sm2emailmarketingMessage(constant($msgVar));
            return;
        }
    }

	if (!$found) { // email is not in the database
		if ($status ==0) {// they want to unsubscribe
			sm2emailmarketingMessage(_EMKTG_UNSUBSCRIBE_NOTFOUND);
		} else { //they are trying to subscribe
			if (!$confirmreq || $confirmreq == 0) { //no confirmation needed
                if (empty($my->id)) {
    				$sql = 'INSERT INTO #__emktg_subscriber ( name , email , receive_html , subscribe_date, confirmed)'
    				    .' VALUES('.$database->Quote($name).', '.$database->Quote($email).', '.(int)$html.', NOW(), 1)';
                } else {
                    $sql = 'INSERT INTO #__emktg_user ( id, receive_html , subscribe_date, confirmed)'
                        .' VALUES('.(int)$my->id.', '.(int)$html.', NOW(), 1)';
                }
				$database->setQuery($sql);
				$database->Query();
                if (empty($my->id)) {
    				$id = $database->insertid(); //subscriberid
    				if ($id) {
    					sm2emailmarketingMessage(_EMKTG_SUBSCRIBE_EMAILADDED);
                        $id = -$id;
    				}
                } else {
                    sm2emailmarketingMessage(_EMKTG_SUBSCRIBE_EMAILADDED);
                }
				//add to the mailing lists they chose
				sm2emailmarketingMailingSubscribe($id, $lists);
			} else {
                if (empty($my->id)) {
    				$sql = 'INSERT INTO #__emktg_subscriber ( name , email , receive_html , subscribe_date, confirmed)'
    				    .' VALUES('.$database->Quote($name).', '.$database->Quote($email).', '.(int)$html.', NOW(), 0)';
                } else {
                    $sql = 'INSERT INTO #__emktg_user ( id, receive_html , subscribe_date, confirmed)'
                        .' VALUES('.(int)$my->id.', '.(int)$html.', NOW(), 0)';
                }
				$database->setQuery($sql);
				$database->Query();
                if (empty($my->id)) {
				    $id = $database->insertid();
                    $id = -$id;
                } else {
                    $row = new mosUser($database);
                    $row->load($my->id);

                    $id = $row->id;
                    $email = $row->email;
                }

				//add to the mailing lists they chose
				sm2emailmarketingMailingSubscribe($id, $lists);

				$code = $id.$email;
				$code = md5($code);
				$mail = mosCreateMail($from, $fromname, _EMKTG_SUBSCRIBE_CONFIRMATION, '');

                $confirmUrl = 'index.php?option='.$option.'&task=confirm&email='.$email.'&code='.$code;
                if (function_exists('sefRelToAbs') && !defined('_JLEGACY')) {
                    $confirmUrl = sefRelToAbs($confirmUrl);
                } else {
                    $confirmUrl = $mosConfig_live_site.'/'.$confirmUrl;
                }

				if (!$html || $html == 0) { //send plain text email
					$mail->IsHTML(false);
                    $message = str_replace("\n", '', $message);
                    $message = str_replace('<br />', "\n", $message);
                    $message = strip_tags($message, '<a>');
					$mail->Body = str_replace('[CONFIRM]', $confirmUrl, $message);
				} else {
					$mail->IsHTML(true);
					$mail->Body = str_replace('[CONFIRM]', '<br /><a href="'.$confirmUrl.'">'._EMKTG_SUBSCRIBE_CLICKTOCONFIRM.'</a>', $message);
				}
				$mail->AddAddress($email, $name);
				if (!$mail->Send()) {
   					sm2emailmarketingMessage(_EMKTG_SUBSCRIBE_ERRORSENDINGMSG);
   					//exit;
				} else {
					sm2emailmarketingMessage(_EMKTG_SUBSCRIBE_MSGSENDSUCCESS);
					$mail->ClearAllRecipients();
				}
			}
		}
	} else {// email is already in database

		if ($status ==0) {// they want to unsubscribe
			//send an email confirming that they do actually want to unsubscribe.
			$mail = mosCreateMail($from, $fromname, _EMKTG_UNSUBSCRIBE_CONFIRMATION, '');
			$name = $rows->name;
			$email = $rows->email;
			$format = $rows->format;
			$lists = mosGetParam($_POST, 'lists');
            if (is_array($lists)) {
                $lists = implode('-', $lists);
            }
            if (empty($my->id)) {
                $rows->id = -$rows->id;
            }
			$code = $rows->id.$rows->email;
			$code = md5($code);
            $unSubscribeUrl = 'index.php?option='.$option.'&task=unsubscribe&email='.$email.'&code='.$code.'&lists='.$lists;

            if (function_exists('sefRelToAbs') && !defined('_JLEGACY')) {
                $unSubscribeUrl = sefRelToAbs($unSubscribeUrl);
            } else {
                $unSubscribeUrl = $mosConfig_live_site.'/'.$unSubscribeUrl;
            }

			if ($format) {
				$mail->IsHTML(true);
				$mail->Body = '<a href="'.$unSubscribeUrl.'">'.$message_unsubscribe.'</a>';
			} else {
				$mail->IsHTML(false);
				$mail->Body = $unSubscribeUrl.' '.$message_unsubscribe;
			}
			$mail->AddAddress($email, $name);

			if (!$mail->Send()) {
   				sm2emailmarketingMessage(_EMKTG_UNSUBSCRIBE_ERRORSENDINGMSG);
   				exit;
			} else {
				sm2emailmarketingMessage(_EMKTG_UNSUBSCRIBE_MSGSENDSUCCESS);
				$mail->ClearAllRecipients();
			}


		} else { // they want to subscribe
			// check to see if we should automatically 'confirm' the user
			// if not auto confirm then will need to send them an email
			if (!$confirmreq || $confirmreq == 0) {  // no confirmation needed
                if (empty($my->id)) {
				    $sql = 'UPDATE #__emktg_subscriber SET name='.$database->Quote($name).', receive_html='.(int)$html.', subscribe_date=NOW(), unsubscribe_date=NULL, unsubscribe_reason=0, confirmed=1 WHERE email LIKE '.$database->Quote($email);
                } else {
                    $sql = 'UPDATE #__emktg_user SET receive_html='.(int)$html.', subscribe_date=NOW(), unsubscribe_date=NULL, unsubscribe_reason=0, confirmed=1 WHERE id='.(int)$my->id;
                }
				$database->setQuery($sql);
				$added = $database->Query();
				//add to the mailing lists they chose
                if (empty($my->id)) {
				    $sql = 'SELECT subscriberid AS id FROM #__emktg_subscriber WHERE email LIKE '.$database->Quote($email);
                    $database->setQuery($sql);
                    $id = -$database->loadResult();
                } else {
                    $id = $my->id;
                }
				sm2emailmarketingMailingSubscribe($id, $lists);
				if ($added) {
					sm2emailmarketingMessage(_EMKTG_SUBSCRIBE_EMAILADDED);
				}
			} else { //need to send them a confirmation email
				//add them to the database with confirm = 0
                if (empty($my->id)) {
				    $sql = 'UPDATE #__emktg_subscriber SET name='.$database->Quote($name).', receive_html='.(int)$html.', subscribe_date=NOW(), unsubscribe_date=NULL, unsubscribe_reason=0, confirmed=0 WHERE email LIKE '.$database->Quote($email);
                } else {
                    $sql = 'UPDATE #__emktg_user SET receive_html='.(int)$html.', subscribe_date=NOW(), unsubscribe_date=NULL, unsubscribe_reason=0, confirmed=0 WHERE id='.(int)$my->id;
                }
				$database->setQuery($sql);
				$added = $database->Query();
				//add to the mailing lists they chose
                if (empty($my->id)) {
    				$sql = 'SELECT subscriberid AS id FROM #__emktg_subscriber WHERE email LIKE '.$database->Quote($email);
    				$database->setQuery($sql);
    				$id = -$database->loadResult();
                } else {
                    $id = $my->id;
                }
				sm2emailmarketingMailingSubscribe($id, $lists);
				$code = $id.$rows->email;
				$code = md5($code);
                $body=$message;
				$mail = mosCreateMail($from, $fromname, _EMKTG_SUBSCRIBE_CONFIRMATION, '');

                $confirmUrl = $mosConfig_live_site.'/index.php?option='.$option.'&task=confirm&email='.$email.'&code='.$code;
                if (function_exists('sefRelToAbs') && !defined('_JLEGACY')) {
                    $confirmUrl = sefRelToAbs($confirmUrl);
                }


				if(!$html || $html == 0) { //send plain text email
					$mail->IsHTML(false);
                    $body = str_replace("\n", '', $body);
                    $body = str_replace('<br />', "\n", $body);
                    $body = strip_tags($body, '<a>');
					$mail->Body = str_replace('[CONFIRM]',$confirmUrl, $body);
				} else {
					$mail->IsHTML(true);
					$mail->Body = str_replace('[CONFIRM]','<br /><a href="'.$confirmUrl.'">'._EMKTG_SUBSCRIBE_CLICKTOCONFIRM.'</a>', $body);
				}
				$mail->AddAddress($rows->email, $rows->name);
				if(!$mail->Send()){
   					sm2emailmarketingMessage(_EMKTG_SUBSCRIBE_ERRORSENDINGMSG);
   					exit;
				} else {
					sm2emailmarketingMessage(_EMKTG_SUBSCRIBE_MSGSENDSUCCESS);
					$mail->ClearAllRecipients();
				}
			}
		}
	}
} // sm2emailmarketingSubscribe()


function sm2emailmarketingUnsubscribe(){
	global $database, $my, $sm2emailmarketingConfig;

    $quick_registered_unsubscribe = $sm2emailmarketingConfig->get('quick_registered_unsubscribe', 0);

	//grab the values from link
	$email = mosGetParam($_GET, 'email');
	$code = mosGetParam($_GET, 'code');

	//check if email is in the system
    if (empty($my->id)) {
	   $sql = 'SELECT subscriberid AS id, email FROM #__emktg_subscriber WHERE email LIKE '.$database->Quote($email);
    } else {
       $sql = 'SELECT u.id AS id, u.email AS format'
        .' FROM #__users u INNER JOIN #__emktg_user eu ON (u.id=eu.id) WHERE eu.id='.(int)$my->id;
    }
	$database->setQuery($sql);
    $rows=null;
	$database->loadObject($rows);

    $found = true;
    if (!is_object($rows)) {
        $found = false;
    } else if (empty($rows->id)) {
        $found = false;
    }

	if (!$found) { //couldn't find the email address. check that they are not a registered subscriber
		$sql = 'SELECT id, email FROM #__users WHERE email LIKE '.$database->Quote($email);
		$database->setQuery($sql);
        $rows=null;
		$database->loadObject($rows);

        $userFound = true;
        if (!is_object($rows)) {
            $userFound = false;
        } else if (empty($rows->id)) {
            $userFound = false;
        }

		if (!$userFound) {
			sm2emailmarketingMessage(_EMKTG_UNSUBSCRIBE_NOTFOUND);
		} else { // they are a registered user
            if ($quick_registered_unsubscribe) {
                $found = true;
            } else {
                sm2emailmarketingMessage(_EMKTG_SUBSCRIBE_ISUSER);
            }
		}
	} else if (empty($my->id)) {
        $rows->id = -$rows->id;
    }

    if (!$found) return;

	$checkcode = $rows->id.$rows->email;
	$checkcode = md5($checkcode);
	if($checkcode != $code) {
		sm2emailmarketingMessage(_EMKTG_CONFIRMATION_SECURITYCHECKFAILED);
	} else { //all good let's remove them from the database
		$lists = mosGetParam($_GET, 'lists');
		if($lists) {
			$lists = explode('-', $lists);
		} else {
			$lists = 0;
		}
		//remove them from the mailinglists
		sm2emailmarketingMailingUnsubscribe($rows->id, $email, $lists);
	}
} // sm2emailmarketingUnsubscribe()

function sm2emailmarketingConfirm(){
	global $database, $my;

	//grab the values from the link
	$email = mosGetParam($_GET, 'email');
	$code = mosGetParam($_GET, 'code');

	//check if email is in the system
    if (empty($my->id)) {
        $sql = 'SELECT subscriberid AS id, name, email, receive_html AS format FROM #__emktg_subscriber WHERE email LIKE '.$database->Quote($email);
    } else {
        $sql = 'SELECT u.id, u.name, u.email, eu.receive_html AS format'
            .' FROM #__users u INNER JOIN #__emktg_user eu ON (u.id=eu.id) WHERE eu.id='.(int)$my->id;
    }
	$database->setQuery($sql);
    $rows=null;
	$database->loadObject($rows);

    $found = true;
    if (!is_object($rows)) {
        $found = false;
    } else if (empty($rows->id)) {
        $found = false;
    }

	if(!$found){ //couldn't find the email address.
		sm2emailmarketingMessage(_EMKTG_CONFIRMATION_NOTFOUND);
		exit;
	} else {
        if (empty($my->id)) {
            $id = -$rows->id;
        } else {
            $id = $my->id;
        }
		$checkcode = $id.$rows->email;
		$checkcode = md5($checkcode);
		if($checkcode != $code) {
			sm2emailmarketingMessage(_EMKTG_CONFIRMATION_SECURITYCHECKFAILED);
		} else { //all good, let's confirm them
            if (empty($my->id)) {
                $sql = 'UPDATE #__emktg_subscriber SET confirmed=1 WHERE subscriberid = '.(int)$rows->id;
            } else {
                $sql = 'UPDATE #__emktg_user SET confirmed=1 WHERE id = '.(int)$rows->id;
            }
			$database->setQuery($sql);
			$confirmed = $database->Query();
			if($confirmed) {
				sm2emailmarketingMessage(_EMKTG_CONFIRMATION_CONFIRMSUCCESS, 'success');
			} else {
				sm2emailmarketingMessage(_EMKTG_CONFIRMATION_CONFIRMERROR);
			}
		}
	}
}

// This gives admins the ability to change the formatting for their errors:
function sm2emailmarketingMessage($message, $type='error') {
	if($type=='success') $class = 'success';
	else $class = 'error';
	echo '<p class="'.$class.'">'.$message.'</p>';
}

function sm2emailmarketingMailingSubscribe($id, $lists=null) {
	global $database, $my;

	if(empty($lists)) {
		return;
	} else {
		foreach($lists as $list) {
            if ($id < 0) {
                $sql = 'INSERT IGNORE INTO #__emktg_list_subscriber ( listid, subscriberid ) VALUES ('.(int)$list.', '.(int)$id.')';
            } else {
                $sql = 'INSERT IGNORE INTO #__emktg_list_user ( listid, id ) VALUES ('.(int)$list.', '.(int)$id.')';
            }
			$database->setQuery($sql);
			$database->Query();
		}
	}
}

function sm2emailmarketingMailingUnsubscribe($id, $email, $lists) {
	global $database, $my;

//    if ($id<0) {
//        $sql = 'SELECT subscriberid AS id FROM #__emktg_subscriber WHERE email LIKE '.$database->Quote($email);
//    } else {
//        $sql = 'SELECT u.id'
//            .' FROM #__users u INNER JOIN #__emktg_user eu ON (u.id=eu.id) WHERE eu.id='.(int)$my->id;
//    }
//	$database->setQuery($sql);
//	$id = $database->loadResult();
//
//    if (empty($my->id)) $id = -$id;

	if($lists == 0) { //remove from lists
        if ($id < 0) {
            $sql = 'DELETE FROM #__emktg_list_subscriber WHERE subscriberid = '.(int)$id;
        } else {
            $sql = 'DELETE FROM #__emktg_list_user WHERE id = '.(int)$id;
        }
		$database->setQuery($sql);
		$database->Query();
	} else {
		foreach($lists as $list) {
            if ($id < 0) {
                $sql = 'DELETE FROM #__emktg_list_subscriber WHERE listid = '.(int)$list.' AND subscriberid = '.(int)$id;
            } else {
                $sql = 'DELETE FROM #__emktg_list_user WHERE listid = '.(int)$list.' AND id = '.(int)$id;
            }
			$database->setQuery($sql);
			$database->Query();
		}
	}
    if ($id < 0) {
        $sql = 'SELECT COUNT(*) FROM #__emktg_list_subscriber WHERE subscriberid = '.(int)$id;
    } else {
        $sql = 'SELECT COUNT(*) FROM #__emktg_list_user WHERE id = '.(int)$id;
    }
	$database->setQuery($sql);
	$mailinglistcount = $database->LoadResult();

	if ($mailinglistcount<1) {
		//mark them as unsubscribed if they no longer belong to any mailing lists
        if ($id < 0) {
            $id = abs($id);
            $sql = 'UPDATE #__emktg_subscriber SET unsubscribe_date=NOW(), unsubscribe_reason=1 WHERE subscriberid = '.(int)$id;
            $msgSQL = 'select name, email, 1 as unsubscribe_reason from #__emktg_subscriber where subscriberid='.(int)$id;
        } else {
            $sql = 'UPDATE #__emktg_user SET unsubscribe_date=NOW(), unsubscribe_reason=1 WHERE id = '.(int)$id;
            $msgSQL = 'select u.name, u.email, 1 as unsubscribe_reason from #__users u inner join #__emktg_user s on (s.id=u.id) where u.id='.(int)$id;
        }
		$database->setQuery($sql);
		$removed = $database->Query();
		if($removed) {
			sm2emailmarketingMessage(_EMKTG_UNSUBSCRIBE_SUCCESS, 'success');
            sm2emAdminUnsubscribeEmailFromQuery($msgSQL);
		} else {
			sm2emailmarketingMessage(_EMKTG_UNSUBSCRIBE_ERRORREMOVING);
		}
	}
	else {
		sm2emailmarketingMessage(_EMKTG_UNSUBSCRIBE_MAILINGLIST, 'success');
	}
} // sm2emailmarketingMailingUnsubscribe()


function sm2emailmarketingImage(){
	global $database, $mosConfig_absolute_path;

	$id = mosGetParam($_GET, 'id', 0);
	if (!empty($id)) {
		$database->setQuery('SELECT messageid FROM #__emktg_stats_message WHERE id='.(int)$id);
		$messageid = $database->loadResult();
		// update the database
		$database->setQuery('UPDATE #__emktg_stats_message SET `read`=1 WHERE ID='.(int)$id);
		$database->query();
		// determine how many times this has been read
		// note did this because we cannot be sure they wont read the message more than once
		// and probably should not have stored the overall read counter in the overall table
		// but instead just doing this sum when lookin at the stats
		$database->setQuery('SELECT SUM(`read`) FROM #__emktg_stats_message WHERE messageid='.(int)$messageid);
		$read = $database->loadResult();
		// update the overall read counter
		$database->setQuery('UPDATE #__emktg_stats_overall SET `html_read`='.(int)$read.' WHERE messageid='.(int)$messageid);
		$database->query();
	}

	// send the image
	ob_end_clean();
	$filename = $mosConfig_absolute_path . '/images/blank.png';
	$handle = fopen($filename, 'r');
	$contents = fread($handle, filesize($filename));
	fclose($handle);
	header('Content-type: image/png');
	echo $contents;
	exit;
}

function sm2emShowArchiveList($option) {
    global $database, $my, $Itemid, $mainframe;

    // get the parameters for this component to determine how to display this
    if (defined('_JLEGACY')) {
        $menu   =& JSite::getMenu();
        $item   = $menu->getActive();
        if($item)
            $params =& $menu->getParams($item->id);
        else
            $params =& $menu->getParams(null);
    } else {
        $item = $mainframe->get( 'menu' );
        $params = new mosParameters( $item->params );
    }

    // determine what the user can see
    $listMessages = array();
    $sentMessages = array();
    $messages = array();

    $lists = getAvailableLists();

    $database->setQuery( 'SELECT DISTINCT m.messageid, m.subject, m.send_date'
        .', mp.plugin_data'
        .' FROM #__emktg_message m'
        .' INNER JOIN #__emktg_message_plugin mp'
            .' USING (messageid)'
        .' INNER JOIN #__emktg_plugin p'
            .' USING (pluginid)'
        .' WHERE (m.send_date!=0)'
        .' AND (p.filename='.$database->Quote( 'list.plugin.php' ).')'
        .' AND (p.enabled=1)'
        .' ORDER BY m.send_date DESC' );
    $listMessages = $database->loadObjectList();


    // get the list of messages for the user
    if ($my->id) {
        // user is logged in so show the list of messages that the user received
        $database->setQuery( 'SELECT DISTINCT m.messageid, m.subject, m.send_date'
            .' FROM #__emktg_message m'
            .' INNER JOIN #__emktg_stats_message s'
                .' ON (m.messageid=s.messageid)'
            .' WHERE (s.userid='.(int)$my->id.')'
            .' AND (s.send_date!=0) AND (s.status=1)'
            .' ORDER BY m.send_date DESC' );
        $sentMessages = $database->loadObjectList();
    }

    // process all of these messages and make sure they are in order
    $foundMessages = array();

    while (count($listMessages) || count($sentMessages)) {
        $type = 0;
        if (!count($listMessages)) {
            $type = 2;
        } else if (!count($sentMessages)) {
            $type = 1;
        } else if ($listMessages[0]->send_date > $sentMessages[0]->send_date) {
            $type = 1;
        } else {
            $type = 2;
        }

        if ($type==1) {
            // process the list message
            $message = array_shift($listMessages);
            $selectedLists = unserialize($message->plugin_data);
            if (!is_array($selectedLists)) $selectedLists = array();
            $matches = array_intersect($selectedLists, $lists);
            if (!count($matches)) continue;

        } else if ($type==2) {
            // process the sent message
            $message = array_shift($sentMessages);
        }

        if (in_array($message->messageid, $foundMessages)) continue;

        $foundMessages[] = $message->messageid;

        $message->link = 'index.php?option='.$option
            .'&task=showarchivemessage'
            .'&id='.$message->messageid
            .'&Itemid='.$Itemid;
        if (function_exists('sefRelToAbs') && !defined('_JLEGACY')) {
            $message->link = sefRelToAbs($message->link);
        }
        $message->send_date_display = mosFormatDate($message->send_date, _EMKTG_MESSAGE_SENDDATE_FORMAT);

        $messages[] = $message;
    }

    // load the language elements
    $lang = sm2emailmarketingLanguage();

    // call the object to display the list
    $tmpl = sm2emailmarketingPatTemplate('message.tpl', $option);
    $tmpl->addVar('pagetitle', 'pagetitle', $item->name);

    if (count($messages)) {
        $tmpl->addObject('list', $lang, 'LANG');
        $tmpl->addObject('list', $params->toObject(), 'PARAM_');
        $tmpl->addObject('rows', $messages);
        $tmpl->displayParsedTemplate('list');
    } else {
        $tmpl->addObject('listempty', $lang, 'LANG');
        $tmpl->addObject('listempty', $params->toObject(), 'PARAM_');
        $tmpl->displayParsedTemplate('listempty');
    }

} // sm2emShowArchiveList()

function sm2emShowMessageArchive($option) {
    global $database, $Itemid, $mainframe, $my;
    global $mosConfig_fromname, $mosConfig_mailfrom, $mosConfig_absolute_path;
    global $sm2emailmarketingConfig, $mosConfig_live_site, $mosConfig_secret;

    $adminPath = $mosConfig_absolute_path.'/administrator/components/'.$option;

    $id = (int) mosGetParam($_GET, 'id', 0);
    if (empty($id)) {
        $url = 'index.php?option='.$option.'&task=showarchivelist&Itemid='.$Itemid;
        if (function_exists('sefRelToAbs') && !defined('_JLEGACY')) {
            $url = sefRelToAbs($url);
        }
        mosRedirect($url);
    }
    $action = (int) mosGetParam($_GET, 'action', 0);
    $confirm = mosGetParam($_GET, 'confirm', null);



    // get the parameters for this component to determine how to display this
    if (defined('_JLEGACY')) {
        $menu   =& JSite::getMenu();
        $item   = $menu->getActive();
        if($item)
            $params =& $menu->getParams($item->id);
        else
            $params =& $menu->getParams(null);
    } else {
        $item = $mainframe->get( 'menu' );
        $params = new mosParameters( $item->params );
    }

    $params->def( 'pageclass_sfx', '' );
    $params->def( 'back_button', $mainframe->getCfg( 'back_button' ) );

    // create an instance of the table class
    $row = new sm2emailmarketingMessage();

    // Load the row from the db table
    $row->load($id);

    // determine if we are allowed to continue
    $allowed = false;
    $confirmURL = '';
    if ($confirm!==null) {
        // check the ident to see if it is valid
        $forwardid = (int) mosGetParam($_GET, 'forwardid', 0);

        if (empty($forwardid)) {
            $validate = md5($mosConfig_secret.$id);
            $confirmURL = '&confirm='.$confirm;
        } else {
            $validate = md5($id.$mosConfig_secret.$forwardid);
            $confirmURL = '&forwardid='.$forwardid.'&confirm='.$confirm;
        }

        // not used yet so display not auth
        if ($validate==$confirm)
            $allowed = true;
    } else {
        // find the lists available to the user
        $lists = getAvailableLists();

        // get the details for the message
        $database->setQuery('SELECT mp.plugin_data'
            .' FROM #__emktg_message_plugin mp'
            .' INNER JOIN #__emktg_plugin p'
                .' USING (pluginid)'
            .' WHERE (mp.messageid='.(int)$id.')'
            .' AND (p.filename='.$database->Quote( 'list.plugin.php' ).')'
            .' AND (p.enabled=1)');
        $pluginData = $database->loadResultArray();
        foreach ($pluginData as $data) {
            $selectedLists = unserialize($data);
            if (!is_array($selectedLists)) $selectedLists = array();
            $matches = array_intersect($selectedLists, $lists);
            if (!count($matches)) continue;
            $allowed = true;
        }

        if (!$allowed && $my->id) {
            // user is logged in
            // check to see if they received this message
            $database->setQuery('SELECT COUNT(*)'
                .' FROM #__emktg_stats_message'
                .' WHERE (messageid='.(int)$id.')'
                .' AND (userid='.(int)$my->id.')');
            $count = $database->loadResult();
            if ($count) $allowed=true;
        }
    }

    if (!$allowed) {
        mosNotAuth();
        return;
    }

    if ($action==0) {
        $row->send_date_display = mosFormatDate($row->send_date, _EMKTG_MESSAGE_SENDDATE_FORMAT);

        // load the language elements
        $lang = sm2emailmarketingLanguage();

        // call the object to display the list
        $tmpl = sm2emailmarketingPatTemplate('message.tpl', $option);
        $tmpl->addVar('pagetitle', 'pagetitle', $item->name);
        $tmpl->addVar('archive', 'confirmurl', $confirmURL);
        $tmpl->addObject('archive', $lang, 'LANG');
        $tmpl->addObject('archive', $row);
        $tmpl->addObject('archive', $params->toObject(), 'PARAM_');
        $tmpl->displayParsedTemplate('archive');

    } else {

        //build message
        $row->replaceUserInfo('[NAME]', '[EMAIL]', null);
        $row->replaceTags(true);

        if (empty($row->fromname)) {
            $row->fromname = $sm2emailmarketingConfig->get('fromname', $mosConfig_fromname);
        }
        if (empty($row->fromemail)) {
            $row->fromemail = $sm2emailmarketingConfig->get('fromemail', $mosConfig_mailfrom);
        }
        if (empty($row->bounceemail)) {
            $row->bounceemail = $sm2emailmarketingConfig->get('bounceemail', $mosConfig_mailfrom);
        }
        if ($row->send_date==0) {
            $row->send_date = '';
        }

        // get the plugins to process
        $database->setQuery('SELECT * FROM #__emktg_plugin WHERE enabled=1 ORDER BY ordering');
        $plugins = $database->loadObjectList();

        // process the plugins
        foreach ($plugins as $plugin) {
            // load the plugin
            if (!file_exists($adminPath.'/plugins/'.$plugin->filename)) continue;
            require_once($adminPath.'/plugins/'.$plugin->filename);
            $class = $plugin->classname;
            $obj = new $class();
            // process the send of the plugin
            if (method_exists($obj, 'processMessage')) {
                $obj->processMessage($id, $plugin->pluginid, $option, $row, 0);
            }
        } // foreach()

        // load the language elements
        $lang = sm2emailmarketingLanguage();

        if (!is_array($row->attachments)) $row->attachments = explode(',', $row->attachments);
        $attachments = array();
        foreach ($row->attachments as $index=>$file) {
            if (!is_file($file)) continue;
            if (substr($file, 0, strlen($mosConfig_absolute_path)) != $mosConfig_absolute_path) continue;

            $attachments[] = '<a href="'
                .str_replace($mosConfig_absolute_path, $mosConfig_live_site, $file)
                .'">'.basename($file).'</a>';
        }
        if (count($attachments)) {
            $attachments = implode('<br />', $attachments);

            $row->message_htmlDisplay = $row->message_html
                .'<br style="clear: both;" /><br /><hr />'
                .'<strong>Attachments:</strong><br />'.$attachments;
            $row->message_textDisplay = nl2br($row->message_text
                .'<hr /><strong>Attachments:</strong><br />'.$attachments);
        } else {
            $row->message_htmlDisplay = $row->message_html;
            $row->message_textDisplay = $row->message_text;
        }

        sm2emailmarketing_addAbsolutePath($row->message_htmlDisplay);

        $out = $row->message_htmlDisplay;
        $outTest = strtolower($out);

        // see if we can somehow add in the BASE tag
        if (strpos($outTest, '</head>')!==false) {
            // add the base to the head
            $out = preg_replace('/(<\/head>)/i','<base target="_blank" />$1', $out);
        } else if (strpos($outTest, '<html')!==false) {
            $out = preg_replace('/(<html[^>]*>)/iu', '$1<head><base target="_blank" /></head>', $out);
        } else {
            $out = '<html><head><base target="_blank" /></head><body>'.$out.'</body></html>';
        }

        echo $out;
    }


} // sm2emShowMessageArchive()


/**
 * Function to display the Forward page.
 * Validates the confirmation code
 */
function sm2emForward($option) {
    global $database, $Itemid, $mainframe, $mosConfig_secret, $sm2emailmarketingConfig;

    // check to see if forwarding is enabled
    if ((int)$sm2emailmarketingConfig->get('forward', 0)==0) {
        mosNotAuth();
        return;
    }

    // get the parameters for this component to determine how to display this
    if (defined('_JLEGACY')) {
        $menu   =& JSite::getMenu();
        $item   = $menu->getActive();
        if($item)
            $params =& $menu->getParams($item->id);
        else {
            $params =& $menu->getParams(null);
            $item = (object)array('name'=>_EMKTG_FORWARD);
        }
    } else {
        $item = $mainframe->get( 'menu' );
        $params = new mosParameters( $item->params );
    }

    // determine if the details entered are correct
    $messageid = (int)mosGetParam($_GET, 'id', 0);
    $subscriberid = (int)mosGetParam($_GET, 'subscriberid', 0);
    $confirm = mosGetParam($_GET, 'confirm', '');

    // validate the confirm
    $validation = md5($mosConfig_secret.$messageid.$subscriberid);

    $template = ($validation==$confirm) ? 'forward' : 'forwarderror';

    $forwardDays = (int)$sm2emailmarketingConfig->get('forward_days', 30);

    if ($forwardDays) {
        $send_date = date('Y-m-d H:i:s',
            time() - ((int)$sm2emailmarketingConfig->get('forward_days', 30) * 24 * 60 * 60)
        );
    } else {
        $send_date = date('Y-m-d H:i:s', mktime(0,0,0,1,1,2000));
    }

    // lookup the information
    if ($subscriberid > 0) {
        $database->setQuery('SELECT m.subject, u.name, u.email, sm.html, p.classname, '
            .'CASE WHEN m.send_date > '.$database->Quote($send_date).' THEN 1 ELSE 0 END AS forward_date '
            .'FROM #__emktg_stats_message sm '
            .'INNER JOIN #__emktg_plugin p ON (sm.pluginid=p.pluginid) '
            .'INNER JOIN #__emktg_message m ON (sm.messageid=m.messageid) '
            .'INNER JOIN #__emktg_user eu ON (sm.userid=eu.id) '
            .'INNER JOIN #__users u ON (eu.id=u.id) '
            .'WHERE sm.messageid='.$messageid
            .' AND sm.userid='.$subscriberid
            .' AND sm.send_date!=0'
            .' AND m.send_date!=0'
            .' AND eu.unsubscribe_date=0'
            .' AND eu.confirmed=1'
            .' AND u.block=0');
    } else {
        $database->setQuery('SELECT m.subject, s.name, s.email, sm.html, p.classname, '
            .'CASE WHEN m.send_date > '.$database->Quote($send_date).' THEN 1 ELSE 0 END AS forward_date '
            .'FROM #__emktg_stats_message sm '
            .'INNER JOIN #__emktg_plugin p ON (sm.pluginid=p.pluginid) '
            .'INNER JOIN #__emktg_message m ON (sm.messageid=m.messageid) '
            .'INNER JOIN #__emktg_subscriber s ON (sm.userid=-s.subscriberid) '
            .'WHERE sm.messageid='.$messageid
            .' AND sm.userid='.$subscriberid
            .' AND sm.send_date!=0'
            .' AND m.send_date!=0'
            .' AND s.unsubscribe_date=0'
            .' AND s.confirmed=1');
    }

    $row = null;
    $contentHtml = 1;
    $receiveHtml = false;
    if (!$database->loadObject($row)) {
        $template = 'forwarderror';
    } else {
        // determine the format of the message to be sent
        if ($subscriberid < 0 && $row->classname=='sm2emailmarketing_plugin_list')
            $canBeLink = true;
        $receiveHtml = $row->html;
        if (!(int)$row->forward_date)
            $template = 'forwardexpired';
    }


    $msg = $sm2emailmarketingConfig->get('forward_msg', _EMKTG_CONFIGURATION_FORWARD_MSG_DEFAULT);
    if (strpos($msg, '[ARCHIVE_URL]')==false && strpos($msg, '[CONTENT]')==false) {
        $contentHtml = 2;
    } else if (strpos($msg, '[ARCHIVE_URL]')) {
        $contentHtml = 0;
    }

    switch ($contentHtml) {
        case 0:
            $contentHtml = _EMKTG_FORWARD_MESSAGE_CONTENT_LINK;
            break;
        case 1:
            $contentHtml = _EMKTG_FORWARD_MESSAGE_CONTENT_MESSAGE;
            break;
        case 2:
        default:
            $contentHtml = _EMKTG_FORWARD_MESSAGE_CONTENT_ATTACHMENT;
            break;
    }

    // load the language elements
    $lang = sm2emailmarketingLanguage();

    // call the object to display the list
    $tmpl = sm2emailmarketingPatTemplate('message.tpl', $option);
    $tmpl->addVar('pagetitle', 'pagetitle', $item->name);

    $tmpl->addObject($template, $lang, 'LANG');
    $tmpl->addVar($template, 'messageid', $messageid);
    $tmpl->addVar($template, 'subscriberid', $subscriberid);
    $tmpl->addVar($template, 'confirm', md5($messageid.$subscriberid.$mosConfig_secret));
    $tmpl->addVar($template, 'receivehtml', ($receiveHtml ? _EMKTG_FORWARD_MESSAGE_FORMAT_HTML : _EMKTG_FORWARD_MESSAGE_FORMAT_TEXT));
    $tmpl->addVar($template, 'messagecontent', $contentHtml);
    $tmpl->addObject($template, $row);
    $tmpl->displayParsedTemplate($template);

} // sm2emForward()


/**
 * Function to send the forward email
 * validates the confirmation code and the details to be sent
 */
function sm2emSendForward($option) {
    global $database, $Itemid, $mainframe, $mosConfig_secret, $sm2emailmarketingConfig;
    global $mosConfig_absolute_path, $mosConfig_live_site;

    // check to see if forwarding is enabled
    if ((int)$sm2emailmarketingConfig->get('forward', 0)==0) {
        mosNotAuth();
        return;
    }

    // get the parameters for this component to determine how to display this
    if (defined('_JLEGACY')) {
        $menu   =& JSite::getMenu();
        $item   = $menu->getActive();
        if($item)
            $params =& $menu->getParams($item->id);
        else {
            $params =& $menu->getParams(null);
            $item = (object)array('name'=>_EMKTG_FORWARD);
        }
    } else {
        $item = $mainframe->get( 'menu' );
        $params = new mosParameters( $item->params );
    }

    // determine if the details entered are correct
    $messageid = (int)mosGetParam($_GET, 'id', 0);
    $subscriberid = (int)mosGetParam($_GET, 'subscriberid', 0);
    $confirm = mosGetParam($_GET, 'confirm', '');

    // validate the confirm
    $validation = md5($messageid.$subscriberid.$mosConfig_secret);
    if ($validation!=$confirm) {
        sm2emSendForwardError(_EMKTG_FORWARD_UNKNOWN_ERROR, $option, $menu);
        return;
    }

    // get the post data
    $recipientName = trim(mosGetParam($_POST, 'name', ''));
    $recipientEmail = trim(mosGetParam($_POST, 'email', ''));
    $recipientEmail = explode(',',$recipientEmail);
    $recipientEmail = $recipientEmail[0];
    $recipientMessage = trim(mosGetParam($_POST, 'note', ''));

    // validate the post data
    $postErrors = array();
    if ($recipientName=='')
        $postErrors[] = _EMKTG_ARCHIVE_RECIPIENT_NAME;
    if ($recipientEmail=='')
        $postErrors[] = _EMKTG_ARCHIVE_RECIPIENT_EMAIL;
    if ($recipientMessage=='')
        $postErrors[] = _EMKTG_FORWARD_PERSONAL_MESSAGE;
    if (count($postErrors)) {
        sm2emSendForwardError(_EMKTG_FORWARD_JS_ERROR
            .'<ul><li>'.implode('</li><li>', $postErrors).'</li></ul>',
            $option, $menu);
        return;
    }
    unset($postErrors);

    // validate the message has not already been sent to this subscriber
    $database->setQuery('SELECT COUNT(*) FROM #__emktg_stats_message'
        .' WHERE messageid='.$messageid
        .' AND LOWER(email)='.$database->Quote(strtolower($recipientEmail)));
    $count = $database->loadResult();

    if ($count) {
        sm2emSendForwardError(_EMKTG_FORWARD_DUPLICATE_ERROR, $option, $menu);
        return;
    }
    unset($count);

    // get the details of the sender
    $use_html = 0;
    if ($subscriberid<0) {
        $sender = new sm2emailmarketingSubscriber();
        $sender->load(-$subscriberid);
        $use_html = $sender->receive_html;
    } else {
        $sender = new mosUser($database);
        $sender->load($subscriberid);

        $temp = new sm2emailmarketingUser();
        $temp->load($subscriberid);
        $use_html = $temp->receive_html;
        unset($temp);
    }

    $path = $sm2emailmarketingConfig->get('attachment_path', $mosConfig_absolute_path.'/images/stories/');

    // determine what to set the memory limit to - if at all
    $currentMemoryLimit = (int)ini_get('memory_limit');
    $memoryLimit = (int)$sm2emailmarketingConfig->get('process_memory', 0);
    if ($memoryLimit) {
        if ($memoryLimit < $currentMemoryLimit) $memoryLimit += $currentMemoryLimit;
        ini_set('memory_limit', $memoryLimit.'M');
    }
    
    define('_SM2EM_FORWARD', 1);

    // get the message
    $row = new sm2emailmarketingMessage();
    $row->load($messageid);
    $row->fromname = $sender->name;
    $row->fromemail = $sender->email;
    $row->bounceemail = $sender->email;

    // get the forward message
    $forwardSubject = $sm2emailmarketingConfig->get('forward_subject', _EMKTG_CONFIGURATION_FORWARD_SUBJECT_DEFAULT);
    $forwardMessage = $sm2emailmarketingConfig->get('forward_msg', _EMKTG_CONFIGURATION_FORWARD_MSG_DEFAULT);

    // process the subject
    $forwardSubject = str_replace('[FORWARD_NAME]', $recipientName, $forwardSubject);
    $forwardSubject = str_replace('[SUBJECT]', $row->subject, $forwardSubject);

    //use Joomla! class to send mail
    $mail = mosCreateMail($sender->email, $sender->name, $forwardSubject, '');
    // identify that we are sending and what the messageid is
    $mail->addCustomHeader('X-Mailer: SM2 Email Marketing');
    $mail->addCustomHeader('X-SM2MessageID: '.$row->messageid);
    $mail->addCustomHeader('X-SM2Recipient: '.$recipientEmail);
    // stop auto responders apparently
    $mail->addCustomHeader('Precedence: bulk');

    $mail->AddAddress($recipientEmail, $recipientName);
    $mail->Subject = $forwardSubject;

    // prepare the search for the message
    $search = array(
        '[FORWARD_NAME]',
        '[FORWARD_EMAIL]',
        '[FROM_NAME]',
        '[FROM_EMAIL]',
        '[FROM]',
        '[NOTE]',
        '[SUBJECT]',
        '[ARCHIVE_URL]',
        '[CONTENT]'
    );
    $replace = array(
        $recipientName,
        $recipientEmail,
        $sender->name,
        $sender->email,
        $sender->name.' ['.$sender->email.']',
        $recipientMessage,
        $row->subject
    );

    // determine what the archive url will be
    $includeArchiveUrl = false;
    if (strpos($forwardMessage, '[ARCHIVE_URL]')) {
        $includeArchiveUrl = true;

        $archiveURL = '';
        $itemid = $row->_getItemId();

        $archiveURL = 'index.php?option=com_sm2emailmarketing'
            .'&task=showarchivemessage'
            .'&id='.$messageid
            .'&forwardid='.$subscriberid
            .'&confirm='.md5($messageid.$mosConfig_secret.$subscriberid)
            .$itemid;
        if (function_exists('sefRelToAbs') && !defined('_JLEGACY')) {
            $archiveURL = sefRelToAbs($archiveURL);
        } else {
            $archiveURL = $mosConfig_live_site.'/'.$archiveURL;
        }

        $replace[] = $archiveURL;
        unset($archiveURL);
    } else {
        $replace[] = '';
    }

    // determine what the content will be
    $contentType = $includeArchiveUrl ? 0 : 2;
    $hasContentTag = (bool)strpos($forwardMessage, '[CONTENT]');
    if ($hasContentTag || !$includeArchiveUrl) {
        // need to include the content in some fashion
        //build message
        $row->replaceTags();

        // get the plugins to process
        $database->setQuery('SELECT * FROM #__emktg_plugin WHERE enabled=1 ORDER BY ordering');
        $plugins = $database->loadObjectList();

        // process the plugins
        foreach ($plugins as $plugin) {
            // load the plugin
            if (!file_exists($mosConfig_absolute_path.'/administrator/components/'.$option.'/plugins/'.$plugin->filename)) continue;
            require_once($mosConfig_absolute_path.'/administrator/components/'.$option.'/plugins/'.$plugin->filename);
            $class = $plugin->classname;
            $obj = new $class();
            // process the send of the plugin
            if (method_exists($obj, 'processMessage')) {
                $obj->processMessage($messageid, $plugin->pluginid, $option, $row, 0);
            }
        } // foreach()

        //personalise the message
        $row->replaceUserInfo($sender->name,$sender->email); //message is all set for sending
        sm2emailmarketing_addAbsolutePath($row->message_html);

        foreach ($row->attachments as $attachment) {
            $mail->AddAttachment($attachment, basename($attachment));
        }
        foreach ($row->embeddedImages as $embed) {
            $mail->AddEmbeddedImage($embed->image, $embed->cid, $embed->name, $embed->encoding, $embed->type);
        }

        if (!$hasContentTag) {
            // attach the content
            if ($use_html) { //html message to be sent
                $mail->AddStringAttachment($row->message_html,
                    'message.dat',
                    'quoted-printable',
                    'text/html');
            } else {
                $mail->AddStringAttachment($row->message_html,
                    'message.dat',
                    'quoted-printable',
                    'text/plain');
            }
            $replace[] = '';
        } else {
            if ($use_html) {
                $replace[] = $row->message_html;
            } else {
                $replace[] = $row->message_text;
            }
        }
    } else {
        $replace[] = '';
    }

    // process the message
    $forwardMessage = str_replace($search, $replace, $forwardMessage);

    //get the correct format of message
    $mail->IsHTML((bool)$use_html);
    $mail->Body = $forwardMessage;

    $wordWrap = $sm2emailmarketingConfig->get('word_wrap', 0);
    if ($wordWrap) {
        // word wrap both bodies
        $mail->Body = $mail->WrapText($mail->Body, $wordWrap);
        if (!empty($mail->AltBody))
             $mail->AltBody = $mail->WrapText($mail->AltBody, $wordWrap);
    }

    //send message
    $sendMailOk = $mail->Send();

    if (!$sendMailOk) {
        sm2emSendForwardError(_EMKTG_FORWARD_SEND_ERROR, $option, $menu);
        return;
    }

    // load the language elements
    $lang = sm2emailmarketingLanguage();

    // call the object to display the list
    $tmpl = sm2emailmarketingPatTemplate('message.tpl', $option);
    $tmpl->addVar('pagetitle', 'pagetitle', $item->name);

    $tmpl->addObject('sendforward', $lang, 'LANG');
    $tmpl->addVar('sendforward', 'subject', $forwardSubject);
    $tmpl->addVar('sendforward', 'fromname', $sender->name);
    $tmpl->addVar('sendforward', 'fromemail', $sender->email);
    $tmpl->addVar('sendforward', 'name', $recipientName);
    $tmpl->addVar('sendforward', 'email', $recipientEmail);
    $tmpl->addVar('sendforward', 'note', $recipientMessage);
    $tmpl->displayParsedTemplate('sendforward');

} // sm2emSendForward()


function sm2emSendForwardError($errorMsg, $option, $menu) {
    // load the language elements
    $lang = sm2emailmarketingLanguage();

    // call the object to display the list
    $tmpl = sm2emailmarketingPatTemplate('message.tpl', $option);
    $tmpl->addVar('pagetitle', 'pagetitle', $menu->name);

    $tmpl->addObject('sendforwarderror', $lang, 'LANG');
    $tmpl->addVar('sendforwarderror', 'error', $errorMsg);
    $tmpl->displayParsedTemplate('sendforwarderror');
} // sm2emSendForwardError()
?>
Back to Top