Repository navigation
Expand file tree
/
Copy pathplgen.php
More file actions
executable file
·972 lines (828 loc) · 28.1 KB
/
Copy pathplgen.php
File metadata and controls
executable file
·972 lines (828 loc) · 28.1 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
<?php
/* Reminder: always indent with 4 spaces (no tabs). */
// +---------------------------------------------------------------------------+
// | Geeklog Plugin Toolkit: Plugin Generator 0.3.0 |
// +---------------------------------------------------------------------------+
// | plgen.php |
// | |
// | Creates a plugin template and an optional versioned ZIP archive |
// +---------------------------------------------------------------------------+
// | Copyright (C) 2011-2026 by the following authors: |
// | |
// | Authors: Dirk Haun dirk AT haun-online DOT de |
// | Rouslan Placella rouslan AT placella DOT com |
// | Ben hostellerie.org AT gmail DOT com |
// +---------------------------------------------------------------------------+
// | |
// | This program is free software; you can redistribute it and/or |
// | modify it under the terms of the GNU General Public License |
// | as published by the Free Software Foundation; either version 2 |
// | of the License, or (at your option) any later version. |
// | |
// | This program is distributed in the hope that it will be useful, |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
// | GNU General Public License for more details. |
// | |
// | You should have received a copy of the GNU General Public License |
// | along with this program; if not, write to the Free Software Foundation, |
// | Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. |
// | |
// +---------------------------------------------------------------------------+
/**
* @package PluginGenerator
* @version 0.3.0
*/
define('VERSION', '0.3.0');
define('TEMPLATE_PATH', __DIR__ . DIRECTORY_SEPARATOR . 'plugin-template');
define('OUTPUT_PATH', getcwd());
error_reporting(E_ALL);
$pluginData = array(
'pi_name' => 'foobar',
'pi_display_name' => 'Foo Bar',
'pi_version' => '1.0',
'pi_gl_version' => '2.2.2',
'pi_homepage' => 'https://www.example.com/',
'author' => 'John Doe',
'email' => 'john@example.com',
'use_sql' => true,
'use_config_ui' => true,
'create_zip' => true,
);
/**
* Activate or remove {optional:...} sections.
*
* Optional tags must appear alone on their line. Nested optional sections are
* supported and malformed structures stop generation with a clear error.
*
* @param string $content File content to patch
* @param array $plgdata Plugin data
* @return string
*/
function optionalSections($content, $plgdata)
{
$lines = preg_split('/\R/', $content);
if ($lines === false) {
throw new RuntimeException('Unable to split template content into lines.');
}
$newLines = array();
$stack = array();
$skip = false;
foreach ($lines as $lineNumber => $line) {
if (preg_match('/^\s*\{optional:([a-zA-Z0-9_]+)\}\s*$/', $line, $matches)) {
$tag = $matches[1];
$stack[] = array(
'tag' => $tag,
'parent_skip' => $skip,
'condition' => !empty($plgdata[$tag]),
'else_seen' => false,
);
$skip = $skip || empty($plgdata[$tag]);
continue;
}
if (preg_match('/^\s*\{!optional:([a-zA-Z0-9_]+)\}\s*$/', $line, $matches)) {
if (empty($stack)) {
throw new RuntimeException(
'Unexpected optional else tag on template line ' . ($lineNumber + 1) . '.'
);
}
$index = count($stack) - 1;
if ($stack[$index]['tag'] !== $matches[1]) {
throw new RuntimeException(
'Mismatched optional else tag on template line ' . ($lineNumber + 1) . '.'
);
}
if ($stack[$index]['else_seen']) {
throw new RuntimeException(
'Duplicate optional else tag on template line ' . ($lineNumber + 1) . '.'
);
}
$stack[$index]['else_seen'] = true;
$skip = $stack[$index]['parent_skip'] || $stack[$index]['condition'];
continue;
}
if (preg_match('/^\s*\{\/optional:([a-zA-Z0-9_]+)\}\s*$/', $line, $matches)) {
if (empty($stack)) {
throw new RuntimeException(
'Unexpected optional closing tag on template line ' . ($lineNumber + 1) . '.'
);
}
$section = array_pop($stack);
if ($section['tag'] !== $matches[1]) {
throw new RuntimeException(
'Mismatched optional closing tag on template line ' . ($lineNumber + 1) . '.'
);
}
$skip = $section['parent_skip'];
continue;
}
if (!$skip) {
$newLines[] = $line;
}
}
if (!empty($stack)) {
$section = array_pop($stack);
throw new RuntimeException(
"Unclosed optional section '{$section['tag']}' in template."
);
}
return implode(PHP_EOL, $newLines);
}
/**
* Patch file content with plugin data.
*
* This intentionally preserves the original toolkit behavior: file headers
* use pi_display_name, while technical identifiers use pi_name.
*
* @param string $content File content to patch
* @param array $plgdata Plugin data
* @return string
*/
function patch($content, $plgdata)
{
$headers = createHeaderTemplates();
foreach ($headers as $name => $comment) {
$newComment = '';
switch ($name) {
case 'authors':
if (empty($plgdata['email'])) {
$newComment = formattedComment('Authors: ' . $plgdata['author']);
} else {
$newComment = formattedComment(
'Authors: ' . $plgdata['author'] . ' - ' . obfuscateEmail($plgdata['email'])
);
}
break;
case 'copyright':
$newComment = formattedComment(
'Copyright (C) ' . date('Y') . ' by the following authors:'
);
break;
case 'pi_name':
$newComment = formattedComment(
$plgdata['pi_display_name'] . ' Plugin ' . $plgdata['pi_version']
);
break;
}
if ($newComment !== '') {
$content = str_replace($comment, $newComment, $content);
}
}
$idfield = substr($plgdata['pi_name'], 0, 1) . 'id';
$className = preg_replace('/[^a-zA-Z0-9\-_]/', '', $plgdata['pi_display_name']);
if ($className === null) {
throw new RuntimeException('Unable to generate the plugin class name.');
}
$content = str_replace(
array('foobar', 'Foo Bar', 'FooBar', 'FOOBAR', 'fbid'),
array(
$plgdata['pi_name'],
$plgdata['pi_display_name'],
$className,
strtoupper($plgdata['pi_name']),
$idfield,
),
$content
);
$content = str_replace('0.0.0', $plgdata['pi_version'], $content);
$content = str_replace('http://www.example.com/', $plgdata['pi_homepage'], $content);
$content = str_replace('https://www.example.com/', $plgdata['pi_homepage'], $content);
$content = str_replace('2.2.2', $plgdata['pi_gl_version'], $content);
return $content;
}
/**
* Create list of strings in template headers that need replacement.
*
* @return array
*/
function createHeaderTemplates()
{
return array(
'pi_name' => formattedComment('Foo Bar Plugin 0.0'),
'copyright' => formattedComment('Copyright (C) yyyy by the following authors:'),
'authors' => formattedComment('Authors: author name goes here'),
);
}
/**
* Format a copyright-header comment to 80 characters.
*
* @param string $text Text to format
* @return string
*/
function formattedComment($text)
{
if (strlen($text) > 73) {
$text = substr($text, 0, 73);
}
return sprintf("// | %-73s |\n", $text);
}
/**
* Make an email address less obvious to simple harvesting bots.
*
* @param string $email Email address
* @return string
*/
function obfuscateEmail($email)
{
return str_replace(array('@', '.'), array(' AT ', ' DOT '), $email);
}
/**
* Read and trim one line from a stream.
*
* @param resource $fp File handle
* @return string
*/
function readln($fp)
{
$value = fgets($fp);
if ($value === false) {
throw new RuntimeException('Error reading from standard input.');
}
return trim($value);
}
/**
* Ask the user for a value and apply the displayed default when Enter is used.
*
* @param resource $fp File handle
* @param string $desc1 Main prompt
* @param string $desc2 Help text
* @param string $defaultValue Default value
* @return string
*/
function getValue($fp, $desc1, $desc2, $defaultValue)
{
echo "\n";
echo $desc1 . "\n";
echo '(' . $desc2 . ') [' . $defaultValue . '] ';
// Ensure the prompt is visible before waiting for input, especially on Windows.
if (defined('STDOUT')) {
fflush(STDOUT);
}
$value = readln($fp);
return ($value === '') ? $defaultValue : $value;
}
/**
* Ask a strict yes/no question.
*
* @param resource $fp File handle
* @param string $question Main prompt
* @param string $description Help text
* @param bool $default Default answer
* @return bool
*/
function getBooleanValue($fp, $question, $description, $default = true)
{
$defaultLabel = $default ? 'yes' : 'no';
while (true) {
$value = strtolower(
getValue($fp, $question, $description . ' - yes or no', $defaultLabel)
);
if (in_array($value, array('yes', 'y'), true)) {
return true;
}
if (in_array($value, array('no', 'n'), true)) {
return false;
}
echo "Please enter yes, y, no or n.\n";
}
}
/**
* Validate the internal plugin name.
*
* @param string $name Internal name
* @return string
*/
function validatePluginName($name)
{
$name = strtolower(trim($name));
if (!preg_match('/^[a-z][a-z0-9_]*$/', $name)) {
throw new InvalidArgumentException(
'Invalid plugin name. Use lowercase letters, numbers and underscores only, '
. 'and start with a letter.'
);
}
return $name;
}
/**
* Validate a plugin or Geeklog version number.
*
* @param string $version Version string
* @param string $label Human-readable label
* @return string
*/
function validateVersion($version, $label)
{
$version = trim($version);
if (!preg_match('/^\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?$/', $version)) {
throw new InvalidArgumentException(
"Invalid {$label} version '{$version}'. Expected x.y, x.y.z or a valid suffix."
);
}
return $version;
}
/**
* Validate a URL.
*
* @param string $url URL
* @return string
*/
function validateUrl($url)
{
$url = trim($url);
if ($url !== '' && filter_var($url, FILTER_VALIDATE_URL) === false) {
throw new InvalidArgumentException("Invalid plugin homepage URL '{$url}'.");
}
return $url;
}
/**
* Validate an optional email address.
*
* @param string $email Email address
* @return string
*/
function validateEmail($email)
{
$email = trim($email);
if ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
throw new InvalidArgumentException("Invalid email address '{$email}'.");
}
return $email;
}
/**
* Convert a template-relative path to the current platform format.
*
* @param string $path Relative path
* @return string
*/
function normalizeRelativePath($path)
{
$path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);
$parts = explode(DIRECTORY_SEPARATOR, $path);
foreach ($parts as $part) {
if ($part === '..') {
throw new InvalidArgumentException('Parent-directory references are not allowed.');
}
}
return ltrim($path, DIRECTORY_SEPARATOR);
}
/**
* Return an absolute template path.
*
* @param string $filename Relative template file
* @return string
*/
function getTemplatePath($filename)
{
return TEMPLATE_PATH . DIRECTORY_SEPARATOR . normalizeRelativePath($filename);
}
/**
* Return an absolute path inside the generation directory.
*
* @param string $generationRoot Temporary generation root
* @param string $relativePath Relative path
* @return string
*/
function getGenerationPath($generationRoot, $relativePath = '')
{
if ($relativePath === '') {
return $generationRoot;
}
return $generationRoot . DIRECTORY_SEPARATOR . normalizeRelativePath($relativePath);
}
/**
* Create a directory without overwriting an existing path.
*
* @param string $path Absolute directory path
* @return void
*/
function createDirectory($path)
{
if (file_exists($path)) {
throw new RuntimeException("Path already exists: '{$path}'.");
}
if (!mkdir($path, 0755, true) && !is_dir($path)) {
throw new RuntimeException("Failed to create directory '{$path}'.");
}
}
/**
* Read a template file.
*
* @param string $filename Relative template file
* @return string
*/
function readTemplate($filename)
{
$templatePath = getTemplatePath($filename);
if (!is_file($templatePath) || !is_readable($templatePath)) {
throw new RuntimeException("Template '{$filename}' is missing or unreadable.");
}
$content = file_get_contents($templatePath);
if ($content === false) {
throw new RuntimeException("Failed to read template '{$filename}'.");
}
return $content;
}
/**
* Write a generated file atomically.
*
* @param string $filename Relative output filename
* @param string $content File content
* @param string $generationRoot Temporary generation root
* @return void
*/
function writePluginFile($filename, $content, $generationRoot)
{
$outputFile = getGenerationPath($generationRoot, $filename);
$outputDirectory = dirname($outputFile);
if (!is_dir($outputDirectory)) {
throw new RuntimeException("Output directory does not exist: '{$outputDirectory}'.");
}
$temporaryFile = $outputFile . '.tmp';
$written = file_put_contents($temporaryFile, $content, LOCK_EX);
if ($written === false || $written !== strlen($content)) {
@unlink($temporaryFile);
throw new RuntimeException("Error writing '{$filename}'.");
}
if (!rename($temporaryFile, $outputFile)) {
@unlink($temporaryFile);
throw new RuntimeException("Unable to finalize '{$filename}'.");
}
}
/**
* Generate one plugin file from its template.
*
* @param string $filename Relative filename
* @param array $plgdata Plugin data
* @param string $generationRoot Temporary generation root
* @return void
*/
function generatePluginFile($filename, $plgdata, $generationRoot)
{
$content = readTemplate($filename);
$content = patch($content, $plgdata);
$content = optionalSections($content, $plgdata);
$content = preg_replace('/\?>\s*$/', '', $content);
if ($content === null) {
throw new RuntimeException("Failed to process template '{$filename}'.");
}
writePluginFile($filename, $content, $generationRoot);
}
/**
* Remove a directory tree created during the current generation.
*
* @param string $path Directory path
* @return void
*/
function removeDirectory($path)
{
if (!is_dir($path)) {
return;
}
$items = scandir($path);
if ($items === false) {
return;
}
foreach ($items as $item) {
if ($item === '.' || $item === '..') {
continue;
}
$itemPath = $path . DIRECTORY_SEPARATOR . $item;
if (is_dir($itemPath) && !is_link($itemPath)) {
removeDirectory($itemPath);
} else {
@unlink($itemPath);
}
}
@rmdir($path);
}
/**
* Copy the default plugin icon.
*
* @param array $plgdata Plugin data
* @param string $generationRoot Temporary generation root
* @return void
*/
function copyPluginIcon($plgdata, $generationRoot)
{
$sourceIcon = getTemplatePath('admin/images/foobar.png');
$destinationIcon = getGenerationPath(
$generationRoot,
'admin/images/' . $plgdata['pi_name'] . '.png'
);
if (!is_file($sourceIcon) || !is_readable($sourceIcon)) {
throw new RuntimeException("Default plugin icon is missing or unreadable: '{$sourceIcon}'.");
}
if (!copy($sourceIcon, $destinationIcon)) {
throw new RuntimeException('Failed to copy the default plugin icon.');
}
}
/**
* Add a directory tree to an open ZIP archive.
*
* @param ZipArchive $zip Open archive
* @param string $sourcePath Absolute directory path
* @param string $archiveRoot Root directory name inside archive
* @return void
*/
function addDirectoryToZip($zip, $sourcePath, $archiveRoot)
{
$sourcePath = rtrim($sourcePath, DIRECTORY_SEPARATOR);
$archiveRoot = trim(str_replace('\\', '/', $archiveRoot), '/');
if (!$zip->addEmptyDir($archiveRoot)) {
throw new RuntimeException("Unable to add '{$archiveRoot}' to ZIP archive.");
}
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($sourcePath, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $item) {
$absolutePath = $item->getPathname();
$relativePath = substr($absolutePath, strlen($sourcePath) + 1);
$archivePath = $archiveRoot . '/' . str_replace(DIRECTORY_SEPARATOR, '/', $relativePath);
if ($item->isDir()) {
if (!$zip->addEmptyDir($archivePath)) {
throw new RuntimeException("Unable to add directory '{$archivePath}' to ZIP archive.");
}
} elseif (!$zip->addFile($absolutePath, $archivePath)) {
throw new RuntimeException("Unable to add file '{$archivePath}' to ZIP archive.");
}
}
}
/**
* Create a versioned ZIP archive when the ZipArchive extension is available.
*
* Archive format: plugin-version-geeklog-version.zip
*
* @param array $plgdata Plugin data
* @param string $pluginDirectory Final plugin directory
* @return string|null Archive path, or null when ZipArchive is unavailable
*/
function createPluginArchive($plgdata, $pluginDirectory)
{
$archiveName = sprintf(
'%s-%s-%s.zip',
$plgdata['pi_name'],
$plgdata['pi_version'],
$plgdata['pi_gl_version']
);
$archivePath = OUTPUT_PATH . DIRECTORY_SEPARATOR . $archiveName;
if (file_exists($archivePath)) {
throw new RuntimeException(
"Archive '{$archiveName}' already exists. Remove or rename it before generating again."
);
}
if (class_exists('ZipArchive')) {
$zip = new ZipArchive();
$result = $zip->open($archivePath, ZipArchive::CREATE | ZipArchive::EXCL);
if ($result !== true) {
throw new RuntimeException(
"Unable to create ZIP archive '{$archiveName}' (error {$result})."
);
}
try {
addDirectoryToZip($zip, $pluginDirectory, $plgdata['pi_name']);
} catch (Throwable $exception) {
$zip->close();
@unlink($archivePath);
throw $exception;
}
if (!$zip->close()) {
@unlink($archivePath);
throw new RuntimeException("Unable to finalize ZIP archive '{$archiveName}'.");
}
return $archivePath;
}
if (class_exists('PharData')) {
try {
$archive = new PharData($archivePath);
$archive->addEmptyDir($plgdata['pi_name']);
$sourcePath = rtrim($pluginDirectory, DIRECTORY_SEPARATOR);
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($sourcePath, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $item) {
$absolutePath = $item->getPathname();
$relativePath = substr($absolutePath, strlen($sourcePath) + 1);
$archivePathName = $plgdata['pi_name']
. '/'
. str_replace(DIRECTORY_SEPARATOR, '/', $relativePath);
if ($item->isDir()) {
$archive->addEmptyDir($archivePathName);
} else {
$archive->addFile($absolutePath, $archivePathName);
}
}
unset($archive);
} catch (Throwable $exception) {
@unlink($archivePath);
throw new RuntimeException(
"Unable to create ZIP archive '{$archiveName}' with PharData: "
. $exception->getMessage(),
0,
$exception
);
}
return $archivePath;
}
return null;
}
/**
* Display the chosen configuration.
*
* @param array $plgdata Plugin data
* @return void
*/
function displaySummary($plgdata)
{
echo "\nPlugin configuration\n";
echo "--------------------\n";
echo 'Internal name: ' . $plgdata['pi_name'] . "\n";
echo 'Display name: ' . $plgdata['pi_display_name'] . "\n";
echo 'Plugin version: ' . $plgdata['pi_version'] . "\n";
echo 'Geeklog version: ' . $plgdata['pi_gl_version'] . "\n";
echo 'Author: ' . $plgdata['author'] . "\n";
echo 'Email: ' . ($plgdata['email'] !== '' ? $plgdata['email'] : '(none)') . "\n";
echo 'Homepage: ' . ($plgdata['pi_homepage'] !== '' ? $plgdata['pi_homepage'] : '(none)') . "\n";
echo 'SQL files: ' . ($plgdata['use_sql'] ? 'yes' : 'no') . "\n";
echo 'Configuration: ' . ($plgdata['use_config_ui'] ? 'yes' : 'no') . "\n";
echo 'ZIP archive: ' . ($plgdata['create_zip'] ? 'yes' : 'no') . "\n";
echo 'Output folder: ' . OUTPUT_PATH . "\n";
}
// MAIN
echo "\nGeeklog Plugin Toolkit: Plugin Generator " . VERSION . "\n";
$stdin = fopen('php://stdin', 'r');
if ($stdin === false) {
fwrite(STDERR, "\nUnable to open standard input.\n");
exit(1);
}
$temporaryDirectory = null;
$finalPluginDirectory = null;
try {
$pluginData['pi_name'] = validatePluginName(
getValue(
$stdin,
'Internal name of your plugin?',
'lowercase letters, numbers and underscores only',
$pluginData['pi_name']
)
);
$defaultDisplayName = ucfirst($pluginData['pi_name']);
$pluginData['pi_display_name'] = trim(
getValue(
$stdin,
'Display name of your plugin?',
'used in menu entries and generated file headers',
$defaultDisplayName
)
);
if ($pluginData['pi_display_name'] === '') {
throw new InvalidArgumentException('The display name cannot be empty.');
}
$pluginData['pi_version'] = validateVersion(
getValue(
$stdin,
'Version number of your plugin?',
'typically x.y or x.y.z',
$pluginData['pi_version']
),
'plugin'
);
$pluginData['author'] = trim(
getValue(
$stdin,
'Your name?',
'for the copyright information',
$pluginData['author']
)
);
if ($pluginData['author'] === '') {
throw new InvalidArgumentException('The author name cannot be empty.');
}
$pluginData['email'] = validateEmail(
getValue(
$stdin,
'Your email address?',
'optional, will be obfuscated in generated headers',
''
)
);
$pluginData['pi_homepage'] = validateUrl(
getValue(
$stdin,
'Plugin homepage?',
'for example https://example.com/',
$pluginData['pi_homepage']
)
);
$pluginData['pi_gl_version'] = validateVersion(
getValue(
$stdin,
'Minimum Geeklog version required by your plugin?',
'for example 2.2.2',
$pluginData['pi_gl_version']
),
'Geeklog'
);
$pluginData['use_sql'] = getBooleanValue(
$stdin,
'Create SQL files?',
'needed if your plugin stores data in the database',
true
);
$pluginData['use_config_ui'] = getBooleanValue(
$stdin,
'Create sample entries for the Configuration UI?',
'needed if the plugin uses Geeklog configuration',
true
);
$pluginData['create_zip'] = getBooleanValue(
$stdin,
'Create a versioned ZIP archive?',
'named plugin-version-geeklogversion.zip',
true
);
displaySummary($pluginData);
if (!getBooleanValue($stdin, 'Generate this plugin?', 'review the configuration above', true)) {
echo "\nGeneration cancelled.\n";
fclose($stdin);
exit(0);
}
$finalPluginDirectory = OUTPUT_PATH . DIRECTORY_SEPARATOR . $pluginData['pi_name'];
if (file_exists($finalPluginDirectory)) {
throw new RuntimeException(
"Plugin directory '{$finalPluginDirectory}' already exists. Generation aborted to prevent data loss."
);
}
$temporaryDirectory = OUTPUT_PATH
. DIRECTORY_SEPARATOR
. '.' . $pluginData['pi_name'] . '.tmp-' . bin2hex(random_bytes(6));
createDirectory($temporaryDirectory);
$directories = array(
'admin',
'admin/images',
'language',
'public_html',
);
if ($pluginData['use_sql']) {
$directories[] = 'sql';
}
foreach ($directories as $directory) {
createDirectory(getGenerationPath($temporaryDirectory, $directory));
}
$files = array(
'autoinstall.php',
'functions.inc',
'language/english.php',
'public_html/index.php',
'admin/index.php',
);
if ($pluginData['use_sql']) {
$files[] = 'sql/mysql_install.php';
$files[] = 'sql/mssql_install.php';
}
if ($pluginData['use_config_ui']) {
$files[] = 'install_defaults.php';
}
foreach ($files as $file) {
generatePluginFile($file, $pluginData, $temporaryDirectory);
}
copyPluginIcon($pluginData, $temporaryDirectory);
if (!rename($temporaryDirectory, $finalPluginDirectory)) {
throw new RuntimeException(
"Unable to finalize plugin directory '{$finalPluginDirectory}'."
);
}
$temporaryDirectory = null;
$archivePath = null;
if ($pluginData['create_zip']) {
try {
$archivePath = createPluginArchive($pluginData, $finalPluginDirectory);
} catch (Throwable $archiveException) {
fwrite(
STDERR,
"\nPlugin generated, but ZIP creation failed: "
. $archiveException->getMessage()
. "\n"
);
}
}
echo "\nGeneration completed successfully.\n";
echo 'Plugin directory: ' . $finalPluginDirectory . "\n";
if ($pluginData['create_zip']) {
if ($archivePath !== null) {
echo 'ZIP archive: ' . $archivePath . "\n";
} elseif (!class_exists('ZipArchive') && !class_exists('PharData')) {
echo "ZIP archive: not created (no ZIP-capable PHP extension is available)\n";
}
}
echo "\n";
} catch (Throwable $exception) {
if ($temporaryDirectory !== null && is_dir($temporaryDirectory)) {
removeDirectory($temporaryDirectory);
}
fwrite(STDERR, "\nGeneration failed: " . $exception->getMessage() . "\n\n");
fclose($stdin);
exit(1);
}
fclose($stdin);