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