Iam using a php class to add event to google calender.But the class return an error when loading index.php page.
This is the code in index.php page here iam calling class:
<?php
require_once('gcal.class.php');
$g = new gcal('test#gmail.com','test123$');
$cal_url = 'https://www.google.com/calendar/feeds/test#gmail.com/private-01d281d910a2622c8c2f5899690b9eb5/basic';
$eTitle = 'test event'; $eDesc = 'Another Test'; $eAuthorName = 'Justin Burger'; $eAuthorEmail = 'justin#loudisrelative.com'; $eLocation = 'LIR Offices'; $eStartTime = date('c'); $eEndTime = date('c',strtotime("+1 hour"));
//Adding an event.
$g->addEvent($cal_url,$eTitle, $eDesc, $eAuthorName, $eAuthorEmail,$eLocation,$eStartTime, $eEndTime);
?>
And this is the gcal.class.php code :
<?php
require_once('HTTP/Request.php');
class gcal{
/** Google Auth Token, used to authorize add functions*/
private $token;
/** Users Email Address (notice, password is not stored) */
private $email;
function __construct($email, $password){
$this->login($email,$password);
$this->email = $email;
}
public function addEvent($cal_url,$eTitle, $eDesc, $eAuthorName, $eAuthorEmail,$eLocation,$eStartTime, $eEndTime){
/* Make sure we send ONLY valid XML. */
$eTitle = htmlentities($eTitle);
$eDesc = htmlentities($eDesc);
$eAuthorName = htmlentities($eAuthorName);
$eAuthorEmail = htmlentities($eAuthorEmail);
$eLocation = htmlentities($eLocation);
$eStartTime = htmlentities($eStartTime);
$eEndTime = htmlentities($eEndTime);
$xml = "<entry xmlns='http://www.w3.org/2005/Atom' xmlns:gd='http://schemas.google.com/g/2005'>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>{$eTitle}</title>
<content type='text'>{$eDesc}</content>
<author>
<name>{$eAuthorName}</name>
<email>{$eAuthorEmail}</email>
</author>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'></gd:transparency>
<gd:eventStatus
value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:where valueString='{$eLocation}'></gd:where>
<gd:when startTime='{$eStartTime}'
endTime='{$eEndTime}'></gd:when>
</entry>";
$http = new HTTP_Request($cal_url,array('allowRedirects' => true));
$http->setMethod('POST');
$http->addHeader('Host','www.google.com');
$http->addHeader('MIME-Version','1.0');
$http->addHeader('Accept','text/xml');
$http->addHeader('Content-type','application/atom+xml');
$http->addHeader('Authorization','GoogleLogin auth=' . $this->token);
$http->addHeader('Content-length',strlen($xml));
$http->addHeader('Cache-Control','no-cache');
$http->addHeader('Connection','close');
$http->setBody($xml);
$http->sendRequest();
switch($http->getResponseCode()){
case 201: case 200:
return true;
break;
default:
throw new Exception('Error Adding Google Cal Event. Response From Google:' . $http->getResponseBody(), $http->getResponseCode());
return false;
break;
}
}
public function getCalendarList(){
$url = 'http://www.google.com/calendar/feeds/' . $this->email;
$http = new HTTP_Request($url,array('allowRedirects' => true));
$http->addHeader('Authorization','GoogleLogin auth=' . $this->token);
$http->setMethod('GET');
$http->sendRequest();
$xml = new SimpleXMLElement($http->getResponseBody());
$calendars = array();
foreach ($xml->entry as $cal){
foreach($cal->link as $key=>$link){
$linkSets = array();
$links = $link->attributes();
$links = (array) $links;
foreach($links as $l){
$linkSets[] = array('rel'=>$l['rel'],
'type'=>$l['type'],
'href'=>$l['href']);
}
}
$calendars[] = array('id'=>strval($cal->id),
'published'=>strval($cal->published),
'updated'=>strval($cal->updated),
'title'=>strval($cal->title),
'authorName'=>strval($cal->author->name),
'authorEmail'=>strval($cal->author->email),
'links'=>$linkSets);
}
return $calendars;
}
private function login($email, $password){
$url = 'https://www.google.com/accounts/ClientLogin';
$http = new HTTP_Request('https://www.google.com/accounts/ClientLogin',
array('allowRedirects' => true));
$http->setMethod('POST');
$http->addPostData('Email', $email);
$http->addPostData('Passwd', $password);
$http->addPostData('source', 'example-test-2');
$http->addPostData('service', 'cl');
$http->addPostData('accountType', 'HOSTED_OR_GOOGLE');
$http->sendRequest();
switch($http->getResponseCode()){
case 403:
throw new Exception('Google Auth Failed',403);
break;
case 200: case 201:
$this->token = $this->extractAuth($http->getResponseBody());
return true;
break;
default:
throw new Exception('Unknown Google Auth Failure',$http->getResponseCode());
break;
}
}
private function extractAuth($body){
$st = strpos($body,'Auth=');
$token = trim(substr($body,($st+5)));
return $token;
}
}
?>
Then iam taking this in browser it displays error:
Warning: require_once(HTTP/Request.php) [function.require-once]: failed to open stream: No such file or directory in E:\wamp\www\gcal\gcal.class.php on line 2
Fatal error: require_once() [function.require]: Failed opening required 'HTTP/Request.php' (include_path='.;C:\php\pear') in E:\wamp\www\gcal\gcal.class.php on line 2
What is the problem in my code?
When i downloading the class from google code they said that please make sure you have both installed before use (for example: pear install Net and pear install HTTP) .
I dont know how to do this?Give me a solution.
You need to install HTTP_Request package in order to make it work. The package can be found here
See here for installation
Hope it helps
First, check in your 'php' folder if 'PEAR' folder exists. If doesn't then install PEAR (instruction: http://pear.php.net/manual/en/installation.php).
If so check in 'php.ini' if parameter 'include_path' has absolute path to 'PEAR' folder (e.g. on Windows: include_path = ".;C:\xampp\php\PEAR")
Regards
Bronek
Related
I'm trying to add new users to moodle 3.2 using a REST web service, and i want to customize thees fields (phone1, department, institution) in the student profile.
I used this code
$token = 'a38805c00f33023f7854d5adc720c7a7';
$domainname = 'http://localhost/moodle';
$functionname = 'core_user_create_users';
$restformat = 'json';
$user2 = new stdClass();
$user2->username = strtolower( $rsnew['Serial']);
$user2->password = $rsnew['pass'];
$user2->firstname = $rsnew['Fname'];
$user2->lastname = $rsnew['Lname'];
$user2->email = $rsnew['Email'];
$user2->lang = 'en';
$user2->auth = 'manual';
$user2->country = $rsnew['Country'];
$user2->timezone = '99';
$user2->phone1 = $rsnew['phone'];
$user2->department = $rsnew['dept'];
$user2->institution = $rsnew['branch'];
$user2->idnumber = $rsnew['grade'];
$users = array($user2);
$params = array('users' => $users);
$serverurl = $domainname . '/webservice/rest/server.php'. '?wstoken=' . $token . '&wsfunction='.$functionname;
require_once('./curl.php');
$curl = new curl;
$restformat = ($restformat == 'json')?'&moodlewsrestformat=' . $restformat:'';
$resp = $curl->post($serverurl . $restformat, $params);
But i get this error :
{
"exception": "invalid_parameter_exception",
"errorcode": "invalidparameter",
"message": "Invalid parameter value detected",
"debuginfo": "users => Invalid parameter value detected: Unexpected keys (phone1, department, institution) detected in parameter array."
}
What should I do to fix that?
Just as the error suggests, that web service does not support the fields you are giving it. You can refer to the function itself to find out what fields are supported and what data they must contain.
core_user_get_users
I am not aware of a workaround for your problem using existing web services. However, you can create your own which includes those additional fields.
Note that this sounds to me like this is a desirable feature and should be raised on the issue tracker.
I'm implementing a moodle web service on localhost.
I followed all the steps to register the service, and I have the token to make the corresponding calls.
I have used the template for REST PHP by Jerome Mouneyrac (https://github.com/moodlehq/sample-ws-clients/blob/master/PHP-REST/client.php).
My code:
$token = '60d4aef82f787b7a0c8499a648a6a919';
$domainname = 'http://localhost/moodle';
$functionname = 'core_user_create_users';
$restformat = 'json';
$user1 = new stdClass();
$user1->username = 'testo';
$user1->password = 'Password_2015';
$user1->createpassword = 0;
$user1->firstname = 'testfirstname1';
$user1->lastname = 'testlastname1';
$user1->email = 'muletssss#gmail.com';
$user1->auth = 'manual';
$user1->idnumber = '';//'testidnumber1';
$user1->lang = 'es';
$user1->theme = "standard";
$user1->timezone = '-12.5';
$user1->mailformat = 0;
$user1->description = 'Hello World!';
$user1->city = 'testcity1';
$user1->country = 'au';
$users = array($user1);//, $user2);
$params = array('users' => $users);
$serverurl = $domainname . '/webservice/rest/server.php'. '?wstoken=' . $token . '&wsfunction='.$functionname;
require_once('./curl.php');
$curl = new curl;
$restformat = ($restformat == 'json')?'&moodlewsrestformat=' . $restformat:'';
$resp = $curl->post($serverurl . $restformat, $params);
print_r($resp);
If I execute it returns this response
{"exception":"invalid_parameter_exception","errorcode":"invalidparameter","message":"Detectado valor de par\u00e1metro no v\u00e1lido","debuginfo":"users => Detectado valor de par\u00e1metro no v\u00e1lido: theme => Detectado valor de par\u00e1metro no v\u00e1lido: Invalid external api parameter: the value is \"standard\", the server was expecting \"theme\" type"}
The API documentation says that the value is string and standard default, so I comment this line because it is optional. And returns
{"exception":"moodle_exception","errorcode":"forcepasswordchangenotice","message":"error\/forcepasswordchangenotice"}
Does anyone know what I can do to work correctly, any solution?
I was facing a similar issue, I have solved it. The issue was that the user that I was using for the web services had force password reset checked while creation. I had not logged in once the user was created and was only using it for the Webservice. Hence I was this error was showing up. I unchecked force password reset from my admin account and it was solved.
I'm updating a PHP application to create new email accounts in Google (using the Google Directory Service). I have no problem creating the account, but so far I've been unable to use the Google Gmail Service to set the sendAsEmail attribute (so that the alias will show up in the "From"). Also, var_dump($createSendAsResult) in the snippet below does not produce any output. Any help would be appreciated. Thanks!
Here's my code:
//Create account in Google
function createGoogleAccount($server_name, $acc_user, $acc_password)
{
$clientDir = getClientDir($server_name);
$dirService = new Google_Service_Directory($clientDir);
$userInstance = new Google_Service_Directory_User();
$nameInstance = new Google_Service_Directory_UserName();
$nameInstance -> setGivenName('Generic');
$nameInstance -> setFamilyName($acc_user);
$userInstance -> setOrgUnitPath("/generic_email");
$userInstance -> setName($nameInstance);
$userInstance -> setHashFunction("MD5");
$domain = getDomain($server_name);
$primary_email = $acc_user . '#' . $domain;
$userInstance -> setPrimaryEmail($primary_email);
$userInstance -> setPassword(hash("md5", $acc_password));
$optParams = array( );
$error_msg = null;
try
{
$createUserResult = $dirService->users->insert($userInstance, $optParams);
var_dump($createUserResult);
}
catch (Google_IO_Exception $gioe)
{
$error_msg = "Error in connection: ".$gioe->getMessage();
}
catch (Google_Service_Exception $gse)
{
$error_msg = "Service Exception: ".$gse->getMessage();
}
addSendAs($server_name, $acc_user, $domain); return $error_msg;
}
function addSendAs($server_name, $acc_user, $domain)
{
$clientGmail = getClientGmail($server_name);
$gmailService = new Google_Service_Gmail($clientGmail);
$primary_email = $acc_user . '#' . $domain;
$sendAsEmail = new Google_Service_Gmail_SendAs();
$alias = '';
if (($server_name == null) || (strpos($server_name, "dev") != false))
{
$alias = '#g.';
}
else
{
$alias = '#mail.';
}
$sendAsEmail -> setSendAsEmail($acc_user . $alias . $domain);
$sendAsEmail -> setIsDefault(TRUE);
$sendAsEmail -> setIsPrimary(TRUE);
$error_msg = null;
try
{
$createSendAsResult = $gmailService->users_settings_sendAs -> create($primary_email, $sendAsEmail);
var_dump($createSendAsResult);
}
catch (Google_IO_Exception $gioe)
{
$error_msg = "Error in connection: ".$gioe->getMessage();
}
catch (Google_Service_Exception $gse)
{
$error_msg = "Service Exception: ".$gse->getMessage();
}
}
Finally, after much experimentation with the code and some help from a couple of colleagues, I figured out what the problem is and how to solve it.
Apparently, Google needs time to set up a new user's account with email. When I added a 10-second delay - sleep(10) in php - that was sufficient for the account to be ready for calls to the Gmail API, including the creation of a SendAs alias.
I tried to convert a pdf file to an image.
I check this website, and follow all step instructions.
1.obtain an api license key
2.download the API Class
3.Deploy the php file
4.create my pdf file
But when i run my file happens this error:
ERROR
Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://apis.pdfaid.com/pdfaidservices/Service1.svc?wsdl' : failed to load external entity "http://apis.pdfaid.com/pdfaidservices/Service1.svc?wsdl" in C:\xampp\htdocs\Web_V2\PdfaidServices.php:128 Stack trace: #0 C:\xampp\htdocs\Web_V2\PdfaidServices.php(128): SoapClient->SoapClient('http://apis.pdf...', Array) #1 C:\xampp\htdocs\Web_V2\teste_1.php(32): Pdf2Jpg->Pdf2Jpg() #2 {main} thrown in C:\xampp\htdocs\Web_V2\PdfaidServices.php on line 128
The part of the bold code is where raises the error
Could anyone help me please?
I would forever gratefull.
This is my file
<?php
include 'PdfaidServices.php';
$myPdf2Jpg = new Pdf2Jpg();
$myPdf2Jpg->apiKey = "xxxxxxxxxx";
$myPdf2Jpg->inputPdfLocation = "pdf_file.pdf";
$myPdf2Jpg->outputZipLocation = "UploadedPdf/pdf2jpg.zip";
$myPdf2Jpg->outputImageFormat = ".jpg";
$myPdf2Jpg->imageQuality = 50;
$result = $myPdf2Jpg->Pdf2Jpg();
?>
This is API Class PdfaidServices.php where erros happens
<?php
class Xps2PdfConverter
{
public $apiKey = "";
public $inputXpsLocation = "";
public $outputPdfLocation = "";
public $pdfAuthor = "";
public $pdfTitle = "";
public $pdfSubject = "";
public $pdfKeywords = "";
function Xps2PdfConvert()
{
if($this->apiKey == "")
return "Please specify ApiKey";
if($this->outputPdfLocation == "")
return "Please specify location to save output Pdf";
if($this->inputXpsLocation == "")
return "Please specify input XPS file Location";
else
{
$fileStream = file_get_contents($this->inputXpsLocation);
}
$parameters = array("FileByteStream" => $fileStream);
$wsdl = "http://apis.pdfaid.com/pdfaidservices/Service1.svc?wsdl";
$endpoint = "http://apis.pdfaid.com/pdfaidservices/Service1.svc";
$option=array('trace'=>1);
$client = new SoapClient($wsdl, $option);
$headers[] = new SoapHeader('http://tempuri.org/', 'apikey', $this->apiKey);
$headers[] = new SoapHeader('http://tempuri.org/', 'pdfTitle', $this->pdfTitle);
$headers[] = new SoapHeader('http://tempuri.org/', 'pdfAuthor', $this->pdfAuthor);
$headers[] = new SoapHeader('http://tempuri.org/', 'pdfSubject', $this->pdfSubject);
$headers[] = new SoapHeader('http://tempuri.org/', 'pdfKeywords', $this->pdfKeywords);
$headers[] = new SoapHeader('http://tempuri.org/', 'responseResult', "test");
$client->__setSoapHeaders($headers);
$result = $client->Xps2Pdf($parameters);
$clientResponse = $client->__getLastResponse();
if($clientResponse == "APINOK")
return "API is not Valid";
if($clientResponse == "NOK")
return "Error Occured";
else
{
$fp = fopen($this->outputPdfLocation, 'wb');
fwrite($fp, $result->FileByteStream);
fclose($fp);
return "OK";
}
}
}
class Pdf2Jpg
{
public $apiKey = "";
public $outputImageFormat = "";
public $inputPdfLocation = "";
public $outputZipLocation = "";
public $imageQuality = 50;
function Pdf2Jpg()
{
if($this->apiKey == "")
return "Please specify ApiKey";
if($this->outputImageFormat == "")
return "Please specify Output Image Format";
if($this->outputZipLocation == "")
return "Please specify Output Zip File Location";
if($this->inputPdfLocation == "")
return "Please specify input Pdf file Location";
else
{
$fileStream = file_get_contents($this->inputPdfLocation);
}
$parameters = array("FileByteStream" => $fileStream);
$wsdl = "http://apis.pdfaid.com/pdfaidservices/Service1.svc?wsdl";
$endpoint = "http://apis.pdfaid.com/pdfaidservices/Service1.svc";
$option=array('trace'=>1);
$client = new SoapClient($wsdl, $option);
$headers[] = new SoapHeader('http://tempuri.org/', 'apikey', $this->apiKey);
$headers[] = new SoapHeader('http://tempuri.org/', 'outputFormat', $this->outputImageFormat);
$headers[] = new SoapHeader('http://tempuri.org/', 'imageQuality', $this->imageQuality);
$headers[] = new SoapHeader('http://tempuri.org/', 'responseResult', "test");
$client->__setSoapHeaders($headers);
$result = $client->Pdf2Jpg($parameters);
$clientResponse = $client->__getLastResponse();
if($clientResponse == "APINOK")
return "API is not Valid";
if($clientResponse == "NOK")
return "Error Occured";
else
{
$fp = fopen($this->outputZipLocation, 'wb');
fwrite($fp, $result->FileByteStream);
fclose($fp);
return "OK";
}
}
}
?>
Please!! Someone can help me please?
Works fine from my machine. Do you have network connectivity to the said wsdl? What happens when you stick that wsdl URL in a browser?
i am using the below code to connect to salesforce using php
require_once ('SforcePartnerClient.php');
require_once ('SforceHeaderOptions.php');
require_once ('SforceMetadataClient.php');
$mySforceConnection = new SforcePartnerClient();
$mySforceConnection->createConnection("cniRegistration.wsdl");
$loginResult = $mySforceConnection->login("username", "password.token");
$queryOptions = new QueryOptions(200);
try {
$sObject = new stdclass();
$sObject->Name = 'Smith';
$sObject->Phone = '510-555-5555';
$sObject->fieldsToNull = NULL;
echo "**** Creating the following:\r\n";
$createResponse = $mySforceConnection->create($sObject, 'Account');
$ids = array();
foreach ($createResponse as $createResult) {
print_r($createResult);
array_push($ids, $createResult->id);
}
} catch (Exception $e) {
echo $e->faultstring;
}
But the above code is connect to salesforce database.
But is not executing the create commands. it's giving me the below error message
Creating the following: Element {}item invalid at this location
can any one suggest me to overcome the above problem
MAK, in your sample code SessionHeader and Endpoint setup calls are missing
$mySforceConnection->setEndpoint($location);
$mySforceConnection->setSessionHeader($sessionId);
after setting up those, if you still see an issue, check the namespace urn
$mySforceConnection->getNamespace
It should match targetNamespace value in your wsdl
the value of $mySforceConnection should point to the xml file of the partner.wsdl.xml.
E.g $SoapClient = $sfdc->createConnection("soapclient/partner.wsdl.xml");
Try adding the snippet code below to reference the WSDL.
$sfdc = new SforcePartnerClient();
// create a connection using the partner wsdl
$SoapClient = $sfdc->createConnection("soapclient/partner.wsdl.xml");
$loginResult = false;
try {
// log in with username, password and security token if required
$loginResult = $sfdc->login($sfdcUsername, $sfdcPassword.$sfdcToken);
}
catch (Exception $e) {
global $errors;
$errors = $e->faultstring;
echo "Fatal Login Error <b>" . $errors . "</b>";
die;
}
// setup the SOAP client modify the headers
$parsedURL = parse_url($sfdc->getLocation());
define ("_SFDC_SERVER_", substr($parsedURL['host'],0,strpos($parsedURL['host'], '.')));
define ("_SALESFORCE_URL_", "https://test.salesforce.com");
define ("_WS_NAME_", "WebService_WDSL_Name_Here");
define ("_WS_WSDL_", "soapclient/" . _WS_NAME_ . ".wsdl");
define ("_WS_ENDPOINT_", 'https://' . _SFDC_SERVER_ . '.salesforce.com/services/wsdl/class/' . _WS_NAME_);
define ("_WS_NAMESPACE_", 'http://soap.sforce.com/schemas/class/' . _WS_NAME_);
$urlLink = '';
try {
$client = new SoapClient(_WS_WSDL_);
$sforce_header = new SoapHeader(_WS_NAMESPACE_, "SessionHeader", array("sessionId" => $sfdc->getSessionId()));
$client->__setSoapHeaders(array($sforce_header));
} catch ( Exception $e ) {
die( 'Error<br/>' . $e->__toString() );
}
Please check the link on Tech Thought for more details on the error.