Passed
Pull Request — master (#5041)
by
unknown
06:24
created
scripts/restore.php 3 patches
Indentation   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -282,10 +282,10 @@  discard block
 block discarded – undo
282 282
         );
283 283
     }
284 284
 } catch (Throwable $e) {
285
-	// Ensure any in-place progress bar line is terminated before printing errors
286
-	if ($interactive) {
287
-	    @fwrite(STDERR, PHP_EOL);
288
-	}
285
+    // Ensure any in-place progress bar line is terminated before printing errors
286
+    if ($interactive) {
287
+        @fwrite(STDERR, PHP_EOL);
288
+    }
289 289
     $log('WARN', 'Unable to check web sessions: ' . $e->getMessage());
290 290
 }
291 291
 
@@ -598,25 +598,25 @@  discard block
 block discarded – undo
598 598
         }
599 599
 
600 600
 
601
-	    // Progress (single-line bar on STDERR to avoid flooding the terminal)
602
-	    if ($totalSize > 0) {
603
-	        $pct = (int) floor(($newOffset / $totalSize) * 100);
604
-	        if ($pct > 100) {
605
-	            $pct = 100;
606
-	        }
607
-	        tpCliProgressBar($pct, $totalExecuted, $interactive);
608
-
609
-	        // Log progress in file every 10%
610
-	        static $lastLoggedPct = -1;
611
-	        if ($pct !== $lastLoggedPct && ($pct % 10 === 0 || $pct === 100)) {
612
-	            $lastLoggedPct = $pct;
613
-	            @file_put_contents(
614
-	                $logFile,
615
-	                '[' . date('c') . '][INFO] Progress: ' . $pct . '% (statements executed: ' . $totalExecuted . ')' . PHP_EOL,
616
-	                FILE_APPEND
617
-	            );
618
-	        }
619
-	    }
601
+        // Progress (single-line bar on STDERR to avoid flooding the terminal)
602
+        if ($totalSize > 0) {
603
+            $pct = (int) floor(($newOffset / $totalSize) * 100);
604
+            if ($pct > 100) {
605
+                $pct = 100;
606
+            }
607
+            tpCliProgressBar($pct, $totalExecuted, $interactive);
608
+
609
+            // Log progress in file every 10%
610
+            static $lastLoggedPct = -1;
611
+            if ($pct !== $lastLoggedPct && ($pct % 10 === 0 || $pct === 100)) {
612
+                $lastLoggedPct = $pct;
613
+                @file_put_contents(
614
+                    $logFile,
615
+                    '[' . date('c') . '][INFO] Progress: ' . $pct . '% (statements executed: ' . $totalExecuted . ')' . PHP_EOL,
616
+                    FILE_APPEND
617
+                );
618
+            }
619
+        }
620 620
 
621 621
         if (!empty($errors)) {
622 622
             throw new RuntimeException('SQL restore failed: ' . implode(' | ', $errors));
Please login to merge, or discard this patch.
Spacing   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -31,19 +31,19 @@  discard block
 block discarded – undo
31 31
 
32 32
 use TeampassClasses\ConfigManager\ConfigManager;
33 33
 
34
-require_once __DIR__ . '/../sources/main.functions.php';
35
-require_once __DIR__ . '/../sources/backup.functions.php';
34
+require_once __DIR__.'/../sources/main.functions.php';
35
+require_once __DIR__.'/../sources/backup.functions.php';
36 36
 
37 37
 loadClasses('DB');
38 38
 
39 39
 function tpCliOut(string $msg): void
40 40
 {
41
-    fwrite(STDOUT, $msg . PHP_EOL);
41
+    fwrite(STDOUT, $msg.PHP_EOL);
42 42
 }
43 43
 
44 44
 function tpCliErr(string $msg): void
45 45
 {
46
-    fwrite(STDERR, $msg . PHP_EOL);
46
+    fwrite(STDERR, $msg.PHP_EOL);
47 47
 }
48 48
 
49 49
 function tpCliHelp(): void
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
 
82 82
     if (!$interactive) {
83 83
         if ($pct !== $lastPct && ($pct % 5 === 0 || $pct === 100)) {
84
-            fwrite(STDERR, 'Progress: ' . $pct . '% (statements executed: ' . $totalExecuted . ')' . PHP_EOL);
84
+            fwrite(STDERR, 'Progress: '.$pct.'% (statements executed: '.$totalExecuted.')'.PHP_EOL);
85 85
             $lastPct = $pct;
86 86
         }
87 87
         return;
@@ -97,11 +97,11 @@  discard block
 block discarded – undo
97 97
 
98 98
     $width = 30;
99 99
     $filled = (int) round(($pct / 100) * $width);
100
-    $bar = str_repeat('#', $filled) . str_repeat('-', $width - $filled);
100
+    $bar = str_repeat('#', $filled).str_repeat('-', $width - $filled);
101 101
     $msg = sprintf("\r[%s] %3d%% | statements: %d", $bar, $pct, $totalExecuted);
102 102
 
103 103
     $pad = max(0, $lastLen - strlen($msg));
104
-    fwrite(STDERR, $msg . str_repeat(' ', $pad));
104
+    fwrite(STDERR, $msg.str_repeat(' ', $pad));
105 105
     $lastLen = strlen($msg);
106 106
 
107 107
     if ($pct === 100) {
@@ -133,14 +133,14 @@  discard block
 block discarded – undo
133 133
 
134 134
 // Logging
135 135
 $filesDir = rtrim((string) ($SETTINGS['path_to_files_folder'] ?? sys_get_temp_dir()), '/');
136
-$logDir = $filesDir . '/restore_cli_logs';
136
+$logDir = $filesDir.'/restore_cli_logs';
137 137
 if (!is_dir($logDir)) {
138 138
     @mkdir($logDir, 0700, true);
139 139
 }
140
-$logFile = $logDir . '/restore_' . date('Ymd_His') . '.log';
140
+$logFile = $logDir.'/restore_'.date('Ymd_His').'.log';
141 141
 
142
-$log = function (string $level, string $message) use ($logFile): void {
143
-    $line = '[' . date('c') . '][' . $level . '] ' . $message . PHP_EOL;
142
+$log = function(string $level, string $message) use ($logFile): void {
143
+    $line = '['.date('c').']['.$level.'] '.$message.PHP_EOL;
144 144
     @file_put_contents($logFile, $line, FILE_APPEND);
145 145
     if ($level === 'ERROR') {
146 146
         tpCliErr($message);
@@ -154,8 +154,8 @@  discard block
 block discarded – undo
154 154
 $lockFile = '';
155 155
 $lockHandle = false;
156 156
 $lockCandidates = [
157
-    $filesDir . '/restore_cli.lock',
158
-    rtrim((string) sys_get_temp_dir(), '/\\') . '/teampass_restore_cli_' . substr(md5($filesDir), 0, 12) . '.lock',
157
+    $filesDir.'/restore_cli.lock',
158
+    rtrim((string) sys_get_temp_dir(), '/\\').'/teampass_restore_cli_'.substr(md5($filesDir), 0, 12).'.lock',
159 159
 ];
160 160
 
161 161
 foreach ($lockCandidates as $candidate) {
@@ -168,17 +168,17 @@  discard block
 block discarded – undo
168 168
 }
169 169
 
170 170
 if ($lockHandle === false) {
171
-    $log('ERROR', 'Unable to open any lock file. Tried: ' . implode(', ', $lockCandidates));
171
+    $log('ERROR', 'Unable to open any lock file. Tried: '.implode(', ', $lockCandidates));
172 172
     exit(20);
173 173
 }
174 174
 
175 175
 if (!flock($lockHandle, LOCK_EX | LOCK_NB)) {
176
-    $log('ERROR', 'Another restore seems to be in progress (lock: ' . $lockFile . ').');
176
+    $log('ERROR', 'Another restore seems to be in progress (lock: '.$lockFile.').');
177 177
     exit(20);
178 178
 }
179 179
 
180 180
 @ftruncate($lockHandle, 0);
181
-@fwrite($lockHandle, (string) getmypid() . ' ' . date('c') . PHP_EOL);
181
+@fwrite($lockHandle, (string) getmypid().' '.date('c').PHP_EOL);
182 182
 
183 183
 // Normalize file path
184 184
 $realFile = realpath($file);
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
 }
188 188
 
189 189
 if (!is_file($file)) {
190
-    $log('ERROR', 'Backup file not found: ' . $file);
190
+    $log('ERROR', 'Backup file not found: '.$file);
191 191
     exit(3);
192 192
 }
193 193
 
@@ -213,7 +213,7 @@  discard block
 block discarded – undo
213 213
 $payloadFilePath = (string) (($payload['file']['path'] ?? ''));
214 214
 
215 215
 if ($status !== 'pending') {
216
-    $log('ERROR', 'Authorization token is not pending (status=' . $status . ').');
216
+    $log('ERROR', 'Authorization token is not pending (status='.$status.').');
217 217
     exit(31);
218 218
 }
219 219
 
@@ -236,8 +236,8 @@  discard block
 block discarded – undo
236 236
 
237 237
 if ($cmp1 === '' || $cmp1 !== $cmp2) {
238 238
     $log('ERROR', 'Authorization token does not match the provided --file path.');
239
-    $log('ERROR', 'Expected: ' . $payloadFilePath);
240
-    $log('ERROR', 'Provided: ' . $file);
239
+    $log('ERROR', 'Expected: '.$payloadFilePath);
240
+    $log('ERROR', 'Provided: '.$file);
241 241
     exit(33);
242 242
 }
243 243
 
@@ -255,9 +255,9 @@  discard block
 block discarded – undo
255 255
             'id = %i',
256 256
             $initiatorId
257 257
         );
258
-        $log('INFO', 'Disconnected restore initiator (user id=' . $initiatorId . ').');
258
+        $log('INFO', 'Disconnected restore initiator (user id='.$initiatorId.').');
259 259
     } catch (Throwable $e) {
260
-        $log('WARN', 'Unable to disconnect restore initiator: ' . $e->getMessage());
260
+        $log('WARN', 'Unable to disconnect restore initiator: '.$e->getMessage());
261 261
     }
262 262
 }
263 263
 
@@ -268,7 +268,7 @@  discard block
 block discarded – undo
268 268
     if ($initiatorId > 0) {
269 269
         $webUsers = DB::query(
270 270
             'SELECT id, login, name, lastname, session_end
271
-             FROM ' . prefixTable('users') . '
271
+             FROM ' . prefixTable('users').'
272 272
              WHERE session_end >= %i AND id != %i',
273 273
             $now,
274 274
             $initiatorId
@@ -276,7 +276,7 @@  discard block
 block discarded – undo
276 276
     } else {
277 277
         $webUsers = DB::query(
278 278
             'SELECT id, login, name, lastname, session_end
279
-             FROM ' . prefixTable('users') . '
279
+             FROM ' . prefixTable('users').'
280 280
              WHERE session_end >= %i',
281 281
             $now
282 282
         );
@@ -286,7 +286,7 @@  discard block
 block discarded – undo
286 286
 	if ($interactive) {
287 287
 	    @fwrite(STDERR, PHP_EOL);
288 288
 	}
289
-    $log('WARN', 'Unable to check web sessions: ' . $e->getMessage());
289
+    $log('WARN', 'Unable to check web sessions: '.$e->getMessage());
290 290
 }
291 291
 
292 292
 try {
@@ -301,10 +301,10 @@  discard block
 block discarded – undo
301 301
 
302 302
     $apiUsers = DB::query(
303 303
         'SELECT u.id, u.login, u.name, u.lastname, api_conn.last_api_date AS last_api
304
-         FROM ' . prefixTable('users') . ' u
304
+         FROM ' . prefixTable('users').' u
305 305
          INNER JOIN (
306 306
             SELECT qui, MAX(date) AS last_api_date
307
-            FROM ' . prefixTable('log_system') . '
307
+            FROM ' . prefixTable('log_system').'
308 308
             WHERE type = %s AND label = %s AND date >= %i
309 309
             GROUP BY qui
310 310
          ) api_conn ON api_conn.qui = u.id',
@@ -314,19 +314,19 @@  discard block
 block discarded – undo
314 314
     );
315 315
 } catch (Throwable $e) {
316 316
     // Optional: ignore API checks if unavailable
317
-    $log('WARN', 'Unable to check API activity: ' . $e->getMessage());
317
+    $log('WARN', 'Unable to check API activity: '.$e->getMessage());
318 318
 }
319 319
 
320 320
 // Enforce disconnect policy for web sessions
321 321
 if (!empty($webUsers) && $forceDisconnect === false) {
322 322
     $log('ERROR', 'Active web sessions detected. Re-run with --force-disconnect or disconnect users first.');
323 323
     foreach ($webUsers as $u) {
324
-        $log('ERROR', 'WEB user connected: ' . ($u['login'] ?? '') . ' (' . ($u['name'] ?? '') . ' ' . ($u['lastname'] ?? '') . ')');
324
+        $log('ERROR', 'WEB user connected: '.($u['login'] ?? '').' ('.($u['name'] ?? '').' '.($u['lastname'] ?? '').')');
325 325
     }
326 326
     if (!empty($apiUsers)) {
327 327
         $log('WARN', 'API activity detected as well (best-effort detection):');
328 328
         foreach ($apiUsers as $u) {
329
-            $log('WARN', 'API activity: ' . ($u['login'] ?? '') . ' (' . ($u['name'] ?? '') . ' ' . ($u['lastname'] ?? '') . ')');
329
+            $log('WARN', 'API activity: '.($u['login'] ?? '').' ('.($u['name'] ?? '').' '.($u['lastname'] ?? '').')');
330 330
         }
331 331
     }
332 332
     // IMPORTANT: keep token pending so the operator can retry after disconnecting users.
@@ -351,7 +351,7 @@  discard block
 block discarded – undo
351 351
             $now
352 352
         );
353 353
     } catch (Throwable $e) {
354
-        $log('WARN', 'Failed to force-disconnect web users: ' . $e->getMessage());
354
+        $log('WARN', 'Failed to force-disconnect web users: '.$e->getMessage());
355 355
     }
356 356
 }
357 357
 
@@ -363,7 +363,7 @@  discard block
 block discarded – undo
363 363
 if (!empty($apiUsers)) {
364 364
     $log('WARN', 'API activity detected (best-effort): those sessions may not be revocable. Proceeding.');
365 365
     foreach ($apiUsers as $u) {
366
-        $log('WARN', 'API activity: ' . ($u['login'] ?? '') . ' (' . ($u['name'] ?? '') . ' ' . ($u['lastname'] ?? '') . ')');
366
+        $log('WARN', 'API activity: '.($u['login'] ?? '').' ('.($u['name'] ?? '').' '.($u['lastname'] ?? '').')');
367 367
     }
368 368
 }
369 369
 
@@ -415,12 +415,12 @@  discard block
 block discarded – undo
415 415
             );
