-
Notifications
You must be signed in to change notification settings - Fork 5
/
OreDict.body.php
executable file
·694 lines (609 loc) · 17.9 KB
/
OreDict.body.php
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
<?php
use Wikimedia\Rdbms\ILoadBalancer;
use MediaWiki\MediaWikiServices;
/**
* OreDict main file
*
* @file
* @ingroup Extensions
* @version 1.0.1
* @author Jinbobo <[email protected]>
* @license
*/
class OreDict{
private $mOutputLimit;
private $mItemName;
private $mItemMod;
private $mRawArray;
static private $mQueries;
/**
* Init properties.
*
* @param string $itemName
* @param string $itemMod
*/
public function __construct($itemName, $itemMod = '') {
$this->mItemName = $itemName;
$this->mOutputLimit = 20;
$this->mItemMod = $itemMod;
}
/**
* Change the output limit of the query.
*
* @param int $limit
*/
public function setOutputLimit($limit) {
$this->mOutputLimit = $limit;
}
/**
* Output a list of item names.
*
* @return array
*/
public function getRawOutput() {
$out = "";
foreach ($this->mRawArray as $item) {
if (is_object($item)) {
if (get_class($item) == "OreDictItem") {
$out .= $item->getItemName() . " \n";
}
}
}
return array($out, 'noparse' => true, 'isHTML' => true);
}
/**
* Execute output hooks and returns their output.
*
* @param string $params
* @return array
*/
public function runHooks($params = "") {
$out = "";
MediaWikiServices::getInstance()->getHookContainer()->run("OreDictOutput", array(&$out, $this->mRawArray, $params));
return array($out, 'noparse' => false, 'isHTML' => false);
}
/**
* Queries the OreDict table
*
* @param bool $byTag
* @param bool $noFallback
* @return bool
*/
public function exec($byTag = false, $noFallback = false) {
$dbr = MediaWikiServices::getInstance()->getDBLoadBalancer()->getConnection(DB_REPLICA);
// Vars
$itemModEscaped = $dbr->addQuotes($this->mItemMod);
$sLim = $this->mOutputLimit;
// Query database
if (!isset(self::$mQueries[$this->mItemName][$this->mItemMod])) {
if ($byTag) {
OreDictError::notice(wfMessage('oredict-query-notice')->params('Tag', $this->mItemName, $this->mItemMod)->text());
$result = $dbr->newSelectQueryBuilder()
->select('*')
->from('ext_oredict_items')
->where([
'tag_name' => $this->mItemName,
"($itemModEscaped = '' OR mod_name = $itemModEscaped)"
])
->caller(__METHOD__)
->orderBy('entry_id')
->limit($sLim)
->fetchResultSet();
} else {
OreDictError::notice(wfMessage('oredict-query-notice')->params('Item', $this->mItemName, $this->mItemMod)->text());
$subResult = $dbr->newSelectQueryBuilder()
->select('tag_name')
->from('ext_oredict_items')
->where([
'item_name' => $this->mItemName,
"($itemModEscaped = '' OR mod_name = $itemModEscaped)"
])
->caller(__METHOD__)
->fetchResultSet();
$tagNameList = [];
foreach ($subResult as $r) {
$tagNameList[] = $r->tag_name;
}
$where = [];
if (!empty($tagNameList)) {
$where['tag_name'] = $tagNameList;
}
$result = $dbr->newSelectQueryBuilder()
->select('*')
->from('ext_oredict_items')
->where($where)
->caller(__METHOD__)
->orderBy('entry_id')
->limit($sLim)
->fetchResultSet();
}
//OreDictError::query($query);
//$result = $dbr->query($query);
foreach ($result as $row) {
self::$mQueries[$this->mItemName][$this->mItemMod][] = new OreDictItem($row);
}
if (!isset(self::$mQueries[$this->mItemName][$this->mItemMod])) {
self::$mQueries[$this->mItemName][$this->mItemMod] = [];
OreDictError::notice(wfMessage('oredict-empty-query-notice')->text());
} else {
$rows = $result->numRows();
OreDictError::notice(wfMessage('oredict-nonempty-query-notice')->numParams($rows)->text());
}
}
if (empty(self::$mQueries[$this->mItemName][$this->mItemMod])) {
if ($noFallback) {
$this->mRawArray = [];
} else {
$this->mRawArray = [new OreDictItem($this->mItemName, '', $this->mItemMod, '')];
}
} else {
$this->mRawArray = self::$mQueries[$this->mItemName][$this->mItemMod];
}
return true;
}
/**
* Shuffles an associated array.
*
* @param array $array
* @return bool
*/
static public function shuffleAssocArray(&$array) {
$keys = array_keys($array);
shuffle($keys);
foreach ($keys as $key) {
$new[$key] = $array[$key];
}
if (!isset($new)) {
$new = [];
}
$array = $new;
return true;
}
/**
* @param string $item
* @param string $tag
* @param string $mod
* @param ILoadBalancer $dbLoadBalancer
* @return bool
*/
static public function entryExists($item, $tag, $mod, ILoadBalancer $dbLoadBalancer) {
$dbr = $dbLoadBalancer->getConnection(DB_REPLICA);
$numEntries = $dbr->newSelectQueryBuilder()
->select('COUNT(entry_id)')
->from('ext_oredict_items')
->where([
'item_name' => $item,
'tag_name' => $tag,
'mod_name' => $mod
])
->caller(__METHOD__)
->fetchField();
return $numEntries > 0;
}
/**
* @param $id Int The entry ID
* @param $dbLoadBalancer ILoadBalancer
* @return mixed See checkExists.
*/
static public function checkExistsByID($id, ILoadBalancer $dbLoadBalancer) {
$dbr = $dbLoadBalancer->getConnection(DB_REPLICA);
$row = $dbr->newSelectQueryBuilder()
->select(array(
'item_name',
'tag_name',
'mod_name'
))
->from('ext_oredict_items')
->where(array('entry_id' => $id))
->caller(__METHOD__)
->fetchRow();
return OreDict::entryExists($row->item_name, $row->tag_name, $row->mod_name, $dbLoadBalancer);
}
/**
* Deletes the entry by its ID, and logs it as the user.
* @param $id Int The entry ID
* @param $user User The user
* @param $dbLoadBalancer ILoadBalancer
* @return bool Whether the deletion was successful
*/
static public function deleteEntry($id, $user, ILoadBalancer $dbLoadBalancer) {
$dbw = $dbLoadBalancer->getConnection(DB_PRIMARY);
$row = $dbw->newSelectQueryBuilder()
->select(array('tag_name', 'item_name', 'mod_name'))
->from('ext_oredict_items')
->where(array('entry_id' => $id))
->fetchRow();
$tag = $row->tag_name;
$item = $row->item_name;
$mod = $row->mod_name;
$target = empty($mod) || $mod == '' ? "$tag - $item" : "$tag - $item ($mod)";
try {
$dbw->newDeleteQueryBuilder()
->deleteFrom('ext_oredict_items')
->where(array('entry_id' => $id))
->caller(__METHOD__)
->execute();
} catch (Exception $e) {
return false;
}
$logEntry = new ManualLogEntry('oredict', 'delete');
$logEntry->setPerformer($user);
$logEntry->setTarget(Title::newFromText("Entry/$target", NS_SPECIAL));
$logEntry->setParameters(array("6::tag" => $tag, "7::item" => $item, "8::mod" => $mod, "15::id" => $id));
$logId = $logEntry->insert();
$logEntry->publish($logId);
return true;
}
/**
* Adds an entry.
* @param string $mod Mod name
* @param string $name Item name
* @param string $tag Tag name
* @param User $user User performing the addition
* @param ILoadBalancer $dbLoadBalancer
* @param string $params Grid parameters
* @return bool|int False if it failed to add, or the new ID.
*/
static public function addEntry($mod, $name, $tag, $user, ILoadBalancer $dbLoadBalancer, $params = '') {
if (!self::isStrValid($mod) || !self::isStrValid($name) || !self::isStrValid($tag)) {
return false;
}
$dbw = $dbLoadBalancer->getConnection(DB_PRIMARY);
try {
$dbw->newInsertQueryBuilder()
->insertInto('ext_oredict_items')
->row([
'item_name' => $name,
'tag_name' => $tag,
'mod_name' => $mod,
'grid_params' => $params
])
->caller(__METHOD__)
->execute();
} catch (Exception $e) {
return false;
}
$lastInsert = intval($dbw->newSelectQueryBuilder()
->select('entry_id')
->from('ext_oredict_items')
->caller(__METHOD__)
->orderBy('`entry_id` DESC')
->limit(1)
->fetchField());
$target = ($mod == "" ? "$tag - $name" : "$tag - $name ($mod)");
// Start log
$logEntry = new ManualLogEntry('oredict', 'createentry');
$logEntry->setPerformer($user);
$logEntry->setTarget(Title::newFromText("Entry/$target", NS_SPECIAL));
$logEntry->setParameters(array(
"4::id" => $lastInsert,
"5::tag" => $tag,
"6::item" => $name,
"7::mod" => $mod,
"8::params" => $params));
$logEntry->setComment(wfMessage('oredict-import-comment')->text());
$logId = $logEntry->insert();
$logEntry->publish($logId);
// End log
return $lastInsert;
}
/**
* @param $str string The string to check
* @return bool Whether this string is non-empty and does not contain invalid values.
*/
public static function isStrValid($str) {
return !empty($str) && Title::newFromText($str) !== null;
}
/**
* Edits an entry based on the data given in the first parameter.
* @param $update array An array essentially identical to a row. This contains the new data.
* @param $id Int The entry ID.
* @param $user User The user performing this edit.
* @param $dbLoadBalancer ILoadBalancer
* @return int 1 if the update query failed, 2 if there was no change, or 0 if successful.
*/
static public function editEntry($update, $id, $user, ILoadBalancer $dbLoadBalancer) {
$dbw = $dbLoadBalancer->getConnection(DB_PRIMARY);
$row = $dbw->newSelectQueryBuilder()
->select('*')
->from('ext_oredict_items')
->where(array('entry_id' => $id))
->caller(__METHOD__)
->fetchRow();
$tag = empty($update['tag_name']) ? $row->tag_name : $update['tag_name'];
$item = empty($update['item_name']) ? $row->item_name : $update['item_name'];
$mod = empty($update['mod_name']) ? $row->mod_name : $update['mod_name'];
$params = empty($update['grid_params']) ? $row->grid_params : $update['grid_params'];
// Sanitize input
if (!self::isStrValid($tag) || !self::isStrValid($item) || !self::isStrValid($mod)) {
return 1;
}
try {
$dbw->newUpdateQueryBuilder()
->update('ext_oredict_items')
->set(array(
'tag_name' => $tag,
'item_name' => $item,
'mod_name' => $mod,
'grid_params' => $params
))
->where(array('entry_id' => $id))
->caller(__METHOD__)
->execute();
} catch (Exception $e) {
return 1;
}
// Prepare log vars
$target = empty($mod) ? "$tag - $item" : "$tag - $item ($mod)";
$diff = array();
if ($row->item_name != $item) {
$diff['item'][] = $row->item_name;
$diff['item'][] = $item;
}
if ($row->mod_name != $mod) {
$diff['mod'][] = $row->mod_name;
$diff['mod'][] = $mod;
}
if ($row->grid_params != $params) {
$diff['params'][] = $row->grid_params;
$diff['params'][] = $params;
}
$diffString = "";
foreach ($diff as $field => $change) {
$diffString .= "$field [$change[0] -> $change[1]] ";
}
if ($diffString == "" || count($diff) == 0) {
return 2;
}
$logEntry = new ManualLogEntry('oredict', 'editentry');
$logEntry->setPerformer($user);
$logEntry->setTarget(Title::newFromText("Entry/$target", NS_SPECIAL));
$logEntry->setParameters(array(
"6::tag" => $tag,
"7::item" => $row->item_name,
"8::mod" => $row->mod_name,
"9::params" => $row->grid_params,
"10::to_item" => $item,
"11::to_mod" => $mod,
"12::to_params" => $params,
"13::id" => $id,
"4::diff" => $diffString,
"5::diff_json" => json_encode($diff)));
$logId = $logEntry->insert();
$logEntry->publish($logId);
return 0;
}
/**
* @param $row ? The row to get the data from.
* @return array An array containing the tag, mod, item, and grid params for use throughout the API.
*/
static public function getArrayFromRow($row) {
return array(
'tag_name' => $row->tag_name,
'mod_name' => $row->mod_name,
'item_name' => $row->item_name,
'grid_params' => $row->grid_params,
'id' => intval($row->entry_id)
);
}
}
class OreDictItem{
private $mTagName;
private $mItemName;
private $mItemMod;
private $mItemParams;
private $mId;
/**
* Contsructor, inits properties
*
* @param string|stdClass $item
* @param string $tag
* @param string $mod
* @param string $params
* @throws InvalidArgumentException Throws an InvalidArgumentException when input format is incorrect.
*/
public function __construct($item, $tag = '', $mod = '', $params = '') {
OreDictError::debug(wfMessage('oredictitem-constructor-debug')->text());
if (is_object($item))
if (get_class($item) == "stdClass") {
if (isset($item->item_name)) {
$this->mItemName = $item->item_name;
} else {
throw new InvalidArgumentException(wfMessage('oredictitem-constructor-error')->params('item_name')->text());
}
if (isset($item->mod_name)) {
$this->mItemMod = $item->mod_name;
} else {
throw new InvalidArgumentException(wfMessage('oredictitem-constructor-error')->params('mod_name')->text());
}
if (isset($item->tag_name)) {
$this->mTagName = $item->tag_name;
} else {
throw new InvalidArgumentException(wfMessage('oredictitem-constructor-error')->params('tag_name')->text());
}
if (isset($item->grid_params)) {
$this->mItemParams = OreDictHooks::ParseParamString($item->grid_params);
} else {
throw new InvalidArgumentException(wfMessage('oredictitem-constructor-error')->params('grid_params')->text());
}
if (isset($item->entry_id)) {
$this->mId = $item->entry_id;
} else {
throw new InvalidArgumentException(wfMessage('oredictitem-constructor-error')->params('entry_id')->text());
}
return 0;
}
$this->mItemName = $item;
$this->mTagName = $tag;
$this->mItemMod = $mod;
$this->mItemParams = OreDictHooks::ParseParamString($params);
$this->setMainParams();
return true;
}
/**
* Helper function that rejoins and overwrites the default parameters provided in the OreDict.
*
* @param string $params
* @param bool $override
*/
public function joinParams($params, $override = false) {
OreDictError::debug(wfMessage('oredictitem-join-debug')->params($params));
$input = OreDictHooks::ParseParamString($params);
foreach ($input as $key => $value) {
if (isset($this->mItemParams[$key])) {
if ($override) $this->mItemParams[$key] = $value;
} else {
$this->mItemParams[$key] = $value;
}
}
$this->setMainParams();
}
/**
* Sets the value of a parameter.
*
* @param string $name
* @param string $value
*/
public function setParam($name, $value) {
$this->mItemParams[$name] = $value;
}
/**
* Removes item from parameter list.
*
* @param string $name
*/
public function unsetParam($name) {
if (isset($this->mItemParams[$name])) unset($this->mItemParams[$name]);
}
/**
* @return mixed
*/
public function getMod() { return $this->mItemMod; }
/**
* @return mixed
*/
public function getItem() { return $this->mItemName; }
/**
* @return mixed
*/
public function getItemName() { return $this->mItemName; }
/**
* @return mixed
*/
public function getName() { return $this->mItemName; }
/**
* Sets parameters that are not to be overwritten, is called every time join params is called.
*/
public function setMainParams() {
$this->mItemParams[1] = $this->mItemName;
$this->mItemParams['mod'] = $this->mItemMod;
$this->mItemParams['ore-dict-name'] = $this->mTagName;
}
/**
* @return string
*/
public function getParamString() {
return OreDictHooks::BuildParamString($this->mItemParams);
}
}
class OreDictError{
static private $mDebug;
private $mDebugMode;
/**
* @param $debugMode
*/
public function __construct($debugMode) {
$this->mDebugMode = $debugMode;
}
/**
* Generate errors on edit page preview
*
* @return string
*/
public function output() {
if (!isset(self::$mDebug)) return "";
$colors = array(
"log" => "#CEFFFD",
"warning" => "#FFFFB5",
"deprecated" => "#CCF",
"query" => "#D1FFB3",
"error" => "#FFCECE",
"notice" => "blue"
);
$textColors = array(
"log" => "black",
"warning" => "black",
"deprecated" => "black",
"query" => "black",
"error" => "black",
"notice" => "white"
);
$html = "<table class=\"wikitable\" style=\"width:100%;\">";
$html .= "<caption>" . wfMessage('oredicterror-heading')->text() . "</caption>";
$html .= "<tr><th style=\"width:10%;\">" . wfMessage('oredicterror-heading-type')->text() . "</th><th>" . wfMessage('oredicterror-heading-msg')->text() . "</th><tr>";
$flag = true;
foreach (self::$mDebug as $message) {
if (!$this->mDebugMode && $message[0] != "warning" && $message[0] != "error" && $message[0] != "notice") {
continue;
}
$html .= "<tr><td style=\"text-align:center; background-color:{$colors[$message[0]]}; color:{$textColors[$message[0]]}; font-weight:bold;\">" . wfMessage("oredicterror-type-{$message[0]}")->text() . "</td><td>{$message[1]}</td></tr>";
if ($message[0] == "warnings" || $message[0] == "error") $flag = false;
}
if ($flag) {
$html .= "<tr><td style=\"text-align:center; background-color:blue; color:white; font-weight:bold;\">" . wfMessage('oredicterror-type-notice')->text() . "</td><td>" . wfMessage('oredicterror-none')->text() . "</td></tr>";
}
$html .= "</table>";
return $html;
}
/**
* @param $message
* @param string $type
*/
public static function debug($message, $type = "log") {
self::$mDebug[] = array($type, $message);
}
/**
* @param $message
*/
public static function deprecated($message) {
MWDebug::deprecated("(OreDict) ".$message);
self::debug($message, "deprecated");
}
/**
* @param $query
*/
public static function query($query) {
global $wgShowSQLErrors;
// Hide queries if debug option is not set in LocalSettings.php
if ($wgShowSQLErrors)
self::debug($query, "query");
}
/**
* @param $message
*/
public static function log($message) {
MWDebug::log("(OreDict) ".$message);
self::debug($message);
}
/**
* @param $message
*/
public static function warn($message) {
MWDebug::warning("(OreDict) ".$message);
self::debug($message, "warning");
}
/**
* @param $message
*/
public static function error($message) {
MWDebug::warning("(OreDict) "."Error: ".$message);
self::debug($message, "error");
}
/**
* @param $message
*/
public static function notice($message) {
MWDebug::warning("(OreDict) "."Notice: ".$message);
self::debug($message, "notice");
}
}