http://www.perlmonks.org?node_id=778663

forinti has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I've been using Perl and OLE to process Word docs. It all works well when the user sends me a valid file; my problem is that it also works when the user sends me rubbish! For instance, one script takes a docx and returns a PDF. If the user sends me a PDF, the script returns a PDF with the source of the original. So, my question is: is there a way to make Word give me some feedback about what it is opening?

Thanks!

Replies are listed 'Best First'.
Re: OLE and WORD docs
by dtr (Scribe) on Jul 09, 2009 at 20:21 UTC

    Probably not. I would suggest that you use one of the MIME Magic modules, such as File::MimeInfo::Magic, to get perl to tell you what type of document you have received. Then, if it is a word document (I believe the MIME type is application/msword), then you can continue with your script, otherwise chuck out an error message.

      Magic numbers do not solve the problem completely. Old versions of MS Word use a file format that is also used by other products. For example, old Crystal Reports files are often misidentified as MS Word files.

      But the OP gave a nice clue: *.docx -- that means a newer MS Word, stuffing XML into a ZIP file. So, if we talk ONLY about newer MS Word files in zipped XML format, the file can be testet easily: Try to open the file using Archive::ZIP (it is a ZIP file, after all). Look inside the archive, try to find an XML file with the name MS Word uses for the content, unpack that file from the archive. Use an XML parser to see if the file has one of the well-known type declarations for MS Word (or similar products, if you want to allow OpenOffice and friends). Should any of those steps fail, the input file is not a valid *.docx MS Word file.

      If also old MS Word files (*.doc) have to be processed, you need a second test routine that can properly detect the old MS Word binary dump formats. There are several, one for each version. Testing "magic numbers" works well most of the times, but you may have false positives (see above).

      Word can also read and write Rich Text Format files (*.rtf). If this format has to be processed, you need a third test. Again, "magic numbers" may work here. CPAN has some RTF readers, using them to test for a valid file should give less false positives.

      Alexander

      --
      Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)