416 416
         }
417 417
     } catch (Throwable $e2) {
418
-        $log('WARN', 'Unable to enable maintenance mode: ' . $e2->getMessage());
418
+        $log('WARN', 'Unable to enable maintenance mode: '.$e2->getMessage());
419 419
     }
420 420
 }
421 421
 
422
-$log('INFO', 'Starting restore from: ' . $file);
423
-$log('INFO', 'Log file: ' . $logFile);
422
+$log('INFO', 'Starting restore from: '.$file);
423
+$log('INFO', 'Log file: '.$logFile);
424 424
 
425 425
 // Build decryption keys to try
426 426
 $keysToTry = [];
@@ -441,7 +441,7 @@  discard block
 block discarded – undo
441 441
         }
442 442
     }
443 443
 } catch (Throwable $e) {
444
-    $log('WARN', 'Unable to decrypt stored secrets: ' . $e->getMessage());
444
+    $log('WARN', 'Unable to decrypt stored secrets: '.$e->getMessage());
445 445
 }
446 446
 
447 447
 // Instance key (scheduled backups)
@@ -460,10 +460,10 @@  discard block
 block discarded – undo
460 460
         }
461 461
     }
462 462
 } catch (Throwable $e) {
463
-    $log('WARN', 'Unable to decrypt instance backup key: ' . $e->getMessage());
463
+    $log('WARN', 'Unable to decrypt instance backup key: '.$e->getMessage());
464 464
 }
465 465
 
466
-$keysToTry = array_values(array_unique(array_filter($keysToTry, function ($v) { return $v !== ''; })));
466
+$keysToTry = array_values(array_unique(array_filter($keysToTry, function($v) { return $v !== ''; })));
467 467
 
468 468
 // Decrypt backup file to temp SQL
469 469
 // IMPORTANT: do NOT use tempnam() here. It creates the file and can break Defuse file decrypt.
@@ -474,12 +474,12 @@  discard block
 block discarded – undo
474 474
     $tmpRand = uniqid('', true);
475 475
 }
476 476
 
477
-$tmpSql = rtrim((string) sys_get_temp_dir(), '/\\') . '/defuse_temp_restore_' . getmypid() . '_' . time() . '_' . $tmpRand . '.sql';
477
+$tmpSql = rtrim((string) sys_get_temp_dir(), '/\\').'/defuse_temp_restore_'.getmypid().'_'.time().'_'.$tmpRand.'.sql';
478 478
 
479 479
 $dec = tpDefuseDecryptWithCandidates($file, $tmpSql, $keysToTry, $SETTINGS);
480 480
 if (empty($dec['success'])) {
481 481
     @unlink($tmpSql);
482
-    $log('ERROR', 'Decrypt failed: ' . (string) ($dec['message'] ?? ''));
482
+    $log('ERROR', 'Decrypt failed: '.(string) ($dec['message'] ?? ''));
483 483
     $payload['status'] = 'failed';
484 484
     $payload['finished_at'] = time();
485 485
     $payload['error'] = 'decrypt_failed';
@@ -560,7 +560,7 @@  discard block
 block discarded – undo
560 560
                         $totalExecuted++;
561 561
                     } catch (Throwable $e) {
562 562
                         $errors[] = $e->getMessage();
563
-                        $log('ERROR', 'SQL error: ' . $e->getMessage());
563
+                        $log('ERROR', 'SQL error: '.$e->getMessage());
564 564
                         // Stop early on first error
565 565
                         break;
566 566
                     }
@@ -582,7 +582,7 @@  discard block
 block discarded – undo
582 582
             }
583 583
             DB::rollback();
584 584
             $errors[] = $e->getMessage();
585
-            $log('ERROR', 'Restore chunk failed: ' . $e->getMessage());
585
+            $log('ERROR', 'Restore chunk failed: '.$e->getMessage());
586 586
         } finally {
587 587
             try {
588 588
                 DB::query("SET FOREIGN_KEY_CHECKS = 1");
@@ -612,14 +612,14 @@  discard block
 block discarded – undo
612 612
 	            $lastLoggedPct = $pct;
613 613
 	            @file_put_contents(
614 614
 	                $logFile,
615
-	                '[' . date('c') . '][INFO] Progress: ' . $pct . '% (statements executed: ' . $totalExecuted . ')' . PHP_EOL,
615
+	                '['.date('c').'][INFO] Progress: '.$pct.'% (statements executed: '.$totalExecuted.')'.PHP_EOL,
616 616
 	                FILE_APPEND
617 617
 	            );
618 618
 	        }
619 619
 	    }
620 620
 
621 621
         if (!empty($errors)) {
622
-            throw new RuntimeException('SQL restore failed: ' . implode(' | ', $errors));
622
+            throw new RuntimeException('SQL restore failed: '.implode(' | ', $errors));
623 623
         }
624 624
 
625 625
         // End conditions
@@ -631,7 +631,7 @@  discard block
 block discarded – undo
631 631
         $offset = $newOffset;
632 632
     }
633 633
 
634
-    $log('INFO', 'SQL import completed. Total statements executed: ' . $totalExecuted);
634
+    $log('INFO', 'SQL import completed. Total statements executed: '.$totalExecuted);
635 635
 
636 636
     $payload['status'] = 'success';
637 637
     $payload['finished_at'] = time();
@@ -644,7 +644,7 @@  discard block
 block discarded – undo
644 644
     $payload['error'] = $e->getMessage();
645 645
     tpRestoreAuthorizationUpdatePayload($authId, $payload);
646 646
 
647
-    $log('ERROR', 'Restore failed: ' . $e->getMessage());
647
+    $log('ERROR', 'Restore failed: '.$e->getMessage());
648 648
     $exitCode = 50;
