<?php
/**
 * XMP Reader - Read XMP data
 *
 * Zoph is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Zoph is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with Zoph; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @author Jeroen Roos
 * @package Zoph
 */

namespace xmp;

use file;
use XMLReader;
use log;

/**
 * @author Jeroen Roos
 * @package Zoph
 */
class reader  {

    /** @var array names of XMP/rdf containers */
    private static $containers = array("rdf:Seq", "rdf:Bag", "rdf:Alt");
    /** @var array names of XMP/rdf container elements */
    private static $containerElements = array("rdf:li");
    /** @var array xmp data */
    private $xmpdata = array();
    /** @var array file data - file contents */
    private $XMPs = array();

    /** @param array Extensions to try for XMP Sidecar files */
    private $XMPext=array("xmp", "XMP", "xml", "XML");


    /**
     * Create new xmp/reader object
     * @param file file to read
     */
    public function __construct(file $file) {
        $this->file = $file;
    }

    /**
     * Read XMP from sidecar files
     */
    public function getXMPfromSidecar() {
        log::msg("Loading XMP from sidecar files", log::NOTIFY, log::IMPORT);
        foreach ($this->XMPext as $ext) {
            foreach (array($this->file->getName(), $this->file->getNameNoExt()) as $name) {
                $filename = $this->file->getPath() . "/" . $name . "." . $ext;
                log::msg("Trying " . $filename, log::DEBUG, log::IMPORT);
                if (file_exists($filename)) {
                    log::msg("Found " . $filename, log::DEBUG, log::IMPORT);
                    $sidecar = new file($filename);
                    $xmp = new self($sidecar);
                    return $xmp->getXMP();
                }
            }
        }
        log::msg("No sidecar file found", log::NOTIFY, log::IMPORT);
        return array();

    }

    /**
     * Read XMP from file
     */
    public function getXMP() {
        $this->file->getMime();
        switch ($this->file->type) {
            case "image":
                $this->getXMPfromJPEG();
                break;
            case "xmp":
                $this->getXMPfromXML();
                break;
            default:
                throw new \Exception("Unknown filetype " . $this->file->type);
        }
        $this->readXMPs();

        $return = array();
        foreach ($this->xmpdata as $xmp) {
            $return[] = new data($xmp);
        }
        return $return;
    }

    /**
     * Read XMP-xml from an XML-file
     */
    private function getXMPfromXML() {
        $this->XMPs=array(file_get_contents($this->file));
    }

    private function readXMPs() {
        foreach ($this->XMPs as $xmp) {
            $this->xmpdata[]=$this->readXMP($xmp);
        }
    }

    /**
     * Decode XMP data from XML
     * @param string XML
     * @return array XMPdata
     */
    public function readXMP($xmp) {
        $xml = new XMLReader();
        $xml->XML($xmp);
        return $this->decodeXML($xml);
    }

    /**
     * Read XMP-xml from a JPEG
     * Read JPG in chunks of 1024 bytes to keep memory usage low.
     */
    private function getXMPfromJPEG() {
        $fp = fopen($this->file, "rb");
        $buffer = "";
        $open = false;

        while (($data = fread($fp, 1024)) !== false) {
            if ($data === "") {
                break;
            }
            $buffer .= $data;
            if (!$open) {
                $openpos =strpos($buffer, "<x:xmpmeta");
                if ($openpos !== false) {
                    $open = true;
                } else {
                    // keep 12 bytes of buffer, in case the XMP is right on the edge
                    $buffer = substr($buffer, strlen($buffer) - 12);
                }
            } else {
                $closepos =strpos($buffer, "</x:xmpmeta>");
                if ($closepos !== false) {
                    $this->XMPs[] = substr($buffer, $openpos, ($closepos - $openpos) + 12);
                    $open = false;
                    $buffer = substr($buffer, $closepos + 11);
                }
            }
        }
    }

    private function decodeXML(XMLReader $xml) {
        $node=array();
        while ($xml->read()) {
            if ($xml->nodeType==XMLReader::ELEMENT) {
                $nodename = $xml->name;

                if (in_array($nodename, self::$containers)) {
                    $container = $nodename;
                    $containerElement = false;
                } else if (in_array($nodename, self::$containerElements)) {
                    $container = false;
                    $containerElement = true;
                } else {
                    $container = false;
                    $containerElement = false;
                }

                $empty=$xml->isEmptyElement;
                if ($xml->hasAttributes) {
                    $attr=array();
                    $xml->moveToFirstAttribute();

                    do {
                        $attr[$xml->name] = $xml->value;
                    } while ($xml->moveToNextAttribute());

                    if (!$empty) {
                        $data=array_merge($attr, (array) $this->decodeXML($xml));
                    } else {
                        $data=$attr;
                    }
                } else if ($xml->hasValue) {
                    $data = $xml->value;
                } else {
                    $data=$this->decodeXML($xml);
                }
                if ($container) {
                    $node = $data;
                } else if ($containerElement) {
                    $node[] =$data;
                } else {
                    if (!is_array($node)) {
                        $node = array($node);
                    }
                    $node[$nodename] = $data;
                }

            } else if ($xml->nodeType==XMLReader::TEXT) {
                $node = $xml->value;
            } else if ($xml->nodeType==XMLReader::END_ELEMENT) {
                break;
            } else if (($xml->nodeType != XMLReader::WHITESPACE) &&
                       ($xml->nodeType != XMLReader::SIGNIFICANT_WHITESPACE) &&
                       ($xml->nodeType != XMLReader::PI)) {
                $node[] = $xml->value;
            }
        }
        return $node;
    }
}
?>
