| 12
 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
 | <?php
/*****************************************************************************
 *   Lottery (/inc/plugins/myplaza/lottery.php)
 *     - MyPlaza for MyBB 1.2
 *    By ZiNgA BuRgA, 2007-2008
 * 
 * Adds a lottery system!
 *****************************************************************************/
if(!defined("IN_MYBB"))
	die("This file cannot be accessed directly.");
function lottery_lang()
{
	global $mybb, $lang;
	switch($mybb->settings['bblanguage'])
	{
		default:
			$lang->invalid_numbers = 'Invalid numbers supplied.';
	}
}
function lottery_lang_admin()
{
	global $mybb, $lang;
	switch($mybb->settings['bblanguage'])
	{
		default:
			$lang->lottery_name = 'Lottery';
			$lang->lottery_description = 'Adds a lottery system!';
			
			$lang->item_lottery_ticket_name = 'Lottery Ticket';
			$lang->item_lottery_ticket_desc = 'Gives a chance to win in the lottery.';
			
			$lang->setting_lottery_max_num = 'Maximum selectable number';
			$lang->setting_lottery_max_num_desc = 'This is the upper range for each number in the lottery.';
			
			$lang->setting_lottery_numbers = 'Number of numbers';
			$lang->setting_lottery_numbers_desc = 'This is the number of lottery numbers to select.';
			
			$lang->setting_lottery_secondaries = 'Number of secondary numbers';
			$lang->setting_lottery_secondaries_desc = 'This is the number of secondary lottery numbers to select.  Secondary numbers can have special purposes - ie act as supplimentaries.  Note that primary numbers are always checked first - ie 6 primary matches is considered "higher" than 5 primary plus 1 secondary.';
			
			$lang->setting_lottery_draw_frequency = 'Hours between each drawing';
			$lang->setting_lottery_draw_frequency_desc = 'How often (in hours) the lottery is run.';
			
			$lang->setting_lottery_winrate = 'Win Payouts Rate';
			$lang->setting_lottery_winrate_desc = 'All winning payouts are multiplied by this number.';
			
			$lang->setting_lottery_usepot = 'Use Lottery Pot';
			$lang->setting_lottery_usepot_desc = 'If yes, the cost of each ticket goes towards the pot of the lottery.';
			
			$lang->setting_lottery_allow_systems = 'Allow System Games';
			$lang->setting_lottery_allow_systems_desc = 'If yes, allows users to select more numbers than the maximum selectable numbers, at, perhaps, higher prices.';
			
			$lang->lottery_options = 'Lottery Options';
			$lang->lottery_tickets = 'Lottery Tickets';
			$lang->tickets_deleted = 'Tickets deleted.';
			$lang->tickets_username = 'Holder';
			$lang->tickets_numbers = 'Selected Numbers';
			$lang->tickets_date = 'Purchase Date';
			$lang->tickets_del = 'Del';
			
			$lang->numbers_pruned = 'Old lottery numbers pruned.';
			$lang->winnings_updated = 'Winning combinations updated.';
			
			$lang->lottery_winnings = 'Lottery Winnings';
			$lang->winning_num_primary = 'No. Pmy Matches';
			$lang->winning_num_secondary = 'No. 2\'ary Matches';
			$lang->winning_payout = 'Payout';
			$lang->winning_potrate = 'Pot Contribution';
			
			$lang->match_numbers_must_be_positive = 'You must enter positive values for the number of matching numbers';
			$lang->add_winning = 'Add Winning Combination';
			
			$lang->are_you_sure_delete = 'Are you sure you wish to delete this?';
			$lang->update = 'Update';
			$lang->add = 'Add';
			$lang->delete = 'Delete';
			
			
			$lang->lottery_options_main = 'What would you like to do?
			<ul>
			 <li><a href="%1$slaction=tickets">View Purchased Tickets</a></li>
			 <li><a href="%1$slaction=winnings">Modify Winning Combinations</a></li>
			 <li><a href="%1$slaction=systems">Modify System Game Combinations</a></li>
			 <li><a href="%1$slaction=settings">Modify Lottery Settings</a></li>
			 <li><a href="%2$s">Edit Lottery Ticket item</a></li>
			</ul>';
	}
}
function lottery_info()
{
	global $lang;
	return array(
		"website"		=> "http://myplaza.zingaburga.com",
		"author"		=> "ZiNgA BuRgA",
		"authorsite"	=> "http://zingaburga.com/",
		"version"		=> "1.0",
		"compatibility"	=> array(0.5)
	);
}
function lottery_activate()
{
	// stop people trying to activate this module as a MyBB plugin
	if(!defined("IN_MYPLAZA_ADMIN"))
		cperror('This is not a normal MyBB plugin!  Please upload this file to your /inc/plugins/myplaza directory.');
	
	// write tables
	db_create_table('plaza_lottery_tickets', array(
		'tid' => array('type' => 'int', 'unsigned' => true, 'not_null' => true, 'auto_increment' => true),
		'uid' => array('type' => 'int', 'size' => 5, 'unsigned' => true, 'not_null' => true, 'default' => 0),
		'numbers' => array('type' => 'varchar', 'size' => 150, 'not_null' => true, 'default' => ''),
		'dateline' => array('type' => 'bigint', 'size' => 30, 'not_null' => true, 'unsigned' => true, 'default' => 0)
	), array(
		array('type' => 'primary', 'fields' => 'tid'),
		array('type' => 'key', 'fields' => 'uid'),
		//array('type' => 'key', 'fields' => 'dateline')
	));
	
	db_create_table('plaza_lottery_numbers', array(
		'nid' => array('type' => 'int', 'unsigned' => true, 'not_null' => true, 'auto_increment' => true),
		'numbers' => array('type' => 'varchar', 'size' => 150, 'not_null' => true, 'default' => ''),
		'secondaries' => array('type' => 'varchar', 'size' => 150, 'not_null' => true, 'default' => ''),
		'dateline' => array('type' => 'bigint', 'size' => 30, 'not_null' => true, 'unsigned' => true, 'default' => 0)
	), array(
		array('type' => 'primary', 'fields' => 'nid'),
		array('type' => 'key', 'fields' => 'dateline')
	));
	
	db_create_table('plaza_lottery_winnings', array(
		'wid' => array('type' => 'smallint', 'unsigned' => true, 'not_null' => true, 'auto_increment' => true),
		'winamount' => array('type' => 'decimal', 'size' => '32,16', 'not_null' => true, 'default' => '0'),
		'potrate' => array('type' => 'float', 'size' => 8, 'not_null' => true, 'unsigned' => true, 'default' => '0'),
		'num_primary' => array('type' => 'smallint', 'size' => 5, 'not_null' => true, 'unsigned' => true, 'default' => 0),
		'num_secondary' => array('type' => 'smallint', 'size' => 5, 'not_null' => true, 'unsigned' => true, 'default' => 0)
	), array(
		array('type' => 'primary', 'fields' => 'wid')
	));
	
	// insert some default win combinations
	db_insert_rows('plaza_lottery_winnings', array(
		array(
			'winamount' => 1000000,
			'potrate' => 0.85,
			'num_primary' => 6,
			'num_secondary' => 0
		),
		array(
			'winamount' => 500000,
			'potrate' => 0.1,
			'num_primary' => 5,
			'num_secondary' => 1
		),
		array(
			'winamount' => 200000,
			'potrate' => 0.05,
			'num_primary' => 5,
			'num_secondary' => 0
		),
		array(
			'winamount' => 50000,
			'potrate' => 0,
			'num_primary' => 4,
			'num_secondary' => 2
		),
		array(
			'winamount' => 25000,
			'potrate' => 0,
			'num_primary' => 4,
			'num_secondary' => 1
		),
		array(
			'winamount' => 15000,
			'potrate' => 0,
			'num_primary' => 4,
			'num_secondary' => 0
		),
		array(
			'winamount' => 12000,
			'potrate' => 0,
			'num_primary' => 3,
			'num_secondary' => 2
		),
		array(
			'winamount' => 5000,
			'potrate' => 0,
			'num_primary' => 3,
			'num_secondary' => 1
		),
		array(
			'winamount' => 1000,
			'potrate' => 0,
			'num_primary' => 3,
			'num_secondary' => 0
		),
	));
	cache_update_winnings();
	
	db_create_table('plaza_lottery_systems', array(
		'num_selectable' => array('type' => 'smallint', 'not_null' => true, 'unsigned' => true, 'default' => '0'),
		'premiumrate' => array('type' => 'float', 'size' => 8, 'not_null' => true, 'unsigned' => true, 'default' => '0')
	), array(
		array('type' => 'primary', 'fields' => 'num_selectable')
	));
	
	// by default, allow up to system 20
	$systems = array();
	for($i=6; $i < 21; $i++)
		$systems[] = array('num_selectable' => $i, 'premiumrate' => combin($i, 6));
	
	db_insert_rows('plaza_lottery_systems', $systems);
	
	
	// add our items
	myplaza_add_item(array(
		"idname"		=> 'lottery_ticket',
		"cost"			=> 1,
		"htmlextra"		=> 'This item cannot be purchased from the plaza.'
	));
	
	// add settings
	add_settings(array(
		array(
			"name"			=> 'lottery_max_num',
			"optionscode"	=> 'text',
			"value"			=> 45,
		),
		array(
			"name"			=> 'lottery_numbers',
			"optionscode"	=> 'text',
			"value"			=> 6,
		),
		array(
			"name"			=> 'lottery_secondaries',
			"optionscode"	=> 'text',
			"value"			=> 2,
		),
		array(
			"name"			=> 'lottery_draw_frequency',
			"optionscode"	=> 'text',
			"value"			=> 72,
		),
		array(
			"name"			=> 'lottery_winrate',
			"optionscode"	=> 'text',
			"value"			=> 1,
		),
		array(
			"name"			=> 'lottery_usepot',
			"optionscode"	=> 'yesno',
			"value"			=> MY_NO,
		),
		array(
			"name"			=> 'lottery_allow_systems',
			"optionscode"	=> 'yesno',
			"value"			=> MY_YES,
		)
	));
	
	
	// insert templates
	$new_templates['plaza_lottery'] = '
{$plaza_header}
<table border="0" cellspacing="{$theme[\'borderwidth\']}" cellpadding="0">
	<tr>
	
<table border="0" cellspacing="{$theme[\'borderwidth\']}" cellpadding="{$theme[\'tablespace\']}" class="tborder">
	<tr><td class="thead" colspan="2"><strong>{$lang->lottery_new_game}</strong></td></tr>
	<tr>
		<td class="trow1" width="30%">
			<strong>{$lang->amount}:</strong>
		</td><td class="trow1" width="70%">
			<input type="text" class="textbox" name="amount" value="0" />
		</td>
	</tr>
	<tr>
		<td class="trow2" width="30%">
			<strong>{$lang->action}</strong>
		</td><td class="trow2" width="70%">
			<input type="radio" class="radio" name="bankaction" value="deposit" id="bank_deposit" checked="checked" /><label for="bank_deposit">{$lang->deposit}</label> {$depositfee}
			<br /><input type="radio" class="radio" name="bankaction" value="withdraw" id="bank_withdraw" /><label for="bank_withdraw">{$lang->withdraw}</label> {$withdrawfee}
		</td>
	</tr>
<form action="plaza.php" method="post" onsubmit="if(this.elements[4].value<=0){alert(\'{$lang->invalid_amount}\');return false;}">
	<input type="hidden" name="action" value="page" />
	<input type="hidden" name="p" value="bank" />
	<input type="hidden" name="process" value="yes" />
	<input type="hidden" name="postcode" value="{$mybb->post_code}" />
	<table border="0" cellspacing="{$theme[\'borderwidth\']}" cellpadding="{$theme[\'tablespace\']}" class="tborder">
		<tr><td class="thead" colspan="2"><img src="{$mybb->settings[\'bburl\']}/images/myplaza/bank.png" class="plazaitem" alt="" /><strong>{$lang->bank}</strong></td></tr>
		<tr>
			<td class="trow1" width="30%">
				<strong>{$lang->amount}:</strong>
			</td><td class="trow1" width="70%">
				<input type="text" class="textbox" name="amount" value="0" />
			</td>
		</tr>
		<tr>
			<td class="trow2" width="30%">
				<strong>{$lang->action}</strong>
			</td><td class="trow2" width="70%">
				<input type="radio" class="radio" name="bankaction" value="deposit" id="bank_deposit" checked="checked" /><label for="bank_deposit">{$lang->deposit}</label> {$depositfee}
				<br /><input type="radio" class="radio" name="bankaction" value="withdraw" id="bank_withdraw" /><label for="bank_withdraw">{$lang->withdraw}</label> {$withdrawfee}
			</td>
		</tr>
		<tr>
			<td class="trow1" width="30%">
				<strong>{$lang->info}</strong>
			</td><td class="trow1" width="70%">
				{$lang->money_on_hand} {$mymoney}<br />
				{$lang->money_in_bank} {$bankmoney}<br />
				{$lang->bank_interest_rate} {$mybb->settings[\'bank_interest_rate\']}%
				<span id="bank_message" style="font-weight: bold;"></span>
			</td>
		</tr>
		<tr><td class="tfoot" colspan="2" align="center">
		<input type="submit" class="button" value="{$lang->go}" />
		</td></tr>
	</table>
</form>
{$plaza_footer}
';
	
	global $cache;
	$cache->update('myplaza_lottery_info', array('lastrun' => REQUEST_TIME);
}
function lottery_deactivate()
{
	global $db, $cache;
	myplaza_remove_module_items();
	$db->delete_query(MY_TABLE_PREFIX.'settings', "name IN ('lottery_max_num', 'lottery_numbers', 'lottery_secondaries', 'lottery_draw_frequency', 'lottery_winrate', 'lottery_usepot', 'lottery_allow_systems')");
	my_rebuild_settings();
	
	db_drop_tables(array('plaza_lottery_tickets', 'plaza_lottery_numbers', 'plaza_lottery_winnings', 'plaza_lottery_systems'));
	
	
	delete_cache_items('myplaza_lottery_info');
}
function lottery_plugin()
{
	lottery_execute();
}
// calculates the mathematical combinations (same as nCr)
function combin($n, $r)
{
	return factorial($n) / (factorial($r) * factorial($n-$r));
}
// calculates $n!
function factorial($n)
{
	$i = $n;
	while(--$i)
		$n *= $i;
	return $n;
}
function lottery_run($item)
{
	if($item['idname'] != 'lottery_ticket') return false;
	
	global $mybb, $lang, $db, $buyRtnMsg, $buyLogMsg;
	
	if(!is_array($mybb->input['numbers']))
	{
		$buyRtnMsg = $lang->invalid_numbers;
		return false;
	}
	$numbers = array();
	foreach($mybb->input['numbers'] as $num => $val)
	{
		$num = intval($num);
		if($num < 1 || $num > intval($mybb->settings['lottery_max_num']))
		{
			$buyRtnMsg = $lang->invalid_numbers;
			return false;
		}
		
		$numbers[$num] = $num;
	}
	
	// default "system rate"
	$systemrate = 1;
	
	// if the user hasn't selected enough numbers, bail out
	if(count($numbers) < intval($mybb->settings['lottery_numbers']))
	{
		$buyRtnMsg = $lang->invalid_numbers;
		return false;
	}
	if(count($numbers) > intval($mybb->settings['lottery_numbers']))
	{
		// if the user has selected too many numbers, and system games aren't allowed, bail out
		if($mybb->settings['lottery_allow_systems'] == MY_NO)
		{
			$buyRtnMsg = $lang->invalid_numbers;
			return false;
		}
		// otherwise, check if we have a valid system
		$systemrate = $db->fetch_field($db->simple_select('plaza_lottery_systems', 'premiumrate', 'num_selectable='.count($numbers)), 'premiumrate');
		if($systemrate === null)
		{
			$buyRtnMsg = $lang->invalid_numbers;
			return false;
		}
		// check if user has enough money for the system game
		if($systemrate > 1)
		{
			$additional_cost = $item['cost'] * ($systemrate-1);
			if($mybb->user['money'] < $additional_cost && $additional_cost > 0)
			{
				$buyRtnMsg = $lang->insufficient_money;
				return false;
			}
			user_change_money($mybb->user, -$additional_cost);
		}
	}
	
	// add money to the pot (regardless of whether option is set or not)
	$add_pot = $item['cost'];
	if(isset($additional_cost)) $add_pot += $additional_cost;
	global $cache;
	$info = $cache->read('myplaza_lottery_info');
	if(!is_array($info)) $info = array();
	$info['pot'] += $add_pot;
	$cache->update('myplaza_lottery_info', $info);
	
	// all validated, add the ticket
	$db->insert_query(MY_TABLE_PREFIX.'plaza_lottery_tickets', array('uid' => $mybb->user['uid'], 'numbers' => implode(',',$numbers), 'dateline' => REQUEST_TIME));
	
	return true;
}
function lottery_execute()
{
	// this will generate the lottery numbers every period
	global $cache, $db;
	$info = $cache->read('myplaza_lottery_info');
	if(!is_array($info)) return;
	
	$timerange = intval($mybb->settings['lottery_draw_frequency'])*3600;
	if(REQUEST_TIME < $info['lastrun'] + $timerange) return;
	
	// okay, time to generate!
	// we'll generate all necessary numbers - however, we only need to check for the _single_ period _after_ the previous one
	$lottery_numbers = intval($mybb->settings['lottery_numbers']);
	$lottery_max_num = intval($mybb->settings['lottery_max_num']);
	$lottery_secondaries = intval($mybb->settings['lottery_secondaries']);
	
	// do we have a silly admin?
	if(($lottery_numbers + $lottery_secondaries) > $lottery_max_num) return;
	
	@ignore_user_abort(true);
	$number_inserts = array();
	for($t = $info['lastrun'] + $timerange; $t < REQUEST_TIME; $t+=$timerange)
	{
		$numbers = array();   $secondaries = array();
		for($i=0; $i<$lottery_numbers+$lottery_secondaries; $i++)
		{
			// force a unique number generation
			do {
				$n = mt_rand(1, $lottery_max_num);
			} while(isset($numbers[$n]) || isset($secondaries[$n]));
			if($i < $lottery_numbers)
				$numbers[$n] = $n;
			else
				$secondaries[$n] = $n;
		}
		
		// save the first set down
		if(!isset($numbers_check))
		{
			$numbers_check = $numbers;
			$secondaries_check = $secondaries;
		}
		$number_inserts[] = array('numbers' => implode(',',$numbers), 'secondaries' => implode(',',$secondaries), 'dateline' => $t);
	}
	db_shutdown_insert_rows('plaza_lottery_numbers', $number_inserts);
	
	$info['lastrun'] = $t;
	$pot_amount = $info['pot'];
	$info['pot'] = 0;
	$cache->update('myplaza_lottery_info', $info);
	
	// now we'll check the last draw
	$numbers = $numbers_check;
	$secondaries = $secondaries_check;
	unset($number_inserts);
	
	
	$winnings = $cache->read('myplaza_lottery_winnings');
	if(!is_array($winnings))
	{
		$winnings = cache_update_winnings();
	}
	// grab the lowest number of primaries (since most tickets will generally be a loss)
	$min_pmy = end($winnings);
	$min_pmy = $winnings['num_primary'];
	
	// loop through all the tickets
	$query = $db->simple_select(MY_TABLE_PREFIX.'plaza_lottery_tickets', '*');
	while($ticket = $db->fetch_array($query))
	{
		$selected_num = explode(',', $ticket['numbers']);
		$matches = lottery_calc_matches($selected_num, $numbers, $secondaries);
		// since most tickets will be a loss, we'll use this "optimization"
		if($matches['primary_matches'] < $min_pmy) continue;
		foreach($winnings as $winning)
		{
			if($matches['primary_matches'] >= $winning['num_primary'] && $matches['secondary_matches'] >= $winning['num_secondaries'])
			{
				user_change_money($ticket['uid'], $winning['winamount']);
				// calc pot amounts
				//send PM?
				// add to list of winners?
				break;
			}
		}
	}
	
	// so we've finished doing the payouts, clean up
	$db->delete_query(MY_TABLE_PREFIX.'plaza_lottery_tickets');
	@ignore_user_abort(false);
}
// sees how many matches exist
function lottery_calc_matches($selected_num, $primaries, $secondaries)
{
	$ret = array('primary_matches' => 0, 'secondary_matches' => 0);
	foreach($selected_num as $n)
	{
		if(isset($primaries[$n]))
			++$ret['primary_matches'];
		elseif(isset($secondaries[$n]))
			++$ret['secondary_matches'];
	}
	return $ret;
}
function cache_update_winnings($winnings = array())
{
	global $db, $cache;
	if(!is_array($winnings))
	{
		$query = $db->simple_select(MY_TABLE_PREFIX.'plaza_lottery_winnings', '*', '', array('order_by' => 'num_primary DESC, num_secondary DESC'));
		while($w = $db->fetch_array($query))
			$winnings[$w['wid']] = $w;
	}
	$cache->update('myplaza_lottery_winnings', $winnings);
	return $winnings;
}
function lottery_page()
{
	global $mybb, $templates;
	myplaza_standard_buy('lottery', "idname='lottery_ticket'");
	
	
	
	// get cur tickets
	// get prev numbers?
	// get pot?
	// get previous winners?
	// get payouts?
	
	// get system game info
	
	// generate number checkboxes
	
	return $templates->get('lottery_page');
}
function lottery_admin($process)
{
	global $mybb, $lang, $db;
	switch($mybb->input['laction'])
	{
		case 'tickets':
			if($process)
			{
				if(is_array($mybb->input['tickets']))
				{
					$tids = array();
					foreach($mybb->input['tickets'] as $tid => $delete)
					{
						if($delete != '1') continue;
						$tids[intval($tid)] = intval($tid);
					}
					$db->delete_query(MY_TABLE_PREFIX.'plaza_lottery_tickets', 'tid IN ('.implode(',',$tids).')');
				}
				myplaza_cpredirect('action=do_module&module=lottery&moduleaction=options', $lang->tickets_deleted);
			}
			else
			{
				$query = db_select(array(
					array('name' => 'plaza_lottery_tickets', 'alias' => 't'),
					array('name' => 'users', 'alias' => 'u', 'join' => 'left', 'on' => 't.uid=u.uid')
				), 't.*,u.username');
				
				cpheader_myplaza_module();
				starttable();
				tableheader($lang->lottery_tickets, "", 4);
				tablesubheader(array(
					$lang->tickets_username,
					$lang->tickets_numbers,
					$lang->tickets_date,
					$lang->tickets_del
				));
				
				makehiddencode('laction', 'tickets');
				while($ticket = $db->fetch_array($query))
				{
					$bgcolor = getaltbg();
					echo '<tr><td class="',$bgcolor,'" width="30%">',htmlspecialchars_uni($ticket['username']),'</td>
						<td class="',$bgcolor,'" width="40%">',$ticket['numbers'],'</td>
						<td class="',$bgcolor,'" width="30%">',date("jS M Y, G:i", $ticket['dateline']),'</td>
						<td class="',$bgcolor,'" width="1"><input type="checkbox" name="tickets[',$ticket['tid'],']" value="1" /></td></tr>';
				}
				endtable();
				
				cpfooter_myplaza_module();
			}
			
			break;
		case 'prunenos':
			if($process)
			{
				$days = intval($mybb->input['days']);
				$cutoff = REQUEST_TIME - ($days * 3600*24);
				
				$db->delete_query(MY_TABLE_PREFIX.'plaza_lottery_numbers', 'dateline < '.$cutoff);
				myplaza_cpredirect('action=do_module&module=lottery&moduleaction=options', $lang->numbers_pruned);
			}
			else
				die('Hacking attempt - well, not really, but who cares?');
			
			break;
		case 'winnings':
			if($process)
			{
				$wid = intval($mybb->input['wid']);
				switch($mybb->input['wlaction'])
				{
					case 'add':
					case 'edit':
						$update_array = array(
							'winamount' => round(floatval($mybb->input['winamount']), $mybb->settings['myplaza_money_decimals']),
							'potrate' => floatval($mybb->input['potrate']),
							'num_primary' => intval($mybb->input['num_primary']),
							'num_secondary' => intval($mybb->input['num_secondary'])
						);
						
						if($update_array['num_primary'] < 0 || $update_array['num_secondary'] < 0)
							cperror($lang->match_numbers_must_be_positive);
						
						if($mybb->input['wlaction'] == 'add')
							$db->insert_query(MY_TABLE_PREFIX.'plaza_lottery_winnings', $update_array);
						else
							$db->update_query(MY_TABLE_PREFIX.'plaza_lottery_winnings', $update_array, "wid=$wid");
						
						break;
					case 'del':
						$db->delete_query(MY_TABLE_PREFIX.'plaza_lottery_winnings', "wid=$wid");
						break;
					default:
						die('Hacking attempt - well, not really, but who cares?');
					
					cache_update_winnings();
					myplaza_cpredirect('action=do_module&module=lottery&moduleaction=options', $lang->winnings_updated);
				}
			}
			else
			{
				myplaza_cpheader();
				starttable();
				tableheader($lang->lottery_winnings, "", 5);
				tablesubheader(array($lang->winning_num_primary, $lang->winning_num_secondary, $lang->winning_payout, $lang->winning_potrate, ' '));
				
				$query = $db->simple_select(TABLE_PREFIX.'plaza_lottery_winnings', '*');
				while($winning = $db->fetch_array($query))
				{
					$bgcolor = getaltbg();
					echo '<tr>';
					startform('myplaza.php', '', 'do_module');
					makehiddencode("moduleaction", 'do_options');
					makehiddencode("module", 'lottery');
					makehiddencode("wlaction", 'edit');
					makehiddencode("wid", $winning['wid']);
					echo '
					<td class="'.$bgcolor.'" width="15%"><input type="text" name="num_primary" value="'.$winning['num_primary']).'" size="20" /></td>
					<td class="'.$bgcolor.'" width="15%"><input type="text" name="num_secondary" value="'.$winning['num_secondary']).'" size="20" /></td>
					<td class="'.$bgcolor.'" width="15%"><input type="text" name="winamount" value="'.$winning['winamount']).'" size="20" /></td>
					<td class="'.$bgcolor.'" width="15%"><input type="text" name="potrate" value="'.$winning['potrate']).'" size="20" /></td>
					<td class="'.$bgcolor.'" width="40%">';
					echo makebuttoncode("updatebutton", $lang->update);
					echo makebuttoncode("deletebutton", $lang->delete, 'button', 'if(confirm(\''.$lang->are_you_sure_delete.'\')) location.href = \'myplaza.php?'.SID.'&action=do_module&moduleaction=do_options&module=lottery&wlaction=del&wid='.$winning['wid'].'\';');
					echo '</td>';
					endform();
					echo '</tr>';
				}
				
				// add combination
				tablesubheader($lang->add_winning, '', 5);
				$bgcolor = getaltbg();
				echo '<tr>';
				startform('myplaza.php', '', 'do_module');
				makehiddencode("moduleaction", 'do_options');
				makehiddencode("module", 'lottery');
				makehiddencode("wlaction", 'add');
				echo '
					<td class="'.$bgcolor.'" width="15%"><input type="text" name="num_primary" value="0" size="20" /></td>
					<td class="'.$bgcolor.'" width="15%"><input type="text" name="num_secondary" value="0" size="20" /></td>
					<td class="'.$bgcolor.'" width="15%"><input type="text" name="winamount" value="0" size="20" /></td>
					<td class="'.$bgcolor.'" width="15%"><input type="text" name="potrate" value="0" size="20" /></td>
				<td class="'.$bgcolor.'" width="40%">';
				echo makebuttoncode("addbutton", $lang->add);
				echo '</td>';
				endform();
				echo '</tr>';
				
				
				endtable();
				
				myplaza_cpfooter();
			}
			
			break;
		case 'systems':
		
		
		case 'settings':
			if($process)
			{
				myplaza_process_settings(array('lottery_max_num', 'lottery_numbers', 'lottery_secondaries', 'lottery_draw_frequency', 'lottery_winrate', 'lottery_usepot', 'lottery_allow_systems'));
			}
			else
			{
				cpheader_myplaza_module();
				starttable();
				tableheader($lang->lottery_options, "", 2);
				myplaza_generate_settings_code(array('lottery_max_num', 'lottery_numbers', 'lottery_secondaries', 'lottery_draw_frequency', 'lottery_winrate', 'lottery_usepot', 'lottery_allow_systems'));
				endtable();
				
				cpfooter_myplaza_module();
			}
			
			break;
		default:
			
			$iid = $db->fetch_field($db->simple_select(MY_TABLE_PREFIX.'plaza_items', 'iid', "idname = 'lottery_ticket'"), 'iid');
			cpheader_myplaza_module();
			starttable();
			tableheader($lang->lottery_options, "", 2);
			makelabelcode(sprintf($lang->lottery_options_main, 'myplaza.php?'.SID.'&action=do_module&module=lottery&moduleaction=options&', 'myplaza.php?'.SID.'&action=edititem&iid='.$iid));
			endtable();
			cpfooter_myplaza_module();
	}
}
?>
 |