summaryrefslogtreecommitdiff
path: root/lib/Image/ExifTool/OOXML.pm
blob: 6e3982dac1aeb86b6db68fb54f47bff47f4fdcb5 (plain)
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
#------------------------------------------------------------------------------
# File:         OOXML.pm
#
# Description:  Read Office Open XML+ZIP files
#
# Revisions:    2009/10/31 - P. Harvey Created
#------------------------------------------------------------------------------

package Image::ExifTool::OOXML;

use strict;
use vars qw($VERSION);
use Image::ExifTool qw(:DataAccess :Utils);
use Image::ExifTool::XMP;
use Image::ExifTool::ZIP;

$VERSION = '1.07';

# test for recognized OOXML document extensions
my %isOOXML = (
    DOCX => 1,  DOCM => 1,
    DOTX => 1,  DOTM => 1,
    POTX => 1,  POTM => 1,
    PPSX => 1,  PPSM => 1,
    PPTX => 1,  PPTM => 1,  THMX => 1,
    XLAM => 1,
    XLSX => 1,  XLSM => 1,  XLSB => 1,
    XLTX => 1,  XLTM => 1,
);

# generate reverse lookup for file type based on MIME
my %fileType;
{
    my $type;
    foreach $type (keys %isOOXML) {
        $fileType{$Image::ExifTool::mimeType{$type}} = $type;
    }
}

# XML attributes to queue
my %queuedAttrs;
my %queueAttrs = (
    fmtid => 1,
    pid   => 1,
    name  => 1,
);

# keep track of items in a vector (to accumulate as a list)
my $vectorCount;
my @vectorVals;

# Office Open XML tags
%Image::ExifTool::OOXML::Main = (
    GROUPS => { 0 => 'XML', 1 => 'XML', 2 => 'Document' },
    PROCESS_PROC => \&Image::ExifTool::XMP::ProcessXMP,
    VARS => { NO_ID => 1 },
    NOTES => q{
        The Office Open XML (OOXML) format was introduced with Microsoft Office 2007
        and is used by file types such as DOCX, PPTX and XLSX.  These are
        essentially ZIP archives containing XML files.  The table below lists some
        tags which have been observed in OOXML documents, but ExifTool will extract
        any tags found from XML files of the OOXML document properties ("docProps")
        directory.

        B<Tips:>
        
        1) Structural ZIP tags may be ignored (if desired) with C<--ZIP:all> on the
        command line.
        
        2) Tags may be grouped by their document number in the ZIP archive with the
        C<-g3> or C<-G3> option.
    },
    # These tags all have 1:1 correspondence with FlashPix tags except for:
    #   OOXML            FlashPix
    #   ---------------  -------------
    #   DocSecurity      Security
    #   Application      Software
    #   dc:Description   Comments
    #   dc:Creator       Author
    Application => { },
    AppVersion  => { },
    category    => { },
    Characters  => { },
    CharactersWithSpaces => { },
    CheckedBy   => { },
    Client      => { },
    Company     => { },
    created     => {
        Name => 'CreateDate',
        Groups => { 2 => 'Time' },
        Format => 'date',
        PrintConv => '$self->ConvertDateTime($val)',
    },
    createdType => { Hidden => 1, RawConv => 'undef' }, # ignore this XML type name
    DateCompleted => {
        Groups => { 2 => 'Time' },
        Format => 'date',
        PrintConv => '$self->ConvertDateTime($val)',
    },
    Department  => { },
    Destination => { },
    Disposition => { },
    Division    => { },
    DocSecurity => {
        # (http://msdn.microsoft.com/en-us/library/documentformat.openxml.extendedproperties.documentsecurity.aspx)
        PrintConv => {
            0 => 'None',
            1 => 'Password protected',
            2 => 'Read-only recommended',
            4 => 'Read-only enforced',
            8 => 'Locked for annotations',
        },
    },
    DocumentNumber=> { },
    Editor      => { Groups => { 2 => 'Author'} },
    ForwardTo   => { },
    Group       => { },
    HeadingPairs=> { },
    HiddenSlides=> { },
    HyperlinkBase=>{ },
    HyperlinksChanged => { PrintConv => { 'false' => 'No', 'true' => 'Yes' } },
    keywords    => { },
    Language    => { },
    lastModifiedBy => { Groups => { 2 => 'Author'} },
    lastPrinted => {
        Groups => { 2 => 'Time' },
        Format => 'date',
        PrintConv => '$self->ConvertDateTime($val)',
    },
    Lines       => { },
    LinksUpToDate=>{ PrintConv => { 'false' => 'No', 'true' => 'Yes' } },
    Mailstop    => { },
    Manager     => { },
    Matter      => { },
    MMClips     => { },
    modified    => {
        Name => 'ModifyDate', 
        Groups => { 2 => 'Time' },
        Format => 'date',
        PrintConv => '$self->ConvertDateTime($val)',
    },
    modifiedType=> { Hidden => 1, RawConv => 'undef' }, # ignore this XML type name
    Notes       => { },
    Office      => { },
    Owner       => { Groups => { 2 => 'Author'} },
    Pages       => { },
    Paragraphs  => { },
    PresentationFormat => { },
    Project     => { },
    Publisher   => { },
    Purpose     => { },
    ReceivedFrom=> { },
    RecordedBy  => { },
    RecordedDate=> {
        Groups => { 2 => 'Time' },
        Format => 'date',
        PrintConv => '$self->ConvertDateTime($val)',
    },
    Reference   => { },
    revision    => { Name => 'RevisionNumber' },
    ScaleCrop   => { PrintConv => { 'false' => 'No', 'true' => 'Yes' } },
    SharedDoc   => { PrintConv => { 'false' => 'No', 'true' => 'Yes' } },
    Slides      => { },
    Source      => { },
    Status      => { },
    TelephoneNumber => { },
    Template    => { },
    TitlesOfParts=>{ },
    TotalTime   => {
        Name => 'TotalEditTime',
        PrintConv => 'ConvertTimeSpan($val, 60)',
    },
    Typist      => { },
    Words       => { },
);

