-
Notifications
You must be signed in to change notification settings - Fork 1
/
SpriteSheet.hooks.php
647 lines (560 loc) · 19.8 KB
/
SpriteSheet.hooks.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
<?php
/**
* SpriteSheet
* SpriteSheet Hooks
*
* @author Alexia E. Smith
* @license LGPL v3.0
* @package SpriteSheet
* @link https://github.com/CurseStaff/SpriteSheet
*
**/
class SpriteSheetHooks {
/**
* Valid parameters.
*
* @var array
*/
static private $validParameters = [
'sprite' => [
'file' => [
'required' => true,
'default' => null
],
'name' => [
'required' => false,
'default' => null
],
'column' => [
'required' => false,
'default' => null,
'sanitize' => "#^(?P<integer>\d+)$#i"
],
'row' => [
'required' => false,
'default' => null,
'sanitize' => "#^(?P<integer>\d+)$#i"
],
'resize' => [
'required' => false,
'default' => null,
'sanitize' => "#^(?P<number>\d+(?:\.\d+)?)(?P<unit>px$|$)#i"
],
'link' => [
'required' => false,
'default' => null
],
'wikitext' => [
'required' => false,
'default' => null
]
],
'slice' => [
'file' => [
'required' => true,
'default' => null
],
'name' => [
'required' => false,
'default' => null
],
'x' => [
'required' => false,
'default' => null,
'sanitize' => "#^(?P<number>\d+(?:\.\d+)?)(?P<unit>px$|%$|$)#i"
],
'y' => [
'required' => false,
'default' => null,
'sanitize' => "#^(?P<number>\d+(?:\.\d+)?)(?P<unit>px$|%$|$)#i"
],
'width' => [
'required' => false,
'default' => null,
'sanitize' => "#^(?P<number>\d+(?:\.\d+)?)(?P<unit>px$|%$|$)#i"
],
'height' => [
'required' => false,
'default' => null,
'sanitize' => "#^(?P<number>\d+(?:\.\d+)?)(?P<unit>px$|%$|$)#i"
],
'resize' => [
'required' => false,
'default' => null,
'sanitize' => "#^(?P<number>\d+(?:\.\d+)?)(?P<unit>px$|$)#i"
],
'link' => [
'required' => false,
'default' => null
],
'wikitext' => [
'required' => false,
'default' => null
]
],
];
/**
* Any error messages that may have been triggerred.
*
* @var array
*/
static private $errors = [];
/**
* The tag type being processed, either sprite or slice.
*
* @var array
*/
static private $tagType = false;
/**
* SpriteSheet Object - Used to hold a SpriteSheet when viewing an image page.
*
* @var object
*/
static private $spriteSheet = null;
/**
* Old SpriteSheet Object
*
* @var object
*/
static private $oldSpriteSheet = null;
/**
* Sets up this extension's parser functions.
*
* @access public
* @param object Parser object passed as a reference.
* @return boolean true
*/
static public function onParserFirstCallInit(Parser &$parser) {
$parser->setFunctionHook("sprite", "SpriteSheetHooks::generateSpriteOutput", SFH_OBJECT_ARGS);
$parser->setFunctionHook("slice", "SpriteSheetHooks::generateSliceOutput", SFH_OBJECT_ARGS);
$parser->setFunctionHook("ifsprite", "SpriteSheetHooks::generateIfSpriteOutput", SFH_OBJECT_ARGS);
$parser->setFunctionHook("ifslice", "SpriteSheetHooks::generateIfSliceOutput", SFH_OBJECT_ARGS);
return true;
}
/**
* The #sprite parser tag entry point.
*
* @access public
* @param object Parser
* @param object PPFrame
* @param array Arguments
* @return string Wiki Text
*/
static public function generateSpriteOutput(Parser &$parser, PPFrame $frame, $arguments) {
self::$errors = [];
self::$tagType = "sprite";
$parameters = self::cleanAndSetupParameters($arguments, $frame);
//Check if any errors occurred during parameter processing and immediately alert the user to them.
if (!empty(self::$errors)) {
return self::makeErrorBox();
}
$title = self::getTitleFromFileName($parameters['file']);
if ($title !== null && $title->isKnown()) {
$spriteSheet = SpriteSheet::newFromTitle($title, true);
if (!$spriteSheet->getId() || !$spriteSheet->getColumns() || !$spriteSheet->getRows()) {
//Either a sprite sheet does not exist or has invalid values.
self::setError('no_sprite_sheet_defined', [$title->getPrefixedText()]);
return self::makeErrorBox();
}
if (!empty($parameters['name'])) {
$spriteName = $spriteSheet->getSpriteName($parameters['name']);
if (!$spriteName->exists()) {
self::setError('could_not_find_named_sprite', [$parameters['file'], $parameters['name']]);
return self::makeErrorBox();
}
if ($spriteName->getType() != 'sprite') {
self::setError('wrong_named_sprite_slice');
return self::makeErrorBox();
}
$html = $spriteSheet->getSpriteHtmlFromName($spriteName->getName(), isset($parameters['resize']['number']) ? $parameters['resize']['number'] : null);
} else {
if (!isset($parameters['column']['integer']) || $parameters['column']['integer'] < 0) {
self::setError('spritesheet_error_invalid_option', ['column', $parameters['column']['integer']]);
return self::makeErrorBox();
}
if (!isset($parameters['row']['integer']) || $parameters['row']['integer'] < 0) {
self::setError('spritesheet_error_invalid_option', ['row', $parameters['row']['integer']]);
return self::makeErrorBox();
}
$html = $spriteSheet->getSpriteHtml($parameters['column']['integer'], $parameters['row']['integer'], $parameters['resize']['number'], $parameters['link']);
}
} else {
self::setError('could_not_find_title', [$parameters['file']]);
return self::makeErrorBox();
}
$parser->getOutput()->addModules('ext.spriteSheet');
return [
$html,
'noparse' => true,
'isHTML' => true
];
}
/**
* The #ifsprite parser tag entry point.
*
* @access public
* @param object Parser
* @param object PPFrame
* @param array Arguments
* @return string Wiki Text
*/
static public function generateIfSpriteOutput(Parser &$parser, PPFrame $frame, $arguments) {
$output = self::generateSpriteOutput($parser, $frame, $arguments);
$parameters = self::cleanAndSetupParameters($arguments, $frame);
if (!is_array($output)) {
return $parameters['wikitext'];
}
return $output;
}
/**
* The #slice parser tag entry point.
*
* @access public
* @param object Parser
* @param object PPFrame
* @param array Arguments
* @return string Wiki Text
*/
static public function generateSliceOutput(Parser &$parser, PPFrame $frame, $arguments) {
self::$errors = false;
self::$tagType = "slice";
$parameters = self::cleanAndSetupParameters($arguments, $frame);
//Check if any errors occurred during parameter processing and immediately alert the user to them.
if (!empty(self::$errors)) {
return self::makeErrorBox();
}
$pixelMode = false;
$title = self::getTitleFromFileName($parameters['file']);
if ($title !== null && $title->isKnown()) {
$spriteSheet = SpriteSheet::newFromTitle($title, true);
if (!$spriteSheet->getId()) {
//Either a sprite sheet does not exist or has invalid values.
self::setError('no_sprite_sheet_defined', [$title->getPrefixedText()]);
return self::makeErrorBox();
}
if ($spriteSheet !== false) {
if (!empty($parameters['name'])) {
$sliceName = $spriteSheet->getSpriteName($parameters['name']);
if (!$sliceName->exists()) {
self::setError('could_not_find_named_slice', [$parameters['file'], $parameters['name']]);
return self::makeErrorBox();
}
if ($sliceName->getType() != 'slice') {
self::setError('wrong_named_sprite_slice');
return self::makeErrorBox();
}
$html = $spriteSheet->getSliceHtmlFromName($sliceName->getName(), isset($parameters['resize']['number']) ? $parameters['resize']['number'] : null, $pixelMode);
} else {
//The unit of measure is allowed to be specified, but they must match to be valid.
$unitParams = ['x', 'y', 'width', 'height'];
$totalUnitParams = 4;
foreach ($unitParams as $unitParam) {
if (!isset($parameters[$unitParam]['number']) || $parameters[$unitParam]['number'] < 0) {
self::setError('spritesheet_error_invalid_option', [$unitParam, $parameters[$unitParam]['number']]);
}
if ($parameters[$unitParam]['unit'] == 'px') {
$pixels++;
}
if (!$parameters[$unitParam]['unit'] || $parameters[$unitParam]['unit'] == '%') {
$percents++;
}
}
if (!empty(self::$errors)) {
return self::makeErrorBox();
}
if ($pixels != $totalUnitParams && $percents != $totalUnitParams) {
self::setError('slice_error_mixed_units');
return self::makeErrorBox();
} elseif ($pixels == $totalUnitParams) {
$pixelMode = true;
}
$html = $spriteSheet->getSliceHtml($parameters['x']['number'], $parameters['y']['number'], $parameters['width']['number'], $parameters['height']['number'], $parameters['resize']['number'], $parameters['link'], $pixelMode);
}
$parser->getOutput()->addModules('ext.spriteSheet');
return [
$html,
'noparse' => true,
'isHTML' => true
];
}
}
self::setError('could_not_find_title', [$parameters['file']]);
return self::makeErrorBox();
}
/**
* The #ifslice parser tag entry point.
*
* @access public
* @param object Parser
* @param object PPFrame
* @param array Arguments
* @return string Wiki Text
*/
static public function generateIfSliceOutput(Parser &$parser, PPFrame $frame, $arguments) {
$output = self::generateSliceOutput($parser, $frame, $arguments);
$parameters = self::cleanAndSetupParameters($arguments, $frame);
if (!is_array($output)) {
return $parameters['wikitext'];
}
return $output;
}
/**
* Get the title from the file name and handle redirects.
*
* @access private
* @param string File Name
* @return mixed Title|null
*/
static private function getTitleFromFileName($file) {
$title = Title::newFromDBKey($file);
if ($title->isRedirect()) {
$oldPage = WikiPage::factory($title);
$newTitle = $oldPage->getRedirectTarget();
if ($newTitle !== null) {
$title = $newTitle;
}
}
return $title;
}
/**
* Clean user supplied parameters and setup defaults.
*
* @access private
* @param array Raw strings of 'parameter=option'.
* @param object PPFrame
* @return array Safe Parameter => Option key value pairs.
*/
static private function cleanAndSetupParameters($arguments, PPFrame $frame) {
/************************************/
/* Clean Parameters */
/************************************/
$rawParameterOptions = [];
if (is_array($arguments)) {
foreach ($arguments as $argument) {
$rawParameterOptions[] = trim($frame->expand($argument));
}
}
$validParameters = self::$validParameters[self::$tagType];
//Check user supplied parameters.
$cleanParameterOptions = [];
foreach ($rawParameterOptions as $raw) {
$equals = strpos($raw, '=');
if ($equals === false || $equals === 0 || $equals === strlen($raw) - 1) {
continue;
}
list($parameter, $option) = explode('=', $raw);
$parameter = strtolower(trim($parameter));
$option = trim($option);
if (isset($validParameters[$parameter])) {
$cleanParameterOptions[$parameter] = $option;
if (isset($validParameters[$parameter]['values']) && is_array($validParameters[$parameter]['values'])) {
if (!in_array($option, $validParameters[$parameter]['values'])) {
//Throw an error.
unset($cleanParameterOptions[$parameter]);
self::setError('spritesheet_error_invalid_option', [$parameter, $option]);
} else {
$cleanParameterOptions[$parameter] = $option;
}
}
if (isset($validParameters[$parameter]['sanitize'])) {
if (preg_match($validParameters[$parameter]['sanitize'], $option, $matches)) {
$cleanParameterOptions[$parameter] = $matches;
} else {
unset($cleanParameterOptions[$parameter]);
self::setError('spritesheet_error_invalid_option', [$parameter, $option]);
}
}
} else {
self::setError('spritesheet_error_bad_parameter', [$parameter]);
}
}
//Enforce required and default.
foreach ($validParameters as $parameter => $parameterData) {
if ($parameterData['required'] && !array_key_exists($parameter, $cleanParameterOptions)) {
self::setError('spritesheet_error_parameter_required', [$parameter]);
}
//Assign the default if not supplied by the user and a default exists.
if (!$parameterData['required'] && !array_key_exists($parameter, $cleanParameterOptions) && $parameterData['default'] !== null) {
$cleanParameterOptions[$parameter] = $parameterData['default'];
}
}
return $cleanParameterOptions;
}
/**
* Set a non-fatal error to be returned to the end user later.
*
* @access private
* @param string Message language string.
* @param array [Optional] Message replacements.
* @return void
*/
static private function setError($message, $replacements = []) {
self::$errors[] = wfMessage($message, $replacements)->escaped();
}
/**
* Make a standard error box.
*
* @access private
* @return string HTML Error
*/
static private function makeErrorBox() {
return "
<div class='errorbox'>
<strong>SpriteSheet</strong><br/>
".implode("<br/>\n", self::$errors)."
</div>";
}
/**
* Display link to invoke sprite sheet editor.
*
* @access public
* @param object ImagePage Object
* @param array Array of table of contents links to modify.
* @return boolean True
*/
static public function onImagePageShowTOC(ImagePage $imagePage, &$toc) {
if (strpos($imagePage->getDisplayedFile()->getMimeType(), 'image/') === false) {
//Can not sprite sheet non-images.
return true;
}
$toc[] = '<li><a id="spritesheet_toc" href="#">'.wfMessage('sprite_sheet')->escaped().'</a></li>';
return true;
}
/**
* Display link to invoke sprite sheet editor.
*
* @access public
* @param object ImagePage Object
* @param object OutputPage Object
* @return boolean True
*/
static public function onImageOpenShowImageInlineBefore(ImagePage $imagePage, OutputPage $output) {
global $wgUser;
$output->addModules('ext.spriteSheet');
if (strpos($imagePage->getDisplayedFile()->getMimeType(), 'image/') === false) {
//Can not sprite sheet non-images.
return true;
}
self::$spriteSheet = SpriteSheet::newFromTitle($imagePage->getTitle());
if (!self::$spriteSheet) {
//This can occur if the page entry in the database becomes corrupted. End users will have to reupload the image to fix the page entry before SpriteSheet will work on it.
return true;
}
if (self::checkAndDoRollbacks()) {
$output->redirect(self::$spriteSheet->getTitle()->getFullURL());
return true;
}
$logLink = Linker::link(SpecialPage::getTitleFor('Log'), wfMessage('sprite_sheet_log')->escaped(), [], ['page' => self::$spriteSheet->getTitle()->getPrefixedText()]);
//Permission checks.
$canEdit = true;
if (!$wgUser->isAllowed('edit_sprites') || !$imagePage->getTitle()->userCan('edit')) {
$canEdit = false;
}
$disabled = (!self::$spriteSheet->isLocal() || !$canEdit ? " disabled='disabled'" : '');
$readOnly = (!self::$spriteSheet->isLocal() || !$canEdit ? " readonly='readonly'" : '');
$templates = new TemplateSpriteSheetEditor();
$form = $templates->spriteSheetForm($imagePage, self::$spriteSheet, self::$oldSpriteSheet, $logLink, $disabled, $readOnly);
$output->addHtml($form);
return true;
}
/**
* Pefrom any rollbacks as necessary.
*
* @access private
* @return boolean If rollbacks were performed.
*/
static private function checkAndDoRollbacks() {
global $wgRequest, $wgUser;
$action = $wgRequest->getVal('sheetAction', false);
if (($action == 'diff' || $action == 'rollback')) {
//Handle sheet roll backs.
if ($wgRequest->getInt('sheetPreviousId') > 0) {
self::$oldSpriteSheet = self::$spriteSheet->getRevisionById($wgRequest->getInt('sheetPreviousId'));
if ($action == 'rollback' && $wgUser->isAllowed('spritesheet_rollback') && self::$oldSpriteSheet !== false) {
//Perform the rollback then redirect to this page with a success message and the editor opened.
self::$spriteSheet->setColumns(self::$oldSpriteSheet->getColumns());
self::$spriteSheet->setRows(self::$oldSpriteSheet->getRows());
self::$spriteSheet->setInset(self::$oldSpriteSheet->getInset());
return self::$spriteSheet->save();
}
}
//Handle individual sprite roll backs.
if ($wgRequest->getInt('spritePreviousId') > 0) {
$oldSpriteName = SpriteName::newFromRevisionId($wgRequest->getInt('spritePreviousId'));
if ($action == 'rollback' && $wgUser->isAllowed('spritesheet_rollback') && $oldSpriteName !== false && $oldSpriteName->getId()) {
$spriteName = SpriteName::newFromId($oldSpriteName->getId(), self::$spriteSheet);
if ($spriteName !== false && $spriteName->getId()) {
$spriteName->setName($oldSpriteName->getName());
$spriteName->setType($oldSpriteName->getType());
$spriteName->setValues($oldSpriteName->getValues());
$spriteName->setDeleted($oldSpriteName->isDeleted());
return $spriteName->save();
}
}
}
}
return false;
}
/**
* Modify the page rendering hash when altering the output.
*
* @access public
* @param string Page rendering hash
* @param object User Object
* @param array Options used to generate the initial hash.
* @return boolean True
*/
static public function onPageRenderingHash(&$hash, User $user, &$forOptions) {
if (self::$spriteSheet instanceOf SpriteSheet && self::$spriteSheet->getId()) {
$hash .= '!'.self::$spriteSheet->getId().'-'.self::$spriteSheet->getColumns().'-'.self::$spriteSheet->getRows().'-'.self::$spriteSheet->getInset();
}
return true;
}
/**
* Modify the page rendering hash when altering the output.
*
* @access public
* @param object Old Title
* @param object New Title
* @param object User who performed the move.
* @param integer Old/Current ID of the Article/Page
* @param integer New(Redirect) ID of redirect page created, if created.
* @param string Reason given by the user performing the move.
* @return boolean True
*/
static public function onTitleMoveComplete(Title &$oldTitle, Title &$newTitle, User $user, $oldId, $newId, $reason = null) {
$spriteSheet = SpriteSheet::newFromTitle($oldTitle);
if (!$spriteSheet || !$spriteSheet->exists()) {
//No sprite sheet to update the Title on so we can safely skip this.
return true;
}
$spriteSheet->setTitle($newTitle);
$spriteSheet->save();
return true;
}
/**
* Setups and Modifies Database Information
*
* @access public
* @param object [Optional] DatabaseUpdater Object
* @return boolean true
*/
static public function onLoadExtensionSchemaUpdates($updater = null) {
$extDir = __DIR__;
$updater->addExtensionUpdate(['addTable', 'spritesheet', "{$extDir}/install/sql/spritesheet_table_spritesheet.sql", true]);
$updater->addExtensionUpdate(['addTable', 'spritesheet_rev', "{$extDir}/install/sql/spritesheet_table_spritesheet_rev.sql", true]);
$updater->addExtensionUpdate(['addTable', 'spritename', "{$extDir}/install/sql/spritesheet_table_spritename.sql", true]);
$updater->addExtensionUpdate(['addTable', 'spritename_rev', "{$extDir}/install/sql/spritesheet_table_spritename_rev.sql", true]);
//2015-02-23
$updater->addExtensionUpdate(['renameIndex', 'spritename', 'name', 'spritesheet_id_name', false, "{$extDir}/upgrade/sql/spritesheet_upgrade_spritesheet_alter_index_name.sql", true]);
//2015-03-03
$updater->addExtensionUpdate(['modifyField', 'spritesheet', 'page_id', "{$extDir}/upgrade/sql/spritesheet_upgrade_spritesheet_alter_page_id.sql", true]);
//2015-04-07
$updater->addExtensionUpdate(['addField', 'spritesheet', 'edited', "{$extDir}/upgrade/sql/spritesheet_upgrade_spritesheet_add_edited.sql", true]);
//2015-04-13
$updater->addExtensionUpdate(['addField', 'spritename', 'edited', "{$extDir}/upgrade/sql/spritesheet_upgrade_spritename_add_edited.sql", true]);
$updater->addExtensionUpdate(['addField', 'spritename', 'deleted', "{$extDir}/upgrade/sql/spritesheet_upgrade_spritename_add_deleted.sql", true]);
$updater->addExtensionUpdate(['addField', 'spritename_rev', 'deleted', "{$extDir}/upgrade/sql/spritesheet_upgrade_spritename_rev_add_deleted.sql", true]);
return true;
}
}