<?php
/*
	Zoho Write
*/
class custom_zoho {
	function init() {
		
		//Set here your Zoho API key:
		$this->APIKey = "0706fa28460d4cacc49928f5a2714301";
		$this->skey = "f1171d4e0b8faf38502b9d1da0c5818a";
		
		$this->writerExtensions = array("doc", "docx", "html", "sxw", "rtf", "txt", "odt");
		$this->sheetExtensions = array("xls", "xlsx", "sxc", "csv", "ods", "tsv");
		$this->showExtensions = array("ppt", "pps", "odp", "sxi", "ppts", "ppsx");
		
		$this->writerURL = "https://exportwriter.zoho.com/remotedoc.im";
		$this->sheetURL = "https://sheet.zoho.com/remotedoc.im";
		$this->showURL = "https://show.zoho.com/remotedoc.im";
		
		global $locale;
		$this->localeSection = "Custom Actions: Zoho";
		$this->JSconfig = array(
			"title" => $locale->get("Zoho Editor", $this->localeSection),
			"iconCls" => 'fa fa-fw fa-file-o',
			"extensions" => array_merge($this->writerExtensions, $this->sheetExtensions, $this->showExtensions),
			"popup" => true,
			"requiredUserPerms" => array("download", 'upload'),
			"createNew" => array(
				"title" => $locale->get("Document with Zoho", $this->localeSection),
				"options" => array(
					array(
						"fileName" => "New Document.odt",
						"title" => $locale->get("Word Document", $this->localeSection),
						"iconCls" => 'fa fa-fw fa-file-word-o'
					),
					array(
						"fileName" => "New Spreadsheet.ods",
						"title" => $locale->get("Spreadsheet", $this->localeSection),
						"iconCls" => 'fa fa-fw fa-file-excel-o'
					),
					array(
						"fileName" => "New Presentation.odp",
						"title" =>  $locale->get("Presentation", $this->localeSection),
						"iconCls" => 'fa fa-fw fa-file-powerpoint-o'
					)
				)
			)
		);
		$this->outputName = "content";
	}
	function run() {
		global $fm, $config, $fileman, $users;
		$fileman->checkPerms("download");
		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();
		}
		$weblinkInfo = $this->weblinks->createForService($this->data['filePath'], false, $fm->dirname($this->data['relativePath']));
		if (!$weblinkInfo) {
			echo "Failed to setup weblink";
			exit();
		}
		if ($users->userPerms->currentUser['upload']) {
			$this->data['saveURL'] = $this->weblinks->getSaveURL($weblinkInfo['id_rnd'], false, "zoho");
		} else {
			$this->data['saveURL'] = "";
		}
		$extension = $fm->getExtension($this->data['fileName']);
		
		if (in_array($extension, $this->writerExtensions)) {
			$url = $this->writerURL."?apikey=".$this->APIKey."&output=url";
		} else if (in_array($extension, $this->showExtensions)) {
			$url = $this->showURL."?apikey=".$this->APIKey."&output=url";
		} else {
			$url = $this->sheetURL."?apikey=".$this->APIKey."&output=url";
		}
		
		$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(
			"saveurl" => $this->data['saveURL'],
			"filename" => $this->data['fileName'],
			"format" => $extension,
			"id" => uniqid(rand()),
			"skey" => $this->skey,
		    "content" => "@".$this->data['filePath'],
			"mode" => "normaledit"
		);
		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 = $this->parseZohoReply($response);
		
		if ($rs['RESULT'] != "FALSE") {
			global $log;
			$log->add(false, "preview", array(
				"relative_path" => gluePath($this->data['relativePath'], $this->data['fileName']),
				"full_path" => $this->data['filePath'],
				"method" => "Zoho"
			));
			header("Location: ".$rs['URL']."");
			exit();
		} else {
			echo "<strong>Zoho:</strong>";
			echo "<div style=\"margin:5px;border:1px solid silver;padding:5px;overflow:auto;\"><pre>";
			echo $response;
			if (strstr($rs['warning'], "unable to import content")) {
				echo "\r\n\r\nZoho.com service does not support this type of documents or was not able to access this web server.";
			} else {
				echo $response;
			}
			echo "</pre></div>";
		}
	}
	function createBlankFile() {
		global $myfiles, $users, $locale, $fm;
		if (!$users->userPerms->currentUser['upload']) {exit();}
		$rs = $myfiles->newFile($fm->dirname($this->data['relativePath']), $this->data['fileName'], false, "");
		if ($rs) {
			jsonOutput(array("rs" => true, 'path' => $this->data['relativePath'], "filename" => $this->data['fileName'], "msg" => $locale->get("Blank file created successfully", $this->localeSection)));
		} else {
			jsonOutput(array("rs" => false, "msg" => $myfiles->error['msg']));
		}
	}
	function getNewFileContents() {
		if ($_FILES[$this->outputName]['tmp_name']) {
			$contents = file_get_contents($_FILES[$this->outputName]['tmp_name']);
		}
		return $contents;
	}
	function parseZohoReply($reply) {
		$lines = explode("\n", $reply);
		$rs = array();
		foreach ($lines as $line) {
			$line = trim($line);
			$p = strpos($line, "=");
			$key = substr($line, 0, $p);
			$val = substr($line, $p+1);
			if (strlen($key) > 0) {
				$rs[$key] = $val;
			}
		}
		return $rs;
	}
}