Laravel Undefined index: document using PHPWord and DomPDF - php

I'm trying to convert a odt file to a pdf, using PHPWord and DomPDF, I've read some issue on their git about how to do it and found this one guide. But I'm getting and error on laravel about the PHPWord library Undefined index: document on the route
C:\xampp\htdocs\DAW2M14\vendor\phpoffice\phpword\src\PhpWord\Reader\Word2007.php
foreach ($steps as $step) {
$stepPart = $step['stepPart'];
$stepItems = $step['stepItems'];
foreach ($relationships[$stepPart] as $relItem) {
$relType = $relItem['type'];
if (isset($stepItems[$relType])) {
$partName = $stepItems[$relType];
$xmlFile = $relItem['target'];
$this->readPart($phpWord, $relationships, $partName, $docFile, $xmlFile);
}
}
}
The error starts in the foreach.
My PHP code is:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\URL_Document;
use App\Document;
use App\Http\Requests;
use Dompdf\Dompdf;
class CU_13Controller extends Controller
{
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function generaPDF(Request $request, $id, $nombre, $path, $pathb, $formato) {
$ruta=$path.'/'.$pathb;
if($formato == "pdf"){
return response()->download(storage_path("app/{$ruta}"));
}else{
$FilePath = "app/".$ruta;
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$document = $phpWord->loadTemplate(storage_path("app/{$ruta}"));
$document->saveAs('temp.odt');
$domPdfPath = base_path('/../vendor/dompdf/dompdf');
\PhpOffice\PhpWord\Settings::setPdfRendererPath($domPdfPath);
\PhpOffice\PhpWord\Settings::setPdfRendererName('DomPDF');
$phpWord = \PhpOffice\PhpWord\IOFactory::load('temp.odt');
$pdfWriter = \PhpOffice\PhpWord\IOFactory::createWriter( $phpWord, 'PDF' );
$pdfWriter->save(storage_path("app/documents{$nombre}.pdf"));
return response()->download(storage_path("app/documents{$nombre}.pdf"));
}
}
}
I don't know what kind of error I am doing

Related

Unable to extract the content of pdf file in php

Currently working on validating the pdf file. I have used PHP pdfparser in Laravel to extract the file. But some files are unable to extract. I come up with the solution to downgrade the pdf file to resolve the issue but still not working for me.
I tried to downgrade the pdf file from version 1.7 to 1.4 but it's not allowing me to do so.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Smalot\PdfParser\Parser;
use Xthiago\PDFVersionConverter\Guesser\RegexGuesser;
use Symfony\Component\Filesystem\Filesystem;
use Xthiago\PDFVersionConverter\Converter\GhostscriptConverterCommand;
use Xthiago\PDFVersionConverter\Converter\GhostscriptConverter;
class ApiController extends Controller {
public function varifyDocument(Request $request, Parser $parser) {
$request = $request->file();
$file = $request['file'];
//Get the version of the pdf file.
$guesser = new RegexGuesser();
$version = $guesser->guess($file);
//If pdf version is 1.7 then convert it to 1.4.
if($version == "1.7") {
$command = new GhostscriptConverterCommand();
$filesystem = new Filesystem();
$converter = new GhostscriptConverter($command, $filesystem);
$converter->convert($file, '1.4');
}
$pdf = $parser->parseFile($file);
$pages = $pdf->getPages();
foreach ($pages as $page) {
echo $page->getText();
}
}
}
I need to read the content of the pdf file and identify it has any vulnerability or not.

Google Cloud Vision ImageAnnotator Google Application Credential File Not Exist Codeigniter PHP

