Converting files using PHP LibreOffice and the ncjoes/office-converter library - php

I am using ampps as a windows 10 apache server, my php version is 7.3. I downloaded it from the LibreOffice download page and installed it on my computer. Then I installed this library via composer https://github.com/ncjoes/office-converter. I try as in the example given, but it does not convert and gives an error. I would be very grateful if you could help me where I am wrong. Here is my code sample and the error I encountered:
<?php
if (!file_exists(__DIR__.'/vendor/autoload.php')) echo 'autoload.php mevcut değil!';
else require __DIR__.'/vendor/autoload.php';
use NcJoes\OfficeConverter\OfficeConverter;
use PHPUnit\Framework\TestCase;
class OfficeConverterTest extends TestCase
{
/**
* #var OfficeConverter $converter
*/
private $converter;
private $outDir;
public function setUp()
{
parent::setUp();
$DS = DIRECTORY_SEPARATOR;
$file = __DIR__."{$DS}sources{$DS}test.docx";
$this->outDir = __DIR__."{$DS}results";
$this->converter = new OfficeConverter($file, $this->outDir);
}
public function testDocxToPdfConversion()
{
$output = $this->converter->convertTo('result.pdf');
$this->assertFileExists($output);
}
public function testDocxToHtmlConversion()
{
$output = $this->converter->convertTo('result.html');
$this->assertFileExists($output);
}
}
$donustur = new OfficeConverterTest();
$donustur->testDocxToPdfConversion();
?>
Fatal error: Uncaught Error: Call to a member function convertTo() on null in C:\Program Files\Ampps\www\converter\converter.php:29 Stack trace: #0 C:\Program Files\Ampps\www\converter\converter.php(43): OfficeConverterTest->testDocxToPdfConversion() #1 {main} thrown in C:\Program Files\Ampps\www\converter\converter.php on line 29

When running tests, we are supposed to leave running them to phpunit, but you are trying to call manually (in last 2 lines of your code).
But if you insist on calling manually, change:
$donustur = new OfficeConverterTest();
$donustur->testDocxToPdfConversion();
Into:
$donustur = new OfficeConverterTest();
$donustur->setUp();
$donustur->testDocxToPdfConversion();
So that you call setUp() which phpunit would normally call for you automatically.
See also:
How do I run all my PHPUnit tests?
How to run single test method with phpunit?
Example for page
If you want to use this logic on a Web-Page, it should look something like:
<?php
if (!file_exists(__DIR__.'/vendor/autoload.php')) echo 'autoload.php mevcut değil!';
else require __DIR__.'/vendor/autoload.php';
use NcJoes\OfficeConverter\OfficeConverter;
echo 'Converting...<br>';
$input = __DIR__ . '/test.docx';
$converter = new OfficeConverter($input, __DIR__.'/results');
$output = $converter->convertTo('result.pdf');
echo 'Saved at:' . $output . '<br>';

Related

Fatal error in Library 'require' and 'use' PHP

