-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass.QuickButtonsPlugin.php
More file actions
2022 lines (1842 loc) · 83 KB
/
class.QuickButtonsPlugin.php
File metadata and controls
2022 lines (1842 loc) · 83 KB
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Quick Buttons Plugin - Main Class
*
* @author ChesnoTech
* @version 8.5.0
*/
require_once 'config.php';
/**
* Plugin-scoped translation function.
* Uses the 'quick-buttons' text domain registered via Plugin::translate().
*/
function qb__($msgid) {
return _dgettext('quick-buttons', $msgid);
}
/**
* v7.0.6: resolve a translatable label.
*
* Accepts either:
* - a plain string (legacy single-language label) → returned as-is
* - an object/array {lang_code: text, ...} → returns the entry for $locale,
* falling back to 'en', then to the first non-empty entry, then to ''.
*
* Empty or null input → ''.
*/
function qb_resolve_label($value, $locale = null) {
if ($value === null) return '';
if (is_string($value)) return $value;
if (is_object($value)) $value = (array)$value;
if (!is_array($value)) return (string)$value;
// Build fallback chain: full locale → short → en_US → en → first non-empty
$tried = array();
if ($locale) {
$norm = qb_normalize_lang($locale);
$tried[] = $norm;
if (strpos($norm, '_') !== false) $tried[] = strtolower(strtok($norm, '_'));
}
$tried[] = 'en_US';
$tried[] = 'en';
foreach ($tried as $key) {
if (isset($value[$key]) && $value[$key] !== '')
return (string)$value[$key];
}
foreach ($value as $v) {
if (is_string($v) && $v !== '') return $v;
}
return '';
}
/**
* v7.0.6: list of language codes for label translation, sourced from
* osTicket's enabled system languages (Primary + Secondary in admin →
* System Settings). Mirrors the translator UX shown in osTicket form fields.
*
* Falls back to {en} if config not available.
*/
function qb_available_languages() {
static $cache = null;
if ($cache !== null) return $cache;
global $cfg;
$langs = array();
if ($cfg && method_exists($cfg, 'getPrimaryLanguage')) {
$primary = $cfg->getPrimaryLanguage();
if ($primary) $langs[] = qb_normalize_lang($primary);
$sec = method_exists($cfg, 'getSecondaryLanguages') ? $cfg->getSecondaryLanguages() : array();
foreach ((array)$sec as $l) {
$l = qb_normalize_lang($l);
if ($l && !in_array($l, $langs, true)) $langs[] = $l;
}
}
if (!$langs) $langs = array('en');
return $cache = $langs;
}
/**
* v7.0.6: normalize osTicket lang code (e.g. "en_US.po@.UTF-8" → "en_US",
* "ru-RU" → "ru_RU", "ru" → "ru") to a stable format usable as a JSON key.
*/
function qb_normalize_lang($code) {
$code = (string)$code;
$code = preg_replace('/[^A-Za-z_-]/', '', $code);
$code = str_replace('-', '_', $code);
if (strpos($code, '_') !== false) {
list($lo, $up) = explode('_', $code, 2);
return strtolower($lo) . '_' . strtoupper($up);
}
return strtolower($code);
}
class QuickButtonsPlugin extends Plugin {
var $config_class = 'QuickButtonsConfig';
const CURRENT_SCHEMA = '7.0.0';
const GITHUB_REPO = 'ChesnoTech/ost-quick-buttons';
const GITHUB_BRANCH = 'stable';
static private $bootstrapped = false;
function bootstrap() {
self::bootstrapStatic();
// v7.0.12: self-heal ost_plugin.version mismatch (e.g. after manual file
// replace or earlier auto-update that did not refresh the row).
$this->syncPluginRowVersion();
// v8.5.3: upgrade DB cnx to utf8mb4 so 4-byte emojis (🎯 🚀 📦 👍 etc.,
// any code point U+10000+) survive INSERT into the already-utf8mb4
// ost_config columns. osTicket core sets `SET NAMES utf8` which is the
// legacy 3-byte alias (utf8mb3); MySQL silently substitutes 4-byte
// chars with `?`. Reissuing here flips the cnx to 4-byte for all
// subsequent queries in this request (incl. widget_config save).
self::ensureUtf8mb4Connection();
// v8.5.0: check for pending two-phase upgrade (Phase 2 finalizer).
// If marker file present, this fresh PHP process can safely swap files +
// run migrations using the freshly-loaded class definitions. Failure is
// non-blocking; saved job state allows retry.
self::checkPendingUpgrade();
}
/**
* v8.5.3 — Promote DB cnx from utf8mb3 to utf8mb4 so 4-byte emojis
* round-trip cleanly. Idempotent. Safe to call multiple times.
*/
private static function ensureUtf8mb4Connection() {
static $done = false;
if ($done) return;
$done = true;
// SET NAMES alters client / connection / results charsets in one go.
// utf8mb4_unicode_ci preserves correct emoji + accented sort order.
@db_query("SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci");
}
/**
* v7.0.12: keep ost_plugin.version aligned with plugin.php manifest.
* Cheap idempotent SELECT + conditional UPDATE on every bootstrap.
*/
private function syncPluginRowVersion() {
$pid = (int) $this->getId();
if (!$pid) return;
$manifestPath = dirname(__FILE__) . '/plugin.php';
if (!file_exists($manifestPath)) return;
$info = @include $manifestPath;
$manifestVersion = is_array($info) ? ($info['version'] ?? null) : null;
if (!$manifestVersion) return;
$row = db_fetch_array(db_query(sprintf(
"SELECT version FROM %splugin WHERE id = %d", TABLE_PREFIX, $pid)));
$currentRowVersion = $row ? (string)$row['version'] : '';
if ($currentRowVersion === (string)$manifestVersion) return;
db_query(sprintf(
"UPDATE %splugin SET version = %s WHERE id = %d",
TABLE_PREFIX, db_input((string)$manifestVersion), $pid));
}
/**
* Prevent osTicket's auto-upgrade from running without confirmation.
* We handle upgrades manually via the admin UI.
*/
function pre_upgrade(&$errors) {
// Don't auto-upgrade — let admin confirm via the UI banner
return false;
}
// ================================================================
// Upgrade detection & admin banner
// ================================================================
/**
* Check if a database upgrade is pending.
* Compares migrated_version in DB against CURRENT_SCHEMA.
*/
static function isUpgradePending() {
$ns = 'plugin.quick-buttons.meta';
$res = db_query(sprintf(
"SELECT value FROM %s WHERE namespace = '%s' AND `key` = 'migrated_version'",
CONFIG_TABLE, $ns));
$row = $res ? db_fetch_row($res) : null;
$migrated = $row ? $row[0] : '0';
return version_compare($migrated, self::CURRENT_SCHEMA, '<');
}
/**
* Get the currently migrated version from DB.
*/
static function getMigratedVersion() {
$ns = 'plugin.quick-buttons.meta';
$res = db_query(sprintf(
"SELECT value FROM %s WHERE namespace = '%s' AND `key` = 'migrated_version'",
CONFIG_TABLE, $ns));
$row = $res ? db_fetch_row($res) : null;
return $row ? $row[0] : '0';
}
/**
* Inject an upgrade banner into admin pages when upgrade is pending.
*/
static function injectUpgradeBanner(&$buffer) {
if (!self::isUpgradePending())
return;
$from = self::getMigratedVersion();
$to = self::CURRENT_SCHEMA;
$csrfToken = '';
if (preg_match('/name="__CSRFToken__"[^>]*value="([^"]+)"/', $buffer, $m))
$csrfToken = $m[1];
$banner = '
<div id="qa-upgrade-banner" style="
position: sticky;
top: 0;
z-index: 99999;
background: linear-gradient(135deg, #ff9800, #f57c00);
color: #fff;
padding: 14px 24px;
margin: 0;
border-radius: 0;
font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', sans-serif;
font-size: 14px;
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
display: flex;
align-items: center;
gap: 16px;
min-height: 36px;
box-sizing: border-box;
">
<span style="font-size: 24px; flex-shrink:0;">⚠</span>
<div style="flex:1; min-width:0;">
<strong>Quick Buttons — Database Update Required</strong><br>
<span style="opacity:0.9;font-size:13px;">
Schema version <strong>' . htmlspecialchars($from ?: 'none') . '</strong>
→ <strong>' . htmlspecialchars($to) . '</strong>.
A backup will be created automatically before upgrading.
</span>
</div>
<button id="qa-upgrade-btn" onclick="QAUpgrade.run()" style="
background: #fff;
color: #e65100;
border: none;
padding: 10px 24px;
border-radius: 6px;
font-size: 14px;
font-weight: 700;
cursor: pointer;
white-space: nowrap;
flex-shrink: 0;
box-shadow: 0 1px 4px rgba(0,0,0,0.2);
">⬆ Upgrade Now</button>
</div>
<script>
var QAUpgrade = {
run: function() {
var btn = document.getElementById("qa-upgrade-btn");
if (!confirm("This will:\\n\\n1. Backup database config\\n2. Backup plugin files\\n3. Run schema migrations\\n\\nProceed with upgrade?"))
return;
btn.disabled = true;
btn.textContent = "Upgrading...";
btn.style.opacity = "0.7";
var xhr = new XMLHttpRequest();
xhr.open("POST", "ajax.php/quick-buttons/upgrade", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("X-CSRFToken", "' . $csrfToken . '");
xhr.onload = function() {
if (xhr.status === 200) {
try {
var res = JSON.parse(xhr.responseText);
if (res.success) {
var banner = document.getElementById("qa-upgrade-banner");
banner.style.background = "linear-gradient(135deg, #4caf50, #388e3c)";
banner.innerHTML = \'<span style="font-size:28px;">✅</span>\' +
\'<div style="flex:1;"><strong>Upgrade Complete!</strong><br>\' +
\'<span style="opacity:0.9;font-size:13px;">Schema updated to v\' + res.version +
\'. Backups saved to <code>backups/</code> directory.</span></div>\';
} else {
btn.textContent = "Retry Upgrade";
btn.disabled = false;
btn.style.opacity = "1";
alert("Upgrade failed: " + (res.error || "Unknown error"));
}
} catch(e) {
btn.textContent = "Retry Upgrade";
btn.disabled = false;
btn.style.opacity = "1";
alert("Upgrade failed: Invalid response");
}
} else {
btn.textContent = "Retry Upgrade";
btn.disabled = false;
btn.style.opacity = "1";
alert("Upgrade failed: HTTP " + xhr.status);
}
};
xhr.onerror = function() {
btn.textContent = "Retry Upgrade";
btn.disabled = false;
btn.style.opacity = "1";
alert("Network error during upgrade");
};
xhr.send("__CSRFToken__=' . urlencode($csrfToken) . '");
}
};
</script>';
// Inject right after <body> so it sits above all page content
$pos = strpos($buffer, '<body');
if ($pos !== false) {
$insertPos = strpos($buffer, '>', $pos);
if ($insertPos !== false)
$buffer = substr_replace($buffer, '>' . $banner, $insertPos, 1);
}
}
// ================================================================
// Upgrade execution (called via AJAX)
// ================================================================
/**
* Execute the full upgrade: backup + migrate + set version flag.
* Returns array with success/error status.
*/
static function executeUpgrade() {
if (!self::isUpgradePending())
return array('success' => true, 'version' => self::CURRENT_SCHEMA, 'msg' => 'Already up to date');
$fromVersion = self::getMigratedVersion();
$toVersion = self::CURRENT_SCHEMA;
$ns = 'plugin.quick-buttons.meta';
// Step 1: Create backups
$dbOk = self::backupDatabase($fromVersion, $toVersion);
$filesOk = self::backupFiles($fromVersion, $toVersion);
if (!$dbOk || !$filesOk)
return array('success' => false, 'error' => 'Backup failed. Check backups/ directory permissions.');
// Step 2: Run migrations
self::runMigrations();
// Step 3: Set version flag
if ($fromVersion === '0') {
db_query(sprintf(
"INSERT INTO %s (namespace, `key`, value) VALUES ('%s', 'migrated_version', '%s')",
CONFIG_TABLE, $ns, $toVersion));
} else {
db_query(sprintf(
"UPDATE %s SET value = '%s' WHERE namespace = '%s' AND `key` = 'migrated_version'",
CONFIG_TABLE, $toVersion, $ns));
}
return array('success' => true, 'version' => $toVersion);
}
// ================================================================
// Backups
// ================================================================
/**
* Backup all plugin-related config rows to a SQL file.
* Returns true on success.
*/
private static function backupDatabase($fromVersion, $toVersion) {
$candidates = array(
dirname(__FILE__) . '/backups',
sys_get_temp_dir() . '/quick-buttons-backups',
);
$backupDir = null;
foreach ($candidates as $d) {
if (!is_dir($d)) @mkdir($d, 0755, true);
if (is_dir($d) && is_writable($d)) { $backupDir = $d; break; }
}
if (!$backupDir) {
error_log('[quick-buttons] backup dir not writable; proceeding without DB backup');
return true;
}
$timestamp = date('Ymd_His');
$file = $backupDir . "/db_backup_{$fromVersion}_to_{$toVersion}_{$timestamp}.sql";
$rows = array();
$res = db_query("SELECT * FROM " . CONFIG_TABLE
. " WHERE namespace LIKE 'plugin.%.instance.%'"
. " OR namespace LIKE 'plugin.quick-buttons.%'"
. " ORDER BY namespace, `key`");
if ($res) {
while ($row = db_fetch_array($res)) {
$vals = array(
db_input($row['namespace']),
db_input($row['key']),
db_input($row['value']),
);
$rows[] = sprintf("(%s, %s, %s)", $vals[0], $vals[1], $vals[2]);
}
}
if ($rows) {
$sql = "-- Quick Buttons plugin DB backup\n"
. "-- Date: " . date('Y-m-d H:i:s') . "\n"
. "-- Upgrade: {$fromVersion} -> {$toVersion}\n"
. "-- Restore: Run this SQL to revert config changes\n\n"
. "-- Delete current plugin configs\n"
. "DELETE FROM " . CONFIG_TABLE . " WHERE namespace LIKE 'plugin.%.instance.%'"
. " OR namespace LIKE 'plugin.quick-buttons.%';\n\n"
. "-- Re-insert original values\n"
. "INSERT INTO " . CONFIG_TABLE . " (namespace, `key`, value) VALUES\n"
. implode(",\n", $rows) . ";\n";
return @file_put_contents($file, $sql) !== false;
}
return true; // No rows to back up is still success
}
/**
* Backup plugin PHP/JS/CSS files to a timestamped zip or directory.
* Returns true on success.
*/
private static function backupFiles($fromVersion, $toVersion) {
$pluginDir = dirname(__FILE__);
$candidates = array(
$pluginDir . '/backups',
sys_get_temp_dir() . '/quick-buttons-backups',
);
$backupDir = null;
foreach ($candidates as $d) {
if (!is_dir($d)) @mkdir($d, 0755, true);
if (is_dir($d) && is_writable($d)) { $backupDir = $d; break; }
}
if (!$backupDir) {
// v7.0.11: don't block the update — log and proceed without backup
error_log('[quick-buttons] backup dir not writable; proceeding without backup');
return true;
}
$timestamp = date('Ymd_His');
$filesToBackup = array(
'plugin.php', 'config.php',
'class.QuickButtonsPlugin.php', 'class.QuickButtonsAjax.php',
'assets/quick-buttons.js', 'assets/quick-buttons.css',
'assets/workflow-builder.js', 'assets/workflow-builder.css',
'assets/icon-picker.js', 'assets/icon-picker.css',
);
// Try zip first
if (class_exists('ZipArchive')) {
$zipFile = $backupDir . "/files_backup_{$fromVersion}_to_{$toVersion}_{$timestamp}.zip";
$zip = new \ZipArchive();
if ($zip->open($zipFile, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === true) {
foreach ($filesToBackup as $f) {
$fullPath = $pluginDir . '/' . $f;
if (file_exists($fullPath))
$zip->addFile($fullPath, $f);
}
$zip->close();
if (file_exists($zipFile)) return true;
}
}
// Fallback: copy files
$copyDir = $backupDir . "/files_{$fromVersion}_to_{$toVersion}_{$timestamp}";
@mkdir($copyDir, 0755, true);
@mkdir($copyDir . '/assets', 0755, true);
foreach ($filesToBackup as $f) {
$src = $pluginDir . '/' . $f;
if (file_exists($src)) @copy($src, $copyDir . '/' . $f);
}
return true; // best effort — never block update
}
// ================================================================
// Auto-Update from GitHub
// ================================================================
/**
* v7.0.13: Fetch latest release tag from GitHub Releases API.
* Falls back to raw.githubusercontent and codeload if api.github.com is blocked.
* Reading manifest version is the legacy local check (kept as fallback).
*/
static function checkForUpdate() {
// Use plugin.php manifest as authoritative local version (was CURRENT_SCHEMA
// which only tracks DB schema, not the plugin release line).
$localVersion = self::getLocalManifestVersion() ?: self::CURRENT_SCHEMA;
// Try GitHub Releases API first — works when raw.githubusercontent is blocked.
$apiUrl = 'https://api.github.com/repos/' . self::GITHUB_REPO . '/releases/latest';
$apiBody = self::httpGet($apiUrl);
$remoteVersion = null;
$remoteAsset = null;
if ($apiBody) {
$j = @json_decode($apiBody, true);
if (is_array($j) && !empty($j['tag_name'])) {
$remoteVersion = ltrim($j['tag_name'], 'v');
// Find first .zip asset (e.g. quick-buttons-v7.0.12.zip)
if (!empty($j['assets']) && is_array($j['assets'])) {
foreach ($j['assets'] as $a) {
if (!empty($a['browser_download_url'])
&& substr($a['browser_download_url'], -4) === '.zip') {
$remoteAsset = $a['browser_download_url'];
break;
}
}
}
}
}
// Fallback 1: raw.githubusercontent.com (legacy path)
if (!$remoteVersion) {
$rawUrl = 'https://raw.githubusercontent.com/' . self::GITHUB_REPO . '/' . self::GITHUB_BRANCH . '/plugin.php';
$rawBody = self::httpGet($rawUrl);
if ($rawBody && preg_match("/'version'\s*=>\s*'([^']+)'/", $rawBody, $m))
$remoteVersion = $m[1];
}
if (!$remoteVersion)
return array('error' => 'Cannot reach GitHub. Check server internet connectivity.');
return array(
'current' => $localVersion,
'latest' => $remoteVersion,
'available' => version_compare($remoteVersion, $localVersion, '>'),
'asset_url' => $remoteAsset, // null = use codeload fallback
);
}
/**
* v7.0.13: read 'version' from plugin.php manifest.
*/
private static function getLocalManifestVersion() {
$f = dirname(__FILE__) . '/plugin.php';
if (!file_exists($f)) return null;
$info = @include $f;
return is_array($info) && !empty($info['version']) ? (string)$info['version'] : null;
}
/**
* Download latest zip from GitHub, backup current files, replace, and run upgrade.
*/
/**
* v8.5.0 — Phase 1 of two-phase upgrade ceremony.
*
* Runs pre-flight checks, downloads the zip, extracts to a _staging/
* sub-directory, creates a marker file, and returns immediately with
* a job_id. The active PHP process never touches live plugin files
* (avoids the self-replace-mid-request crash that produced 500s on
* v8.3.x → v8.4.x upgrades).
*
* Phase 2 (finalizeUpdate) runs in a fresh PHP process on the next
* bootstrap, when the new code is loaded cleanly from disk.
*
* Returns: {success: true, job_id, stage: 'staged_awaiting_swap'}
* {success: false, error: '...'} on pre-flight or stage failure
*/
static function stageUpdate() {
$pluginDir = dirname(__FILE__);
// Concurrency guard: refuse if another update is in progress.
$pending = self::getPendingUpgrade();
if ($pending && (time() - ($pending['started_at'] ?? 0)) < 3600) {
return array('success' => false, 'error' => 'Another update is in progress (job ' . $pending['job_id'] . '). Wait or force-unlock.');
}
// 1. Pre-flight: writability, disk, memory, network
$pre = self::preflightUpdate();
if (!empty($pre['error']))
return array('success' => false, 'error' => 'Pre-flight failed: ' . $pre['error']);
$check = self::checkForUpdate();
if (isset($check['error']))
return array('success' => false, 'error' => $check['error']);
if (empty($check['available']))
return array('success' => false, 'error' => 'Already up to date');
$latestVersion = $check['latest'];
$currentVersion = $check['current'];
$jobId = (string) time();
// 2. Init job state
$job = array(
'job_id' => $jobId,
'from_version' => $currentVersion,
'to_version' => $latestVersion,
'stage' => 'download',
'stages_done' => array('preflight'),
'stages_remaining' => array('download', 'stage', 'swap', 'migrate'),
'started_at' => time(),
'last_update' => time(),
'staging_path' => '',
'backup_path' => '',
'asset_url' => $check['asset_url'] ?? null,
'error' => null,
'percent' => 10,
'msg' => 'Pre-flight passed',
);
self::saveJobState($job);
// 3. Backup current files (existing logic, reused for rollback path)
$backupOk = self::backupFiles(self::CURRENT_SCHEMA, $latestVersion);
if (!$backupOk) {
return self::failJob($job, 'File backup failed. Check backups/ directory permissions.');
}
// 4. Download zip
$job['percent'] = 25;
$job['msg'] = 'Downloading v' . $latestVersion . '...';
self::saveJobState($job);
$candidates = array();
if (!empty($check['asset_url'])) $candidates[] = $check['asset_url'];
$candidates[] = 'https://github.com/' . self::GITHUB_REPO
. '/releases/download/v' . $latestVersion . '/quick-buttons-v' . $latestVersion . '.zip';
$candidates[] = 'https://codeload.github.com/' . self::GITHUB_REPO
. '/zip/refs/heads/' . self::GITHUB_BRANCH;
$candidates[] = 'https://github.com/' . self::GITHUB_REPO
. '/archive/refs/heads/' . self::GITHUB_BRANCH . '.zip';
$zipContent = null;
foreach (array_unique($candidates) as $u) {
$zipContent = self::httpGet($u);
if ($zipContent) break;
}
if (!$zipContent) {
return self::failJob($job, 'Failed to download update from GitHub.');
}
$tmpFile = tempnam(sys_get_temp_dir(), 'qb_update_');
file_put_contents($tmpFile, $zipContent);
// 5. Extract zip
$job['stage'] = 'stage';
$job['stages_done'][] = 'download';
$job['percent'] = 50;
$job['msg'] = 'Extracting...';
self::saveJobState($job);
if (!class_exists('ZipArchive')) {
return self::failJob($job, 'ZipArchive PHP extension required.');
}
$zip = new \ZipArchive();
if ($zip->open($tmpFile) !== true) {
@unlink($tmpFile);
return self::failJob($job, 'Cannot open downloaded zip.');
}
$stagingDir = $pluginDir . DIRECTORY_SEPARATOR . '_staging' . DIRECTORY_SEPARATOR . $latestVersion;
self::recursiveDelete($stagingDir); // clean any prior attempt
@mkdir($stagingDir, 0755, true);
$zip->extractTo($stagingDir);
$zip->close();
@unlink($tmpFile);
// 6. Find extracted source dir.
//
// v8.5.1 — handle three known layouts:
// A. GitHub release zip with `quick-buttons-<ver>/` wrapper (preferred)
// B. Flat zip with files at root (no wrapper) — treat staging dir as source
// C. PowerShell Compress-Archive zip — files extracted with literal
// backslash in name (e.g. `quick-buttons-8.5.0\plugin.php`) because
// Linux ZipArchive treats `\` as a filename character. Auto-repair
// by recreating real subdirs from backslash-prefixed names.
$dirs = glob($stagingDir . DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR);
$sourceDir = null;
if ($dirs) {
// Case A
$sourceDir = $dirs[0];
} elseif (file_exists($stagingDir . DIRECTORY_SEPARATOR . 'plugin.php')) {
// Case B — flat zip, use staging dir as source
$sourceDir = $stagingDir;
} else {
// Case C — try to repair backslash-mangled filenames (PowerShell)
$entries = @scandir($stagingDir) ?: array();
$repaired = 0;
foreach ($entries as $name) {
if ($name === '.' || $name === '..') continue;
if (strpos($name, '\\') === false) continue;
$src = $stagingDir . DIRECTORY_SEPARATOR . $name;
if (!is_file($src)) continue;
$real = str_replace('\\', '/', $name);
$target = $stagingDir . DIRECTORY_SEPARATOR . $real;
@mkdir(dirname($target), 0755, true);
if (@rename($src, $target)) $repaired++;
}
if ($repaired > 0) {
// Retry: should now find a wrapper dir
$dirs = glob($stagingDir . DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR);
if ($dirs) {
$sourceDir = $dirs[0];
$job['msg'] = 'Repaired ' . $repaired . ' Windows-separator filename(s).';
self::saveJobState($job);
}
}
if (!$sourceDir) {
self::recursiveDelete($stagingDir);
return self::failJob($job, 'Invalid archive structure (no subdir, no plugin.php at root, no repairable backslash names).');
}
}
// 7. Verify staged manifest version matches expected
$stagedManifest = $sourceDir . '/plugin.php';
if (file_exists($stagedManifest)) {
$info = @include $stagedManifest;
$stagedVer = is_array($info) ? ($info['version'] ?? '') : '';
if ($stagedVer !== $latestVersion) {
self::recursiveDelete($stagingDir);
return self::failJob($job, 'Staged manifest version mismatch (expected ' . $latestVersion . ', got ' . $stagedVer . ').');
}
}
$job['stages_done'][] = 'stage';
$job['stage'] = 'staged_awaiting_swap';
$job['staging_path'] = $sourceDir;
$job['percent'] = 65;
$job['msg'] = 'Staged. Awaiting finalize.';
self::saveJobState($job);
// 8. Marker file — Phase 2 trigger
self::createMarker($jobId);
return array(
'success' => true,
'job_id' => $jobId,
'stage' => 'staged_awaiting_swap',
'message' => 'Files staged. Reload any admin page to finalize.',
);
}
/**
* v8.5.0 — Phase 2 of two-phase upgrade ceremony.
*
* Called automatically by bootstrap() when the pending-update marker
* file is detected. Runs in a fresh PHP process — new class definitions
* are loaded cleanly from disk, no mid-request self-replace risk.
*
* Atomically moves staged files to the live plugin dir (per-file rename),
* updates ost_plugin.version row, runs migrations, clears marker.
*
* Idempotent: re-running with the same job_id resumes from last good stage.
*/
static function finalizeUpdate($jobId) {
$job = self::readJobState($jobId);
if (!$job || empty($job['staging_path'])) return false;
if ($job['stage'] === 'done') return true;
$pluginDir = dirname(__FILE__);
$sourceDir = $job['staging_path'];
try {
// 1. Atomic file swap (per-file rename)
$job['stage'] = 'swap';
$job['percent'] = 75;
$job['msg'] = 'Swapping files...';
$job['last_update'] = time();
self::saveJobState($job);
self::resetCopyFailures();
$copyOk = self::recursiveCopy($sourceDir, $pluginDir);
if (!$copyOk) {
$fails = self::getLastCopyFailures();
$detail = !empty($fails) ? ' Failed paths: ' . implode('; ', array_slice($fails, 0, 5)) : '';
return self::failJob($job, 'Swap failed.' . $detail);
}
// 2. Migrate
$job['stages_done'][] = 'swap';
$job['stage'] = 'migrate';
$job['percent'] = 90;
$job['msg'] = 'Running migrations + sync...';
$job['last_update'] = time();
self::saveJobState($job);
self::runMigrations();
// Sync DB version row immediately (was previously bootstrap-deferred)
$plugin = self::findPlugin();
if ($plugin) {
db_query(sprintf(
"UPDATE %splugin SET version = %s, install_path = install_path WHERE id = %d",
TABLE_PREFIX, db_input($job['to_version']), (int)$plugin->getId()
));
}
// 3. Done
$job['stages_done'][] = 'migrate';
$job['stage'] = 'done';
$job['percent'] = 100;
$job['msg'] = 'Upgraded to v' . $job['to_version'];
$job['last_update'] = time();
self::saveJobState($job);
// Clean staging + marker
self::recursiveDelete(dirname($sourceDir));
self::clearMarker();
self::pruneJobStates();
return true;
} catch (\Throwable $e) {
return self::failJob($job, 'Finalize exception: ' . $e->getMessage());
}
}
/**
* v8.5.0 — Bootstrap hook. Detects pending marker + invokes finalizer.
* No-op if no marker present.
*/
private static function checkPendingUpgrade() {
$marker = self::getMarkerPath();
if (!file_exists($marker)) return;
$jobId = trim(@file_get_contents($marker));
if (!$jobId) {
@unlink($marker);
return;
}
// Stale marker: clear if > 1 hour old
if ((time() - @filemtime($marker)) > 3600) {
@unlink($marker);
return;
}
self::finalizeUpdate($jobId);
}
private static function getMarkerPath() {
return dirname(__FILE__) . '/_pending_update.flag';
}
private static function createMarker($jobId) {
@file_put_contents(self::getMarkerPath(), $jobId);
}
private static function clearMarker() {
@unlink(self::getMarkerPath());
}
/**
* v8.5.0 — Pre-flight checks before destructive ops.
* Returns ['ok' => bool, 'error' => string|null].
*/
static function preflightUpdate() {
$pluginDir = dirname(__FILE__);
if (!is_writable($pluginDir))
return array('error' => 'Plugin directory not writable: ' . $pluginDir);
$free = @disk_free_space($pluginDir);
if ($free !== false && $free < (50 * 1024 * 1024))
return array('error' => sprintf('Insufficient disk: %d MB free, need 50 MB.', (int)($free / 1024 / 1024)));
$mem = self::parseMemoryLimit(ini_get('memory_limit'));
if ($mem > 0 && $mem < (64 * 1024 * 1024))
return array('error' => sprintf('PHP memory_limit too low (%s). Increase to 64M+.', ini_get('memory_limit')));
// Network: HEAD api.github.com
$apiOk = false;
if (function_exists('curl_init')) {
$ch = curl_init('https://api.github.com');
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$apiOk = ($code >= 200 && $code < 500);
} else {
$apiOk = @file_get_contents('https://api.github.com', false, stream_context_create(array('http' => array('timeout' => 10)))) !== false;
}
if (!$apiOk)
return array('error' => 'Cannot reach api.github.com. Check server internet/firewall.');
return array('ok' => true);
}
private static function parseMemoryLimit($v) {
$v = trim((string)$v);
if ($v === '' || $v === '-1') return -1; // unlimited
$u = strtolower(substr($v, -1));
$n = (float) $v;
if ($u === 'g') return (int)($n * 1024 * 1024 * 1024);
if ($u === 'm') return (int)($n * 1024 * 1024);
if ($u === 'k') return (int)($n * 1024);
return (int) $n;
}
/**
* v8.5.0 — Job state persistence (ost_config table, same plugin namespace).
* Key pattern: update_job_<job_id>. JSON-encoded state.
*/
static function saveJobState($job) {
$plugin = self::findPlugin();
if (!$plugin) return false;
$ns = 'plugin.' . $plugin->getId();
$key = 'update_job_' . $job['job_id'];
$job['last_update'] = time();
return db_query(sprintf(
"INSERT INTO %s (namespace, `key`, value, updated) VALUES (%s, %s, %s, NOW())
ON DUPLICATE KEY UPDATE value=VALUES(value), updated=NOW()",
CONFIG_TABLE, db_input($ns), db_input($key), db_input(json_encode($job))
));
}
static function readJobState($jobId) {
$plugin = self::findPlugin();
if (!$plugin) return null;
$ns = 'plugin.' . $plugin->getId();
$key = 'update_job_' . $jobId;
$row = db_fetch_array(db_query(sprintf(
"SELECT value FROM %s WHERE namespace = %s AND `key` = %s LIMIT 1",
CONFIG_TABLE, db_input($ns), db_input($key)
)));
if (!$row || empty($row['value'])) return null;
return json_decode($row['value'], true);
}
static function listJobs() {
$plugin = self::findPlugin();
if (!$plugin) return array();
$ns = 'plugin.' . $plugin->getId();
$res = db_query(sprintf(
"SELECT value FROM %s WHERE namespace = %s AND `key` LIKE 'update_job_%%' ORDER BY `key` DESC",
CONFIG_TABLE, db_input($ns)
));
$jobs = array();
if ($res) {
while ($r = db_fetch_array($res)) {
$j = @json_decode($r['value'], true);
if (is_array($j)) $jobs[] = $j;
}
}
return $jobs;
}
static function pruneJobStates() {
$plugin = self::findPlugin();
if (!$plugin) return;
$ns = 'plugin.' . $plugin->getId();
$res = db_query(sprintf(
"SELECT `key` FROM %s WHERE namespace = %s AND `key` LIKE 'update_job_%%' ORDER BY `key` DESC",
CONFIG_TABLE, db_input($ns)
));
if (!$res) return;
$keys = array();
while ($r = db_fetch_array($res)) $keys[] = $r['key'];
if (count($keys) > 10) {
$toDel = array_slice($keys, 10);
$quoted = array_map(function($k) { return db_input($k); }, $toDel);
db_query(sprintf(
"DELETE FROM %s WHERE namespace = %s AND `key` IN (%s)",
CONFIG_TABLE, db_input($ns), implode(',', $quoted)
));
}
}
/** Returns the most recent unfinished job, or null. */
static function getPendingUpgrade() {
foreach (self::listJobs() as $j) {
if (in_array($j['stage'] ?? '', array('done', 'failed'), true)) continue;
return $j;
}
return null;
}
/** Mark a job failed + save state. Returns the standard error array. */
private static function failJob($job, $err) {
$job['stage'] = 'failed';
$job['error'] = $err;
$job['last_update'] = time();
self::saveJobState($job);
self::clearMarker(); // allow retry
return array('success' => false, 'error' => $err, 'job_id' => $job['job_id']);
}
/**
* v8.5.0 — Rollback by restoring a backup snapshot.
* @param int $backupTs unix timestamp of backup file (matches backupFiles naming).
*/
static function rollbackUpdate($backupTs) {
$pluginDir = dirname(__FILE__);
$backupDir = $pluginDir . '/backups';
// Find backup zip by ts
$matches = glob($backupDir . '/quick-buttons-*-' . (int)$backupTs . '.zip');
if (!$matches) {
// Try sys_get_temp_dir fallback used by v7.0.11
$altDir = sys_get_temp_dir() . '/quick-buttons-backups';
$matches = glob($altDir . '/quick-buttons-*-' . (int)$backupTs . '.zip');
}
if (!$matches) return array('success' => false, 'error' => 'Backup file not found for ts ' . $backupTs);
$backupZip = $matches[0];
// Snapshot current first (rollback is reversible)
self::backupFiles(self::CURRENT_SCHEMA, 'rollback-' . time());
// Extract backup to staging
$stagingDir = $pluginDir . '/_staging/rollback-' . time();
@mkdir($stagingDir, 0755, true);
$zip = new \ZipArchive();
if ($zip->open($backupZip) !== true)
return array('success' => false, 'error' => 'Cannot open backup zip.');
$zip->extractTo($stagingDir);
$zip->close();
// Find extracted source
$dirs = glob($stagingDir . '/*', GLOB_ONLYDIR);
$sourceDir = $dirs ? $dirs[0] : $stagingDir;
// Copy back to live
self::resetCopyFailures();
$copyOk = self::recursiveCopy($sourceDir, $pluginDir);
self::recursiveDelete($stagingDir);
if (!$copyOk) return array('success' => false, 'error' => 'Rollback copy failed.');
// Re-read manifest to get restored version
$restoredVer = self::getLocalManifestVersion();
$plugin = self::findPlugin();