I have try to implement the google cloud vision with API ImageAnnotator using a codeigniter PHP.
I have install the require google cloud vision using a composer to my third party directory in codeigniter.
This is the code looks like in my controller :
defined('BASEPATH') OR exit('No direct script access allowed');
use Google\Auth\ApplicationDefaultCredentials;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
class Manage_center extends CI_Controller {
function __construct() {
parent::__construct();
include APPPATH . 'third_party/vendor/autoload.php';
}
public function index()
{
$this->load->view('index');
}
function upload_ocr_image()
{
//img_data contain image => i just shorten the code.
$img_data = $this->upload->data();
// Authenticating with a keyfile path.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.base_url().'assets/google_cloud_vision/credentials.json');
$scopes = ['https://www.googleapis.com/auth/cloud-vision'];
// create middleware
$middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
$stack = HandlerStack::create();
$stack->push($middleware);
$imageAnnotator = new ImageAnnotatorClient();
# annotate the image
$response = $imageAnnotator->textDetection($img_data['full_path']);
$texts = $response->getTextAnnotations();
printf('%d texts found:' . PHP_EOL, count($texts));
foreach ($texts as $text) {
print($text->getDescription() . PHP_EOL);
# get bounds
$vertices = $text->getBoundingPoly()->getVertices();
$bounds = [];
foreach ($vertices as $vertex) {
$bounds[] = sprintf('(%d,%d)', $vertex->getX(), $vertex->getY());
}
print('Bounds: ' . join(', ',$bounds) . PHP_EOL);
}
$imageAnnotator->close();
}
}
I got the error :
Type: DomainException Message: Unable to read the credential
file specified by GOOGLE_APPLICATION_CREDENTIALS: file
http://localhost/theseeds/assets/google_cloud_vision/credentials.json
does not exist Filename:
D:\xampp\htdocs\theseeds\application\third_party\vendor\google\auth\src\CredentialsLoader.php
Line Number: 74
File:
D:\xampp\htdocs\theseeds\application\controllers\Manage_center.php Line: 3188 Function: getMiddleware
I dont understand why this error occur :
http://localhost/theseeds/assets/google_cloud_vision/credentials.json does not exist
Because when i opened the link the file is there.
And this error :
File:
D:\xampp\htdocs\theseeds\application\controllers\Admin_center.php Line: 3188 Function: getMiddleware
is a line code :
$middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
What is the proper way to use the google cloud vision ImageAnnotatorClient in codeigniter PHP ?
Is there a problem with the authentication to google cloud api ?
Thank You
I found the solution myself.
This is how the right way to use the google cloud ImageAnnotator with service account key.
defined('BASEPATH') OR exit('No direct script access allowed');
use Google\Cloud\Vision\VisionClient;
class Admin_center extends CI_Controller {
function __construct() {
parent::__construct();
include APPPATH . 'third_party/vendor/autoload.php';
}
public function index() {
$this->load->view('index');
}
function upload_ocr_image() {
$img_data = $this->upload->data();
$vision = new VisionClient(['keyFile' => json_decode(file_get_contents('credentials.json'), true)]);
$imageRes = fopen($img_data['full_path'], 'r');
$image = $vision->image($imageRes,['Text_Detection']);
$result = $vision->annotate($image);
print_r($result);
}
}

Import CSV on Maatwebsite / Laravel Excel 3.1 using Excel::import

I've upgraded Maatwebsite/Laravel-Excel to 3.1 from 2.1. Some of the method are deprecated.
Here is the code on version 2.1.
$data = Excel::load($path, function($reader) {})->get()->toArray();
It's working when I used 2.1 but after I upgraded, it's error
Call to undefined method Maatwebsite\Excel\Excel::load()
For version 3.1, i tried to change to
$data = Excel::import($path, function($reader) {})->get()->toArray();
I know this probably not the correct syntax.
Here my full code when developing using 2.1.
$path = $request->file('csv_file')->getRealPath();
if ($request->has('header')) {
$data = Excel::import($path, function($reader) {})->get()->toArray();
} else {
$data = array_map('str_getcsv', file($path));
}
if (count($data) > 0) {
if ($request->has('header')) {
$csv_header_fields = [];
foreach ($data[0] as $key => $value) {
$csv_header_fields[] = $key;
}
}
$csv_data = array_slice($data, 0, 8);
$csv_data_file = CsvData::create([
'csv_filename' => $request->file('csv_file')->getClientOriginalName(),
'csv_header' => $request->has('header'),
'csv_data' => json_encode($data)
]);
} else {
return redirect()->back();
}
return view('import.import_field', compact( 'csv_header_fields', 'csv_data', 'csv_data_file'));
How to fix this error on version 3.1?
Actually there is no need to create any extra classes for the Excel import in Maatwebsite/Laravel-Excel version 3. Basically you can do the whole CSV to array conversion almost in a same way as in version 2:
$path = $request->file('csv_file')->getRealPath();
$data = \Excel::toArray('', $path, null, \Maatwebsite\Excel\Excel::TSV)[0];
The first parameter of the import() method is not the path to the file anymore in 3.1, but the class name of the Import file you have to create.
In this import file you can define how you want to read the sheet, and to what format you want to convert it, for example a model or a collection.
The easiest way to migrate from 2.1 to 3.1 is to create such an Import class by running (in your case):
php artisan make:import CsvDataImport
If you want to read all to rows at once, as in your question's code, you could use the ToCollection Concern in your import file:
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
class CsvDataImport implements ToCollection
{
public function collection(Collection $rows)
{
// Use the $rows collection to create your CsvData model.
}
}
In your Controller you can call the import like this:
use App\Imports\CsvDataImport;
use Maatwebsite\Excel\Excel;
Excel::import(new CsvDataImport, $path);
You can read more about importing to a collection here
Do Not get back to downgrade, you can easily use new updated version("maatwebsite/excel": "~3.1.0") with easiest import method.
Update Your Composer.json..
"require": {
**"maatwebsite/excel": "~3.1.0"**
},
Steps To Use New Version..
Create Import to run this command in cmd
php artisan make:import UsersImport
It will Create Import in app\imports\UserImport.php
<?php
namespace App\Imports;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class UserImport implements ToCollection,WithHeadingRow
{
public function collection(Collection $rows)
{
return $rows;
}
// headingRow function is use for specific row heading in your xls file
public function headingRow(): int
{
return 3;
}
}
?>
In Your Controller file..
use Excel;
public function importExcel(Request $request) {
$import = new UsersImport();
$data = \Excel::import($import, request()->file('import_file'));
}

