I am trying to convert HTML 2 PDF with this library and its converting fine as per my expectations.
However, When I convert with more data, its giving me an error saying 504 Gateway Timeout. Here is the error screenshot what I am getting.
In local server its working fine. I have the same server in my local and my live (Linux). The only problem is I am getting when I try to produce PDF with long data on live server.
I researched and found out that to increase php execution time and other settings. Hence I try to put below code in my .php file.
ini_set('max_execution_time', 60000);
ini_set('post_max_size','128M');
ini_set('upload_max_filesize','128M');
I even try to set max_execution_time to 0 and -1 but yet its not working for me. After setting this values, I even printed the updated values with phpinfo(), the values are overwriting but I am having the same 502 Gateway timeout error. Here is small chunk of code just in case you want to see.
<?php
ini_set('max_execution_time', 60000);
ini_set('post_max_size','20M');
ini_set('upload_max_filesize','8M');
require_once dirname(__FILE__) . '/vendor/autoload.php';
require_once dirname(__FILE__) . '/templateInfo.php';
use Spipu\Html2Pdf\Html2Pdf;
use Spipu\Html2Pdf\Exception\Html2PdfException;
use Spipu\Html2Pdf\Exception\ExceptionFormatter;
use technobrave\brochuresettings\Models\Brochuresettings as BS;
use Technobrave\Transactions\Models\Transactions as TR;
use Technobrave\Offices\Models\Offices;
use technobrave\themesettings\Models\ThemeSetting as TS;
use Technobrave\Team\Models\Team;
class generateTemplate {
public $theme = "";
public $theme_settings = array();
public function __construct($templateId, $resolution , $theme ,$pdf_sections = array(),$openFile = false, $finalPdfFile = null) {
$this->getBrochureTransactionData = BS::first();
$this->getPdfSection = $pdf_sections;
$this->theme_settings = TS::first();
$this->theme = $theme;
$this->baseUrl = url(Config::get('cms'));
$this->teamPageName = $this->baseUrl . '/our-team';
$this->capabilitiesPageName = $this->baseUrl . '/capabilities';
$this->getFooterText = $this->getFooterText();
$getTeamId = (isset($_GET['teamId']) && !empty($_GET['teamId'])) ? $_GET['teamId'] : "";
$this->uniquePath = __DIR__ . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR;
$templatePath = __DIR__ . DIRECTORY_SEPARATOR . 'regency_template' . DIRECTORY_SEPARATOR . $getTeamId . DIRECTORY_SEPARATOR . $templateId . '.php';
$templateInfoText = new templateInfo($templateId, $this->uniquePath, $getTeamId);
$this->customImagePath = $this->uniquePath;
foreach ($templateInfoText->defaultValues as $key => $value) {
$this->{$key} = $value;
}
$template = file_get_contents($templatePath);
try
{
$html2pdf = new Html2Pdf('L','A4', 'en', true, 'UTF-8', array(0, 0, 0, 0));
$html2pdf->Addfont('perpetua');
$html2pdf->Addfont('montserratbold');
$html2pdf->Addfont('montserratmedium');
$html2pdf->Addfont('montserratregular');
$html2pdf->Addfont('montserratsembold');
$html2pdf->Addfont('montserratitalic');
$html2pdf->writeHTML($template, false);
$html2pdf->Output('regency_corporate_brochure.pdf', 'D');
} catch (Html2PdfException $e) {
$formatter = new ExceptionFormater($e);
echo $formatter->getHtmlMessage();
}
}
}
I tried to preview how my HTML is generating and its generating without any error.
$html2pdf->writeHTML($template, true);
So basically I am facing server issue here as per my understanding so far.
Can someone guide me what should I do from here on to solve this issue.
After a hard debugging I found that my problem was that I was including an external image in the PDF and the server can't reach the server image (server access only trough white-list IP).
Related
so here is my problem:
I want to use jwplatform-php to upload my video files.
here is my php script: (this is more or less the sample script provided)
<?php
use Jwplayer\JwplatformClient;
header_remove( 'X-Powered-By' );
chdir(dirname(__DIR__));
require 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
$secret = "XXXXXXXXXXXXXXXXXXX";
$site_id = "XXXXX";
$jwplatform_api = new JwplatformClient($secret);
$target_file = "test.mp4";
$params = [];
$params['metadata'] = [];
$params['metadata']['title'] = 'PHP API Test Upload';
$params['metadata']['description'] = 'Video description here';
$params['upload'] = [];
$params['upload']['method'] = 'direct';
// Create the example media
$create_response = json_encode($jwplatform_api->Media->create($site_id, $params));
print_r($create_response);
print("\n");
$decoded = json_decode(json_decode(trim($create_response), true), true);
$upload_link = $decoded['upload_link'];
// Upload the media file
$upload_response = $jwplatform_api->Media->upload($target_file, $upload_link);
print_r($upload_response);
print("\n");
And so the error occurs at $create_response he return false.
I think the problem is $target_file = "test.mp4"; that he can't solve even by putting the relative path $target_file = dirname(__FILE__) . DIRECTORY_SEPARATOR ."test.mp4"; he returns to me false.
I don't know what to do and in addition the doc jwplatform-php is almost non-existent
I thank you already for all the help provided and sorry for my approximate English...
I'm using "google-api-php-client" library which is working fine on local system but it's giving following error on server as it's version is 5.2!
syntax error, unexpected T_FUNCTION, expecting ')'
So I have two questions here, if we can fix this error by doing some changes in code to make it work with this function? Below is the code of autoload.php
spl_autoload_register(
function ($className) {
$classPath = explode('_', $className);
if ($classPath[0] != 'Google') {
return;
}
// Drop 'Google', and maximum class file path depth in this project is 3.
$classPath = array_slice($classPath, 1, 2);
$filePath = dirname(__FILE__) . '/' . implode('/', $classPath) . '.php';
if (file_exists($filePath)) {
require_once($filePath);
}
}
);
but I'm not sure how to change the above to solve this issue and also is there any library which can run on php version 5.2? As if I use this, it might be possible that it start giving error on some other functionality. Thanks!
It seems your php version not knows about anonymous functions or closures. Try to use named one:
function autoloadGoogleApi($className) {
$classPath = explode('_', $className);
if ($classPath[0] != 'Google') {
return;
}
// Drop 'Google', and maximum class file path depth in this project is 3.
$classPath = array_slice($classPath, 1, 2);
$filePath = dirname(__FILE__) . '/' . implode('/', $classPath) . '.php';
if (file_exists($filePath)) {
require_once($filePath);
}
}
spl_autoload_register('autoloadGoogleApi');
Still, I'm also want to point out, that php version you specifying is very old, so I'm suggesting to really consider option of upgrading.
UPD: 3v4l test
I'm using Roots.io wordpress starter theme. It's coded for PHP 5.5 but the server I'm posting the site on is running PHP 5.3
I need to change this code to be supported by the PHP on the server, but don't know how.
function asset_path($filename) {
$dist_path = get_template_directory_uri() . DIST_DIR;
$directory = dirname($filename) . '/';
$file = basename($filename);
static $manifest;
if (empty($manifest)) {
$manifest_path = get_template_directory() . DIST_DIR . 'assets.json';
$manifest = new JsonManifest($manifest_path);
}
if (WP_ENV !== 'development' && array_key_exists($file, $manifest->get())) {
return $dist_path . $directory . $manifest->get()[$file];
} else {
return $dist_path . $directory . $file;
}
}
The issue is in this line:
return $dist_path . $directory . $manifest->get()[$file];
The [$file] is confusing PHP I think but no idea how to modify this. Any tips? If more code is needed please let me know.
You'll need to split that return as requesting an index from a method call I think started getting supported in 5.4.
Try splitting it out.
$val = $manifest->get();
return $dist_path . $directory . $val[$file];
For reference this is know as array dereferencing. You can find more information about it here.
I downloaded the PHP ews database from https://github.com/jamesiarmes/php-ews.
Autoloader:
function __autoload ($className){
preg_match ("/^(([a-zA-Z]{5})_)?(.+)$/",$className,&$treffer); # die ersten 5 Stellen=Verzeichnisname, Weitere Zeichen=Dateiname
if(file_exists(PROJEKT_DIR.$className.".class.php")) include_once(PROJEKT_DIR.$className.".class.php");
else{
$pfad=SCRIPT_DIR."include/";
if($treffer[2]) $pfad.="classes/".$treffer[2]."/";
if(file_exists($pfad.$treffer[3].".class.php"))
include_once($pfad.$treffer[3].".class.php");
elseif(substr($treffer[3],-7)!="_bvstnd" and class_exists($className."_bvstnd")){
eval("class $className extends ".$className."_bvstnd {} ");
}
else{
// Start from the base path and determine the location from the class name,
$pfad=SCRIPT_DIR."include/php-ews";
$include_file = $pfad . '/' . str_replace('_', '/', $className) . '.php';
return (file_exists($include_file) ? require_once $include_file : false);
}
}
#if(file_exists(SCRIPT_DIR."include/".$className.".class.php"))
# include_once(SCRIPT_DIR."include/".$className.".class.php");
}
it also load some other files.
Then I started doing the Guide from his site, I started doing this:
<?php
$host = "*********";
$username="**********";
$password="***********";
$version= "***********";
$ews = new ExchangeWebServices($host, $username, $password, $version);
$request = new EWSType_FindFolderType();
$request->Traversal = EWSType_FolderQueryTraversalType::SHALLOW;
$request->FolderShape = new EWSType_FolderResponseShapeType();
$request->FolderShape->BaseShape = EWSType_DefaultShapeNamesType::ALL_PROPERTIES;
// configure the view
$request->IndexedPageFolderView = new EWSType_IndexedPageViewType();
$request->IndexedPageFolderView->BasePoint = 'Beginning';
$request->IndexedPageFolderView->Offset = 0;
// set the starting folder as the inbox
$request->ParentFolderIds = new EWSType_NonEmptyArrayOfBaseFolderIdsType();
$request->ParentFolderIds->DistinguishedFolderId = new EWSType_DistinguishedFolderIdType();
$request->ParentFolderIds->DistinguishedFolderId->Id = EWSType_DistinguishedFolderIdNameType::INBOX;
// make the actual call
$response = $ews->FindFolder($request);
?>
At first the Site at the browser just load very long but then tell me something like this: class Exception is undefined. I can't tell the correct message because now this Message doesn´t even show up if I load the script.
The Browser just load infinitely. After this I can't even connect to my server with my PHP files. I have to open my other Browser to connect again.
If I open up the script in my other Browser then I can run the script again but it´s again loading infinity. (I include all my files I need with autoloader so that's not the Problem)
Does anybody have a Problem like that and found a solution?
You have an issue with your autoloader. The default files of that library are loaded like this:
$pfad=SCRIPT_DIR."include/php-ews";
$include_file = $pfad . '/' . str_replace('_', '/', $className) . '.php';
If your autoloader is the first to try and load that exception, it will replace the '_'. If you put an error_log in that autoloader function you will probably see the result of $inlcude_file to be something like
include/php-ews/EWS/Exception
And that file doesn't exist.
So you should fix your autoloader so it can actually find the file.
To be aboslutely clear:
you (the code) are looking for the class EWS_Exception
this is in the file EWS_Exception.php (in the root of the project)
your autoloader cannot find that file as you replace all _
so the sollution is to either fix your autoloader, or just include that EWS_Exception.php file somewhere.
Running Apache 2.2 with PHP 5.3 on Windows 8. Trying to get the PHP class ImapMailbox to download attachments, but each time I getMail(), the attachments value is empty on every email that has attachments.
All the rest of the email info is downloaded correctly.
I've looked through the class code but can't identify where the problem might be.
Here is my current code:
$mailbox = new ImapMailbox('{testsite.com:110/pop3/novalidate-cert}INBOX', 'testemail#testsite.com', 'MyPaSs', ATTACH_DIR, 'utf-8');
$mails = array();
foreach($mailbox->searchMailbox('SUBJECT "test attach" SINCE "' . date('m/d/Y', strtotime('-1 week')) . '"') as $mailId) {
$mail = $mailbox->getMail($mailId);
$mails[] = $mail;
}
After dumping the $data var in getMail(), it appears there are attachments in winmail.dat format. The code cannot get to these because no attachmentId value is being assigned due to an empty 'ifid' value. Decoding the winmail.dat attachments can be done, but only if they are detected and written to file.
Any ideas how create a workaround in the ImapMailbox code for this?
Here is what I wrote that fixes this problem.
At the beginning of initMailPart() method, add the following:
static $altAttachmentId = 0;
At the end of the IF block for if($this->attachmentsDir) { add the following where the closing } bracket is:
} elseif (!empty($params['fileName']) || !empty($params['filename']) || !empty($params['name'])) { // Process attachments that are not inline.
// Check if need to decode TNEF (Winmail.dat) file.
if ($partStructure->ifsubtype && $partStructure->subtype == 'MS-TNEF') {
require_once 'path_to_your/tnef_decoder.php';
$Tnef = new tnef_decoder;
$un_tnef = $Tnef->decompress($data);
$attached_files = array();
foreach ($un_tnef as $f) {
if (!empty($f['name']) && !empty($f['stream'])) {
$attachment = new IncomingMailAttachment();
$attachment->id = $altAttachmentId;
$attachment->name = $f['name'];
$attachment->filePath = $this->attachmentsDir . DIRECTORY_SEPARATOR . preg_replace('~[\\\\/]~', '', $f['name']);
$mail->addAttachment($attachment);
if (file_exists($attachment->filePath) && md5($f['stream']) != md5_file($attachment->filePath)) {
$attachment->filePath = $this->attachmentsDir . DIRECTORY_SEPARATOR . preg_replace('~[\\\\/]~', '', $mail->id . '_' . $altAttachmentId . '_' . $f['name']);
}
file_put_contents($attachment->filePath, $f['stream']);
$altAttachmentId++;
}
}
} else {
if (!empty($params['filename'])) {
$fileName = $params['filename']; // Account for random camel-case mistake on element.
} elseif (!empty($params['fileName'])) {
$fileName = $params['fileName'];
} else {
$fileName = $params['name'];
}
$attachment = new IncomingMailAttachment();
$attachment->id = $altAttachmentId;
$attachment->name = $fileName;
$attachment->filePath = $this->attachmentsDir . DIRECTORY_SEPARATOR . preg_replace('~[\\\\/]~', '', $mail->id . '_' . $altAttachmentId . '_' . $fileName);
$mail->addAttachment($attachment);
file_put_contents($attachment->filePath, $data);
$altAttachmentId++;
}
}
Note that you must include the tnef_decoder.php file found in the Roundcube Webmail package for the TNEF decoding to work. I got inspiration for the TNEF solution here.
This modification will process all TNEF encoded files in a Winmail.dat file and any other attachment that is not attached inline. Watch your memory usage on large files.
It also won't overwrite existing files that are the same name if they are not exactly the same.