-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMediaWiki.psm1
More file actions
8764 lines (6926 loc) · 241 KB
/
MediaWiki.psm1
File metadata and controls
8764 lines (6926 loc) · 241 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
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
<#
.SYNOPSIS
PowerShell module for interfacing with MediaWiki API.
.DESCRIPTION
PowerShell module for interfacing with a MediaWiki API endpoint.
.NOTES
Was design and tested towards the PCGamingWiki endpoint, so _a lot_
of assumptions stem from that, such as supported properties and whatnot.
Be sure to add/adjust if needed!
#>
Write-Host ""
Write-Host "---------------------------------------------------------------------------" -ForegroundColor Yellow
Write-Host ""
Write-Host "This PowerShell module allows you to connect to a MediaWiki API endpoint." -ForegroundColor Yellow
Write-Host ""
Write-Host " To establish a new connection: " -ForegroundColor Yellow -NoNewline
Write-Host "Connect-MWSession" -ForegroundColor DarkGreen
Write-Host " To use/setup a persistent config: " -ForegroundColor Yellow -NoNewline
Write-Host "Connect-MWSession -Persistent" -ForegroundColor DarkYellow
Write-Host " To log in anonymously as a guest: " -ForegroundColor Yellow -NoNewline
Write-Host "Connect-MWSession -Guest" -ForegroundColor DarkCyan
Write-Host " To disconnect the active session: " -ForegroundColor Yellow -NoNewline
Write-Host "Disconnect-MWSession" -ForegroundColor Gray
Write-Host " To reset the persistent config: " -ForegroundColor Yellow -NoNewline
Write-Host "Connect-MWSession -Reset" -ForegroundColor DarkGray
Write-Host ""
Write-Host "---------------------------------------------------------------------------" -ForegroundColor Yellow
Write-Host ""
# --------------------------------------------------------------------------------------- #
# #
# NOTEs #
# #
# --------------------------------------------------------------------------------------- #
# - HashTable is used for the pure JSON responses, while PSObject is used for the
# "end-user facing" objects.
#
# * ConvertFrom-JsonToHashtable handles all of the raw JSON objects.
# * ConvertFrom-HashtableToPSObject handles all of the user-facing objects, and
# renames the properties to PascalCase.
# - The MediaWiki API 'limit' parameter can at times be misleading as it does not ensure
# that said amount of result is actually returned... So if you use a limit of say 100,
# you may only get 69 results back, meaning you need to then make an additional
# request just to attempt to get the missing requests... As such, it is easier to
# request the maximum limit and then throw away any unused or unneeded trailing
# entries...
#
# * This also means the module is partially "wasteful" in that some cmdlets requests
# _all_ of the data, _and then_ filters upon it. It makes for a simpler design
# to implement, and reduces a huge amount of unnecessary repeated calls.
# - Supported parameter values can be retrieved through Get-MWAPIModule, e.g.
# (Get-MWAPIModule -Properties parse).paraminfo.modules.parameters | where name -eq 'prop').type
#
# Long-term potential TODO (lol); change $Properties and the like to be based on values
# obtained through Get-MWAPIModule...
# --------------------------------------------------------------------------------------- #
# #
# GLOBAL STUFF #
# #
# --------------------------------------------------------------------------------------- #
# Enum used to indicate watchlist parameter value for cmdlets
enum Watchlist
{
NoChange
Preferences
Unwatch
Watch
}
# Enum used to indicate search type for Find-MWPage
enum SearchType
{
NearMatch
Text
Title
}
# Enum used to indicate token type for Get-MWToken
enum TokenType
{
None
CSRF
Patrol
Rollback
UserRights
Watch
}
# Unset all variables when the module is being removed from the session
$MyInvocation.MyCommand.ScriptBlock.Module.OnRemove = { Clear-MWSession }
# Global configurations
$script:ProgressPreference = 'SilentlyContinue' # Suppress progress bar (speeds up Invoke-WebRequest by a ton)
# Global variable to hold the web session
$global:MWSession
# Script variable to indicate the location of the saved config file
$script:ConfigFileName = $env:LOCALAPPDATA + '\PowerShell\MediaWiki\config.json'
# Script variables used internally during runtime
$script:MWSessionGuest = $false
$script:MWSessionBot = $false
$script:MWTokens = @{
CreateAccount = $null
CSRF = $null # Cross-site request forgery (CSRF)
Patrol = $null
Rollback = $null # Rollback token
UserRights = $null
Watch = $null
}
$script:Config = @{
Protocol = $null
Wiki = $null
API = $null
URI = $null
Persistent = $false
}
$script:Cache = @{
SiteInfo = $null
UserInfo = $null
Namespaces = $null
RestrictionTypes = @( )
RestrictionLevels = @( )
}
# PowerShell prefers using pascal case wherever is possible so let us rename as many property names as possible.
# This can potentially cause issues when something is renamed (e.g. Anon -> Anonymous)
$script:PropertyNamePascal = @{
<# API #>
batchcomplete = 'BatchComplete'
query = 'Query'
limits = 'Limits'
duplicatefiles = 'DuplicateFiles'
allpages = 'AllPages'
allimages = 'AllImages'
pages = 'Pages'
parse = 'Parse'
warnings = 'Warnings'
errors = 'Errors'
code = 'Code'
module = 'Module'
docref = 'DocumentationReference'
<# Need to be retained (for now) #>
continue = 'continue'
apcontinue = 'apcontinue'
gapcontinue = 'gapcontinue'
aicontinue = 'aicontinue'
gaicontinue = 'gaicontinue'
dfcontinue = 'dfcontinue'
sroffset = 'sroffset'
<# Site Info #>
serverinfo = 'ServerInfo'
dbrepllag = 'DatabaseReplicationLag'
host = 'Host'
lag = 'Lag'
defaultoptions = 'DefaultOptions'
'email-allow-new-users' = 'AllowMailFromNewUsers'
# usebetatoolbar = 'UseEnhancedToolbar' # WikiEditor 2010: Enhanced editing toolbar
#'usebetatoolbar-cgd' = 'UseEnhancedToolbarDialogs' # WikiEditor 2010: Enhanced toolbar dialogs/link and table wizards
extensions = 'Extensions'
namemsg = 'NameMessage'
credits = 'Credits'
descriptionmsg = 'DescriptionMessage'
license = 'License'
'license-name' = 'LicenseName'
version = 'Version'
'vcs-date' = 'VcsDate'
'vcs-system' = 'VcsSystem'
'vcs-version' = 'VcsVersion'
'vcs-url' = 'VcsUrl'
extensiontags = 'ExtensionTags'
fileextensions = 'FileExtensions'
ext = 'Ext'
functionhooks = 'FunctionHooks'
general = 'General'
allcentralidlookupproviders = 'AllCentralIDLookupProviders'
allunicodefixes = 'AllUnicodeFixes'
articlepath = 'ArticlePath'
base = 'Base'
case = 'Case'
categorycollation = 'CategoryCollation'
centralidlookupprovider = 'CentralIDLookupProvider'
citeresponsivereferences = 'CiteResponsiveReferences'
dbtype = 'DatabaseType'
dbversion = 'DatabaseVersion'
fallback = 'Fallback'
fallback8bitEncoding = 'Fallback8bitEncoding'
favicon = 'FavoriteIcon'
fixarabicunicode = 'FixArabicUnicode'
fixmalayalamunicode = 'FixMalayalamUnicode'
galleryoptions = 'GalleryOptions'
generator = 'Generator'
imagelimits = 'ImageLimits'
imagewhitelistenabled = 'ImageWhitelistEnabled'
interwikimagic = 'InterwikiMagic'
invalidusernamechars = 'InvalidUsernameCharacters'
lang = 'Language'
langconversion = 'LanguageConversion'
legaltitlechars = 'LegalTitleCharacters'
linkprefix = 'LinkPrefix'
linkprefixcharset = 'LinkPrefixCharacterSet'
linktrail = 'LinkTrail'
logo = 'Logo'
magiclinks = 'MagicLinks'
mainpage = 'MainPage'
mainpageisdomainroot = 'MainPageIsDomainRoot'
maxarticlesize = 'MaximumArticleSize'
maxuploadsize = 'MaximumUploadSize'
minuploadchunksize = 'MinimumUploadChunkSize'
misermode = 'MiserMode'
phpsapi = 'PhpServerAPI'
phpversion = 'PhpVersion'
readonly = 'ReadOnly'
rtl = 'RightToLeft'
script = 'Script'
scriptpath = 'ScriptPath'
server = 'Server'
servername = 'ServerName'
sitename = 'SiteName'
thumblimits = 'ThumbnailLimits'
time = 'Time'
timeoffset = 'TimeOffset'
timezone = 'Timezone'
titleconversion = 'TitleConversion'
uploadsenabled = 'UploadsEnabled'
variantarticlepath = 'VariantArticlePath'
wikiid = 'WikiID'
writeapi = 'WriteAPI'
interwikimap = 'InterwikiMap'
protorel = 'ProtocolRelative'
libraries = 'Libraries'
magicwords = 'MagicWords'
'case-sensitive' = 'CaseSensitive'
protocols = 'Protocols'
rightsinfo = 'RightsInfo'
skins = 'Skins'
default = 'Default'
unusable = 'Unusable'
showhooks = 'ShowHooks'
subscribers = 'Subscribers'
languages = 'Languages'
bcp47 = 'Bcp47'
languagevariants = 'LanguageVariants'
fallbacks = 'Fallbacks'
statistics = 'Statistics'
activeusers = 'ActiveUsers'
admins = 'Admins'
articles = 'Articles'
edits = 'Edits'
jobs = 'Jobs'
users = 'Users'
uploaddialog = 'UploadDialog'
fields = 'Fields'
format = 'Format'
filepage = 'FilePage'
ownwork = 'IsOwnWork'
uncategorized = 'Uncategorized'
licensemessages = 'LicenseMessages'
foreign = 'Foreign'
usergroups = 'UserGroups'
variables = 'Variables'
name = 'Name'
author = 'Author'
ISBN = 'ISBN'
PMID = 'PMID'
RFC = 'RFC'
captionLength = 'CaptionLength'
height = 'Height'
imageHeight = 'ImageHeight'
width = 'Width'
imageWidth = 'ImageWidth'
imagesPerRow = 'ImagesPerRow'
mode = 'Mode'
showBytes = 'ShowBytes'
showDimensions = 'ShowDimensions'
<# Aliases #>
alias = 'Alias'
aliases = 'Aliases'
namespacealiases = 'NamespaceAliases'
specialpagealiases = 'SpecialPageAliases'
<# Namespaces #>
namespaces = 'Namespaces'
canonical = 'CanonicalName'
nonincludable = 'IsNonIncludable' # Renamed
subpages = 'IsSubPagesAllowed' # Renamed
defaultcontentmodel = 'DefaultContentModel'
namespaceprotection = 'NamespaceProtection'
<# Protection #>
restrictions = 'Restrictions'
cascadinglevels = 'CascadingLevels'
levels = 'Levels'
semiprotectedlevels = 'SemiProtectedLevels'
types = 'Types'
<# User Info #>
userinfo = 'UserInfo'
anon = 'Anonymous' # Renamed
messages = 'Messages'
unreadcount = 'UnreadCount'
editcount = 'EditCount'
latestcontrib = 'LatestContribution' # Renamed
groups = 'Groups'
rights = 'Rights'
# Rate Limits
ratelimits = 'RateLimits'
changeemail = 'ChangeEmail'
confirmemail = 'ConfirmEmail'
changetag = 'ChangeTag'
editcontentmodel = 'EditContentModel'
emailuser = 'EmailUser'
mailpassword = 'MailPassword'
move = 'Move'
purge = 'Purge'
linkpurge = 'LinkPurge'
renderfile = 'RenderFile'
'renderfile-nonstandard' = 'RenderFileNonStandard'
rollback = 'Rollback'
stashedit = 'StashEdit'
'thanks-notification' = 'ThanksNotification' # Renamed
upload = 'Upload'
user = 'User'
ip = 'IP'
hits = 'Hits'
seconds = 'Seconds'
attachedlocal = 'AttachedLocal'
local = 'Local'
centralids = 'CentralIDs'
changeablegroups = 'ChangeableGroups'
add = 'Add'
'add-self' = 'AddSelf' # Renamed
remove = 'Remove'
'remove-self' = 'RemoveSelf' # Renamed
email = 'Email'
groupmemberships = 'GroupMemberships'
implicitgroups = 'ImplicitGroups'
options = 'Options' # Options are as varied as the extesions installed, so only pascal case some of them...
# User Profile
fancysig = 'FancySig' # If User uses a custom (raw) signature (0 or 1). If user has specified a custom sig, the actual text of the signature is in the nickname option.
nickname = 'Nickname' # Custom signature
enotifwatchlistpages = 'ENotifWatchlistPages'
enotifusertalkpages = 'ENotifUserTalkPages'
enotifminoredits = 'ENotifMinorEdits'
enotifrevealaddr = 'ENotifRevealAddr'
gender = 'Gender'
realname = 'RealName'
language = 'Language'
disablemail = 'DisableMail'
# Skin
skin = 'Skin'
# Files
imagesize = 'ImageSize'
thumbsize = 'Thumbsize'
# Date and Time
date = 'Date'
timecorrection = 'TimeCorrection'
# Editing
editfont = 'EditFont'
editondblclick = 'EditOnDblClick'
editsectiononrightclick = 'EditSectionOnRightClick'
forceeditsummary = 'ForceEditSummary'
previewonfirst = 'PreviewOnFirst'
previewontop = 'PreviewOnTop'
minordefault = 'MinorDefault'
useeditwarning = 'UseEditWarning'
uselivepreview = 'UseLivePreview'
# Recent Changes
rcdays = 'RcDays'
rclimit = 'RcLimit'
hidecategorization = 'HideCategorization'
hideminor = 'HideMinor'
hidepatrolled = 'HidePatrolled'
newpageshidepatrolled = 'NewPagesHidePatrolled'
shownumberswatching = 'ShowNumbersWatching'
usenewrc = 'UseNewRc'
# Watchlist
extendwatchlist = 'ExtendWatchlist' # Expand watchlist to show all applicable changes
watchcreations = 'WatchCreations'
watchdefault = 'WatchDefault'
watchdeletion = 'WatchDeletion'
watchlistdays = 'WatchlistDays'
watchlisthideanons = 'WatchlistHideAnons'
watchlisthidebots = 'WatchlistHideBots'
watchlisthidecategorization = 'WatchlistHideCategorization'
watchlisthideliu = 'WatchlistHideLIU' # Hide Logged In User
watchlisthideminor = 'WatchlistHideMinor'
watchlisthideown = 'WatchlistHideOwn'
watchlisthidepatrolled = 'Watchlist'
watchlistreloadautomatically= 'WatchlistReloadAutomatically'
watchlistunwatchlinks = 'WatchlistUnwatchLinks'
watchmoves = 'WatchMoves'
watchrollback = 'WatchRollback'
watchuploads = 'WatchUploads'
wllimit = 'WlLimit' # Number of edits to show in expanded watchlist (if 'extendwatchlist' == 1)
# Misc
ccmeonemails = 'CCMeOnEmails'
diffonly = 'DiffOnly'
norollbackdiff = 'NoRollbackDiff'
numberheadings = 'NumberHeadings'
prefershttps = 'PrefersHTTPS'
requireemail = 'RequireEmail'
showhiddencats = 'ShowHiddenCats'
showrollbackconfirmation = 'ShowRollbackConfirmation'
stubthreshold = 'StubThreshold'
underline = 'Underline'
<# Users #>
attachedwiki = 'AttachedWiki'
emailable = 'Emailable'
expiry = 'Expiry'
group = 'Group'
registration = 'Registration'
<# Pages #>
id = 'ID' # Potential conflict with PageID ?
ns = 'Namespace' # Renamed
pageid = 'ID' # Renamed
title = 'Name' # Renamed
displaytitle = 'DisplayTitle'
touched = 'LastModified' # Renamed
revid = 'RevisionID' # Renamed
lastrevid = 'LastRevisionID' # Renamed
length = 'Length'
links = 'Links'
externallinks = 'ExternalLinks'
images = 'Images'
sections = 'Sections'
edit = 'Edit'
new = 'New'
exists = 'Exists'
redirect = 'Redirect'
missing = 'Missing'
toclevel = 'TocLevel'
anchor = 'Anchor'
byteoffset = 'ByteOffset'
fromtitle = 'FromTitle'
index = 'Index'
level = 'Level'
line = 'Line'
number = 'Number'
template = 'Template'
templates = 'Templates'
category = 'Category'
categories = 'Categories'
categorieshtml = 'CategoriesAsHtml' # Renamed
content = 'Content' # Dual-use! Content for pages, and "IsContentNamespace" for namespaces
contentmodel = 'ContentModel'
pagelanguage = 'PageLanguage'
pagelanguagedir = 'PageLanguageDirection' # Renamed
pagelanguagehtmlcode = 'PageLanguageHtmlCode'
<# Parse #>
jsconfigvars = 'JsConfigurationVariables'
encodedjsconfigvars = 'JsConfigurationVariablesAsJson' # Renamed
headhtml = 'HeadAsHtml' # Renamed
iwlinks = 'InterwikiLinks' # Renamed
indicators = 'Indicators'
prefix = 'Prefix'
url = 'Url'
langlinks = 'LanguageLinks' # Renamed
limitreportdata = 'LimitReportData'
limitreporthtml = 'LimitReportAsHtml'
modules = 'Modules'
modulescripts = 'ModuleScripts'
modulestyles = 'ModuleStyles'
parsedsummary = 'ParsedSummary'
parsetree = 'ParseTree'
parsewarnings = 'ParseWarnings'
properties = 'Properties'
text = 'Text' # Text / WikitextAsHtml
wikitext = 'Wikitext'
transcludedin = 'TranscludedIn'
<# Images #>
descriptionurl = 'DescriptionUrl'
imageinfo = 'ImageInfo'
imagerepository = 'ImageRepository'
bitdepth = 'BitDepth'
archivename = 'ArchiveName'
canonicaltitle = 'CanonicalName'
comment = 'Comment'
parsedcomment = 'ParsedComment'
metadata = 'Metadata'
commonmetadata = 'CommonMetadata'
hidden = 'Hidden'
source = 'Source'
value = 'Value'
html = 'Html'
mediatype = 'MediaType'
duration = 'Duration'
mime = 'MIME'
sha1 = 'SHA1'
userid = 'UserID'
badfile = 'BadFile'
# https://www.mediawiki.org/wiki/Extension:CommonsMetadata ?
extmetadata = 'ExtensionMetadata' # ExtendedMetadata? ExtensionMetadata? ExternalMetadata? ExtractedMetadata?
DateTime = 'DateTime'
ObjectName = 'ObjectName'
<# Listing #>
type = 'Type'
sortkey = 'SortKey'
sortkeyprefix = 'SortKeyPrefix'
<# Search #>
search = 'Search'
size = 'Size'
snippet = 'Snippet'
timestamp = 'Timestamp'
wordcount = 'WordCount'
searchinfo = 'SearchInfo'
totalhits = 'TotalHits'
<# Change Tags #>
active = 'Active'
defined = 'Defined'
description = 'Description'
displayname = 'DisplayName'
hitcount = 'HitCount'
<# Upload #>
result = 'Result'
filekey = 'FileKey'
sessionkey = 'SessionKey'
<# API Modules #>
classname = 'ClassName'
dynamicparameters = 'DynamicParameters'
examples = 'Examples'
helpurls = 'HelpUrls'
licenselink = 'LicenseLink'
licensetag = 'LicenseTag'
mustbeposted = 'MustBePosted'
parameters = 'Parameters'
allowsduplicates = 'AllowsDuplicates'
allspecifier = 'AllSpecifier'
deprecated = 'Deprecated'
deprecatedvalues = 'DeprecatedValues'
highlimit = 'HighLimit'
highmax = 'HighMax'
limit = 'Limit'
lowlimit = 'LowLimit'
max = 'Max'
min = 'Min'
multi = 'Multi'
required = 'Required'
sensitive = 'Sensitive'
subtypes = 'SubTypes'
tokentype = 'TokenType'
path = 'Path'
readrights = 'ReadRights'
info = 'Info'
internal = 'Internal'
extranamespaces = 'ExtraNamespaces'
slot = 'Slot'
sourcename = 'SourceName'
submodules = 'SubModules'
submoduleparamprefix = 'SubModuleParameterPrefix'
templatedparameters = 'TemplatedParameters'
templatevars = 'TemplateVariables'
values = 'Values'
writerights = 'WriteRights'
<# Debug #>
curtimestamp = 'ServerTimestamp' # Current server timestamp / Retrieved
<# Internals #>
NamespaceID = 'NamespaceID'
}
# --------------------------------------------------------------------------------------- #
# #
# HELPER CMDLETs #
# #
# --------------------------------------------------------------------------------------- #
#region Copy-Object
function Copy-Object
{
<#
.SYNOPSIS
Helper function to do a deep copy on input objects.
.DESCRIPTION
In various situations PowerShell can pass a reference to another object instead of
passing a copy of the object. This can result in situations where modifying the data
in a later function or call also modifies the original data. This helper function
works around the issue by forcing a deep copy of the input objects to ensure no
references to the original copy remain.
Note that depending on the complexity of the input object, this action can be slow
and should therefor only be used when necessary.
.PARAMETER InputObject
The input object to perform a deep copy of. The object will be traversed to the
depth specified by the -Depth parameter (default 100).
.PARAMETER Depth
The depth of the object to traverse when doing the deep copy. Defaults to 100.
.LINK
https://stackoverflow.com/a/57045268
.NOTES
Licensed by CC BY-SA 4.0
https://creativecommons.org/licenses/by-sa/4.0/
#>
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline)]
[Object[]]$InputObject,
[Parameter()]
[uint32] $Depth = 100
)
Begin { }
Process {
$Clones = ForEach ($Object in $InputObject) {
$Object | ConvertTo-Json -Compress -Depth $Depth | ConvertFrom-Json
}
return $Clones
}
End { }
}
#endregion
#region ConvertFrom-JsonToHashtable
<#
.SYNOPSIS
Helper function to take a JSON string and turn it into a hashtable
.DESCRIPTION
The ConvertFrom-Json method does not have the -AsHashtable switch in Windows PowerShell,
which makes it inconvenient to convert JSON to hashtable.
.LINK
https://github.com/abgox/ConvertFrom-JsonToHashtable
.NOTES
MIT License
Copyright (c) 2024-present abgox <https://github.com/abgox | https://gitee.com/abgox>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
#>
function ConvertFrom-JsonToHashtable
{
param (
[Parameter(ValueFromPipeline = $true)]
[string]$InputObject
)
$Results = [regex]::Matches($InputObject, '\s*"\s*"\s*:')
foreach ($Result in $Results)
{ $InputObject = $InputObject -replace $Result.Value, "`"empty_key_$([System.Guid]::NewGuid().Guid)`":" }
$InputObject = [regex]::Replace($InputObject, ",`n?(\s*`n)?\}", "}")
function ProcessArray ($Array)
{
$NestedArray = @()
foreach ($Item in $Array)
{
if ($Item -is [System.Collections.IEnumerable] -and $Item -isnot [string])
{ $NestedArray += , (ProcessArray $Item) }
elseif ($Item -is [System.Management.Automation.PSCustomObject])
{ $NestedArray += ConvertToHashtable $Item }
else
{ $NestedArray += $Item }
}
return , $NestedArray
}
function ConvertToHashtable ($Object)
{
$Hash = [ordered]@{}
if ($Object -is [System.Management.Automation.PSCustomObject])
{
foreach ($Property in $Object | Get-Member -MemberType Properties)
{
$Key = $Property.Name # Key
$Value = $Object.$Key # Value
# Handle array (preserve nested structure)
if ($Value -is [System.Collections.IEnumerable] -and $Value -isnot [string])
{ $Hash[[object] $Key] = ProcessArray $Value }
# Handle object
elseif ($Value -is [System.Management.Automation.PSCustomObject])
{ $Hash[[object] $Key] = ConvertToHashtable $Value }
else
{ $Hash[[object] $Key] = $Value }
}
}
else
{ $Hash = $Object }
$Hash # Do not convert to [PSCustomObject] and output. # [PSCustomObject]
}
# Recurse
ConvertToHashtable ($InputObject | ConvertFrom-Json)
}
#endregion
#region ConvertFrom-HashtableToPSObject
# Based on ConvertFrom-JsonToHashtable just above
function ConvertFrom-HashtableToPSObject
{
param (
[Parameter(Mandatory, ValueFromPipeline)]
[AllowNull()]
$InputObject
)
function ProcessArray ($Array)
{
$NestedArray = @()
#$NestedArray = [ordered] @{}
foreach ($Item in $Array)
{
if ($Item -is [System.Collections.Specialized.OrderedDictionary])
{ $NestedArray += ConvertToPSObject $Item }
elseif ($Item -is [System.Collections.IEnumerable] -and $Item -isnot [string])
{ $NestedArray += , (ProcessArray $Item) }
else
{ $NestedArray += $Item }
}
return , $NestedArray
}
function ConvertToPSObject ($Object)
{
$Hash = [ordered] @{}
if ($Object -is [System.Collections.Specialized.OrderedDictionary])
{
foreach ($Property in $Object.GetEnumerator())
{
$Key = $Property.Name # Key
$Value = $Object.$Key # Value
$NewName = $PropertyNamePascal[$Key]
if ($NewName)
{ $Key = $NewName }
elseif ($Key -notmatch "^[-]?[\d]+$")
{ Write-Verbose "Missing pascal case for: $Key" }
# Handle array (preserve nested structure)
if ($Value -is [System.Collections.IEnumerable] -and $Value -isnot [string])
{ $Hash[[object] $Key] = ProcessArray $Value }
# Handle object
elseif ($Value -is [System.Collections.Specialized.OrderedDictionary])
{ $Hash[[object] $Key] = ConvertToPSObject $Value }
else
{ $Hash[[object] $Key] = $Value }
}
}
else
{ $Hash = $Object }
[PSCustomObject]$Hash # Convert to [PSCustomObject] and output
}
# Recurse
ConvertToPSObject ($InputObject)
}
#endregion
#region ConvertTo-MWEscapedString
function ConvertTo-MWEscapedString
{
<#
.SYNOPSIS
Conversion helper used to escape a subset of characters to their HTML entities.
.DESCRIPTION
Some characters ("|=[]" etc) are used by the wikitext parser of MediaWiki and can
therefor run into issues if these characters are used in some places. This helper
converts such characters to their HTML entities, bypassing the issue.
.PARAMETER InputObject
A string or an array of strings to perform the character escaping on.
.EXAMPLE
ConvertTo-MWEscapedString -InputObject $WebsiteTitle
#>
[CmdletBinding()]
param (
<#
Core parameters
#>
[Parameter(Mandatory, ValueFromPipeline, Position=0)]
[string[]]$InputObject
)
Begin { }
Process
{
# https://www.thoughtco.com/html-code-for-common-symbols-and-signs-2654021
$Buffer = $InputObject | ForEach-Object {
$Escaped = $_
$Escaped = $Escaped.Replace('=', '=' )
$Escaped = $Escaped.Replace('[', '[' )
$Escaped = $Escaped.Replace(']', ']' )
$Escaped = $Escaped.Replace('|', '|')
$Escaped
}
return $Buffer
}
End { }
}
#endregion
#region ConvertTo-MWNamespaceID
function ConvertTo-MWNamespaceID
{
<#
.SYNOPSIS
Conversion helper used to convert namespace names into their relevant IDs.
.DESCRIPTION
When used to validate a [string] parameter, the input object will only be accepted if it
matches a positive namespace ID or name registered on the MediaWiki site.
.PARAMETER InputObject
An array of strings containing either valid namespace IDs or names, where the names will
be converted into their respective IDs.
.EXAMPLE
$Namespace = ConvertTo-MWNamespaceID $Namespace
#>
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[AllowEmptyString()]
[AllowNull()]
[string[]]$InputObject,
# Some API calls only support a single namespace
[switch]$Single,
# Negative namespaces (Media and Special) are special and seldom used/supported through the API.
[switch]$IncludeNegative
)
Begin { }
Process
{
[string[]]$Buffer = @()
if ($null -ne $InputObject.Count)
{
# Does the array include a wildcard?
# If so, include all of the namespaces the site supports
if ($InputObject -contains '*')
{
if ($IncludeNegative)
{ $Buffer = (Get-MWNamespace -IncludeNegative).ID }
else
{ $Buffer = (Get-MWNamespace).ID }
}
# Test each element in the array
else
{
ForEach ($NS in $InputObject)
{
# Try-Catch to suppress exception thrown when
# casting a non-numeric string to int32
try {
if ($tmp = Get-MWNamespace -NamespaceName $NS)
{ $Buffer += $tmp.ID }
elseif ($tmp = Get-MWNamespace -NamespaceID $NS)
{ $Buffer += $tmp.ID }
} catch { }
}
}
}
$Buffer = $Buffer | Select-Object -Unique
if ($Buffer.Count -gt 0)