Coverage Report

Created: 2025-07-01 06:10

/src/qpdf/libqpdf/QPDFAcroFormDocumentHelper.cc
Line
Count
Source (jump to first uncovered line)
1
#include <qpdf/QPDFAcroFormDocumentHelper.hh>
2
3
#include <qpdf/Pl_Buffer.hh>
4
#include <qpdf/QPDFObjectHandle_private.hh>
5
#include <qpdf/QPDFPageDocumentHelper.hh>
6
#include <qpdf/QTC.hh>
7
#include <qpdf/QUtil.hh>
8
#include <qpdf/ResourceFinder.hh>
9
10
using namespace qpdf;
11
12
QPDFAcroFormDocumentHelper::QPDFAcroFormDocumentHelper(QPDF& qpdf) :
13
0
    QPDFDocumentHelper(qpdf),
14
0
    m(new Members())
15
0
{
16
    // We have to analyze up front. Otherwise, when we are adding annotations and fields, we are in
17
    // a temporarily unstable configuration where some widget annotations are not reachable.
18
0
    analyze();
19
0
}
20
21
void
22
QPDFAcroFormDocumentHelper::invalidateCache()
23
0
{
24
0
    m->cache_valid = false;
25
0
    m->field_to_annotations.clear();
26
0
    m->annotation_to_field.clear();
27
0
}
28
29
bool
30
QPDFAcroFormDocumentHelper::hasAcroForm()
31
0
{
32
0
    return qpdf.getRoot().hasKey("/AcroForm");
33
0
}
34
35
QPDFObjectHandle
36
QPDFAcroFormDocumentHelper::getOrCreateAcroForm()
37
0
{
38
0
    auto acroform = qpdf.getRoot().getKey("/AcroForm");
39
0
    if (!acroform.isDictionary()) {
40
0
        acroform = qpdf.getRoot().replaceKeyAndGetNew(
41
0
            "/AcroForm", qpdf.makeIndirectObject(QPDFObjectHandle::newDictionary()));
42
0
    }
43
0
    return acroform;
44
0
}
45
46
void
47
QPDFAcroFormDocumentHelper::addFormField(QPDFFormFieldObjectHelper ff)
48
0
{
49
0
    auto acroform = getOrCreateAcroForm();
50
0
    auto fields = acroform.getKey("/Fields");
51
0
    if (!fields.isArray()) {
52
0
        fields = acroform.replaceKeyAndGetNew("/Fields", QPDFObjectHandle::newArray());
53
0
    }
54
0
    fields.appendItem(ff.getObjectHandle());
55
0
    QPDFObjGen::set visited;
56
0
    traverseField(ff.getObjectHandle(), QPDFObjectHandle::newNull(), 0, visited);
57
0
}
58
59
void
60
QPDFAcroFormDocumentHelper::addAndRenameFormFields(std::vector<QPDFObjectHandle> fields)
61
0
{
62
0
    analyze();
63
0
    std::map<std::string, std::string> renames;
64
0
    QPDFObjGen::set seen;
65
0
    for (std::list<QPDFObjectHandle> queue{fields.begin(), fields.end()}; !queue.empty();
66
0
         queue.pop_front()) {
67
0
        auto& obj = queue.front();
68
0
        if (seen.add(obj)) {
69
0
            auto kids = obj.getKey("/Kids");
70
0
            if (kids.isArray()) {
71
0
                for (auto const& kid: kids.aitems()) {
72
0
                    queue.push_back(kid);
73
0
                }
74
0
            }
75
76
0
            if (obj.hasKey("/T")) {
77
                // Find something we can append to the partial name that makes the fully qualified
78
                // name unique. When we find something, reuse the same suffix for all fields in this
79
                // group with the same name. We can only change the name of fields that have /T, and
80
                // this field's /T is always at the end of the fully qualified name, appending to /T
81
                // has the effect of appending the same thing to the fully qualified name.
82
0
                std::string old_name = QPDFFormFieldObjectHelper(obj).getFullyQualifiedName();
83
0
                if (!renames.contains(old_name)) {
84
0
                    std::string new_name = old_name;
85
0
                    int suffix = 0;
86
0
                    std::string append;
87
0
                    while (!getFieldsWithQualifiedName(new_name).empty()) {
88
0
                        ++suffix;
89
0
                        append = "+" + std::to_string(suffix);
90
0
                        new_name = old_name + append;
91
0
                    }
92
0
                    renames[old_name] = append;
93
0
                }
94
0
                std::string append = renames[old_name];
95
0
                if (!append.empty()) {
96
0
                    obj.replaceKey(
97
0
                        "/T",
98
0
                        QPDFObjectHandle::newUnicodeString(
99
0
                            obj.getKey("/T").getUTF8Value() + append));
100
0
                }
101
0
            }
102
0
        }
103
0
    }
104
105
0
    for (auto const& i: fields) {
106
0
        addFormField(i);
107
0
    }
108
0
}
109
110
void
111
QPDFAcroFormDocumentHelper::removeFormFields(std::set<QPDFObjGen> const& to_remove)
112
0
{
113
0
    auto acroform = qpdf.getRoot().getKey("/AcroForm");
114
0
    if (!acroform.isDictionary()) {
115
0
        return;
116
0
    }
117
0
    auto fields = acroform.getKey("/Fields");
118
0
    if (!fields.isArray()) {
119
0
        return;
120
0
    }
121
122
0
    for (auto const& og: to_remove) {
123
0
        auto annotations = m->field_to_annotations.find(og);
124
0
        if (annotations != m->field_to_annotations.end()) {
125
0
            for (auto aoh: annotations->second) {
126
0
                m->annotation_to_field.erase(aoh.getObjectHandle().getObjGen());
127
0
            }
128
0
            m->field_to_annotations.erase(og);
129
0
        }
130
0
        auto name = m->field_to_name.find(og);
131
0
        if (name != m->field_to_name.end()) {
132
0
            m->name_to_fields[name->second].erase(og);
133
0
            if (m->name_to_fields[name->second].empty()) {
134
0
                m->name_to_fields.erase(name->second);
135
0
            }
136
0
            m->field_to_name.erase(og);
137
0
        }
138
0
    }
139
140
0
    int i = 0;
141
0
    while (i < fields.getArrayNItems()) {
142
0
        auto field = fields.getArrayItem(i);
143
0
        if (to_remove.contains(field.getObjGen())) {
144
0
            fields.eraseItem(i);
145
0
        } else {
146
0
            ++i;
147
0
        }
148
0
    }
149
0
}
150
151
void
152
QPDFAcroFormDocumentHelper::setFormFieldName(QPDFFormFieldObjectHelper ff, std::string const& name)
153
0
{
154
0
    ff.setFieldAttribute("/T", name);
155
0
    QPDFObjGen::set visited;
156
0
    auto ff_oh = ff.getObjectHandle();
157
0
    traverseField(ff_oh, ff_oh.getKey("/Parent"), 0, visited);
158
0
}
159
160
std::vector<QPDFFormFieldObjectHelper>
161
QPDFAcroFormDocumentHelper::getFormFields()
162
0
{
163
0
    analyze();
164
0
    std::vector<QPDFFormFieldObjectHelper> result;
165
0
    for (auto const& iter: m->field_to_annotations) {
166
0
        result.emplace_back(qpdf.getObject(iter.first));
167
0
    }
168
0
    return result;
169
0
}
170
171
std::set<QPDFObjGen>
172
QPDFAcroFormDocumentHelper::getFieldsWithQualifiedName(std::string const& name)
173
0
{
174
0
    analyze();
175
    // Keep from creating an empty entry
176
0
    auto iter = m->name_to_fields.find(name);
177
0
    if (iter != m->name_to_fields.end()) {
178
0
        return iter->second;
179
0
    }
180
0
    return {};
181
0
}
182
183
std::vector<QPDFAnnotationObjectHelper>
184
QPDFAcroFormDocumentHelper::getAnnotationsForField(QPDFFormFieldObjectHelper h)
185
0
{
186
0
    analyze();
187
0
    std::vector<QPDFAnnotationObjectHelper> result;
188
0
    QPDFObjGen og(h.getObjectHandle().getObjGen());
189
0
    if (m->field_to_annotations.contains(og)) {
190
0
        result = m->field_to_annotations[og];
191
0
    }
192
0
    return result;
193
0
}
194
195
std::vector<QPDFAnnotationObjectHelper>
196
QPDFAcroFormDocumentHelper::getWidgetAnnotationsForPage(QPDFPageObjectHelper h)
197
0
{
198
0
    return h.getAnnotations("/Widget");
199
0
}
200
201
std::vector<QPDFFormFieldObjectHelper>
202
QPDFAcroFormDocumentHelper::getFormFieldsForPage(QPDFPageObjectHelper ph)
203
0
{
204
0
    analyze();
205
0
    QPDFObjGen::set todo;
206
0
    std::vector<QPDFFormFieldObjectHelper> result;
207
0
    for (auto& annot: getWidgetAnnotationsForPage(ph)) {
208
0
        auto field = getFieldForAnnotation(annot).getTopLevelField();
209
0
        if (todo.add(field) && field.getObjectHandle().isDictionary()) {
210
0
            result.push_back(field);
211
0
        }
212
0
    }
213
0
    return result;
214
0
}
215
216
QPDFFormFieldObjectHelper
217
QPDFAcroFormDocumentHelper::getFieldForAnnotation(QPDFAnnotationObjectHelper h)
218
0
{
219
0
    QPDFObjectHandle oh = h.getObjectHandle();
220
0
    QPDFFormFieldObjectHelper result(QPDFObjectHandle::newNull());
221
0
    if (!oh.isDictionaryOfType("", "/Widget")) {
222
0
        return result;
223
0
    }
224
0
    analyze();
225
0
    QPDFObjGen og(oh.getObjGen());
226
0
    if (m->annotation_to_field.contains(og)) {
227
0
        result = m->annotation_to_field[og];
228
0
    }
229
0
    return result;
230
0
}
231
232
void
233
QPDFAcroFormDocumentHelper::analyze()
234
0
{
235
0
    if (m->cache_valid) {
236
0
        return;
237
0
    }
238
0
    m->cache_valid = true;
239
0
    QPDFObjectHandle acroform = qpdf.getRoot().getKey("/AcroForm");
240
0
    if (!(acroform.isDictionary() && acroform.hasKey("/Fields"))) {
241
0
        return;
242
0
    }
243
0
    QPDFObjectHandle fields = acroform.getKey("/Fields");
244
0
    if (auto fa = fields.as_array(strict)) {
245
        // Traverse /AcroForm to find annotations and map them bidirectionally to fields.
246
247
0
        QPDFObjGen::set visited;
248
0
        QPDFObjectHandle null(QPDFObjectHandle::newNull());
249
0
        for (auto const& field: fa) {
250
0
            traverseField(field, null, 0, visited);
251
0
        }
252
0
    } else {
253
0
        QTC::TC("qpdf", "QPDFAcroFormDocumentHelper fields not array");
254
0
        acroform.warnIfPossible("/Fields key of /AcroForm dictionary is not an array; ignoring");
255
0
        fields = QPDFObjectHandle::newArray();
256
0
    }
257
258
    // All Widget annotations should have been encountered by traversing /AcroForm, but in case any
259
    // weren't, find them by walking through pages, and treat any widget annotation that is not
260
    // associated with a field as its own field. This just ensures that requesting the field for any
261
    // annotation we find through a page's /Annots list will have some associated field. Note that
262
    // a file that contains this kind of error will probably not
263
    // actually work with most viewers.
264
265
0
    for (auto const& ph: QPDFPageDocumentHelper(qpdf).getAllPages()) {
266
0
        for (auto const& iter: getWidgetAnnotationsForPage(ph)) {
267
0
            QPDFObjectHandle annot(iter.getObjectHandle());
268
0
            QPDFObjGen og(annot.getObjGen());
269
0
            if (!m->annotation_to_field.contains(og)) {
270
0
                QTC::TC("qpdf", "QPDFAcroFormDocumentHelper orphaned widget");
271
                // This is not supposed to happen, but it's easy enough for us to handle this case.
272
                // Treat the annotation as its own field. This could allow qpdf to sensibly handle a
273
                // case such as a PDF creator adding a self-contained annotation (merged with the
274
                // field dictionary) to the page's /Annots array and forgetting to also put it in
275
                // /AcroForm.
276
0
                annot.warnIfPossible(
277
0
                    "this widget annotation is not"
278
0
                    " reachable from /AcroForm in the document catalog");
279
0
                m->annotation_to_field[og] = QPDFFormFieldObjectHelper(annot);
280
0
                m->field_to_annotations[og].emplace_back(annot);
281
0
            }
282
0
        }
283
0
    }
284
0
}
285
286
void
287
QPDFAcroFormDocumentHelper::traverseField(
288
    QPDFObjectHandle field, QPDFObjectHandle parent, int depth, QPDFObjGen::set& visited)
