function process($currentXml) { $currentDirectory = dirname($this->docvertTransformDirectory); $documentType = detectDocumentType($currentXml); switch ($documentType) { case 'OpenDocument1.0': //text-colon-section text-colon-style-name="Sect2" text-colon-name="Section2"> $styles = $this->getStyles(); $currentXml = preg_replace('/<office:document-content[^>]*?>/s', "\$0" . $styles, $currentXml); //displayXmlString($currentXml); $currentXml = xsltTransform($currentXml, $this->docvertTransformDirectory . 'fix-opendocument-content.xsl'); //displayXmlString($currentXml); $currentXml = xsltTransform($currentXml, $this->docvertTransformDirectory . 'fix-opendocument-content-stage2.xsl'); //displayXmlString($currentXml); $currentXml = xsltTransform($currentXml, $currentDirectory . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'sun-xsl' . DIRECTORY_SEPARATOR . 'opendocument-content-to-docbook.xsl'); //displayXmlString($this->docvertTransformDirectory.'opendocument-content-to-docbook.xsl'); //displayXmlString($currentXml); $metaData = $this->getMetaData(); $currentXml = preg_replace('/<db:book[^>]*?>/s', "\$0" . $metaData, $currentXml); //displayXmlString($currentXml); $currentXml = xsltTransform($currentXml, $this->docvertTransformDirectory . 'fix-docbook.xsl'); //displayXmlString($currentXml); break; case 'OpenOffice1.x': webServiceError('&error-process-transformopendocumenttodocbook-openofficefile;'); break; default: webServiceError('&error-process-transformopendocumenttodocbook-unsupported-file; [' . revealXml($currentXml) . ']', 500, array('documentType' => $documentType)); break; } return $currentXml; }
function postToBloggerApiBlog($host, $port, $xmlRpcPath, $username, $password, $title, $body, $authorName, $authorEmail, $draft, $proxyUsername = null, $proxyPassword = null) { $postData = "<entry xmlns='http://www.w3.org/2005/Atom'>\n"; $postData .= "\t<title type='text'>" . revealXml($title) . "</title>\n"; if ($draft) { $postData .= "\t<app:control xmlns:app='http://purl.org/atom/app#'>\n"; $postData .= "\t\t<app:draft>yes</app:draft>\n"; $postData .= "\t</app:control>\n"; } $postData .= "\t<content type='xhtml'>\n"; $postData .= $body; //must be valid XML $postData .= "\t</content>\n"; $postData .= "\t<author>\n"; $postData .= "\t\t<name>" . revealXml($authorName) . "</name>\n"; $postData .= "\t\t<email>" . revealXml($authorEmail) . "</email>\n"; $postData .= "\t</author>\n"; $postData .= "</entry>"; $textArray['xmlrpc'] = $postData; //TODO: how to do submit this to the xmlrpc interface? return pullpage('POST', $host, $port, $xmlRpcPath, $username, $password, $proxyUsername, $proxyPassword, $textArray = null, $binaryArray = null, $debug = false, $timeOutInSeconds = null); }
} $pipeline = $unescapedPosts["pipeline"]; if (!preg_match($badCharactersPattern, $pipeline)) { webServiceError('pipeline contains bad characters. Was "' . revealXml($pipeline) . '"'); } $autopipeline = $unescapedPosts["autopipeline"]; if (!preg_match($badCharactersPattern, $autopipeline)) { webServiceError('autopipeline contains bad characters. Was "' . revealXml($autopipeline) . '"'); } $allhtml = '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><body>' . $allhtml . '</body></html>'; $transformDirectory = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'core' . DIRECTORY_SEPARATOR . 'transform' . DIRECTORY_SEPARATOR; $htmlPagesXsltPath = $transformDirectory . 'htmlpages-to-html.xsl'; $allhtml = characterEntityToNCR($allhtml); $html = xsltTransform($allhtml, $htmlPagesXsltPath); if (!$html) { webServiceError("Unable to rebuild document, either because I was given invalid XML or there was a programming error.<hr />Document was:<blockquote>" . str_replace("\n", "<br />", str_replace(" ", ' ', revealXml($allhtml))) . "</blockquote>"); } //displayXmlString($html); $docbookBodyXsltPath = $transformDirectory . 'html-to-docbook-body.xsl'; $docbookBody = xsltTransform($html, $docbookBodyXsltPath); $docbookBody = removeXmlDeclaration($docbookBody); $docbookBody = preg_replace("/<docvert-remove-me[^>]*?>/", '', $docbookBody); $docbookBody = preg_replace("/<\\/docvert-remove-me[^>]*?>/", '', $docbookBody); //displayXmlString($docbookBody); //displayXmlString(file_get_contents($docbookBodyXsltPath)); $allDocumentsPreviewDirectory = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'writable' . DIRECTORY_SEPARATOR . $documentPathParts[0] . DIRECTORY_SEPARATOR; $previewDirectory = $allDocumentsPreviewDirectory . $documentPathParts[1] . DIRECTORY_SEPARATOR; $unitTestResults = $previewDirectory . 'test.html'; if (file_exists($unitTestResults)) { silentlyUnlink($unitTestResults); }
foreach ($filesToDisplay as $fileToDisplay) { $possibleFile = getFirstByPattern($pathToUse . $fileToDisplay); if ($possibleFile) { $chosenFile = $possibleFile; break; } } if (!$chosenFile) { $filesToDisplayAsString = null; foreach ($filesToDisplay as $fileToDisplay) { $filesToDisplayAsString .= '"' . $fileToDisplay . '", '; } $filesToDisplayAsString = trim($filesToDisplayAsString); $filesToDisplayAsString = substr($filesToDisplayAsString, 0, strlen($filesToDisplayAsString) - 1); $filesInPreviewDirectory = glob($pathToUse . '*'); die('Docvert or pipeline error: Unable to determine the file to preview. I searched for the filename patterns ' . $filesToDisplayAsString . ' were tested but do not exist. Was given pathToUse of <tt>"' . $pathToUse . '"</tt> which contained <pre>' . revealXml(print_r($filesInPreviewDirectory, true)) . '</pre>'); } $chosenFile = str_replace('\\', '/', $chosenFile); if ($thereIsAPreview) { print '<html>'; print '<head>'; print '<frameset cols="80%, *" border="10" bordercolor="#333333" frameborder="15">'; print '<frame src="' . $chosenFile . '" id="contentFrame"/>'; print '<frame src ="' . dirname($chosenFile) . '/test.html"/>'; print '</frameset>'; print '</head>'; print '<body><noframes>Docvert requires a frames-compatible browser</noframes></body>'; print '</html>'; } else { print '<html>'; print '<head>';
function setupOpenOfficeOrgServer() { $operatingSystemFamily = getOperatingSystemFamily(); if (!$this->allowedAdminAccess || $operatingSystemFamily != 'Unix') { return; } $hideOpenOfficeOrgServerOption = getGlobalConfigItem('hideAdminOptionOpenOfficeOrgServer'); if ($hideOpenOfficeOrgServerOption == "true") { return; } $userMessage = null; $pidFile = '/tmp/openoffice.org-server.pid'; $output = ''; if (isset($_REQUEST['openofficeorg-server-on']) || isset($_REQUEST['openofficeorg-server-off'])) { $unixConfigPath = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'unix-specific' . DIRECTORY_SEPARATOR; $startStopBashScript = $unixConfigPath . 'openoffice.org-server-init.sh'; $startOrStop = null; if (isset($_REQUEST['openofficeorg-server-on'])) { if (file_exists($pidFile) && filesize($pidFile) > 0) { $userMessage = 'existing-pid'; } else { $startOrStop = 'start'; } } elseif (isset($_REQUEST['openofficeorg-server-off'])) { if (file_exists($pidFile) && filesize($pidFile) > 0) { $startOrStop = 'stop'; } else { $userMessage = 'no-existing-pid'; } } if ($startOrStop) { include_once dirname(__FILE__) . '/config.php'; $runAsUser = ''; $sudo = ''; $startTime = 8; $stopTime = 3; $customUser = getGlobalConfigItem('runExternalApplicationAsUser'); if ($customUser) { $runAsUser = $customUser; } $startStopScript = null; $superUserPreference = getSuperUserPreference(); if ($superUserPreference == 'sudo') { $startStopScript = $startStopBashScript; $sudo = 'sudo -u {runAsUser}'; } elseif ($superUserPreference == 'nothing') { $startStopScript = $startStopBashScript; $sudo = ''; } $commandTemplate = '{sudo} {startStopScript} {startOrStop} {runAsUser}'; $commandTemplate = str_replace('{sudo}', $sudo, $commandTemplate); $commandTemplate = str_replace('{startStopScript}', $startStopScript, $commandTemplate); $commandTemplate = str_replace('{startOrStop}', $startOrStop, $commandTemplate); $commandTemplate = str_replace('{runAsUser}', $runAsUser, $commandTemplate); $commandTemplate = trim($commandTemplate); $output = shellCommand($commandTemplate, 0); switch ($startOrStop) { // due to OOo delay in startup/shutdown we'll just twiddle our thumbs for a bit case 'start': sleep($startTime); break; case 'stop': sleep($stopTime); break; } if (isset($_REQUEST['openofficeorg-server-on']) || isset($_REQUEST['openofficeorg-server-off'])) { $output = '<blockquote><tt>' . revealXml($commandTemplate) . '</tt></blockquote><blockquote><tt>' . revealXml($output) . '</tt></blockquote>'; if (isset($_REQUEST['openofficeorg-server-on']) && !file_exists($pidFile)) { webServiceError('&error-unable-to-start-ooo-server; ' . $output . ' '); } elseif (isset($_REQUEST['openofficeorg-server-off']) && file_exists($pidFile)) { webServiceError('&error-unable-to-stop-ooo-server; ' . $output . ' '); } } } } if (!is_readable($pidFile)) { $response = $this->getThemeFragment('admin-setupopenofficeorg-server-button-unknown.htmlf'); } elseif (file_exists($pidFile) && filesize($pidFile) > 0) { $response = $this->getThemeFragment('admin-setupopenofficeorg-server-button-disabled.htmlf'); } else { $response = $this->getThemeFragment('admin-setupopenofficeorg-server-button-enabled.htmlf'); } //if($userMessage) // { // $response = $response.$this->getThemeFragment('error-setupopenofficeorg-server-'.$userMessage.'.htmlf'); // } if ($output) { $response = $response . '<p>Output:</p><pre style="padding:0px 0.5em;font-size:small;background:#cccccc">' . $output . '</pre>'; } return $response; }
function generateDocument($pages, $generatorPipeline) { if (preg_match('/.\\//s', $generatorPipeline)) { webServiceError('&error-disallowed-characters;'); } $userAgent = 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:bignumber) Docvert'; $httpContextOptions = array('http' => array('header' => 'User-Agent: ' . $userAgent)); $httpContext = stream_context_create($httpContextOptions); $docvertDir = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR; $docvertWritableDir = getWritableDirectory(); $disallowDocumentGeneration = getGlobalConfigItem('doNotAllowDocumentGeneration'); if ($disallowDocumentGeneration == 'true') { webServiceError('&document-generation-disabled;'); } $pageXml = '<c:document xmlns="http://www.w3.org/1999/xhtml" xmlns:c="container">' . "\n"; $pageTemplate = "\n\t" . '<c:page url="{{url}}" {{baseUrl}}>{{page}}</c:page>' . "\n"; $config = array('indent' => true, 'output-xhtml' => true, 'wrap' => 200); if (!class_exists('tidy')) { webServiceError('&tidy-is-not-installed;'); } $tidy = new tidy(); $baseTagPattern = "/<base[^>]*?href=([^>]*?)>/is"; foreach ($pages as $page) { if (trim($page) != '' && (stringStartsWith($page, 'http://') || stringStartsWith($page, 'https://'))) { $pageHtml = file_get_contents($page, null, $httpContext); $tidy->parseString($pageHtml, $config, 'utf8'); $tidy->cleanRepair(); $thisPage = str_replace('{{url}}', $page, $pageTemplate); $baseUrl = ''; //supporting that ugly old hack of <base> preg_match($baseTagPattern, $pageHtml, $matches); if (count($matches) > 0) { $baseUrl = 'baseUrl="' . substr($matches[1], 1, -2) . '"'; } $thisPage = str_replace('{{baseUrl}}', $baseUrl, $thisPage); $tidiedPageContents = characterEntityToNCR(removeDoctype(removeXmlComments($tidy))); $styleTagPattern = "/<style.*?<\\/style>/is"; $tidiedPageContents = preg_replace($styleTagPattern, '', $tidiedPageContents); $scriptTagPattern = "/<script.*?<\\/script>/is"; $tidiedPageContents = preg_replace($scriptTagPattern, '', $tidiedPageContents); $questionMarkPattern = "/<\\?.*?\\?>/is"; //as strangely used on news.yahoo.com $tidiedPageContents = preg_replace($questionMarkPattern, '', $tidiedPageContents); $thisPage = str_replace('{{page}}', $tidiedPageContents, $thisPage); $pageXml .= $thisPage; } } $pageXml .= '</c:document>'; $temporaryDirectory = getTemporaryDirectory(); $pipelineDirectory = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'generator-pipeline' . DIRECTORY_SEPARATOR . $generatorPipeline . DIRECTORY_SEPARATOR; $pipelinePath = $pipelineDirectory . 'pipeline.xml'; if (!file_exists($pipelinePath)) { webServiceError('&generation-pipeline-not-found; ' . revealXml($pipelinePath)); } $pipelineString = file_get_contents($pipelinePath); $pipelineString = substr($pipelineString, strpos($pipelineString, '<pipeline>') + 10); $pipelineString = substr($pipelineString, 0, strpos($pipelineString, '</pipeline>')); $pipelineStages = xmlStringToArray($pipelineString); $pipelineSettings = array("pipeline" => $generatorPipeline, "autopipeline" => $generatorPipeline); processAPipelineLevel($pipelineStages, $pageXml, $pipelineDirectory, $temporaryDirectory, $temporaryDirectory, $pipelineSettings); $openDocumentPath = $temporaryDirectory . 'output.odt'; zipFiles($temporaryDirectory, $openDocumentPath); header('Content-disposition: attachment; filename=' . basename($openDocumentPath)); header('Content-type: application/vnd.oasis.opendocument.text'); readfile($openDocumentPath); }
function pullpage($method, $host, $port, $usepath, $username, $password, $proxyUsername, $proxyPassword, $textArray = null, $binaryArray = null, $debug = false, $timeOutInSeconds = null) { //Used as pullpage ("GET" || "POST", "localhost", "80", "/blah.php", $textArray['key'] = $value, $binaryArray['key'] = $value['type' || 'binary']); //TODO: use parse_url rather than asking for url components $output = null; if ($binaryArray && $method == 'GET') { die('Can\'t method=GET with binaries.'); } $userAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:bignumber) Docvert"; if ($timeOutInSeconds == null) { $timeOutInSeconds = 30; } $protocol = 'http'; if ($port == 443) { $protocol = 'https'; } $fp = fsockopen($host, $port, $errno, $errstr, $timeOutInSeconds); stream_set_blocking($fp, false); $response = null; if (!$fp) { return false; //webServiceError($errstr.' ('.$errno.') at host "'.$host.'", port "'.$port.'", <br>'."\n", 502); } stream_set_timeout($fp, $timeOutInSeconds); $request = null; $request['head'] = null; $request['body'] = null; switch ($method) { case 'GET': case 'POST': case 'PULL': case 'MKCOL': case 'PUT': $request['head'] .= httpLine($method . ' ' . $usepath . ' HTTP/1.1'); break; case 'HEAD': $request['head'] .= httpLine($method . ' ' . $protocol . '://' . $host . $usepath . ' HTTP/1.1'); break; default: webServiceError('&error-http-unknown-method;', 500, array('method' => $method)); } $request['head'] .= httpLine('User-Agent: ' . $userAgent); $request['head'] .= httpLine('Accept: */*'); $request['head'] .= httpLine('Host: ' . $host); // does this need ':'.$port $request['head'] .= httpLine('Keep-Alive: 300'); $request['head'] .= httpLine('Connection: keep-alive'); if ($username . $password) { $request['head'] .= httpLine('Authorization: Basic ' . base64_encode($username . ':' . $password)); } if ($proxyUsername . $proxyPassword) { $request['head'] .= httpLine('Proxy-Authorization: Basic ' . base64_encode($proxyUsername . ':' . $proxyPassword)); } if ($binaryArray && $method == "POST") { srand((double) microtime() * 1000000); $boundary = "---------------------------" . substr(md5(rand(0, 32000)), 0, 10); $request['body'] .= '--' . $boundary; $request['head'] .= httpLine('Content-type: multipart/form-data; boundary=' . $boundary); $arrayKeys = array_keys($binaryArray); $formItemCount = 0; foreach ($binaryArray as $key => $value) { $formItemCount++; $request['body'] .= "\r\n"; $request['body'] .= httpLine('Content-Disposition: form-data; name="' . $key . '"; filename="' . $value['name'] . '"'); $request['body'] .= httpLine('Content-Type: ' . $value['type']); $request['body'] .= httpLine('Content-Transfer-Encoding: binary'); $request['body'] .= "\r\n"; $request['body'] .= $value['binary']; $request['body'] .= "\r\n--" . $boundary; } $arrayKeys = array_keys($textArray); foreach ($textArray as $key => $value) { $request['body'] .= "\r\n"; $request['body'] .= httpLine('Content-Disposition: form-data; name="' . $key . '"'); $request['body'] .= "\r\n"; $request['body'] .= $value; $request['body'] .= "\r\n--" . $boundary; } $request['body'] .= "\r\n\r\n"; } if ($binaryArray && $method == "PUT") { if (count($binaryArray) != 1) { webServiceError("&error-http-put-multiple-files", 500, array('numberOfFiles' => count($binaryArray))); } $request['head'] .= httpLine('Content-type: application/octet-stream'); $request['body'] = $binaryArray[0]; } elseif ($textArray) { $request['head'] .= httpLine('Content-type: application/x-www-form-urlencoded'); $arrayKeys = array_keys($textArray); foreach ($textArray as $key => $value) { if ($request['body'] != null) { $request['body'] .= "&"; } $request['body'] .= $key . '=' . urlencode($value); } } $request['head'] .= httpLine('Content-length: ' . strlen($request['body'])); $request['head'] .= "\r\n"; $request['body'] .= "\r\n"; fputs($fp, $request['head'] . $request['body']); $divisionString = "\r\n\r\n"; switch ($method) { case 'MKCOL': case 'PUT': $exitAfterLoops = 0; while (stripos($output, "\n") === False) { $output .= fgets($fp, 8); $exitAfterLoops++; if ($exitAfterLoops > 30) { break; } } fclose($fp); $output = trim($output); $outputParts = explode(' ', $output); $httpCode = $outputParts[1]; $httpMessage = ''; for ($i = 2; $i < count($outputParts); $i++) { $httpMessage .= trim(' ' . $outputParts[$i]); } return $httpCode; break; //print $method.' = '.$httpCode.":".$httpMessage."<br />"; //print $method.' = '.$httpCode.":".$httpMessage."<br />"; case 'HEAD': while (stripos($output, $divisionString) === False && !feof($fp)) { $output .= fgets($fp, 8); } fclose($fp); return $output; break; default: if ($debug) { print "Started feof at " . date(DATE_RFC822) . '<br />'; } while (!feof($fp)) { $info = stream_get_meta_data($fp); if ($info['timed_out']) { break; } $output .= fgets($fp, 4096); } if ($debug) { print "Ended feof at " . date(DATE_RFC822) . '<br />'; } } fclose($fp); if ($output) { $divisionPosition = strpos($output, $divisionString); if (!$divisionPosition) { webServiceError("&error-http-segment;", 500, array('output' => revealXml($output))); } $httpHeader = substr($output, 0, $divisionPosition); $httpHeader = explode("\n", $httpHeader); $httpBody = substr($output, $divisionPosition + strlen($divisionString)); $response['head'] = $httpHeader; $response['body'] = $httpBody; } if ($debug) { print '<h1>Debug</h1>'; print '<p>Connection is ' . $method . ' to ' . $host . ':' . $port . $usepath . '. Scroll down to see request and response.</p>'; print '<h2>Request</h2>'; print '<div style="margin:0px 3%">'; print nl2br(textEncodingToHtmlEncoding($request['head'] . $request['body'])); print "</div>"; print '<h2>Response</h2>'; print '<h3>Head</h3>'; print '<div style="margin:0px 3%">'; if (is_array($response) && array_key_exists('head', $response)) { foreach ($response['head'] as $eachHeader) { print $eachHeader . "<br />"; } } else { print "No header in response."; } print "</div>"; print "<h3>Body</h3>"; print '<div style="margin:0px 3%">'; if (is_array($response) && array_key_exists('body', $response)) { print nl2br(textEncodingToHtmlEncoding($response['body'])); } else { print "No body in response."; } print "</div>"; die; } return $response; }