649 649
 } finally {
650 650
     if (is_resource($handle)) {
Please login to merge, or discard this patch.
Braces   +6 added lines, -2 removed lines patch added patch discarded remove patch
@@ -432,12 +432,16 @@
 block discarded – undo
432 432
         if (!empty($secrets['encryptionKey'])) {
433 433
             $tmp = cryption((string) $secrets['encryptionKey'], '', 'decrypt', $SETTINGS);
434 434
             $k = isset($tmp['string']) ? (string) $tmp['string'] : '';
435
-            if ($k !== '') $keysToTry[] = $k;
435
+            if ($k !== '') {
436
+                $keysToTry[] = $k;
437
+            }
436 438
         }
437 439
         if (!empty($secrets['overrideKey'])) {
438 440
             $tmp = cryption((string) $secrets['overrideKey'], '', 'decrypt', $SETTINGS);
439 441
             $k = isset($tmp['string']) ? (string) $tmp['string'] : '';
440
-            if ($k !== '') $keysToTry[] = $k;
442
+            if ($k !== '') {
443
+                $keysToTry[] = $k;
444
+            }
441 445
         }
442 446
     }
443 447
 } catch (Throwable $e) {
Please login to merge, or discard this patch.
sources/backups.queries.php 3 patches
Indentation   +63 added lines, -63 removed lines patch added patch discarded remove patch
@@ -1328,66 +1328,66 @@  discard block
 block discarded – undo
1328 1328
 
1329 1329
                     $tpRoot = (string) ($SETTINGS['cpassman_dir'] ?? '');
1330 1330
 
1331
-					// Build a command adapted to the OS and (when possible) running as the same OS user as the web server.
1332
-					// This avoids common permission issues on files/ and keeps behavior consistent.
1333
-					$osFamily = defined('PHP_OS_FAMILY') ? (string) PHP_OS_FAMILY : (string) PHP_OS;
1334
-					$isWindows = (stripos($osFamily, 'Windows') !== false);
1335
-					$webUser = '';
1336
-					if (!$isWindows && function_exists('posix_getpwuid') && function_exists('posix_geteuid')) {
1337
-						$pw = @posix_getpwuid(@posix_geteuid());
1338
-						if (is_array($pw) && !empty($pw['name'])) {
1339
-							$webUser = (string) $pw['name'];
1340
-						}
1341
-					}
1342
-
1343
-					$scriptRel = $isWindows ? 'scripts\\restore.php' : 'scripts/restore.php';
1344
-					$filePathForCmd = $isWindows ? str_replace('/', '\\', $resolvedPath) : $resolvedPath;
1345
-					$rootForCmd = $isWindows ? str_replace('/', '\\', rtrim($tpRoot, '/\\')) : rtrim($tpRoot, '/');
1346
-
1347
-					$sudoPrefix = '';
1348
-					if (!$isWindows && $webUser !== '') {
1349
-						$sudoPrefix = 'sudo -u ' . escapeshellarg($webUser) . ' ';
1350
-					}
1351
-
1352
-					$cmdNoCd = $sudoPrefix . 'php ' . $scriptRel
1353
-						. ' --file ' . escapeshellarg($filePathForCmd)
1354
-						. ' --auth-token ' . escapeshellarg($token);
1355
-					$cmdNoCdForce = $cmdNoCd . ' --force-disconnect';
1356
-
1357
-					$cmd = $cmdNoCd;
1358
-					$cmdForce = $cmdNoCdForce;
1359
-					if ($tpRoot !== '') {
1360
-						if ($isWindows) {
1361
-							$cmd = 'cd /d ' . escapeshellarg($rootForCmd) . ' && ' . $cmdNoCd;
1362
-							$cmdForce = 'cd /d ' . escapeshellarg($rootForCmd) . ' && ' . $cmdNoCdForce;
1363
-						} else {
1364
-							$cmd = 'cd ' . escapeshellarg($rootForCmd) . ' && ' . $cmdNoCd;
1365
-							$cmdForce = 'cd ' . escapeshellarg($rootForCmd) . ' && ' . $cmdNoCdForce;
1366
-						}
1367
-					}
1368
-
1369
-					// Provide multiple variants to cover the most common OS families and privilege models.
1370
-					$variants = [];
1371
-					$variants[] = [
1372
-						'label' => $isWindows ? 'Windows (CMD/Powershell)' : 'Recommended',
1373
-						'command' => $cmd,
1374
-					];
1375
-					$variants[] = [
1376
-						'label' => $isWindows ? 'Force disconnect (--force-disconnect)' : 'Force disconnect (--force-disconnect)',
1377
-						'command' => $cmdForce,
1378
-					];
1379
-					if (!$isWindows && $webUser !== '') {
1380
-						$cmdNoSudo = 'php scripts/restore.php'
1381
-							. ' --file ' . escapeshellarg($resolvedPath)
1382
-							. ' --auth-token ' . escapeshellarg($token);
1383
-						$cmdNoSudoCd = ($tpRoot !== '')
1384
-							? ('cd ' . escapeshellarg($rootForCmd) . ' && ' . $cmdNoSudo)
1385
-							: $cmdNoSudo;
1386
-						$variants[] = [
1387
-							'label' => 'Alternative (no sudo) - run as ' . $webUser,
1388
-							'command' => $cmdNoSudoCd,
1389
-						];
1390
-					}
1331
+                    // Build a command adapted to the OS and (when possible) running as the same OS user as the web server.
1332
+                    // This avoids common permission issues on files/ and keeps behavior consistent.
1333
+                    $osFamily = defined('PHP_OS_FAMILY') ? (string) PHP_OS_FAMILY : (string) PHP_OS;
1334
+                    $isWindows = (stripos($osFamily, 'Windows') !== false);
1335
+                    $webUser = '';
1336
+                    if (!$isWindows && function_exists('posix_getpwuid') && function_exists('posix_geteuid')) {
1337
+                        $pw = @posix_getpwuid(@posix_geteuid());
1338
+                        if (is_array($pw) && !empty($pw['name'])) {
1339
+                            $webUser = (string) $pw['name'];
1340
+                        }
1341
+                    }
1342
+
1343
+                    $scriptRel = $isWindows ? 'scripts\\restore.php' : 'scripts/restore.php';
1344
+                    $filePathForCmd = $isWindows ? str_replace('/', '\\', $resolvedPath) : $resolvedPath;
1345
+                    $rootForCmd = $isWindows ? str_replace('/', '\\', rtrim($tpRoot, '/\\')) : rtrim($tpRoot, '/');
1346
+
1347
+                    $sudoPrefix = '';
1348
+                    if (!$isWindows && $webUser !== '') {
1349
+                        $sudoPrefix = 'sudo -u ' . escapeshellarg($webUser) . ' ';
1350
+                    }
1351
+
1352
+                    $cmdNoCd = $sudoPrefix . 'php ' . $scriptRel
1353
+                        . ' --file ' . escapeshellarg($filePathForCmd)
1354
+                        . ' --auth-token ' . escapeshellarg($token);
1355
+                    $cmdNoCdForce = $cmdNoCd . ' --force-disconnect';
1356
+
1357
+                    $cmd = $cmdNoCd;
1358
+                    $cmdForce = $cmdNoCdForce;
1359
+                    if ($tpRoot !== '') {
1360
+                        if ($isWindows) {
1361
+                            $cmd = 'cd /d ' . escapeshellarg($rootForCmd) . ' && ' . $cmdNoCd;
1362
+                            $cmdForce = 'cd /d ' . escapeshellarg($rootForCmd) . ' && ' . $cmdNoCdForce;
1363
+                        } else {
1364
+                            $cmd = 'cd ' . escapeshellarg($rootForCmd) . ' && ' . $cmdNoCd;
1365
+                            $cmdForce = 'cd ' . escapeshellarg($rootForCmd) . ' && ' . $cmdNoCdForce;
1366
+                        }
1367
+                    }
1368
+
1369
+                    // Provide multiple variants to cover the most common OS families and privilege models.
1370
+                    $variants = [];
1371
+                    $variants[] = [
1372
+                        'label' => $isWindows ? 'Windows (CMD/Powershell)' : 'Recommended',
1373
+                        'command' => $cmd,
1374
+                    ];
1375
+                    $variants[] = [
1376
+                        'label' => $isWindows ? 'Force disconnect (--force-disconnect)' : 'Force disconnect (--force-disconnect)',
1377
+                        'command' => $cmdForce,
1378
+                    ];
1379
+                    if (!$isWindows && $webUser !== '') {
1380
+                        $cmdNoSudo = 'php scripts/restore.php'
1381
+                            . ' --file ' . escapeshellarg($resolvedPath)
1382
+                            . ' --auth-token ' . escapeshellarg($token);
1383
+                        $cmdNoSudoCd = ($tpRoot !== '')
1384
+                            ? ('cd ' . escapeshellarg($rootForCmd) . ' && ' . $cmdNoSudo)
1385
+                            : $cmdNoSudo;
1386
+                        $variants[] = [
1387
+                            'label' => 'Alternative (no sudo) - run as ' . $webUser,
1388
+                            'command' => $cmdNoSudoCd,
1389
+                        ];
1390
+                    }
1391 1391
 
1392 1392
                     echo prepareExchangedData(
1393 1393
                         [
@@ -1399,9 +1399,9 @@  discard block
 block discarded – undo
1399 1399
                             'command' => $cmd,
1400 1400
                             'command_force_disconnect' => $cmdForce,
1401 1401
                             'command_no_cd' => $cmdNoCd,
1402
-							'command_variants' => $variants,
1403
-							'os_family' => $osFamily,
1404
-							'web_user' => $webUser,
1402
+                            'command_variants' => $variants,
1403
+                            'os_family' => $osFamily,
1404
+                            'web_user' => $webUser,
1405 1405
                             'resolved_path' => $resolvedPath,
1406 1406
                         ],
1407 1407
                         'encode'
Please login to merge, or discard this patch.
Spacing   +144 added lines, -144 removed lines patch added patch discarded remove patch
@@ -40,7 +40,7 @@  discard block
 block discarded – undo
40 40
 
41 41
 // Load functions
42 42
 require_once 'main.functions.php';
43
-require_once __DIR__ . '/backup.functions.php';
43
+require_once __DIR__.'/backup.functions.php';
44 44
 $session = SessionManager::getSession();
45 45
 
46 46
 
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
     ) {
106 106
         // Not allowed page
107 107
         $session->set('system-error_code', ERR_NOT_ALLOWED);
108
-        include $SETTINGS['cpassman_dir'] . '/error.php';
108
+        include $SETTINGS['cpassman_dir'].'/error.php';
109 109
         exit;
110 110
     }
111 111
 }
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
     function tpGetSettingsValue(string $key, string $default = ''): string
