-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.php
1739 lines (1538 loc) · 73.4 KB
/
index.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
// MainTiddlyServer
$version = '1.7.6';
// MIT-licensed (see https://yakovl.github.io/MainTiddlyServer/license.html)
$debug_mode = false;
// "no cache" headers to always get up-to-date TW content (not loaded from cache)
// especially important on Android, since aggressive task killer unloads browsers from RAM quite often
// important: avoid BOM in this script: that causes warnings instead of setting headers
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1
header("Pragma: no-cache"); // HTTP 1.0
header("Expires: 0"); // Proxies
// solution was taken from https://stackoverflow.com/q/49547/
/*
This PHP script allows TiddlyWiki to save directly onto an HTTP server.
To install, simply copy the index.php and the TiddlyWiki HTML file onto your web server,
then open the address of this script in a web browser.
You will then be asked to perform some initial configuration, after which you can save your wiki file on your website.
to do:
! collect user scenarios (+), design interfaces, make them simple and straight-forward
! simplify installation
- try http://www.clickteam.com/install-creator-2 for simplifying the installation process on Windows (look for alternatives, too: https://alternativeto.net/software/clickteam-install-creator/)
* Windows Store?
- learn how installation can be simplified for Unix-like OSes (packaging, stores)
- learn how installation can be simplified using Composer
- add upload TW option, download; new TW option (?wikis)
- minimize pages and clicks (showTW: remove extra page..)
- improve description of memory_limit in ?options + comment source better /.oO can we increase automatically?
- tell user password protection won't work when it is so
- when saving options/changes fails, notify, don't fail silently (file_put_contents does so)
- improve interface for the case of no TWs in the workingFolder (both ?options and ?wikis)
- add settings: server title (instead of MainTiddlyServer), color scheme (2-3-4 colors)
- make interface look close to that of MTS site: navbar with ?wikis, ?config, ?usage?, ?about (put version history of changes there)
- hightlight the current page in navbar
* make the interfaces be really shared between MTS and its site (how to?)
- add docs and history of MTS changes as html served by MTS itself (showDocPage)
.oO improve typographics/layout (same as on the site? commons css?), including color scheme (different one?)
- go on implementing working with other folders (see after $workingFolder)
- process in $_POST['options'] section the choice of the workingFolder in the options interface
- next: make interface consistent (either update the wikis <select> of location choice or remove at all)
- retest usage with workingFolder switched to ph: debug current slow including in FF for microrepos
- allow including from other dataFolders (next: by w.f.'s aliases /implemented: by relative address)
- next: allow choosing workingFolder in interface, visit subfolders (for microrepos), ..
- allow to switch off proxying (js hijacking)
- either proxy non-GET requests (use $_REQUEST instead?) or limit httpReq hijacking to GET requests
- pass _any_ request that is not processed directly, through proxy (now those to the same domain won't work)
- gather proxy implementation issues, test stuff
- add checks if getFolderAndFileNameFromPath returned empty folder (for instance, including from http://site.com – with no path at all, like http://site.com/TW.html → http://site.com?wiki=otherTW.thml)
* calc $mtsHost in a more reliable way: get rid of port manually: https://stackoverflow.com/a/8909559
(wrong values like containing :port can cause MTS infinite loops because of proxying)
* go through the proxy_to code and analyse its algorithm for custom ports
- test opportunities of sending requests to web from localhost/proxy:
- .oO and try including from other devices
- retest (re-implement?) import from remote TWs
- (re-)implement TW core upgrading (in the core, not in MTS)
.oO what sync did, re-implement? integrate with git?
.oO simple interface for getting a list of available plugins and installing them (where to index? .oO UX)
- try with various services like CrossRef, scrapping (~GET) and ~social/with push (RSS, mail, BC, etc with back-ends)
.oO updating MTS from a repo (security is paramount!)
- implement image uploading (in MTS + TW)
- improve security, error handling
- make sure we got an image, without injected code (or resave it to ~sanitize)
. previously (bad idea): try to convert every image to base64 on the client-side instead,
see: https://stackoverflow.com/a/37690794/ (retest)
. for consideration: [SO question and] https://jehy.github.io/mami/infosec-lab3.html
- add request handling
- add front-end part, inject into TW ..may be useful: https://codepen.io/anon/pen/mpKaJe?editors=1010
- start with uploading favicon (.ico, .png); .oO about security for uploading arbitrary
. big goal: create a paste-place for all sorts of files and materials via TW + MTS
- review debug dumps/logging, now controlled by $debug_mode:
? what user may need, what's needed for maintaining (and whether some parts should be switched on/off separately),
what should be removed/substituted by autotests; add configuring and review through an interface
. would be useful to have logs regarding what was requested (and which routing was used)
- remove conflicting dumps to test_store_area_locating.txt
* see https://www.loggly.com/ultimate-guide/php-logging-basics/ and http://www.phptherightway.com/ #errors_and_exceptions and #testing
* add logging of errors for the POST requests (and all requests themselves? use for sync editing?)
- implement real-time updating of content (on the front-end) when used by multiple users
- test compression by Apache or PHP (see https://stackoverflow.com/q/1862641/) in showTW (online and offline)
! extracting js and css to separate "files" so that they get cached may be much more effective
- retest readOnly with opening both MTS and html in the same folder,
prevent saving/loading chkHttpReadOnly cookie (probably inject into setOption: 'if(name == "chkHttpReadOnly") return')
- remake core overwriting: change window.saveFile, not (only) saveChanges,
security: start with allowing only saving TWs in the . folder (currently supported request) and backups
* test and add support of TW below 2.6.5 (build autotests)
* extend isTwLike to recognize PureStore
* test with IE: is encoding of non-latin letters broken? (change the convertUnicodeToFileFormat patch accordingly)
password-protection to-dos:
- make password field type="password" and add a duplicate field to check if those values coincide
. until we stop relying on Apache:
- add an option to protect only the .php, options and .ht files with password (see TW for details)
! try to find an external lib to avoid using .htaccess/apache
like may be https://github.com/delight-im/PHP-Auth or https://github.com/PHPAuth/PHPAuth
. to make password protection work on Windows, Android, via Apache 2.2.18 and above
? there's no support of htaccess/Apache implementation on Android, right?
. crypt is a unix-only solution, non-reliable
* support password-protection for Apache 2.2.18 and above, see https://stackoverflow.com/q/41078702/
and https://stackoverflow.com/q/11815121/
* for implementation, see https://searchengines.guru/archive/index.php/t-234844.html (using htpasswd, 28.05.2008, 05:32) and http://httpd.apache.org/docs/current/misc/password_encryptions.html,
or Apache module that uses DB http://httpd.apache.org/docs/2.2/mod/mod_authn_dbd.html
- implement non-\w containing passwords (or improve ~visibility of the notification) [either non-Apache or non-crypt solution]
- fix: not all letters of password are used (since crypt uses only the first 8 ones) [either non-Apache or non-crypt solution]
refactoring:
- add lingo for server, move interface strings there and those in injected js – to TW's lingo
also store links to MTS site and repo in a similar central place
- separate "model" and "controller" fully; then separate "controller" and "view"
- get rid of ugly ids un and pw (should be different from name s at least)
(forked from MTS v2.8.1.0, see https://groups.google.com/forum/#!topic/tiddlywiki/25LbvckJ3S8)
changes from the original version:
1.7.6
+ fixes to remove warnings in PHP8 (see #10)
+ a fix to support serving through https
1.7.5
+ added support of TW 2.10.1 (not using new interfaces yet)
+ introduce skip_file_locking
1.7.4
+ added support of TW 2.10.0 (not using new interfaces yet)
+ support .htm, .hta files (treat the same as .html)
1.7.3
+ fixed backstage save button
+ added permission fix recipe to the error message
+ added fix suggestion to the error message when DOMDocument is not available
1.7.2 see https://github.com/YakovL/MainTiddlyServer/pull/5
+ added support of TW 2.9.4, forward-compatibility for tw.io.onSaveMainSuccess
+ made injected js work correctly even when similar bits are inside storeArea
+ several UI improvements
1.7.1
+ introduced color theme and dark mode support (follows OS mode) to both MTS and docs pages
1.7.0
+ reduced injected JS to just one chunk, simplified injecting/removing on backend,
fixed removeInjectedJsFromWiki for upgrading TW: don't modify the file if injected bits are not found
+ added support of TWs with CRLF linebreaks (for instance, git changes them so)
+ made messages about unsupported TW versions more specific and helpful
+ improved paddings in the list of ?wikis for touch devices
+ fixed lack of message when non-granulated saving fails to reach server on the stage of loading original
+ fixed conflicts of simultaneous proxied requests from different working folders
+ added locking options/TW files when reading/writing to avoid conflicts
+ refactored options into a singleton class
+ update latest tested TW version to 2.9.3
+ fixed store dirtiness when changes to save are empty
+ introduced tiddlyBackend on front-end, encapsulated several methods into it from global scope,
exposed MTS version in it for feature detection
+ implemented ?backupByName endpoint and decorated copyFile so that during TW upgrading the backup is really saved
. started using contemporary JS bits (arrow functions, const/let)
1.6.3
+ introduce single wiki mode
+ refactored various bits of code, setting memory_limit should now work consistently
1.6.2
+ refactored injected js to fix exotic issues and to support custom saving (encrypted etc),
governed by config.options.chkAvoidGranulatedSaving
+ show error message when saving changes fails due to access failure
1.6.1
+ made 'unavailable' error pages respond with 404 (fix an issue with removable storages)
+ change: now request to MTS without ?.. opens options page if those are not set and wikis otherwise,
removed unnecessary "bookmark this" links
+ added hardcoded $debug_mode flag for further improvement of ~debug logging
+ fixed: global $baselink missing in showWikisList (causes errors in elder versions of php)
+ fixed path processing of the proxy (broke including in some cases)
+ secure data in case server/TW wasn't available during asyncLoadOriginal but was available afterwards during saving (and other cases)
1.6.0
+ introduced simple proxy to enable including TWs from TWs served through MTS and to request stuff from web
to even overcome CORS! (request to CORS-enabled sites are already available from localhost, though)
httpReq is hijacked by the injected JS so that it makes requests to MTS and it proxies those
+ introduced a template for server interfaces including error pages, improved (colomn wrapper, viewport, ...)
+ fixed links to TWs with '+' in their name at ?wikis
+ added an interface to set memory_limit for larger TWs
+ added support of TW 2.9.1
+ fixed granulated saving failed to update title when it is not set (<title>\n\n</title>)
+ renamed to MainTiddlyServer
1.5.2
+ added doctype and viewport to ?options and ?wikis interfaces for better view on mobile
+ fixed major bug of 1.5.x: saving failed for TWs below 2.8.0
+ fixed major bug of 1.5.x: saving changes to an empty TW 2.8.0+ corrupted TW
1.5.1
+ when TW is not chosen, show ?options interface instead of a separate page with a link to it
+ fix .htaccess creating for paths containing the space symbol
+ tweaked interfaces to make them look less horrible
1.5.0
+ implement "saving by patching" to reduce traffic and further use for sync editing
. now if 2+ users can edit /different/ tiddlers and save without interfering, although they won't know about
other editors online and won't get the updates made by others (yet)
. error messages are now much more helpful
before 1.5.0
+ made possible non-conflicting work with multiple TWs simultaneously via 1 MTS (to do so, open them via ?wiki=.. requests)
. now saving arbitrary .html in the workingFolder (but not in subfolders) is supported – by ?save=yes&wiki=wikiname.html
requests (if MTS/TW is opened through the ?wiki request, this kind of saving is used automatically)
. only tw-like htmls (that have a supported version) are listed/saved
. it would be better if it's not quite clear from JS that saving any other wiki in the same folder is possible,
to use POST ?wiki: this way, JS won't show other server options; it seems not quite possible: we can add the whole
.search part to the request to hide the "wiki=" keyword, but it's still visible that .search is used
+ added no-cache headers to prevent loading non-up-to-date content
+ added messages on successful saving
+ backups are saved or not according to the chkSaveBackups option
+ reduced code by using core updateOriginal method + added a patch for FireFox (that corrupted non-latin letters)
. now SiteTitle, SiteSubtitle, MarkupPreHead and such correctly update the HTML of TW
. now symbols like non-latin letters are not encoded like л → л (which reduces filesize)
+ added usage of location.host instead of location.hostname in getOriginalUrl
so now saving works with servers with custom ports as well
+ added support of TW 2.6.5, 2.9.0
+ ?wiki=tw_name sets current TW (both opens immediately and saves to options.txt)
+ support addresses with port number in server messages (add to $baselink, $optionsLink)
+ ?wikis shows the list of available htmls as ...?wiki=... links,
on screens large enough, navigation via keyboard can be used to open a wiki
+ (experimental) added adaptive font size to the wikis page
+ added image grab helpers
+ the chkHttpReadOnly patch is now removed on saving
+ made saving asynchronous
+ rewrote options saving using JSON format with indents so that they are easy to edit manually
+ fixed json_decode problem (added second argument), other minor stuff
+ set dirty: false on saving response, not when sending request
*/
$injectedJsHelpers = '// TW v2.8.0 and above where recreateOriginal is finished and used
function isGranulatedSavingSupported() {
return version.major > 2 || (version.major == 2 && version.minor >= 8);
}
// make option visible through the <<options>> macro (but not among standart options)
if(config.options.chkAvoidGranulatedSaving === undefined) config.options.chkAvoidGranulatedSaving = false;
function shouldGranulatedSavingBeUsed() {
return isGranulatedSavingSupported() && !config.options.chkAvoidGranulatedSaving;
}
function saveOnlineChanges() {
if(shouldGranulatedSavingBeUsed())
saveOnlineGranulatedChanges();
else
tiddlyBackend.saveTwSnapshot();
}
function saveOnlineGranulatedChanges() {}
// patch so that FireFox does not corrupt the content
//# to be tested with IE, Edge
convertUnicodeToFileFormat = function(s) { return config.browser.isIE ? convertUnicodeToHtmlEntities(s) : s; };
function getQueryParts() {
var queryArray = window.location.search.substr(1).split("&"), queryMap = {};
while(queryArray.length) {
var nameAndValue = queryArray.pop().split("=");
queryMap[nameAndValue[0]] = nameAndValue[1];
}
return queryMap;
}
function getCurrentTwRequestPart() {
var queryMap = getQueryParts(),
twQueryParts = []; // keep only wiki= and folder=
for(var key in { wiki:1, folder:1 })
if(queryMap[key])
twQueryParts.push(key +"="+ queryMap[key]);
return twQueryParts.join("&");
//# or just return the whole window.location.search ?
}
function getOriginalUrl() {
// use document.location.host so that custom ports are supported
return document.location.protocol + "//" + document.location.host + document.location.pathname;
};
function setupGranulatedSaving() {
TiddlyWiki.prototype.rememberStoredState = function(title, markupBlocks, externalizedTiddlers) {
// perhaps a more correct term would be "stored-tracking"
if(title !== null)
this.storedTitle = title;
this.storedMarkupBlocks = this.storedMarkupBlocks || {};
for(var tiddlerName in markupBlocks)
this.storedMarkupBlocks[tiddlerName] = markupBlocks[tiddlerName];
// {} of texts of tiddlers as they should be saved
this.storedTiddlers = externalizedTiddlers;
};
//# may be remembering whole HTML [= window.originalHTML || recreateOriginal()] and a getter should be added
// for encrypted vault support; upgrading support?
TiddlyWiki.prototype.markupBlocksMap = {
MarkupPreHead: "PRE-HEAD",
MarkupPostHead: "POST-HEAD",
MarkupPreBody: "PRE-BODY",
MarkupPostBody: "POST-SCRIPT"
};
TiddlyWiki.prototype.getExternalizedMarkupBlocks = function() {
var blockValues = {};
for(var tiddlerName in this.markupBlocksMap) {
// apadted from replaceChunk
blockValues[tiddlerName] =
convertUnicodeToFileFormat(this.getRecursiveTiddlerText(tiddlerName, ""));
}
return blockValues;
};
TiddlyWiki.prototype.getExternalizedTitle = function() {
// for now, we only support title updating for the main store
return this !== store ? null : convertUnicodeToFileFormat(getPageTitle()).htmlEncode()
};
TiddlyWiki.prototype.getExternalizedTiddlers = function() {
var externalizedTiddlers = {}, saver = this.getSaver();
this.forEachTiddler(function(title, tiddler) {
if(!tiddler.doNotSave())
externalizedTiddlers[title] = saver.externalizeTiddler(this,tiddler);
});
return externalizedTiddlers;
};
TiddlyWiki.prototype.refreshStoredData = function() {
this.rememberStoredState(
// title, remember only for main store
this.getExternalizedTitle(),
// markup blocks, tiddlers
this.getExternalizedMarkupBlocks(), this.getExternalizedTiddlers()
//# use diffs calced by getChanges to refresh .storedTiddlers instead?
);
};
TiddlyWiki.prototype.getChanges = function() {
var overallChagnes = {};
// check if some tiddlers were updated
var changedTiddlers = {};
// hash by title of "deleted"/{added:externalizedText}/{changed:externalizedText}
var saver = this.getSaver();
this.forEachTiddler(function(title, tiddler) {
if(tiddler.doNotSave()) return;
var currentExternalizedText = saver.externalizeTiddler(this, tiddler);
if(!this.storedTiddlers[title]) {
changedTiddlers[title] = { added:currentExternalizedText };
return;
}
if(currentExternalizedText != this.storedTiddlers[title])
changedTiddlers[title] = { changed:currentExternalizedText };
});
for(var title in this.storedTiddlers)
if(!this.fetchTiddler(title))
changedTiddlers[title] = "deleted";
//# find renamed tiddlers (added + deleted with same text),
// put 1 "renamed" instead of 1 "deleted" and 1 "added"?
for(var key in changedTiddlers) { // if any changes
overallChagnes.tiddlers = changedTiddlers; break;
}
// check if page title was changed
var currentTitle = this.getExternalizedTitle();
if(currentTitle != this.storedTitle)
overallChagnes.title = currentTitle;
// check if markupBlocks were updated
var updatedBlocks = this.getExternalizedMarkupBlocks(), blockName;
for(var tiddlerName in updatedBlocks)
if(updatedBlocks[tiddlerName] != this.storedMarkupBlocks[tiddlerName]) {
overallChagnes.markupBlocks = overallChagnes.markupBlocks || {};
blockName = this.markupBlocksMap[tiddlerName];
overallChagnes.markupBlocks[blockName] = updatedBlocks[tiddlerName];
}
return overallChagnes;
}
window.saveOnlineGranulatedChanges = function() {
var dataToSend = JSON.stringify(store.getChanges());
if(dataToSend == "{}") {
store.setDirty(false);
return;
}
tiddlyBackend.call({
method: "POST",
onSuccess: function(responseText) {
if(responseText == "saved")
tw.io.onSaveMainSuccess();
else
displayMessage("Error while saving. Server:\n" + responseText);
},
onProblem: function(status) {
displayMessage("Error while saving, failed to reach the server, status: "+ status);
},
body: "saveChanges="+encodeURIComponent(dataToSend) +
(config.options.chkSaveBackups ? ("&backupid=" + (new Date().convertToYYYYMMDDHHMMSSMMM())) : "")
});
};
// when successfully saved, update .storedTiddlers etc
TiddlyWiki.prototype.orig_noRefreshingLoaded_setDirty = store.setDirty;
TiddlyWiki.prototype.setDirty = function(dirty) {
if(!dirty) this.refreshStoredData();
return this.orig_noRefreshingLoaded_setDirty.apply(this, arguments);
};
// since getPageTitle uses wikifyPlainText which requires formatter which is calced
// after all plugins are loaded, we calc it in advance...
if(!formatter) {
formatter = new Formatter(config.formatters);
store.refreshStoredData();
formatter = null;
}
// ...and remove it afterwards for backward compability
//# this probably should be fixed in the core, though (at least we can hijack getPageTitle)
} //setupGranulatedSaving
function implementRequestProxying() {
window.config.orig_noProxy_httpReq = httpReq; //# or use window.httpReq?
httpReq = function(type, url, callback, params, headers, data, contentType, username, password, allowCache) {
// in case of request to current MTS;
// we don`t try to guess if urls are the same when the ~index.php bit is omitted/added
// since we don`t know settings of the index file in the folder;
// we don`t do this for requests to the same folder/subfolder
// (that`s the point of the workingFolder fix)
if(url == getOriginalUrl())
return window.config.orig_noProxy_httpReq.apply(this, arguments);
var proxy_url = getOriginalUrl(), // back to MTS
request_url = url,
currentTwRequestParts = getCurrentTwRequestPart().split("&"),
proxy_content = "proxy_to=" + encodeURIComponent(request_url);
for(var i = 0; i < currentTwRequestParts.length; i++)
if(currentTwRequestParts[i].indexOf("folder=") == 0)
proxy_content += "&" + currentTwRequestParts[i];
// change agruments to make request to MTS` proxy instead:
// just add request_url to the request body and send to MTS
//# what if its type was not application/x-www-form-urlencoded ?
url = proxy_url;
while(arguments.length < 6) // data is the 6th argument and may have been omitted
[].push.call(arguments, undefined);
arguments[5] = data ? (proxy_content + "&" + data) : proxy_content;
return window.config.orig_noProxy_httpReq.apply(this, arguments);
};
}
window.tiddlyBackend = {
version: {
title: "MainTiddlyServer",
asString: "' . $version . '"
},
init: function() {
if(this.isInitialized) return;
this.isInitialized = true;
config.options.chkHttpReadOnly = false;
// before TW 2.9.4
if(!window.tw) window.tw = {
io: {
onSaveMainSuccess: function() {
displayMessage(config.messages.mainSaved);
store.setDirty(false);
}
}
};
implementRequestProxying();
if(isGranulatedSavingSupported())
setupGranulatedSaving();
// override saving
window.saveChanges = function(onlyIfDirty, tiddlers) {
if(onlyIfDirty && !store.isDirty()) return;
return saveOnlineChanges();
};
// update backstage saving as well
config.tasks.save.action = saveChanges;
// decorate copyFile to make it work for backuping on upgrading (sync, returns boolean indicating whether succeeded)
var nonBackuping_copyFile = window.copyFile;
window.copyFile = function(destinationPath, sourcePath) {
// check if was used for creating a backup (see config.macros.upgrade.onClickUpgrade)
const backupPathReconstructed = getBackupPath(sourcePath, config.macros.upgrade.backupExtension)
const maskTimestamp = (path) => path.replace(/\d/g, "*")
if(sourcePath != getLocalPath(document.location.toString())
|| maskTimestamp(destinationPath) != maskTimestamp(backupPathReconstructed))
return nonBackuping_copyFile.apply(this, arguments);
const backslash = "\\\\";
const slashUsed = destinationPath.indexOf("/") == -1 ? backslash : "/";
const pathParts = destinationPath.split(slashUsed);
const fileName = pathParts[pathParts.length - 1];
let success = false;
tiddlyBackend.call({
method: "POST",
onSuccess: function(responseText) { success = responseText === "success" },
body: "backupByName=" + encodeURIComponent(fileName) +
"&backupFolder=" + encodeURIComponent(config.options.txtBackupFolder),
isSync: true
})
return success;
};
},
// auxiliary ("private") methods
// params: { method?: "GET" | "POST" | ..., headers: { [name:string]: string }, body?: string (data form),
// onSuccess?: (responseText ??) => void, onProblem?: (status ??)=>void, isSync?: boolean }
call: function(params) {
var method = (params.method || "GET").toUpperCase();
var url = getOriginalUrl();
var body = params.body || null;
var headers = params.headers || {};
var currentPageRequest = getCurrentTwRequestPart();
if(method === "GET") {
if(currentPageRequest) url += (url.indexOf("?") == -1 ? "?" : "&") + currentPageRequest;
} else {
body = !body ? currentPageRequest :
body + (currentPageRequest ? "&" + currentPageRequest : "");
headers["Content-Type"] = "application/x-www-form-urlencoded";
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(this.readyState != 4) return;
if(this.status == 200) {
if(params.onSuccess) params.onSuccess(this.responseText);
} else {
if(params.onProblem) params.onProblem(this.status, this.responseText);
}
}
xhr.open(method, url, !params.isSync);
for(var name in headers) xhr.setRequestHeader(name, headers[name]);
xhr.send(body);
},
loadOriginal: function(onSuccess) {
// GET call with default params loads the TW itself
this.call({
onSuccess: onSuccess,
onProblem: function(status) {
displayMessage("Error while saving, failed to reach the server and load original, status: "+ status);
}
});
},
// original = HTML currently stored on backend
updateAndSendMain: function (original, onSuccess) {
// Skip any comment at the start of the file..
const documentStart = original.indexOf("<!DOCTYPE");
original = original.substring(documentStart);
// ..get updated html..
// url to display in the ~saving failed~ message
const localPath = document.location.toString();
// alerts on fail, so we don`t notify (again)
const newHtml = updateOriginal(original, null, localPath);
if(!newHtml) return;
// ..and pass the new document to MTS for saving
tiddlyBackend.call({
method: "POST",
onSuccess: function(responseText) {
if(responseText == "saved") onSuccess();
else displayMessage("Error while saving. Server:\n" + responseText);
},
onProblem: function(status, responseText) {
displayMessage("Error while saving, failed to reach the server, status: "+ status +"; responseText:");
// the only way to show it multiline, as for TW 2.9.3
displayMessage(responseText);
},
body: "save=yes&content=" + encodeURIComponent(newHtml) +
(config.options.chkSaveBackups ? ("&backupid=" + (new Date().convertToYYYYMMDDHHMMSSMMM())) : "")
});
},
// "public" methods
saveTwSnapshot: function() {
this.loadOriginal(original => this.updateAndSendMain(original, tw.io.onSaveMainSuccess));
}
}
// we need store and other stuff to be defined when we setupGranulatedSaving;
// chkHttpReadOnly should be set before calculating readOnly
var noOnlineSaving_invokeParamifier = invokeParamifier;
invokeParamifier = function(params, handler) {
if(handler == "onload") {
window.tiddlyBackend.init();
}
return noOnlineSaving_invokeParamifier.apply(this, arguments);
};
';
function lock_and_read_file($path) {
//if(!file_exists($path)) return null; // or use throw new Exception('.. file does not exist'); ?
$file = fopen($path, "r");
if(!$file) return null; // or use throw new Exception('failed to open .. file');
$locked = flock($file, LOCK_SH);
//* if(!$locked) throw new Exception('failed to lock .. file');
$content = file_get_contents($path);
flock($file, LOCK_UN); // needed in PHP after 5.3.2
fclose($file);
return $content;
}
function lock_and_write_file($path, $content) {
$saved = Options::get('skip_file_locking') ?
file_put_contents($path, $content) :
file_put_contents($path, $content, LOCK_EX);
if(!$saved) return "MainTiddlyServer failed to save updated TiddlyWiki.\n" .
"Please make sure the containing folder is accessible for writing and the TiddlyWiki can be (over)written.\n" .
"Usually this requires that those have owner/group of \"www-data\" and access mode is 7** (e.g. 744) for folder and 6** for TW. " .
"Usually a proper way to fix this is to open the folder in bash, " .
"add the group (sudo chgrp -R www-data .), and add permissions to it (sudo chmod -R g+rwx .)";
}
define("DEFAULT_DATAFOLDER_NAME", "main");
define("DEFAULT_DATAFOLDER_PATH", ".");
class Options {
protected static $optionsFolder;
protected static $options;
// used to avoid redundant saving
protected static $isChanged;
public static function init($optionsFolder) {
if(self::$optionsFolder !== null) return;
self::$optionsFolder = $optionsFolder;
self::$isChanged = false;
}
public static function load() {
// first, read old options as a fallback
$oldPath = self::$optionsFolder . "/" . "options.txt";
$newPath = self::$optionsFolder . "/" . "mts_options.json";
$path = file_exists($newPath) ? $newPath : $oldPath;
if(file_exists($path)) {
$optionsText = lock_and_read_file($path);
self::$options = $path == $newPath ? json_decode($optionsText, true) : unserialize($optionsText);
}
// normalize
if(!isset(self::$options['dataFolders']))
self::$options['dataFolders'] = [];
if(!isset(self::$options['dataFolders'][DEFAULT_DATAFOLDER_NAME]))
self::$options['dataFolders'][DEFAULT_DATAFOLDER_NAME] = DEFAULT_DATAFOLDER_PATH;
}
public static function get($optionName) {
//# if($optionName == 'dataFolders') ... return copy of options['dataFolders'] so that they cannot be changed
return isset(self::$options[$optionName]) ?
self::$options[$optionName] : null;
}
public static function set($optionName, $value, $unsetEmpty = false) {
if($optionName == 'dataFolders') return;
$oldValue = self::get($optionName);
if($value != $oldValue && ($value || $oldValue))
self::$isChanged = true;
if(!$value && $unsetEmpty)
unset(self::$options[$optionName]);
else
self::$options[$optionName] = $value;
}
public static function chooseWorkingFolder($name) {
if(isset(self::$options['dataFolders'][$name])) {
self::set('workingFolderName', $name);
}
if(!self::get('workingFolderName') or !self::get('dataFolders'))
self::set('workingFolderName', DEFAULT_DATAFOLDER_NAME);
return self::get('workingFolderName');
}
public static function getWorkingFolder() {
return self::$options['dataFolders'][self::get('workingFolderName')];
}
public static function save() {
if(!self::$isChanged) return;
// a fallback for PHP below 5.4.0 (see http://stackoverflow.com/q/22208831/3995261)
$pretty_print = (JSON_PRETTY_PRINT == "JSON_PRETTY_PRINT") ? 128 : JSON_PRETTY_PRINT;
$path = self::$optionsFolder . "/" . "mts_options.json";
return lock_and_write_file($path, json_encode(self::$options, $pretty_print));
}
}
function injectJsToWiki($wikiData) {
global $injectedJsHelpers;
// inject the new saving function before saveMain definition (make sure it's not inside storeArea)
$endOfStoreArea = strpos($wikiData, "<!--POST-STOREAREA-->");
$x = strpos($wikiData, "function saveMain(", $endOfStoreArea);
$wikiData = substr($wikiData, 0, $x) . $injectedJsHelpers . substr($wikiData, $x);
return $wikiData;
}
function removeInjectedJsFromWiki($wikiData) {
global $injectedJsHelpers;
$endOfStoreArea = strpos($wikiData, "<!--POST-STOREAREA-->");
// we imply that $injectedJsHelpers are either unchanged inside TW html or not present at all (may be so on upgrading)
//# try to use substr_replace instead (compare times, memory usage)
$start = strpos($wikiData, $injectedJsHelpers, $endOfStoreArea);
if($start === false) {
return $wikiData;
}
$end = $start + strlen($injectedJsHelpers);
return substr($wikiData, 0, $start) . substr($wikiData, $end);
}
function getTwVersion($wikiFileText) {
preg_match('/version = {\s*title: "TiddlyWiki", major: (\d+), minor: (\d+), revision: (\d+)/', $wikiFileText, $match);
return $match;
}
define("EARLIEST_TESTED_VERSION", 20600);
define("LATEST_TESTED_VERSION", 21002);
function isSupportedTwVersion($versionParts) {
if(!$versionParts)
return false;
$version = intval($versionParts[1]) * 10000 + intval($versionParts[2]) * 100 + intval($versionParts[3]);
if($version < EARLIEST_TESTED_VERSION or $version > LATEST_TESTED_VERSION)
return false;
return true;
}
function isNewerUntestedTwVersion($versionParts) {
if(!$versionParts)
return false;
$version = intval($versionParts[1]) * 10000 + intval($versionParts[2]) * 100 + intval($versionParts[3]);
if($version > LATEST_TESTED_VERSION)
return true;
return false;
}
function hasSupportedTwVersion($wikiFileText) {
$versionParts = getTwVersion($wikiFileText);
return isSupportedTwVersion($versionParts);
}
function hasHtmlLikeExtension($nameOrPath) {
return substr_compare($nameOrPath, ".html", -5, 5) == 0
or substr_compare($nameOrPath, ".htm", -4, 4) == 0
or substr_compare($nameOrPath, ".hta", -4, 4) == 0;
}
// doesn't support PureStore yet
function isTwLike($file_full_path_and_name) {
if(!hasHtmlLikeExtension($file_full_path_and_name))
return false;
if(!is_file($file_full_path_and_name))
return false;
$content = lock_and_read_file($file_full_path_and_name);
if(!hasSupportedTwVersion($content)) // not TW
return false;
return true;
}
function isInWokringFolder($file_or_folder_name) {
$workingFolder = Options::getWorkingFolder();
// workingFolder may be unavailable
if(!is_dir($workingFolder)) return false;
$filesAndFoldersNames = scandir($workingFolder);
return in_array($file_or_folder_name, $filesAndFoldersNames);
}
function isTwLikeInCurrentWorkingFolder($file_name) {
if(!isInWokringFolder($file_name)) return false;
$fullPath = Options::getWorkingFolder() . "/" . $file_name;
return isTwLike($fullPath);
}
function getListOfTwLikeHtmls($folder) {
$twLikeHtmls = [];
if(!is_dir($folder)) return null;
$filesAndFolders = scandir($folder);
foreach ($filesAndFolders as $name) {
$fullPath = $folder . "/" . $name;
if(is_file($fullPath) && hasHtmlLikeExtension($fullPath) && isTwLike($fullPath))
$twLikeHtmls[] = $name;
}
return $twLikeHtmls;
};
function showMtsPage($html, $title = '', $httpStatus = 200) {
global $optionsLink, $baselink, $wikisLink, $version;
http_response_code($httpStatus);
echo '<!-- ######################### MainTiddlyServer v'.$version.' ############################ -->';
echo '<!DOCTYPE html><html><head>';
echo '<meta charset="UTF-8" />';
echo '<meta name="viewport" content="width=device-width, initial-scale=1" />';
if($title)
echo "<title>MainTiddlyServer – $title</title>";
echo '<style>
@import url("https://fonts.googleapis.com/css?family=Roboto:400,700");
body { font-family: "Roboto", sans-serif; font-size: 15px; }
:root {
--color-outside: #888577;
--color-background: rgb(246, 234, 196);
--color-foreground: black;
/*--color-link: ;
--color-link-visited: ;*/
--color-nav-and-footer-background: black;
--color-nav-and-footer-link: rgb(246, 234, 196);
--color-selection: #b7b69f;
}
main a {
color: inherit;
opacity: 0.6;
}
::selection {
background: var(--color-selection);
}
@media (prefers-color-scheme: dark) {
:root {
--color-outside: #373630;
--color-background: black;
--color-foreground: rgb(150, 143, 120);
--color-nav-and-footer-background: black;
--color-nav-and-footer-link: rgb(150, 143, 120);
--color-selection: rgba(150, 143, 120, 0.5);
}
html {
color-scheme: dark;
}
}
input, textarea, select {
background: inherit;
color: inherit;
border: thin solid black;
}
option { background: var(--color-background); }
/* the hover and selected ones are more complecated, see https://stackoverflow.com/q/10484053/3995261 and https://stackoverflow.com/q/8619406/3995261 */
input[type="text"] { } /* keep disabled in mind */
body {
margin: 0;
margin-left: calc(100vw - 100%); /* fixes the scrollbar jumping issue, see https://stackoverflow.com/q/6357870/ */
}
.wrapper {
width: 40em;
max-width: 100%;
margin: 0 auto;
min-height: 100vh;
display: flex;
flex-direction: column;
}
footer { margin-top: auto; } /* https://stackoverflow.com/a/47640893/ */
.navigation {
text-align: center;
}
.navigation__link {
display: inline-block; padding: 1em 2em;
}
main {
padding-left: 1em; padding-right: 1em;
box-sizing: border-box;
}
footer {
text-align: center;
font-size: 0.8rem;
padding-top: 1em;
padding-bottom: 1em;
}
body { background-color: var(--color-outside); }
.wrapper {
background-color: var(--color-background);
color: var(--color-foreground);
}
nav, footer { background-color: var(--color-nav-and-footer-background); }
nav a, footer a { color: var(--color-nav-and-footer-link); }
</style>';
echo '</head><body><div class="wrapper">';
//# set navigation__link_currently-opened class to the currently opened page + get rid of "Available TiddlyWikis:" on the wikis page
echo '<nav class="navigation">';
echo '<a class="navigation__link" href="'.(Options::get('single_wiki_mode') ? $baselink : $wikisLink).'">'.
(Options::get('single_wiki_mode') ? 'wiki' : 'wikis').'</a>';
echo '<a class="navigation__link" href="'. $optionsLink .'">options</a>';
echo '</nav>';
echo '<main>'. $html .'</main>';
echo '<footer><a href="https://yakovl.github.io/MainTiddlyServer/" target="_blank">MainTiddlyServer v'.$version.'</a></footer>';
echo '</div></body></html>';
}
function showOptionsPage() {
global $optionsLink;
$output = '<style>
.options-form__password-panel { padding: 0 1em; }
.no-password-warning { color: red; }
.memory-limit-input { width: 6em; }
button {
cursor: pointer;
padding: 0.3em 0.6em;
}
</style>
<script type="text/javascript">
function togglePasswordSetting(isEnabled) {
const passInputsArea = document.getElementsByClassName("options-form__password-inputs")[0];
passInputsArea.style.display = isEnabled ? "" : "none";
}
</script>';
$output .= '<form class="options-form" name="input" action="' . $optionsLink . '" method="post">' .
'<input type="hidden" name="options">';
function getOptionCheckbox($optionName, $labelHtml) {
return '<label><input type="checkbox" name="' . $optionName . '" ' .
(Options::get($optionName) ? 'checked ' : '') . '>' . $labelHtml . '</label>';
}
// workingFolder: list Options::get('dataFolders')'s names, send to further save Options 'workingFolderName'
/*$folders = Options::get('dataFolders');
$selected = Options::get('workingFolderName');
$output .= '<p>Use this location: <select name="foldername">';
foreach ($folders as $name => $path) {
$output .= "<option value=\"$name\"" . ($name == $selected ? " selected" : "") . ">$name</option>\n";
}
$output .= '</select> ()</p>';*/
//# add description: what is this location, where and how to add new ones
//# process in $_POST['options']
//# this should cause updating of the wikis dropdown.. or the latter should be removed from ?options
// wiki
$files = getListOfTwLikeHtmls(Options::getWorkingFolder());
if(is_null($files)) {
$output .= '<p><i>The chosen working folder is currently unavailable</i></p>';
} else {
$output .= '<p>Use this wiki file: <select name="wikiname">';
foreach ($files as $fileName) {
// avoid showing backups (legacy of MicroTiddlyServer)
if(preg_match("/[0-9]{6}\.[0-9]{10}/", $fileName))
continue;
$output .= "<option value=\"$fileName\"" . ($fileName == Options::get('wikiname') ? " selected" : "") . ">$fileName</option>\n";
}
$output .= '</select></p>';
}
$output .= '<p>' . getOptionCheckbox('single_wiki_mode',
'Single wiki mode (redirect from wikis to wiki page, no ?wiki=.. in URL required)') . '</p>';
// login/password
$output .=
'<div class="options-form__password-panel">' .
'<p><label><input type="checkbox" name="setpassword" onclick="togglePasswordSetting(this.checked)">Change or set a password</label></p>';
// gives false negatives (.htaccess may be without pass)
$noPassSet = !file_exists('.htaccess');
if($noPassSet) {
$output .= '<p class="no-password-warning">You currently do not have a password protecting your wiki file.' .
' If somebody guesses its path, they could modify it to include malicious javascript that steals your cookies ' .
'and potentially leads to further hacking on your entire web site. Please set a password below.</p>';
}
$output .=
'<div class="options-form__password-inputs" style="display: none;">' .
'<p><i>Use only letters (lower- and uppercase) and numbers</i></p>' .
'<table><tbody>' .
'<tr><td><label for="un">Username:</label></td> <td><input type="text" name="un" id="un"></td></tr>' .
'<tr><td><label for="pw">Password:</label></td> <td><input type="text" name="pw" id="pw"></td></tr>' .
'</table></tbody>' .
'</div>'.
'</div>';
// memory limit
$output .= "<p>PHP memory limit: <input type='text' name='memory_limit' value='" . Options::get('memory_limit') .
"' class='memory-limit-input'>" .
" (increase if your TW is large and saving doesn't work, try values like 6 * the size of your TW;" .
" leave blank to restore the default value)</p>";
// file locking
$output .= '<p>' . getOptionCheckbox('skip_file_locking',
'Skip file locking (<a href="https://github.com/YakovL/MainTiddlyServer/issues/8">workaround</a> ' .
'for the "Exclusive locks are not supported" error)') . '</p>';
$output .= '<p><button type="submit">Save</button></p>';
$output .= '</form>';