1<?php
2require_once('ZoteroFeedReader.php');
3require_once('ZoteroParserException.php');
4
5class ImportZoteroFeedReader implements ZoteroFeedReader
6{
7	/**
8	 * @var ZoteroConfig
9	 */
10	private $config;
11
12	public function __construct(ZoteroConfig $config)
13	{
14		$this->config = $config;
15	}
16
17	function getFeed()
18	{
19		if (!function_exists('curl_init'))
20		{
21			throw new Exception("CURL functions are not available.");
22		}
23
24		$feed = $this->download($this->config->getUrlForEntries());
25		$dom = $this->getDocument($feed);
26
27		$xpath = $this->getXPath($feed);
28		$nextUrl = $this->getNextUrl($xpath);
29		while ($nextUrl != null)
30		{
31			$additionalFeed = $this->download($nextUrl);
32			$xpath = $this->getXPath($additionalFeed);
33			$this->addEntriesToMainFeed($dom, $xpath);
34			$xml = $dom->saveXML();
35			file_put_contents("ZoteroImport.xml", $xml);
36			$nextUrl = $this->getNextUrl($xpath);
37		}
38
39		$xml = $dom->saveXML();
40		return $xml;
41	}
42
43	private function download($url)
44	{
45        #return file_get_contents("ZoteroImport.xml");
46		echo "Downloading " . $url . "\n";
47		$ch = curl_init();
48		curl_setopt($ch, CURLOPT_URL, $url);
49		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
50		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
51		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
52		$download = curl_exec($ch);
53		curl_close($ch);
54		return $download;
55	}
56
57    private function getDocument($xml)
58    {
59		$dom = new DomDocument();
60        $dom->loadXml($xml);
61        return $dom;
62    }
63
64	private function getXPath($xml)
65	{
66		$dom = $this->getDocument($xml);
67		$xpath = $this->getXPathForDocument($dom);
68		return $xpath;
69	}
70
71	private function getXPathForDocument(DOMDocument $dom)
72    {
73		$xpath = new DomXPath($dom);
74		$xpath->registerNameSpace("atom", "http://www.w3.org/2005/Atom");
75		$xpath->registerNameSpace("zapi", "http://zotero.org/ns/api");
76		return $xpath;
77    }
78
79	private function getNextUrl(DOMXPath $xpath)
80	{
81		$next = $xpath->query("//atom:feed/atom:link[@rel='next']")->item(0);
82		if ($next != null)
83		{
84			return $next->getAttribute("href") . "&key=" . $this->config->getConfig("ZoteroAccess", "key");
85		}
86		return null;
87	}
88
89	private function addEntriesToMainFeed(DOMDocument $dom, DOMXPath $xpath)
90	{
91        $domXpath = $this->getXPathForDocument($dom);
92		$root = $xpath->query('/atom:feed')->item(0);
93
94		$r = $xpath->query('//atom:feed/atom:entry');
95		foreach ($r as $node)
96		{
97			$newNode = $dom->importNode($node, true);
98			$dom->documentElement->appendChild($newNode);
99		}
100	}
101}
102?>
103