#------------------------------------------------------------------------------
# Generate a tag ID for this XML tag
# Inputs: 0) tag property name list ref
# Returns: tagID and outtermost interesting namespace (or '' if no namespace)
sub GetTagID($)
{
    my $props = shift;
    my ($tag, $prop, $namespace);
    foreach $prop (@$props) {
        # split name into namespace and property name
        # (Note: namespace can be '' for property qualifiers)
        my ($ns, $nm) = ($prop =~ /(.*?):(.*)/) ? ($1, $2) : ('', $prop);
        next if $ns eq 'vt';        # ignore 'vt' properties
        if (defined $tag) {
            $tag .= ucfirst($nm);   # add to tag name
        } elsif ($prop ne 'Properties' and $prop ne 'cp:coreProperties' and
                 $prop ne 'property')
        {
            $tag = $nm;
            # save namespace of first property to contribute to tag name
            $namespace = $ns unless $namespace;
        }
    }
    return ($tag, $namespace || '');
}

#------------------------------------------------------------------------------
# We found an XMP property name/value
# Inputs: 0) ExifTool object ref, 1) tag table ref
#         2) reference to array of XMP property names (last is current property)
#         3) property value, 4) attribute hash ref (not used here)
# Returns: 1 if valid tag was found
sub FoundTag($$$$;$)
{
    my ($et, $tagTablePtr, $props, $val, $attrs) = @_;
    return 0 unless @$props;
    my $verbose = $et->Options('Verbose');

    my $tag = $$props[-1];
    $et->VPrint(0, "  | - Tag '", join('/',@$props), "'\n") if $verbose > 1;

    # un-escape XML character entities
    $val = Image::ExifTool::XMP::UnescapeXML($val);
    # convert OOXML-escaped characters (eg. "_x0000d_" is a newline)
    $val =~ s/_x([0-9a-f]{4})_/Image::ExifTool::PackUTF8(hex($1))/gie;
    # convert from UTF8 to ExifTool Charset
    $val = $et->Decode($val, 'UTF8');
    # queue this attribute for later if necessary
    if ($queueAttrs{$tag}) {
        $queuedAttrs{$tag} = $val;
        return 0;
    }
    my $ns;
    ($tag, $ns) = GetTagID($props);
    if (not $tag) {
        # all properties are in ignored namespaces
        # so 'name' from our queued attributes for the tag
        my $name = $queuedAttrs{name} or return 0;
        $name =~ s/(^| )([a-z])/$1\U$2/g;     # start words with uppercase
        ($tag = $name) =~ tr/-_a-zA-Z0-9//dc;
        return 0 unless length $tag;
        unless ($$tagTablePtr{$tag}) {
            my %tagInfo = (
                Name => $tag,
                Description => $name,
            );
            # format as a date/time value if type is 'vt:filetime'
            if ($$props[-1] eq 'vt:filetime') {
                $tagInfo{Groups} = { 2 => 'Time' },
                $tagInfo{Format} = 'date',
                $tagInfo{PrintConv} = '$self->ConvertDateTime($val)';
            }
            $et->VPrint(0, "  | [adding $tag]\n") if $verbose;
            AddTagToTable($tagTablePtr, $tag, \%tagInfo);
        }
    } elsif ($tag eq 'xmlns') {
        # ignore namespaces (for now)
        return 0;
    } elsif (ref $Image::ExifTool::XMP::Main{$ns} eq 'HASH' and
        $Image::ExifTool::XMP::Main{$ns}{SubDirectory})
    {
        # use standard XMP table if it exists
        my $table = $Image::ExifTool::XMP::Main{$ns}{SubDirectory}{TagTable};
        no strict 'refs';
        if ($table and %$table) {
            $tagTablePtr = Image::ExifTool::GetTagTable($table);
        }
    } elsif (@$props > 2 and grep /^vt:vector$/, @$props) {
        # handle vector properties (accumulate as lists)
        if ($$props[-1] eq 'vt:size') {
            $vectorCount = $val;
            undef @vectorVals;
            return 0;
        } elsif ($$props[-1] eq 'vt:baseType') {
            return 0;   # ignore baseType
        } elsif ($vectorCount) {
            --$vectorCount;
            if ($vectorCount) {
                push @vectorVals, $val;
                return 0;
            }
            $val = [ @vectorVals, $val ] if @vectorVals;
            # Note: we will lose any improper-sized vector elements here
        }
    }
    # add any unknown tags to table
    if ($$tagTablePtr{$tag}) {
        my $tagInfo = $$tagTablePtr{$tag};
        if (ref $tagInfo eq 'HASH') {
            # reformat date/time values
            my $fmt = $$tagInfo{Format} || $$tagInfo{Writable} || '';
            $val = Image::ExifTool::XMP::ConvertXMPDate($val) if $fmt eq 'date';
        }
    } else {
        $et->VPrint(0, "  [adding $tag]\n") if $verbose;
        AddTagToTable($tagTablePtr, $tag, { Name => ucfirst $tag });
    }
    # save the tag
    $et->HandleTag($tagTablePtr, $tag, $val);

    # start fresh for next tag
    undef $vectorCount;
    undef %queuedAttrs;

    return 1;
}

