PHP Laravel LibreOffice DOC to PDF not converting via browser run - php

I'm currently uploading a DOC or DOCX file via DropzoneJS and then convert it to PDF in the server using LibreOffice PHP exec. If I typed it manually in the server then it will convert but if I run it via browser then it is not converting. I'm trying to run the soffice without a sudo but the command run via browser is not working. How can I convert it via browser run?
Manual Command in Terminal:
/opt/libreoffice5.2/program/soffice --convert-to pdf
/var/www/html/my_system/public/msword.doc --outdir
/var/www/html/my_system/storage/app/quotations
Command ls -liah results for folders:
my_system, storage, app, quotations = drwxrwxrwx apache apache
My sudo visudo results (pasted lines with no comments in order):
Defaults requiretty
Defaults !visiblepw
Defaults always_set_home
www-data ALL=NOPASSWD:ALL
robert ALL=NOPASSWD:ALL
apache ALL=NOPASSWD:ALL
PHP File:
$command = '/opt/libreoffice5.2/program/soffice --convert-to pdf /var/www/html/my_system/public/msword.doc --outdir /var/www/html/my_system/storage/app/quotations';
if (!$return) {
echo "PDF Created Successfully";
} else {
echo 'PDF not created. Command = ' . $command . '=' . $return;
}
Thanks.

Found the correct answer via https://superuser.com/questions/627266/convert-file-to-pdf-using-libreoffice-under-user-apache-i-e-when-using-php
Quoting Correct Answer:
So, you need to i) give apache's user a home and ii) give it a
directory it has access to to write in. So, create a tmp directory in
the same folder where you store your webpage and then run the
following php code:
<?php
shell_exec('export HOME=/tmp && libreoffice --headless -convert-to pdf --outdir ./tmp /tmp/ayb/document_34.doc');
?>
I just tested and it works perfectly on my machine. Make sure your
./tmp has its permissions set to 777. Also, you may need to restart
apache if you play aroud with it too much. It stopped working for me
after a while when I made changes and I needed to restart it.

Related

CentOS Linux console command versus PHP exec(command)

