-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOIDplusPagePublicIO4.class.php
3010 lines (2334 loc) · 97.5 KB
/
OIDplusPagePublicIO4.class.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
/*
* OIDplus 2.0
* Copyright 2019 - 2023 Daniel Marschall, ViaThinkSoft/Till Wehowski, Frdlweb
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace { }
namespace io4{
use ViaThinkSoft\OIDplus\Core\OIDplus;
function withFacades(){
$io4Plugin = OIDplus::getPluginByOid("1.3.6.1.4.1.37476.9000.108.19361.24196");
$io4Plugin->bootIO4();
}
function container(){
$Stunrunner = OIDplus::getPluginByOid("1.3.6.1.4.1.37476.9000.108.19361.24196")->getWebfat(true,false);
return $Stunrunner->getAsContainer(null);
}
}//ns io4
namespace Frdlweb\OIDplus\Plugins\AdminPages\IO4{
use ViaThinkSoft\OIDplus\Core\OIDplus;
use ViaThinkSoft\OIDplus\Core\OIDplusConfig;
use ViaThinkSoft\OIDplus\Core\OIDplusException;
use ViaThinkSoft\OIDplus\Core\OIDplusObject;
use ViaThinkSoft\OIDplus\Core\OIDplusPagePluginPublic;
use ViaThinkSoft\OIDplus\Core\OIDplusPagePluginRa;
use ViaThinkSoft\OIDplus\Core\OIDplusPlugin;
use ViaThinkSoft\OIDplus\Core\OIDplusPagePluginAdmin;
use ViaThinkSoft\OIDplus\Plugins\AdminPages\Notifications\OIDplusNotification;
use ViaThinkSoft\OIDplus\Plugins\ObjectTypes\OID\WeidOidConverter;
use ViaThinkSoft\OIDplus\Plugins\PublicPages\Whois\INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_4;
use ViaThinkSoft\OIDplus\Plugins\PublicPages\Objects\INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_2;
use ViaThinkSoft\OIDplus\Plugins\AdminPages\Notifications\INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_8;
use ViaThinkSoft\OIDplus\Plugins\PublicPages\RestApi\INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_9;
use Webfan\DescriptorType;
use Webfan\RuntimeInterface;
use Webfan\ConfigType;
use Webfan\ExecutionContextType;
use Webfan\Batch;
use Webfan\Baum;
use League\Pipeline\PipelineBuilder;
use League\Pipeline\Pipeline;
use League\Pipeline\StageInterface;
use frdlweb\StubHelperInterface;
use frdlweb\StubRunnerInterface;
use Frdlweb\WebAppInterface;
use InvalidArgumentException;
use Webfan\Webfat\App\ConfigContainer;
use Webfan\Webfat\App\ContainerCollection;
# use frdl\ContainerCollectionV2 as ContainerCollection;
use Frdlweb\Contract\Autoload\ClassLoaderInterface;
use Configula\ConfigFactory as Config;
use Configula\ConfigValues as Configuration;
use Configula\Loader;
use Doctrine\Common\Cache\FilesystemCache;
//use Eljam\CircuitBreaker\Breaker
use Webfan\Webfat\App\CircuitBreaker as Breaker;
use Eljam\CircuitBreaker\Circuit;
use Eljam\CircuitBreaker\Event\CircuitEvents;
//use Eljam\CircuitBreaker\Event\CircuitEvent as Event;
//use Fuz\Component\SharedMemory\SharedMemory;
use Webfan\Webfat\App\SharedMemory;
//use Fuz\Component\SharedMemory\Storage\StorageFile;
use Webfan\Webfat\App\SharedMemoryStorageFile as StorageFile;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\ServerRequest;
use IvoPetkov\HTML5DOMDocument;
use Webfan\Webfat\HTMLServerComponentsCompiler;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Server\MiddlewareInterface;
use LogicException;
use Spatie\Once\Backtrace as SpatieBacktrace;
use Spatie\Once\Cache as SpatieCache;
# use Monolog\Level as LogLevel;
use Psr\Log\LogLevel;
#use Monolog\Logger;
use Monolog\Handler\StreamHandler as LoggerStreamHandler;
use Psr\Log\LoggerInterface;
use Monolog\Registry as LoggerRegistry;
use Webfan\Webfat\Filesystems\PathResolvingFilesystem as StreamHandler;
use ActivityPhp\Server;
use ActivityPub\ActivityPub;
use ActivityPub\Config\ActivityPubConfig;
use ActivityPub\Utils\Logger;
use Monolog\Logger as MonoLogger;
use Jobby\Jobby;
use Opis\Closure\SerializableClosure;
use Jobby\Exception;
// phpcs:disable PSR1.Files.SideEffects
\defined('INSIDE_OIDPLUS') or die;
// phpcs:enable PSR1.Files.SideEffects
/*
API:
public function packagist(string $method, array $params = [])
public function package(string $name) : array
*/
class OIDplusPagePublicIO4 extends OIDplusPagePluginAdmin //OIDplusPagePluginPublic // implements RequestHandlerInterface
implements //INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_1, /* oobeEntry, oobeRequested */
INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_4, //Ra+Whois Attributes
INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_2, /* modifyContent */
INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_8 , /* getNotifications */
INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_9/* restApi* */
//
/* INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_7 getAlternativesForQuery() */
{
public const WebfatDownloadUrl = 'https://packages.frdl.de/raw/webfan/website/webfan.setup.php';
public const BODY_REPLACER = '@@@@BODYCONTENTREPLACER@@@@';
const PAGE_ID_COMPOSER = 'oidplus:io4:composer';
const PAGE_ID_WEBFAT = 'webfan:webfat:setup';
const PAGE_ID_BRIDGE = 'webfan:io4:bridge';
const PAGES = [
'webfan:io4:bridge' => 'gui_PAGE_ID_BRIDGE',
'webfan:webfat:setup' => 'gui_PAGE_ID_WEBFAT',
'oidplus:io4:composer' => 'gui_PAGE_ID_COMPOSER',
];
/*
[
"oiplus-plugin-public-pages",
"oiplus-plugin-ra-pages",
"oiplus-plugin-admin-pages",
"oiplus-plugin-auth",
"oiplus-plugin-database",
"oiplus-plugin-sql-slang",
"oiplus-plugin-logger",
"oiplus-plugin-object-types",
"oiplus-plugin-language",
"oiplus-plugin-design",
"oiplus-plugin-captcha"
"project",
"library"
],
*/
protected $AppLauncher = null;
protected $_containerDeclared = false;
protected $StubRunner = null;
protected $schemaCacheDir;
protected $schemaCacheExpires;
protected $packagistCacheDir;
protected $packagistExpires;
protected $packagistClient = null;
protected $composerUI = null;
protected static $autoloaderRegistered = false;
public $db_table_exists;
protected $zipfile;
/**
* @var int
*/
public function __construct() {
$this->packagistCacheDir = OIDplus::baseConfig()->getValue('IO4_PACKAGIST_CACHE_DIRECTORY',
OIDplus::localpath().'userdata/cache/' );
$this->packagistExpires = OIDplus::baseConfig()->getValue('IO4_PACKAGIST_CACHE_EXPIRES', 15 * 60 );
$this->schemaCacheDir = OIDplus::baseConfig()->getValue('SCHEMA_CACHE_DIRECTORY', OIDplus::localpath().'userdata/cache/' );
$this->schemaCacheExpires = OIDplus::baseConfig()->getValue('SCHEMA_CACHE_EXPIRES', 60 * 60 );
//if(!static::is_cli() ){
// $this->ob_privacy();
// }
$this->zipfile =OIDplus::localpath().\DIRECTORY_SEPARATOR.'frdl-plugins.zip';
$this->zipfile_info = __DIR__
.\DIRECTORY_SEPARATOR.'frdl-plugins.json';
$this->zipfile_remote_info = OIDplus::localpath().'userdata'.\DIRECTORY_SEPARATOR.'cache'
.\DIRECTORY_SEPARATOR.'frdl-plugins-remote.json';
$this->zipfile_publish = OIDplus::localpath().'frdl-plugins.json';
}
/*
https://github.com/webuni/front-matter
*/
public static function objectCMSPage(string | OIDplusObject $obj, ?bool $verbose = false, ?bool $die = false, ?string $id = null){
return \call_user_func_array('\Frdlweb\OIDplus\Plugins\PublicPages\WTFunctions\OIDplusPageWTFunctions::objectCMSPage',
func_get_args() );
}
public function handleFallbackRoutes($REQUEST_URI, $request, $rel_url_original, $rel_url, $requestMethod){
$html = '';
if('/' === substr(explode('?',$request)[0], -1)
&& $request === OIDplus::webpath(null, OIDplus::PATH_RELATIVE_TO_ROOT)
&& (
0===count($_GET)
&& !str_contains(explode('?',$_SERVER['REQUEST_URI'],2)[0], '~')
&& !str_ends_with(explode('?',$_SERVER['REQUEST_URI'],2)[0], '.js')
&& !str_ends_with(explode('?',$_SERVER['REQUEST_URI'],2)[0], '.php') &&
$this->webUriRoot(OIDplus::localpath()) === OIDplus::webpath(null, OIDplus::PATH_RELATIVE_TO_ROOT) )
){
if ($obj = OIDplusObject::findFitting('uri:'.$request)) {
static::objectCMSPage($obj, true, true);
}
// var_dump($REQUEST_URI, $request, $rel_url_original, $rel_url, $requestMethod);
// die(basename(__FILE__).__LINE__);
// ob_end_clean();
ignore_user_abort(true);
header("Refresh:5; url=?goto=oidplus:system");
header('Connection: close') ;
$html.= '<h1>@ToDo: Startseite in Arbeit...</h1><p class="btn-warning" style="color:red;background:url(https://cdn.startdir.de/ajax-
loader_2.gif) no-repeat;">We are working on a new System feature</p><p>Page will reload soon, please wait...!<br />Neue Seite bald verfügbar!</p><img src="https://cdn.startdir.de/ajax-loader_2.gif" style="border:0px;" />';
$html.='<br />[ <a href="https://weid.info/plus/docs/oidplus-cms-pages" target="_blank">Doku: How to setup pages</a> ]';
// flush();
die($html);
// return $html;
}
/* */
//$uri = explode('?', $REQUEST_URI, 2)[0];
//$file = OIDplus::localpath().$uri;
//if(file_exists($file)){
// die($file);
//}
return false;
}
/*
if(isset($_GET['test'])){
// $isTenant = OIDplus::isTenant();
// die('$isTenant '.$isTenant.' '.__FILE__.__LINE__);
ob_end_clean();
echo print_r(static::getQuotaUsedDB(), true);
die();
}
SELECT table_name AS "table",
ROUND(((data_length + index_length) / 1024 / 1024), 2) AS "size_bm"
FROM information_schema.TABLES
WHERE table_schema = "oidplus_production" AND table_name LIKE "oidplus\_%"
ORDER BY (data_length + index_length) DESC;
OIDplus::baseConfig()->setValue('PUBSUB_MYSQL_DATABASE', 'webfan_pubsub_reg');
OIDplus::baseConfig()->setValue('PUBSUB_TABLENAME_PREFIX', 'frdl_reg_');
*/
public static function getQuotaUsedDB(){
$sum = 0;
$q="SELECT table_name AS `table`,
ROUND(((data_length + index_length) / 1024 / 1024), 2) AS `megabyte`
FROM information_schema.TABLES
WHERE table_schema = ? AND table_name LIKE '".str_replace('_', '\_', OIDplus::baseConfig()->getValue('TABLENAME_PREFIX'))."%'
ORDER BY (data_length + index_length) DESC";
// die($q);
$resQ = OIDplus::db()->query($q, [
OIDplus::baseConfig()->getValue('MYSQL_DATABASE'),
]);
$t = [];
while ($row = $resQ->fetch_array()) {
$sum+=$row['megabyte'];
$t[$row['table']] = $row['megabyte'];
}
return [
'used'=>$sum,
'tables'=>$t,
];
}
public function formatBytes($bytes, $precision = 2)
{
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
// Uncomment one of the following alternatives
$bytes /= pow(1024, $pow);
// $bytes /= (1 << (10 * $pow));
return round($bytes, $precision) . $units[$pow];
}
public function getWebfat(bool $load = true, bool $serveRequest = false/* load app */) {
$defDir = is_dir($_SERVER['DOCUMENT_ROOT'].\DIRECTORY_SEPARATOR.'..')
&& is_writable($_SERVER['DOCUMENT_ROOT'].\DIRECTORY_SEPARATOR.'..')
? $_SERVER['DOCUMENT_ROOT'].\DIRECTORY_SEPARATOR.'..'.\DIRECTORY_SEPARATOR.'.frdl'
: __DIR__.\DIRECTORY_SEPARATOR.'.frdl';
$d = OIDplus::baseConfig()->getValue('FRDLWEB_FRDL_WORKDIR', '@global' );
$frdlDir = !empty($d) && (is_dir($d) || is_writable(dirname($d))) ? $d : $defDir;
putenv('IO4_WORKSPACE_SCOPE="'.$frdlDir.'"');
// $_ENV['FRDL_WORKSPACE']=$frdlDir;
if(null === $this->StubRunner){
$webfatFile =$this->getWebfatFile();
if(!is_dir(dirname($webfatFile)) && dirname($webfatFile) !== $_SERVER['DOCUMENT_ROOT']){
mkdir(dirname($webfatFile), 0775, true);
}
require_once __DIR__.\DIRECTORY_SEPARATOR.'autoloader.php';
$getter = new ( \IO4\Webfat::getWebfatTraitSingletonClass() );
$getter->setStubDownloadUrl(\Frdlweb\OIDplus\Plugins\AdminPages\IO4\OIDplusPagePublicIO4::WebfatDownloadUrl);
$this->StubRunner = $getter->getWebfat($webfatFile,
$load
&& OIDplus::baseConfig()->getValue('IO4_ALLOW_AUTOLOAD_FROM_REMOTE', true )
, $serveRequest,
2592000,
$getter::$_stub_download_url );
$this->StubRunner->getAsContainer(null)->set('app.$dir', $frdlDir);
\Webfan\Patches\Start\Timezone2::defaults( );
}//! $this->StubRunner | null
// if(true === $serveRequest){
// $this->bootIO4($this->StubRunner);
//}
return $this->StubRunner;
}
public function getWebfatFile() {
$webfatFile =is_writable($_SERVER['DOCUMENT_ROOT'])
? $_SERVER['DOCUMENT_ROOT'].\DIRECTORY_SEPARATOR.'webfan.setup.php'
: OIDplus::localpath().'webfan.setup.php';
return $webfatFile;
}
public function getWebfatSetupLink(){
return OIDplus::webpath(dirname($this->getWebfatFile()),true).basename($this->getWebfatFile());
}
public function init($html = true): void {
$me = $this;
$Stubrunner = $this->webfatDoorKick();
// if(!static::is_cli() || true === $html){
// $this->ob_privacy();
//$me->ob_privacy();
// }
$rel_url = false;
$rel_url_original =substr($_SERVER['REQUEST_URI'], strlen(OIDplus::webpath(null, OIDplus::PATH_RELATIVE_TO_ROOT)));
$requestMethod = $_SERVER["REQUEST_METHOD"];
if(empty(OIDplus::baseConfig()->getValue('TENANCY_CENTRAL_DOMAIN'))
&& $_SERVER['SERVER_NAME'] === $_SERVER['HTTP_HOST']
&& ! OIDplus::isTenant()
){
OIDplus::baseConfig()->setValue('TENANCY_CENTRAL_DOMAIN',
OIDplus::baseConfig()->getValue('COOKIE_DOMAIN', $_SERVER['SERVER_NAME']) );
}
$tenantDirFromHost = $_SERVER['HTTP_HOST'];
if (str_ends_with($tenantDirFromHost, OIDplus::baseConfig()->getValue('TENANCY_CENTRAL_DOMAIN'))) {
$tenantDirFromHost = substr($tenantDirFromHost, 0,
strlen($tenantDirFromHost)-strlen( OIDplus::baseConfig()->getValue('TENANCY_CENTRAL_DOMAIN')) );
}
if(substr($tenantDirFromHost, 0, strlen('www.'))==='www.'){
$tenantDirFromHost = substr($tenantDirFromHost, strlen('www.'), strlen($tenantDirFromHost) );
}
$tenantDirFromHost = str_replace('---', '.', $tenantDirFromHost);
$tenantDirFromHost = trim($tenantDirFromHost,'.');
if(! OIDplus::isTenant()
&& OIDplus::baseConfig()->getValue('TENANCY_CENTRAL_DOMAIN') !== $_SERVER['HTTP_HOST']
&& OIDplus::baseConfig()->getValue('TENANCY_CENTRAL_DOMAIN') !== $tenantDirFromHost
&& OIDplus::baseConfig()->getValue('TENANCY_CENTRAL_DOMAIN') !== $_SERVER['SERVER_NAME']
&& is_dir(OIDplus::localpath('userdata/tenant').$tenantDirFromHost.'/')
){
OIDplus::forceTenantSubDirName( $tenantDirFromHost );
try{
header_remove();
while(ob_get_level())ob_end_clean();
// $request = \GuzzleHttp\Psr7\ServerRequest::fromGlobals();
$client = new \GuzzleHttp\Client();
$args = 'POST'===$_SERVER['REQUEST_METHOD'] ? [
'form_params'=>$_POST
] : [
];
$request = new \GuzzleHttp\Psr7\Request($_SERVER['REQUEST_METHOD'],
sprintf('https://%1$s%2$s', $tenantDirFromHost, $_SERVER['REQUEST_URI']));
$response = $client->send($request,array_merge($args, [
'timeout' => 30,
]));
(new \Laminas\HttpHandlerRunner\Emitter\SapiEmitter)->emit($response);
die();
} catch(\Exception $e){
die($e->getMessage().__METHOD__.__LINE__);
}
}
if(! OIDplus::isTenant()
&& OIDplus::baseConfig()->getValue('TENANCY_CENTRAL_DOMAIN') !== $_SERVER['HTTP_HOST']
&& OIDplus::baseConfig()->getValue('TENANCY_CENTRAL_DOMAIN') !== $_SERVER['SERVER_NAME']
&& OIDplus::baseConfig()->getValue('TENANCY_CENTRAL_DOMAIN') !== $tenantDirFromHost
){
$homelink ='https://webfan.de/admin/registry/?host='.urlencode($_SERVER['HTTP_HOST']).'&action=register';
//header(sprintf('Refresh:%2$d; url=%1$s' , $homelink, 3));
die(
'No tenant '.$tenantDirFromHost
.'<br />'
.'<a href="'.$homelink.'">Register '
.$tenantDirFromHost.' for you now to manage OID-Registries, Websites and Services...</a>'
);
}
OIDplus::config()->prepareConfigKey('TENANT_QUOTA_DEFAULT_DB',
'Default Tenant Quota (Database) in megabyte',
'4', OIDplusConfig::PROTECTION_EDITABLE, function ($value) {
});
OIDplus::config()->prepareConfigKey('FRDLWEB_FRDL_WORKDIR',
'Scope or Directory to save frdlweb framework source code in. Default=emty',
'', OIDplusConfig::PROTECTION_EDITABLE, function ($value) {
OIDplus::baseConfig()->setValue('FRDLWEB_FRDL_WORKDIR', $value );
});
OIDplus::config()->prepareConfigKey('FRDLWEB_PRIVACY_HIDE_MAILS',
'Privacy Mail Protection Addon (1=default active)',
'1', OIDplusConfig::PROTECTION_EDITABLE, function ($value) {
$value = intval($value);
OIDplus::baseConfig()->setValue('FRDLWEB_RDAP_PRIVACY_HIDE_MAILS', $value );
});
OIDplus::config()->prepareConfigKey('FRDLWEB_ALIAS_PROVIDER',
'Alias Service Provider Domain (e.g.: "profalias.webfan.de"). Alias and privacy service (e.g. mail-hashes for privacy and relation-mappings)',
'profalias.webfan.de', OIDplusConfig::PROTECTION_EDITABLE, function ($value) {
OIDplus::baseConfig()->setValue('FRDLWEB_ALIAS_PROVIDER', $value );
});
OIDplus::config()->prepareConfigKey('FRDLWEB_CONTAINER_REMOTE_SERVER_RELATIVE_BASE_URI',
'Uri relative to the OIDplus webBase to serve as endpoint for the container server https://packages.frdl.de/webfan/container-remote-server/archive/main.zip',
'api/v1/io4/remote-container/'
.OIDplus::baseConfig()->getValue('TENANT_OBJECT_ID_OID',
OIDplus::baseConfig()->getValue('TENANT_REQUESTED_HOST', 'webfan/website' ) )
, OIDplusConfig::PROTECTION_EDITABLE, function ($value) {
OIDplus::baseConfig()->setValue('FRDLWEB_CONTAINER_REMOTE_SERVER_RELATIVE_BASE_URI', $value );
});
OIDplus::config()->prepareConfigKey('FRDLWEB_INSTALLER_REMOTE_SERVER_RELATIVE_BASE_URI',
'Uri relative to the OIDplus webBase to serve as endpoint for the container server https://packages.frdl.de/webfan/installer-remote-server/archive/main.zip',
'api/v1/io4/remote-installer/'
.OIDplus::baseConfig()->getValue('TENANT_OBJECT_ID_OID',
OIDplus::baseConfig()->getValue('TENANT_REQUESTED_HOST', 'webfan/website' ) )
, OIDplusConfig::PROTECTION_EDITABLE, function ($value) {
OIDplus::baseConfig()->setValue('FRDLWEB_INSTALLER_REMOTE_SERVER_RELATIVE_BASE_URI', $value );
});
if (!OIDplus::db()->tableExists("###cron_and_jobs")) {
if (OIDplus::db()->getSlang()->id() == 'mysql') {
OIDplus::db()->query("CREATE TABLE IF NOT EXISTS ###cron_and_jobs
(`name` VARCHAR(255) NOT NULL ,
`command` TEXT NOT NULL ,
`schedule` VARCHAR(255) NOT NULL ,
`mailer` VARCHAR(255) NULL DEFAULT 'sendmail' ,
`maxRuntime` INT UNSIGNED NULL ,
`smtpHost` VARCHAR(255) NULL ,
`smtpPort` SMALLINT UNSIGNED NULL ,
`smtpUsername` VARCHAR(255) NULL ,
`smtpPassword` VARCHAR(255) NULL ,
`smtpSender` VARCHAR(255) NULL DEFAULT 'jobby@localhost' ,
`smtpSenderName` VARCHAR(255) NULL DEFAULT 'Jobby' ,
`smtpSecurity` VARCHAR(20) NULL ,
`runAs` VARCHAR(255) NULL ,
`environment` TEXT NULL ,
`runOnHost` VARCHAR(255) NULL ,
`output` VARCHAR(255) NULL ,
`dateFormat` VARCHAR(100) NULL DEFAULT 'Y-m-d H:i:s' ,
`enabled` BOOLEAN NULL DEFAULT TRUE ,
`haltDir` VARCHAR(255) NULL , `debug` BOOLEAN NULL DEFAULT FALSE ,
PRIMARY KEY (`name`)
)");
$me->db_table_exists = true;
} else if (OIDplus::db()->getSlang()->id() == 'mssql') {
// We use nvarchar(225) instead of varchar(255), see https://github.com/frdl/oidplus-plugin-alternate-id-tracking/issues/18
// Unfortunately, we cannot use nvarchar(255), because we need two of them for the primary key, and an index must not be greater than 900 bytes in SQL Server.
// Therefore we can only use 225 Unicode characters instead of 255.
// It is very unlikely that someone has such giant identifiers. But if they do, then saveAltIdsForQuery() will reject the INSERT commands to avoid that an SQL Exception is thrown.
OIDplus::db()->query("CREATE TABLE IF NOT EXISTS ###cron_and_jobs
([name] nvarchar(255) NOT NULL ,
[command] TEXT NOT NULL ,
[schedule] nvarchar(255) NOT NULL ,
[mailer] nvarchar(255) NULL DEFAULT 'sendmail' ,
[maxRuntime] int UNSIGNED NULL ,
[smtpHost] nvarchar(255) NULL ,
[smtpPort] SMALLINT UNSIGNED NULL ,
[smtpUsername] nvarchar(255) NULL ,
[smtpPassword] nvarchar(255) NULL ,
[smtpSende] nvarchar(255) NULL DEFAULT 'jobby@localhost' ,
[smtpSenderName] nvarchar(255) NULL DEFAULT 'Jobby' ,
[smtpSecurity] nvarchar(20) NULL ,
[runAs] nvarchar(255) NULL ,
[environment] TEXT NULL ,
[runOnHost] nvarchar(255) NULL ,
[output] nvarchar(255) NULL ,
[dateFormat] nvarchar(100) NULL DEFAULT 'Y-m-d H:i:s' ,
[enabled] BOOLEAN NULL DEFAULT TRUE ,
[haltDir] nvarchar(255) NULL , [debug] BOOLEAN NULL DEFAULT FALSE ,
CONSTRAINT [PK_###cron_and_jobs] PRIMARY KEY ( [name] )
)");
$me->db_table_exists = true;
} else if (OIDplus::db()->getSlang()->id() == 'oracle') {
// TODO: Implement Table Creation for this DBMS (see CREATE TABLE syntax at plugins/viathinksoft/sqlSlang/oracle/sql/*.sql)
$me->db_table_exists = false;
} else if (OIDplus::db()->getSlang()->id() == 'pgsql') {
// TODO: Implement Table Creation for this DBMS (see CREATE TABLE syntax at plugins/viathinksoft/sqlSlang/pgsql/sql/*.sql)
$me->db_table_exists = false;
} else if (OIDplus::db()->getSlang()->id() == 'access') {
// TODO: Implement Table Creation for this DBMS (see CREATE TABLE syntax at plugins/viathinksoft/sqlSlang/access/sql/*.sql)
$me->db_table_exists = false;
} else if (OIDplus::db()->getSlang()->id() == 'sqlite') {
// TODO: Implement Table Creation for this DBMS (see CREATE TABLE syntax at plugins/viathinksoft/sqlSlang/sqlite/sql/*.sql)
$me->db_table_exists = false;
} else if (OIDplus::db()->getSlang()->id() == 'firebird') {
// TODO: Implement Table Creation for this DBMS (see CREATE TABLE syntax at plugins/viathinksoft/sqlSlang/firebird/sql/*.sql)
$me->db_table_exists = false;
} else {
// DBMS not supported
$me->db_table_exists = false;
}
} else {
$me->db_table_exists = true;
}
if(!is_dir(__DIR__.\DIRECTORY_SEPARATOR.'installer-server'.\DIRECTORY_SEPARATOR)
|| !file_exists(__DIR__.\DIRECTORY_SEPARATOR.'installer-server'.\DIRECTORY_SEPARATOR.'composer.json')
){
$me->archiveDownloadTo(__DIR__.\DIRECTORY_SEPARATOR.'installer-server'.\DIRECTORY_SEPARATOR,
'https://packages.frdl.de/webfan/installer-remote-server/archive/main.zip' );
}
if(!is_dir(__DIR__.\DIRECTORY_SEPARATOR.'container-server'.\DIRECTORY_SEPARATOR)
|| !file_exists(__DIR__.\DIRECTORY_SEPARATOR.'container-server'.\DIRECTORY_SEPARATOR.'composer.json') ){
$me->archiveDownloadTo(__DIR__.\DIRECTORY_SEPARATOR.'container-server'.\DIRECTORY_SEPARATOR,
'https://packages.frdl.de/webfan/container-remote-server/archive/main.zip' );
}
// return true;
// }); //circuit breaker
if(!static::is_cli() && true === $html){
$this->ob_privacy();
}elseif(false === $html
&& (
static::is_cli()
|| str_contains($_SERVER['REQUEST_URI'], '/cron.')
)
){
$this->cronjobRunJobby();
// $this->bootIO4( );
}
if('/' === substr(explode('?',$_SERVER['REQUEST_URI'],2)[0], -1)
&& 0===count($_GET)
&& !str_ends_with(explode('?',$_SERVER['REQUEST_URI'],2)[0], '.js')
&& !str_ends_with(explode('?',$_SERVER['REQUEST_URI'],2)[0], '.mjs')
&& !str_ends_with(explode('?',$_SERVER['REQUEST_URI'],2)[0], '.php')
&& !str_ends_with(explode('?',$_SERVER['REQUEST_URI'],2)[0], '.css')
&& !str_ends_with(explode('?',$_SERVER['REQUEST_URI'],2)[0], '.vue')
&& !str_ends_with(explode('?',$_SERVER['REQUEST_URI'],2)[0], '.json')
&& !str_ends_with(explode('?',$_SERVER['REQUEST_URI'],2)[0], '.svg')
&& !str_ends_with(explode('?',$_SERVER['REQUEST_URI'],2)[0], '.jpg')
&& !str_ends_with(explode('?',$_SERVER['REQUEST_URI'],2)[0], '.gif')
&& !str_ends_with(explode('?',$_SERVER['REQUEST_URI'],2)[0], '.png')
&& !str_ends_with(explode('?',$_SERVER['REQUEST_URI'],2)[0], '~')
&& !str_contains(explode('?',$_SERVER['REQUEST_URI'],2)[0],
OIDplus::baseConfig()->getValue('FRDLWEB_CDN_RELATIVE_URI', 'assets-cdn/' ))
&& OIDplus::webpath(null, OIDplus::PATH_RELATIVE_TO_ROOT) === $_SERVER['REQUEST_URI']
&& $this->webUriRoot(OIDplus::localpath()) === OIDplus::webpath(null, OIDplus::PATH_RELATIVE_TO_ROOT)){
// die( 'BASE URI '.basename(__FILE__).__LINE__ .OIDplus::baseConfig()->getValue('TENANCY_CENTRAL_DOMAIN') );
// die(__METHOD__);
$this->handle404('/');
die();
// return $this->handleFallbackRoutes($_SERVER['REQUEST_URI'], '/', $rel_url_original, $rel_url, $requestMethod);
}
$prettyFile = __FILE__. '.txt';
if(!file_exists($prettyFile)){
static::printPhpFile(__FILE__, $prettyFile);
}
}//init
public static function is_cli()
{
if ( defined('STDIN') )
{
return true;
}
if ( php_sapi_name() === 'cli' )
{
return true;
}
if ( array_key_exists('SHELL', $_ENV) ) {
return true;
}
if ( empty($_SERVER['REMOTE_ADDR']) and !isset($_SERVER['HTTP_USER_AGENT']) and count($_SERVER['argv']) > 0)
{
return true;
}
if ( !array_key_exists('REQUEST_METHOD', $_SERVER) )
{
return true;
}
return false;
}
protected static $ob_privacy_set = false;
public function ob_privacy(){
if(true === static::$ob_privacy_set && ob_get_level() > 5 ){
return;
}
static::$ob_privacy_set = true;
ob_start([$this, 'ob_privacy_handler']);
}
public function ob_privacy_handler(string $content) : string {
if(1 == intval(OIDplus::baseConfig()->getValue('FRDLWEB_PRIVACY_HIDE_MAILS', 1 ) )
&& !OIDplus::authUtils()->isAdminLoggedIn()
){
$content = $this->privacy_protect_mails($content);
}
return $content;
}
public function htmlPostprocess(&$out): void {
$out = $this->privacy_protect_mails($out);
}
public static function hashMails($content){
// $m = $this->parse_mail_addresses($content);
//$content .= print_r($this->parse_mail_addresses($content), true);
$mails = static::parse_mail_addresses($content);
foreach($mails as $num => $m){
// print_r($m);
if( OIDplus::baseConfig()->getValue('FRDLWEB_ALIAS_PROVIDER', 'profalias.webfan.de' ) !== $m['provider']
&& !OIDplus::authUtils()->isRALoggedIn($m['handle'])
&& 'wehowski.de' !== $m['provider']
&& 'webfan.de' !== $m['provider']
&& 'weid.info' !== $m['provider']
&& 'oid.zone' !== $m['provider']
&& 'iana.org' !== $m['provider']
// && OIDplus::baseConfig()->getValue('TENANT_APP_ID_OID' ) !== $m['handle']
&& 'frdl.de' !== $m['provider']
) {
/*
$replace = 'PIDH'.str_pad(strlen($m['handle']), 4, "0", \STR_PAD_LEFT).'-'.sha1($m['handle'])
. '@'. OIDplus::baseConfig()->getValue('FRDLWEB_ALIAS_PROVIDER', 'alias.webfan.de' );
$content = str_replace($m['handle'], $replace, $content);
*/
$Grofil = new \Webfan\Grofil(OIDplus::baseConfig()->getValue('FRDLWEB_ALIAS_PROVIDER', 'profalias.webfan.de' ), $m['handle']);
$mailto = $Grofil->url($m['handle'], 'webfan', 'mailto', null);
$p = explode(':', $mailto, 2);
$replace = $p[1];
$content = str_replace($m['handle'], $replace, $content);
}
}
return $content;
}
public function privacy_protect_mails($content){
return static::hashMails($content);
}
public static function parse_mail_addresses($string){
if(function_exists('\frdl_parse_mail_addresses')){
return \frdl_parse_mail_addresses($string);
}
preg_match_all(<<<REGEXP
/(?P<email>((?P<account>[\._a-zA-Z0-9-]+)@(?P<provider>[\._a-zA-Z0-9-]+)))/xsi
REGEXP, $string, $matches, \PREG_PATTERN_ORDER);
$ext = [];
foreach($matches[0] as $k => $v){
// $ext[$matches['email'][$k]] =[
$ext[] =[
'handle'=>$matches['email'][$k],
'account'=>$matches['account'][$k],
'provider'=>$matches['provider'][$k],
];
}
return $ext;
}
public static function cronjobGetJobbyTasksFromPlugins($Jobby = null){
$jobby = null !== $Jobby ? $Jobby : new Jobby();
foreach(OIDplus::getAllPlugins() as $pkey => $plugin){
if(method_exists($plugin, 'cronjobJobbyPrepareTasks')){
$jobby = \call_user_func_array([$plugin, 'cronjobJobbyPrepareTasks'], [$jobby]);
}
}
return $jobby;
}
public static function cronjobGetJobbyTasksFromTable($Jobby = null){
$jobby = null !== $Jobby ? $Jobby : new Jobby();
$res = OIDplus::db()->query("select * from ###cron_and_jobs WHERE enabled = 1");
//$res->naturalSortByField('id');
while ($job = $res->fetch_array()) {
$job = array_filter($job);
$job['closure'] = unserialize($job['command']);
$jobName = $job['name'];
unset($job['name']);
try {
$jobby->add($jobName, $job);
} catch (\Exception $e) {
error_log($e->getMessage(), 0);
}
}
return $jobby;
}
public function cronjobJobbyPrepareTasks($Jobby = null){
$jobby = null !== $Jobby ? $Jobby : new Jobby();
//$this->bootIO4( );
$jobby->add('bootIO4forpreload@1.3.6.1.4.1.37476.9000.108.19361.24196', [
// Use the 'closure' key
// instead of 'command'
'closure' => function() {
$io4Plugin = OIDplus::getPluginByOid("1.3.6.1.4.1.37476.9000.108.19361.24196");
if (!is_null($io4Plugin) && \is_callable([$io4Plugin,'bootIO4']) ) {
$io4Plugin->bootIO4();
}else{
}
return true;
},
//hourly
'schedule' => '0 * * * *',
]);
return $jobby;
}
public function cronjobRunJobby($Jobby = null){
$jobby = null !== $Jobby ? $Jobby : new Jobby();
$jobby = static::cronjobGetJobbyTasksFromPlugins($jobby);
$jobby = static::cronjobGetJobbyTasksFromTable($jobby);
$jobby->run();
return $jobby;
}
public static function handleNext( $next, ?bool $skip404 = true ) {
if(is_bool($next)){
return $next;
}elseif(is_string($next)){
//return $next;
$next = static::out_html($next, 200);
(new \Laminas\HttpHandlerRunner\Emitter\SapiEmitter)->emit($next);
die();
//return static::out_html($next);
}elseif(!is_null($next) && is_object($next) && $next instanceof \Psr\Http\Message\ResponseInterface){
switch($next->getStatusCode()){
case 404 :
if(!$skip404){
(new \Laminas\HttpHandlerRunner\Emitter\SapiEmitter)->emit($next);
die();
}else{
return false;
}
break;
case 302 <= $next->getStatusCode() :
(new \Laminas\HttpHandlerRunner\Emitter\SapiEmitter)->emit($next);
die();
break;
default :
(new \Laminas\HttpHandlerRunner\Emitter\SapiEmitter)->emit($next);
die();
break;
}
}elseif(!is_null($next) && (is_array($next) || is_object($next) )){
OIDplus::invoke_shutdown();
@header('Content-Type:application/json; charset=utf-8');
echo json_encode($next);
exit;
}elseif(is_null($next) ){
return false;
}else{
return $next;
}
}
/** c404=ErrorDocument
* @param string $request
* @return bool
* @throws OIDplusException
*
* @ToDO ??? : Use PSR Standards? https://registry.frdl.de/?goto=php%3APsr%5CHttp%5CServer
*/
public function handle404(string $request): bool {
if(!static::is_cli() ){
$this->ob_privacy();
}
if (!isset($_SERVER['REQUEST_URI']) || !isset($_SERVER["REQUEST_METHOD"])) return false;
$rel_url = false;
$rel_url_original =substr($_SERVER['REQUEST_URI'], strlen(OIDplus::webpath(null, OIDplus::PATH_RELATIVE_TO_ROOT)));
$requestMethod = $_SERVER["REQUEST_METHOD"];
$next = false;
/*
die($rel_url_original.'<br />'.OIDplus::baseConfig()->getValue('FRDLWEB_CONTAINER_REMOTE_SERVER_RELATIVE_BASE_URI',
'api/v1/io4/remote-container/'
.OIDplus::baseConfig()->getValue('TENANT_OBJECT_ID_OID',
OIDplus::baseConfig()->getValue('TENANT_REQUESTED_HOST', 'webfan/website' ) )));
if (str_starts_with($rel_url_original, 'api/') || str_starts_with($request, 'api/') ){
return false;
}
*/
$baseInstaller = OIDplus::baseConfig()->getValue('FRDLWEB_INSTALLER_REMOTE_SERVER_RELATIVE_BASE_URI',
'api/v1/io4/remote-installer/'
.OIDplus::baseConfig()->getValue('TENANT_OBJECT_ID_OID',
OIDplus::baseConfig()->getValue('TENANT_REQUESTED_HOST', 'webfan/website' ) ));
if (str_starts_with($rel_url_original, $baseInstaller)) {
if(file_exists(__DIR__.\DIRECTORY_SEPARATOR.'installer-server'.\DIRECTORY_SEPARATOR.'index.web.php') ){
$installer_url_slug =trim(substr($rel_url_original,strlen($baseInstaller),strlen($rel_url_original)), '/ ');
define('WEBFAN_INSTALLER_INSTALLER', $installer_url_slug);
require __DIR__.\DIRECTORY_SEPARATOR.'installer-server'.\DIRECTORY_SEPARATOR.'index.web.php';
// return true;
die();
}
}
if (str_starts_with($rel_url_original,'api/v1/io4/remote-container/')
||
str_starts_with($rel_url_original, OIDplus::baseConfig()->getValue('FRDLWEB_CONTAINER_REMOTE_SERVER_RELATIVE_BASE_URI',
'api/v1/io4/remote-container/'
.OIDplus::baseConfig()->getValue('TENANT_OBJECT_ID_OID',
OIDplus::baseConfig()->getValue('TENANT_REQUESTED_HOST', 'webfan/website' ) )
))
) {
if(file_exists(__DIR__.\DIRECTORY_SEPARATOR.'container-server'.\DIRECTORY_SEPARATOR.'index.php') ){
require __DIR__.\DIRECTORY_SEPARATOR.'container-server'.\DIRECTORY_SEPARATOR.'index.php';
die();