289
0
{
290
0
    if (depth > 100) {
291
        // Arbitrarily cut off recursion at a fixed depth to avoid specially crafted files that
292
        // could cause stack overflow.
293
0
        return;
294
0
    }
295
0
    if (!field.isIndirect()) {
296
0
        QTC::TC("qpdf", "QPDFAcroFormDocumentHelper direct field");
297
0
        field.warnIfPossible(
298
0
            "encountered a direct object as a field or annotation while "
299
0
            "traversing /AcroForm; ignoring field or annotation");
300
0
        return;
301
0
    }
302
0
    if (!field.isDictionary()) {
303
0
        QTC::TC("qpdf", "QPDFAcroFormDocumentHelper non-dictionary field");
304
0
        field.warnIfPossible(
305
0
            "encountered a non-dictionary as a field or annotation while"
306
0
            " traversing /AcroForm; ignoring field or annotation");
307
0
        return;
308
0
    }
309
0
    QPDFObjGen og(field.getObjGen());
310
0
    if (!visited.add(og)) {
311
0
        QTC::TC("qpdf", "QPDFAcroFormDocumentHelper loop");
312
0
        field.warnIfPossible("loop detected while traversing /AcroForm");
313
0
        return;
314
0
    }
315
316
    // A dictionary encountered while traversing the /AcroForm field may be a form field, an
317
    // annotation, or the merger of the two. A field that has no fields below it is a terminal. If a
318
    // terminal field looks like an annotation, it is an annotation because annotation dictionary
319
    // fields can be merged with terminal field dictionaries. Otherwise, the annotation fields might
320
    // be there to be inherited by annotations below it.
321
322
0
    bool is_annotation = false;
323
0
    bool is_field = (0 == depth);
324
0
    if (auto a = field.getKey("/Kids").as_array(strict)) {
325
0
        is_field = true;
326
0
        for (auto const& item: a) {
327
0
            traverseField(item, field, 1 + depth, visited);
328
0
        }
329
0
    } else {
330
0
        if (field.hasKey("/Parent")) {
331
0
            is_field = true;
332
0
        }
333
0
        if (field.hasKey("/Subtype") || field.hasKey("/Rect") || field.hasKey("/AP")) {
334
0
            is_annotation = true;
335
0
        }
336
0
    }
337
338
0
    QTC::TC("qpdf", "QPDFAcroFormDocumentHelper field found", (depth == 0) ? 0 : 1);
339
0
    QTC::TC("qpdf", "QPDFAcroFormDocumentHelper annotation found", (is_field ? 0 : 1));
340
341
0
    if (is_annotation) {
342
0
        QPDFObjectHandle our_field = (is_field ? field : parent);
343
0
        m->field_to_annotations[our_field.getObjGen()].emplace_back(field);
344
0
        m->annotation_to_field[og] = QPDFFormFieldObjectHelper(our_field);
345
0
    }
346
347
0
    if (is_field && (field.hasKey("/T"))) {
348
0
        QPDFFormFieldObjectHelper foh(field);
349
0
        auto f_og = field.getObjGen();
350
0
        std::string name = foh.getFullyQualifiedName();
351
0
        auto old = m->field_to_name.find(f_og);
352
0
        if (old != m->field_to_name.end()) {
353
            // We might be updating after a name change, so remove any old information
354
0
            std::string old_name = old->second;
355
0
            m->name_to_fields[old_name].erase(f_og);
356
0
        }
357
0
        m->field_to_name[f_og] = name;
358
0
        m->name_to_fields[name].insert(f_og);
359
0
    }
360
0
}
361
362
bool
363
QPDFAcroFormDocumentHelper::getNeedAppearances()
364
0
{
365
0
    bool result = false;
366
0
    QPDFObjectHandle acroform = qpdf.getRoot().getKey("/AcroForm");
367
0
    if (acroform.isDictionary() && acroform.getKey("/NeedAppearances").isBool()) {
368
0
        result = acroform.getKey("/NeedAppearances").getBoolValue();
369
0
    }
370
0
    return result;
371
0
}
372
373
void
374
QPDFAcroFormDocumentHelper::setNeedAppearances(bool val)
375
0
{
376
0
    QPDFObjectHandle acroform = qpdf.getRoot().getKey("/AcroForm");
377
0
    if (!acroform.isDictionary()) {
378
0
        qpdf.getRoot().warnIfPossible(
379
0
            "ignoring call to QPDFAcroFormDocumentHelper::setNeedAppearances"
380
0
            " on a file that lacks an /AcroForm dictionary");
381
0
        return;
382
0
    }
383
0
    if (val) {
384
0
        acroform.replaceKey("/NeedAppearances", QPDFObjectHandle::newBool(true));
385
0
    } else {
386
0
        acroform.removeKey("/NeedAppearances");
387
0
    }
388
0
}
389
390
void
391
QPDFAcroFormDocumentHelper::generateAppearancesIfNeeded()
392
0
{
393
0
    if (!getNeedAppearances()) {
394
0
        return;
395
0
    }
396
397
0
    for (auto const& page: QPDFPageDocumentHelper(qpdf).getAllPages()) {
398
0
        for (auto& aoh: getWidgetAnnotationsForPage(page)) {
399
0
            QPDFFormFieldObjectHelper ffh = getFieldForAnnotation(aoh);
400
0
            if (ffh.getFieldType() == "/Btn") {
401
                // Rather than generating appearances for button fields, rely on what's already
402
                // there. Just make sure /AS is consistent with /V, which we can do by resetting the
403
                // value of the field back to itself. This code is referenced in a comment in
404
                // QPDFFormFieldObjectHelper::generateAppearance.
405
0
                if (ffh.isRadioButton() || ffh.isCheckbox()) {
406
0
                    ffh.setV(ffh.getValue());
407
0
                }
408
0
            } else {
409
0
                ffh.generateAppearance(aoh);
410
0
            }
411
0
        }
412
0
    }
413
0
    setNeedAppearances(false);
414
0
}
415
416
void
417
QPDFAcroFormDocumentHelper::disableDigitalSignatures()
418
0
{
419
0
    qpdf.removeSecurityRestrictions();
420
0
    std::set<QPDFObjGen> to_remove;
421
0
    auto fields = getFormFields();
422
0
    for (auto& f: fields) {
423
0
        auto ft = f.getFieldType();
424
0
        if (ft == "/Sig") {
425
0
            auto oh = f.getObjectHandle();
426
0
            to_remove.insert(oh.getObjGen());
427
            // Make this no longer a form field. If it's also an annotation, the annotation will
428
            // survive. If it's only a field and is no longer referenced, it will disappear.
429
0
            oh.removeKey("/FT");
430
            // Remove fields that are specific to signature fields.
431
0
            oh.removeKey("/V");
432
0
            oh.removeKey("/SV");
433
0
            oh.removeKey("/Lock");
434
0
        }
435
0
    }
436
0
    removeFormFields(to_remove);
437
0
}
438
439
void
440
QPDFAcroFormDocumentHelper::adjustInheritedFields(
441
    QPDFObjectHandle obj,
442
    bool override_da,
443
    std::string const& from_default_da,
444
    bool override_q,
445
    int from_default_q)