I have a C program that I wrote called convert3to5, originally written for CentOS / Fedora 32bit system in early 2010. I am moving it to new CentOS 6.x 64bit system host.
From a CentOS Putty console I can run the convert3to5 command just fine; here is a sample of it running from my console:
[root#cloud convert3to5]# ls
CircleStar convert3to5 Convert3To5.txt test.tif
[root#cloud convert3to5]# ./convert3to5 /var/www/webadmin/data/www/mydomain.com/uploads/SV-DIS160217B.tif
TIFFReadDirectory: Warning, /var/www/webadmin/data/www/mydomain.com/uploads/SV-DIS160217B.tif: wrong data type 7 for "RichTIFFIPTC"; tag ignored. Image has an undefined fillorder - using default: MSB2LSB
The above is a normal completion of convert3to5 and I get a SV-DIS160217B.bmp that is placed in /var/www/webadmin/data/www/mydomain.com/uploads/ So running it from console works fine.
Question - I am attempting to run the same exact command from PHP using the exec(command, output, return) command as follows:
chdir($sv_path.$c3to5_path); //change our working directory to "/convert3to5" directory
$command = "./convert3to5 $targetFile 2>&1";
$result = exec($command, $output, $return);
// the output of the above command - is a .bmp file it will be placed in the same path as the input .tif file
I get the following $result:
ERROR: Unable to convert
/var/www/webadmin/data/www/mydomain.com/uploads/SV-DIS160217B.tif to 5
color BMP file: Open file Error: Tiff_3_to_BMP_5_.lut!
My convert3to5 does need to open Tiff_3_to_BMP_5_.lut
Why does it find Tiff_3_to_BMP_5_.lut when I run convert3to5 from a console prompt but not from PHP exec(...) in both cases my pwd shows that I am in
[root#cloud convert3to5]# pwd
/var/www/webadmin/data/www/mydomain.com/myView/convert3to5
I have also verified pwd is correct from my PHP script after the
chdir($sv_path.$c3to5_path);
Tiff_3_to_BMP_5_.lut is in CircleStar directory - the path to CircleStar is /var/www/webadmin/data/www/mydomain.com/myView/convert3to5/CircleStar
Summary: ./convert3to5 works while PHP exec('convert3to5 ..) does not appear to work.
Can anyone suggest the difference and how to fix and/or debug?
Thanks
You're running the console from the convert3to5 directory, and I suspect your old C program used a relative path to the .lut file, possible relative to the .tif?
What if in the console example you did
cd ../..
./path/to/convert3to5/convert3to5 /var/www/webadmin/data/www/mydomain.com/uploads/SV-DIS160217B.tif
Might be related to $targetFile. Print that and see if it's the full path.
Finally, run
/full/path/to/convert3to5 fullTargetPath
If that works, then as a workaround, if you just do exec('/full/path/to/convert3to5 $fullTargetPath, ..) it should behave like the console.
Per my above comment to wonton:
From the console I was running as root (so fully privileged). I supposed my PHP script will run as the "apache" user on the server?
Here was the problem I believe: I looked at the CircleStar directory privileges where the Tiff_3_to_BMP_5_.lut file exists. CircleStar had rw-r--r-- (0644) when running as root from console this allowed my convert3to5 program to find and open Tiff_3_to_BMP_5_.lut file just fine. However not the PHP exec(...) once I changed the privilege on CircleStar to rwxr-xr-x (0755) PHP exec(...) ran fine!
So ultimately it was a permission issue.

run exec in php for converting file using unoconv

I'm trying to convert HTML file into RTF file using unoconv in php.
From php I'm calling :
......
file_put_contents("/tmp/unoconv55b2862fea753.html", $content);
$command = "unoconv -f rtf -o /tmp/unoconv55b2862fea753.rtf /tmp/unoconv55b2862fea753.html";
exec($command, $output);
$converted = file_get_contents("/tmp/unoconv55b2862fea753.rtf");
the problem is, that file_put content will save .html, but unoconv for some reason doesn't save converted file into /tmp directory.
When I run that $command directly on server in console, converted file was created.
Do you have any idea where could be problem?
The problem could lie with PHP not having the right privileges for the tmp directory.
Try saving the converted file to the root of your site (or a subfolder within it) and see if it converts successfully.
When configuring unoconv on ubuntu server to be run under apache (www-data) user
This solution is based on:
https://github.com/dagwieers/unoconv/issues/87#issuecomment-16563550
and
https://github.com/dagwieers/unoconv/issues/87#issuecomment-32084464
Step-by-step guide
Follow these steps:
1. Create new file which will contain sudoers entry for user www-data:
sudo vi /etc/sudoers.d/www-data
2. Add following content to newly created file and save:
www-data ALL=NOPASSWD: /usr/bin/unoconv
3. In PHP exec() use "sudo unoconv"

php libreoffice shell_exec not working

I am trying to convert .docx file to .html using php shell_exec in CentOS 6.5
My php code:
$command = "libreoffice --headless -convert-to html resume.docx 2>&1";
$result = shell_exec($command);
echo $result;
When I run the index.php at http://localhost/converter/ it gives me:
javaldx: Could not find a Java Runtime Environment! Warning: failed to read path from javaldx /usr/lib64/libreoffice/program/soffice.bin X11 error: Can't open display: Set DISPLAY environment variable, use -display option or check permissions of your X-Server (See "man X" resp. "man xhost" for details)`
while in terminal it is working perfectly:
cd /var/www/html/converter/
libreoffice --healdess -convert-to html resume.docx
here it creates resume.html in my /var/www/html/converter/.
Hi i have the same problem, i want to convert PDF's from DOCS created with PHP, i'm using OpenSuse 12.3 with LibreOffice, tried many things, finally i detect that the error is in folder:
1.- First check that you don't have disabled shell_exec in php.ini, and open_basedir don't restrict your access folders.
2.- Run the command as a simple user in shell (terminal)
export HOME=/tmp && soffice --headless --convert-to pdf --outdir /srv/www/htdocs/ /srv/www/htdocs/Creecimientos/sic/app/webroot/usuarios/2/8_Pagare_CreePersonas.docx
3.- If it works, you only have to put the correct folders in your code, when i run this code in PHP, it show me a blank page, so i check the access_log of apache for any hint:
[Java framework] Error in function createSettingsDocument (elements.cxx).
javaldx failed!
Warning: failed to read path from javaldx
terminate called after throwing an instance of 'com::sun::star::uno::RuntimeException'
Note: my error was in using export HOME=/tmp, i checked that the folder in root system has 777 for tmp, but the problem was that apache don't acces to it, maybe search for a relative folder of the script, but after test many things i only put a folder with permissons for wwwrun HOME=/srv/www/htdocs/folder_with_777
This is my final code, that works..
<?php
function word2pdf()
{
echo "Procesando";
$result = shell_exec('export HOME=/srv/www/htdocs/Creecimientos/sic/ && soffice --headless --convert-to pdf --outdir /srv/www/htdocs/Creecimientos/sic/ /srv/www/htdocs/Creecimientos/sic/app/webroot/usuarios/2/8_Pagare_CreePersonas.docx');
echo $result;
}
word2pdf();
?>
In fact, it prints: convert srv/www/htdocs/Creecimientos/sic/app/webroot/usuarios/2/8_Pagare_CreePersonas.docx -> /srv/www/htdocs/Creecimientos/sic//8_Pagare_CreePersonas.pdf using writer_pdf_Export, after succes.
I made other changes before in desesperate mode, but none of them solved the problem, tried to change owner to soffice wich found it witch $ ls -l $(which libreoffice), tried with 777, etc..
/* This command will work on centos 6 /7 with installation of libreoffice headless package */
First install package on centos as :
yum install libreoffice-headless
/* following code work to extract text format from */
<?php
$result = exec("export HOME=/tmp/ && /usr/bin/libreoffice --headless --convert-to txt:Text --outdir /tmp filePath");
var_dump($result);
?>
Most likely the user that LibreOffice is ran as, does not have a writeable home directory so LibreOffice fails to create it's config directory and then it cannot create it's config files and then fails to load Java, because it cannot write the default config. A bit silly I know.
Try adding this parameter: -env:UserInstallation=file:///tmp/whateverhere
I don't have enough reputation to comment on TD_Nijboer's answer, but the answer to his specific problem appears to be that soffice needs to be able to read & write config information somewhere. The first place it tries to do this is the libreoffice directory in ~/.config ('~' means "the current user's home directory").
In Debian, by default, the www-data user has the home directory /var/www, and does not have write permission there.
If you make sure it has permission to either create ~/.config itself, or libreoffice within an existing ~/.config, I expect it will work.
2 things, 1st the command is soffice --headless,
2nd i have an similar javaldx error and it has to do with permission.
when executing as root it works fine, but php executes as www-data.
if anybody knows a good way to execute libreoffice from php please let me know.
as i'm getting an error code 77 saying:
[Java framework] Error in function createSettingsDocument (elements.cxx).
javaldx failed!
Warning: failed to read path from javaldx

Executing .exe file using PHP on Linux server

I'm new in using Linux, I'm trying to write a PHP code which can run .exe linux compatible file, I've made a short shell script
hello bash script:
#!/bin/bash
./program.exe file.mp4 // file.mp4 is an an input for .exe
echo "Hello World!"
shell.php:
<?php
$output = exec ("./hello ");
echo "<pre>$output</pre>";
?>
Now when I run shell.php using web browser it shows Hello World! but the .exe doesn't run, however when I run php using terminal command php shell.php, It works fine.
I think I'm having problems with permissions but I'm new with Linux and I don't know how to solve this.
Update:
I ignored the shell script and I used
<?php
$output = shell_exec ("cd /var/www/ && ./program.exe file.mp4 2>& " );
?>
also I granted access to program.exe
chmod 777 program.exe
the error I receive in the browser :could not open debug.bin!
use the absolute path to hello executable exec("sh path/to/the/file")
I'm using something similar to call an app compiled with mono on a remote ubuntu webserver and return it's output to the calling script.
For any of this to work properly wine needs to be already installed.
On Ubuntu systems try:
sudo apt-get -y install wine
You then need to know the owner of the web server process. If you are running the apache web server try the following:
cat /etc/apache2/envvars | grep "RUN"
The output will look something like this:
export APACHE_RUN_USER=www-data
export APACHE_RUN_GROUP=www-data
export APACHE_RUN_DIR=/var/run/apache2$SUFFIX
Now that you have the name of the process owner, which in this case is www-data you should ensure the file is owned the user and its group:
sudo chown www-data /var/www/program.exe
sudo chgrp www-data /var/www/program.exe
Finally, we can invoke the application from inside our PHP script by passsing it as a parameter to 'wine' and using its full file path.
<?php
$output = shell_exec("wine /var/www/program.exe file.mp4" );
?>
Any output from the above shell command sent to the command line will be saved in the PHP script variable $output.
It looks like you are trying to do some output redirection with your use of program.exe file.mp4 2>& so I've left that off of the example for clairity.
Try using the absolute path, such as exec("sh /path/to/file")
Generally, php is run as www or apache, so make sure that the execute access permission is granted to all user.

PHP how to execute a command

I'm trying to use LibreOffice for converting a spreadsheet to another format, when I execute the command from the console it works fine but when I do it from PHP using exec() or system() it doesn't work.
It doesn't show any error or anything, it simply silently fails, if I try executing some simple command like "ls" it works just fine.
This is the command I'm using:
<?php
system("libreoffice --headless -convert-to ooxml '/home/www/path_to_app/file.xlsx' -outdir /home/www/path_to_app/");
I already tried changing the apache User and Group on /opt/lampp/etc/httpd.conf to the same logged in user I am.
I'm wondering if the problem is that the www folder is /home instead of inside my user and that causes permissions problems, but so far couldn't make it work.
Any help will be appreciated.
I solved this problem with the command below :
system('
export HOME=/tmp
libreoffice --headless --invisible --norestore --convert-to pdf --outdir /my/folder /my/file/calc.xls');
I solved this problem with the command below :
exec('libreoffice --headless --invisible --norestore --convert-to pdf --outdir /my/folder /my/file/calc.xls');
Just check rights, libreoffice uses user home folder, If you use default settings for Ubuntu then PHP runs oenter code heren www-data rights and it's home is /var/www/, but default this directory is owned by root.enter code here
In PHP - you can see rigths:
exec('whoami', $arr);
print_r($arr);
In console - You can see your HOME and give correct rights:
su wwww-data
echo $HOME
exit;
chown www-data:www-data /var/www -R
Notwithstanding your $PATH, which drew010 alluded to, I wouldn't do it this way.
LibreOffice is a pretty big program, has lots of code you don't know about, it generates and updates files in a directory in your $HOME, and is certainly not something you're going to be able to run more than one copy of at a time.
So instead of having LibreOffice launched by your web server, and subverting Apache's security by running it as a more privileged user than "www-data" or "nobody", you should make a handler.
First off, verify that you can run your libreoffice ... command line from a terminal. To be extra sure that you don't have any X11 dependencies, run unset DISPLAY (for bash) or unsetenv DISPLAY (for tcsh) in your xterm before you test your command line. Does it break? Fix that problem first. Does it work? Great, then proceed with a handler.
Your handler, in its simplest form, can be a script that loops forever, checking for "files to handle" in a spool directory, and if it finds them, converts them using libreoffice and puts the resultant file where it can be found by your web app.
#!/bin/sh
while sleep 10; do
if [ `ls /var/tmp/myspool/ | grep -c '\.xlsx$'` -gt 0 ]; then
ls /var/tmp/myspool/*.xlsx | while read file; do
/usr/local/bin/libreoffice --headless -convert-to ooxml "$file" yadda yadda
if [ $? = 0 ]; then
mv "$file" "/var/tmp/myspool/done/
fi
done
fi
done
If you don't want the overhead of something "polling" (checking the spool directory every 10 seconds), then you could have your PHP script add a line to a log that gets watched by your handler. For example:
<?php
// process form, save file to spool dir
syslog(LOG_NOTICE, "Saved: " . $filename);
?>
Make sure you've configured syslog to store these messages in, say, /var/log/filelog, then your handler can just tail the log.
#!/bin/sh
tail -F /var/log/filelog | while read line; do
filename="`echo \"$line\" | sed 's/.*Saved: //'`"
/usr/local/bin/libreoffice --headless -convert-to ooxml "$file" yadda yadda
# etc ... error handling and mv as in the other script
done
Get the idea?
I also faced same problem before.....
This solution seems worked for me...
function execInBackground($cmd) {
if (substr(php_uname(), 0, 7) == "Windows"){
pclose(popen("start /B ". $cmd, "r"));
}
else {
exec($cmd . " > /dev/null &");
}
}
$mainFile = "YOUR FILE";
$cmd2 = "export HOME=/tmp
libreoffice --headless --invisible --norestore --convert-to pdf " .
"'$mainFile'";
$saved = getenv("LD_LIBRARY_PATH"); // save old value
$newld = "/usr/lib"; // extra paths to add
if ($saved) {
putenv("LD_LIBRARY_PATH=" . $newld);
}
// set new value
//
// command is loaded using
// libs in the new path list
execInBackground($cmd2);
putenv("LD_LIBRARY_PATH=$saved"); // restore old value

Categories