-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass.QuickButtonsPlugin.php
More file actions
1543 lines (1399 loc) · 63.2 KB
/
class.QuickButtonsPlugin.php
File metadata and controls
1543 lines (1399 loc) · 63.2 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 5.0.0-dev
*/
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();
}
/**
* 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.
*/
static function applyUpdate() {
$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'];
$pluginDir = dirname(__FILE__);
// 1. Backup current files
$backupOk = self::backupFiles(self::CURRENT_SCHEMA, $latestVersion);
if (!$backupOk)
return array('success' => false, 'error' => 'File backup failed. Check backups/ directory permissions.');
// 2. Download zip from GitHub. Prefer release asset (works without
// codeload.github.com), fall back to branch archive on api/codeload.
$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 array('success' => false, 'error' => 'Failed to download update from GitHub.');
$tmpFile = tempnam(sys_get_temp_dir(), 'qb_update_');
file_put_contents($tmpFile, $zipContent);
// 3. Extract zip
if (!class_exists('ZipArchive'))
return array('success' => false, 'error' => 'ZipArchive PHP extension required.');
$zip = new \ZipArchive();
if ($zip->open($tmpFile) !== true) {
@unlink($tmpFile);
return array('success' => false, 'error' => 'Cannot open downloaded zip.');
}
$tmpDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'qb_update_' . uniqid();
@mkdir($tmpDir, 0755, true);
$zip->extractTo($tmpDir);
$zip->close();
@unlink($tmpFile);
// 4. Find extracted directory (GitHub adds repo-branch prefix)
$dirs = glob($tmpDir . DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR);
if (!$dirs) {
self::recursiveDelete($tmpDir);
return array('success' => false, 'error' => 'Invalid archive structure.');
}
$sourceDir = $dirs[0];
// 5. Copy new files over current plugin directory
self::resetCopyFailures();
$copyOk = self::recursiveCopy($sourceDir, $pluginDir);
self::recursiveDelete($tmpDir);
if (!$copyOk) {
$fails = self::getLastCopyFailures();
$detail = '';
if (!empty($fails)) {
$detail = ' Failed paths: ' . implode('; ', array_slice($fails, 0, 5));
if (count($fails) > 5) $detail .= ' ... +' . (count($fails) - 5) . ' more';
}
return array('success' => false,
'error' => 'Failed to copy updated files. Check directory permissions.' . $detail);
}
// v7.0.11: refresh ost_plugin.version so admin Plugin Information panel
// reflects the new manifest version. PluginManager caches the install-time
// value otherwise.
$plugin = self::findPlugin();
if ($plugin) {
db_query(sprintf(
"UPDATE %splugin SET version = %s, install_path = install_path WHERE id = %d",
TABLE_PREFIX, db_input($latestVersion), (int)$plugin->getId()
));
}
return array('success' => true, 'version' => $latestVersion);
}
/**
* HTTP GET with cURL fallback.
*/
private static function httpGet($url) {
// Try file_get_contents first
$ctx = @stream_context_create(array('http' => array(
'timeout' => 15,
'follow_location' => 1,
'user_agent' => 'osTicket-QuickButtons/' . self::CURRENT_SCHEMA,
)));
$content = @file_get_contents($url, false, $ctx);
if ($content)
return $content;
// Fallback: cURL
if (function_exists('curl_init')) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'osTicket-QuickButtons/' . self::CURRENT_SCHEMA);
$content = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($content && $httpCode >= 200 && $httpCode < 400)
return $content;
}
return null;
}
/**
* Recursively copy directory contents.
* v7.0.14: chmod target file to writable before copy (handles 644 files
* owned by a different user), use unlink+copy fallback. Collects failures
* in static $copyFailures for diagnostics.
*/
private static $copyFailures = array();
private static function recursiveCopy($src, $dst) {
$dir = @opendir($src);
if (!$dir) {
self::$copyFailures[] = "open src failed: $src";
return false;
}
if (!is_dir($dst)) @mkdir($dst, 0755, true);
if (!is_writable($dst)) @chmod($dst, 0755);
$ok = true;
while (($file = readdir($dir)) !== false) {
if ($file === '.' || $file === '..' || $file === '.git' || $file === 'backups')
continue;
$srcPath = $src . DIRECTORY_SEPARATOR . $file;
$dstPath = $dst . DIRECTORY_SEPARATOR . $file;
if (is_dir($srcPath)) {
$ok = self::recursiveCopy($srcPath, $dstPath) && $ok;
continue;
}
// File: ensure target is writable then copy
if (file_exists($dstPath) && !is_writable($dstPath))
@chmod($dstPath, 0644);
$copied = @copy($srcPath, $dstPath);
if (!$copied) {
// Try unlink + copy as fallback
@unlink($dstPath);
$copied = @copy($srcPath, $dstPath);
}
if (!$copied) {
$err = error_get_last();
self::$copyFailures[] = $dstPath . ' (' . ($err['message'] ?? 'unknown') . ')';
$ok = false;
}
}
closedir($dir);
return $ok;
}
/** v7.0.14: expose collected copy failures for error reporting. */
static function getLastCopyFailures() {
return self::$copyFailures;
}
static function resetCopyFailures() {
self::$copyFailures = array();
}
/**
* Recursively delete a directory.
*/
private static function recursiveDelete($dir) {
if (!is_dir($dir)) return;
$items = scandir($dir);
foreach ($items as $item) {
if ($item === '.' || $item === '..') continue;
$path = $dir . DIRECTORY_SEPARATOR . $item;
if (is_dir($path))
self::recursiveDelete($path);
else
@unlink($path);
}
@rmdir($dir);
}
// ================================================================
// Migrations
// ================================================================
/**
* Database migrations for version upgrades.
* Safe to run multiple times — each migration checks before acting.
*/
static function runMigrations() {
// v4.1.0: Enable show_deadline on all existing instances that don't have it
self::migrate_410_showDeadline();
// v4.1.0: Update stop icon from stacked to emoji checkmark
self::migrate_410_stopIcon();
// v5.0.0: Convert flat variant configs to dynamic steps arrays
self::migrate_500_dynamicSteps();
// v5.1.0: Add access_control defaults to existing steps
self::migrate_510_accessControl();
// v5.2.0: Add perf_mode + perf_value defaults to existing configs
self::migrate_520_perfTracking();
// v5.3.0: Add interruptions defaults to existing configs
self::migrate_530_interruptions();
// v6.0.0: Move perf + interruptions from dept-level to per-step
self::migrate_600_perStepPerfAndInterruptions();
// v7.0.0: Add Rejections panel + Icons table + kind column. Unwinds any
// bad-v7 alt_steps wrapping so variants stay flat (status-driven button model).
self::migrate_700_rejectionsAndIcons();
// v7.0.4: Unify panels. Rejection is a TYPE attribute (kind=rejection), not
// a separate panel. Merge step.rejections.types into step.interruptions.types
// with kind=rejection set on migrated types. Drop step.rejections.
self::migrate_704_unifyInterruptionPanels();
}
private static function migrate_410_showDeadline() {
$res = db_query("SELECT DISTINCT c1.namespace
FROM " . CONFIG_TABLE . " c1
WHERE c1.namespace LIKE 'plugin.%.instance.%'
AND c1.namespace NOT IN (
SELECT c2.namespace FROM " . CONFIG_TABLE . " c2
WHERE c2.`key` = 'show_deadline'
)
GROUP BY c1.namespace");
if ($res) {
while ($row = db_fetch_row($res)) {
db_query(sprintf(
"INSERT INTO %s (namespace, `key`, value) VALUES (%s, 'show_deadline', '1')",
CONFIG_TABLE,
db_input($row[0])
));
}
}
}
private static function migrate_410_stopIcon() {
db_query("UPDATE " . CONFIG_TABLE . " SET value = '{\"icon-ok-sign\":\"OK Sign (Bold Checkmark)\"}'
WHERE `key` = 'button_icon'
AND value LIKE '%icon-check+icon-share%'
AND namespace LIKE 'plugin.%.instance.%'");
}
/**
* v5.0.0: Convert flat single/twostep variant configs to dynamic steps arrays.
* Reads each instance's widget_config, converts legacy dept configs, writes back.
*/
private static function migrate_500_dynamicSteps() {
$res = db_query("SELECT id, namespace, `key`, value FROM " . CONFIG_TABLE
. " WHERE `key` = 'widget_config'"
. " AND namespace LIKE 'plugin.%.instance.%'");
if (!$res) return;
while ($row = db_fetch_array($res)) {
$raw = strip_tags($row['value'] ?: '');
$data = @json_decode($raw, true);
if (!is_array($data) || empty($data['departments'])) continue;
$changed = false;
foreach ($data['departments'] as $deptId => &$deptCfg) {
if (!empty($deptCfg['schema_version']) && (int)$deptCfg['schema_version'] >= 2)
continue; // Already migrated
if (isset($deptCfg['steps']))
continue; // Already has steps
$deptCfg = self::normalizeDeptConfig($deptCfg);
$changed = true;
}
unset($deptCfg);
if ($changed) {
$json = json_encode($data, JSON_UNESCAPED_UNICODE);
db_query(sprintf(
"UPDATE %s SET value = %s WHERE id = %d",
CONFIG_TABLE, db_input($json), (int)$row['id']
));
}
}
}
/**
* v5.1.0: Add access_control to existing step configs.
* Sets mode="native" on all existing steps to preserve current permission behavior.
* New steps created in the workflow builder default to "workflow" mode.
*/
private static function migrate_510_accessControl() {
$res = db_query("SELECT id, namespace, `key`, value FROM " . CONFIG_TABLE
. " WHERE `key` = 'widget_config'"
. " AND namespace LIKE 'plugin.%.instance.%'");
if (!$res) return;
while ($row = db_fetch_array($res)) {
$raw = strip_tags($row['value'] ?: '');
$data = @json_decode($raw, true);
if (!is_array($data) || empty($data['departments'])) continue;
$changed = false;
foreach ($data['departments'] as $deptId => &$deptCfg) {
if (empty($deptCfg['steps'])) continue;
// Skip if already at schema_version 3
if (!empty($deptCfg['schema_version']) && (int)$deptCfg['schema_version'] >= 3)
continue;
foreach ($deptCfg['steps'] as &$step) {
if (!isset($step['access_control'])) {
// Existing steps get "native" to preserve current behavior
$step['access_control'] = array(
'mode' => 'native',
'restrict_to' => array('agents' => array(), 'teams' => array(), 'roles' => array()),
);
$changed = true;
}
}
unset($step);
$deptCfg['schema_version'] = 3;
$changed = true;
}
unset($deptCfg);
if ($changed) {
$json = json_encode($data, JSON_UNESCAPED_UNICODE);
db_query(sprintf(
"UPDATE %s SET value = %s WHERE id = %d",
CONFIG_TABLE, db_input($json), (int)$row['id']
));
}
}
}
/**
* v5.2.0: Add perf_mode and perf_value defaults to existing configs.
* Sets perf_mode="off" on departments and perf_value="0" on steps.
*/
private static function migrate_520_perfTracking() {
$res = db_query("SELECT id, namespace, `key`, value FROM " . CONFIG_TABLE
. " WHERE `key` = 'widget_config'"
. " AND namespace LIKE 'plugin.%.instance.%'");
if (!$res) return;
while ($row = db_fetch_array($res)) {
$raw = strip_tags($row['value'] ?: '');
$data = @json_decode($raw, true);
if (!is_array($data) || empty($data['departments'])) continue;
$changed = false;
foreach ($data['departments'] as $deptId => &$deptCfg) {
if (empty($deptCfg['steps'])) continue;
// Skip if already at schema_version 4
if (!empty($deptCfg['schema_version']) && (int)$deptCfg['schema_version'] >= 4)
continue;
if (!isset($deptCfg['perf_mode'])) {
$deptCfg['perf_mode'] = 'off';
$changed = true;
}
foreach ($deptCfg['steps'] as &$step) {
if (!isset($step['perf_value'])) {
$step['perf_value'] = '0';
$changed = true;
}
}
unset($step);
$deptCfg['schema_version'] = 4;
$changed = true;
}
unset($deptCfg);
if ($changed) {
$json = json_encode($data, JSON_UNESCAPED_UNICODE);
db_query(sprintf(
"UPDATE %s SET value = %s WHERE id = %d",
CONFIG_TABLE, db_input($json), (int)$row['id']
));
}
}
}
/**
* v5.3.0: Add interruptions defaults to existing configs.
* Adds interruptions={enabled:false,...} and bumps schema_version to 5.
*/
private static function migrate_530_interruptions() {
$res = db_query("SELECT id, namespace, `key`, value FROM " . CONFIG_TABLE
. " WHERE `key` = 'widget_config'"
. " AND namespace LIKE 'plugin.%.instance.%'");
if (!$res) return;
$defaultInt = array(
'enabled' => false,
'label' => '',
'color' => '#e67e22',
'icon' => 'icon-pause',
'types' => array(),
);
while ($row = db_fetch_array($res)) {
$raw = strip_tags($row['value'] ?: '');
$data = @json_decode($raw, true);
if (!is_array($data) || empty($data['departments'])) continue;
$changed = false;
foreach ($data['departments'] as $deptId => &$deptCfg) {
if (empty($deptCfg['steps'])) continue;
if (!empty($deptCfg['schema_version']) && (int)$deptCfg['schema_version'] >= 5)
continue;
if (!isset($deptCfg['interruptions'])) {
$deptCfg['interruptions'] = $defaultInt;
$changed = true;
}
$deptCfg['schema_version'] = 5;
$changed = true;
}
unset($deptCfg);
if ($changed) {
$json = json_encode($data, JSON_UNESCAPED_UNICODE);
db_query(sprintf(
"UPDATE %s SET value = %s WHERE id = %d",
CONFIG_TABLE, db_input($json), (int)$row['id']
));
}
}
}
/**
* v6.0.0: Move perf_mode/perf_source_field/perf_mappings and interruptions
* from dept-level into each step. Also add step_index column to interruptions table.
*/
private static function migrate_600_perStepPerfAndInterruptions() {
$res = db_query("SELECT id, namespace, `key`, value FROM " . CONFIG_TABLE
. " WHERE `key` = 'widget_config'"
. " AND namespace LIKE 'plugin.%.instance.%'");
if (!$res) return;
$defaultInt = array(
'enabled' => false,
'label' => '',
'color' => '#e67e22',
'icon' => 'icon-pause',
'types' => array(),
);
while ($row = db_fetch_array($res)) {
$raw = strip_tags($row['value'] ?: '');
$data = @json_decode($raw, true);
if (!is_array($data) || empty($data['departments'])) continue;
$changed = false;
foreach ($data['departments'] as $deptId => &$deptCfg) {
if (empty($deptCfg['steps'])) continue;
if (!empty($deptCfg['schema_version']) && (int)$deptCfg['schema_version'] >= 6)
continue;
// Copy dept-level perf config into every step
$deptPerfMode = $deptCfg['perf_mode'] ?? 'off';
$deptPerfSrc = $deptCfg['perf_source_field'] ?? '';
$deptPerfMap = $deptCfg['perf_mappings'] ?? array();
$deptInt = $deptCfg['interruptions'] ?? $defaultInt;
foreach ($deptCfg['steps'] as &$step) {
if (!isset($step['perf_mode']))
$step['perf_mode'] = $deptPerfMode;
if (!isset($step['perf_source_field']))
$step['perf_source_field'] = $deptPerfSrc;
if (!isset($step['perf_mappings']))
$step['perf_mappings'] = $deptPerfMap;
if (!isset($step['interruptions']))
$step['interruptions'] = $deptInt;
}
unset($step);
// Remove dept-level keys
unset($deptCfg['perf_mode']);
unset($deptCfg['perf_source_field']);
unset($deptCfg['perf_mappings']);
unset($deptCfg['interruptions']);
$deptCfg['schema_version'] = 6;
$changed = true;
}