<?php
/*
	Annotate with Crocodoc..
*/
class custom_crocodoc{
	function init() {
		global $locale;
		$this->APIToken = "KRkScndF3oQDmWsIHL5g";
		$this->extensions = array("pdf");
		$this->APIURL = "https://crocodoc.com/api/v1";
		$this->JSconfig = array(
			"title" => $locale->get("Crocodoc", 'Custom Actions: Crocodoc'),
			"iconCls" => 'fa fa-fw fa-cloud',
			"extensions" => $this->extensions,
			"popup" => true,
			"requiredUserPerms" => array("download")
		);
		$this->outputName = "content";
	}
	function run() {
		if (!function_exists("curl_init")) {
			echo "This feature requires the <a href=\"http://www.php.net/manual/en/curl.installation.php\" target=\"_blank\">PHP cURL</a> extension. Please contact the server administrator about enabling it.";
			exit();
		}
		
		$url = $this->APIURL."/document/upload";
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_VERBOSE, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, true);
		
		$post = array(
			"async" => 1,
			"private" => 1,
			"token" => $this->APIToken,
		    "file" => "@".$this->data['filePath']
		);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
		$response = curl_exec($ch);
		curl_close($ch);
		
		$rs = json_decode($response);
		
		if (!$rs->error) {
			$url = $this->APIURL."/session/get?uuid=".urlencode($rs->uuid)."&token=".urlencode($this->APIToken);
			
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_VERBOSE, 1);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_POST, true);
			global $auth;
			$post = array(
				"name" => $auth->currentUserInfo['name'],
				"token" => $this->APIToken
			);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
			$response = curl_exec($ch);
			curl_close($ch);
			
			$rs = json_decode($response);
			
			if ($rs->sessionId) {
				global $log;
				$log->add(false, "preview", array(
					"relative_path" => $this->data['relativePath'],
					"full_path" => $this->data['filePath'],
					"method" => "Corocodoc"
				));
				
				header("Location: https://crocodoc.com/view/?sessionId=".urlencode($rs->sessionId));
				exit();
			} else {
				echo "Failed to create Crocodoc session: ".$rs->error;
			}
		} else {
			echo "<strong>Crocodoc.com:</strong>";
			echo "<div style=\"margin:5px;border:1px solid silver;padding:5px;overflow:auto;\"><pre>";
			echo $rs->error;
			echo "</pre></div>";
		}
	}
}