]> BookStack Code Mirror - bookstack/blob - dev/licensing/gen-licenses-shared.php
Licensing: Updated license gen scripts to share logic
[bookstack] / dev / licensing / gen-licenses-shared.php
1 <?php
2
3 declare(strict_types=1);
4
5 $warnings = [];
6
7 function findLicenseFile(string $packageName, string $packagePath): string
8 {
9     $licenseNameOptions = [
10         'license', 'LICENSE', 'License',
11         'license.*', 'LICENSE.*', 'License.*',
12         'license-*.*', 'LICENSE-*.*', 'License-*.*',
13     ];
14     $packageDir = dirname($packagePath);
15
16     $foundLicenses = [];
17     foreach ($licenseNameOptions as $option) {
18         $search = glob("{$packageDir}/$option");
19         array_push($foundLicenses, ...$search);
20     }
21
22     if (count($foundLicenses) > 1) {
23         warn("Package {$packageName}: more than one license file found");
24     }
25
26     if (count($foundLicenses) > 0) {
27         $fileName = basename($foundLicenses[0]);
28         return "{$packageDir}/{$fileName}";
29     }
30
31     warn("Package {$packageName}: no license files found");
32     return '';
33 }
34
35 function findCopyright(string $licenseFile): string
36 {
37     $fileContents = file_get_contents($licenseFile);
38     $pattern = '/^.*?copyright (\(c\)|\d{4})[\s\S]*?(\n\n|\.\n)/mi';
39     $matches = [];
40     preg_match($pattern, $fileContents, $matches);
41     $copyright = trim($matches[0] ?? '');
42
43     if (str_contains($copyright, 'i.e.')) {
44         return '';
45     }
46
47     $emailPattern = '/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/i';
48     return preg_replace_callback($emailPattern, obfuscateEmail(...), $copyright);
49 }
50
51 function obfuscateEmail(array $matches): string
52 {
53     return preg_replace('/[^@.]/', '*', $matches[1]);
54 }
55
56 function warn(string $text): void
57 {
58     global $warnings;
59     $warnings[] = "WARN:" . $text;
60 }
61
62 function getWarnings(): array
63 {
64     global $warnings;
65     return $warnings;
66 }