-
Notifications
You must be signed in to change notification settings - Fork 0
/
DiagDebug.class.php
408 lines (334 loc) · 13.7 KB
/
DiagDebug.class.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
<?php
/*
* This file is part of the DiagDebug distribution (https://github.com/mguyard/DiagDebug).
* Copyright (c) 2021 Marc GUYARD (https://github.com/mguyard).
* Version : 0.1
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace MyPluginNameToChange;
/* * ***************************Includes Jeedom Core ********************************* */
require_once __DIR__ . '/../../../../core/php/core.inc.php';
class DiagDebug {
private $diagDebugVersion = "0.2";
private $plugin;
private $zip;
private $webSRVPathBase;
private $pluginPath;
private $zipStorage;
private $contentAdded = FALSE;
/* ------------------------------- Initialisation ------------------------------ */
/**
* Class Initialization
* @param integer $pluginId - Jeedom plugin Id
* @param string $zipStorage - Optional Path to store DiagDebug Archive
*/
public function __construct(string $pluginId, string $zipStorage = NULL)
{
// Params Verifications
if (empty($pluginId)) {
throw new \Exception(__METHOD__ . ' - You need to specify your pluginId');
}
$this->plugin = \plugin::byId($pluginId);
if (! $this->plugin instanceof \plugin) {
throw new \Exception(__METHOD__ . ' - Unable to find plugin in Jeedom (based on pluginId provided)');
}
// Retreive WebSRV base path for Jeedom
preg_match('/^(\/.*)\/core\/.*\/info.json$/', $this->plugin->getFilepath(), $webSRVBase);
$this->webSRVPathBase = $webSRVBase[1];
// Set pluginPath
$this->pluginPath = $this->webSRVPathBase.'/plugins/' . $this->plugin->getId();
// Set Default DiagDebug Archive storage if not specify
if(is_null($zipStorage)) {
$this->zipStorage = $this->pluginPath . '/data/DiagDebug';
} else {
$this->zipStorage = rtrim($zipStorage, '/');
}
if (! is_dir($this->zipStorage)) {
mkdir($this->zipStorage, 0700, TRUE);
}
// Remove all old DiagDebug archives
foreach (glob($this->zipStorage . "/DiagDebug_" . $this->plugin->getId() . "_*.ts") as $filename) {
unlink($filename);
}
// Instance Zip
$now = new \DateTime('now', new \DateTimeZone('Europe/Paris'));
$this->zipFile = $this->zipStorage . "/DiagDebug_" . $this->plugin->getId() . "_" . $now->format('Y-m-d_H\hi') . ".ts";
$this->zip = new \ZipArchive();
if ($this->zip->open($this->zipFile, \ZipArchive::CREATE)!==TRUE) {
throw new \Exception(__METHOD__ . ' - Unable to create DiagDebug Archive');
}
}
/**
* Remplace MagicWords
* @param string $input
* @return string with magic words replaced
*/
private function replaceMagicWords(string $input): string
{
// Replace Magic Words
$input = str_replace('#JEEBASE#', $this->webSRVPathBase, $input);
$input = str_replace('#PLUGBASE#', $this->pluginPath, $input);
// Return input with magic words replaced
return $input;
}
/**
* Store all plugin logs in DiagDebug Archive
* @param integer $lines - Specify optional number of line (last lines) for each plugin logs
* @return void
*/
public function addPluginLogs(int $lines = NULL)
{
$pluginLogs = $this->plugin->getLogList();
if(!empty($pluginLogs)) {
foreach ($pluginLogs as $pluginLog) {
$this->addPluginLog($pluginLog, $lines);
}
} else {
throw new \Exception(__METHOD__ . ' - Plugin don\'t have logs.');
}
}
/**
* Store plugin log in DiagDebug Archive
* @param string $pluginLog - Log Name (without path) as show in Jeedom Logs interface
* @param integer $lines - Specify optional number of line (last lines) for each plugin logs
* @return void
*/
public function addPluginLog(string $pluginLog, int $lines = NULL)
{
$pluginLogPath = \log::getPathToLog($pluginLog);
if (is_null($lines)) {
if (is_readable($pluginLogPath)) {
$this->zip->addFile($pluginLogPath, '/plugin/Logs/'.$pluginLog.'.log');
$this->contentAdded = TRUE;
} else {
throw new \Exception(__METHOD__ . ' - File ' . $pluginLogPath . ' isn\'t readable. We are not able to store this file');
}
} else {
$getLines = array_reverse(\log::get($pluginLog, (count(file($pluginLogPath))-$lines), $lines));
$this->zip->addFromString('/plugin/Logs/'.$pluginLog, implode( "\n",$getLines));
$this->contentAdded = TRUE;
}
}
/**
* Store multiple Jeedom Logs file in DiagDebug Archive
* @param array $logs - Log Name (without path) as show in Jeedom Logs interface
* @return void
*/
public function addJeedomLogs(array $logs)
{
foreach ($logs as $log) {
self::addJeedomLog($log);
}
}
/**
* Store a specific Jeedom Log file in DiagDebug Archive
* @param string $log - Log Name (without path) as show in Jeedom Logs interface
* @return void
*/
public function addJeedomLog(string $log)
{
if (empty(\log::liste($log))) {
throw new \Exception(__METHOD__ . ' - File ' . $log . ' don\'t exist in Jeedom. We are not able to store this file');
} else {
$logPath = \log::getPathToLog($log);
if (is_readable($logPath)) {
$this->zip->addFile($logPath, '/jeedom/Logs/'.$log.'.log');
$this->contentAdded = TRUE;
} else {
throw new \Exception(__METHOD__ . ' - File ' . $logPath . ' isn\'t readable. We are not able to store this file');
}
}
}
/**
* Add multiple commands result in a single file to DiagDebug Archive
* @param array $cmds - List of system commands to run
* @param string $filename - Filename where store commands results
* @param boolean $sudo - Optional to specify if commands need to be run as sudo user
* @return void
*/
public function addCmds(array $cmds, string $filename, bool $sudo = False)
{
if (!empty($cmds)) {
foreach ($cmds as $cmd) {
// Replace Magic Words
$cmd = self::replaceMagicWords($cmd);
$storage = "****************************************\n";
$storage .= "*** Cmd : " . $cmd . "\n";
$storage .= "****************************************\n\n";
if ($sudo === TRUE) {
$storage .= shell_exec(\system::getCmdSudo().' '. $cmd . ' 2>&1');
} else {
$storage .= shell_exec($cmd . ' 2>&1');
}
$storage .= "\n\n";
}
// If command is success, store result, else throw exception
if (! is_null($storage)) {
$this->zip->addFromString('/Cmds/'.$filename.'.log', $storage);
$this->contentAdded = TRUE;
} else {
throw new \Exception(__METHOD__ . ' - Failed to execute command ' . $cmd);
}
} else {
throw new \Exception(__METHOD__ . ' - List of commands is empty');
}
}
/**
* Add command result to DiagDebug Archive
* @param string $cmd - System command to run
* @param string $filename - Optional filename of result. If not specified, command will be use as result filename
* @param boolean $sudo - Optional to specify if command need to be run as sudo user
* @return void
*/
public function addCmd(string $cmd, string $filename = NULL, bool $sudo = False)
{
// Replace Magic Words
$cmd = self::replaceMagicWords($cmd);
// If filename isn't pass in params, cmd is use as filename
if(is_null($filename)) {
// If command contain slashes we replace with hash
if (strpos($cmd, '/') === FALSE) {
$filename = $cmd;
} else {
$filename = str_replace('/', '#', $cmd);
}
}
// Launch command and store result
$storage = "****************************************\n";
$storage .= "*** Cmd : " . $cmd . "\n";
$storage .= "****************************************\n\n";
if ($sudo === TRUE) {
$storage .= shell_exec(\system::getCmdSudo().' '. $cmd . ' 2>&1');
} else {
$storage .= shell_exec($cmd . ' 2>&1');
}
// If command is success, store result, else throw exception
if (! is_null($storage)) {
$this->zip->addFromString('/Cmds/'.$filename.'.log', $storage);
$this->contentAdded = TRUE;
} else {
throw new \Exception(__METHOD__ . ' - Failed to execute command ' . $cmd);
}
}
/**
* Retrieve and add Plugin Configurations to DiagDebug Archive
* @return void
*/
public function addPluginConf()
{
// Retreive and store all plugin Configurations
$pluginConfigurations = \config::searchKey(NULL, $this->plugin->getId());
foreach ($pluginConfigurations as $key => &$pluginConfiguration) {
// If configuration can be a Password, we hide it
if (preg_match('/(pass|password|pwd|mdp|motdepasse|apikey)/i', $pluginConfiguration['key'])) {
$pluginConfiguration['value'] = "** HIDDED by DiagDebug **";
}
}
if (!empty($pluginConfigurations)) {
$this->zip->addFromString('/plugin/configuration.txt', json_encode($pluginConfigurations,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));
$this->contentAdded = TRUE;
} else {
throw new \Exception(__METHOD__ . ' - No plugin configuration find');
}
}
/**
* Retrieve and add Eqlogics informations to DiagDebug Archive
* @return void
*/
public function addAllPluginEqlogic()
{
$eqList = array();
foreach (\eqLogic::byType($this->plugin->getId()) as $eqLogic) {
$eqList[$eqLogic->getId()] = array (
'name' => $eqLogic->getName(),
'logicalId' => $eqLogic->getLogicalId(),
'isVisible' => $eqLogic->getIsVisible(),
'isEnable' => $eqLogic->getIsEnable(),
'configuration' => $eqLogic->getConfiguration(NULL)
);
}
if (!empty($eqList)) {
$this->zip->addFromString('/plugin/deviceList.txt', json_encode($eqList,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));
$this->contentAdded = TRUE;
} else {
throw new \Exception(__METHOD__ . ' - No eqLogic find');
}
}
/**
* Add files to DiagDebug Archive thru array
* Support folder and wildcard
* @param array $files - Files with absolute path. Can be a file, folder, or glob (wildcard)
* @return void
*/
public function addFiles(array $files)
{
if(!empty($files)) {
foreach ($files as $file) {
$this->addFile($file);
}
} else {
throw new \Exception(__METHOD__ . ' - List of files is empty.');
}
}
/**
* Add file to DiagDebug Archive
* Support folder and wildcard
* @param string $file - File with absolute path. Can be a file, folder, or glob (wildcard)
* @return void
*/
public function addFile(string $file)
{
// Replace Magic Words
$file = self::replaceMagicWords($file);
// If $file is a directory or contain wildcard
if (is_dir($file)) {
foreach (glob($file.'/*') as $file) {
self::addFile($file);
}
}else if (strpos($file, '*') !== FALSE) {
foreach (glob($file) as $file) {
self::addFile($file);
}
}else if (is_file($file) && is_readable($file)) {
$this->zip->addFile($file, '/files/' . $file);
$this->contentAdded = TRUE;
} else {
throw new \Exception(__METHOD__ . ' - File ' . $file . ' isn\'t readable. We are not able to store this file');
}
}
/**
* Provide information to be able to download DiagDebug Archive
* @return array - with filename, filesize, absolutePath and relativePath (after the Jeedom base URL)
*/
public function download(): array
{
$this->zip->setArchiveComment('Archive create by DiagDebug ' . $this->diagDebugVersion . ' - Provided by @mguyard');
$this->zip->close();
if (! file_exists($this->zipFile)) {
if ($this->contentAdded === FALSE) {
throw new \Exception(__METHOD__ . ' - DiagDebug archive don\'t content files so archive don\' exist.');
} else {
throw new \Exception(__METHOD__ . ' - DiagDebug archive don\'t exist. Probably due to an error.');
}
return array();
} else {
return array(
'filename' => basename($this->zipFile),
'filesize' => filesize($this->zipFile),
'absolutePath' => $this->zipFile,
'relativePath' => str_replace($this->webSRVPathBase, '', $this->zipFile)
);
}
}
}