-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorderForm.php
More file actions
252 lines (224 loc) · 8.26 KB
/
orderForm.php
File metadata and controls
252 lines (224 loc) · 8.26 KB
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
<?php
/**
* Accepts orders from the player sheet in the form of POST data
* and puts them into the data file
*/
###
# Configuration
###
$EXIT_PAGE = "sheet/index.html"; // relative player page to redirect to
$dataFileDir = "files/"; // location of the data files
###
# Initialization
###
require_once("./GameData.php"); // for the reading and writing functions
$errors = []; // structured error messages
// Order table: [ require "reciever", require "target", require "note", 'description' ]
$orderTable = [
# Fleet Deployment
'add_fleet' => [ true, false, true, 'Add to Fleet' ],
'flight' => [ true, true, false, true ],
'name_fleet' => [ true, false, true, 'Rename a fleet' ],
# Intelligence Orders
'covert' => [ true, true, true, 'Perform covert mission' ],
'special_force'=> [ true, true, true, 'Perform special-forces mission' ],
# Movement Orders
'convoy_raid' => [ true, true, false, 'Convoy Raid' ],
'explore_lane' => [ true, false, false, 'Explore Jump-Lane' ],
'move' => [ true, true, false, 'Move fleet' ],
'load' => [ true, true, true, 'Load units' ],
'long_range' => [ true, true, false, 'Long-Range Scan' ],
'start_trade' => [ true, false, false, 'Set a trade route' ],
'stop_trade' => [ true, true, false, true ],
'unload' => [ true, false, true, 'Unload units' ],
# Diplomatic Orders
'hostile_check'=> [ true, false, false, 'Declare War' ],
'diplo_check' => [ true, false, false, 'Offer a treaty' ],
'sign_treaty' => [ true, true, false, 'Sign a treaty' ],
'sneak_attack' => [ true, false, false, 'Sneak Attack' ],
# Construction orders
'build_unit' => [ true, true, 'New fleet name', 'Build unit at system' ],
'convert' => [ true, true, false, 'Convert/Refit Unit' ],
'mothball' => [ true, false, false, 'Mothball a unit' ],
'purchase_civ' => [ true, true, true, 'Purchase civilian unit at system' ],
'purchase_troop'=> [ true, true, true, 'Purchase troop at system' ],
'remote_build' => [ true, true, false, 'Remote build unit' ],
'repair' => [ true, false, false, 'Repair unit' ],
'scrap' => [ true, false, false, 'Scrap a unit' ],
'unmothball' => [ true, false, false, 'Unmothball a unit' ],
# Investment Orders
'colonize' => [ true, false, false, 'Colonize system' ],
'downgrade_lane'=> [ true, true, false, 'Downgrade Lane' ],
'martial_law' => [ true, false, false, 'Enact martial law' ],
'imp_capacity' => [ true, false, false, 'Improve capacity' ],
'imp_pop' => [ true, false, false, 'Improve Population' ],
'imp_intel' => [ true, false, false, 'Improve Intelligence' ],
'imp_fort' => [ true, false, false, 'Improve Fortifications' ],
'research' => [ false, false, true, 'Invest into research' ],
'name_place' => [ true, false, true, '(Re) name a colony' ],
'research_new' => [ true, true, false, 'Research Target' ],
'upgrade_lane' => [ true, true, false, 'Upgrade Lane' ],
# Combat Orders
'cripple' => [ true, false, false, 'Cripple unit' ],
'destroy' => [ true, false, false, 'Destroy unit' ],
'gift' => [ true, true, false, 'Transfer ownership of unit' ]
];
###
# Input validation
###
// Require POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
exit("Method not allowed");
}
// Validate file name
if (empty($_POST["dataFile"]))
exit("No data file specified");
$dataFileRoot = basename($_POST["dataFile"],'.js');
if (!preg_match('/^[a-zA-Z0-9_-]+$/', $dataFileRoot))
exit("Invalid data file name, '$dataFileRoot'");
$dataFileName = $dataFileDir . $dataFileRoot . ".js";
// Check file readability and writability
if (!is_readable($dataFileName))
exit("Cannot read from '$dataFileName'");
if (!is_writable($dataFileName))
exit("Cannot write to '$dataFileName'");
###
# Load current file contents
###
$fileObj = new GameData($dataFileName);
$issues = $fileObj->getErrors();
if ($issues) {
foreach ($issues as $issue)
$errors[] = $issue."\n";
endScript();
}
if (!isset($fileObj->orders))
$fileObj->orders = [];
###
# Process incoming orders
###
$flagDelete = -1;
foreach ($_POST as $key => $value) {
// Only process OrderEntryNNX keys
if (!preg_match('/^OrderEntry(\d+)([ABCD])$/', $key, $matches))
continue;
$orderNum = (int)$matches[1];
$orderPos = strtolower($matches[2]);
// Handle delete or "<-- No Order -->"
if ($value === "<-- No Order -->" || $flagDelete === $orderNum) {
$flagDelete = $orderNum;
if (isset($fileObj->orders[$orderNum]))
unset($fileObj->orders[$orderNum]);
continue;
}
// Ensure order entry exists
if (!isset($fileObj->orders[$orderNum]))
$fileObj->orders[$orderNum] = [];
// Assign field based on position
switch ($orderPos) {
case 'a': $fileObj->orders[$orderNum]["type"] = trim($value); break;
case 'b': $fileObj->orders[$orderNum]["reciever"] = trim($value); break;
case 'c': $fileObj->orders[$orderNum]["target"] = trim($value); break;
case 'd': $fileObj->orders[$orderNum]["note"] = trim($value); break;
}
}
###
# Validate orders
###
foreach (array_keys($fileObj->orders) as $orderNum) {
$order = &$fileObj->orders[$orderNum];
// Ensure all fields exist
foreach (['type','reciever','target','note'] as $f)
if (!isset($order[$f]))
$order[$f] = "";
// Check valid order type
if (!isset($orderTable[$order["type"]])) {
$errors[] = "Unknown order type '{$order["type"]}' at #$orderNum.";
unset($fileObj->orders[$orderNum]);
continue;
}
// Check order requirements
// Where the $orderTable is TRUE, that $order field is required
$requirements = $orderTable[$order["type"]];
$desc = $requirements[3];
// Validate required fields
$requiredMap = ['reciever','target','note'];
foreach ($requiredMap as $i => $field) {
if ($requirements[$i] && empty($order[$field])) {
$errors[] = "Order type '$desc' requires a $field. None given (order #$orderNum).";
unset($fileObj->orders[$orderNum]);
break;
}
}
// Correct for mis-spelled covert projects
if ($order['type'] == 'covert' || $order['type'] == 'special_force') {
$order['note'] = findIntelProject($order['note']);
}
}
unset($order);
// Reindex array
$fileObj->orders = array_values($fileObj->orders);
###
# Write updated file
###
$fileObj->writeToFile($dataFileName);
$issues = $fileObj->getErrors();
if ($issues) {
foreach ($issues as $issue)
$errors[] = $issue."\n";
}
endScript();
###
# Redirect back to player sheet
###
function endScript(): void
{
global $EXIT_PAGE, $dataFileRoot, $errors;
$redirectUrl = sprintf(
"http://%s/%s?data=%s&e=%s&t=%d",
$_SERVER["HTTP_HOST"],
$EXIT_PAGE,
urlencode($dataFileRoot),
urlencode(implode("\n", $errors)),
time()
);
header("Location: $redirectUrl", true, 302);
exit;
}
###
# findIntelProject(string $intelInput): string
# Determines which intel project was meant from the input
# Direct steal from the Levenstein example in the PHP docs
# Arguments: $intelInput – Mis-spelled intel project
# Output: string - The closest actual intel project from the input
###
function findIntelProject(string $intelInput): string
{
// array of projects to check against
$words = array('civilian','counter-insurgency','counterintel','espionage',
'fortification','industrial','insurgency','piracy','population',
'sabotage','tech');
$shortest = -1; // no shortest distance found, yet
// loop through words to find the closest
foreach ($words as $word) {
// calculate the distance between the input word, and the current word
$lev = levenshtein($intelInput, $word);
// check for an exact match
if ($lev == 0) {
// closest word is this one (exact match)
$closest = $word;
$shortest = 0;
break;
}
// if this distance is less than the next found shortest
// distance, OR if a next shortest word has not yet been found
if ($lev <= $shortest || $shortest < 0) {
// set the closest match, and shortest distance
$closest = $word;
$shortest = $lev;
}
}
return $closest;
}
?>