Compile latex from php: "Error: Invalid XRef stream header" - php

I have been trying to compile latex from php. I got the help from this tutorial. However, I keep getting this error.
Error: Invalid XRef stream header Error: Invalid XRef stream header pdf.worker.js:232:5
XRef_readXRef#resource://pdf.js/build/pdf.worker.js:3708:13
XRef_parse#resource://pdf.js/build/pdf.worker.js:3296:23
PDFDocument_setup#resource://pdf.js/build/pdf.worker.js:2469:7
PDFDocument_parse#resource://pdf.js/build/pdf.worker.js:2350:7
ensureHelper#resource://pdf.js/build/pdf.worker.js:1971:22
NetworkPdfManager_ensure/<#resource://pdf.js/build/pdf.worker.js:1985:7
NetworkPdfManager_ensure#resource://pdf.js/build/pdf.worker.js:1965:1
BasePdfManager_ensureDoc#resource://pdf.js/build/pdf.worker.js:1832:14
loadDocument/
Note: I have installed texlive in ubuntu so I can use pdftex.
xelatex is also installed.
Web server content:
small latex file contained "latex_template.php" and the
index.php contains the following php script.
ob_start();
include 'latex_template.php';
$outputData .=ob_get_contents();
ob_end_clean();
$texFile = tempnam(sys_get_temp_dir(), 'test');
$base = basename($texFile);
rename($texFile, $texFile.".tex");
$texFile .= ".tex";
file_put_contents($texFile, $outputData);
chdir(dirname(realpath($texFile)));
$console = shell_exec("xelatex {$base}" );
//$console = system("xelatex {$base}" );
header('Content-Type: application/pdf');
$pdf = dirname(realpath($console)).DIRECTORY_SEPARATOR.$base.".pdf";
readfile($pdf);
Note: Manual execution xelatex: log file:

Related

Class php_com_dotnet is missing in php

So I am using the call php_com_dotnet in my code:
$word = new COM("word.application");
// Hide MS Word application window
$word->Visible = 0;
//Create new document
$word->Documents->Add();
// Define page margins
$word->Selection->PageSetup->LeftMargin = '2';
$word->Selection->PageSetup->RightMargin = '2';
// Define font settings
$word->Selection->Font->Name = 'Arial';
$word->Selection->Font->Size = 10;
// Add text
$word->Selection->TypeText("TEXT!");
// Save document
$filename = tempnam(sys_get_temp_dir(), "word");
$word->Documents[1]->SaveAs($filename);
// Close and quit
$word->quit();
unset($word);
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=document_name.doc");
// Send file to browser
readfile($filename);
unlink($filename);
and I got his error:
Fatal error: Uncaught Error: Class 'COM' not found in /var/www/clients/client1/web1/web/nordin/save.php:6 Stack trace: #0 {main} thrown in /var/www/clients/client1/web1/web/nordin/save.php on line 6
so I looked around I added this to my php.ini file:
[COM_DOT_NET]
;extension=php_com_dotnet.dll
enable_dl = On
; extension_dir = "ext"
and it still doesn't work, what am I doing wrong? please help!
EDIT
my files are on a sftp server and I get error's like this:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
The semi-colon before the extension is a comment and means that extension is not enabled. To enable it you must remove that semi-colon:
;extension=php_com_dotnet.dll
becomes
extension=php_com_dotnet.dll
You may need to restart IIS after making this change.

Error when extracting xml file from compresed zip file created by PHP web service

