TesseractOCR with zend framework 2 - php

I want to use TesseractOCR in zend framework 2 project, i've installed TesseractOCR and when i call recognize function from an action i get the following errors:
file_get_contents(/tmp/1999512125.txt): failed to open stream: No such file or directory in var/www/res-admin/vendor/thiagoalessio/tesseract_ocr/TesseractOCR/TesseractOCR.php on line 235
unlink(/tmp/1999512125.txt): No such file or directory in /var/www/res-admin/vendor/thiagoalessio/tesseract_ocr/TesseractOCR/TesseractOCR.php on line 248
I need to read email address from a hosted image like this one.
This is the function from where i call TesseractOCR recognize function:
public function getTextFromImage($img){
$tesseract = new TesseractOCR($img);
return $tesseract->recognize();
}
and this is the action:
public function emailAction(){
$request = $this->getRequest();
if ($request->isPost())
{
$id = $request->getPost('id');
$maj = $this->email($id);
$data = new JsonModel(array(
'success' => true,
'maj' => $maj
));
return $data;
}
}
where email is:
public function email($source){
$maj = 0;
if($source=='toutes les sources') $annonces = $this->getAnnonces();
else $annonces = $this->getAnnoncesBySource($source);
foreach($annonces as $annonce){
$annonce['email'] = $this->getTextFromImage($annonce['email_annonceur']);
$this->updateEmail($annonce);
$maj +=1;
}
return $maj;
}

Does not seems to be a zf2 related pb.
Look at your tmp file *.txt if it exists and if rights are well set.
If it does not exist check why in the source method.
If it exists, check your rights.
No more ;).

Related

How to use JWPlayer in CodeIgniter?

So far i have tried below:
...
public function upload()
{
$jwplatform_api = new Jwplayer\JwplatformAPI('my_key', 'my_secret');
$target_file = 'upload/vids/course/bede6b9c266b876fc2f0dea7a86cf8bd.mp4';
$params = array();
$params['title'] = 'PHP API Test Upload';
$params['description'] = 'Video description here';
// Create video metadata
$create_response = json_encode($jwplatform_api->call('/videos/create', $params));
$decoded = json_decode(trim($create_response), TRUE);
$upload_link = $decoded['link'];
$upload_response = $jwplatform_api->upload($upload_link, $target_file);
print_r($upload_response);
}
...
But no luck, it says "Class 'Jwplayer\JwplatformAPI' not found".
And yeah, i have put the files I got from https://github.com/jwplayer/jwplatform-php in the ROOT position inside a folder named "jwplatform-php".
Ok since you don't want to use composer - here is a guide
1. Download as Zip
2. Create a folder
In your folder application/third_party/ create a folder called jwplatformapi/
3. Unpack the init.php and the src folder
Unpack from your zip file the init.php and the src folder into your application/third_party/jwplatformapi/ folder
it should looke like
4. Create your library
Create a file called Jwplatform_library.php in your application/libraries/ folder
class Jwplatform_library
{
private $key;
private $secret;
public function __construct($key = 'my_key', $secret = 'my_secret')
{
$this->key = $key;
$this->secret = $secret;
}
public function get()
{
require_once(APPPATH.'third_party/jwplatformapi/init.php');
return new Jwplayer\JwplatformAPI($this->key, $this->secret);
}
}
5. use it in one of your controllers
public function upload()
{
$this->load->library('Jwplatform_library', ['my_key', 'my_secret']);
$obj = $this->jwplatform_library->get();
var_dump($obj);
}

Why success is not being returned in my PHP WSDL (Zf2)

