1
<?php
2
/**
3
 *   File functions:
4
 *   Warehouse - sell minerals and herbs, view history of transactions.
5
 *
6
 *   @name                 : warehouse.php
7
 *   @copyright            : (C) 2004,2005,2006 Vallheru Team based on Gamers-Fusion ver 2.5
8
 *   @author               : thindil <thindil@users.sourceforge.net>
9
 *   @author               : eyescream <tduda@users.sourceforge.net>
10
 *   @version              : 1.4
11
 *   @since                : 18.07.2007
12
 *
13
 */
14
15
// Published under GNU GPL 2 or later. See /install/README file for details.
16
// $Id$
17
18
/**
19
 * File uses selective Smarty caching.
20
 * The reason is that people tend to view the warehouse and compare prices with market, but they don't buy/sell as often.
21
 * Main page (view prices and amounts) and transactions history are cached.
22
 * Main page's $cache_id: 'Altara' or 'Ardulith' (different intro texts)
23
 * History page's group is 'h|[id]', where [id] = viewed item's number.
24
 *
25
 * It's meaningles to cache buying/selling page, it will change almost always. Even more: transactions clear the cache.
26
 *
27
 * Caching is silent - users don't feel that it works, unlike monuments or ranking. The only clue is faster loading.
28
 * Cache invalidates on main reset.
29
 */
30
$title = 'Królewski Skład';
31
require_once('includes/head.php');
32
33
/**
34
* Get the localization for game
35
*/
36
require_once('languages/'.$player -> lang.'/warehouse.php');
37
38
if ($player -> location != 'Altara' && $player -> location != 'Ardulith')
39
    error (ERROR);
40
41
/**
42
 * Function returns sell price, buy price and amount of mineral specified by index to $arrSQLNames array.
43
 * Additionally returns boolean indicating data source.
44
 */
45
function getWarehouseData($i)
46
{
47
    global $db;
48
    global $arrSQLNames;
49
    // Prices and amounts of items in first day of new era.
50
	$arrStartPrices = array(2,4,6,9,7,18,22,35,50,1,15,150,20,7,12,20,40,20,15,25,40,50,50,100,140,180);
51
	$arrStartAmount = array(50000,0,0,0,10000,0,0,0,0,100000,2000,500,2000,20000,0,0,0,10000,2000,2000,2000,2000,0,0,0,0);
52
	$arrTest = $db -> GetRow('SELECT `cost`, `amount` FROM `warehouse` WHERE `reset`=1 AND `mineral`=\''.$arrSQLNames[$i].'\'');
53
    if(empty($arrTest))   // No one bought/sold anything yet.
54
        return array($arrStartPrices[$i], 2 * $arrStartPrices[$i], $arrStartAmount[$i], false);
55
    return array(round($arrTest[0],1), round($arrTest[0] * 2,1), $arrTest[1], true);
56
}
57
58
/**
59
 * Function returns amount of mineral/herb owned by player.
60
 */
61
function getPlayersMineral($i)
62
{
63
    global $db;
64
    global $player;
65
    global $arrSQLNames;
66
    if ($i == 17)
67
        return $player -> platinum;
68
    $strName = $arrSQLNames[$i];
69
    if ($i < 17)
70
        $arrTest = $db -> GetRow('SELECT `'.$strName.'` FROM `minerals` WHERE `owner`='.$player -> id);
71
    else
72
        $arrTest = $db -> GetRow('SELECT `'.$strName.'` FROM `herbs` WHERE `gracz`='.$player -> id);
73
    return empty($arrTest) ? 0 : $arrTest[0];
74
}
75
76
$arrSQLNames = array('copperore', 'zincore', 'tinore', 'ironore', 'copper', 'bronze', 'brass', 'iron', 'steel', 'coal', 'adamantium', 'meteor', 'crystal', 'pine', 'hazel', 'yew', 'elm', 'mithril', 'illani', 'illanias', 'nutari', 'dynallca', 'illani_seeds', 'illanias_seeds', 'nutari_seeds', 'dynallca_seeds');
77
$db -> SetFetchMode(ADODB_FETCH_NUM);
78
79
// Setup Smarty caching.
80
if (!isset($_GET['action']) || $_GET['action']=='history')
81
{
82
    $smarty -> cache_dir = 'cache/';
83
    $smarty -> caching = 1;
84
}
85
// End of Smarty setup.
86
/**
87
* Main menu
88
*/
89
if (!isset($_GET['action']))
90
{
91
    if (!$smarty -> is_cached('warehouse.tpl', $player -> location))
92
    {
93
        for($i = 0, $arrItems=array(); $i < 26; ++$i)
94
            $arrItems[] = getWarehouseData($i);
95
        /// Info about caravan.
96
        $arrCaravan = $db -> GetRow('SELECT `value` FROM `settings` WHERE `setting`=\'caravan\'');
97
        $smarty -> assign_by_ref('Items', $arrItems);
98
        $smarty -> assign_by_ref('ItemNames', $arrItemNames);
99
        $smarty -> assign('Caravaninfo', $arrCaravan[0] == 'Y' ? CARAVAN_VISIT : '<br /><br />');
100
    }
101
    $smarty -> display('warehouse.tpl', $player -> location);
102
}
103
else
104
    require_once('includes/security.php');
