I'm playing around with Cloud Translation API v3 in PHP. I went through setup process and tried simple translation shown here and it worked. Then I wanted to test glossaries so I tried to add one as described here. When I'm trying to call the function:
protected function createGlossary()
{
$translationServiceClient = new TranslationServiceClient();
$projectId = 'my-project-id';
$glossaryId = 'my-new-glossary';
$inputUri = 'gs://bucket/file.csv';
$formattedParent = $translationServiceClient->locationName(
$projectId,
'us-central1'
);
$formattedName = $translationServiceClient->glossaryName(
$projectId,
'us-central1',
$glossaryId
);
$languageCodesElement = 'pl';
$languageCodesElement2 = 'en';
$languageCodes = [$languageCodesElement, $languageCodesElement2];
$languageCodesSet = new LanguageCodesSet();
$languageCodesSet->setLanguageCodes($languageCodes);
$gcsSource = (new GcsSource())
->setInputUri($inputUri);
$inputConfig = (new GlossaryInputConfig())
->setGcsSource($gcsSource);
$glossary = (new Glossary())
->setName($formattedName)
->setLanguageCodesSet($languageCodesSet)
->setInputConfig($inputConfig);
try {
$operationResponse = $translationServiceClient->createGlossary(
$formattedParent,
$glossary
);
$operationResponse->pollUntilComplete();
if ($operationResponse->operationSucceeded()) {
$response = $operationResponse->getResult();
printf('Created Glossary.' . PHP_EOL);
printf('Glossary name: %s' . PHP_EOL, $response->getName());
printf('Entry count: %s' . PHP_EOL, $response->getEntryCount());
printf(
'Input URI: %s' . PHP_EOL,
$response->getInputConfig()
->getGcsSource()
->getInputUri()
);
} else {
$error = $operationResponse->getError();
// handleError($error)
}
} finally {
$translationServiceClient->close();
}
}
it returns an error:
Failed to build request, as the provided path (google.longrunning.Operations/GetOperation) was not found in the configuration.
It throws error at $operationResponse->pollUntilComplete();. The file in bucket contains just one line - test,test.
Then when I try to call function that lists all glossaries, it works but it doesn't return any.
What can cause this problem and how do I add glossary?
You need to install gRPC extension for PHP.
Info: https://cloud.google.com/php/grpc
Install gRPC for PHP
gRPC is a modern, open-source, high-performance remote procedure call framework. If you want to use PHP client libraries for gRPC-enabled APIs, you must install gRPC for PHP. This tutorial explains how to install and enable gRPC.
Install the gRPC extension for PHP.
sudo pecl install grpc
Enable the gRPC extension for PHP.
Add this line anywhere in your php.ini file, for example, /etc/php7/cli/php.ini. You can find this file by running php --ini.
extension=grpc.so
Related
I want to use https://github.com/HelloFax/hellosign-php-sdk in Yii2 project so I followed following step
1 ) updated composer.json with "hellosign/hellosign-php-sdk": "3.*#dev" in require section
2) run composer update in CMD (I work with window 7)
so it downloaded required libraries (hellosign-php-sdk and libary) in vendor
3 ) include following code in controller file
$client = new HelloSign\Client('df754dd564e52fb2891a60eb2fea777b5320397********');
$response = $client->getSignatureRequest('f6197945000616b383d4752*****');
if ($response->isComplete()) {
echo 'All signers have signed this request.';
} else {
foreach ($response->getSignatures() as $signature) {
echo $signature->getStatusCode() . "\n";
}
}
Error
Unable to find 'app\controllers\HelloSign\Client' in file: C:\wamp\www\yii2hellosign/controllers/HelloSign/Client.php. Namespace missing?
How to solve this issue, any help ?
the library use psr-0 autoload, so you need to prepend classname with \ , like this:
$client = new \HelloSign\Client('...');
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
I am using OpenFire to manage my xmpp server I want to add new users using a PHP, So I have installed RESETAPI Plugin to OpenFire to administrate with http request. I am using gidkom Project also. But getting a error
Parse error: syntax error, unexpected T_VARIABLE in C:\wamp\www\IM\registration.php on line 12
My code for registration.php is:
<?php
if(isset($_POST["User_Name"]) && isset($_POST["Name"]) )
{
$User_ID = $_POST["User_Name"];
$User_Name = $_POST["Name"];
$User_Email = $_POST["Email"];
include "Gidkom/OpenFireRestApi/OpenFireRestApi.php";
// Create the OpenfireUserservice object
$api = new Gidkom\OpenFireRestApi
// Set the required config parameters
$api->secret = "my keys";
$api->host = "domain.my.org";
$api->port = "9090"; // default 9090
// Optional parameters (showing default values)
$api->useSSL = false;
$api->plugin = "/plugins/restapi/v1"; // plugin
// Add a new user to OpenFire and add to a group
$result = $api->addUser($User_ID, 'Password', $User_Name, $User_Email, array('welcome'));
// Check result if command is succesful
if($result['status']) {
// Display result, and check if it's an error or correct response
echo 'Success: ';
echo $result['message'];
} else {
// Something went wrong, probably connection issues
echo 'Error: ';
echo $result['message'];
}
//Add to roster
$api->addToRoster('Administrator', 'admin');
}
else
{
echo 'Error: Something went wrong..... please go back ';
}
I want the page to add a new new user in the openfire and add admin to his roster.
Thanks !!!!
Semicolon is missing.
$api = new Gidkom\OpenFireRestApi\OpenFireRestApi;
The errors were caused because of an outdated version of PHP, YPdating PHP to latest version fixed it...
prerequirements: must to have composer.exe installed on your machine
from cmd.exe
go to your web root server(htdocs) then
go into your directory which contain the rest api sources
then from this cmd.exe(or create one batch)
c:/..../....> composer install
Remark: -this commnad(composer install) must to have in same directory the composer.json
-this command(composer install) will create one subdirectory "vendor" named
now into your index.php must insert on top, the following line:
<?php
include "vendor/autoload.php";
....
and continue your actual program
and is trully must to end the lines with ;
...
?
https://github.com/gnello/php-openfire-restapi
Easy Php REST API Client for the Openfire REST API Plugin which provides the ability to manage Openfire instance by sending an REST/HTTP request to the server
Please read documentation for further information on using this application.
Installation
composer require gnello/php-openfire-restapi
Authentication
There are two ways to authenticate:
Basic HTTP Authentication
$authenticationToken = new \Gnello\OpenFireRestAPI\AuthenticationToken('your_user', 'your_password');
Shared secret key
$authenticationToken = new \Gnello\OpenFireRestAPI\AuthenticationToken('your_secret_key');
Start
$api = new \Gnello\OpenFireRestAPI\API('your_host', 9090, $authenticationToken);
Users
//Add a new user
$properties = array('key1' => 'value1', 'key2' => 'value2');
$result = $api->Users()->createUser('Username', 'Password', 'Full Name', 'email#domain.com', $properties);
//Delete a user
$result = $api->Users()->deleteUser('Username');
//Ban a user
$result = $api->Users()->lockoutUser('Username');
//Unban a user
$result = $api->Users()->unlockUser('Username');
Open Link Fore more.
Is there any PHP class or resource for using Metaweblog api ?
I want to add this api to my own cms (like wp) so that other application could easily post (or ...) throw it
Implementation of the MetaWeblog API http://www.xmlrpc.com/metaWeblogApi in PHP.
I looked to this script I linked for inspiration to develop the implementation I'm currently using. Feel free to use the example code below as an example of implementing the metaweblog API - but please consider using a modern XMLRPC library. I've included a link to a modified version of the original "xmlrpc.php" file that the example code requires.
Here's the xmlrpc library the example code utilizes: XMLRPC library modified to work with PHP 5.4 - originally written by Keith Devens.
Doing a quick package search on packagist also provides many great options that are much more forward thinking in terms of PHP standards. ZendFramework2 even includes a component you can use in your project with minimal dependencies (10 packages - not the entire framework). I would strongly recommend that this example code, be used as such, and any new development be done with a modern XMLRPC library.
Adding the example code here in case the first link dies:
<?php
/**
* Skeleton file for MetaWeblog API http://www.xmlrpc.com/metaWeblogApi in PHP
* Requires Keith Devens' XML-RPC Library http://keithdevens.com/software/xmlrpc and store it as xmlrpc.php in the same folder
* Written by Daniel Lorch, based heavily on Keith Deven's examples on the Blogger API.
*/
require_once dirname(__FILE__) . '/xmlrpc.php';
function metaWeblog_newPost($params) {
list($blogid, $username, $password, $struct, $publish) = $params;
$title = $struct['title'];
$description = $struct['description'];
// YOUR CODE:
$post_id = 0; // id of the post you just created
XMLRPC_response(XMLRPC_prepare((string)$post_id), WEBLOG_XMLRPC_USERAGENT);
}
function metaWeblog_editPost($params) {
list($postid, $username, $password, $struct, $publish) = $params;
// YOUR CODE:
$result = false; // whether or not the action succeeded
XMLRPC_response(XMLRPC_prepare((boolean)$result), WEBLOG_XMLRPC_USERAGENT);
}
function metaWeblog_getPost($params) {
list($postid, $username, $password) = $params;
$post = array();
// YOUR CODE:
$post['userId'] = '1';
$post['dateCreated'] = XMLRPC_convert_timestamp_to_iso8601(time());
$post['title'] = 'Replace me';
$post['content'] = 'Replace me, too';
$post['postid'] = '1';
XMLRPC_response(XMLRPC_prepare($post), WEBLOG_XMLRPC_USERAGENT);
}
function XMLRPC_method_not_found($methodName) {
XMLRPC_error("2", "The method you requested, '$methodName', was not found.", WEBLOG_XMLRPC_USERAGENT);
}
$xmlrpc_methods = array(
'metaWeblog.newPost' => 'metaWeblog_newPost',
'metaWeblog.editPost' => 'metaWeblog_editPost',
'metaWeblog.getPost' => 'metaWeblog_getPost'
);
$xmlrpc_request = XMLRPC_parse($HTTP_RAW_POST_DATA);
$methodName = XMLRPC_getMethodName($xmlrpc_request);
$params = XMLRPC_getParams($xmlrpc_request);
if(!isset($xmlrpc_methods[$methodName])) {
XMLRPC_method_not_found($methodName);
} else {
$xmlrpc_methods[$methodName]($params);
}
I'm trying to write some code to track dependencies. Is there a way to programatically detect if a PEAR package has been installed? I'm thinking something like:
if ($some_pear_api->isPackageInstalled('FooPack')) {
echo 'FooPack is installed!';
} else {
echo 'FooPack is not installed. :(';
}
I know you can simply detect if the class file for that package exists, but I mostly want to know if PEAR has that installed because sometimes some libraries provide other means of including their code (e.g. PHPUnit has a pear channel as well as a git repo.).
Thanks for the help!
You need to use the PEAR_Registry class to do this (which is what the PEAR script itself uses).
Read Adam Harvey's blog post "pear -> list" from 3 years ago - all the details/examples you need are there.
include 'PEAR/Registry.php';
$reg = new PEAR_Registry;
foreach ($reg->listPackages() as $package) {
print "$package\n";
}
If you need this to check for specific versions of each package, then you could base something on the following example, which I provided in a comment to that blog entry:
<?php
require 'PEAR/Registry.php';
$reg = new PEAR_Registry;
define("NAME", 0);
define("VERSION", 1);
$packages = array(
array("PEAR", "1.6.2"),
array("Date", "1.4.7"),
array("Date_Holidays", "0.17.1"),
array("Validate_IE", "0.3.1")
);
foreach ($packages as $package) {
$pkg = $reg->getPackage($package[NAME]);
$version = $pkg->getVersion();
echo "{$package[NAME]} – {$package[VERSION]} – ";
echo version_compare($version, $package[VERSION], '>=') ? 'OK': 'BAD', "\n";
}
?>
If you need to copy and paste this, then it might be best for you to use the version at https://gist.github.com/kenguest/1671361.
You can use Pear/Infos packageInstalled to answer this:
<?php
require_once 'PEAR/Info.php';
$res = PEAR_Info::packageInstalled('FooPack');
if ($res) {
print "Package FooPack is installed \n";
} else {
print "Package FooPack is not yet installed \n";
}
?>
Why not just include the package and see if the class exists?
// Supress Errors. Checking is done below.
#require_once 'PHP/UML.php';
if(!class_exists('PHP_UML'))
{
throw new Exception('PHP_UML is not installed. Please call `pear install PHP_UML` from the command line',1);
}
// Code to use PHP_UML below...
$uml = new PHP_UML();