-
Notifications
You must be signed in to change notification settings - Fork 0
/
boot.php
executable file
·1949 lines (1587 loc) · 58.2 KB
/
boot.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
use Code\Lib\Libzot;
use Code\Storage\Stdio;
use Code\Web\Session;
use Code\Web\HttpMeta;
use Code\Render\SmartyTemplate;
use Code\Render\Comanche;
use Code\Render\Theme;
use Code\Lib\DB_Upgrade;
use Code\Lib\System;
use Code\Lib\PConfig;
use Code\Lib\Config;
use Code\Daemon\Run;
use Code\Lib\Channel;
use Code\Lib\Navbar;
use Code\Lib\Stringsjs;
use Code\Extend\Hook;
use Code\Lib\Head;
use Code\Lib\Url;
/**
* @file boot.php
*
* @brief This file defines some global constants and includes the central App class.
*/
const REPOSITORY_ID = 'raconteur';
const DB_UPDATE_VERSION = 1267;
const PROJECT_BASE = __DIR__;
const ACTIVITYPUB_ENABLED = true;
const NOMAD_PROTOCOL_VERSION = '11.0';
// composer autoloader for all namespaced Classes
require_once('vendor/autoload.php');
if (file_exists('addon/vendor/autoload.php')) {
/** @noinspection PhpIncludeInspection */
require_once('addon/vendor/autoload.php');
}
require_once('version.php');
if (file_exists('addon/version.php')) {
require_once('addon/version.php');
}
require_once('include/constants.php');
require_once('include/config.php');
require_once('include/network.php');
require_once('include/misc.php');
require_once('include/datetime.php');
require_once('include/language.php');
require_once('include/permissions.php');
require_once('include/taxonomy.php');
require_once('include/connections.php');
require_once('include/zid.php');
require_once('include/xchan.php');
require_once('include/hubloc.php');
require_once('include/attach.php');
require_once('include/bbcode.php');
require_once('include/items.php');
require_once('include/dba/dba_driver.php');
function sys_boot() {
// Optional startup file for situations which require system
// configuration before anything is executed.
if (file_exists('.htstartup.php')) {
/** @noinspection PhpIncludeInspection */
include('.htstartup.php');
}
if(!file_exists('.htaccess')) {
Stdio::fcopy('htaccess.dist', '.htaccess');
}
// our central App object
App::init();
/*
* Load the configuration file which contains our DB credentials.
* Ignore errors. If the file doesn't exist or is empty, we are running in
* installation mode.
*/
App::$install = !((file_exists('.htconfig.php') && filesize('.htconfig.php')));
$db_host = $db_user = $db_pass = $db_data = EMPTY_STR;
$db_port = $db_type = 0;
@include('.htconfig.php');
date_default_timezone_set(App::$config['system']['timezone'] ?: 'UTC');
/*
* Try to open the database;
*/
if (! App::$install) {
DBA::dba_factory($db_host, $db_port, $db_user, $db_pass, $db_data, $db_type, App::$install);
if (! DBA::$dba->connected) {
system_unavailable();
}
unset($db_host, $db_port, $db_user, $db_pass, $db_data, $db_type);
/*
* Load configs from db. Overwrite configs from .htconfig.php
*/
load_config('system');
load_config('feature');
App::$session = new Session();
App::$session->init();
App::$sys_channel = Channel::get_system();
Hook::load();
/**
* @hooks 'startup'
*/
$arr = [];
Hook::call('startup',$arr);
}
}
function startup() {
error_reporting(E_ERROR | E_PARSE);
// Some hosting providers block/disable this
@set_time_limit(0);
if (function_exists ('ini_set')) {
// This has to be quite large
@ini_set('pcre.backtrack_limit', 5000000);
// Use cookies to store the session ID on the client side
@ini_set('session.use_only_cookies', 1);
// Disable transparent Session ID support
@ini_set('session.use_trans_sid', 0);
}
}
/**
* class: App
*
* @brief Our main application structure for the life of this page.
*
* Primarily deals with the URL that got us here
* and tries to make some sense of it, and
* stores our page contents and config storage
* and anything else that might need to be passed around
* before we spit the page out.
*
*/
class App {
public static $install = false; // true if we are installing the software
public static $account = null; // account record of the logged-in account
public static $channel = null; // channel record of the current channel of the logged-in account
public static $observer = null; // xchan record of the page observer
public static $profile_uid = 0; // If applicable, the channel_id of the "page owner"
public static $sys_channel = null; // cache sys channel lookups here
public static $poi = null; // "person of interest", generally a referenced connection or directory entry
private static $oauth_key = null; // consumer_id of oauth request, if used
public static $layout = []; // Comanche parsed template
public static $pdl = null; // Comanche page description
private static $perms = null; // observer permissions
private static $widgets = []; // widgets for this page
public static $config = []; // config cache
public static $icon = '';
public static $override_intltext_templates = [];
public static $override_markup_templates = [];
public static $override_templateroot = null;
public static $session = null;
public static $language;
public static $langsave;
public static $rtl = false;
public static $addons_admin;
public static $module_loaded = false;
public static $query_string;
public static $page;
public static $profile;
public static $user;
public static $cid;
public static $contact;
public static $contacts;
public static $content;
public static $data = [];
public static $error = false;
public static $cmd;
public static $argv;
public static $argc;
public static $module;
public static $pager;
public static $strings;
public static $stringsave; // used in push_lang() and pop_lang()
public static $hooks;
public static $interactive = true;
public static $addons;
public static $identities;
public static $css_sources = [];
public static $js_sources = [];
public static $linkrel = [];
public static $theme_info = [];
public static $is_sys = false;
public static $nav_sel;
public static $comanche;
public static $httpheaders = null;
public static $httpsig = null;
public static $channel_links;
public static $category;
// Allow themes to control internal parameters
// by changing App values in theme.php
public static $sourcename = '';
public static $videowidth = 425;
public static $videoheight = 350;
public static $meta;
/**
* @brief An array for all theme-controllable parameters
*
* Mostly unimplemented yet. Only options 'template_engine' and
* beyond are used.
*/
private static $theme = [
'sourcename' => '',
'videowidth' => 425,
'videoheight' => 350,
'force_max_items' => 0,
'thread_allow' => true,
'stylesheet' => '',
'template_engine' => 'smarty3',
];
/**
* @brief An array of registered template engines ('name'=>'class name')
*/
public static $template_engines = [];
/**
* @brief An array of instanced template engines ('name'=>'instance')
*/
public static $template_engine_instance = [];
private static $ldelim = [
'internal' => '',
'smarty3' => '{{'
];
private static $rdelim = [
'internal' => '',
'smarty3' => '}}'
];
// These represent the URL which was used to access the page
private static $scheme;
private static $hostname;
private static $path;
// This is our standardised URL - regardless of what was used
// to access the page
private static $baseurl;
/**
* App constructor.
*/
public static function init() {
// we'll reset this after we read our config file
date_default_timezone_set('UTC');
self::$config = [
'system' => []
];
self::$page = [];
self::$pager= [];
self::$query_string = '';
startup();
set_include_path(
'include' . PATH_SEPARATOR
. 'library' . PATH_SEPARATOR
. '.'
);
// normally self::$hostname (also scheme and port) will be filled in during startup.
// Set it manually from $_SERVER variables only if it wasn't.
if (! self::$hostname) {
self::$hostname = punify(get_host());
self::$scheme = 'http';
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']) {
self::$scheme = 'https';
}
elseif (isset($_SERVER['SERVER_PORT']) && (intval($_SERVER['SERVER_PORT']) === 443)) {
self::$scheme = 'https';
}
if (isset($_SERVER['SERVER_PORT']) && intval($_SERVER['SERVER_PORT']) !== 80 && intval($_SERVER['SERVER_PORT']) !== 443) {
self::$hostname .= ':' . $_SERVER['SERVER_PORT'];
}
}
/*
* Figure out if we are running at the top of a domain
* or in a subdirectory and adjust accordingly
*/
$path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
if (strlen($path) && ($path != self::$path)) {
self::$path = $path;
}
// Rewrite rules on the server will convert incoming paths to a request parameter.
// Strip this path information from our stored copy of the query_string, in case
// we need to re-use the rest of the original query.
if (isset($_SERVER['QUERY_STRING']) && str_starts_with($_SERVER['QUERY_STRING'], "req=")) {
self::$query_string = str_replace(['<','>'],['<','>'],substr($_SERVER['QUERY_STRING'], 4));
// removing leading '/' - maybe a nginx problem
if (str_starts_with(self::$query_string, "/")) {
self::$query_string = substr(self::$query_string, 1);
}
// change the first & to ?
self::$query_string = preg_replace('/&/','?',self::$query_string,1);
}
// Here is where start breaking out the URL path information to both route the
// web request based on the leading path component, and also to use remaining
// path components as C-style arguments to our individual controller modules.
if (isset($_GET['req'])) {
self::$cmd = escape_tags(trim($_GET['req'],'/\\'));
}
// support both unix and fediverse style "homedir"
if ((str_starts_with(self::$cmd, '~')) || (str_starts_with(self::$cmd, '@'))) {
self::$cmd = 'channel/' . substr(self::$cmd, 1);
}
/*
* Break the URL path into C style argc/argv style arguments for our
* modules. Given "http://example.com/module/arg1/arg2", self::$argc
* will be 3 (integer) and self::$argv will contain:
* [0] => 'module'
* [1] => 'arg1'
* [2] => 'arg2'
*
* There will always be one argument. If provided a naked domain
* URL, self::$argv[0] is set to "home".
*
* If $argv[0] has a period in it, for example foo.json; rewrite
* to module = 'foo' and set $_REQUEST['module_format'] = 'json';
*
* As a result, say you offered a feed for member bob. Most applications
* would address it as /feed/bob.xml or /feed/bob.json
* We would address it as /feed.xml/bob and /feed.json/bob because
* you're altering the output format of the feed module, and bob is
* just an identifier or variable.
*/
self::$argv = explode('/', self::$cmd);
self::$argc = count(self::$argv);
if ((array_key_exists('0', self::$argv)) && strlen(self::$argv[0])) {
if(strpos(self::$argv[0],'.')) {
$_REQUEST['module_format'] = substr(self::$argv[0],strpos(self::$argv[0],'.')+1);
self::$argv[0] = substr(self::$argv[0],0,strpos(self::$argv[0],'.'));
}
self::$module = str_replace(".", "_", self::$argv[0]);
self::$module = str_replace("-", "_", self::$module);
if(str_starts_with(self::$module, '_'))
self::$module = substr(self::$module,1);
} else {
self::$argc = 1;
self::$argv = ['home'];
self::$module = 'home';
}
/*
* See if there is any page number information, and initialise
* pagination
*/
self::$pager['unset'] = !array_key_exists('page', $_REQUEST);
self::$pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
self::$pager['itemspage'] = 60;
self::$pager['start'] = (self::$pager['page'] * self::$pager['itemspage']) - self::$pager['itemspage'];
self::$pager['total'] = 0;
if (self::$pager['start'] < 0) {
self::$pager['start'] = 0;
}
self::$meta = new HttpMeta();
/*
* register template engines (probably just smarty, but this can be extended)
*/
self::register_template_engine(get_class(new SmartyTemplate()));
}
public static function get_baseurl() {
if(is_array(self::$config)
&& array_key_exists('system',self::$config)
&& is_array(self::$config['system'])
&& array_key_exists('baseurl',self::$config['system'])
&& strlen(self::$config['system']['baseurl'])) {
$url = self::$config['system']['baseurl'];
return trim($url,'\\/');
}
$scheme = self::$scheme;
self::$baseurl = $scheme . "://" . punify(self::$hostname) . ((isset(self::$path) && strlen(self::$path)) ? '/' . self::$path : '' );
return self::$baseurl;
}
public static function set_baseurl($url) {
if(is_array(self::$config)
&& array_key_exists('system',self::$config)
&& is_array(self::$config['system'])
&& array_key_exists('baseurl',self::$config['system'])
&& strlen(self::$config['system']['baseurl'])) {
$url = punify(self::$config['system']['baseurl']);
$url = trim($url,'\\/');
}
$parsed = @parse_url($url);
self::$baseurl = $url;
if($parsed !== false) {
self::$scheme = $parsed['scheme'];
self::$hostname = punify($parsed['host']);
if(x($parsed,'port'))
self::$hostname .= ':' . $parsed['port'];
if(x($parsed,'path'))
self::$path = trim($parsed['path'],'\\/');
}
}
public static function get_scheme() {
return self::$scheme;
}
public static function get_hostname() {
return self::$hostname;
}
public static function set_hostname($h) {
self::$hostname = $h;
}
public static function set_path($p) {
self::$path = trim(trim($p), '/');
}
public static function get_path() {
return self::$path;
}
public static function get_channel_links_header() {
$s = '';
$x = self::$channel_links;
if ($x && is_array($x) && count($x)) {
foreach ($x as $y) {
if ($s) {
$s .= ',';
}
$s .= '<' . $y['href'] . '>; rel="' . $y['rel'] . '"; type="' . $y['type'] . '"';
}
}
return $s;
}
public static function set_account($acct) {
self::$account = $acct;
}
public static function get_account() {
return self::$account;
}
public static function set_channel($channel) {
self::$channel = $channel;
}
public static function get_channel(): mixed
{
return self::$channel;
}
public static function set_observer($xchan) {
self::$observer = $xchan;
}
public static function get_observer(): mixed
{
return self::$observer;
}
public static function set_perms($perms) {
self::$perms = $perms;
}
public static function get_perms() {
return self::$perms;
}
public static function set_oauth_key($consumer_id) {
self::$oauth_key = $consumer_id;
}
public static function get_oauth_key() {
return self::$oauth_key;
}
public static function set_pager_total($n) {
self::$pager['total'] = intval($n);
}
public static function set_pager_itemspage($n) {
self::$pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
self::$pager['start'] = (self::$pager['page'] * self::$pager['itemspage']) - self::$pager['itemspage'];
}
public static function build_pagehead() {
$user_scalable = ((local_channel()) ? get_pconfig(local_channel(),'system','user_scalable', 0) : 0);
$preload_images = ((local_channel()) ? get_pconfig(local_channel(),'system','preload_images',0) : 0);
$interval = ((local_channel()) ? get_pconfig(local_channel(),'system','update_interval', 30000) : 30000);
if ($interval < 15000) {
$interval = 15000;
}
$alerts_interval = intval(get_config('system','alerts_interval',10000));
if ($alerts_interval < 5000) {
$alerts_interval = 5000;
}
if (! x(self::$page,'title')) {
self::$page['title'] = ucfirst(App::$module) . ' | ' . ((array_path_exists('system/sitename',self::$config)) ? self::$config['system']['sitename'] : REPOSITORY_ID);
}
if (! self::$meta->get_field('og:title')) {
self::$meta->set('og:title',self::$page['title']);
}
// webmanifest
Head::add_link( [ 'rel' => 'manifest', 'href' => z_root() . '/manifest.webmanifest' ] );
self::$meta->set('application-name', System::get_project_name() );
self::$meta->set('generator', System::get_project_name());
$i = head_get_icon();
if (! $i) {
$i = System::get_site_icon();
}
if ($i) {
// normalise the sizes if possible.
$i = str_replace('/s/','/l/',$i);
$i = str_replace('/m/','/l/',$i);
Head::add_link(['rel' => 'shortcut icon', 'href' => str_replace('/l/','/32/',$i) ]);
Head::add_link(['rel' => 'icon', 'sizes' => '64x64', 'href' => str_replace('/l/','/64/', $i) ]);
Head::add_link(['rel' => 'icon', 'sizes' => '192x192', 'href' => str_replace('/l/','/192/', $i) ]);
}
$x = [ 'header' => '' ];
/**
* @hooks build_pagehead
* Called when creating the HTML page header.
* * \e string \b header - Return the HTML header which should be added
*/
Hook::call('build_pagehead', $x);
/* put the head template at the beginning of page['htmlhead']
* since the code added by the modules frequently depends on it
* being first
*/
if (! isset(self::$page['htmlhead'])) {
self::$page['htmlhead'] = EMPTY_STR; // needed to silence warning
}
self::$page['htmlhead'] = replace_macros(Theme::get_template('head.tpl'),
[
'$preload_images' => $preload_images,
'$user_scalable' => $user_scalable,
'$query' => urlencode(self::$query_string),
'$baseurl' => self::get_baseurl(),
'$local_channel' => local_channel(),
'$metas' => self::$meta->get(),
'$plugins' => $x['header'],
'$update_interval' => $interval,
'$alerts_interval' => $alerts_interval,
'$head_css' => Head::get_css(),
'$head_js' => Head::get_js(),
'$linkrel' => Head::get_links(),
'$js_strings' => Stringsjs::strings(),
'$zid' => Channel::get_my_address(),
'$channel_id' => ((isset(self::$profile) && is_array(self::$profile) && array_key_exists('uid',self::$profile)) ? self::$profile['uid'] : '')
]
) . self::$page['htmlhead'];
// always put main.js at the end
self::$page['htmlhead'] .= Head::get_main_js();
}
/**
* @brief Register template engine class.
*
* If $name is "", is used class static property $class::$name.
*
* @param string $class
* @param string $name
*/
public static function register_template_engine($class, $name = '') {
if (! $name) {
$v = get_class_vars($class);
if (x($v, "name")) {
$name = $v['name'];
}
}
if (! $name) {
echo "template engine <b>$class</b> cannot be registered without a name.\n";
killme();
}
self::$template_engines[$name] = $class;
}
/**
* @brief Return template engine instance.
*
* If $name is not defined, return engine defined by theme, or default.
*
* @param string $name Template engine name
*
* @return mixed
* @noinspection PhpInconsistentReturnPointsInspection
*/
public static function template_engine($name = '') {
if ($name !== '') {
$template_engine = $name;
}
else {
$template_engine = 'smarty3';
if (x(self::$theme, 'template_engine')) {
$template_engine = self::$theme['template_engine'];
}
}
if (isset(self::$template_engines[$template_engine])) {
if (isset(self::$template_engine_instance[$template_engine])) {
return self::$template_engine_instance[$template_engine];
}
else {
$class = self::$template_engines[$template_engine];
$obj = new $class();
self::$template_engine_instance[$template_engine] = $obj;
return $obj;
}
}
// If we fell through to this step, it is considered fatal.
echo "template engine <b>$template_engine</b> is not registered!\n";
killme();
}
/**
* @brief Returns the active template engine.
*
* @return string
*/
public static function get_template_engine() {
return self::$theme['template_engine'];
}
public static function set_template_engine($engine = 'smarty3') {
self::$theme['template_engine'] = $engine;
}
public static function get_template_ldelim($engine = 'smarty3') {
return self::$ldelim[$engine];
}
public static function get_template_rdelim($engine = 'smarty3') {
return self::$rdelim[$engine];
}
public static function head_set_icon($icon) {
self::$icon = $icon;
}
public static function head_get_icon() {
$icon = self::$icon;
if ($icon && ! strpos($icon,'://')) {
$icon = z_root() . $icon;
}
return $icon;
}
} // End App class
/**
* @brief Multipurpose function to check variable state.
*
* Usage: x($var) or x($array, 'key')
*
* returns false if variable/key is not set
* if variable is set, returns 1 if variable contains 'truthy' value, otherwise returns 0.
* e.g. x('') or x(0) returns 0;
*
* @param string|array $s variable to check
* @param string $k key inside the array to check
*
* @return bool|int
*/
function x($s, $k = null) {
if($k != null) {
if((is_array($s)) && (array_key_exists($k, $s))) {
if($s[$k])
return (int) 1;
return (int) 0;
}
return false;
}
else {
if(isset($s)) {
if($s) {
return (int) 1;
}
return (int) 0;
}
return false;
}
}
/**
* @brief Called from db initialisation if db is dead.
*
* @ref include/system_unavailable.php will handle everything further.
*/
function system_unavailable() {
include('include/system_unavailable.php');
system_down();
killme();
}
function clean_urls() {
// if(App::$config['system']['clean_urls'])
return true;
// return false;
}
function z_path() {
$base = z_root();
if(! clean_urls())
$base .= '/?q=';
return $base;
}
/**
* @brief Returns the baseurl.
*
* @see App::get_baseurl()
*
* @return string
*/
function z_root() {
return App::get_baseurl();
}
/**
* @brief Return absolute URL for given $path.
*
* @param string $path
*
* @return string
*/
function absurl($path) {
if (str_starts_with($path, '/')) {
return z_path() . $path;
}
return $path;
}
/**
* @brief Recursively delete a directory.
*
* @param string $path
* @return bool
*/
function rrmdir($path) {
if (is_dir($path) === true) {
$files = array_diff(scandir($path), ['.', '..']);
foreach ($files as $file) {
rrmdir(realpath($path) . '/' . $file);
}
return rmdir($path);
}
elseif (is_file($path) === true) {
return unlink($path);
}
return false;
}
/**
* @brief Function to check if request was an AJAX (xmlhttprequest) request.
*
* @return bool
*/
function is_ajax() {
return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
}
function killme_if_ajax() {
if (is_ajax()) {
killme();
}
}
/**
* Primarily involved with database upgrade, but also sets the
* base url for use in cmdline programs which don't have
* $_SERVER variables, and synchronising the state of installed plugins.
*/
function check_config() {
$saved = get_config('system','urlverify');
if (! $saved) {
set_config('system','urlverify', bin2hex(z_root()));
}
if(($saved) && ($saved != bin2hex(z_root()))) {
// our URL changed. Do something.
$oldurl = hex2bin($saved);
logger('Baseurl changed!');
$oldhost = substr($oldurl, strpos($oldurl, '//') + 2);
$host = substr(z_root(), strpos(z_root(), '//') + 2);
$is_ip_addr = (bool)preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $host);
$was_ip_addr = (bool)preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $oldhost);
// only change the url to an ip address if it was already an ip and not a dns name
if((! $is_ip_addr) || ($is_ip_addr && $was_ip_addr)) {
fix_system_urls($oldurl,z_root());
set_config('system', 'urlverify', bin2hex(z_root()));
}
else
logger('Attempt to change baseurl from a DNS name to an IP address was refused.');
}
// This will actually set the url to the one stored in .htconfig, and ignore what
// we're passing - unless we are installing, and it has never been set.
App::set_baseurl(z_root());
// Ensure the site has a system channel and that it has been upgraded.
// This function will only do work if work is required.
Channel::create_system();
/** @noinspection PhpUnusedLocalVariableInspection */
$x = new DB_Upgrade(DB_UPDATE_VERSION);
Hook::load();
check_cron_broken();
}
function fix_system_urls($oldurl, $newurl) {
logger('fix_system_urls: renaming ' . $oldurl . ' to ' . $newurl);
// Basically a site rename, but this can happen if you change from http to https for instance - even if the site name didn't change
// This should fix URL changes on our site, but other sites will end up with orphan hublocs which they will try to contact and will
// cause wasted communications.
// What we need to do after fixing this up is to send a revocation of the old URL to every other site that we communicate with so
// that they can clean up their hubloc tables (this includes directories).
// It's a very expensive operation, so you don't want to have to do it often or after your site gets to be large.
$r = q("select xchan.*, hubloc.* from xchan left join hubloc on xchan_hash = hubloc_hash where hubloc_url like '%s' and hublod_deleted = 0",
dbesc($oldurl . '%')
);
if($r) {
foreach($r as $rv) {
$channel_address = substr($rv['hubloc_addr'],0,strpos($rv['hubloc_addr'],'@'));
// get the associated channel. If we don't have a local channel, do nothing for this entry.
$c = q("select * from channel where channel_hash = '%s' limit 1",
dbesc($rv['hubloc_hash'])
);
if(! $c)
continue;
$parsed = @parse_url($newurl);
if(! $parsed)
continue;
$newhost = $parsed['host'];
// sometimes parse_url returns unexpected results.
if(str_contains($newhost, '/'))
$newhost = substr($newhost,0,strpos($newhost,'/'));
$rhs = $newhost . (($parsed['port']) ? ':' . $parsed['port'] : '');
// paths aren't going to work. You have to be at the (sub)domain root
// . (($parsed['path']) ? $parsed['path'] : '');
// The xchan_url might point to another nomadic identity clone
$replace_xchan_url = str_contains($rv['xchan_url'], $oldurl);
q("update xchan set xchan_addr = '%s', xchan_url = '%s', xchan_connurl = '%s', xchan_follow = '%s', xchan_connpage = '%s', xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_date = '%s' where xchan_hash = '%s'",
dbesc($channel_address . '@' . $rhs),
dbesc(($replace_xchan_url) ? str_replace($oldurl,$newurl,$rv['xchan_url']) : $rv['xchan_url']),
dbesc(str_replace($oldurl,$newurl,$rv['xchan_connurl'])),
dbesc(str_replace($oldurl,$newurl,$rv['xchan_follow'])),
dbesc(str_replace($oldurl,$newurl,$rv['xchan_connpage'])),
dbesc(str_replace($oldurl,$newurl,$rv['xchan_photo_l'])),
dbesc(str_replace($oldurl,$newurl,$rv['xchan_photo_m'])),
dbesc(str_replace($oldurl,$newurl,$rv['xchan_photo_s'])),
dbesc(datetime_convert()),
dbesc($rv['xchan_hash'])
);
q("update hubloc set hubloc_addr = '%s', hubloc_url = '%s', hubloc_id_url = '%s', hubloc_url_sig = '%s', hubloc_site_id = '%s', hubloc_host = '%s', hubloc_callback = '%s' where hubloc_hash = '%s' and hubloc_url = '%s'",
dbesc($channel_address . '@' . $rhs),
dbesc($newurl),
dbesc(str_replace($oldurl,$newurl,$rv['hubloc_id_url'])),
dbesc(Libzot::sign($newurl,$c[0]['channel_prvkey'])),
dbesc(Libzot::make_xchan_hash($newurl,Config::Get('system','pubkey'))),
dbesc($newhost),
dbesc($newurl . '/post'),
dbesc($rv['xchan_hash']),
dbesc($oldurl)
);
q("update profile set photo = '%s', thumb = '%s' where uid = %d",
dbesc(str_replace($oldurl,$newurl,$rv['xchan_photo_l'])),
dbesc(str_replace($oldurl,$newurl,$rv['xchan_photo_m'])),
intval($c[0]['channel_id'])
);
$m = q("select abook_id, abook_instance from abook where abook_instance like '%s' and abook_channel = %d",
dbesc('%' . $oldurl . '%'),
intval($c[0]['channel_id'])
);
if($m) {
foreach($m as $mm) {
q("update abook set abook_instance = '%s' where abook_id = %d",
dbesc(str_replace($oldurl,$newurl,$mm['abook_instance'])),
intval($mm['abook_id'])
);
}
}
Run::Summon( [ 'Notifier', 'refresh_all', $c[0]['channel_id'] ]);
}