446
0
{
447
    // Override /Q or /DA if needed. If this object has a field type, directly or inherited, it is a
448
    // field and not just an annotation. In that case, we need to override if we are getting a value
449
    // from the document that is different from the value we would have gotten from the old
450
    // document. We must take care not to override an explicit value. It's possible that /FT may be
451
    // inherited by lower fields that may explicitly set /DA or /Q or that this is a field whose
452
    // type does not require /DA or /Q and we may be put a value on the field that is unused. This
453
    // is harmless, so it's not worth trying to work around.
454
455
0
    auto has_explicit = [](QPDFFormFieldObjectHelper& field, std::string const& key) {
456
0
        if (field.getObjectHandle().hasKey(key)) {
457
0
            return true;
458
0
        }
459
0
        auto oh = field.getInheritableFieldValue(key);
460
0
        if (!oh.isNull()) {
461
0
            return true;
462
0
        }
463
0
        return false;
464
0
    };
465
466
0
    if (override_da || override_q) {
467
0
        QPDFFormFieldObjectHelper cur_field(obj);
468
0
        if (override_da && (!has_explicit(cur_field, "/DA"))) {
469
0
            std::string da = cur_field.getDefaultAppearance();
470
0
            if (da != from_default_da) {
471
0
                QTC::TC("qpdf", "QPDFAcroFormDocumentHelper override da");
472
0
                obj.replaceKey("/DA", QPDFObjectHandle::newUnicodeString(from_default_da));
473
0
            }
474
0
        }
475
0
        if (override_q && (!has_explicit(cur_field, "/Q"))) {
476
0
            int q = cur_field.getQuadding();
477
0
            if (q != from_default_q) {
478
0
                QTC::TC("qpdf", "QPDFAcroFormDocumentHelper override q");
479
0
                obj.replaceKey("/Q", QPDFObjectHandle::newInteger(from_default_q));
480
0
            }
481
0
        }
482
0
    }
483
0
}
484
485
namespace
486
{
487
    class ResourceReplacer: public QPDFObjectHandle::TokenFilter
488
    {
489
      public:
490
        ResourceReplacer(
491
            std::map<std::string, std::map<std::string, std::string>> const& dr_map,
492
            std::map<std::string, std::map<std::string, std::set<size_t>>> const& rnames);
493
0
        ~ResourceReplacer() override = default;
494
        void handleToken(QPDFTokenizer::Token const&) override;
495
496
      private:
497
        size_t offset{0};
498
        std::map<std::string, std::map<size_t, std::string>> to_replace;
499
    };
500
} // namespace
501
502
ResourceReplacer::ResourceReplacer(
503
    std::map<std::string, std::map<std::string, std::string>> const& dr_map,
504
    std::map<std::string, std::map<std::string, std::set<size_t>>> const& rnames)
