1<?php
2/**
3 * Copyright (c) 2021. ComboStrap, Inc. and its affiliates. All Rights Reserved.
4 *
5 * This source code is licensed under the GPL license found in the
6 * COPYING  file in the root directory of this source tree.
7 *
8 * @license  GPL 3 (https://www.gnu.org/licenses/gpl-3.0.en.html)
9 * @author   ComboStrap <support@combostrap.com>
10 *
11 */
12
13namespace ComboStrap;
14
15
16use ComboStrap\Meta\Field\PageTemplateName;
17use ComboStrap\Meta\Field\Region;
18use ComboStrap\Web\Url;
19use ComboStrap\Web\UrlRewrite;
20use Exception;
21
22class Site
23{
24
25    const STRAP_TEMPLATE_NAME = "strap";
26
27    const SVG_LOGO_IDS = array(
28        'wiki:logo.svg',
29        'logo.svg'
30    );
31
32    const PNG_LOGO_IDS = array(
33        'logo.png',
34        'wiki:logo.png',
35        'favicon-32×32.png',
36        'favicon-16×16.png',
37        'apple-touch-icon.png',
38        'android-chrome-192x192.png'
39    );
40    /**
41     * Name of the main header slot
42     */
43    public const SLOT_MAIN_HEADER_NAME = "slot_main_header";
44    /**
45     * Name of the main footer slot
46     */
47    public const SLOT_MAIN_FOOTER_NAME = "slot_main_footer";
48
49    public const SLOT_MAIN_SIDE_NAME = "slot_main_side";
50
51    const CANONICAL = "configuration";
52    /**
53     * Strap Template meta (version, release date, ...)
54     * @var array
55     */
56    private static $STRAP_TEMPLATE_INFO;
57    private $executingContext;
58
59    private $config;
60
61    /**
62     * @param ExecutionContext $executingContext
63     */
64    public function __construct(ExecutionContext $executingContext)
65    {
66        $this->executingContext = $executingContext;
67    }
68
69
70    /**
71     * @return WikiPath[]
72     */
73    public static function getLogoImagesAsPath(): array
74    {
75        $logosPaths = PluginUtility::mergeAttributes(self::PNG_LOGO_IDS, self::SVG_LOGO_IDS);
76        $logos = [];
77        foreach ($logosPaths as $logoPath) {
78            $dokuPath = WikiPath::createMediaPathFromId($logoPath);
79            if (FileSystems::exists($dokuPath)) {
80                try {
81                    $logos[] = $dokuPath;
82                } catch (Exception $e) {
83                    // The image is not valid
84                    LogUtility::msg("The logo ($logoPath) is not a valid image. {$e->getMessage()}");
85                }
86            }
87        }
88        return $logos;
89    }
90
91    /**
92     * @deprecated see {@link SiteConfig::setUrlRewriteToDoku()}
93     */
94    public static function setUrlRewriteToDoku()
95    {
96        ExecutionContext::getActualOrCreateFromEnv()->getConfig()
97            ->setUrlRewriteToDoku();
98    }
99
100    /**
101     * Web server rewrite (Apache rewrite (htaccess), Nginx)
102     * @deprecated see {@link SiteConfig::setUrlRewriteToWebServer()}
103     */
104    public static function setUrlRewriteToWebServer()
105    {
106        ExecutionContext::getActualOrCreateFromEnv()->getConfig()
107            ->setUrlRewriteToWebServer();
108    }
109
110    /**
111     * https://www.dokuwiki.org/config:useslash
112     * @return void
113     */
114    public static function useSlashSeparatorInEndpointUrl()
115    {
116        global $conf;
117        $conf['useslash'] = 1; // use slash instead of ;
118    }
119
120
121    public static function getUrlEndpointSeparator(): string
122    {
123        $defaultSeparator = WikiPath::NAMESPACE_SEPARATOR_DOUBLE_POINT;
124        $slashSeparator = "/";
125        global $conf;
126        $key = 'useslash';
127        $value = $conf[$key];
128        try {
129            $valueInt = DataType::toInteger($value);
130        } catch (ExceptionBadArgument $e) {
131            LogUtility::internalError("The ($key) configuration does not have an integer value ($value). Default separator returned");
132            return $defaultSeparator;
133        }
134        switch ($valueInt) {
135            case 0:
136                return $defaultSeparator;
137            case 1:
138                return $slashSeparator;
139            default:
140                LogUtility::internalError("The ($key) configuration has an integer value ($valueInt) that is not a valid one (0 or 1). Default separator returned");
141                return $defaultSeparator;
142        }
143    }
144
145
146    public static function getTocMinHeadings(): int
147    {
148        global $conf;
149        $confKey = 'tocminheads';
150        $tocMinHeads = $conf[$confKey];
151        if ($tocMinHeads === null) {
152            return 0;
153        }
154        try {
155            return DataType::toInteger($tocMinHeads);
156        } catch (ExceptionBadArgument $e) {
157            LogUtility::error("The configuration ($confKey) is not an integer. Error:{$e->getMessage()}", self::CANONICAL);
158            return 0;
159        }
160    }
161
162
163    /**
164     * @param int $int
165     * @deprecated
166     */
167    public static function setTocMinHeading(int $int)
168    {
169        ExecutionContext::getActualOrCreateFromEnv()
170            ->getConfig()
171            ->setTocMinHeading($int);
172    }
173
174    public static function getTopTocLevel(): int
175    {
176        global $conf;
177        $confKey = 'toptoclevel';
178        $value = $conf[$confKey];
179        try {
180            return DataType::toInteger($value);
181        } catch (ExceptionBadArgument $e) {
182            LogUtility::error("The configuration ($confKey) has a value ($value) that is not an integer", self::CANONICAL);
183            return 1;
184        }
185    }
186
187    /**
188     * @param int $int
189     * @return void
190     * @deprecated
191     */
192    public static function setTocTopLevel(int $int)
193    {
194        ExecutionContext::getActualOrCreateFromEnv()
195            ->getConfig()
196            ->setTocTopLevel($int);
197
198    }
199
200    /**
201     * @return int
202     * https://www.dokuwiki.org/config:breadcrumbs
203     */
204    public static function getVisitedPagesCountInHistoricalBreadCrumb(): int
205    {
206        global $conf;
207        $confKey = 'breadcrumbs';
208        $visitedPagesInBreadCrumb = $conf[$confKey];
209        $defaultReturnValue = 10;
210        if ($visitedPagesInBreadCrumb === null) {
211            return $defaultReturnValue;
212        }
213        try {
214            return DataType::toInteger($visitedPagesInBreadCrumb);
215        } catch (ExceptionBadArgument $e) {
216            LogUtility::error("The configuration ($confKey) has value ($visitedPagesInBreadCrumb) that is not an integer. Error:{$e->getMessage()}");
217            return $defaultReturnValue;
218        }
219
220    }
221
222    /**
223     * This setting enables the standard DokuWiki XHTML renderer to be replaced by a render plugin that also provides XHTML output.
224     * @param string $string
225     * @return void
226     */
227    public static function setXhtmlRenderer(string $string)
228    {
229        global $conf;
230        $conf["renderer_xhtml"] = $string;
231    }
232
233    /**
234     * The host of the actual server
235     * (may be virtual)
236     * @return string
237     */
238    public static function getServerHost(): string
239    {
240        /**
241         * Based on {@link getBaseURL()}
242         * to be dokuwiki compliant
243         */
244        $remoteHost = $_SERVER['HTTP_HOST'];
245        if ($remoteHost !== null) {
246            return $remoteHost;
247        }
248        $remoteHost = $_SERVER['SERVER_NAME'];
249        if ($remoteHost !== null) {
250            return $remoteHost;
251        }
252        /**
253         * OS name
254         */
255        return php_uname('n');
256    }
257
258    public static function getLangDirection()
259    {
260        global $lang;
261        return $lang['direction'];
262    }
263
264    /**
265     * Set a site configuration outside a {@link ExecutionContext}
266     * It permits to configure the installation before execution
267     *
268     * For instance, we set the {@link PageTemplateName::CONF_DEFAULT_NAME default page layout} as {@link PageTemplateName::BLANK_TEMPLATE_VALUE}
269     * in test by default to speed ud test. In a normal environment, the default is {@link PageTemplateName::HOLY_TEMPLATE_VALUE}
270     *
271     * @param $key
272     * @param $value
273     * @param string|null $namespace - the plugin name
274     * @return void
275     * @deprecated use {@link SiteConfig::setConf()}
276     */
277    public static function setConf($key, $value, ?string $namespace = PluginUtility::PLUGIN_BASE_NAME)
278    {
279        global $conf;
280        if ($namespace !== null) {
281            $conf['plugin'][$namespace][$key] = $value;
282        } else {
283            $conf[$key] = $value;
284        }
285    }
286
287    public static function getLangObject(): Lang
288    {
289        return Lang::createFromValue(Site::getLang());
290    }
291
292
293    public static function getOldDirectory(): LocalPath
294    {
295        global $conf;
296        /**
297         * Data dir is the pages dir (savedir is the data dir)
298         */
299        $oldDirConf = $conf['olddir'];
300        if ($oldDirConf === null) {
301            throw new ExceptionRuntime("The old directory ($oldDirConf) is null");
302        }
303        return LocalPath::createFromPathString($oldDirConf);
304    }
305
306
307    function getEmailObfuscationConfiguration()
308    {
309        global $conf;
310        return $conf['mailguard'];
311    }
312
313    /**
314     * @return string|null
315     */
316    public static function getLogoUrlAsSvg(): ?string
317    {
318
319
320        $url = null;
321        foreach (self::SVG_LOGO_IDS as $svgLogo) {
322
323            $svgLogoFN = mediaFN($svgLogo);
324            if (file_exists($svgLogoFN)) {
325                $url = ml($svgLogo, '', true, '', true);
326                break;
327            }
328        }
329        return $url;
330    }
331
332    /**
333     * @throws ExceptionNotFound
334     */
335    public static function getLogoAsSvgImage(): WikiPath
336    {
337        foreach (self::SVG_LOGO_IDS as $svgLogo) {
338            $image = WikiPath::createMediaPathFromId($svgLogo);
339            if (FileSystems::exists($image)) {
340                return $image;
341            }
342        }
343        throw new ExceptionNotFound("No Svg Logo Image found");
344    }
345
346    /**
347     * @throws ExceptionNotFound
348     */
349    public static function getLogoAsRasterImage(): FetcherRaster
350    {
351        foreach (self::PNG_LOGO_IDS as $pngLogo) {
352            $pngLogoPath = WikiPath::createMediaPathFromId($pngLogo);
353            if (!FileSystems::exists($pngLogoPath)) {
354                continue;
355            }
356            try {
357                return FetcherRaster::createImageRasterFetchFromPath($pngLogoPath);
358            } catch (ExceptionCompile $e) {
359                LogUtility::error("Error while getting the log as raster image: The png logo ($pngLogo) returns an error. {$e->getMessage()}", self::CANONICAL, $e);
360                continue;
361            }
362        }
363        throw new ExceptionNotFound("No raster logo image was found");
364    }
365
366
367    public static function getLogoUrlAsPng(): ?string
368    {
369
370        $url = null;
371        foreach (self::PNG_LOGO_IDS as $pngId) {
372
373            $svgLogoFN = mediaFN($pngId);
374            if (file_exists($svgLogoFN)) {
375                try {
376                    $url = FetcherRaster::createImageRasterFetchFromId($pngId)
377                        ->getFetchUrl()
378                        ->toAbsoluteUrl()
379                        ->toHtmlString();
380                } catch (ExceptionBadArgument|ExceptionBadSyntax|ExceptionNotExists $e) {
381                    LogUtility::internalError("Hardcoded id should not give an error for the png logo url", self::CANONICAL, $e);
382                    continue;
383                }
384                break;
385            };
386        }
387        return $url;
388    }
389
390    /**
391     * @return mixed
392     * @deprecated use {@link Site::getName()} instead
393     * https://www.dokuwiki.org/config:title
394     */
395    public static function getTitle()
396    {
397        global $conf;
398        return $conf['title'];
399    }
400
401    /**
402     * https://www.dokuwiki.org/config:title
403     */
404    public static function setName($name)
405    {
406        global $conf;
407        $conf['title'] = $name;
408    }
409
410    /**
411     * @param string $sep - the separator - generally ("-") but not always
412     * @return string
413     *
414     * Locale always canonicalizes to upper case.
415     */
416    public static function getLocale(string $sep = "-"): string
417    {
418
419        $locale = null;
420
421        $lang = self::getLang();
422
423        $country = self::getLanguageRegion();
424
425        $locale = strtolower($lang) . $sep . strtoupper($country);
426
427        return $locale;
428    }
429
430    /**
431     *
432     * ISO 3166 alpha-2 country code
433     *
434     */
435    public static function getLanguageRegion(): string
436    {
437        $region = SiteConfig::getConfValue(Region::CONF_SITE_LANGUAGE_REGION);
438        if (!empty($region)) {
439            return $region;
440        } else {
441
442            if (extension_loaded("intl")) {
443                $locale = locale_get_default();
444                $localeParts = explode("_", $locale, 2);
445                if (sizeof($localeParts) === 2) {
446                    return $localeParts[1];
447                }
448            }
449        }
450        return "us";
451
452    }
453
454    /**
455     * @return string
456     * Wrapper around  https://www.dokuwiki.org/config:lang
457     */
458    public static function getLang(): string
459    {
460        global $conf;
461        $lang = $conf['lang'];
462        if ($lang === null) {
463            return "en";
464        }
465        return $lang;
466    }
467
468    /**
469     * In a {@link PluginUtility::isDevOrTest()} dev environment,
470     * don't set the
471     * https://www.dokuwiki.org/config:baseurl
472     * to be able to test the metadata / social integration
473     * via a tunnel
474     *
475     */
476    public static function getBaseUrl(): string
477    {
478
479        /**
480         * Same as {@link getBaseURL()} ??
481         */
482        global $conf;
483        $baseUrl = $conf['baseurl'];
484        if (!empty($baseUrl)) {
485            return $baseUrl;
486        }
487        return DOKU_URL;
488
489    }
490
491    public static function getTag()
492    {
493        global $conf;
494        return $conf['tag'] ?? null;
495    }
496
497    public static function setTemplate($template)
498    {
499        global $conf;
500        $conf['template'] = $template;
501    }
502
503    /**
504     * @return void
505     * @deprecated
506     */
507    public static function setCacheXhtmlOn()
508    {
509        // ensure the value is not -1, which disables caching
510        // https://www.dokuwiki.org/config:cachetime
511        global $conf;
512        $conf['cachetime'] = 60 * 60;
513    }
514
515    public static function debugIsOn()
516    {
517        global $conf;
518        return $conf['allowdebug'];
519    }
520
521    public static function setCacheDefault()
522    {
523        // The value is -1, which disables caching
524        // https://www.dokuwiki.org/config:cachetime
525        global $conf;
526        $conf['cachetime'] = -1;
527    }
528
529    public static function useHeadingAsTitle()
530    {
531        // https://www.dokuwiki.org/config:useheading
532        global $conf;
533        $conf['useheading'] = 1;
534    }
535
536    public static function useHeadingDefault()
537    {
538        // https://www.dokuwiki.org/config:useheading
539        global $conf;
540        $conf['useheading'] = 0;
541    }
542
543    public static function getTemplate()
544    {
545        global $conf;
546        return $conf['template'];
547
548    }
549
550    public static function isStrapTemplate()
551    {
552        global $conf;
553        return $conf['template'] == self::STRAP_TEMPLATE_NAME;
554    }
555
556
557    public static function getPageDirectory(): LocalPath
558    {
559        global $conf;
560        /**
561         * Data dir is the pages dir (savedir is the data dir)
562         */
563        $pageDirectory = $conf['datadir'];
564        if ($pageDirectory === null) {
565            throw new ExceptionRuntime("The page directory ($pageDirectory) is null");
566        }
567        return LocalPath::createFromPathString($pageDirectory);
568    }
569
570    public static function disableHeadingSectionEditing()
571    {
572        ExecutionContext::getActualOrCreateFromEnv()
573            ->getConfig()
574            ->setDisableHeadingSectionEditing();
575    }
576
577    public static function setBreadCrumbOn()
578    {
579        global $conf;
580        $conf['youarehere'] = 1;
581    }
582
583    public static function isHtmlRenderCacheOn(): bool
584    {
585        return ExecutionContext::getActualOrCreateFromEnv()
586            ->getConfig()
587            ->isXhtmlCacheOn();
588    }
589
590    /**
591     * @return LocalPath
592     * @deprecated
593     */
594    public static function getDataDirectory(): LocalPath
595    {
596        return ExecutionContext::getActualOrCreateFromEnv()->getConfig()->getDataDirectory();
597    }
598
599    public static function isLowQualityProtectionEnable(): bool
600    {
601        return SiteConfig::getConfValue(LowQualityPage::CONF_LOW_QUALITY_PAGE_PROTECTION_ENABLE) === 1;
602    }
603
604    /**
605     * @return string
606     * @deprecated
607     */
608    public static function getIndexPageName()
609    {
610        return ExecutionContext::getActualOrCreateFromEnv()->getConfig()->getIndexPageName();
611    }
612
613    /**
614     * @return mixed - Application / Website name
615     */
616    public static function getName()
617    {
618        return self::getTitle();
619    }
620
621    public static function getTagLine()
622    {
623        global $conf;
624        return $conf['tagline'];
625    }
626
627    /**
628     * @return int
629     */
630    public static function getXhtmlCacheTime(): int
631    {
632        global $conf;
633        $cacheTime = $conf['cachetime'];
634        if ($cacheTime === null) {
635            LogUtility::internalError("The global `cachetime` configuration was not set.", self::CANONICAL);
636            return FetcherMarkup::MAX_CACHE_AGE;
637        }
638        try {
639            return DataType::toInteger($cacheTime);
640        } catch (ExceptionBadArgument $e) {
641            LogUtility::error("The global `cachetime` configuration has a value ($cacheTime) that is not an integer. Error: {$e->getMessage()}", self::CANONICAL);
642            return FetcherMarkup::MAX_CACHE_AGE;
643        }
644    }
645
646    /**
647     * Absolute vs Relative URL
648     * https://www.dokuwiki.org/config:canonical
649     */
650    public static function shouldUrlBeAbsolute(): bool
651    {
652        global $conf;
653        $value = $conf['canonical'];
654        if ($value === 1) {
655            return true;
656        }
657        return false;
658    }
659
660    /**
661     * @param string $description
662     * Same as {@link Site::setDescription()}
663     */
664    public static function setTagLine(string $description)
665    {
666        global $conf;
667        $conf['tagline'] = $description;
668    }
669
670    /**
671     * @param string $description
672     *
673     */
674    public static function setDescription(string $description)
675    {
676        self::setTagLine($description);
677    }
678
679    /**
680     * @param string $primaryColorValue
681     * @return void
682     * @deprecated
683     */
684    public static function setPrimaryColor(string $primaryColorValue)
685    {
686        ExecutionContext::getActualOrCreateFromEnv()
687            ->getConfig()
688            ->setPrimaryColor($primaryColorValue);
689    }
690
691    /**
692     * @param $default
693     * @return ColorRgb|null
694     * @deprecated use {@link SiteConfig::getPrimaryColor()} instead
695     */
696    public static function getPrimaryColor(string $default = null): ?ColorRgb
697    {
698        try {
699            return ExecutionContext::getActualOrCreateFromEnv()
700                ->getConfig()
701                ->getPrimaryColor();
702        } catch (ExceptionNotFound $e) {
703            if ($default === null) {
704                return null;
705            }
706            try {
707                return ColorRgb::createFromString($default);
708            } catch (ExceptionBadArgument $e) {
709                LogUtility::internalError("The value ($default) is not a valid color");
710                return null;
711            }
712        }
713    }
714
715    public static function getSecondaryColor($default = null): ?ColorRgb
716    {
717        $value = Site::getSecondaryColorValue($default);
718        if ($value === null) {
719            return null;
720        }
721        try {
722            return ColorRgb::createFromString($value);
723        } catch (ExceptionCompile $e) {
724            LogUtility::msg("The secondary color value configuration ($value) is not valid. Error: {$e->getMessage()}");
725            return null;
726        }
727    }
728
729    public static function setSecondaryColor(string $secondaryColorValue)
730    {
731        self::setConf(ColorRgb::SECONDARY_COLOR_CONF, $secondaryColorValue);
732    }
733
734    public static function unsetPrimaryColor()
735    {
736        self::setConf(BrandingColors::PRIMARY_COLOR_CONF, null);
737    }
738
739
740    /**
741     * @return bool
742     * @deprecated
743     */
744    public static function isBrandingColorInheritanceEnabled(): bool
745    {
746        return ExecutionContext::getActualOrCreateFromEnv()->getConfig()->isBrandingColorInheritanceEnabled();
747    }
748
749
750    /**
751     * @param $default
752     * @return string|null
753     */
754    public static function getPrimaryColorValue($default = null): ?string
755    {
756        $value = SiteConfig::getConfValue(BrandingColors::PRIMARY_COLOR_CONF, $default);
757        if ($value !== null && trim($value) !== "") {
758            return $value;
759        }
760        if (PluginUtility::isTest()) {
761            // too much trouble
762            // the load of styles is not consistent
763            return null;
764        }
765        $styles = ColorRgb::getDokuWikiStyles();
766        return $styles["replacements"]["__theme_color__"];
767
768    }
769
770    public static function getSecondaryColorValue($default = null)
771    {
772        $value = SiteConfig::getConfValue(ColorRgb::SECONDARY_COLOR_CONF, $default);
773        if ($value === null || trim($value) === "") {
774            return null;
775        }
776        return $value;
777    }
778
779    public static function setCanonicalUrlType(string $value)
780    {
781        self::setConf(PageUrlType::CONF_CANONICAL_URL_TYPE, $value);
782    }
783
784    public static function setCanonicalUrlTypeToDefault()
785    {
786        self::setConf(PageUrlType::CONF_CANONICAL_URL_TYPE, null);
787    }
788
789    public static function isBrandingColorInheritanceFunctional(): bool
790    {
791        return self::isBrandingColorInheritanceEnabled() && Site::getPrimaryColorValue() !== null;
792    }
793
794    public static function getMediaDirectory(): LocalPath
795    {
796        global $conf;
797        $mediaDirectory = $conf['mediadir'];
798        if ($mediaDirectory === null) {
799            throw new ExceptionRuntime("The media directory ($mediaDirectory) is null");
800        }
801        return LocalPath::createFromPathString($mediaDirectory);
802    }
803
804    public static function getCacheDirectory(): LocalPath
805    {
806        global $conf;
807        $cacheDirectory = $conf['cachedir'];
808        if ($cacheDirectory === null) {
809            throw new ExceptionRuntime("The cache directory ($cacheDirectory) is null");
810        }
811        return LocalPath::createFromPathString($cacheDirectory);
812    }
813
814
815    /**
816     * @throws ExceptionCompile
817     */
818    private static function checkTemplateVersion()
819    {
820        /**
821         * Check the version
822         */
823        if (self::$STRAP_TEMPLATE_INFO === null) {
824            self::$STRAP_TEMPLATE_INFO = confToHash(__DIR__ . '/../../../tpl/strap/template.info.txt');
825        }
826        $templateVersion = self::$STRAP_TEMPLATE_INFO['version'];
827        $comboVersion = PluginUtility::$INFO_PLUGIN['version'];
828        /** @noinspection DuplicatedCode */
829        if ($templateVersion !== $comboVersion) {
830            $strapName = "Strap";
831            $comboName = "Combo";
832            $strapLink = "<a href=\"https://www.dokuwiki.org/template:strap\">$strapName</a>";
833            $comboLink = "<a href=\"https://www.dokuwiki.org/plugin:combo\">$comboName</a>";
834            if ($comboVersion > $templateVersion) {
835                $upgradeTarget = $strapName;
836            } else {
837                $upgradeTarget = $comboName;
838            }
839            $upgradeLink = "<a href=\"" . wl() . "&do=admin&page=extension" . "\">upgrade <b>$upgradeTarget</b> via the extension manager</a>";
840            $message = "You should $upgradeLink to the latest version to get a fully functional experience. The version of $comboLink is ($comboVersion) while the version of $strapLink is ($templateVersion).";
841            LogUtility::msg($message);
842            throw new ExceptionCompile($message);
843        }
844    }
845
846    /**
847     * @throws ExceptionNotFound
848     */
849    public static function getLogoImage(): WikiPath
850    {
851        $logosImages = Site::getLogoImagesAsPath();
852        if (empty($logosImages)) {
853            throw new ExceptionNotFound("No logo image was installed", "logo");
854        }
855        return $logosImages[0];
856    }
857
858
859    /**
860     * @return void
861     * @deprecated
862     */
863    public static function enableSectionEditing()
864    {
865        ExecutionContext::getActualOrCreateFromEnv()->getConfig()->setEnableSectionEditing();
866    }
867
868    public static function setDefaultTemplate()
869    {
870        global $conf;
871        $conf['template'] = "dokuwiki";
872    }
873
874    /**
875     * @return LocalPath[]
876     */
877    public static function getConfigurationFiles(): array
878    {
879        $files = [];
880        foreach (getConfigFiles('main') as $fileConfig) {
881            $files[] = LocalPath::createFromPathString($fileConfig);
882        }
883        return $files;
884    }
885
886    /**
887     * @return string the base directory for all url
888     * @throws ExceptionNotFound
889     */
890    public static function getUrlPathBaseDir(): string
891    {
892        /**
893         * Based on {@link getBaseURL()}
894         */
895        global $conf;
896        if (!empty($conf['basedir'])) {
897            return $conf['basedir'];
898        }
899        $scriptName = LocalPath::createFromPathString($_SERVER['SCRIPT_NAME']);
900        if ($scriptName->getExtension() === 'php') {
901            return Url::toUrlSeparator($scriptName->getParent()->toAbsoluteId());
902        }
903        $phpSelf = LocalPath::createFromPathString($_SERVER['PHP_SELF']);
904        if ($phpSelf->getExtension() === "php") {
905            return Url::toUrlSeparator($scriptName->getParent()->toAbsoluteId());
906        }
907        if ($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']) {
908            $dir = preg_replace('/^' . preg_quote($_SERVER['DOCUMENT_ROOT'], '/') . '/', '',
909                $_SERVER['SCRIPT_FILENAME']);
910            return Url::toUrlSeparator(dirname('/' . $dir));
911        }
912        throw new ExceptionNotFound("No Base dir");
913
914    }
915
916    public static function getUrlRewrite(): string
917    {
918        global $conf;
919        $confKey = UrlRewrite::CONF_KEY;
920        $urlRewrite = $conf[$confKey];
921        try {
922            $urlRewriteInt = DataType::toInteger($urlRewrite);
923        } catch (ExceptionBadArgument $e) {
924            LogUtility::internalError("The ($confKey) configuration is not an integer ($urlRewrite)");
925            return UrlRewrite::NO_REWRITE;
926        }
927        switch ($urlRewriteInt) {
928            case UrlRewrite::NO_REWRITE_DOKU_VALUE:
929                return UrlRewrite::NO_REWRITE;
930            case UrlRewrite::WEB_SERVER_REWRITE_DOKU_VALUE:
931                return UrlRewrite::WEB_SERVER_REWRITE;
932            case UrlRewrite::DOKU_REWRITE_DOKU_VALUE:
933                return UrlRewrite::VALUE_DOKU_REWRITE;
934            default:
935                LogUtility::internalError("The ($confKey) configuration value ($urlRewriteInt) is not a valid value (0, 1 or 2). No rewrite");
936                return UrlRewrite::NO_REWRITE;
937        }
938    }
939
940    public static function getDefaultMediaLinking(): string
941    {
942        return SiteConfig::getConfValue(MediaMarkup::CONF_DEFAULT_LINKING, MediaMarkup::LINKING_DIRECT_VALUE);
943    }
944
945    public static function shouldEndpointUrlBeAbsolute(): bool
946    {
947        global $conf;
948        return $conf['canonical'] === 1;
949    }
950
951    public static function setEndpointToAbsoluteUrl()
952    {
953        global $conf;
954        $conf['canonical'] = 1;
955    }
956
957    public static function setEndpointToDefaultUrl()
958    {
959        global $conf;
960        $conf['canonical'] = 0;
961    }
962
963    public function getConfig(): SiteConfig
964    {
965        if (isset($this->config)) {
966            return $this->config;
967        }
968        $this->config = new SiteConfig($this->executingContext);
969        return $this->config;
970    }
971
972
973}
974