I used these two resources as launching pad for my creation of a WSDL endpoint server.
https://odan.github.io/2017/11/20/implementing-a-soap-api-with-php-7.html
https://www.youtube.com/watch?v=e_7jDqN2A-Y&t=799s
By combining these two I was able to come up with a hybrid system that works. My issue that I am trying resolve right now is getting a response back from the api.php/endpoint server.
In the odan git example, it worked to the letter. But once I made changes to the code that requires objects. I started getting errors.
PHP Notice: Trying to get property of non-object
Here is a portion of the server code.
class wenoError
{
public $response = "Sucess";
public static function authenticate($header_params)
{
if($header_params->username == 'WEX' && $header_params->password == 'WEX1') return true;
else throw new SOAPFault('Wrong user/pass combination', 601);
}
/**
* #param string $payload
* #return string $delivery
*/
public function receivePayload($payload)
{
$xml = base64_decode($payload);
$fileName = 'message-'.rand().'.xml';
$file = file_put_contents('messages/'.$fileName, $xml);
$xml2json = simplexml_load_string($xml);
$jsonOut = json_encode($xml2json);
$arrayJson = json_decode($jsonOut, TRUE);
//$seeArray = print_r($arrayJson, true);
//file_put_contents('messages/converted-'.$fileName.'.json', $arrayJson['Header']['MessageID']);
$response = "Success";
return $response;
}
}
$serverUrl = "https://localhost/WenoErrors/api.php";
$options = [
'uri' => $serverUrl,
];
$server = new Zend\Soap\Server('wsdl', $options);
if (isset($_GET['wsdl'])) {
$soapAutoDiscover = new \Zend\Soap\AutoDiscover(new \Zend\Soap\Wsdl\ComplexTypeStrategy\ArrayOfTypeSequence());
$soapAutoDiscover->setBindingStyle(array('style' => 'document'));
$soapAutoDiscover->setOperationBodyStyle(array('use' => 'literal'));
$soapAutoDiscover->setClass('wenoError');
$soapAutoDiscover->setUri($serverUrl);
header("Content-Type: text/xml");
echo $soapAutoDiscover->generate()->toXml();
} else {
$soap = new \Zend\Soap\Server($serverUrl . '?wsdl');
$soap->setObject(new \Zend\Soap\Server\DocumentLiteralWrapper(new wenoError()));
$soap->handle();
}
What I don't understand is the error message of $response being a non-object. According to the PHP manual https://www.php.net/manual/en/language.oop5.properties.php
The property is set correctly at the top of the class, the property is declared and a value us set.
What went wrong?
UPDATE:
Adding the client code.
$client = new Zend\Soap\Client('https://localhost/WenoErrors/api.php?wsdl');
$delivery = $client->call('receivePayload',[['payload' => $message]]);
Dumping client yields:
C:\eRxGateway\www\apa\WenoErrors\clientapi.php:55:
object(client)[3]
public 'delivery' => null
UPDATE:
What finally worked for me was this change.
First change:
$server = new Zend\Soap\Server('wsdl', $options);
$server = new Zend\Soap\Server(null, $options);
Your code seems to work fine for me. Though, I am getting a different result then yours as below:
$client = new Zend\Soap\Client('http://localhost/test/api.php?wsdl');
$message = ' -> Hello World';
$delivery = $client->call('receivePayload',[['payload' => $message]]);
var_dump($delivery);
object(stdClass)#4 (1) {
["receivePayloadResult"]=>
string(7) "Success"
}
Step 1
Please try to remove all the '/tmp/wsdl-****' files from your /tmp directory. You seem to be on windows, so instead of /tmp it might be something else like C:\Windows\Temp. You can easily find which directory by going into your php.ini file and looking for the below directive.
soap.wsdl_cache_dir="/tmp"
Step 2
Also, for developing and testing purposes always put the below ini directive at the start of your client php file, which in your case is clientapi.php file.
ini_set("soap.wsdl_cache_enabled", 0);
You shouldn't be required to put this directive at the start of the server(api.php) file, but you can if the above still does not work for you.

Unable to find wrapper when testing Guzzle call with PHPUnit