I have created web service (client) in PHP (which uses SOAP protocol) that downloads list of ID's for users that want receive messages.
Now they've changed system (on server side) of delivering list of ID's. They have split xml list of more than 200000 ID's in 7 files and encoded them in base64 and compressed in zip file. I have managed to download every file via my PHP client, decode them from base64, then I have created UTF-8 zip file and wrote contents of message in it as you can see in part of my script here:
<?php
$obj = array('PinsCcIdsAsXmlZipBase64' => "", 'EmptyPage' => FALSE);
$PageNum=0;
while(!$obj['EmptyPage']){
$obj=Send_SOAP_mssg($TipPoruke,$SERVICE_TEST,$SOAP_cert,$NAMESPACE_URI,$cert_password,$ServiceId,$PageNum,$obj);
$zip_file=$OIB_path . 'PinListOfUsersThatDontHavePersonalization' . $PageNum . '.zip';
$f=fopen($zip_file,"wb")or die("Unable to open file!");
# Now UTF-8 - Add byte order mark
fwrite($f, pack("CCC",0xef,0xbb,0xbf));
fwrite($f,$obj['PinsCcIdsAsXmlZipBase64']);
fclose($f);
$zip = new ZipArchive;
$res = $zip->open($zip_file);
if ($res === TRUE) {
$zip->extractTo("C:\\xampp\\htdocs\\NIAS\\OIB\\");
$zip->close();
echo 'Success!';
} else {
echo 'ERROR! ' . $res ;
}
$PageNum++;
}
function Send_SOAP_mssg($TipPoruke,$SERVICE_TEST,$SOAP_cert,$NAMESPACE_URI,$cert_password,$ServiceId,$PageNum,$obj){
$client->__getLastRequest();
$xml=$client->__getLastResponse();
$doc = new DOMDocument();
$doc->loadXML( $xml );
$SOAPRequest = $doc->getElementsByTagName( "EmptyResultSet" );
if ($SOAPRequest->length!=0){
$obj['EmptyPage'] = TRUE;
return $obj;
}
else{
$SOAPRequest = $doc->getElementsByTagName( "PinsCcIdsAsXmlZipBase64" );
$obj['PinsCcIdsAsXmlZipBase64'] .= base64_decode($SOAPRequest->item(0)->nodeValue);
$obj['EmptyPage'] = FALSE;
return $obj;
}
}
?>
Problem occurs when I try to extract content of zip files. I got error 19 (Not a zip archive) as a result of this function
$res=$zip->open($zip_file);.
Same goes for manually extracting file
except extracting it with 7-zip, then I don't have errors.
In this code:
$obj['PinsCcIdsAsXmlZipBase64'] .= base64_decode($SOAPRequest->item(0)->nodeValue);
// ...
# Now UTF-8 - Add byte order mark
fwrite($f, pack("CCC",0xef,0xbb,0xbf));
fwrite($f,$obj['PinsCcIdsAsXmlZipBase64']);
base64_decode gives you a binary result, this zip content. The Now UTF-8 comment is false: you have a binary string, the actual zip file. You do not need to add the BOM:
$ php -a
Interactive shell
php > $content = base64_decode("UEsDBAoAAAAAADiaeEkAAAAAAAAAAAAAAAAFABwAYS50eHRVVAkAA8suN1jLLjdYdXgLAAEE6AMAAAToAwAAUEsBAh4DCgAAAAAAOJp4SQAAAAAAAAAAAAAAAAUAGAAAAAAAAAAAAKSBAAAAAGEudHh0VVQFAAPLLjdYdXgLAAEE6AMAAAToAwAAUEsFBgAAAAABAAEASwAAAD8AAAAAAA==");
php > $f=fopen("a.zip","wb");
php > fwrite($f,$content);
php > fclose($f);
That gives me a correct zip file.
A zip file uses offsets to find its internal structures. If you prepend bytes, these offsets are now wrong: you have a corrupted zip file. 7zip tries (and succeeds) to find the correct value but ZipArchive and Windows Compressed Folders don't seem to do that.

how to test if curl is available in PHP without errors

I am trying to detect if curl is installed using PHP in a script run from the command line. I tried the following:
if(#function_exists('curl_version')){
...
}
and
error_reporting(E_ERROR);
ini_set('display_errors', '0');
if(is_callable('curl_init')){
...
}
but in both cases I get this message:
PHP Warning: PHP Startup: Unable to load dynamic library '/usr/local/lib/php/extensions/no-debug-zts-20121212/curl.so' - /usr/local/lib/php/extensions/no-debug-zts-20121212/curl.so: cannot open shared object file: No such file or directory in Unknown on line 0
I would prefer to hide the error message, but it appears that the # and the error_reporting don't work. Is there a different way to suppress this message?
you could check your installed extionsions
$needed_extensions = array('curl', '... other extionsions to check');
$missing_extensions = array();
foreach ($needed_extensions as $needed_extension) {
if (!extension_loaded($needed_extension)) {
$missing_extensions[] = $needed_extension;
}
}
if (count($missing_extensions) > 0) {
echo 'This software needs the following extensions, please install/enable them: ' . implode(', ', $missing_extensions) . PHP_EOL;
exit(1);
}
'