146 146
     {
147 147
         $val = DB::queryFirstField(
148
-            'SELECT valeur FROM ' . prefixTable('misc') . ' WHERE type=%s AND intitule=%s LIMIT 1',
148
+            'SELECT valeur FROM '.prefixTable('misc').' WHERE type=%s AND intitule=%s LIMIT 1',
149 149
             'settings',
150 150
             $key
151 151
         );
@@ -159,12 +159,12 @@  discard block
 block discarded – undo
159 159
     function tpUpsertSettingsValue(string $key, string $value): void
160 160
     {
161 161
         $exists = DB::queryFirstField(
162
-            'SELECT 1 FROM ' . prefixTable('misc') . ' WHERE type=%s AND intitule=%s LIMIT 1',
162
+            'SELECT 1 FROM '.prefixTable('misc').' WHERE type=%s AND intitule=%s LIMIT 1',
163 163
             'settings',
164 164
             $key
165 165
         );
166 166
 
167
-        if ((int)$exists === 1) {
167
+        if ((int) $exists === 1) {
168 168
             DB::update(
169 169
                 prefixTable('misc'),
170 170
                 ['valeur' => $value],
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
     function tpGetAdminTimezoneName(): string
187 187
     {
188 188
         $tz = DB::queryFirstField(
189
-            'SELECT valeur FROM ' . prefixTable('misc') . ' WHERE type=%s AND intitule=%s LIMIT 1',
189
+            'SELECT valeur FROM '.prefixTable('misc').' WHERE type=%s AND intitule=%s LIMIT 1',
190 190
             'admin',
191 191
             'timezone'
192 192
         );
@@ -223,7 +223,7 @@  discard block
 block discarded – undo
223 223
         if ($v !== '') return $v;
224 224
     }
225 225
     if (defined('TP_VERSION') && defined('TP_VERSION_MINOR')) {
226
-        return (string) TP_VERSION . '.' . (string) TP_VERSION_MINOR;
226
+        return (string) TP_VERSION.'.'.(string) TP_VERSION_MINOR;
227 227
     }
228 228
     return '';
229 229
 }
@@ -262,7 +262,7 @@  discard block
 block discarded – undo
262 262
     if ($operationId > 0) {
263 263
         // Uploaded restore file (temp_file in misc)
264 264
         $data = DB::queryFirstRow(
265
-            'SELECT valeur FROM ' . prefixTable('misc') . ' WHERE increment_id = %i LIMIT 1',
265
+            'SELECT valeur FROM '.prefixTable('misc').' WHERE increment_id = %i LIMIT 1',
266 266
             $operationId
267 267
         );
268 268
         $val = isset($data['valeur']) ? (string) $data['valeur'] : '';
@@ -281,8 +281,8 @@  discard block
 block discarded – undo
281 281
         }
282 282
 
283 283
         $bn = basename($val);
284
-        $baseDir = rtrim((string) ($SETTINGS['path_to_files_folder'] ?? (__DIR__ . '/../files')), '/');
285
-        $targetPath = $baseDir . '/' . $bn;
284
+        $baseDir = rtrim((string) ($SETTINGS['path_to_files_folder'] ?? (__DIR__.'/../files')), '/');
285
+        $targetPath = $baseDir.'/'.$bn;
286 286
 
287 287
         if (function_exists('tpParseSchemaLevelFromBackupFilename')) {
288 288
             $backupSchema = (string) tpParseSchemaLevelFromBackupFilename($bn);
@@ -306,13 +306,13 @@  discard block
 block discarded – undo
306 306
             ];
307 307
         }
308 308
 
309
-        $baseDir = rtrim((string) ($SETTINGS['path_to_files_folder'] ?? (__DIR__ . '/../files')), '/');
309
+        $baseDir = rtrim((string) ($SETTINGS['path_to_files_folder'] ?? (__DIR__.'/../files')), '/');
310 310
         if ($serverScope === 'scheduled') {
311
-            $baseFilesDir = (string) ($SETTINGS['path_to_files_folder'] ?? (__DIR__ . '/../files'));
312
-            $dir = (string) tpGetSettingsValue('bck_scheduled_output_dir', rtrim($baseFilesDir, '/') . '/backups');
311
+            $baseFilesDir = (string) ($SETTINGS['path_to_files_folder'] ?? (__DIR__.'/../files'));
312
+            $dir = (string) tpGetSettingsValue('bck_scheduled_output_dir', rtrim($baseFilesDir, '/').'/backups');
313 313
             $baseDir = rtrim($dir, '/');
314 314
         }
315
-        $targetPath = $baseDir . '/' . $bn;
315
+        $targetPath = $baseDir.'/'.$bn;
316 316
 
317 317
         if (function_exists('tpGetBackupTpFilesVersionFromMeta')) {
318 318
             $v = (string) tpGetBackupTpFilesVersionFromMeta($targetPath);
@@ -455,14 +455,14 @@  discard block
 block discarded – undo
455 455
                 exit;
456 456
             }
457 457
 
458
-            $baseFilesDir = (string) ($SETTINGS['path_to_files_folder'] ?? (__DIR__ . '/../files'));
459
-            $dir = (string) tpGetSettingsValue('bck_scheduled_output_dir', rtrim($baseFilesDir, '/') . '/backups');
460
-            $fp = rtrim($dir, '/') . '/' . $get_file;
458
+            $baseFilesDir = (string) ($SETTINGS['path_to_files_folder'] ?? (__DIR__.'/../files'));
459
+            $dir = (string) tpGetSettingsValue('bck_scheduled_output_dir', rtrim($baseFilesDir, '/').'/backups');
460
+            $fp = rtrim($dir, '/').'/'.$get_file;
461 461
 
462 462
             $dirReal = realpath($dir);
463 463
             $fpReal = realpath($fp);
464 464
 
465
-            if ($dirReal === false || $fpReal === false || strpos($fpReal, $dirReal . DIRECTORY_SEPARATOR) !== 0 || is_file($fpReal) === false) {
465
+            if ($dirReal === false || $fpReal === false || strpos($fpReal, $dirReal.DIRECTORY_SEPARATOR) !== 0 || is_file($fpReal) === false) {
466 466
                 header('HTTP/1.1 404 Not Found');
467 467
                 exit;
468 468
             }
@@ -494,13 +494,13 @@  discard block
 block discarded – undo
494 494
 
495 495
             header('Content-Description: File Transfer');
496 496
             header('Content-Type: application/octet-stream');
497
-            header('Content-Disposition: attachment; filename="' . $get_file . '"');
497
+            header('Content-Disposition: attachment; filename="'.$get_file.'"');
498 498
             header('Content-Transfer-Encoding: binary');
499 499
             header('Expires: 0');
500 500
             header('Cache-Control: private, must-revalidate');
501 501
             header('Pragma: public');
502 502
             if ($size > 0) {
503
-                header('Content-Length: ' . $size);
503
+                header('Content-Length: '.$size);
504 504
             }
505 505
 
506 506
             readfile($fpReal);
@@ -538,7 +538,7 @@  discard block
 block discarded – undo
538 538
             // Prepare variables
539 539
             $encryptionKey = filter_var($dataReceived['encryptionKey'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
540 540
         
541
-            require_once __DIR__ . '/backup.functions.php';
541
+            require_once __DIR__.'/backup.functions.php';
542 542
 
543 543
             $backupResult = tpCreateDatabaseBackup($SETTINGS, $encryptionKey);
544 544
 
@@ -557,7 +557,7 @@  discard block
 block discarded – undo
557 557
 // Write metadata sidecar (<backup>.meta.json) for fast listings / migration safety
558 558
 try {
559 559
     if (function_exists('tpWriteBackupMetadata') && !empty($backupResult['filepath'])) {
560
-        tpWriteBackupMetadata((string)$backupResult['filepath'], '', '', ['source' => 'onthefly']);
560
+        tpWriteBackupMetadata((string) $backupResult['filepath'], '', '', ['source' => 'onthefly']);
561 561
     }
562 562
 } catch (Throwable $ignored) {
563 563
     // best effort
@@ -580,9 +580,9 @@  discard block
 block discarded – undo
580 580
                 array(
581 581
                     'error' => false,
582 582
                     'message' => '',
583
-                    'download' => 'sources/downloadFile.php?name=' . urlencode($filename) .
584
-                        '&action=backup&file=' . $filename . '&type=sql&key=' . $session->get('key') . '&key_tmp=' .
585
-                        $session->get('user-key_tmp') . '&pathIsFiles=1',
583
+                    'download' => 'sources/downloadFile.php?name='.urlencode($filename).
584
+                        '&action=backup&file='.$filename.'&type=sql&key='.$session->get('key').'&key_tmp='.
585
+                        $session->get('user-key_tmp').'&pathIsFiles=1',
586 586
                 ),
587 587
                 'encode'
588 588
             );
@@ -592,7 +592,7 @@  discard block
 block discarded – undo
592 592
          * ============================================================ */
593 593
 
594 594
         case 'scheduled_get_settings':
595
-            if ($post_key !== $session->get('key') || (int)$session->get('user-admin') !== 1) {
595
+            if ($post_key !== $session->get('key') || (int) $session->get('user-admin') !== 1) {
596 596
                 echo prepareExchangedData(['error' => true, 'message' => 'Not allowed'], 'encode');
597 597
                 break;
598 598
             }
@@ -626,12 +626,12 @@  discard block
 block discarded – undo
626 626
 
627 627
         case 'disk_usage':
628 628
             // Provide disk usage information for the storage containing the <files> directory
629
-            if ($post_key !== $session->get('key') || (int)$session->get('user-admin') !== 1) {
629
+            if ($post_key !== $session->get('key') || (int) $session->get('user-admin') !== 1) {
630 630
                 echo prepareExchangedData(['error' => true, 'message' => 'Not allowed'], 'encode');
631 631
                 break;
632 632
             }
633 633
 
634
-            $baseFilesDir = (string)($SETTINGS['path_to_files_folder'] ?? (__DIR__ . '/../files'));
634
+            $baseFilesDir = (string) ($SETTINGS['path_to_files_folder'] ?? (__DIR__.'/../files'));
635 635
             $dirReal = realpath($baseFilesDir);
636 636
 
637 637
             if ($dirReal === false) {
@@ -642,21 +642,21 @@  discard block
 block discarded – undo
642 642
             $total = @disk_total_space($dirReal);
643 643
             $free = @disk_free_space($dirReal);
644 644
 
645
-            if ($total === false || $free === false || (float)$total <= 0) {
645
+            if ($total === false || $free === false || (float) $total <= 0) {
646 646
                 echo prepareExchangedData(['error' => true, 'message' => 'Unable to read disk usage'], 'encode');
647 647
                 break;
648 648
             }
649 649
 
650
-            $used = max(0.0, (float)$total - (float)$free);
651
-            $pct = round(($used / (float)$total) * 100, 1);
650
+            $used = max(0.0, (float) $total - (float) $free);
651
+            $pct = round(($used / (float) $total) * 100, 1);
652 652
 
653
-            $label = tpFormatBytes($used) . ' / ' . tpFormatBytes((float)$total);
653
+            $label = tpFormatBytes($used).' / '.tpFormatBytes((float) $total);
654 654
             $tooltip = sprintf(
655 655
                 $lang->get('bck_storage_usage_tooltip'),
656 656
                 tpFormatBytes($used),
657
-                tpFormatBytes((float)$total),
658
-                (string)$pct,
659
-                tpFormatBytes((float)$free),
657
+                tpFormatBytes((float) $total),
658
+                (string) $pct,
659
+                tpFormatBytes((float) $free),
660 660
                 $dirReal
661 661
             );
662 662
 
@@ -708,7 +708,7 @@  discard block
 block discarded – undo
708 708
             break;
709 709
 
710 710
         case 'scheduled_save_settings':
711
-            if ($post_key !== $session->get('key') || (int)$session->get('user-admin') !== 1) {
711
+            if ($post_key !== $session->get('key') || (int) $session->get('user-admin') !== 1) {
712 712
                 echo prepareExchangedData(['error' => true, 'message' => 'Not allowed'], 'encode');
713 713
                 break;
714 714
             }
@@ -716,26 +716,26 @@  discard block
 block discarded – undo
716 716
             $dataReceived = prepareExchangedData($post_data, 'decode');
717 717
             if (!is_array($dataReceived)) $dataReceived = [];
718 718
 
719
-            $enabled = (int)($dataReceived['enabled'] ?? 0);
719
+            $enabled = (int) ($dataReceived['enabled'] ?? 0);
720 720
             $enabled = ($enabled === 1) ? 1 : 0;
721 721
 
722 722
 
723
-            $emailReportEnabled = (int)($dataReceived['email_report_enabled'] ?? 0);
723
+            $emailReportEnabled = (int) ($dataReceived['email_report_enabled'] ?? 0);
724 724
             $emailReportEnabled = ($emailReportEnabled === 1) ? 1 : 0;
725 725
 
726
-            $emailReportOnlyFailures = (int)($dataReceived['email_report_only_failures'] ?? 0);
726
+            $emailReportOnlyFailures = (int) ($dataReceived['email_report_only_failures'] ?? 0);
727 727
             $emailReportOnlyFailures = ($emailReportOnlyFailures === 1) ? 1 : 0;
728 728
 
729 729
             if ($emailReportEnabled === 0) {
730 730
                 $emailReportOnlyFailures = 0;
731 731
             }
732 732
 
733
-            $frequency = (string)($dataReceived['frequency'] ?? 'daily');
733
+            $frequency = (string) ($dataReceived['frequency'] ?? 'daily');
734 734
             if (!in_array($frequency, ['daily', 'weekly', 'monthly'], true)) {
735 735
                 $frequency = 'daily';
736 736
             }
737 737
 
738
-            $timeStr = (string)($dataReceived['time'] ?? '02:00');
738
+            $timeStr = (string) ($dataReceived['time'] ?? '02:00');
739 739
             if (!preg_match('/^\d{2}:\d{2}$/', $timeStr)) {
740 740
                 $timeStr = '02:00';
741 741
             } else {
@@ -745,22 +745,22 @@  discard block
 block discarded – undo
745 745
                 }
746 746
             }
747 747
 
748
-            $dow = (int)($dataReceived['dow'] ?? 1);
748
+            $dow = (int) ($dataReceived['dow'] ?? 1);
749 749
             if ($dow < 1 || $dow > 7) $dow = 1;
750 750
 
751
-            $dom = (int)($dataReceived['dom'] ?? 1);
751
+            $dom = (int) ($dataReceived['dom'] ?? 1);
752 752
             if ($dom < 1) $dom = 1;
753 753
             if ($dom > 31) $dom = 31;
754 754
 
755
-            $retentionDays = (int)($dataReceived['retention_days'] ?? 30);
755
+            $retentionDays = (int) ($dataReceived['retention_days'] ?? 30);
756 756
             if ($retentionDays < 1) $retentionDays = 1;
757 757
             if ($retentionDays > 3650) $retentionDays = 3650;
758 758
 
759 759
             // Output dir: default to <files>/backups
760
-            $baseFilesDir = (string)($SETTINGS['path_to_files_folder'] ?? (__DIR__ . '/../files'));
761
-            $defaultDir = rtrim($baseFilesDir, '/') . '/backups';
760
+            $baseFilesDir = (string) ($SETTINGS['path_to_files_folder'] ?? (__DIR__.'/../files'));
761
+            $defaultDir = rtrim($baseFilesDir, '/').'/backups';
762 762
 
763
-            $outputDir = trim((string)($dataReceived['output_dir'] ?? ''));
763
+            $outputDir = trim((string) ($dataReceived['output_dir'] ?? ''));
764 764
             if ($outputDir === '') $outputDir = $defaultDir;
765 765
 
766 766
             // Safety: prevent path traversal / outside files folder
@@ -773,15 +773,15 @@  discard block
 block discarded – undo
773 773
                 break;
774 774
             }
775 775
 
776
-            tpUpsertSettingsValue('bck_scheduled_enabled', (string)$enabled);
776
+            tpUpsertSettingsValue('bck_scheduled_enabled', (string) $enabled);
777 777
             tpUpsertSettingsValue('bck_scheduled_frequency', $frequency);
778 778
             tpUpsertSettingsValue('bck_scheduled_time', $timeStr);
779
-            tpUpsertSettingsValue('bck_scheduled_dow', (string)$dow);
780
-            tpUpsertSettingsValue('bck_scheduled_dom', (string)$dom);
779
+            tpUpsertSettingsValue('bck_scheduled_dow', (string) $dow);
780
+            tpUpsertSettingsValue('bck_scheduled_dom', (string) $dom);
781 781
             tpUpsertSettingsValue('bck_scheduled_output_dir', $dirReal);
782
-            tpUpsertSettingsValue('bck_scheduled_retention_days', (string)$retentionDays);
783
-            tpUpsertSettingsValue('bck_scheduled_email_report_enabled', (string)$emailReportEnabled);
784
-            tpUpsertSettingsValue('bck_scheduled_email_report_only_failures', (string)$emailReportOnlyFailures);
782
+            tpUpsertSettingsValue('bck_scheduled_retention_days', (string) $retentionDays);
783
+            tpUpsertSettingsValue('bck_scheduled_email_report_enabled', (string) $emailReportEnabled);
784
+            tpUpsertSettingsValue('bck_scheduled_email_report_only_failures', (string) $emailReportOnlyFailures);
785 785
 
786 786
 
787 787
             // Force re-init of next_run_at so handler recomputes cleanly
@@ -791,13 +791,13 @@  discard block
 block discarded – undo
791 791
             break;
792 792
 
793 793
         case 'scheduled_list_backups':
794
-            if ($post_key !== $session->get('key') || (int)$session->get('user-admin') !== 1) {
794
+            if ($post_key !== $session->get('key') || (int) $session->get('user-admin') !== 1) {
795 795
                 echo prepareExchangedData(['error' => true, 'message' => 'Not allowed'], 'encode');
796 796
                 break;
797 797
             }
798 798
 
799
-            $baseFilesDir = (string)($SETTINGS['path_to_files_folder'] ?? (__DIR__ . '/../files'));
800
-            $dir = (string)tpGetSettingsValue('bck_scheduled_output_dir', rtrim($baseFilesDir, '/') . '/backups');
799
+            $baseFilesDir = (string) ($SETTINGS['path_to_files_folder'] ?? (__DIR__.'/../files'));
800
+            $dir = (string) tpGetSettingsValue('bck_scheduled_output_dir', rtrim($baseFilesDir, '/').'/backups');
801 801
             @mkdir($dir, 0770, true);
802 802
             // Build a relative path from files/ root (output_dir can be a subfolder)
803 803
             $filesRoot = realpath($baseFilesDir);
@@ -817,16 +817,16 @@  discard block
 block discarded – undo
817 817
 
818 818
 
819 819
             $files = [];
820
-            foreach (glob(rtrim($dir, '/') . '/scheduled-*.sql') ?: [] as $fp) {
820
+            foreach (glob(rtrim($dir, '/').'/scheduled-*.sql') ?: [] as $fp) {
821 821
                 $bn = basename($fp);
822 822
                 $files[] = [
823 823
                     'name' => $bn,
824
-                    'size_bytes' => (int)@filesize($fp),
825
-                    'mtime' => (int)@filemtime($fp),
826
-                    'tp_files_version' => (function_exists('tpGetBackupTpFilesVersionFromMeta') ? ((($v = (string)tpGetBackupTpFilesVersionFromMeta($fp)) !== '') ? $v : null) : null),
827
-                    'download' => 'sources/backups.queries.php?type=scheduled_download_backup&file=' . urlencode($bn)
828
-                        . '&key=' . urlencode((string) $session->get('key'))
829
-                        . '&key_tmp=' . urlencode($keyTmp),
824
+                    'size_bytes' => (int) @filesize($fp),
825
+                    'mtime' => (int) @filemtime($fp),
826
+                    'tp_files_version' => (function_exists('tpGetBackupTpFilesVersionFromMeta') ? ((($v = (string) tpGetBackupTpFilesVersionFromMeta($fp)) !== '') ? $v : null) : null),
827
+                    'download' => 'sources/backups.queries.php?type=scheduled_download_backup&file='.urlencode($bn)
828
+                        . '&key='.urlencode((string) $session->get('key'))
829
+                        . '&key_tmp='.urlencode($keyTmp),
830 830
                 ];
831 831
             }
832 832
 
@@ -836,7 +836,7 @@  discard block
 block discarded – undo
836 836
             break;
837 837
 
838 838
         case 'scheduled_delete_backup':
839
-            if ($post_key !== $session->get('key') || (int)$session->get('user-admin') !== 1) {
839
+            if ($post_key !== $session->get('key') || (int) $session->get('user-admin') !== 1) {
840 840
                 echo prepareExchangedData(['error' => true, 'message' => 'Not allowed'], 'encode');
841 841
                 break;
842 842
             }
@@ -844,7 +844,7 @@  discard block
 block discarded – undo
844 844
             $dataReceived = prepareExchangedData($post_data, 'decode');
845 845
             if (!is_array($dataReceived)) $dataReceived = [];
846 846
 
847
-            $file = (string)($dataReceived['file'] ?? '');
847
+            $file = (string) ($dataReceived['file'] ?? '');
848 848
             $file = basename($file);
849 849
 
850 850
             if ($file === '' || strpos($file, 'scheduled-') !== 0 || !str_ends_with($file, '.sql')) {
@@ -852,9 +852,9 @@  discard block
 block discarded – undo
852 852
                 break;
853 853
             }
854 854
 
855
-            $baseFilesDir = (string)($SETTINGS['path_to_files_folder'] ?? (__DIR__ . '/../files'));
856
-            $dir = (string)tpGetSettingsValue('bck_scheduled_output_dir', rtrim($baseFilesDir, '/') . '/backups');
857
-            $fp = rtrim($dir, '/') . '/' . $file;
855
+            $baseFilesDir = (string) ($SETTINGS['path_to_files_folder'] ?? (__DIR__.'/../files'));
856
+            $dir = (string) tpGetSettingsValue('bck_scheduled_output_dir', rtrim($baseFilesDir, '/').'/backups');
857
+            $fp = rtrim($dir, '/').'/'.$file;
858 858
 
859 859
             /**
860 860
              * Delete a file and its associated metadata.
@@ -869,30 +869,30 @@  discard block
 block discarded – undo
869 869
 
870 870
             // Check permissions
871 871
             if (is_writable($fp) === false) {
872
-                $errorMessage = "File is not writable, cannot delete: " . $fp;
873
-                if (WIP === true) error_log("TeamPass - " . $errorMessage);
872
+                $errorMessage = "File is not writable, cannot delete: ".$fp;
873
+                if (WIP === true) error_log("TeamPass - ".$errorMessage);
874 874
                 echo prepareExchangedData(['error' => true, 'message' => $errorMessage], 'encode');
875 875
                 break;
876 876
             }
877 877
 
878 878
             // Attempt deletion
879 879
             if (unlink($fp) === false) {
880
-                $errorMessage = "Failed to delete file: " . $fp;
881
-                if (WIP === true) error_log("TeamPass - " . $errorMessage);
880
+                $errorMessage = "Failed to delete file: ".$fp;
881
+                if (WIP === true) error_log("TeamPass - ".$errorMessage);
882 882
                 echo prepareExchangedData(['error' => true, 'message' => $errorMessage], 'encode');
883 883
                 break;
884 884
             }
885 885
 
886 886
             // Cleanup metadata (silent fail for sidecar is acceptable)
887
-            if (file_exists($fp . '.meta.json')) {
888
-                @unlink($fp . '.meta.json');
887
+            if (file_exists($fp.'.meta.json')) {
888
+                @unlink($fp.'.meta.json');
889 889
             }
890 890
 
891 891
             echo prepareExchangedData(['error' => false], 'encode');
892 892
             break;
893 893
 
894 894
         case 'check_connected_users':
895
-            if ($post_key !== $session->get('key') || (int)$session->get('user-admin') !== 1) {
895
+            if ($post_key !== $session->get('key') || (int) $session->get('user-admin') !== 1) {
896 896
                 echo prepareExchangedData(['error' => true, 'message' => 'Not allowed'], 'encode');
897 897
                 break;
898 898
             }
@@ -903,7 +903,7 @@  discard block
 block discarded – undo
903 903
             }
904 904
 
905 905
             $connectedCount = (int) DB::queryFirstField(
906
-                'SELECT COUNT(*) FROM ' . prefixTable('users') . ' WHERE session_end >= %i AND id != %i',
906
+                'SELECT COUNT(*) FROM '.prefixTable('users').' WHERE session_end >= %i AND id != %i',
907 907
                 time(),
908 908
                 $excludeUserId
909 909
             );
@@ -912,19 +912,19 @@  discard block
 block discarded – undo
912 912
             break;
913 913
 
914 914
         case 'scheduled_run_now':
915
-            if ($post_key !== $session->get('key') || (int)$session->get('user-admin') !== 1) {
915
+            if ($post_key !== $session->get('key') || (int) $session->get('user-admin') !== 1) {
916 916
                 echo prepareExchangedData(['error' => true, 'message' => 'Not allowed'], 'encode');
917 917
                 break;
918 918
             }
919 919
 
920 920
             $now = time();
921
-            $baseFilesDir = (string)($SETTINGS['path_to_files_folder'] ?? (__DIR__ . '/../files'));
922
-            $dir = (string)tpGetSettingsValue('bck_scheduled_output_dir', rtrim($baseFilesDir, '/') . '/backups');
921
+            $baseFilesDir = (string) ($SETTINGS['path_to_files_folder'] ?? (__DIR__.'/../files'));
922
+            $dir = (string) tpGetSettingsValue('bck_scheduled_output_dir', rtrim($baseFilesDir, '/').'/backups');
923 923
             @mkdir($dir, 0770, true);
924 924
 
925 925
             // avoid duplicates
926
-            $pending = (int)DB::queryFirstField(
927
-                'SELECT COUNT(*) FROM ' . prefixTable('background_tasks') . '
926
+            $pending = (int) DB::queryFirstField(
927
+                'SELECT COUNT(*) FROM '.prefixTable('background_tasks').'
928 928
                  WHERE process_type=%s AND is_in_progress IN (0,1)
929 929
                    AND (finished_at IS NULL OR finished_at = "" OR finished_at = 0)',
930 930
                 'database_backup'
@@ -937,7 +937,7 @@  discard block
 block discarded – undo
937 937
             DB::insert(
938 938
                 prefixTable('background_tasks'),
939 939
                 [
940
-                    'created_at' => (string)$now,
940
+                    'created_at' => (string) $now,
941 941
                     'process_type' => 'database_backup',
942 942
                     'arguments' => json_encode(['output_dir' => $dir, 'source' => 'scheduler', 'initiator_user_id' => (int) $session->get('user-id')], JSON_UNESCAPED_SLASHES),
943 943
                     'is_in_progress' => 0,
@@ -945,7 +945,7 @@  discard block
 block discarded – undo
945 945
                 ]
946 946
             );
947 947
 
948
-            tpUpsertSettingsValue('bck_scheduled_last_run_at', (string)$now);
948
+            tpUpsertSettingsValue('bck_scheduled_last_run_at', (string) $now);
949 949
             tpUpsertSettingsValue('bck_scheduled_last_status', 'queued');
950 950
             tpUpsertSettingsValue('bck_scheduled_last_message', 'Task enqueued by UI');
951 951
 
@@ -954,7 +954,7 @@  discard block
 block discarded – undo
954 954
 
955 955
         case 'onthefly_delete_backup':
956 956
             // Delete an on-the-fly backup file stored in <files> directory
957
-            if ($post_key !== $session->get('key') || (int)$session->get('user-admin') !== 1) {
957
+            if ($post_key !== $session->get('key') || (int) $session->get('user-admin') !== 1) {
958 958
                 echo prepareExchangedData(
959 959
                     array(
960 960
                         'error' => true,
@@ -966,7 +966,7 @@  discard block
 block discarded – undo
966 966
             }
967 967
 
968 968
             $dataReceived = prepareExchangedData($post_data, 'decode');
969
-            $fileToDelete = isset($dataReceived['file']) === true ? (string)$dataReceived['file'] : '';
969
+            $fileToDelete = isset($dataReceived['file']) === true ? (string) $dataReceived['file'] : '';
970 970
             $bn = basename($fileToDelete);
971 971
 
972 972
             // Safety checks
@@ -993,9 +993,9 @@  discard block
 block discarded – undo
993 993
                 break;
994 994
             }
995 995
 
996
-            $baseFilesDir = (string)($SETTINGS['path_to_files_folder'] ?? (__DIR__ . '/../files'));
996
+            $baseFilesDir = (string) ($SETTINGS['path_to_files_folder'] ?? (__DIR__.'/../files'));
997 997
             $dir = rtrim($baseFilesDir, '/');
998
-            $fullPath = $dir . '/' . $bn;
998
+            $fullPath = $dir.'/'.$bn;
999 999
 
1000 1000
             if (file_exists($fullPath) === false) {
1001 1001
                 echo prepareExchangedData(
@@ -1012,7 +1012,7 @@  discard block
 block discarded – undo
1012 1012
             $ok = @unlink($fullPath);
1013 1013
 
1014 1014
             // Also remove metadata sidecar if present
1015
-            @unlink($fullPath . '.meta.json');
1015
+            @unlink($fullPath.'.meta.json');
1016 1016
 
1017 1017
             if ($ok !== true) {
1018 1018
                 echo prepareExchangedData(
@@ -1037,7 +1037,7 @@  discard block
 block discarded – undo
1037 1037
 
1038 1038
         case 'onthefly_list_backups':
1039 1039
             // List on-the-fly backup files stored directly in <files> directory (not in /backups for scheduled)
1040
-            if ($post_key !== $session->get('key') || (int)$session->get('user-admin') !== 1) {
1040
+            if ($post_key !== $session->get('key') || (int) $session->get('user-admin') !== 1) {
1041 1041
                 echo prepareExchangedData(
1042 1042
                     array(
1043 1043
                         'error' => true,
@@ -1048,11 +1048,11 @@  discard block
 block discarded – undo
1048 1048
                 break;
1049 1049
             }
1050 1050
 
1051
-            $baseFilesDir = (string)($SETTINGS['path_to_files_folder'] ?? (__DIR__ . '/../files'));
1051
+            $baseFilesDir = (string) ($SETTINGS['path_to_files_folder'] ?? (__DIR__.'/../files'));
1052 1052
             $dir = rtrim($baseFilesDir, '/');
1053 1053
 
1054 1054
             $files = array();
1055
-            $paths = glob($dir . '/*.sql');
1055
+            $paths = glob($dir.'/*.sql');
1056 1056
             if ($paths === false) {
1057 1057
                 $paths = array();
1058 1058
             }
@@ -1077,18 +1077,18 @@  discard block
 block discarded – undo
1077 1077
 
1078 1078
                 $files[] = array(
1079 1079
                     'name' => $bn,
1080
-                    'size_bytes' => (int)@filesize($fp),
1081
-                    'mtime' => (int)@filemtime($fp),
1082
-                    'tp_files_version' => (function_exists('tpGetBackupTpFilesVersionFromMeta') ? ((($v = (string)tpGetBackupTpFilesVersionFromMeta($fp)) !== '') ? $v : null) : null),
1083
-                    'download' => 'sources/downloadFile.php?name=' . urlencode($bn) .
1084
-                        '&action=backup&file=' . urlencode($bn) .
1085
-                        '&type=sql&key=' . $session->get('key') .
1086
-                        '&key_tmp=' . $session->get('user-key_tmp') .
1080
+                    'size_bytes' => (int) @filesize($fp),
1081
+                    'mtime' => (int) @filemtime($fp),
1082
+                    'tp_files_version' => (function_exists('tpGetBackupTpFilesVersionFromMeta') ? ((($v = (string) tpGetBackupTpFilesVersionFromMeta($fp)) !== '') ? $v : null) : null),
1083
+                    'download' => 'sources/downloadFile.php?name='.urlencode($bn).
1084
+                        '&action=backup&file='.urlencode($bn).
1085
+                        '&type=sql&key='.$session->get('key').
1086
+                        '&key_tmp='.$session->get('user-key_tmp').
1087 1087
                         '&pathIsFiles=1',
1088 1088
                 );
1089 1089
             }
1090 1090
 
1091
-            usort($files, static function ($a, $b) {
1091
+            usort($files, static function($a, $b) {
1092 1092
                 return ($b['mtime'] ?? 0) <=> ($a['mtime'] ?? 0);
1093 1093
             });
1094 1094
 
@@ -1102,7 +1102,7 @@  discard block
 block discarded – undo
1102 1102
             );
1103 1103
             break;
1104 1104
         case 'preflight_restore_compatibility':
1105
-            if ($post_key !== $session->get('key') || (int)$session->get('user-admin') !== 1) {
1105
+            if ($post_key !== $session->get('key') || (int) $session->get('user-admin') !== 1) {
1106 1106
                 echo prepareExchangedData(['error' => true, 'message' => 'Not allowed'], 'encode');
1107 1107
                 break;
1108 1108
             }
@@ -1113,8 +1113,8 @@  discard block
 block discarded – undo
1113 1113
             }
1114 1114
 
1115 1115
             $serverScope = (string) ($dataReceived['serverScope'] ?? '');
1116
-            $serverFile  = (string) ($dataReceived['serverFile']  ?? '');
1117
-            $operationId = (int)    ($dataReceived['operation_id'] ?? 0);
1116
+            $serverFile  = (string) ($dataReceived['serverFile'] ?? '');
1117
+            $operationId = (int) ($dataReceived['operation_id'] ?? 0);
1118 1118
 
1119 1119
             $chk = tpCheckRestoreCompatibility($SETTINGS, $serverScope, $serverFile, $operationId);
1120 1120
 
@@ -1153,8 +1153,8 @@  discard block
 block discarded – undo
1153 1153
                     }
1154 1154
 
1155 1155
                     $serverScope = (string) ($dataReceived['serverScope'] ?? '');
1156
-                    $serverFile  = (string) ($dataReceived['serverFile']  ?? '');
1157
-                    $operationId = (int)    ($dataReceived['operation_id'] ?? 0);
1156
+                    $serverFile  = (string) ($dataReceived['serverFile'] ?? '');
1157
+                    $operationId = (int) ($dataReceived['operation_id'] ?? 0);
1158 1158
 
1159 1159
                     $encryptionKey = (string) ($dataReceived['encryptionKey'] ?? '');
1160 1160
                     $overrideKey   = (string) ($dataReceived['overrideKey'] ?? '');
@@ -1242,7 +1242,7 @@  discard block
 block discarded – undo
1242 1242
                         }
1243 1243
                     }
1244 1244
 
1245
-                    $keysToTry = array_values(array_unique(array_filter($keysToTry, function ($v) {
1245
+                    $keysToTry = array_values(array_unique(array_filter($keysToTry, function($v) {
1246 1246
                         return $v !== '';
1247 1247
                     })));
1248 1248
 
@@ -1266,8 +1266,8 @@  discard block
 block discarded – undo
1266 1266
                         $tmpRand = uniqid('', true);
1267 1267
                     }
1268 1268
 
1269
-                    $tmpDecryptedSql = rtrim((string) sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR
1270
-                        . 'defuse_temp_restore_' . (int) ($session->get('user-id') ?? 0) . '_' . time() . '_' . $tmpRand . '.sql';
1269
+                    $tmpDecryptedSql = rtrim((string) sys_get_temp_dir(), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR
1270
+                        . 'defuse_temp_restore_'.(int) ($session->get('user-id') ?? 0).'_'.time().'_'.$tmpRand.'.sql';
1271 1271
 
1272 1272
                     // Try to decrypt with the available keys
1273 1273
                     $decRet = tpDefuseDecryptWithCandidates($resolvedPath, $tmpDecryptedSql, $keysToTry, $SETTINGS);
@@ -1346,23 +1346,23 @@  discard block
 block discarded – undo
1346 1346
 
1347 1347
 					$sudoPrefix = '';
1348 1348
 					if (!$isWindows && $webUser !== '') {
1349
-						$sudoPrefix = 'sudo -u ' . escapeshellarg($webUser) . ' ';
1349
+						$sudoPrefix = 'sudo -u '.escapeshellarg($webUser).' ';
1350 1350
 					}
1351 1351
 
1352
-					$cmdNoCd = $sudoPrefix . 'php ' . $scriptRel
1353
-						. ' --file ' . escapeshellarg($filePathForCmd)
1354
-						. ' --auth-token ' . escapeshellarg($token);
1355
-					$cmdNoCdForce = $cmdNoCd . ' --force-disconnect';
1352
+					$cmdNoCd = $sudoPrefix.'php '.$scriptRel
1353
+						. ' --file '.escapeshellarg($filePathForCmd)
1354
+						. ' --auth-token '.escapeshellarg($token);
1355
+					$cmdNoCdForce = $cmdNoCd.' --force-disconnect';
1356 1356
 
1357 1357
 					$cmd = $cmdNoCd;
1358 1358
 					$cmdForce = $cmdNoCdForce;
1359 1359
 					if ($tpRoot !== '') {
1360 1360
 						if ($isWindows) {
1361
-							$cmd = 'cd /d ' . escapeshellarg($rootForCmd) . ' && ' . $cmdNoCd;
1362
-							$cmdForce = 'cd /d ' . escapeshellarg($rootForCmd) . ' && ' . $cmdNoCdForce;
1361
+							$cmd = 'cd /d '.escapeshellarg($rootForCmd).' && '.$cmdNoCd;
1362
+							$cmdForce = 'cd /d '.escapeshellarg($rootForCmd).' && '.$cmdNoCdForce;
1363 1363
 						} else {
1364
-							$cmd = 'cd ' . escapeshellarg($rootForCmd) . ' && ' . $cmdNoCd;
1365
-							$cmdForce = 'cd ' . escapeshellarg($rootForCmd) . ' && ' . $cmdNoCdForce;
1364
+							$cmd = 'cd '.escapeshellarg($rootForCmd).' && '.$cmdNoCd;
1365
+							$cmdForce = 'cd '.escapeshellarg($rootForCmd).' && '.$cmdNoCdForce;
1366 1366
 						}
1367 1367
 					}
1368 1368
 
@@ -1378,13 +1378,13 @@  discard block
 block discarded – undo
1378 1378
 					];
1379 1379
 					if (!$isWindows && $webUser !== '') {
1380 1380
 						$cmdNoSudo = 'php scripts/restore.php'
1381
-							. ' --file ' . escapeshellarg($resolvedPath)
1382
-							. ' --auth-token ' . escapeshellarg($token);
1381
+							. ' --file '.escapeshellarg($resolvedPath)
1382
+							. ' --auth-token '.escapeshellarg($token);
1383 1383
 						$cmdNoSudoCd = ($tpRoot !== '')
1384
-							? ('cd ' . escapeshellarg($rootForCmd) . ' && ' . $cmdNoSudo)
1384
+							? ('cd '.escapeshellarg($rootForCmd).' && '.$cmdNoSudo)
1385 1385
 							: $cmdNoSudo;
1386 1386
 						$variants[] = [
1387
-							'label' => 'Alternative (no sudo) - run as ' . $webUser,
1387
+							'label' => 'Alternative (no sudo) - run as '.$webUser,
1388 1388
 							'command' => $cmdNoSudoCd,
1389 1389
 						];
1390 1390
 					}
@@ -1448,8 +1448,8 @@  discard block
 block discarded – undo
1448 1448
             $earlyOffset = (int) ($dataEarly['offset'] ?? 0);
1449 1449
             $earlyClear = (string) ($dataEarly['clearFilename'] ?? '');
1450 1450
             $earlyServerScope = (string) ($dataEarly['serverScope'] ?? '');
1451
-            $earlyServerFile  = (string) ($dataEarly['serverFile']  ?? '');
1452
-            $earlyBackupFile  = (string) ($dataEarly['backupFile']  ?? '');
1451
+            $earlyServerFile  = (string) ($dataEarly['serverFile'] ?? '');
1452
+            $earlyBackupFile  = (string) ($dataEarly['backupFile'] ?? '');
1453 1453
             $earlyOperationId = (int) ($dataEarly['operation_id'] ?? 0);
1454 1454
 
1455 1455
             // If restore is starting (first chunk), enforce schema compatibility.
@@ -1509,7 +1509,7 @@  discard block
 block discarded – undo
1509 1509
             $post_clearFilename = filter_var(($dataReceived['clearFilename'] ?? ''), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
1510 1510
 
1511 1511
             $post_serverScope = filter_var(($dataReceived['serverScope'] ?? ''), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
1512
-            $post_serverFile  = filter_var(($dataReceived['serverFile']  ?? ''), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
1512
+            $post_serverFile  = filter_var(($dataReceived['serverFile'] ?? ''), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
1513 1513
 
1514 1514
             // Scheduled backups must always be decrypted with the instance key (server-side).
1515 1515
             // Ignore any key coming from the UI to avoid mismatches.
@@ -1518,7 +1518,7 @@  discard block
 block discarded – undo
1518 1518
             }
1519 1519
             // Ensure all strings we send back through prepareExchangedData() are JSON-safe.
1520 1520
             // This avoids PHP "malformed UTF-8" warnings when restore errors contain binary/latin1 bytes.
1521
-            $tpSafeJsonString = static function ($value): string {
1521
+            $tpSafeJsonString = static function($value): string {
1522 1522
                 if ($value === null) {
1523 1523
                     return '';
1524 1524
                 }
@@ -1538,7 +1538,7 @@  discard block
 block discarded – undo
1538 1538
                     $isUtf8 = (@preg_match('//u', $str) === 1);
1539 1539
                 }
1540 1540
                 if ($isUtf8 === false) {
1541
-                    return '[hex]' . bin2hex($str);
1541
+                    return '[hex]'.bin2hex($str);
1542 1542
                 }
1543 1543
 
1544 1544
                 // Strip ASCII control chars that could pollute JSON.
@@ -1554,7 +1554,7 @@  discard block
 block discarded – undo
1554 1554
             // Restore session + concurrency lock management.
1555 1555
             // - We keep a token in session to allow chunked restore even while DB is being replaced.
1556 1556
             // - We also block starting a second restore in the same session (double click / 2 tabs).
1557
-            $clearRestoreState = static function ($session): void {
1557
+            $clearRestoreState = static function($session): void {
1558 1558
                 $tmp = (string) ($session->get('restore-temp-file') ?? '');
1559 1559
                 if ($tmp !== '' && file_exists($tmp) === true && strpos(basename($tmp), 'defuse_temp_restore_') === 0 && is_file($tmp)) {
1560 1560
                     if (is_writable($tmp)) {
@@ -1657,9 +1657,9 @@  discard block
 block discarded – undo
1657 1657
                 error_log('DEBUG: Offset -> '.$post_offset.'/'.$post_totalSize.' | File -> '.$post_clearFilename);
1658 1658
             }
1659 1659
         
1660
-            include_once $SETTINGS['cpassman_dir'] . '/sources/main.functions.php';
1660
+            include_once $SETTINGS['cpassman_dir'].'/sources/main.functions.php';
1661 1661
         
1662
-            include_once $SETTINGS['cpassman_dir'] . '/sources/main.functions.php';
1662
+            include_once $SETTINGS['cpassman_dir'].'/sources/main.functions.php';
1663 1663
 
1664 1664
             /*
1665 1665
              * Restore workflow
@@ -1696,12 +1696,12 @@  discard block
 block discarded – undo
1696 1696
 
1697 1697
                     // Scheduled backups are stored in configured output directory
1698 1698
                     if ($post_serverScope === 'scheduled') {
1699
-                        $baseFilesDir = (string) ($SETTINGS['path_to_files_folder'] ?? (__DIR__ . '/../files'));
1700
-                        $dir = (string) tpGetSettingsValue('bck_scheduled_output_dir', rtrim($baseFilesDir, '/') . '/backups');
1699
+                        $baseFilesDir = (string) ($SETTINGS['path_to_files_folder'] ?? (__DIR__.'/../files'));
1700
+                        $dir = (string) tpGetSettingsValue('bck_scheduled_output_dir', rtrim($baseFilesDir, '/').'/backups');
1701 1701
                         $baseDir = rtrim($dir, '/');
1702 1702
                     }
1703 1703
 
1704
-                    $serverPath = $baseDir . '/' . $bn;
1704
+                    $serverPath = $baseDir.'/'.$bn;
1705 1705
 
1706 1706
                     if (file_exists($serverPath) === false) {
1707 1707
                         try {
@@ -1736,7 +1736,7 @@  discard block
 block discarded – undo
1736 1736
                         );
1737 1737
 
1738 1738
                         try {
1739
-                            $msg = 'dataBase restore started (scope=' . $post_serverScope . ', file=' . $bn . ')';
1739
+                            $msg = 'dataBase restore started (scope='.$post_serverScope.', file='.$bn.')';
1740 1740
                             logEvents(
1741 1741
                                 $SETTINGS,
1742 1742
                                 'admin_action',
@@ -1763,7 +1763,7 @@  discard block
 block discarded – undo
1763 1763
 
1764 1764
                     // Find filename from DB (misc)
1765 1765
                     $data = DB::queryFirstRow(
1766
-                        'SELECT valeur FROM ' . prefixTable('misc') . ' WHERE increment_id = %i LIMIT 1',
1766
+                        'SELECT valeur FROM '.prefixTable('misc').' WHERE increment_id = %i LIMIT 1',
1767 1767
                         $legacyOperationId
1768 1768
                     );
1769 1769
 
@@ -1788,7 +1788,7 @@  discard block
 block discarded – undo
1788 1788
                     }
1789 1789
 
1790 1790
                     $bn = safeString($data['valeur']);
1791
-                    $serverPath = rtrim((string) $SETTINGS['path_to_files_folder'], '/') . '/' . $bn;
1791
+                    $serverPath = rtrim((string) $SETTINGS['path_to_files_folder'], '/').'/'.$bn;
1792 1792
 
1793 1793
                     if (file_exists($serverPath) === false) {
1794 1794
                         try {
@@ -1822,7 +1822,7 @@  discard block
 block discarded – undo
1822 1822
 
1823 1823
                 // Decrypt to a dedicated temp file (unique)
1824 1824
                 $tmpDecrypted = rtrim((string) $SETTINGS['path_to_files_folder'], '/')
1825
-                    . '/defuse_temp_restore_' . (int) $session->get('user-id') . '_' . time() . '_' . $bn;
1825
+                    . '/defuse_temp_restore_'.(int) $session->get('user-id').'_'.time().'_'.$bn;
1826 1826
 
1827 1827
                 // Build the list of keys we can try to decrypt with.
1828 1828
                 // - on-the-fly: uses the key provided by the UI
@@ -1897,7 +1897,7 @@  discard block
 block discarded – undo
1897 1897
                         array(
1898 1898
                             'error' => true,
1899 1899
                             'error_code' => 'DECRYPT_FAILED',
1900
-                            'message' => 'Unable to decrypt backup: ' . $tpSafeJsonString((string) ($decRet['message'] ?? 'unknown error')),
1900
+                            'message' => 'Unable to decrypt backup: '.$tpSafeJsonString((string) ($decRet['message'] ?? 'unknown error')),
1901 1901
                         ),
1902 1902
                         'encode'
1903 1903
                     );
@@ -2051,7 +2051,7 @@  discard block
 block discarded – undo
2051 2051
                             } catch (Exception $e) {
2052 2052
                                 $snippet = substr($query, 0, 120);
2053 2053
                                 $snippet = $tpSafeJsonString($snippet);
2054
-                                $errors[] = 'Error executing query: ' . $tpSafeJsonString($e->getMessage()) . ' - Query: ' . $snippet . '...';
2054
+                                $errors[] = 'Error executing query: '.$tpSafeJsonString($e->getMessage()).' - Query: '.$snippet.'...';
2055 2055
                             }
2056 2056
                             $query = '';
2057 2057
                         }
@@ -2077,7 +2077,7 @@  discard block
 block discarded – undo
2077 2077
                 }
2078 2078
                 // Rollback transaction on any exception
2079 2079
                 DB::rollback();
2080
-                $errors[] = 'Transaction failed: ' . $tpSafeJsonString($e->getMessage());
2080
+                $errors[] = 'Transaction failed: '.$tpSafeJsonString($e->getMessage());
2081 2081
             }
2082 2082
         
2083 2083
             // Calculate the new offset
@@ -2104,7 +2104,7 @@  discard block
 block discarded – undo
2104 2104
                     logEvents(
2105 2105
                         $SETTINGS,
2106 2106
                         'admin_action',
2107
-                        'dataBase restore failed' . ($scope !== '' ? ' (scope=' . $scope . ')' : ''),
2107
+                        'dataBase restore failed'.($scope !== '' ? ' (scope='.$scope.')' : ''),
2108 2108
                         (string) $session->get('user-id'),
2109 2109
                         $session->get('user-login')
2110 2110
                     );
@@ -2117,7 +2117,7 @@  discard block
 block discarded – undo
2117 2117
                 echo prepareExchangedData(
2118 2118
                     array(
2119 2119
                         'error' => true,
2120
-                        'message' => 'Errors occurred during import: ' . implode('; ', ($post_serverScope === 'scheduled' ? array_map($tpSafeJsonString, $errors) : $errors)),
2120
+                        'message' => 'Errors occurred during import: '.implode('; ', ($post_serverScope === 'scheduled' ? array_map($tpSafeJsonString, $errors) : $errors)),
2121 2121
                         'newOffset' => $newOffset,
2122 2122
                         'totalSize' => $post_totalSize,
2123 2123
                         'clearFilename' => $post_backupFile,
@@ -2198,15 +2198,15 @@  discard block
 block discarded – undo
2198 2198
                     if ($scope !== '' || $fileLabel !== '' || $duration > 0) {
2199 2199
                         $parts = array();
2200 2200
                         if ($scope !== '') {
2201
-                            $parts[] = 'scope=' . $scope;
2201
+                            $parts[] = 'scope='.$scope;
2202 2202
                         }
2203 2203
                         if ($fileLabel !== '') {
2204
-                            $parts[] = 'file=' . $fileLabel;
2204
+                            $parts[] = 'file='.$fileLabel;
2205 2205
                         }
2206 2206
                         if ($duration > 0) {
2207
-                            $parts[] = 'duration=' . $duration . 's';
2207
+                            $parts[] = 'duration='.$duration.'s';
2208 2208
                         }
2209
-                        $msg .= ' (' . implode(', ', $parts) . ')';
2209
+                        $msg .= ' ('.implode(', ', $parts).')';
2210 2210
                     }
2211 2211
 
2212 2212
                     logEvents(
Please login to merge, or discard this patch.
Braces   +39 added lines, -13 removed lines patch added patch discarded remove patch
@@ -220,7 +220,9 @@  discard block
 block discarded – undo
220 220
 {
221 221
     if (function_exists('tpGetTpFilesVersion')) {
222 222
         $v = (string) tpGetTpFilesVersion();
223
-        if ($v !== '') return $v;
223
+        if ($v !== '') {
224
+            return $v;
225
+        }
224 226
     }
225 227
     if (defined('TP_VERSION') && defined('TP_VERSION_MINOR')) {
226 228
         return (string) TP_VERSION . '.' . (string) TP_VERSION_MINOR;
@@ -235,7 +237,9 @@  discard block
 block discarded – undo
235 237
     }
236 238
     if (defined('UPGRADE_MIN_DATE')) {
237 239
         $v = (string) UPGRADE_MIN_DATE;
238
-        if ($v !== '' && preg_match('/^\d+$/', $v) === 1) return $v;
240
+        if ($v !== '' && preg_match('/^\d+$/', $v) === 1) {
241
+            return $v;
242
+        }
239 243
     }
240 244
     return '';
241 245
 }
@@ -714,7 +718,9 @@  discard block
 block discarded – undo
714 718
             }
715 719
 
716 720
             $dataReceived = prepareExchangedData($post_data, 'decode');
717
-            if (!is_array($dataReceived)) $dataReceived = [];
721
+            if (!is_array($dataReceived)) {
722
+                $dataReceived = [];
723
+            }
718 724
 
719 725
             $enabled = (int)($dataReceived['enabled'] ?? 0);
720 726
             $enabled = ($enabled === 1) ? 1 : 0;
@@ -746,22 +752,34 @@  discard block
 block discarded – undo
746 752
             }
747 753
 
748 754
             $dow = (int)($dataReceived['dow'] ?? 1);
749
-            if ($dow < 1 || $dow > 7) $dow = 1;
755
+            if ($dow < 1 || $dow > 7) {
756
+                $dow = 1;
757
+            }
750 758
 
751 759
             $dom = (int)($dataReceived['dom'] ?? 1);
752
-            if ($dom < 1) $dom = 1;
753
-            if ($dom > 31) $dom = 31;
760
+            if ($dom < 1) {
761
+                $dom = 1;
762
+            }
763
+            if ($dom > 31) {
764
+                $dom = 31;
765
+            }
754 766
 
755 767
             $retentionDays = (int)($dataReceived['retention_days'] ?? 30);
756
-            if ($retentionDays < 1) $retentionDays = 1;
757
-            if ($retentionDays > 3650) $retentionDays = 3650;
768
+            if ($retentionDays < 1) {
769
+                $retentionDays = 1;
770
+            }
771
+            if ($retentionDays > 3650) {
772
+                $retentionDays = 3650;
773
+            }
758 774
 
759 775
             // Output dir: default to <files>/backups
760 776
             $baseFilesDir = (string)($SETTINGS['path_to_files_folder'] ?? (__DIR__ . '/../files'));
761 777
             $defaultDir = rtrim($baseFilesDir, '/') . '/backups';
762 778
 
763 779
             $outputDir = trim((string)($dataReceived['output_dir'] ?? ''));
764
-            if ($outputDir === '') $outputDir = $defaultDir;
780
+            if ($outputDir === '') {
781
+                $outputDir = $defaultDir;
782
+            }
765 783
 
766 784
             // Safety: prevent path traversal / outside files folder
767 785
             @mkdir($outputDir, 0770, true);
@@ -842,7 +860,9 @@  discard block
 block discarded – undo
842 860
             }
843 861
 
844 862
             $dataReceived = prepareExchangedData($post_data, 'decode');
845
-            if (!is_array($dataReceived)) $dataReceived = [];
863
+            if (!is_array($dataReceived)) {
864
+                $dataReceived = [];
865
+            }
846 866
 
847 867
             $file = (string)($dataReceived['file'] ?? '');
848 868
             $file = basename($file);
@@ -870,7 +890,9 @@  discard block
 block discarded – undo
870 890
             // Check permissions
871 891
             if (is_writable($fp) === false) {
872 892
                 $errorMessage = "File is not writable, cannot delete: " . $fp;
873
-                if (WIP === true) error_log("TeamPass - " . $errorMessage);
893
+                if (WIP === true) {
894
+                    error_log("TeamPass - " . $errorMessage);
895
+                }
874 896
                 echo prepareExchangedData(['error' => true, 'message' => $errorMessage], 'encode');
875 897
                 break;
876 898
             }
@@ -878,7 +900,9 @@  discard block
 block discarded – undo
878 900
             // Attempt deletion
879 901
             if (unlink($fp) === false) {
880 902
                 $errorMessage = "Failed to delete file: " . $fp;
881
-                if (WIP === true) error_log("TeamPass - " . $errorMessage);
903
+                if (WIP === true) {
904
+                    error_log("TeamPass - " . $errorMessage);
905
+                }
882 906
                 echo prepareExchangedData(['error' => true, 'message' => $errorMessage], 'encode');
883 907
                 break;
884 908
             }
@@ -1443,7 +1467,9 @@  discard block
 block discarded – undo
1443 1467
 
1444 1468
 // Compatibility check (schema-level) BEFORE maintenance/lock and any destructive action
1445 1469
             $dataEarly = prepareExchangedData($post_data, 'decode');
1446
-            if (!is_array($dataEarly)) $dataEarly = [];
1470
+            if (!is_array($dataEarly)) {
1471
+                $dataEarly = [];
1472
+            }
1447 1473
 
1448 1474
             $earlyOffset = (int) ($dataEarly['offset'] ?? 0);
1449 1475
             $earlyClear = (string) ($dataEarly['clearFilename'] ?? '');
Please login to merge, or discard this patch.
sources/backup.functions.php 1 patch
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
     function tpCreateDatabaseBackup(array $SETTINGS, string $encryptionKey = '', array $options = []): array
55 55
     {
56 56
         // Ensure required dependencies are loaded
57
-        $mainFunctionsPath = __DIR__ . '/main.functions.php';
57
+        $mainFunctionsPath = __DIR__.'/main.functions.php';
58 58
         if ((!function_exists('GenerateCryptKey') || !function_exists('prefixTable')) && is_file($mainFunctionsPath)) {
59 59
             require_once $mainFunctionsPath;
60 60
         }
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
             {
74 74
                 try {
75 75
                     $row = DB::queryFirstRow(
76
-                        'SELECT valeur FROM ' . prefixTable('misc') . ' WHERE intitule=%s AND type=%s',
76
+                        'SELECT valeur FROM '.prefixTable('misc').' WHERE intitule=%s AND type=%s',
77 77
                         'maintenance_mode',
78 78
                         'admin'
79 79
                     );
@@ -125,9 +125,9 @@  discard block
 block discarded – undo
125 125
         };
126 126
 
127 127
         $outputDir = $options['output_dir'] ?? ($SETTINGS['path_to_files_folder'] ?? '');
128
-        $prefix = (string)($options['filename_prefix'] ?? '');
129
-        $chunkRows = (int)($options['chunk_rows'] ?? 1000);
130
-        $flushEvery = (int)($options['flush_every_inserts'] ?? 200);
128
+        $prefix = (string) ($options['filename_prefix'] ?? '');
129
+        $chunkRows = (int) ($options['chunk_rows'] ?? 1000);
130
+        $flushEvery = (int) ($options['flush_every_inserts'] ?? 200);
131 131
         $includeTables = $options['include_tables'] ?? [];
132 132
         $excludeTables = $options['exclude_tables'] ?? [];
133 133
 
@@ -138,7 +138,7 @@  discard block
 block discarded – undo
138 138
                 'filepath' => '',
139 139
                 'encrypted' => false,
140 140
                 'size_bytes' => 0,
141
-                'message' => 'Backup folder is not writable or not found: ' . $outputDir,
141
+                'message' => 'Backup folder is not writable or not found: '.$outputDir,
142 142
             ];
143 143
         }
144 144
 
@@ -155,9 +155,9 @@  discard block
 block discarded – undo
155 155
 if ($schemaLevel !== '' && preg_match('/^\d+$/', $schemaLevel) !== 1) {
156 156
     $schemaLevel = '';
157 157
 }
158
-$schemaSuffix = ($schemaLevel !== '') ? ('-sl' . $schemaLevel) : '';
159
-$filename = $prefix . time() . '-' . $token . $schemaSuffix . '.sql';
160
-        $filepath = rtrim($outputDir, '/') . '/' . $filename;
158
+$schemaSuffix = ($schemaLevel !== '') ? ('-sl'.$schemaLevel) : '';
159
+$filename = $prefix.time().'-'.$token.$schemaSuffix.'.sql';
160
+        $filepath = rtrim($outputDir, '/').'/'.$filename;
161 161
 
162 162
         $handle = @fopen($filepath, 'w+');
163 163
         if ($handle === false) {
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
                 'filepath' => $filepath,
168 168
                 'encrypted' => false,
169 169
                 'size_bytes' => 0,
170
-                'message' => 'Could not create backup file: ' . $filepath,
170
+                'message' => 'Could not create backup file: '.$filepath,
171 171
             ];
172 172
         }
173 173
 
@@ -200,22 +200,22 @@  discard block
 block discarded – undo
200 200
                 }
201 201
 
202 202
                 // Write drop and creation
203
-                fwrite($handle, 'DROP TABLE IF EXISTS `' . $tableName . "`;\n");
203
+                fwrite($handle, 'DROP TABLE IF EXISTS `'.$tableName."`;\n");
204 204
 
205
-                $row2 = DB::queryFirstRow('SHOW CREATE TABLE `' . $tableName . '`');
205
+                $row2 = DB::queryFirstRow('SHOW CREATE TABLE `'.$tableName.'`');
206 206
                 if (!is_array($row2) || empty($row2['Create Table'])) {
207 207
                     // Skip table if structure cannot be fetched
208 208
                     fwrite($handle, "\n");
209 209
                     continue;
210 210
                 }
211 211
 
212
-                fwrite($handle, $row2['Create Table'] . ";\n\n");
212
+                fwrite($handle, $row2['Create Table'].";\n\n");
213 213
 
214 214
                 // Process table data in chunks to reduce memory usage
215 215
                 $offset = 0;
216 216
                 while (true) {
217 217
                     $rows = DB::query(
218
-                        'SELECT * FROM `' . $tableName . '` LIMIT %i OFFSET %i',
218
+                        'SELECT * FROM `'.$tableName.'` LIMIT %i OFFSET %i',
219 219
                         $chunkRows,
220 220
                         $offset
221 221
                     );
@@ -244,10 +244,10 @@  discard block
 block discarded – undo
244 244
 
245 245
                             // Escape and keep newlines
246 246
                             $value = addslashes(preg_replace("/\n/", '\\n', $value));
247
-                            $values[] = '"' . $value . '"';
247
+                            $values[] = '"'.$value.'"';
248 248
                         }
249 249
 
250
-                        $insertQuery = 'INSERT INTO `' . $tableName . '` VALUES(' . implode(',', $values) . ");\n";
250
+                        $insertQuery = 'INSERT INTO `'.$tableName.'` VALUES('.implode(',', $values).");\n";
251 251
                         fwrite($handle, $insertQuery);
252 252
 
253 253
                         $insertCount++;
@@ -268,7 +268,7 @@  discard block
 block discarded – undo
268 268
                 fclose($handle);
269 269
             }
270 270
 
271
-            $errorMessage = 'Backup failed: ' . $e->getMessage();
271
+            $errorMessage = 'Backup failed: '.$e->getMessage();
272 272
 
273 273
             // Suppression sécurisée sans @
274 274
             if (file_exists($filepath)) {
@@ -293,7 +293,7 @@  discard block
 block discarded – undo
293 293
         // Encrypt the file if key provided
294 294
         $encrypted = false;
295 295
         if ($encryptionKey !== '') {
296
-            $tmpPath = rtrim($outputDir, '/') . '/defuse_temp_' . $filename;
296
+            $tmpPath = rtrim($outputDir, '/').'/defuse_temp_'.$filename;
297 297
 
298 298
             if (!function_exists('prepareFileWithDefuse')) {
299 299
                 if (file_exists($filepath)) {
@@ -324,7 +324,7 @@  discard block
 block discarded – undo
324 324
                     'filepath' => $filepath,
325 325
                     'encrypted' => false,
326 326
                     'size_bytes' => 0,
327
-                    'message' => 'Encryption failed: ' . (is_string($ret) ? $ret : 'unknown error'),
327
+                    'message' => 'Encryption failed: '.(is_string($ret) ? $ret : 'unknown error'),
328 328
                 ];
329 329
             }
330 330
 
@@ -406,7 +406,7 @@  discard block
 block discarded – undo
406 406
 
407 407
         if ($isUtf8 === false) {
408 408
             // ASCII safe fallback
409
-            return '[hex]' . bin2hex($str);
409
+            return '[hex]'.bin2hex($str);
410 410
         }
411 411
 
412 412
         // Strip ASCII control chars
@@ -463,7 +463,7 @@  discard block
 block discarded – undo
463 463
     ): array {
464 464
         $lastMsg = '';
465 465
         foreach ($candidateKeys as $k) {
466
-            $k = (string)$k;
466
+            $k = (string) $k;
467 467
             if ($k === '') {
468 468
                 continue;
469 469
             }
@@ -477,7 +477,7 @@  discard block
 block discarded – undo
477 477
             if (!empty($r['success'])) {
478 478
                 return ['success' => true, 'message' => '', 'key_used' => $k];
479 479
             }
480
-            $lastMsg = tpSafeUtf8String((string)($r['message'] ?? ''));
480
+            $lastMsg = tpSafeUtf8String((string) ($r['message'] ?? ''));
481 481
         }
482 482
 
483 483
         return ['success' => false, 'message' => ($lastMsg !== '' ? $lastMsg : 'Unable to decrypt')];
@@ -493,7 +493,7 @@  discard block
 block discarded – undo
493 493
     function tpGetTpFilesVersion(): string
494 494
     {
495 495
         if (defined('TP_VERSION') && defined('TP_VERSION_MINOR')) {
496
-            return (string) TP_VERSION . '.' . (string) TP_VERSION_MINOR;
496
+            return (string) TP_VERSION.'.'.(string) TP_VERSION_MINOR;
497 497
         }
498 498
         return '';
499 499
     }
@@ -515,7 +515,7 @@  discard block
 block discarded – undo
515 515
 if (function_exists('tpGetBackupMetadataPath') === false) {
516 516
     function tpGetBackupMetadataPath(string $backupFilePath): string
517 517
     {
518
-        return $backupFilePath . '.meta.json';
518
+        return $backupFilePath.'.meta.json';
519 519
     }
520 520
 }
521 521
 
@@ -738,7 +738,7 @@  discard block
 block discarded – undo
738 738
     function tpRestoreAuthorizationFetchByHash(string $tokenHash): array
739 739
     {
740 740
         $row = DB::queryFirstRow(
741
-            'SELECT increment_id, valeur FROM ' . prefixTable('misc') . ' WHERE type = %s AND intitule = %s LIMIT 1',
741
+            'SELECT increment_id, valeur FROM '.prefixTable('misc').' WHERE type = %s AND intitule = %s LIMIT 1',
742 742
             'restore_authorization_cli',
743 743
             $tokenHash
744 744
         );
Please login to merge, or discard this patch.