I'm trying to implement https://github.com/zytzagoo/smtp-validate-email for email validation, but I have a problem in the sintallation of the package (manually, I'm not using composer)
So here is the hierarchy of my files:
My index has this code:
<?php
require 'Library/Validator.php';
use \Library\Validator;
$email = 'someone#example.org';
$sender = 'sender#example.org';
$validator = new Validator($email, $sender);
$results = $validator->validate();
var_dump($results);
$log = $validator->getLog();
var_dump($log);
?>
And the 'Validator.php' has 1000 lines of code but here are the first 25 lines so you can have an idea:
<?php
namespace SMTPValidateEmail;
use \SMTPValidateEmail\Exceptions\Exception as Exception;
use \SMTPValidateEmail\Exceptions\Timeout as TimeoutException;
use \SMTPValidateEmail\Exceptions\NoTimeout as NoTimeoutException;
use \SMTPValidateEmail\Exceptions\NoConnection as NoConnectionException;
use \SMTPValidateEmail\Exceptions\UnexpectedResponse as UnexpectedResponseException;
use \SMTPValidateEmail\Exceptions\NoHelo as NoHeloException;
use \SMTPValidateEmail\Exceptions\NoMailFrom as NoMailFromException;
use \SMTPValidateEmail\Exceptions\NoResponse as NoResponseException;
use \SMTPValidateEmail\Exceptions\SendFailed as SendFailedException;
class Validator
{
public $log = [];
/**
* Print stuff as it happens or not
*
* #var bool
*/
public $debug = false;
So, the output of the 'index.php' is this:
Fatal error: Uncaught Error: Class "Library\Validator" not found in C:\xampp\htdocs\EmailValidation\index.php:9 Stack trace: #0 {main} thrown in C:\xampp\htdocs\EmailValidation\index.php on line 9
use namespace name and class name to call it.
use \SMTPValidateEmail\Validator;
example
namespace Helpers
and the CheckUser class
then the text becomes
use Helpers/CheckUser;

This happens only on live server: Fatal error: Uncaught Error: Call to a member function signin() on boolean in

Confession:
I read many similar questions on this platform, but nothing seems closely aligned to my situation. Most of the questions seem to originate from binding params in prepared statements or execute statement.
In my case, the website runs smooth on a local server(Apache2). However, it throws the error below when published on live server.
Fatal error: Uncaught Error: Call to a member function signin() on boolean in /storage/ssd5/815/17670815/app/controllers/signin.php:16 Stack trace: #0 /storage/ssd5/815/17670815/app/core/app.php(33): Signin->index() #1 /storage/ssd5/815/17670815/public_html/index.php(4): App->__construct() #2 {main} thrown in /storage/ssd5/815/17670815/app/controllers/signin.php on line 16
Context
I'm using MVC (OOP) in PHP and here the relevant parts mentioned in the error. I hope this is not too much.
In the main index page, the line referred in the error is a core class(App) instantiation
<?php
session_start();
require_once '../app/initializer.php';
$app = new App(); //this is the line 4 mentioned in the error
In Signin controller class the line referred in the error is indicated below
<?php
class Signin extends Controller{
function index(){
//you can do this if passing data to view
$data["Page_title"] = "Signin";
if($_SERVER['REQUEST_METHOD'] == "POST"){
// this is a debuggin code
//echo "I am signin controller <br />";
// show($_POST);
$user = $this->loadModel("User");
$user->signin($_POST); //this the line referred in the error
}
$this->view("zac/signin",$data);
}
}
In class APP the line is a callback - check below
<?php
class App {
private $controller = "home";
private $method = "index";
private $params = [];
public function __construct()
{
$url = $this->splitURL();
if(file_exists("../app/controllers/".strtolower($url[0]).".php")){
$this->controller = strtolower($url[0]);
//unset the array position
unset($url[0]);
}
require "../app/controllers/".$this->controller.".php";
// echo file_get_contents('http://smart-ecom.000webhostapp.com/app/controllers/'.$this->controller.".php");
//Create instance of whatever controller class is passed(if it exists, otherwise the home controller)
$this->controller = new $this->controller;
if(isset($url[1])){
if(method_exists($this->controller, $url[1])){
$this->method =$url[1];
unset($url[1]);
}
}
$this->params = array_values($url);
call_user_func_array([$this->controller, $this->method],$this->params); //this is line 33
}
/**
* splitURL gets url from browser and processes against the conroller classes and their methods
* #return array
*/
private function splitURL(){
//check if the the GET is set otherwise set the url to defualt class home
$url = isset($_GET['url']) ? $_GET['url'] :"home";
// return explode("/",filter_var(trim($_GET['url'],"/"), FILTER_SANITIZE_URL));
return explode("/",filter_var(trim($url,"/"), FILTER_SANITIZE_URL));
}
}
?>
The Database class's read function is as follows. This method isn't directly referred in the error message
public function read($query, $data = []){
$stmt = self::$conn->prepare($query);
$result = $stmt->execute($data);
if($result){
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(is_array($data) && count($data) > 0){
return $data;
}
}
return false;
}
As I mentioned earlier, this error fires on a live server but the website runs smooth in dev environment with PHP 7.4, Apache2, MySQL 8 Windows 10.
Your help is match appreciated in advance.
I learned this the hard way and I hope this can help someone with similar issues. The cause of the error because of how windows and Linux deals with case sensitivity in file names. In Windows, file names aren't case sensitive while in Linux - they are. So, that was the reason why the website was running smooth in the local dev environment(Windows machine) but throwing an error on a live server(which is Linux). To see the difference, refer to my earlier comment in this thread.
protected function loadModel($model){
if(file_exists("../app/models/". strtolower($model) . ".class.php")){
include "../app/models/".strtolower($model).".class.php";
return $model = new $model();
}else{
return false;
}
}
}
In the "include" line, you can see that I added the strtolower function to include the proper model and that solved the issue.

Including a file with PHP - avoiding not found?

I am new to php, I have two files, one where I want to keep my classes and bulk of my code, and another where I integrate with some HTML. My code was working, but now I am getting the error:
PHP Fatal error: Uncaught Error: Class 'bardrink' not found in C:\MAMP\htdocs\index.view.php:84 Stack trace: > #0 {main} thrown in C:\MAMP\htdocs\index.view.php on line 84
Here is my index.php file:
<?php
class bardrink {
public $drink_name;
public $drink_desc;
public $drink_strength;
public $drink_price;
public function __construct($drink_name,$drink_desc,$drink_strength,$drink_price)
{
$this->drink_name = $drink_name;
$this->drink_desc = $drink_desc;
$this->drink_strength = $drink_strength;
$this->drink_price = $drink_price;
}
}
require 'index.view.php';
?>
And in my index.view.php I am adding:
<?php
$barselection = [
new bardrink('Water','A light refreshing drink.',0,1),
new bardrink('Light Ale','A pale ale brewed locally.',2,4),
new bardrink('Mulled Wine','A warm festive wine, perfect for a chilly evening!',3,6),
new bardrink('Dark Ale','A strange frothy, dark liquid...',5,10)
];
var_dump($barselection)
?>
I've required the index.view.php in the index file, but I do I need to add a require into my view file also to make this work?

