/
ManagePlugins.php
1866 lines (1657 loc) · 61.1 KB
/
ManagePlugins.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
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
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Handle all key aspects relating to plugins and their management.
*
* Wedge (http://wedge.org)
* Copyright © 2010 René-Gilles Deberdt, wedge.org
* License: http://wedge.org/license/
*/
if (!defined('WEDGE'))
die('Hacking attempt...');
function PluginsHome()
{
global $txt, $context;
// General stuff
loadLanguage('ManagePlugins');
loadTemplate('ManagePlugins');
loadSource('Subs-Plugins');
define('WEDGE_PLUGIN', 1); // Any scripts that are run from here, should *really* test that this is defined and exit if not.
if (isset($_GET['area']) && $_GET['area'] == 'addplugin')
return AddPlugin();
// Because our good friend the GenericMenu complains otherwise.
$context[$context['admin_menu_name']]['tab_data'] = array(
'title' => $txt['plugin_manager'],
'description' => $txt['plugin_manager_desc'],
'tabs' => array(
'plugins' => array(
),
),
);
$subActions = array(
'list' => 'ListPlugins',
'readme' => 'PluginReadme',
'enable' => 'EnablePlugin',
'disable' => 'DisablePlugin',
'remove' => 'RemovePlugin',
);
// By default do the basic settings.
$_REQUEST['sa'] = isset($_REQUEST['sa'], $subActions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : key($subActions);
$context['sub_action'] = $_REQUEST['sa'];
$subActions[$_REQUEST['sa']]();
}
function ListPlugins()
{
global $txt, $context, $maintenance;
wetem::load('browse');
$context['page_title'] = $txt['plugin_manager'];
getLanguages();
$context['available_plugins'] = array();
$hooks = knownHooks();
// 1. Step through the directory, figure out what's there and what's not, and store everything that's valid in $context['available_plugins'].
// Since we explicitly want folders at this point, we don't want to use scandir.
// !! libxml_use_internal_errors(true); ??
if ($handle = opendir($plug_dir = ROOT_DIR . '/plugins/'))
{
while (($folder = readdir($handle)) !== false)
{
if ($folder[0] == '.' || strpos($folder, ',') !== false)
continue;
if (filetype($plug_dir . $folder) == 'dir' && file_exists($plug_dir . $folder . '/plugin-info.xml'))
{
$manifest = safe_sxml_load($plug_dir . $folder . '/plugin-info.xml');
if ($manifest === false || empty($manifest['id']) || empty($manifest->name) || empty($manifest->author) || empty($manifest->version))
continue;
$plugin = array(
'folder' => $folder,
'id' => (string) $manifest['id'],
'name' => westr::htmlspecialchars((string) $manifest->name),
'author' => westr::htmlspecialchars($manifest->author),
'author_url' => (string) $manifest->author['url'],
'author_email' => (string) $manifest->author['email'],
'website' => (string) $manifest->website,
'version' => westr::htmlspecialchars($manifest->version),
'description' => westr::htmlspecialchars($manifest->description),
'hooks' => array(),
'provide_hooks' => array(),
'optional_hooks' => array(
'function' => array(),
'language' => array(),
),
'readmes' => array(),
'acp_url' => '',
'install_errors' => array(),
'enabled' => false,
'maint' => array(),
);
// Use the supplied link if, well, given, but failing that check to see if they used an auto admin page.
if (!empty($manifest->{'acp-url'}))
$plugin['acp_url'] = (string) $manifest->{'acp-url'};
elseif (!empty($manifest->{'settings-page'}['area']))
$plugin['acp_url'] = 'action=admin;area=' . (string) $manifest->{'settings-page'}['area'];
// Do some sanity checking, to validate that any given URL or email are at least vaguely legal.
if (empty($plugin['author_url']) || (strpos($plugin['author_url'], 'http://') !== 0 && strpos($plugin['author_url'], 'https://') !== 0))
$plugin['author_url'] = '';
if (empty($plugin['website']) || (strpos($plugin['website'], 'http://') !== 0 && strpos($plugin['website'], 'https://') !== 0))
$plugin['website'] = '';
if (empty($plugin['author_email']) || !is_valid_email($plugin['author_email']))
$plugin['author_email'] = '';
// Test minimum versions of things.
if (!empty($manifest->{'min-versions'}))
{
$min_versions = testRequiredVersions($manifest->{'min-versions'});
foreach (array('php', 'mysql') as $test)
if (isset($min_versions[$test]))
$plugin['install_errors']['min' . $test] = sprintf($txt['install_error_min' . $test], $min_versions[$test][0], $min_versions[$test][1]);
}
// Required functions?
if (!empty($manifest->{'required-functions'}))
{
$required_functions = testRequiredFunctions($manifest->{'required-functions'});
if (!empty($required_functions))
$plugin['install_errors']['reqfunc'] = sprintf($txt['install_error_reqfunc'], implode(', ', $required_functions));
}
// Hooks associated with this plugin.
if (!empty($manifest->hooks))
{
$hooks_listed = $manifest->hooks->children();
foreach ($hooks_listed as $each_hook)
{
switch ($each_hook->getName())
{
case 'function':
if (!empty($each_hook['point']))
$plugin['hooks']['function'][] = $each_hook['point'];
if (!empty($each_hook['optional']) && $each_hook['optional'] == 'yes')
$plugin['optional_hooks']['function'][] = $each_hook['point'];
break;
case 'language':
if (!empty($each_hook['point']))
$plugin['hooks']['language'][] = $each_hook['point'];
if (!empty($each_hook['optional']) && $each_hook['optional'] == 'yes')
$plugin['optional_hooks']['language'][] = $each_hook['point'];
break;
case 'provides':
$provided_hooks = $each_hook->children();
foreach ($provided_hooks as $hook)
if (!empty($hook['type']) && ((string) $hook['type'] == 'function' || (string) $hook['type'] == 'language'))
{
// Only deal with hooks provided by a plugin if it's enabled.
if (in_array($folder, $context['enabled_plugins']))
$hooks[(string) $hook['type']][] = (string) $hook;
if (empty($plugin['provide_hooks'][(string) $hook['type']]))
$plugin['provide_hooks'][(string) $hook['type']] = array();
$plugin['provide_hooks'][(string) $hook['type']][] = (string) $hook;
}
break;
}
}
}
// Readme files. $context['languages'] contains all the languages we have - no sense offering readmes we don't have installed languages for.
if (!empty($manifest->readmes))
{
foreach ($manifest->readmes->readme as $readme)
{
$lang = (string) $readme['lang'];
if (!empty($lang) && isset($context['languages'][$lang]))
$plugin['readmes'][$lang] = true;
}
// We'll put them in alphabetic order, but English first because that's guaranteed to be available as an installed language.
ksort($plugin['readmes']);
if (isset($plugin['readmes']['english']))
{
unset($plugin['readmes']['english']);
$plugin['readmes'] = array_merge(array('english' => true), $plugin['readmes']);
}
}
// Is there anything it has to do in maintenance mode?
$plugin['maint'] = get_maint_requirements($manifest);
// OK, add to the list.
$context['available_plugins'][strtolower($plugin['name'] . $folder)] = $plugin;
}
}
closedir($handle);
}
// 1a. We want the packages in a nice order. The array key is the name of the plugin, then with the folder appended in the case of duplicates.
ksort($context['available_plugins']);
// 2. Having passed through everything once, we will have figured out what dependencies and provisions there are. Apply that too.
foreach ($context['available_plugins'] as $id => $plugin)
{
foreach ($plugin['hooks'] as $hook_type => $required_hooks)
{
if (!empty($context['available_plugins'][$id]['install_errors']['missinghook']))
break;
// Hmm, just make sure there's actually something available for what we're doing to do in a minute.
if (empty($plugin['provide_hooks'][$hook_type]))
$plugin['provide_hooks'][$hook_type] = array();
$missing_hooks = array_diff($required_hooks, $hooks[$hook_type], $plugin['provide_hooks'][$hook_type], $plugin['optional_hooks'][$hook_type]);
if (count($missing_hooks) > 0)
{
$context['available_plugins'][$id]['install_errors']['missinghook'] = $txt['install_error_missinghook'] . ' (' . implode(', ', $missing_hooks) . ')';
break 2;
}
}
}
// 3. Make sure to deactivate any plugins that were activated but now shouldn't be. This includes general cleanup too.
if (!empty($context['enabled_plugins']))
{
$original = $context['enabled_plugins'];
$context['enabled_plugins'] = array();
foreach ($context['available_plugins'] as $id => $plugin)
if (empty($plugin['install_errors']) && in_array($plugin['folder'], $original))
{
$context['enabled_plugins'][$plugin['id']] = $plugin['folder'];
$context['available_plugins'][$id]['enabled'] = true;
}
updateSettings(array('enabled_plugins' => implode(',', $context['enabled_plugins'])));
}
// 4. Go through the remaining disabled plugins and check that they're not trying to activate where there's another plugin with the same id already enabled.
$by_id = array(
'enabled' => array(),
'disabled' => array(),
);
foreach ($context['available_plugins'] as $id => $plugin)
$by_id[$plugin['enabled'] ? 'enabled' : 'disabled'][] = $plugin['id'];
if (!empty($by_id['enabled']) && !empty($by_id['disabled']))
{
foreach ($by_id['disabled'] as $disabled)
if (in_array($disabled, $by_id['enabled']))
{
foreach ($context['available_plugins'] as $id => $plugin)
{
if ($plugin['enabled'] || $plugin['id'] != $disabled)
continue;
$context['available_plugins'][$id]['install_errors']['duplicate_id'] = $txt['install_error_duplicate_id'] . ' (' . $plugin['id'] . ')';
}
}
}
// 5. Deal with any plugins that are not currently enabled, but want to be in maintenance mode to do so.
// If we're not in maintenance, the plugin isn't enabled and it wants maintenance mode to be able to do so.
if ($maintenance == 0)
foreach ($context['available_plugins'] as $id => $plugin)
if (!$plugin['enabled'] && !empty($plugin['maint']) && in_array('enable', $plugin['maint']))
$context['available_plugins'][$id]['install_errors']['maint_mode'] = $txt['install_error_maint_mode'];
// 6. Deal with any filtering. We have to do it here, rather than earlier, simply because we need to have processed everything beforehand.
$context['filter_plugins'] = array(
'all' => 0,
'enabled' => 0,
'disabled' => 0,
'install_errors' => 0,
);
$context['current_filter'] = isset($_GET['filter']) && isset($context['filter_plugins'][$_GET['filter']]) ? $_GET['filter'] : 'all';
foreach ($context['available_plugins'] as $id => $plugin)
{
if (!empty($plugin['install_errors']))
$type = 'install_errors';
elseif (!empty($plugin['enabled']))
$type = 'enabled';
else
$type = 'disabled';
$context['filter_plugins']['all']++;
$context['filter_plugins'][$type]++;
if ($context['current_filter'] !== 'all' && $context['current_filter'] !== $type)
unset($context['available_plugins'][$id]);
}
}
function PluginReadme()
{
global $context, $txt;
// Let's start and fire up the template. We're reusing the nice popup, so load templates and set up various things.
loadTemplate('GenericPopup');
loadLanguage('Help');
wetem::hide();
$context['page_title'] = $txt['plugin_manager'] . ' - ' . $txt['help'];
wetem::load('popup');
// Did they specify a plugin, and is it a valid one?
$valid = isViablePlugin();
// Did they specify a language, and is it valid?
if ($valid && isset($_GET['lang']))
{
getLanguages();
if (!isset($context['languages'][$_GET['lang']]))
$valid = false;
}
else
$valid = false;
// Lastly, does the package know this readme?
if ($valid)
{
$manifest = safe_sxml_load(ROOT_DIR . '/plugins/' . $_GET['plugin'] . '/plugin-info.xml');
if (!empty($manifest->readmes))
{
$readme_found = false;
foreach ($manifest->readmes->readme as $readme)
{
$lang = (string) $readme['lang'];
if ($_GET['lang'] == $lang)
{
$readme_found = (string) $readme;
break;
}
}
if (!$readme_found)
$valid = false;
}
else
$valid = false;
}
// So, the readme is valid. Read it, it's probably bbcode, so preparse and parse it.
if ($valid)
{
$path = strtr($readme, array('$plugindir' => ROOT_DIR . '/plugins/' . $_GET['plugin']));
$contents = file_get_contents($path);
loadSource('Class-Editor');
// Preparse, then remove any instances of the html bbcode. There is no reason to allow *raw* HTML here.
$contents = westr::htmlspecialchars($contents, ENT_QUOTES);
$contents = preg_replace('~\[[/]?html\]~i', '', $contents);
wedit::preparsecode($contents);
$name = '';
if (!empty($manifest->name))
{
$name = (string) $manifest->name;
if (!empty($manifest->version))
$name .= ' ' . westr::htmlspecialchars((string) $manifest->version);
$name = '<h6>' . $name . '</h6>';
}
$context['popup_contents'] = $name . parse_bbc($contents, 'plugin-readme');
}
else
$context['popup_contents'] = $txt['invalid_plugin_readme'];
}
function EnablePlugin()
{
global $context, $settings, $maintenance;
checkSession('request');
// !! libxml_use_internal_errors(true); ??
if (!isViablePlugin())
fatal_lang_error('fatal_not_valid_plugin', false);
$manifest = safe_sxml_load(ROOT_DIR . '/plugins/' . $_GET['plugin'] . '/plugin-info.xml');
if ($manifest === false || empty($manifest['id']) || empty($manifest->name) || empty($manifest->author) || empty($manifest->version))
fatal_lang_error('fatal_not_valid_plugin', false);
// Since we might use this in a few places...
$manifest_id = (string) $manifest['id'];
// Already installed? Or another with the same id?
if (in_array($_GET['plugin'], $context['enabled_plugins']))
fatal_lang_error('fatal_already_enabled', false);
if (isset($context['enabled_plugins'][$manifest_id]))
fatal_lang_error('fatal_duplicate_id', false);
// OK, so we need to go through and validate that we have everything we need.
if (!empty($manifest->{'min-versions'}))
{
$min_versions = testRequiredVersions($manifest->{'min-versions'});
foreach (array('php', 'mysql') as $test)
if (isset($min_versions[$test]))
fatal_lang_error('fatal_install_error_min' . $test, false, $min_versions[$test]);
}
// Required functions?
if (!empty($manifest->{'required-functions'}))
{
$required_functions = testRequiredFunctions($manifest->{'required-functions'});
if (!empty($required_functions))
fatal_lang_error('fatal_install_error_reqfunc', false, westr::htmlspecialchars(implode(', ', $required_functions)));
}
// Does the plugin require maintenance mode?
if ($maintenance == 0)
{
$maint = get_maint_requirements($manifest);
if (!empty($maint) && in_array('enable', $maint))
fatal_lang_error('fatal_install_error_maint_mode', false);
}
// Hooks associated with this plugin.
$hooks_required = array();
$hook_data = array();
$optional_hooks = array(
'function' => array(),
'language' => array(),
);
if (!empty($manifest->hooks))
{
$hooks_listed = $manifest->hooks->children();
foreach ($hooks_listed as $each_hook)
{
$hook = $each_hook->getName();
$point = (string) $each_hook['point'];
if (($hook == 'function' || $hook == 'language') && !empty($point))
{
$hooks_required[$hook][] = $point;
$hook_data[$point][] = array(
'function' => $each_hook['function'],
'filename' => $each_hook['filename'],
'priority' => $hook == 'language' ? '' : '|' . (!empty($each_hook['priority']) ? min(max((int) $each_hook['priority'], 1), 100) : 50), // Language hooks do not need priority.
);
if (!empty($each_hook['optional']) && $each_hook['optional'] == 'yes')
$optional_hooks[$hook][] = $point;
}
}
}
// Now we have a list of the hooks this plugin needs. Are they all accounted for?
$hooks_missing = array();
$hooks_available = knownHooks();
$hooks_provided = array();
// Technically, a plugin can also call its own hooks.
if (!empty($manifest->hooks) && !empty($manifest->hooks->provides))
foreach ($manifest->hooks->provides->hook as $provided)
{
$attrs = $provided->attributes();
$hooks_available[(string) $attrs['type']][] = (string) $provided;
$hooks_provided[(string) $attrs['type']][] = (string) $provided;
}
// Add all the other hooks available
foreach ($context['enabled_plugins'] as $plugin)
{
$plugin = unserialize($settings['plugin_' . $plugin]);
foreach ($plugin['provides'] as $hook_type => $hooks)
foreach ($hooks as $hook)
$hooks_available[$hook_type][] = $hook;
}
foreach ($hooks_required as $hook_type => $hook_list)
{
if (empty($hook_list))
continue;
$hooks_missing[$hook_type] = array_diff($hook_list, $hooks_available[$hook_type], $optional_hooks[$hook_type]);
if (empty($hooks_missing[$hook_type]))
unset($hooks_missing[$hook_type]);
}
// !!! Check other plugins.
// So, any missing hooks?
$missing_hooks_flatten = array();
foreach ($hooks_missing as $hook_type => $hook_list)
$missing_hooks_flatten = array_merge($missing_hooks_flatten, $hook_list);
if (!empty($missing_hooks_flatten))
fatal_lang_error('fatal_install_error_missinghook', false, westr::htmlspecialchars(implode(', ', $missing_hooks_flatten)));
// Add this point, we appear to have everything we need, so let's start committing things.
// Database changes
if (!empty($manifest->database))
{
$valid_types = array('tinyint', 'smallint', 'mediumint', 'int', 'bigint', 'float', 'real', 'double', 'text', 'mediumtext', 'char', 'varchar', 'set', 'enum', 'date', 'datetime');
$int_types = array('tinyint', 'smallint', 'mediumint', 'int', 'bigint');
$float_types = array('float', 'real', 'double');
loadSource('Class-DBHelper');
$new_tables = $new_columns = $new_indexes = array();
$existing_columns = $existing_indexes = array();
$existing_tables = wedb::list_tables();
// First, pass through and collate a list of tables, columns and indexes that we are expecting to deal with. That way we know what we're going to have to query for.
if (!empty($manifest->database->tables))
{
foreach ($manifest->database->tables->table as $table)
{
$this_table = array(
'name' => (string) $table['name'],
'if-exists' => (string) $table['if-exists'],
'columns' => array(),
'indexes' => array(),
);
// Basic formalities.
if (empty($this_table['name']) || ($this_table['if-exists'] != 'update' && $this_table['if-exists'] != 'ignore') || empty($table->columns))
continue;
foreach ($table->columns->column as $column)
{
// Like most things with SimpleXML, we just try to get everything, then make sense of it after. Note that you can call for an attribute even if it isn't stated, and no error will result.
$this_col = array(
'name' => (string) $column['name'],
'type' => (string) $column['type'],
'size' => (string) $column['size'],
'null' => (string) $column['null'],
'values' => (string) $column['values'], // For SET and ENUM types.
'auto' => (string) $column['autoincrement'],
'unsigned' => (string) $column['unsigned'],
'default' => (string) $column['default'],
);
if (empty($this_col['name']) || !in_array($this_col['type'], $valid_types))
continue;
$this_col['null'] = $this_col['null'] == 'yes'; // Columns should be NOT NULL unless specifically needed as such.
$this_col['auto'] = $this_col['auto'] == 'yes'; // The column should not be auto-increment unless specifically needed as such.
$this_col['unsigned'] = $this_col['unsigned'] != 'no'; // Columns should be unsigned where possible.
// Apply some type-specific rules before doing something clever.
if (in_array($this_col['type'], $int_types))
{
// Int columns can be auto inc, can be unsigned etc. Just needs to have an integer default, or expressly not specify one.
if ($this_col['default'] == '')
unset($this_col['default']);
else
$this_col['default'] = (int) $this_col['default'];
}
elseif (in_array($this_col['type'], $float_types))
{
// Float columns, like int columns, have to have a meaningful default. But they can't be auto inc.
if ($this_col['default'] == '')
unset($this_col['default']);
else
$this_col['default'] = (float) $this_col['default'];
$this_col['auto'] = false;
}
elseif ($this_col['type'] == 'text' || $this_col['type'] == 'mediumtext')
{
// Block text columns can't have a default, be auto inc, or be unsigned.
unset($this_col['auto'], $this_col['unsigned'], $this_col['default']);
}
elseif ($this_col['type'] == 'date')
{
// Date columns can have a default, but can't be auto inc or unsigned.
unset($this_col['auto'], $this_col['unsigned']);
// Check the date is meaningful.
if (empty($this_col['default']) || !preg_match('~^[0-9]{4}\-(0[1-9]|1[0-2])\-(0[1-9]|[12][0-9]|3[0-2])$~', $this_col['default']))
unset($this_col['default']);
}
elseif ($this_col['type'] == 'datetime')
{
// Datetime columns can have a default, but can't be auto inc or unsigned.
unset($this_col['auto'], $this_col['unsigned']);
// Check the date is meaningful.
if (empty($this_col['default']) || !preg_match('~^[0-9]{4}\-(0[1-9]|1[0-2])\-(0[1-9]|[12][0-9]|3[0-2]) ([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$~', $this_col['default']))
unset($this_col['default']);
}
// This applies to everything but set and enum: get rid of the values. If it IS set or enum, check it does have values.
if ($this_col['type'] != 'set' && $this_col['type'] != 'enum')
unset($this_col['values']);
else
{
unset($this_col['auto'], $this_col['unsigned']);
if (empty($this_col['default']) && !isset($column['default']))
unset($this_col['default']);
if (strpos($this_col['values'], ',') === false)
continue;
}
$this_table['columns'][] = $this_col;
}
foreach ($table->index as $index)
{
$this_index = array(
'type' => strtolower((string) $index['type']),
'name' => (string) $index['name'],
'columns' => array(),
);
foreach ($index->field as $index_field)
$this_index['columns'][] = (string) $index_field[0];
if (!empty($this_index['columns']))
$this_table['indexes'][] = $this_index;
}
if (empty($this_table['columns']))
continue;
wedb::create_table($this_table['name'], $this_table['columns'], $this_table['indexes'], $this_table['if-exists']);
}
}
// Other database changes: adding new columns
if (!empty($manifest->database->columns))
{
foreach ($manifest->database->columns->column as $column)
{
// Like most things with SimpleXML, we just try to get everything, then make sense of it after. Note that you can call for an attribute even if it isn't stated, and no error will result.
$this_col = array(
'name' => (string) $column['name'],
'type' => (string) $column['type'],
'size' => (string) $column['size'],
'null' => (string) $column['null'],
'values' => (string) $column['values'], // For SET and ENUM types.
'auto' => (string) $column['autoincrement'],
'unsigned' => (string) $column['unsigned'],
'default' => (string) $column['default'],
);
$table_name = (string) $column['table'];
if (empty($this_col['name']) || empty($table_name) || !in_array($this_col['type'], $valid_types))
continue;
$this_col['null'] = $this_col['null'] == 'yes'; // Columns should be NOT NULL unless specifically needed as such.
$this_col['auto'] = $this_col['auto'] == 'yes'; // The column should not be auto-increment unless specifically needed as such.
$this_col['unsigned'] = $this_col['unsigned'] != 'no'; // Columns should be unsigned where possible.
// Apply some type-specific rules before doing something clever.
if (in_array($this_col['type'], $int_types))
{
// Int columns can be auto inc, can be unsigned etc. Just needs to have an integer default, or expressly not specify one.
if ($this_col['default'] == '')
unset($this_col['default']);
else
$this_col['default'] = (int) $this_col['default'];
}
elseif (in_array($this_col['type'], $float_types))
{
// Float columns, like int columns, have to have a meaningful default. But they can't be auto inc.
if ($this_col['default'] == '')
unset($this_col['default']);
else
$this_col['default'] = (float) $this_col['default'];
$this_col['auto'] = false;
}
elseif ($this_col['type'] == 'text' || $this_col['type'] == 'mediumtext')
{
// Block text columns can't have a default, be auto inc, or be unsigned.
unset($this_col['auto'], $this_col['unsigned'], $this_col['default']);
}
elseif ($this_col['type'] == 'date')
{
// Date columns can have a default, but can't be auto inc or unsigned.
unset($this_col['auto'], $this_col['unsigned']);
// Check the date is meaningful.
if (empty($this_col['default']) || !preg_match('~^[0-9]{4}\-(0[1-9]|1[0-2])\-(0[1-9]|[12][0-9]|3[0-2])$~', $this_col['default']))
unset($this_col['default']);
}
elseif ($this_col['type'] == 'datetime')
{
// Datetime columns can have a default, but can't be auto inc or unsigned.
unset($this_col['auto'], $this_col['unsigned']);
// Check the date is meaningful.
if (empty($this_col['default']) || !preg_match('~^[0-9]{4}\-(0[1-9]|1[0-2])\-(0[1-9]|[12][0-9]|3[0-2]) ([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$~', $this_col['default']))
unset($this_col['default']);
}
// This applies to everything but set and enum: get rid of the values. If it IS set or enum, check it does have values.
if ($this_col['type'] != 'set' && $this_col['type'] != 'enum')
unset($this_col['values']);
else
{
unset($this_col['auto'], $this_col['unsigned']);
if (empty($this_col['default']) && !isset($column['default']))
unset($this_col['default']);
if (strpos($this_col['values'], ',') === false)
continue;
}
// There's really no point in being clever and trying the work that's in create_table.
// You can't call create_table on the core tables, and add_column already checks to see if it exists and promptly updates if not.
wedb::add_column($table_name, $this_col, 'update');
}
}
}
// Database changes: enable script
if (!empty($manifest->database->scripts->enable))
executePluginScript('enable', (string) $manifest->database->scripts->enable);
// Adding settings
if (!empty($manifest->settings))
{
$new_settings = array();
foreach ($manifest->settings->setting as $setting)
{
$setting_name = (string) $setting['name'];
$setting_default = (string) $setting['default'];
// Add it to the list to be updated if we haven't already got this one, and it's not empty, as updateSettings won't set actually-empty ones.
if (!empty($setting_name) && $setting_default != '' && !isset($settings[$setting_name]))
$new_settings[$setting_name] = $setting_default;
}
if (!empty($new_settings))
updateSettings($new_settings);
}
// Adding scheduled tasks
if (!empty($manifest->scheduledtasks))
{
$new_tasks = array();
$valid_freq = array('minute', 'hour', 'day', 'week');
foreach ($manifest->scheduledtasks->task as $task)
{
$this_task = array(
'runevery' => (int) $task['runevery'],
'runfreq' => (string) $task['runfreq'],
'name' => (string) $task['name'],
'file' => (string) $task['file'],
);
// Validate the task options. Note that we don't have to have a file.
if ($this_task['runevery'] < 1 || !in_array($this_task['runfreq'], $valid_freq) || empty($this_task['name']))
continue;
// If there's a filename, we have to fix its path
if (!empty($this_task['file']))
$this_task['file'] = trim('plugin;' . $manifest_id . ';' . $this_task['file']);
$new_tasks[] = $this_task;
}
// Any to do?
if (!empty($new_tasks))
{
$inserts = array();
$next = strtotime('tomorrow');
foreach ($new_tasks as $task)
$inserts[] = array(
$next, // next_time
0, // time_offset
$task['runevery'], // time_regularity
$task['runfreq'][0], // time_unit; it's only m, h, d, w for the table
0, // disabled
$task['name'], // task
$task['file'], // sourcefile
);
wesql::insert('replace',
'{db_prefix}scheduled_tasks',
array(
'next_time' => 'int',
'time_offset' => 'int',
'time_regularity' => 'int',
'time_unit' => 'string',
'disabled' => 'int',
'task' => 'string',
'sourcefile' => 'string',
),
$inserts
);
}
}
// Adding any bbcodes indicated in the plugin manifest.
if (!empty($manifest->bbcodes))
{
$new_bbcode = array();
$valid_types = array('parsed', 'unparsed_equals', 'parsed_equals', 'unparsed_content', 'closed', 'unparsed_commas', 'unparsed_commas_content', 'unparsed_equals_content');
$valid_quoted = array('none', 'optional', 'required');
$valid_trim = array('none', 'inside', 'outside', 'both');
foreach ($manifest->bbcodes->bbcode as $bbcode)
{
// bbcode must declare itself as having a tag and what type of tag it is
if (empty($bbcode['tag']) || empty($bbcode['type']))
continue;
$this_bbcode = array(
'tag' => (string) $bbcode['tag'],
'len' => strlen((string) $bbcode['tag']),
'bbctype' => (string) $bbcode['type'],
'before_code' => !empty($bbcode->{'before-code'}) ? (string) $bbcode->{'before-code'} : '',
'after_code' => !empty($bbcode->{'after-code'}) ? (string) $bbcode->{'after-code'} : '',
'content' => !empty($bbcode->content) ? (string) $bbcode->content : '',
'disabled_before' => !empty($bbcode->disabled->{'before-code'}) ? (string) $bbcode->disabled->{'before-code'} : '',
'disabled_after' => !empty($bbcode->disabled->{'after-code'}) ? (string) $bbcode->disabled->{'after-code'} : '',
'disabled_content' => !empty($bbcode->disabled->content) ? (string) $bbcode->disabled->content : '',
'block_level' => !empty($bbcode['block-level']) && ((string) $bbcode['block-level'] == 'yes') ? 1 : 0,
'test' => !empty($bbcode->test) ? (string) $bbcode->test : '',
'validate_func' => !empty($bbcode->{'validate-func'}) ? (string) $bbcode->{'validate-func'} : '',
'disallow_children' => '',
'require_parents' => '',
'require_children' => '',
'parsed_tags_allowed' => '',
'quoted' => !empty($bbcode['quoted']) ? (string) $bbcode['quoted'] : 'none',
'params' => '',
'trim_wspace' => !empty($bbcode['trim_wspace']) ? (string) $bbcode['trim_wspace'] : 'none',
'id_plugin' => $manifest_id,
);
// Checking the type and some other stuff. Doing it here after we've typecast them. It won't always work cleanly otherwise.
if (!in_array($this_bbcode['bbctype'], $valid_types) || !in_array($this_bbcode['quoted'], $valid_quoted) || !in_array($this_bbcode['trim_wspace'], $valid_trim))
continue;
// OK, now we need to parse the remaining content that we couldn't have done in the above because of our nice XML structure.
if (!empty($bbcode->{'disallow-children'}))
{
$temp = array();
foreach ($bbcode->{'disallow-children'}->child as $child)
$temp[] = (string) $child;
if (!empty($temp))
$this_bbcode['disallow_children'] = implode(',', $temp);
}
if (!empty($bbcode->{'require-parents'}))
{
$temp = array();
foreach ($bbcode->{'require-parents'}->{'parent-tag'} as $parent)
$temp[] = (string) $parent;
if (!empty($temp))
$this_bbcode['require_parents'] = implode(',', $temp);
}
if (!empty($bbcode->{'require-children'}))
{
$temp = array();
foreach ($bbcode->{'require-children'}->child as $child)
$temp[] = (string) $child;
if (!empty($temp))
$this_bbcode['require_children'] = implode(',', $temp);
}
if (!empty($bbcode->{'parsed-tags-allowed'}))
{
$temp = array();
foreach ($bbcode->{'parsed-tags-allowed'}->bbc as $tag)
$temp[] = (string) $tag;
if (!empty($temp))
$this_bbcode['parsed_tags_allowed'] = implode(',', $temp);
}
// Lastly, parameters
if (!empty($bbcode->params))
{
$params = array();
foreach ($bbcode->params->param as $param)
{
// Collect parameters. Note that we don't need to store stuff if it is default values.
if (empty($param['name']))
continue;
$this_param = array();
// Typically a parameter will not require quotes, and will not be optional.
if (!empty($param['quoted']) && (string) $param['quoted'] == 'yes')
$this_param['quoted'] = true;
if (!empty($param['optional']) && (string) $param['optional'] == 'yes')
$this_param['optional'] = true;
// Now get the other stuff.
if (!empty($param->match))
$this_param['match'] = (string) $param->match;
if (!empty($param->validate))
$this_param['validate'] = (string) $param->validate;
if (!empty($param->value) && empty($this_param['validate']))
$this_param['value'] = (string) $param->value; // Can't use these two together.
if (!empty($this_param))
$params[(string) $param['name']] = $this_param;
}
if (!empty($params))
$this_bbcode['params'] = serialize($params);
}
// Now, before we commit this one, we need to make some sense of the type of bbcode because different types require different content.
// A lot of the simplest rules can be dealt with by simply checking for certain content that's specific to each type and if found, excluding it.
// And checking for things that must be provided. Note that I'm leaving it split in case anything changes in the future.
$rules = array();
switch ($this_bbcode['bbctype'])
{
case 'parsed':
$rules = array(
'require' => array('before_code', 'after_code'),
'disallow' => array('content', 'validate_func', 'parsed_tags_allowed'),
);
break;
case 'unparsed_equals':
$rules = array(
'require' => array('before_code', 'after_code'),
'disallow' => array('content', 'parsed_tags_allowed'),
);
break;
case 'parsed_equals':
$rules = array(
'require' => array('before_code', 'after_code'),
'disallow' => array('content'),
);
break;
case 'unparsed_content':
$rules = array(
'require' => array('content'),
'disallow' => array('before_code', 'after_code', 'parsed_tags_allowed'),
);
break;
case 'closed':
if ($this_bbcode['trim_wspace'] == 'inside' || $this_bbcode['trim_wspace'] == 'both')
continue;
$rules = array(
'require' => array('content'),
'disallow' => array('before_code', 'after_code', 'test', 'params', 'disallow_children', 'require_children', 'require_parents', 'validate_func', 'parsed_tags_allowed'),
);
break;
case 'unparsed_commas':
$rules = array(
'require' => array('before_code', 'after_code'),
'disallow' => array('content', 'parsed_tags_allowed'),
);
break;
case 'unparsed_commas_content':
$rules = array(
'require' => array('content'),
'disallow' => array('before_code', 'after_code', 'parsed_tags_allowed'),
);
break;
case 'unparsed_equals_content':
$rules = array(
'require' => array('content'),
'disallow' => array('before_code', 'after_code', 'parsed_tags_allowed'),
);
break;
}
if (!empty($rules['disallow']))
{
$found = false;
foreach ($rules['disallow'] as $item)
if (!empty($this_bbcode[$item]))
{
$found = true;
break;
}
if ($found)
continue;
}
if (!empty($rules['require']))
{
$found = true;
foreach ($rules['require'] as $item)
if (empty($this_bbcode[$item]))
{
$found = false;
break;
}
if (!$found)
continue;
}
// Other rules
// Can't specify a quoting-parameters type for things that don't support quotable parameters.
if ($this_bbcode['quoted'] != 'none' && $this_bbcode['bbctype'] != 'unparsed_equals' && $this_bbcode['bbctype'] != 'parsed_equals')
continue;
$new_bbcode[] = $this_bbcode;
}
// Any to do?
if (!empty($new_bbcode))
{
wesql::insert('replace',
'{db_prefix}bbcode',
array(
'tag' => 'string',
'len' => 'int',
'bbctype' => 'string',
'before_code' => 'string',
'after_code' => 'string',
'content' => 'string',
'disabled_before' => 'string',
'disabled_after' => 'string',
'disabled_content' => 'string',
'block_level' => 'string',
'test' => 'string',
'validate_func' => 'string',
'disallow_children' => 'string',
'require_parents' => 'string',
'require_children' => 'string',
'parsed_tags_allowed' => 'string',
'quoted' => 'string',
'params' => 'string',
'trim_wspace' => 'string',
'id_plugin' => 'string',
),