505
0
{
506
    // We have:
507
    // * dr_map[resource_type][key] == new_key
508
    // * rnames[resource_type][key] == set of offsets
509
    //
510
    // We want:
511
    // * to_replace[key][offset] = new_key
512
513
0
    for (auto const& rn_iter: rnames) {
514
0
        std::string const& rtype = rn_iter.first;
515
0
        auto dr_map_rtype = dr_map.find(rtype);
516
0
        if (dr_map_rtype == dr_map.end()) {
517
0
            continue;
518
0
        }
519
0
        auto const& key_offsets = rn_iter.second;
520
0
        for (auto const& ko_iter: key_offsets) {
521
0
            std::string const& old_key = ko_iter.first;
522
0
            auto dr_map_rtype_old = dr_map_rtype->second.find(old_key);
523
0
            if (dr_map_rtype_old == dr_map_rtype->second.end()) {
524
0
                continue;
525
0
            }
526
0
            auto const& offsets = ko_iter.second;
527
0
            for (auto const& o_iter: offsets) {
528
0
                to_replace[old_key][o_iter] = dr_map_rtype_old->second;
529
0
            }
530
0
        }
531
0
    }
532
0
}
533
534
void
535
ResourceReplacer::handleToken(QPDFTokenizer::Token const& token)
536
0
{
537
0
    bool wrote = false;
538
0
    if (token.getType() == QPDFTokenizer::tt_name) {
539
0
        std::string name = QPDFObjectHandle::newName(token.getValue()).getName();
540
0
        if (to_replace.contains(name) && to_replace[name].contains(offset)) {
541
0
            QTC::TC("qpdf", "QPDFAcroFormDocumentHelper replaced DA token");
542
0
            write(to_replace[name][offset]);
543
0
            wrote = true;
544
0
        }
545
0
    }
546
0
    offset += token.getRawValue().length();
547
0
    if (!wrote) {
548
0
        writeToken(token);
549
0
    }
550
0
}
551
552
void
553
QPDFAcroFormDocumentHelper::adjustDefaultAppearances(
554
    QPDFObjectHandle obj, std::map<std::string, std::map<std::string, std::string>> const& dr_map)
