]> git.mxchange.org Git - friendica.git/blob - src/Core/Addon.php
Replace own VoidLogger with PSR-Standard NullLogger()
[friendica.git] / src / Core / Addon.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, 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\Database\DBA;
25 use Friendica\DI;
26 use Friendica\Model\Contact;
27 use Friendica\Util\Strings;
28
29 /**
30  * Some functions to handle addons
31  */
32 class Addon
33 {
34         /**
35          * The addon sub-directory
36          * @var string
37          */
38         const DIRECTORY = 'addon';
39
40         /**
41          * List of the names of enabled addons
42          *
43          * @var array
44          */
45         private static $addons = [];
46
47         /**
48          * Returns the list of available addons with their current status and info.
49          * This list is made from scanning the addon/ folder.
50          * Unsupported addons are excluded unless they already are enabled or system.show_unsupported_addon is set.
51          *
52          * @return array
53          * @throws \Exception
54          */
55         public static function getAvailableList()
56         {
57                 $addons = [];
58                 $files = glob('addon/*/');
59                 if (is_array($files)) {
60                         foreach ($files as $file) {
61                                 if (is_dir($file)) {
62                                         list($tmp, $addon) = array_map('trim', explode('/', $file));
63                                         $info = self::getInfo($addon);
64
65                                         if (DI::config()->get('system', 'show_unsupported_addons')
66                                                 || strtolower($info['status']) != 'unsupported'
67                                                 || self::isEnabled($addon)
68                                         ) {
69                                                 $addons[] = [$addon, (self::isEnabled($addon) ? 'on' : 'off'), $info];
70                                         }
71                                 }
72                         }
73                 }
74
75                 return $addons;
76         }
77
78         /**
79          * Returns a list of addons that can be configured at the node level.
80          * The list is formatted for display in the admin panel aside.
81          *
82          * @return array
83          * @throws \Exception
84          */
85         public static function getAdminList()
86         {
87                 $addons_admin = [];
88                 $addonsAdminStmt = DBA::select('addon', ['name'], ['plugin_admin' => 1], ['order' => ['name']]);
89                 while ($addon = DBA::fetch($addonsAdminStmt)) {
90                         $addons_admin[$addon['name']] = [
91                                 'url' => 'admin/addons/' . $addon['name'],
92                                 'name' => $addon['name'],
93                                 'class' => 'addon'
94                         ];
95                 }
96                 DBA::close($addonsAdminStmt);
97
98                 return $addons_admin;
99         }
100
101
102         /**
103          * Synchronize addons:
104          *
105          * system.addon contains a comma-separated list of names
106          * of addons which are used on this system.
107          * Go through the database list of already installed addons, and if we have
108          * an entry, but it isn't in the config list, call the uninstall procedure
109          * and mark it uninstalled in the database (for now we'll remove it).
110          * Then go through the config list and if we have a addon that isn't installed,
111          * call the install procedure and add it to the database.
112          *
113          */
114         public static function loadAddons()
115         {
116                 $installed_addons = DBA::selectToArray('addon', ['name'], ['installed' => true]);
117                 self::$addons = array_column($installed_addons, 'name');
118         }
119
120         /**
121          * uninstalls an addon.
122          *
123          * @param string $addon name of the addon
124          * @return void
125          * @throws \Exception
126          */
127         public static function uninstall($addon)
128         {
129                 $addon = Strings::sanitizeFilePathItem($addon);
130
131                 Logger::notice("Addon {addon}: {action}", ['action' => 'uninstall', 'addon' => $addon]);
132                 DBA::delete('addon', ['name' => $addon]);
133
134                 @include_once('addon/' . $addon . '/' . $addon . '.php');
135                 if (function_exists($addon . '_uninstall')) {
136                         $func = $addon . '_uninstall';
137                         $func();
138                 }
139
140                 Hook::delete(['file' => 'addon/' . $addon . '/' . $addon . '.php']);
141
142                 unset(self::$addons[array_search($addon, self::$addons)]);
143         }
144
145         /**
146          * installs an addon.
147          *
148          * @param string $addon name of the addon
149          * @return bool
150          * @throws \Exception
151          */
152         public static function install($addon)
153         {
154                 $addon = Strings::sanitizeFilePathItem($addon);
155
156                 $addon_file_path = 'addon/' . $addon . '/' . $addon . '.php';
157
158                 // silently fail if addon was removed of if $addon is funky
159                 if (!file_exists($addon_file_path)) {
160                         return false;
161                 }
162
163                 Logger::notice("Addon {addon}: {action}", ['action' => 'install', 'addon' => $addon]);
164                 $t = @filemtime($addon_file_path);
165                 @include_once($addon_file_path);
166                 if (function_exists($addon . '_install')) {
167                         $func = $addon . '_install';
168                         $func(DI::app());
169                 }
170
171                 DBA::insert('addon', [
172                         'name' => $addon,
173                         'installed' => true,
174                         'timestamp' => $t,
175                         'plugin_admin' => function_exists($addon . '_addon_admin'),
176                         'hidden' => file_exists('addon/' . $addon . '/.hidden')
177                 ]);
178
179                 if (!self::isEnabled($addon)) {
180                         self::$addons[] = $addon;
181                 }
182
183                 return true;
184         }
185
186         /**
187          * reload all updated addons
188          */
189         public static function reload()
190         {
191                 $addons = DBA::selectToArray('addon', [], ['installed' => true]);
192
193                 foreach ($addons as $addon) {
194                         $addonname = Strings::sanitizeFilePathItem(trim($addon['name']));
195                         $addon_file_path = 'addon/' . $addonname . '/' . $addonname . '.php';
196                         if (file_exists($addon_file_path) && $addon['timestamp'] == filemtime($addon_file_path)) {
197                                 // Addon unmodified, skipping
198                                 continue;
199                         }
200
201                         Logger::notice("Addon {addon}: {action}", ['action' => 'reload', 'addon' => $addon['name']]);
202
203                         self::uninstall($addon['name']);
204                         self::install($addon['name']);
205                 }
206         }
207
208         /**
209          * Parse addon comment in search of addon infos.
210          *
211          * like
212          * \code
213          *   * Name: addon
214          *   * Description: An addon which plugs in
215          * . * Version: 1.2.3
216          *   * Author: John <profile url>
217          *   * Author: Jane <email>
218          *   * Maintainer: Jess <email>
219          *   *
220          *   *\endcode
221          * @param string $addon the name of the addon
222          * @return array with the addon information
223          * @throws \Exception
224          */
225         public static function getInfo($addon)
226         {
227                 $addon = Strings::sanitizeFilePathItem($addon);
228
229                 $info = [
230                         'name' => $addon,
231                         'description' => "",
232                         'author' => [],
233                         'maintainer' => [],
234                         'version' => "",
235                         'status' => ""
236                 ];
237
238                 if (!is_file("addon/$addon/$addon.php")) {
239                         return $info;
240                 }
241
242                 DI::profiler()->startRecording('file');
243                 $f = file_get_contents("addon/$addon/$addon.php");
244                 DI::profiler()->stopRecording();
245
246                 $r = preg_match("|/\*.*\*/|msU", $f, $m);
247
248                 if ($r) {
249                         $ll = explode("\n", $m[0]);
250                         foreach ($ll as $l) {
251                                 $l = trim($l, "\t\n\r */");
252                                 if ($l != "") {
253                                         $addon_info = array_map("trim", explode(":", $l, 2));
254                                         if (count($addon_info) < 2) {
255                                                 continue;
256                                         }
257
258                                         list($type, $v) = $addon_info;
259                                         $type = strtolower($type);
260                                         if ($type == "author" || $type == "maintainer") {
261                                                 $r = preg_match("|([^<]+)<([^>]+)>|", $v, $m);
262                                                 if ($r) {
263                                                         if (!empty($m[2]) && empty(parse_url($m[2], PHP_URL_SCHEME))) {
264                                                                 $contact = Contact::getByURL($m[2], false);
265                                                                 if (!empty($contact['url'])) {
266                                                                         $m[2] = $contact['url'];
267                                                                 }
268                                                         }
269                                                         $info[$type][] = ['name' => $m[1], 'link' => $m[2]];
270                                                 } else {
271                                                         $info[$type][] = ['name' => $v];
272                                                 }
273                                         } else {
274                                                 if (array_key_exists($type, $info)) {
275                                                         $info[$type] = $v;
276                                                 }
277                                         }
278                                 }
279                         }
280                 }
281                 return $info;
282         }
283
284         /**
285          * Checks if the provided addon is enabled
286          *
287          * @param string $addon
288          * @return boolean
289          */
290         public static function isEnabled($addon)
291         {
292                 return in_array($addon, self::$addons);
293         }
294
295         /**
296          * Returns a list of the enabled addon names
297          *
298          * @return array
299          */
300         public static function getEnabledList()
301         {
302                 return self::$addons;
303         }
304
305         /**
306          * Returns the list of non-hidden enabled addon names
307          *
308          * @return array
309          * @throws \Exception
310          */
311         public static function getVisibleList()
312         {
313                 $visible_addons = [];
314                 $stmt = DBA::select('addon', ['name'], ['hidden' => false, 'installed' => true]);
315                 if (DBA::isResult($stmt)) {
316                         foreach (DBA::toArray($stmt) as $addon) {
317                                 $visible_addons[] = $addon['name'];
318                         }
319                 }
320
321                 return $visible_addons;
322         }
323
324         /**
325          * Shim of Hook::register left for backward compatibility purpose.
326          *
327          * @see        Hook::register
328          * @deprecated since version 2018.12
329          * @param string $hook     the name of the hook
330          * @param string $file     the name of the file that hooks into
331          * @param string $function the name of the function that the hook will call
332          * @param int    $priority A priority (defaults to 0)
333          * @return mixed|bool
334          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
335          */
336         public static function registerHook($hook, $file, $function, $priority = 0)
337         {
338                 return Hook::register($hook, $file, $function, $priority);
339         }
340
341         /**
342          * Shim of Hook::unregister left for backward compatibility purpose.
343          *
344          * @see        Hook::unregister
345          * @deprecated since version 2018.12
346          * @param string $hook     the name of the hook
347          * @param string $file     the name of the file that hooks into
348          * @param string $function the name of the function that the hook called
349          * @return boolean
350          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
351          */
352         public static function unregisterHook($hook, $file, $function)
353         {
354                 return Hook::unregister($hook, $file, $function);
355         }
356
357         /**
358          * Shim of Hook::callAll left for backward-compatibility purpose.
359          *
360          * @see        Hook::callAll
361          * @deprecated since version 2018.12
362          * @param string        $name of the hook to call
363          * @param string|array &$data to transmit to the callback handler
364          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
365          */
366         public static function callHooks($name, &$data = null)
367         {
368                 Hook::callAll($name, $data);
369         }
370 }