#------------------------------------------------------------------------------
# Extract information from an OOXML file
# Inputs: 0) ExifTool object reference, 1) dirInfo reference
# Returns: 1
# Notes: Upon entry to this routine, the file type has already been verified
# and the dirInfo hash contains 2 elements unique to this process proc:
#   MIME    - mime type of main document from "[Content_Types].xml"
#   ZIP     - reference to Archive::Zip object for this file
sub ProcessDOCX($$)
{
    my ($et, $dirInfo) = @_;
    my $zip = $$dirInfo{ZIP};
    my $tagTablePtr = GetTagTable('Image::ExifTool::OOXML::Main');
    my $mime = $$dirInfo{MIME} || $Image::ExifTool::mimeType{DOCX};

    # set the file type ('DOCX' by default)
    my $fileType = $fileType{$mime};
    if ($fileType) {
        # THMX is a special case because its contents.main MIME types is PPTX
        if ($fileType eq 'PPTX' and $$et{FILE_EXT} and $$et{FILE_EXT} eq 'THMX') {
            $fileType = 'THMX';
        }
    } else {
        $et->VPrint(0, "Unrecognized MIME type: $mime\n");
        # get MIME type according to file extension
        $fileType = $$et{FILE_EXT};
        # default to 'DOCX' if this isn't a known OOXML extension
        $fileType = 'DOCX' unless $fileType and $isOOXML{$fileType};
    }
    $et->SetFileType($fileType);

    # must catch all Archive::Zip warnings
    local $SIG{'__WARN__'} = \&Image::ExifTool::ZIP::WarnProc;
    # extract meta information from all files in ZIP "docProps" directory
    my $docNum = 0;
    my @members = $zip->members();
    my $member;
    foreach $member (@members) {
        # get filename of this ZIP member
        my $file = $member->fileName();
        next unless defined $file;
        $et->VPrint(0, "File: $file\n");
        # set the document number and extract ZIP tags
        $$et{DOC_NUM} = ++$docNum;
        Image::ExifTool::ZIP::HandleMember($et, $member);
        # process only XML and JPEG/WMF thumbnail images in "docProps" directory
        next unless $file =~ m{^docProps/(.*\.xml|(thumbnail\.(jpe?g|wmf)))$}i;
        # get the file contents (CAREFUL! $buff MUST be local since we hand off a value ref)
        my ($buff, $status) = $zip->contents($member);
        $status and $et->Warn("Error extracting $file"), next;
        # extract docProps/thumbnail.(jpg|mwf) as PreviewImage|PreviewMWF
        if ($file =~ /\.(jpe?g|wmf)$/i) {
            my $tag = $file =~ /\.wmf$/i ? 'PreviewWMF' : 'PreviewImage';
            $et->FoundTag($tag, \$buff);
            next;
        }
        # process XML files (docProps/app.xml, docProps/core.xml, docProps/custom.xml)
        my %dirInfo = (
            DataPt => \$buff,
            DirLen => length $buff,
            DataLen => length $buff,
            XMPParseOpts => {
                FoundProc => \&FoundTag,
            },
        );
        $et->ProcessDirectory(\%dirInfo, $tagTablePtr);
        undef $buff;    # (free memory now)
    }
    delete $$et{DOC_NUM};
    return 1;
}

1;  # end

__END__

=head1 NAME

Image::ExifTool::OOXML - Read Office Open XML+ZIP files

=head1 SYNOPSIS

This module is used by Image::ExifTool

=head1 DESCRIPTION

This module contains definitions required by Image::ExifTool to extract meta
information from Office Open XML files.  This is the format of Word, Excel
and PowerPoint files written by Microsoft Office 2007 -- essentially ZIP
archives of XML files.

=head1 AUTHOR

Copyright 2003-2014, Phil Harvey (phil at owl.phy.queensu.ca)

This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

=head1 SEE ALSO

L<Image::ExifTool::TagNames/OOXML Tags>,
L<Image::ExifTool::TagNames/FlashPix Tags>,
L<Image::ExifTool(3pm)|Image::ExifTool>

=cut