555
0
{
556
    // This method is called on a field that has been copied from another file but whose /DA still
557
    // refers to resources in the original file's /DR.
558
559
    // When appearance streams are generated for variable text fields (see ISO 32000 PDF spec
560
    // section 12.7.3.3), the field's /DA is used to generate content of the appearance stream. /DA
561
    // contains references to resources that may be resolved in the document's /DR dictionary, which
562
    // appears in the document's /AcroForm dictionary. For fields that we copied from other
563
    // documents, we need to ensure that resources are mapped correctly in the case of conflicting
564
    // names. For example, if a.pdf's /DR has /F1 pointing to one font and b.pdf's /DR also has /F1
565
    // but it points elsewhere, we need to make sure appearance streams of fields copied from b.pdf
566
    // into a.pdf use whatever font /F1 meant in b.pdf, not whatever it means in a.pdf. This method
567
    // takes care of that. It is only called on fields copied from foreign files.
568
569
    // A few notes:
570
    //
571
    // * If the from document's /DR and the current document's /DR have conflicting keys, we have
572
    //   already resolved the conflicts before calling this method. The dr_map parameter contains
573
    //   the mapping from old keys to new keys.
574
    //
575
    // * /DA may be inherited from the document's /AcroForm dictionary. By the time this method has
576
    //   been called, we have already copied any document-level values into the fields to avoid
577
    //   having them inherit from the new document. This was done in adjustInheritedFields.
578
579
0
    auto DA = obj.getKey("/DA");
580
0
    if (!DA.isString()) {
581
0
        return;
582
0
    }
583
584
    // Find names in /DA. /DA is a string that contains content stream-like code, so we create a
585
    // stream out of the string and then filter it. We don't attach the stream to anything, so it
586
    // will get discarded.
587
0
    ResourceFinder rf;
588
0
    auto da_stream = QPDFObjectHandle::newStream(&qpdf, DA.getUTF8Value());
589
0
    try {
590
0
        auto nwarnings = qpdf.numWarnings();
591
0
        da_stream.parseAsContents(&rf);
592
0
        if (qpdf.numWarnings() > nwarnings) {
593
0
            QTC::TC("qpdf", "QPDFAcroFormDocumentHelper /DA parse error");
594
0
        }
595
0
    } catch (std::exception& e) {
596
        // No way to reproduce in test suite right now since error conditions are converted to
597
        // warnings.
598
0
        obj.warnIfPossible(
599
0
            std::string("Unable to parse /DA: ") + e.what() +
600
0
            "; this form field may not update properly");
601
0
        return;
602
0
    }
603
604
    // Regenerate /DA by filtering its tokens.
605
0
    ResourceReplacer rr(dr_map, rf.getNamesByResourceType());
606
0
    Pl_Buffer buf_pl("filtered DA");
607
0
    da_stream.filterAsContents(&rr, &buf_pl);
608
0
    std::string new_da = buf_pl.getString();
609
0
    obj.replaceKey("/DA", QPDFObjectHandle::newString(new_da));
610
0
}
611
612
void
613
QPDFAcroFormDocumentHelper::adjustAppearanceStream(
614
    QPDFObjectHandle stream, std::map<std::string, std::map<std::string, std::string>> dr_map)
615
0
{
616
    // We don't have to modify appearance streams or their resource dictionaries for them to display
617
    // properly, but we need to do so to make them save to regenerate. Suppose an appearance stream
618
    // as a font /F1 that is different from /F1 in /DR, and that when we copy the field, /F1 is
619
    // remapped to /F1_1. When the field is regenerated, /F1_1 won't appear in the stream's resource
620
    // dictionary, so the regenerated appearance stream will revert to the /F1_1 in /DR. If we
621
    // adjust existing appearance streams, we are protected from this problem.
622
623
0
    auto dict = stream.getDict();
624
0
    auto resources = dict.getKey("/Resources");
625
626
    // Make sure this stream has its own private resource dictionary.
627
0
    bool was_indirect = resources.isIndirect();
628
0
    resources = resources.shallowCopy();
629
0
    if (was_indirect) {
630
0
        resources = qpdf.makeIndirectObject(resources);
631
0
    }
632
0
    dict.replaceKey("/Resources", resources);
633
    // Create a dictionary with top-level keys so we can use mergeResources to force them to be
634
    // unshared. We will also use this to resolve conflicts that may already be in the resource
635
    // dictionary.
636
0
    auto merge_with = QPDFObjectHandle::newDictionary();
637
0
    for (auto const& top_key: dr_map) {
638
0
        merge_with.replaceKey(top_key.first, QPDFObjectHandle::newDictionary());
639
0
    }
640
0
    resources.mergeResources(merge_with);
641
    // Rename any keys in the resource dictionary that we remapped.
642
0
    for (auto const& i1: dr_map) {
643
0
        std::string const& top_key = i1.first;
644
0
        auto subdict = resources.getKey(top_key);
645
0
        if (!subdict.isDictionary()) {
646
0
            continue;
647
0
        }
648
0
        for (auto const& i2: i1.second) {
649
0
            std::string const& old_key = i2.first;
650
0
            std::string const& new_key = i2.second;
651
0
            auto existing_new = subdict.getKey(new_key);
652
0
            if (!existing_new.isNull()) {
653
                // The resource dictionary already has a key in it matching what we remapped an old
654
                // key to, so we'll have to move it out of the way. Stick it in merge_with, which we
655
                // will re-merge with the dictionary when we're done. We know merge_with already has
656
                // dictionaries for all the top keys.
657
0
                QTC::TC("qpdf", "QPDFAcroFormDocumentHelper ap conflict");
658
0
                merge_with.getKey(top_key).replaceKey(new_key, existing_new);
659
0
            }
660
0
            auto existing_old = subdict.getKey(old_key);
661
0
            if (!existing_old.isNull()) {
662
0
                QTC::TC("qpdf", "QPDFAcroFormDocumentHelper ap rename");
663
0
                subdict.replaceKey(new_key, existing_old);
664
0
                subdict.removeKey(old_key);
665
0
            }
666
0
        }
667
0
    }
668
    // Deal with any any conflicts by re-merging with merge_with and updating our local copy of
669
    // dr_map, which we will use to modify the stream contents.
670
0
    resources.mergeResources(merge_with, &dr_map);
671
    // Remove empty subdictionaries
672
0
    for (auto iter: resources.ditems()) {
673
0
        if (iter.second.isDictionary() && iter.second.getKeys().empty()) {
674
0
            resources.removeKey(iter.first);
675
0
        }
676
0
    }
677
678
    // Now attach a token filter to replace the actual resources.
679
0
    ResourceFinder rf;
680
0
    try {
681
0
        auto nwarnings = qpdf.numWarnings();
682
0
        stream.parseAsContents(&rf);
683
0
        if (qpdf.numWarnings() > nwarnings) {
684
0
            QTC::TC("qpdf", "QPDFAcroFormDocumentHelper AP parse error");
685
0
        }
686
0
        auto rr = new ResourceReplacer(dr_map, rf.getNamesByResourceType());
687
0
        auto tf = std::shared_ptr<QPDFObjectHandle::TokenFilter>(rr);
688
0
        stream.addTokenFilter(tf);
689
0
    } catch (std::exception& e) {
690
        // No way to reproduce in test suite right now since error conditions are converted to
691
        // warnings.
692
0
        stream.warnIfPossible(std::string("Unable to parse appearance stream: ") + e.what());
693
0
    }
694
0
}
695
696
void
697
QPDFAcroFormDocumentHelper::transformAnnotations(
698
    QPDFObjectHandle old_annots,
699
    std::vector<QPDFObjectHandle>& new_annots,
700
    std::vector<QPDFObjectHandle>& new_fields,
701
    std::set<QPDFObjGen>& old_fields,
702
    QPDFMatrix const& cm,
703
    QPDF* from_qpdf,
704
    QPDFAcroFormDocumentHelper* from_afdh)