105
/**
106
* Sell or buy herbs and minerals
107
*/
108
if (isset($_GET['action']) && ($_GET['action'] == 'sell' || $_GET['action'] == 'buy'))
109
{
110
    strictInt($_GET['item']);
111
    if ($_GET['item'] > 25)
112
        error(ERROR);
113
114
    // Prepare general variables that will handle database table differences.
115
    $strSQLname = $arrSQLNames[$_GET['item']];
116
    if ($_GET['item'] < 17)
117
    {
118
        $strTable = 'minerals';
119
        $strOwner = 'owner';
120
    }
121
    elseif ($_GET['item'] > 17)
122
    {
123
        $strTable = 'herbs';
124
        $strOwner = 'gracz';
125
    }
126
    elseif ($_GET['item'] == 17)
127
    {
128
        $strTable = 'players';
129
        $strOwner = 'id';
130
    }
131
132
    $arrInfo = getWarehouseData($_GET['item']);
133
    $intAmount = $_GET['action'] == 'sell' ? getPlayersMineral($_GET['item']) : $arrInfo[2];
134
135
    if (isset($_POST['amount']) && strictInt($_POST['amount']))
136
    {   // We don't display "no such amount" error, but try to buy as much as possible.
137
        if ($_POST['amount'] > $intAmount)
138
            $_POST['amount'] = $intAmount;
139
140
        $intGold = ceil($arrInfo[0] * $_POST['amount'] * ($_GET['action'] == 'buy' ? 2 : 1));
141
        if ($intGold > $player -> credits && $_GET['action'] == 'buy')
142
        {
143
            // Instead of error mesage "no money" we try to buy as much as possible.
144
            $_POST['amount'] = min($_POST['amount'], floor($player -> credits /$arrInfo[1]));
145
            $intGold = ceil($arrInfo[1] * $_POST['amount']);
146
        }
147
        // Give/take player's gold and platinum, if it was the transaction item.
148
        $db -> Execute('UPDATE `players` SET `credits`=`credits`'.($_GET['action'] == 'sell' ? '+' :
149
'-').$intGold.($_GET['item'] == 17 ? ',`platinum`=`platinum`'.($_GET['action'] == 'sell' ? '-' : '+').$_POST['amount'] : '').' WHERE `id`='.$player -> id);
150
        if ($arrInfo[3]) // Wa have already some transactions today with this item, so increment fiels only.
151
            $db -> Execute('UPDATE `warehouse` SET `'.$_GET['action'].'`=`'.$_GET['action'].'`+'.$_POST['amount'].', `amount`=`amount`'.($_GET['action'] == 'sell' ? '+' : '-').$_POST['amount'].' WHERE `reset`=1 AND `mineral`=\''.$strSQLname.'\'');
152
        else    // Else we add new transaction info. In normal circumstances this should only happen on day 1 of new era, since main resets perform these inserts and recompute the price.
153
            $db -> Execute('INSERT INTO `warehouse`(`reset`, `mineral`, `'.$_GET['action'].'`, `amount`, `cost`) VALUES (1,\''.$strSQLname.'\', '.$_POST['amount'].', '.($_GET['action'] == 'buy' ? $intAmount-$_POST['amount'] : $_POST['amount']).', '.$arrInfo[0].')');
154
155
        if ($_GET['action'] == 'sell')
156
        {   // Take player's herbs/minerals.
157
            $db -> Execute('UPDATE `'.$strTable.'` SET `'.$strSQLname.'`=`'.$strSQLname.'`-'.$_POST['amount'].' WHERE `'.$strOwner.'`='.$player -> id);
158
            $intAmount -= $_POST['amount'];
159
        }
160
        else
161
        {
162
            // Give herbs/minerals to player. Make new record or increment existing value.
163
            $arrTest = $db -> GetRow('SELECT `'.$strOwner.'` FROM `'.$strTable.'` WHERE `'.$strOwner.'`='.$player -> id);
164
            if (empty($arrTest))
165
                $db -> Execute('INSERT INTO `'.$strTable.'` (`'.$strOwner.'`, `'.$strSQLname.'`) VALUES('.$player -> id.','.$_POST['amount'].')');
166
            else
167
                $db -> Execute('UPDATE `'.$strTable.'` SET `'.$strSQLname.'`=`'.$strSQLname.'`+'.$_POST['amount'].' WHERE `'.$strOwner.'`='.$player -> id);
168
            $intAmount -=$_POST['amount'];
169
        }
170
        $smarty -> assign('Message', ($_GET['action'] == 'sell' ? YOU_SELL : YOU_BUY).$_POST['amount'].AMOUNT.$arrItemNames[$_GET['item']].FOR_A.$intGold.GOLD_COINS);
171
        // Clear cache of main page and corresponding mineral history.
172
		$smarty -> caching = true;
173
		if ($smarty -> is_cached('warehouse.tpl', 'Altara'))
174
			$smarty -> clear_cache('warehouse.tpl', 'Altara');
175
		if ($smarty -> is_cached('warehouse.tpl', 'Ardulith'))
176
        	$smarty -> clear_cache('warehouse.tpl', 'Ardulith');
177
		if ($smarty -> is_cached('warehouse.tpl', 'h|'.$_GET['item']))
178
        	$smarty -> clear_cache('warehouse.tpl', 'h|'.$_GET['item']);
179
		$smarty -> caching = false;
180
    }
181
    $smarty -> assign(array('Name' => $arrItemNames[$_GET['item']],
182
                            'Item' => $_GET['item'],
183
                            'Amount' => $intAmount,
184
                            'Price' => $arrInfo[$_GET['action'] == 'buy' ? 1 : 0]));
185
    $smarty -> display('warehouse.tpl');
186
}
187
188
/**
189
* Display history of changes for selected herb/mineral.
190
*/
191
if (isset($_GET['action']) && $_GET['action'] == 'history' && isset($_GET['item']))
192
{
193
    strictInt($_GET['item']);
194
    if($_GET['item'] > 25)
195
        error(ERROR);
196
    if (!$smarty -> is_cached('warehouse.tpl', 'h|'.$_GET['item']))
197
    {
198
        // Get biggest value of buys/sales, so all other can be scaled appropriately (percentages, fit to selected height).
199
        $arrMaximums = $db -> GetRow('SELECT MAX(`buy`), MAX(`sell`) FROM `warehouse` WHERE `mineral`=\''.$arrSQLNames[$_GET['item']].'\'');
200
        // Get data for each day.
201
        $arrData = $db -> GetAll('SELECT `sell`, `buy`, `amount`, `cost` FROM `warehouse` WHERE `mineral`=\''.$arrSQLNames[$_GET['item']].'\' ORDER BY `reset` DESC');
202
        $smarty -> assign_by_ref('Data', $arrData);
203
        $smarty -> assign_by_ref('Headers', $arrHeaders);
204
        $smarty -> assign(array('Name' => $arrItemNames[$_GET['item']],
205
                                'Max' => max($arrMaximums[0], $arrMaximums[1], 1)));
206
    }
207
    $smarty -> display('warehouse.tpl', 'h|'.$_GET['item']);
208
}
209
210
// Disable caching, to ensure that foot.php works in good, old, ineffective way.
211
$smarty -> caching = 0;
212
require_once('includes/foot.php');
213
?>