]> git.mxchange.org Git - friendica.git/blob - src/Core/Theme.php
Merge remote-tracking branch 'upstream/develop' into user-defined-channels
[friendica.git] / src / Core / Theme.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Core;
23
24 use Friendica\DI;
25 use Friendica\Model\Profile;
26 use Friendica\Util\Strings;
27
28 /**
29  * Some functions to handle themes
30  */
31 class Theme
32 {
33         public static function getAllowedList(): array
34         {
35                 $allowed_themes_str = DI::config()->get('system', 'allowed_themes');
36                 $allowed_themes_raw = explode(',', str_replace(' ', '', $allowed_themes_str));
37                 $allowed_themes = [];
38                 if (count($allowed_themes_raw)) {
39                         foreach ($allowed_themes_raw as $theme) {
40                                 $theme = Strings::sanitizeFilePathItem(trim($theme));
41                                 if (strlen($theme) && is_dir("view/theme/$theme")) {
42                                         $allowed_themes[] = $theme;
43                                 }
44                         }
45                 }
46
47                 return array_unique($allowed_themes);
48         }
49
50         public static function setAllowedList(array $allowed_themes)
51         {
52                 DI::config()->set('system', 'allowed_themes', implode(',', array_unique($allowed_themes)));
53         }
54
55         /**
56          * Parse theme comment in search of theme infos.
57          *
58          * like
59          * \code
60          * ..* Name: My Theme
61          *   * Description: My Cool Theme
62          * . * Version: 1.2.3
63          *   * Author: John <profile url>
64          *   * Maintainer: Jane <profile url>
65          *   *
66          * \endcode
67          * @param string $theme the name of the theme
68          * @return array
69          */
70         public static function getInfo(string $theme): array
71         {
72                 $theme = Strings::sanitizeFilePathItem($theme);
73
74                 $info = [
75                         'name' => $theme,
76                         'description' => "",
77                         'author' => [],
78                         'maintainer' => [],
79                         'version' => "",
80                         'credits' => "",
81                         'experimental' => file_exists("view/theme/$theme/experimental"),
82                         'unsupported' => file_exists("view/theme/$theme/unsupported")
83                 ];
84
85                 if (!is_file("view/theme/$theme/theme.php")) {
86                         return $info;
87                 }
88
89                 DI::profiler()->startRecording('file');
90                 $theme_file = file_get_contents("view/theme/$theme/theme.php");
91                 DI::profiler()->stopRecording();
92
93                 $result = preg_match("|/\*.*\*/|msU", $theme_file, $matches);
94
95                 if ($result) {
96                         $comment_lines = explode("\n", $matches[0]);
97                         foreach ($comment_lines as $comment_line) {
98                                 $comment_line = trim($comment_line, "\t\n\r */");
99                                 if (strpos($comment_line, ':') !== false) {
100                                         list($key, $value) = array_map("trim", explode(":", $comment_line, 2));
101                                         $key = strtolower($key);
102                                         if ($key == "author") {
103                                                 $result = preg_match("|([^<]+)<([^>]+)>|", $value, $matches);
104                                                 if ($result) {
105                                                         $info['author'][] = ['name' => $matches[1], 'link' => $matches[2]];
106                                                 } else {
107                                                         $info['author'][] = ['name' => $value];
108                                                 }
109                                         } elseif ($key == "maintainer") {
110                                                 $result = preg_match("|([^<]+)<([^>]+)>|", $value, $matches);
111                                                 if ($result) {
112                                                         $info['maintainer'][] = ['name' => $matches[1], 'link' => $matches[2]];
113                                                 } else {
114                                                         $info['maintainer'][] = ['name' => $value];
115                                                 }
116                                         } elseif (array_key_exists($key, $info)) {
117                                                 $info[$key] = $value;
118                                         }
119                                 }
120                         }
121                 }
122                 return $info;
123         }
124
125         /**
126          * Returns the theme's screenshot.
127          *
128          * The screenshot is expected as view/theme/$theme/screenshot.[png|jpg].
129          *
130          * @param string $theme The name of the theme
131          * @return string
132          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
133          */
134         public static function getScreenshot(string $theme): string
135         {
136                 $theme = Strings::sanitizeFilePathItem($theme);
137
138                 $exts = ['.png', '.jpg'];
139                 foreach ($exts as $ext) {
140                         if (file_exists('view/theme/' . $theme . '/screenshot' . $ext)) {
141                                 return DI::baseUrl() . '/view/theme/' . $theme . '/screenshot' . $ext;
142                         }
143                 }
144                 return DI::baseUrl() . '/images/blank.png';
145         }
146
147         /**
148          * Uninstalls given theme name
149          *
150          * @param string $theme Name of theme
151          * @return bool true on success
152          */
153         public static function uninstall(string $theme)
154         {
155                 $theme = Strings::sanitizeFilePathItem($theme);
156
157                 // silently fail if theme was removed or if $theme is funky
158                 if (file_exists("view/theme/$theme/theme.php")) {
159                         include_once "view/theme/$theme/theme.php";
160
161                         $func = "{$theme}_uninstall";
162                         if (function_exists($func)) {
163                                 $func();
164                         }
165
166                         Hook::delete(['file' => "view/theme/$theme/theme.php"]);
167                 }
168
169                 $allowed_themes = Theme::getAllowedList();
170                 $key = array_search($theme, $allowed_themes);
171                 if ($key !== false) {
172                         unset($allowed_themes[$key]);
173                         Theme::setAllowedList($allowed_themes);
174                         return true;
175                 }
176                 return false;
177         }
178
179         /**
180          * Installs given theme name
181          *
182          * @param string $theme Name of theme
183          * @return bool true on success
184          */
185         public static function install(string $theme): bool
186         {
187                 $theme = Strings::sanitizeFilePathItem($theme);
188
189                 // silently fail if theme was removed or if $theme is funky
190                 if (!file_exists("view/theme/$theme/theme.php")) {
191                         return false;
192                 }
193
194                 try {
195                         include_once "view/theme/$theme/theme.php";
196
197                         $func = "{$theme}_install";
198                         if (function_exists($func)) {
199                                 $func();
200                         }
201
202                         $allowed_themes = Theme::getAllowedList();
203                         $allowed_themes[] = $theme;
204                         Theme::setAllowedList($allowed_themes);
205
206                         return true;
207                 } catch (\Exception $e) {
208                         Logger::error('Theme installation failed', ['theme' => $theme, 'error' => $e->getMessage()]);
209                         return false;
210                 }
211         }
212
213         /**
214          * Get the full path to relevant theme files by filename
215          *
216          * This function searches in order in the current theme directory, in the current theme parent directory, and lastly
217          * in the base view/ folder.
218          *
219          * @param string $file Filename
220          * @return string Path to the file or empty string if the file isn't found
221          * @throws \Exception
222          */
223         public static function getPathForFile(string $file): string
224         {
225                 $a = DI::app();
226
227                 $theme = $a->getCurrentTheme();
228
229                 $parent = Strings::sanitizeFilePathItem($a->getThemeInfoValue('extends', $theme));
230
231                 $paths = [
232                         "view/theme/$theme/$file",
233                         "view/theme/$parent/$file",
234                         "view/$file",
235                 ];
236
237                 foreach ($paths as $path) {
238                         if (file_exists($path)) {
239                                 return $path;
240                         }
241                 }
242
243                 return '';
244         }
245
246         /**
247          * Return relative path to theme stylesheet file
248          *
249          * Provide a sane default if nothing is chosen or the specified theme does not exist.
250          *
251          * @param string $theme Theme name
252          * @return string
253          */
254         public static function getStylesheetPath(string $theme): string
255         {
256                 $theme = Strings::sanitizeFilePathItem($theme);
257
258                 if (!file_exists('view/theme/' . $theme . '/style.php')) {
259                         return 'view/theme/' . $theme . '/style.css';
260                 }
261
262                 $a = DI::app();
263
264                 $query_params = [];
265
266                 $puid = Profile::getThemeUid($a);
267                 if ($puid) {
268                         $query_params['puid'] = $puid;
269                 }
270
271                 return 'view/theme/' . $theme . '/style.pcss' . (!empty($query_params) ? '?' . http_build_query($query_params) : '');
272         }
273
274         /**
275          * Returns the path of the provided theme
276          *
277          * @param string $theme Theme name
278          * @return string|null
279          */
280         public static function getConfigFile(string $theme)
281         {
282                 $theme = Strings::sanitizeFilePathItem($theme);
283
284                 $a = DI::app();
285                 $base_theme = $a->getThemeInfoValue('extends') ?? '';
286
287                 if (file_exists("view/theme/$theme/config.php")) {
288                         return "view/theme/$theme/config.php";
289                 }
290                 if ($base_theme && file_exists("view/theme/$base_theme/config.php")) {
291                         return "view/theme/$base_theme/config.php";
292                 }
293                 return null;
294         }
295
296         /**
297          * Returns the background color of the provided theme if available.
298          *
299          * @param string   $theme Theme name
300          * @param int|null $uid   Current logged-in user id
301          * @return string|null
302          */
303         public static function getBackgroundColor(string $theme, int $uid = null)
304         {
305                 $theme = Strings::sanitizeFilePathItem($theme);
306
307                 $return = null;
308
309                 // silently fail if theme was removed or if $theme is funky
310                 if (file_exists("view/theme/$theme/theme.php")) {
311                         include_once "view/theme/$theme/theme.php";
312
313                         $func = "{$theme}_get_background_color";
314                         if (function_exists($func)) {
315                                 $return = $func($uid);
316                         }
317                 }
318
319                 return $return;
320         }
321
322         /**
323          * Returns the theme color of the provided theme if available.
324          *
325          * @param string   $theme
326          * @param int|null $uid   Current logged-in user id
327          * @return string|null
328          */
329         public static function getThemeColor(string $theme, int $uid = null)
330         {
331                 $theme = Strings::sanitizeFilePathItem($theme);
332
333                 $return = null;
334
335                 // silently fail if theme was removed or if $theme is funky
336                 if (file_exists("view/theme/$theme/theme.php")) {
337                         include_once "view/theme/$theme/theme.php";
338
339                         $func = "{$theme}_get_theme_color";
340                         if (function_exists($func)) {
341                                 $return = $func($uid);
342                         }
343                 }
344
345                 return $return;
346         }
347 }