How do I include PHP required libs in an AWS EMR streaming cluster

I've created a PHP project that converts JSON format into AVRO format.
The original project requires PHP libs that I'm not sure how to add on EMR.
This is the stderr log received by EMR:
PHP Warning: require_once(vendor/autoload.php): failed to open stream: No such file or directory in /mnt/var/lib/hadoop/tmp/nm-local-dir/usercache/hadoop/filecache/12/convert-json-to-avro.php on line 3
PHP Fatal error: require_once(): Failed opening required 'vendor/autoload.php' (include_path='.:/usr/share/pear:/usr/share/php') in /mnt/var/lib/hadoop/tmp/nm-local- dir/usercache/hadoop/filecache/12/convert-json-to-avro.php on line 3
log4j:WARN No appenders could be found for logger (amazon.emr.metrics.MetricsUtil).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
And here is the main code for the mapper:
#!/usr/bin/php
<?php
require_once 'vendor/autoload.php';
error_reporting(E_ALL);
ini_set('display_errors', 1);
$outputFile = __DIR__ . '/test_avro_out.avr';
$avroJsonSchema = file_get_contents(__DIR__ . '/HttpRequestEvent.avsc');
// Open $file_name for writing, using the given writer's schema
$avroWriter = AvroDataIO::open_file($outputFile, 'w', $avroJsonSchema);
$counter = 1;
while (($buf = fgets(STDIN)) !== false) {
try {
//replace ,null: with ,"null": to prevent map keys which are not strings.
$original = array("null:","userIp");
$replaceWith = array("\"null\":", "userIP");
$data = json_decode(str_replace($original, $replaceWith, $buf), true);
//print_r($buf);
if ($data === false || $data == null ) {
throw new InvalidArgumentException("Unable to parse JSON line");
}
$mapped = map_request_event($data);
var_dump($mapped);
//$avroWriter->append($mapped);
//echo json_encode($mapped), "\n";
} catch (Exception $ex) {
fprintf(STDERR, "Caught exception: %s\n", $ex->getMessage());
fprintf(STDERR, "Line num: %s\n",$counter);
fprintf(STDERR, "buf: %s\n", $buf);
}
$counter++;
}
$avroWriter->close();
Notice I'm using the require_once 'vendor/autoload.php'; which states that autoload.php is under the folder vendor.
What is the right way to load the vendor folder into the EMR cluster (there are needed files there)?
Should the require_once path change?
Thanks.
Following Guy's comment I've used a bash script similar to the one you can find here.
I've changed the require_once 'vendor/autoload.php' line in the code to point to the location where i dropped my files. (/home/hadoop/contents worked perfect).
lastly I've added an EMR bootstrap custom step where you can add the bash script so it can run before the PHP streaming step.

PHP Application Not Working Cant Write PDF File

I'm working on http://usborrow.com. The site used to be able to output the data to a PDF, however I am now getting the following error:
Error: [2] /home/usborrow/public_html/gfe.php on line 218
fopen(docs/30b583784503f7dc61999d234c67e204.pdf) [function.fopen]: failed to open stream:
No such file or directory
The script around line 218 is as follows:
// Create the pdf
$pdfmaker = new pdftk_php();
$pdfmaker->make_pdf($fdf_data_strings, $fdf_data_names, $fields_hidden, $fields_readonly, $pdf_original, $pdf_filename);
// Create the attachment and params
$fileatt = '/'.$pdf_filename;
$fileatttype = "application/pdf";
$fileattname = $offer->hashval.'.pdf';
$file = fopen($fileatt, 'rb');
$data = fread($file, filesize($fileatt));
$data = chunk_split(base64_encode($data));
fclose($file);
$random_hash = md5(date('r', time()));
I've tried changing the permissions on the Docs folder, however it's still not working. Any support would be greatly appreciated.
Maybe its not for the kind of read .. its for the path
try this before the fopen:
if (!is_dir("docs") {
mkdir("docs");
}
Not sure what file mode rb is...but I think the one you're wanting is r+.

Categories