How can I access my class properties from a namespace with php version 5.5.12?

I'm using WAMPSERVER 2.5 and PHP version 5.5.12 on Windows 8 PC. I created a namespace which worked ok when I was running PHP version 5.2.12. After upgrading to php version 5.5.12 I'm getting error message about undefined variables which I think means that the namespace is not being used. Here's what my code looks like:
In my UploadFile.php file I have this:
<?php
namespace myNamespace;
class UploadFile
{
protected $avatarUrl;
public function getUrl()
{
return $this->avatarUrl;
}
protected function moveFile($file)
{
$filename = isset($this->newName) ? $this->newName : $file['name'];
echo $file[$key];
$success = move_uploaded_file($file['tmp_name'], $this->destination . $filename);
if ($success) {
$url='http://westcoastchill.com/dc-esports/images/' . $filename;
$this->avatarUrl=$url;
...
}
.....
?>
Then here's the html form that uses the class in the namespace where I get the error messages that states that the variable 'newUrl' is undefined and the index 'displaymax' is undifined.
<?php
require_once 'uploads/src/myNamespace/UploadFile.php';//<------names here
if (!isset($_SESSION['maxfiles'])) {
$_SESSION['maxfiles'] = ini_get('max_file_uploads');
$_SESSION['postmax'] = UploadFile::convertToBytes(ini_get('post_max_size'));
$_SESSION['displaymax'] = UploadFile::convertFromBytes($_SESSION['postmax']); //<------ undifined index
}
$max = 50 * 1024;
$result = array();
if (isset($_POST['upload'])) {
$destination = __DIR__ . '/uploads/uploaded/';
try {
$upload = new UploadFile($destination);
$upload->setMaxSize($max);
$upload->allowAllTypes();
$upload->upload();
$result = $upload->getMessages();
$newUrl=$upload->getUrl(); //<----------- here's the undifined newUrl;
} catch (Exception $e) {
$result[] = $e->getMessage();
}
}
$error = error_get_last();
$oldUrl=$newUrl;
...
?>
}
How can I access my class from a namespace with php version 5.5.12?
Thanks for any help with this!
UPDATE: Sorry I had getUrl() outside of superclass but in my actual project is in the correct place. So I tried:
\myNamespace\UploadFile::convertToBytes(ini_get('post_max_size'));...
but I still get the same error. I also tried adding use:
myNamespace\UploadFile and \myNamespace\UploadFile...
still getting the same error message. The thing is my code worked with the using statement before I updated PHP so I'm curious why just an update would change things.
UploadFile class is within the namespace myNamespace, so to reference the class from outside of myNamespace, you would need to use \myNamespace\UploadFile.
If you are already in the global namespace, you don't need the leading slash, but I think it's good practice to always use the leading slash, since the leading slash refers to the global namespace.
Ex:
$_SESSION['postmax'] = \myNamespace\UploadFile::convertToBytes(ini_get('post_max_size'));
and
$upload = new \myNamespace\UploadFile($destination);
The issue was the configuration of the php.ini file. After researching more I tried turning off 'display_errors=Off in the php.ini file and the code the code ran using the namespace and everything. Conclusion: the php.ini file of the new installation different settings. I'll explore the settings more but my problem was solved by turning off error displaying. Obviously this is not a desired option so I'll toggle on and off as I go forward and read up on other parameters in the file that may help me.

spl_autoload_register in Zend

I'm currently trying to use the Twilio PHP library that uses spl_autoload_register to include its classes.
function Services_Twilio_autoload($className) {
if (substr($className, 0, 15) != 'Services_Twilio') {
return false;
}
$file = str_replace('_', '/', $className);
$file = str_replace('Services/', '', $file);
return include dirname(__FILE__) . "/Twilio.php";
}
spl_autoload_register('Services_Twilio_autoload');
I throw in this code:
require_once('Library/Services/Twilio.php');
$client = new Services_Twilio($this->sid, $this->token);
And then I get this error when running it:
Fatal error: Cannot redeclare Services_Twilio_autoload() (previously declared in ...\Twilio\Library\Services\Twilio.php:9) in ... \Twilio\Library\Services\Twilio.php on line 16
This code runs off Zend, and already has a bootstrap with _initAutoload(). I'm not sure where or how I should implement the autoload for this library as I'm not very familiar with it.
I think I have reproduced the problem.
To correct it, I just add require_once('Services/Twilio.php'); in the bootstrap like this:
require_once('Services/Twilio.php');
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
....
In my case, I put Services directory in library directory (where is Zend directory).
And in a controller, I can call Services_Twilio like you :
$client = new Services_Twilio($this->sid, $this->token);
I hope it will help you. :)

Categories