Owncloud 8.1 "myapp" sample, add a function to write to a file

On Owncloud 8.1 using the owncloud command line, I create a new test app:
ocdev startapp MyApp --email mail#example.com --author "Your Name" --description "My first app" --owncloud 8
The app is working, I can add it in the owncloud control panel.
Now I'd like to write to a file, so I use one example from the owncloud documentation:
https://doc.owncloud.org/server/8.1/developer_manual/app/filesystem.html
[Edit] I started over and now, I don't know if I omitted something, but "myapp" comes with no "application.php" file.
So I create it at /var/www/core/apps/myapp/appinfo/application.php :
<?php
namespace OCA\MyApp\AppInfo;
use \OCP\AppFramework\App;
use \OCA\MyApp\Storage\AuthorStorage;
class Application extends App {
public function __construct(array $urlParams=array()){
parent::__construct('myapp', $urlParams);
$container = $this->getContainer();
/**
* Storage Layer
*/
$container->registerService('AuthorStorage', function($c) {
return new AuthorStorage($c->query('RootStorage'));
});
$container->registerService('RootStorage', function($c) {
return $c->query('ServerContainer')->getRootFolder();
});
}
}
Then I create a file called /var/www/core/apps/myapp/storage/AuthorStorage.php with:
<?php
namespace OCA\MyApp\Storage;
class AuthorStorage {
private $storage;
public function __construct($storage){
$this->storage = $storage;
}
public function writeTxt($content) {
// check if file exists and write to it if possible
try {
try {
$file = $this->storage->get('/myfile.txt');
} catch(\OCP\Files\NotFoundException $e) {
$this->storage->touch('/myfile.txt');
$file = $this->storage->get('/myfile.txt');
}
// the id can be accessed by $file->getId();
$file->putContent($content);
} catch(\OCP\Files\NotPermittedException $e) {
// you have to create this exception by yourself ;)
throw new StorageException('Cant write to file');
}
}
}
The sample app already gives me a route to the index function in the pagecontroller.php
['name' => 'page#index', 'url' => '/', 'verb' => 'GET']
How do I call the function "writeTxt" from there?
Based on http://php.net/manual/en/language.oop5.basic.php
I tried:
use \OCA\MyApp\Storage\AuthorStorage;
and
public function index() {
//added part
$a = new AuthorStorage();
$a->writeTxt('test');
//original part
$params = ['user' => $this->userId];
return new TemplateResponse('myapp', 'main', $params); //templates/main.php
}
After running I get a "Class 'OCA\MyApp\Storage\AuthorStorage' not found at /var/www/core/apps/myapp/controller/pagecontroller.php#44"
Even with the help of use \OCA\MyApp\Storage\AuthorStorage; ( ClassNotFoundException: Attempted to load class... Symfony ) it doesn't seem to help.
Thanks
Time has gone by, so I'm posting an answer to my question for owncloud 9.
Here are the steps to a basic script with read, write, copy file ability.
"application.php" has definitively been removed from the example. It was not a bug.
Following:
https://doc.owncloud.org/server/9.0/developer_manual/app/startapp.html
Generate the demo "MyApp" app:
ocdev startapp MyApp --email mail#example.com --author "Your Name" --description "My first app" --owncloud 9
Edit the file myapp/controller/pagecontroller.php
<?php
/**
* ownCloud - myapp
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* #author Your Name <mail#example.com>
* #copyright Your Name 2016
*/
namespace OCA\MyApp\Controller;
use OCP\IRequest;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\Controller;
use OCP\Files\IRootFolder;
use OC\Files\Storage\Temporary;
class PageController extends Controller {
private $userId;
private $storage;
private $userstorage;
public function __construct($AppName, IRequest $request, IRootFolder $storage, $UserId){
parent::__construct($AppName, $request);
$this->storage = $storage;
$this->userId = $UserId;
$this->userstorage = $this->storage->get($this->userId.'/files/');
}
/**
* CAUTION: the #Stuff turns off security checks; for this page no admin is
* required and no CSRF check. If you don't know what CSRF is, read
* it up in the docs or you might create a security hole. This is
* basically the only required method to add this exemption, don't
* add it to any other method if you don't exactly know what it does
*
* #NoAdminRequired
* #NoCSRFRequired
*/
public function index() {
$listedudossier = $this->userstorage->getDirectoryListing();
//list all items in the root directory
//and copies the files in an directory called old
//the directory "old" is not script created
foreach ($listedudossier as $value) {
if ( $value->getType() == 'file' ){
$value->copy($this->userId.'/files/old/'.$value->getName());
//also works
//$value->copy($this->userstorage->getPath().'/old/'.$value->getName());
}
}
$params = ['listedudossier' => $listedudossier ];
return new TemplateResponse('myapp', 'main', $params); // templates/main.php
}
/**
* Simply method that posts back the payload of the request
* #NoAdminRequired
*/
public function doEcho($echo) {
//creates a file
$this->userstorage->newFile('myfile2.txt');
//opens a file, adds inputbox content and saves the file
$file = $this->userstorage->get('myfile.txt');
$contenu = $file->getContent();
$file->putContent($contenu.$echo);
return new DataResponse(['echo' => $echo]);
}
}
You also need to edit the myapp/templates/part.content.php
<p>Hello World <?php p($_['user']) ?></p>
<p><button id="hello">click me</button></p>
<p><textarea id="echo-content">
Send this as ajax
</textarea></p>
<p><button id="echo">Send ajax request</button></p>
Ajax response: <div id="echo-result"></div>
<p>listedudossier:<p> <?php
foreach ($_['listedudossier'] as $file) {
echo "type:".$file->getType();
echo "<p>";
echo "nom:".$file->getName();
echo "<p>";
echo "modif:".$file->getMTime();
echo "<p>";
}
From here you can test the code in a development environment:
https://github.com/owncloud/ocdev/blob/master/README.rst#installation