705
0
{
706
0
    std::shared_ptr<QPDFAcroFormDocumentHelper> afdhph;
707
0
    if (!from_qpdf) {
708
        // Assume these are from the same QPDF.
709
0
        from_qpdf = &qpdf;
710
0
        from_afdh = this;
711
0
    } else if ((from_qpdf != &qpdf) && (!from_afdh)) {
712
0
        afdhph = std::make_shared<QPDFAcroFormDocumentHelper>(*from_qpdf);
713
0
        from_afdh = afdhph.get();
714
0
    }
715
0
    bool foreign = (from_qpdf != &qpdf);
716
717
    // It's possible that we will transform annotations that don't include any form fields. This
718
    // code takes care not to muck around with /AcroForm unless we have to.
719
720
0
    QPDFObjectHandle acroform = qpdf.getRoot().getKey("/AcroForm");
721
0
    QPDFObjectHandle from_acroform = from_qpdf->getRoot().getKey("/AcroForm");
722
723
    // /DA and /Q may be inherited from the document-level /AcroForm dictionary. If we are copying a
724
    // foreign stream and the stream is getting one of these values from its document's /AcroForm,
725
    // we will need to copy the value explicitly so that it doesn't start getting its default from
726
    // the destination document.
727
0
    bool override_da = false;
728
0
    bool override_q = false;
729
0
    std::string from_default_da;
730
0
    int from_default_q = 0;
731
    // If we copy any form fields, we will need to merge the source document's /DR into this
732
    // document's /DR.
733
0
    QPDFObjectHandle from_dr = QPDFObjectHandle::newNull();
734
0
    if (foreign) {
735
0
        std::string default_da;
736
0
        int default_q = 0;
737
0
        if (acroform.isDictionary()) {
738
0
            if (acroform.getKey("/DA").isString()) {
739
0
                default_da = acroform.getKey("/DA").getUTF8Value();
740
0
            }
741
0
            if (acroform.getKey("/Q").isInteger()) {
742
0
                default_q = acroform.getKey("/Q").getIntValueAsInt();
743
0
            }
744
0
        }
745
0
        if (from_acroform.isDictionary()) {
746
0
            if (from_acroform.getKey("/DR").isDictionary()) {
747
0
                from_dr = from_acroform.getKey("/DR");
748
0
                if (!from_dr.isIndirect()) {
749
0
                    from_dr = from_qpdf->makeIndirectObject(from_dr);
750
0
                }
751
0
                from_dr = qpdf.copyForeignObject(from_dr);
752
0
            }
753
0
            if (from_acroform.getKey("/DA").isString()) {
754
0
                from_default_da = from_acroform.getKey("/DA").getUTF8Value();
755
0
            }
756
0
            if (from_acroform.getKey("/Q").isInteger()) {
757
0
                from_default_q = from_acroform.getKey("/Q").getIntValueAsInt();
758
0
            }
759
0
        }
760
0
        if (from_default_da != default_da) {
761
0
            override_da = true;
762
0
        }
763
0
        if (from_default_q != default_q) {
764
0
            override_q = true;
765
0
        }
766
0
    }
767
768
    // If we have to merge /DR, we will need a mapping of conflicting keys for rewriting /DA. Set
769
    // this up for lazy initialization in case we encounter any form fields.
770
0
    std::map<std::string, std::map<std::string, std::string>> dr_map;
771
0
    bool initialized_dr_map = false;
772
0
    QPDFObjectHandle dr = QPDFObjectHandle::newNull();
773
0
    auto init_dr_map = [&]() {
774
0
        if (!initialized_dr_map) {
775
0
            initialized_dr_map = true;
776
            // Ensure that we have a /DR that is an indirect
777
            // dictionary object.
778
0
            if (!acroform.isDictionary()) {
779
0
                acroform = getOrCreateAcroForm();
780
0
            }
781
0
            dr = acroform.getKey("/DR");
782
0
            if (!dr.isDictionary()) {
783
0
                dr = QPDFObjectHandle::newDictionary();
784
0
            }
785
0
            dr.makeResourcesIndirect(qpdf);
786
0
            if (!dr.isIndirect()) {
787
0
                dr = acroform.replaceKeyAndGetNew("/DR", qpdf.makeIndirectObject(dr));
788
0
            }
789
            // Merge the other document's /DR, creating a conflict map. mergeResources checks to
790
            // make sure both objects are dictionaries. By this point, if this is foreign, from_dr
791
            // has been copied, so we use the target qpdf as the owning qpdf.
792
0
            from_dr.makeResourcesIndirect(qpdf);
793
0
            dr.mergeResources(from_dr, &dr_map);
794
795
0
            if (from_afdh->getNeedAppearances()) {
796
0
                setNeedAppearances(true);
797
0
            }
798
0
        }
799
0
    };
800
801
    // This helper prevents us from copying the same object multiple times.
802
0
    std::map<QPDFObjGen, QPDFObjectHandle> orig_to_copy;
803
0
    auto maybe_copy_object = [&](QPDFObjectHandle& to_copy) {
804
0
        auto og = to_copy.getObjGen();
805
0
        if (orig_to_copy.contains(og)) {
806
0
            to_copy = orig_to_copy[og];
807
0
            return false;
808
0
        } else {
809
0
            to_copy = qpdf.makeIndirectObject(to_copy.shallowCopy());
810
0
            orig_to_copy[og] = to_copy;
811
0
            return true;
812
0
        }
813
0
    };
814
815
    // Now do the actual copies.
816
817
0
    QPDFObjGen::set added_new_fields;
818
0
    for (auto annot: old_annots.aitems()) {
819
0
        if (annot.isStream()) {
820
0
            annot.warnIfPossible("ignoring annotation that's a stream");
821
0
            continue;
822
0
        }
823
824
        // Make copies of annotations and fields down to the appearance streams, preserving all
825
        // internal referential integrity. When the incoming annotations are from a different file,
826
        // we first copy them locally. Then, whether local or foreign, we copy them again so that if
827
        // we bring the same annotation in multiple times (e.g. overlaying a foreign page onto
828
        // multiple local pages or a local page onto multiple other local pages), we don't create
829
        // annotations that are referenced in more than one place. If we did that, the effect of
830
        // applying transformations would be cumulative, which is definitely not what we want.
831
        // Besides, annotations and fields are not intended to be referenced in multiple places.
832
833
        // Determine if this annotation is attached to a form field. If so, the annotation may be
834
        // the same object as the form field, or the form field may have the annotation as a kid. In
835
        // either case, we have to walk up the field structure to find the top-level field. Within
836
        // one iteration through a set of annotations, we don't want to copy the same item more than
837
        // once. For example, suppose we have field A with kids B, C, and D, each of which has
838
        // annotations BA, CA, and DA. When we get to BA, we will find that BA is a kid of B which
839
        // is under A. When we do a copyForeignObject of A, it will also copy everything else
840
        // because of the indirect references. When we clone BA, we will want to clone A and then
841
        // update A's clone's kid to point B's clone and B's clone's parent to point to A's clone.
842
        // The same thing holds for annotations. Next, when we get to CA, we will again discover
843
        // that A is the top, but we don't want to re-copy A. We want CA's clone to be linked to the
844
        // same clone as BA's. Failure to do this will break up things like radio button groups,
845
        // which all have to kids of the same parent.
846
847
0
        auto ffield = from_afdh->getFieldForAnnotation(annot);
848
0
        auto ffield_oh = ffield.getObjectHandle();
849
0
        QPDFObjectHandle top_field;
850
0
        bool have_field = false;
851
0
        bool have_parent = false;
852
0
        if (ffield_oh.isStream()) {
853
0
            ffield_oh.warnIfPossible("ignoring form field that's a stream");
854
0
        } else if ((!ffield_oh.isNull()) && (!ffield_oh.isIndirect())) {
855
0
            ffield_oh.warnIfPossible("ignoring form field not indirect");
856
0
        } else if (!ffield_oh.isNull()) {
857
            // A field and its associated annotation can be the same object. This matters because we
858
            // don't want to clone the annotation and field separately in this case.
859
0
            have_field = true;
860
            // Find the top-level field. It may be the field itself.
861
0
            top_field = ffield.getTopLevelField(&have_parent).getObjectHandle();
862
0
            if (foreign) {
863
                // copyForeignObject returns the same value if called multiple times with the same
864
                // field. Create/retrieve the local copy of the original field. This pulls over
865
                // everything the field references including annotations and appearance streams, but
866
                // it's harmless to call copyForeignObject on them too. They will already be copied,
867
                // so we'll get the right object back.
868
869
                // top_field and ffield_oh are known to be indirect.
870
0
                top_field = qpdf.copyForeignObject(top_field);
871
0
                ffield_oh = qpdf.copyForeignObject(ffield_oh);
872
0
            } else {
873
                // We don't need to add top_field to old_fields if it's foreign because the new copy
874
                // of the foreign field won't be referenced anywhere. It's just the starting point
875
                // for us to make an additional local copy of.
876
0
                old_fields.insert(top_field.getObjGen());
877
0
            }
878
879
            // Traverse the field, copying kids, and preserving integrity.
880
0
            std::list<QPDFObjectHandle> queue;
881
0
            QPDFObjGen::set seen;
882
0
            if (maybe_copy_object(top_field)) {
883
0
                queue.push_back(top_field);
884
0
            }
885
0
            for (; !queue.empty(); queue.pop_front()) {
886
0
                auto& obj = queue.front();
887
0
                if (seen.add(obj)) {
888
0
                    auto parent = obj.getKey("/Parent");
889
0
                    if (parent.isIndirect()) {
890
0
                        auto parent_og = parent.getObjGen();
891
0
                        if (orig_to_copy.contains(parent_og)) {
892
0
                            obj.replaceKey("/Parent", orig_to_copy[parent_og]);
893
0
                        } else {
894
0
                            parent.warnIfPossible(
895
0
                                "while traversing field " + obj.getObjGen().unparse(',') +
896
0
                                ", found parent (" + parent_og.unparse(',') +
897
0
                                ") that had not been seen, indicating likely invalid field "
898
0
                                "structure");
899
0
                        }
900
0
                    }
901
0
                    auto kids = obj.getKey("/Kids");
902
0
                    if (kids.isArray()) {
903
0
                        for (int i = 0; i < kids.getArrayNItems(); ++i) {
904
0
                            auto kid = kids.getArrayItem(i);
905
0
                            if (maybe_copy_object(kid)) {
906
0
                                kids.setArrayItem(i, kid);
907
0
                                queue.push_back(kid);
908
0
                            }
909
0
                        }
910
0
                    }
911
912
0
                    if (override_da || override_q) {
913
0
                        adjustInheritedFields(
914
0
                            obj, override_da, from_default_da, override_q, from_default_q);
915
0
                    }
916
0
                    if (foreign) {
917
                        // Lazily initialize our /DR and the conflict map.
918
0
                        init_dr_map();
919
                        // The spec doesn't say anything about /DR on the field, but lots of writers
920
                        // put one there, and it is frequently the same as the document-level /DR.
921
                        // To avoid having the field's /DR point to information that we are not
922
                        // maintaining, just reset it to that if it exists. Empirical evidence
923
                        // suggests that many readers, including Acrobat, Adobe Acrobat Reader,
924
                        // chrome, firefox, the mac Preview application, and several of the free
925
                        // readers on Linux all ignore /DR at the field level.
926
0
                        if (obj.hasKey("/DR")) {
927
0
                            obj.replaceKey("/DR", dr);
928
0
                        }
929
0
                    }
930
0
                    if (foreign && obj.getKey("/DA").isString() && (!dr_map.empty())) {
931
0
                        adjustDefaultAppearances(obj, dr_map);
932
0
                    }
933
0
                }
934
0
            }
935
936
            // Now switch to copies. We already switched for top_field
937
0
            maybe_copy_object(ffield_oh);
938
0
            ffield = QPDFFormFieldObjectHelper(ffield_oh);
939
0
        }
940
941
0
        QTC::TC(
942
0
            "qpdf",
943
0
            "QPDFAcroFormDocumentHelper copy annotation",
944
0
            (have_field ? 1 : 0) | (foreign ? 2 : 0));
945
0
        if (have_field) {
946
0
            QTC::TC(
947
0
                "qpdf",
948
0
                "QPDFAcroFormDocumentHelper field with parent",
949
0
                (have_parent ? 1 : 0) | (foreign ? 2 : 0));
950
0
        }
951
0
        if (foreign) {
952
0
            if (!annot.isIndirect()) {
953
0
                annot = from_qpdf->makeIndirectObject(annot);
954
0
            }
955
0
            annot = qpdf.copyForeignObject(annot);
956
0
        }
957
0
        maybe_copy_object(annot);
958
959
        // Now we have copies, so we can safely mutate.
960
0
        if (have_field && added_new_fields.add(top_field)) {
961
0
            new_fields.push_back(top_field);
962
0
        }
963
0
        new_annots.push_back(annot);
964
965
        // Identify and copy any appearance streams
966
967
0
        auto ah = QPDFAnnotationObjectHelper(annot);
968
0
        auto apdict = ah.getAppearanceDictionary();
969
0
        std::vector<QPDFObjectHandle> streams;
970
0
        auto replace_stream = [](auto& dict, auto& key, auto& old) {
971
0
            return dict.replaceKeyAndGetNew(key, old.copyStream());
972
0
        };
973
974
0
        for (auto& [key1, value1]: apdict.as_dictionary()) {
975
0
            if (value1.isStream()) {
976
0
                streams.emplace_back(replace_stream(apdict, key1, value1));
977
0
            } else {
978
0
                for (auto& [key2, value2]: value1.as_dictionary()) {
979
0
                    if (value2.isStream()) {
980
0
                        streams.emplace_back(replace_stream(value1, key2, value2));
981
0
                    }
982
0
                }
983
0
            }
984
0
        }
985
986
        // Now we can safely mutate the annotation and its appearance streams.
987
0
        for (auto& stream: streams) {
988
0
            auto dict = stream.getDict();
989
0
            auto omatrix = dict.getKey("/Matrix");
990
0
            QPDFMatrix apcm;
991
0
            if (omatrix.isArray()) {
992
0
                QTC::TC("qpdf", "QPDFAcroFormDocumentHelper modify ap matrix");
993
0
                auto m1 = omatrix.getArrayAsMatrix();
994
0
                apcm = QPDFMatrix(m1);
995
0
            }
996
0
            apcm.concat(cm);
997
0
            auto new_matrix = QPDFObjectHandle::newFromMatrix(apcm);
998
0
            if (omatrix.isArray() || (apcm != QPDFMatrix())) {
999
0
                dict.replaceKey("/Matrix", new_matrix);
1000
0
            }
1001
0
            auto resources = dict.getKey("/Resources");
1002
0
            if ((!dr_map.empty()) && resources.isDictionary()) {
1003
0
                adjustAppearanceStream(stream, dr_map);
1004
0
            }
1005
0
        }
1006
0
        auto rect = cm.transformRectangle(annot.getKey("/Rect").getArrayAsRectangle());
1007
0
        annot.replaceKey("/Rect", QPDFObjectHandle::newFromRectangle(rect));
1008
0
    }
1009
0
}
1010
1011
void
1012
QPDFAcroFormDocumentHelper::fixCopiedAnnotations(
1013
    QPDFObjectHandle to_page,
1014
    QPDFObjectHandle from_page,
1015
    QPDFAcroFormDocumentHelper& from_afdh,
1016
    std::set<QPDFObjGen>* added_fields)
1017
0
{
1018
0
    auto old_annots = from_page.getKey("/Annots");
1019
0
    if ((!old_annots.isArray()) || (old_annots.getArrayNItems() == 0)) {
1020
0
        return;
1021
0
    }
1022
1023
0
    std::vector<QPDFObjectHandle> new_annots;
1024
0
    std::vector<QPDFObjectHandle> new_fields;
1025
0
    std::set<QPDFObjGen> old_fields;
1026
0
    transformAnnotations(
1027
0
        old_annots,
1028
0
        new_annots,
1029
0
        new_fields,
1030
0
        old_fields,
1031
0
        QPDFMatrix(),
1032
0
        &(from_afdh.getQPDF()),
1033
0
        &from_afdh);
1034
1035
0
    to_page.replaceKey("/Annots", QPDFObjectHandle::newArray(new_annots));
1036
0
    addAndRenameFormFields(new_fields);
1037
0
    if (added_fields) {
1038
0
        for (auto const& f: new_fields) {
1039
0
            added_fields->insert(f.getObjGen());
1040
0
        }
1041
0
    }
1042
0
}