Repository navigation
Expand file tree
/
Copy pathDocxEngine.php
More file actions
190 lines (166 loc) · 8.26 KB
/
Copy pathDocxEngine.php
File metadata and controls
190 lines (166 loc) · 8.26 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
<?php
namespace UWMadison\MailMerge;
use ZipArchive;
class DocxEngine
{
public static function extractTags($filePath): array
{
if (!file_exists($filePath)) return [];
$zip = new ZipArchive();
if ($zip->open($filePath) !== true) return [];
$tags = [];
$xmlFiles = ['word/document.xml'];
for ($i = 0; $i < $zip->numFiles; $i++) {
$name = $zip->getNameIndex($i);
if (preg_match('/^word\/(header|footer)\d+\.xml$/', $name))
$xmlFiles[] = $name;
}
foreach ($xmlFiles as $xmlFile) {
$content = $zip->getFromName($xmlFile);
if ($content === false) continue;
if (preg_match_all('/<w:fldSimple[^>]+w:instr=["\'][^"\']*MERGEFIELD\s+["\']?([^"\'\s\\\\]+)["\']?/i', $content, $m))
foreach ($m[1] as $t) $tags[] = trim($t);
if (preg_match_all('/<w:instrText[^>]*>\s*MERGEFIELD\s+["\']?([^"\'\s\\\\]+)["\']?/i', $content, $m))
foreach ($m[1] as $t) $tags[] = trim($t);
// Match cross-event and formatted bracket tags: [event][field:format], [event][field], [field:format], [field]
if (preg_match_all('/(?:\[([a-zA-Z0-9_\-]+)\])?\[([a-zA-Z0-9_\-]+)(?::([^\]]+))?\]/u', $content, $m, PREG_SET_ORDER)) {
foreach ($m as $match) {
$full = $match[0];
$ev = $match[1] ?? '';
$field = $match[2];
$fmt = $match[3] ?? '';
if (!empty($ev) || !empty($fmt)) {
$tags[] = $full;
} else {
$tags[] = $field;
}
}
}
// Match curly brackets and guillemets: {{tag}}, «tag»
if (preg_match_all('/(?:«|«|\{\{)([a-zA-Z0-9_\-\.:\s,]+)(?:»|»|\}\})/u', $content, $m))
foreach ($m[1] as $t) $tags[] = trim($t);
}
$zip->close();
return array_values(array_unique(array_filter($tags)));
}
public static function merge($templatePath, $data, $outputPath, $tagResolver = null): bool
{
if (!file_exists($templatePath)) return false;
if (!copy($templatePath, $outputPath)) return false;
$zip = new ZipArchive();
if ($zip->open($outputPath) !== true) return false;
for ($i = 0; $i < $zip->numFiles; $i++) {
$name = $zip->getNameIndex($i);
if ($name === 'word/document.xml' || preg_match('/^word\/(header|footer)\d+\.xml$/', $name)) {
$content = $zip->getFromName($name);
if ($content === false) continue;
$merged = self::replaceXmlPlaceholders($content, $data, $tagResolver);
// Safety guard: never overwrite with empty content
if (!empty($merged) && strlen($merged) > 10) {
$zip->addFromString($name, $merged);
}
}
}
return $zip->close();
}
private static function replaceXmlPlaceholders($xml, $data, $tagResolver = null): string
{
// 1. Handle Word complex MERGEFIELDs:
$complexPattern = '/<w:r\b[^>]*>(?:(?!<w:r\b).)*?<w:fldChar\s+w:fldCharType="begin"\/>.*?<\/w:r>\s*<w:r\b[^>]*>(?:(?!<w:r\b).)*?<w:instrText[^>]*>\s*MERGEFIELD\s+["\']?([^"\'\s\\\\]+)["\']?.*?<\/w:instrText>.*?<\/w:r>\s*<w:r\b[^>]*>(?:(?!<w:r\b).)*?<w:fldChar\s+w:fldCharType="separate"\/>.*?<\/w:r>(.*?)<w:r\b[^>]*>(?:(?!<w:r\b).)*?<w:fldChar\s+w:fldCharType="end"\/>.*?<\/w:r>/is';
$xmlMerged = preg_replace_callback(
$complexPattern,
function ($m) use ($data, $tagResolver) {
$tag = trim($m[1]);
$disp = $m[2];
$valStr = (string)($data[$tag] ?? '');
if ($valStr === '' && $tagResolver !== null) {
$resolved = $tagResolver($tag);
if ($resolved !== $tag) $valStr = (string)$resolved;
}
$val = htmlspecialchars($valStr, ENT_XML1, 'UTF-8');
$val = str_replace(["\r\n", "\r", "\n"], '</w:t><w:br/><w:t xml:space="preserve">', $val);
$rPr = '';
if (preg_match('/<w:rPr\b[^>]*>.*?<\/w:rPr>/is', $disp, $pMatch)) {
$rPr = $pMatch[0];
} else if (preg_match('/<w:rPr\b[^>]*>.*?<\/w:rPr>/is', $m[0], $pMatch)) {
$rPr = $pMatch[0];
}
return "<w:r>{$rPr}<w:t xml:space=\"preserve\">{$val}</w:t></w:r>";
},
$xml
);
if ($xmlMerged !== null) {
$xml = $xmlMerged;
}
// 2. Handle w:fldSimple MERGEFIELDs: preserve run formatting if present
$simplePattern = '/<w:fldSimple[^>]+w:instr=["\'][^"\']*MERGEFIELD\s+["\']?([^"\'\s\\\\]+)["\']?[^"\']*["\'][^>]*>(.*?)<\/w:fldSimple>/is';
$xmlMerged = preg_replace_callback(
$simplePattern,
function ($m) use ($data, $tagResolver) {
$tag = trim($m[1]);
$inner = $m[2];
$valStr = (string)($data[$tag] ?? '');
if ($valStr === '' && $tagResolver !== null) {
$resolved = $tagResolver($tag);
if ($resolved !== $tag) $valStr = (string)$resolved;
}
$val = htmlspecialchars($valStr, ENT_XML1, 'UTF-8');
$val = str_replace(["\r\n", "\r", "\n"], '</w:t><w:br/><w:t xml:space="preserve">', $val);
// Extract run properties (<w:rPr>...</w:rPr>) from the inner content if present
$rPr = '';
if (preg_match('/<w:rPr\b[^>]*>.*?<\/w:rPr>/is', $inner, $pMatch)) {
$rPr = $pMatch[0];
} else if (preg_match('/<w:rPr\b[^>]*>.*?<\/w:rPr>/is', $m[0], $pMatch)) {
$rPr = $pMatch[0];
}
return "<w:r>{$rPr}<w:t xml:space=\"preserve\">{$val}</w:t></w:r>";
},
$xml
);
if ($xmlMerged !== null) {
$xml = $xmlMerged;
}
// 3. Safely replace variables inside text nodes (<w:t>...</w:t>)
$xmlMerged = preg_replace_callback('/<w:t(\b[^>]*)>(.*?)<\/w:t>/is', function ($tMatch) use ($data, $tagResolver) {
$attrs = $tMatch[1];
$text = $tMatch[2];
foreach ($data as $key => $val) {
$cleanVal = htmlspecialchars((string)$val, ENT_XML1, 'UTF-8');
$cleanVal = str_replace(["\r\n", "\r", "\n"], '</w:t><w:br/><w:t xml:space="preserve">', $cleanVal);
if (str_starts_with($key, '[') && str_ends_with($key, ']')) {
$patterns = ['/' . preg_quote($key, '/') . '/u'];
} else {
$patterns = [
'/(?:«|«)' . preg_quote($key, '/') . '(?:»|»)/u',
'/\{\{' . preg_quote($key, '/') . '\}\}/u',
'/\{' . preg_quote($key, '/') . '\}/u',
'/\[' . preg_quote($key, '/') . '\]/u',
];
}
foreach ($patterns as $pattern) {
$text = preg_replace($pattern, $cleanVal, $text);
}
}
// Dynamic resolution of any remaining tags if resolver is provided
if ($tagResolver !== null && str_contains($text, '[')) {
$text = preg_replace_callback('/(?:\[([a-zA-Z0-9_\-]+)\])?\[([a-zA-Z0-9_\-]+)(?::([^\]]+))?\](?::([a-zA-Z0-9_\/:\s\-]+))?/u', function ($match) use ($tagResolver) {
$fullTag = $match[0];
$resolved = $tagResolver($fullTag);
if ($resolved !== $fullTag) {
$clean = htmlspecialchars((string)$resolved, ENT_XML1, 'UTF-8');
return str_replace(["\r\n", "\r", "\n"], '</w:t><w:br/><w:t xml:space="preserve">', $clean);
}
return $fullTag;
}, $text);
}
if (!str_contains($attrs, 'xml:space')) {
$attrs .= ' xml:space="preserve"';
}
return "<w:t{$attrs}>{$text}</w:t>";
}, $xml);
if ($xmlMerged !== null) {
$xml = $xmlMerged;
}
return $xml;
}
}