PHP: Load a class in a class

I have a class which is meant to "load" an another class, however I haven't been able to get it to work.
Error Message
Fatal error: Call to undefined method stdClass::echoString() in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\classes\example.php on line 5
Code
My code is broken up into three main sections:
api.php - the class to load the other classes.
API/exampleExternalAPI.php - (multiple files) the classes that api.php loads
example.php - the file that uses the main class (api.php)
If it helps these files can be downloaded from my dropbox
api.php
<?php
/* Config */
define('pathToAPIs','API/');
/* Autoload Function */
spl_autoload_register(function($className){
$namespace=str_replace("\\","/",__NAMESPACE__);
$className=str_replace("\\","/",$className);
$class=pathToAPIs.(empty($namespace)?"":$namespace."/")."{$className}.php";
include_once($class);
});
class api {
private $listOfAPIs;
public $APIs;
public function __construct($setAPI = null){
$this->updateListOfAPIs();
if (isset($setAPI)){
return $this->setAPI($setAPI);
}
}
public function setAPIs($setAPIs){
$this->APIs = null; // clears a previous call to this method
if (!is_array($setAPIs)){ // if not an array
$setAPIs = array($setAPIs); // make array
}
foreach ($setAPIs as $setAPIType){
if(in_array($setAPIType,$this->listOfAPIs)){
$array[$setAPIType] = new $setAPIType;
}
}
$this->APIs = json_decode(json_encode($array), FALSE); // convert array of required api objects to an object
return $this->APIs;
}
public function getListOfAPIs($update = false){
if ($update){
$this->updateListOfAPIs();
}
return $this->listOfAPIs;
}
private function updateListOfAPIs(){
$this->listOfAPIs = null; // clears a previous call to this method
$it = new FilesystemIterator(pathToAPIs);
foreach ($it as $fileinfo){
$filename = pathinfo($fileinfo->getFilename(), PATHINFO_FILENAME); // removes extension
$this->listOfAPIs[]= $filename;
}
}
public function __call($method,$args){
}
}
API/exampleExternalAPI.php
<?php
class exampleExternalAPI {
public function echoString($string){
echo $string;
}
}
example.php
<?php
require_once 'api.php';
$api = new api();
$api->setAPIs('exampleExternalAPI');
$api->APIs->exampleExternalAPI->echoString('string');
Background Info
(may give some insight to my madness)
I'm working on a project where I need to connect to lots of external APIs.
So I decided to creating a class to look after all my communications with external APIs ( not sure if best way - new to Object Oriented Programming).
I'm not entirely sure what problem you're trying to solve, but if your APIs is a simple stdClass instance it should work as expected:
public function setAPIs($setAPIs)
{
$this->APIs = new stdClass; // clears a previous call to this method
if (!is_array($setAPIs)) { // if not an array
$setAPIs = array($setAPIs); // make array
}
foreach ($setAPIs as $setAPIType) {
if (in_array($setAPIType, $this->listOfAPIs)) {
$this->APIs->{$setAPIType} = new $setAPIType;
}
}
return $this->APIs;
}

Categories