I am writing a unit test for an API that I am developing. The API is written in the Codeigniter framework, that calls another API using Guzzle. The test I am writing verifies that the API call returns the correct response.
The Test.php file contains the following code
require '/application/libraries/apiWrappers/Breathehr.php';
class BreathehrTest extends PHPUnit_Framework_TestCase {
public function testCanReturnEmployeeArray() {
$breatheHR = new Breathehr();
$employees = $breatheHR->list_employees(1);
$this->assertArrayHasKey('employees', $employees);
}
}
The method that is being tested is as follows
class Breathehr {
function __construct() {
}
public function list_employees($page)
{
$client = new GuzzleHttp\Client(
['base_uri' => 'https://xxx/',
'headers' => ['X-API-KEY' => 'xxx'],
'verify' => false]
);
$request = $client->get('employees?page='.$page);
$employees = json_decode($request->getBody(true));
$employeeData = array(
'employees' => array(),
'pagination' => array()
);
$i = 0;
foreach($employees->employees as $employee) {
if($employee->status !== 'Ex-employee') {
$employeeData['employees'][$i]['firstName'] = $employee->first_name;
$employeeData['employees'][$i]['lastName'] = $employee->last_name;
$employeeData['employees'][$i]['jobTitle'] = $employee->job_title;
if(isset($employee->line_manager)) {
$employeeData['employees'][$i]['lineManagerName'] = $employee->line_manager->first_name . ' '. $employee->line_manager->last_name;
$employeeData['employees'][$i]['lineManagerID'] = $employee->line_manager->id;
}
$employeeData['employees'][$i]['workingHours'] = $employee->full_or_part_time;
$employeeData['employees'][$i]['email'] = $employee->email;
$employeeData['employees'][$i]['workPhone'] = $employee->ddi;
$employeeData['employees'][$i]['personalMobile'] = $employee->personal_mobile;
$employeeData['employees'][$i]['homeTelephone'] = $employee->home_telephone;
$employeeData['employees'][$i]['birthday'] = $employee->dob;
$i++;
}
}
$nextLink = $request->getHeader('Link');
$nextLinkSplit = explode(',', $nextLink[0]);
$pageination = array();
foreach($nextLinkSplit as $data) {
$split = explode(';', $data);
preg_match('/"(.*?)"/', $split[1], $keyMatch);
$key = isset($keyMatch[1]) ? $keyMatch[1] : FALSE;
$number = substr($split[0], -2, 1);
$pageination[$key] = $number;
}
array_push($employeeData['pagination'], $pageination);
return $employeeData;
}
}
The API call works correctly via Postman and from a browser, but the result of running PHPUnit from the command line is the following
RuntimeException: Error creating resource: [message] fopen(): Unable
to find the wrapper "https" - did you forget to enable it when you
configured PHP?
[message] fopen(https://api.breathehr.com/v1/employees?page=1): failed
to open stream: No such file or directory
I have googled the error message and came across this SO post Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?
Making these changes has made no difference. It's worth noting this is on localhost, running MAMP.
Any ideas?
Thanks
Sometime the CLI use a different php.ini than Apache, so your settings made through the WAMP menu don't apply to CLI.
Check if the correct extension are loaded launching the
command php -i | grep ssl
In the same manner you can locate the php.ini script:
php -i | grep ini
hope this help

Lithium PHP integration testing - routes.php not included?

I'm building a toy app in Lithium (PHP framework) based upon the Union of RAD's Framework project. It's all working great in the browser but when running integration tests, routes.php is not loaded, so the routing isn't working.
Here's the code I'm testing:
class StaffController extends \lithium\action\Controller {
public function add() {
$staff = Staff::create();
if (($this->request->data) && $staff->save($this->request->data)) {
return $this->redirect(array('Staff::view', 'args' => array($staff->id)));
}
return compact('staff');
}
My test:
public function testAdd() {
//Router::connect('/{:controller}/{:action}/{:args}');
$request = new Request();
$request->data = array('name' => 'Brand new user');
$controller = new StaffController(array('request' => $request));
/* #var $response \lithium\action\Response */
$response = $controller->add();
$this->assertEqual(302, $response->status['code']);
}
Notice the commented out line - Router::connect('/{:controller}/{:action}/{:args}'); - if I uncomment that, it's all good.
What I'm puzzled about is why, when running in unit tests, app/config/routes.php (where I define my routes) isn't loaded. From what I can determine, app/config/bootstrap/action.php adds a filter to the "run" method of the Dispatcher which loads routes.php.
Of course, it's possible that I am totally missing the point here! I'd appreciate any guidance you can give me!
Lithium has a lithium\action\Dispatcher used for http requests and a lithium\console\Dispatcher for console commands.
I'm assuming you are running tests from the command-line. I'm looking at the "framework" project's app/config/bootstrap/action.php file (here on github).
It is only including the routes.php file for the lithium\action\Dispatcher which is not loaded from the command-line. The app/config/bootstrap/console.php also doesn't include routes.php for the console.
My suggestion is to edit the console.php file and change the filter to look like this:
Dispatcher::applyFilter('run', function($self, $params, $chain) {
Environment::set($params['request']);
foreach (array_reverse(Libraries::get()) as $name => $config) {
if ($name === 'lithium') {
continue;
}
$file = "{$config['path']}/config/routes.php";
file_exists($file) ? call_user_func(function() use ($file) { include $file; }) : null;
}
return $chain->next($self, $params, $chain);
});

error not found model after upload into hosting

In localhost, it works fine. After uploading into my hosting i got this error. I'm using zend framework 1.12.
Fatal error: Class 'Application_Models_DBTable_Kereta' not found in /home/mysite/public_html/application/controllers/CarController.php
others post said the problem is because the case sensitivity of file names. But i tried to change and nothing happens. See my attachment for the structured of my project. The attachment shown application and model names.
edited : This problem occurs to all my models class.. can't find models..
Controller code :
class CarController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
//klu login sbgai admin, papar layout admin, klu login sbgai user, papar layout user laaaa,
Zend_Session::start();//start session
$session = new Zend_Session_Namespace("MyNamespace");
$id_pengguna = $session->id_pengguna;
$kategori = $session->kategori;
if($kategori==3)
{
$this->_helper->layout->setLayout('layoutadmin');
}
else
{
}
}
public function indexAction()
{
// $albums = new Application_Model_DbTable_Albums();
//$this->view->albums = $albums->fetchAll();
}
public function reservationAction()
{
if($this->getRequest()->isPost())
{
$jadual_tarikhmula = $this->getRequest()->getPost("jadual_tarikhmula");
$jadual_tarikhtamat = $this->getRequest()->getPost("jadual_tarikhtamat");
$jadual_masamula1 = $this->getRequest()->getPost("jadual_masamula1");
$jadual_masamula2 = $this->getRequest()->getPost("jadual_masamula2");
$jadual_masatamat1 = $this->getRequest()->getPost("jadual_masatamat1");
$jadual_masatamat2 = $this->getRequest()->getPost("jadual_masatamat2");
$simpan = array($jadual_tarikhmula,$jadual_tarikhmula,$jadual_masamula1,$jadual_masatamat1);
$papar = $this->view->dataReserve= $simpan;
$db = new Application_Model_DbTable_Kereta();
$paparkereta = $this->view->reserve = $db->getReservationCar($jadual_tarikhmula,$jadual_tarikhmula,$jadual_masamula1,$jadual_masatamat1);
$this->view->dataWujud = count($paparkereta);
$gambar = $this->view->gambarKereta = $db->getGambarKereta($paparkereta[0]['id_kereta'],false);
}
}
}
Your folder name is DbTable and your model class name is ..._DBTable_... ?
Note that Linux is case-sensitive directory or filename.
And did you add this line to .ini file?
Appnamespace = "Application"
Are you sure you don't have another class named Kereta in /home/mysite/public_html/application/controllers/CarController.php ?
Also, consider cleaning the symfony cache with symfony cc. It's the cache for autoload that is giving you this error I guess.

Categories