How to clear all events in Google Calendar using API V3 PHP - google-calendar-api

I spent a long time to work out how to do the following using Google Calendar using API V3 in PHP
insert a new event
read all existing events
delete each existing event
However I would still like to know how to clear an entire Google Calendar to make my code faster, as the read & delete method is a little slow.
I've been trying to work out how to use the supplied Google function "clear" for this, and the documentation supplied by Google simply shows that I should be able to use the following command to achieve this:
$service->calendars->clear('primary');
Also within the Google Code there is a comment relating to the "calendars" collection of methods (where the clear function exists):
Typical usage is:
<code>
$calendarService = new Google_Service_Calendar(...);
$calendars = $calendarService->calendars;
</code>
So I've put this together with the preceding authentication code. I am sure the authentication is working OK as I've used that elsewhere, but the clear code is obviously wrong as I get error message:
Notice: Undefined variable: service in C:\wamp\www\googleapi\clear\index.php on line 39
I've tried using 'primary' as well as the main owner, and I've tried making the calendar private and public but to no avail.
Anyone who has got the clear method to work, please point me in the right direction.
This is the code I'm running so far:
<?php
session_start();
require_once '../google-api-php-client-master/autoload.php';
//Google credentials
$client_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com';
$service_account_name = 'xxxxxxxxxxxxxxxxxxxxxx#developer.gserviceaccount.com';
$key_file_location = '../google-api-php-client-master/API Project-xxxxxxx.p12';
if (!strlen($service_account_name) || !strlen($key_file_location))
echo missingServiceAccountDetailsWarning();
$client = new Google_Client();
$client->setApplicationName("Whatever the name of your app is");
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/calendar'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
try {
$client->getAuth()->refreshTokenWithAssertion($cred);
} catch (Exception $e) {
var_dump($e->getMessage());
}
}
$_SESSION['service_token'] = $client->getAccessToken();
/* ------------------------- We are now properly authenticated ------------------- */
$calendarService = new Google_Service_Calendar($client);
$calendars = $calendarService->calendars;
$service->calendars->clear('primary');
?>

Just use your service calendar instance.
$service = new Google_Service_Calendar($client);
$calendar = $service->calendars->clear('primary');

Related

Google Cloud Vision PHP — Make Batch Request

I need to perform an OCR analysis on an image for an university project.
I am imposed to use PHP, unfortunately, on the Google Cloud Vision Documentation few are the code sample using PHP...
I succeed to perform OCR on one image at time but 80% of the time I have a lot of images (around 20) to treat at once.
So I tried to use BatchRequest, to minimize the API calls, as specified here but I can't found how to build the $requests array they put at the top.
Btw I tried other APIs like Tesseract but the recognition is not accurate enough to use.
If you only want to perform a batch request you can just use batchAnnotateImages using ImageAnnotatorClient. Below you can find a sample using it as well as a way to create a request variable. Also, I include below a asyncBatchAnnotateImages sample but I recommend the one I mentioned earlier.
Using ImageAnnotatorClient with batchAnnotateImages
<?php
require '../vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Vision\V1\Feature;
use Google\Cloud\Vision\V1\Feature_Type;
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
use Google\Cloud\Vision\V1\Image;
use Google\Cloud\Vision\V1\ImageSource;
use Google\Cloud\Vision\V1\AnnotateImageRequest;
use Google\Cloud\Vision\V1\Likelihood;
$client = new ImageAnnotatorClient();
try {
$feature = (new Feature())
->setType(Feature_Type::FACE_DETECTION);
$image = (new Image())
->setContent(file_get_contents("../images/family.jpg","r"));
$request = (new AnnotateImageRequest())
->setImage($image)
->setFeatures([$feature]);
$requests = [$request];
# note: you can add as many requests you want to perform. ie: [$request,$request2,..,..]
$results = $client->batchAnnotateImages($requests);
foreach($results->getResponses() as $result){
foreach ($result->getFaceAnnotations() as $faceAnnotation) {
$likelihood = Likelihood::name($faceAnnotation->getJoyLikelihood());
echo "Likelihood of headwear: $likelihood" . PHP_EOL;
}
}
} finally {
$client->close();
}
Using ImageAnnotatorClient with asyncBatchAnnotateImages
<?php
require '../vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Vision\V1\Feature;
use Google\Cloud\Vision\V1\Feature_Type;
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
use Google\Cloud\Vision\V1\Image;
use Google\Cloud\Vision\V1\ImageSource;
use Google\Cloud\Vision\V1\AnnotateImageRequest;
use Google\Cloud\Vision\V1\asyncBatchAnnotateImages;
use Google\Cloud\Vision\V1\OutputConfig;
use Google\Cloud\Vision\V1\GcsDestination;
$client = new ImageAnnotatorClient();
try {
$feature = (new Feature())
->setType(Feature_Type::FACE_DETECTION);
$gcsImageUri = 'gs://<YOUR BUCKET ID>/<YOUR IMAGE FILE>';
$source = new ImageSource();
$source->setImageUri($gcsImageUri);
$image = (new Image())
->setSource($source);
$request = (new AnnotateImageRequest())
->setImage($image)
->setFeatures([$feature]);
$requests = [$request];
$gcsDestination = (new GcsDestination())
->setUri("gs://<YOUR BUCKET>/<OUTPUT FOLDER>/");
$outputConfig = (new OutputConfig())
->setGcsDestination($gcsDestination);
$operationResponse = $client->asyncBatchAnnotateImages($requests, $outputConfig);
$operationResponse->pollUntilComplete();
if ($operationResponse->operationSucceeded()) {
$result = $operationResponse->getResult();
var_dump($result);
#Your Folder output will have your file processing results.
}
} finally {
$client->close();
}
Note: To add on this, you can also check an official implementation of a similar case using vision client on this link but its a sample to detect text on a pdf file.
You can also find additional information on these links:
ImageAnnotatorClient
AnnotateImageRequest
AsyncBatchAnnotateImages
BatchAnnotateImagesResponse
AsyncBatchAnnotateImagesResponse
PHP CLOUD VISION Github Project Page

Mocking a GuzzleHttp response

How should I mock a Guzzle response properly. When testing a parser I'm writing, the test html is contained in files. In my PHPUnit tests I'm doing file_read_contents and passing the result into my method. Occasionally the HTML will link to a seperate file. I can mock this response like so:
public function testAlgo()
{
$mock = new MockAdapter(function() {
$mockhtml = file_get_contents($this->dir . '/HTML/authorship-test-cases/h-card_with_u-url_that_is_also_rel-me.html');
$stream = Stream\create($mockhtml);
return new Response(200, array(), $stream);
});
$html = file_get_contents($this->dir . '/HTML/authorship-test-cases/h-entry_with_rel-author_pointing_to_h-card_with_u-url_that_is_also_rel-me.html');
$parser = new Parser();
$parser->parse($html, $adaptor = $mock);
Then in my actual method, when I make the guzzle request this code works:
try {
if($adapter) {
$guzzle = new \GuzzleHttp\Client(['adapter' => $adapter]);
} else {
$guzzle = new \GuzzleHttp\Client();
}
$response = $guzzle->get($authorPage);
So obviously this isn't ideal. Does anyone know of a better way of doing this?
$html = (string) $response->getBody();
EDIT: I'm now using the __construct() methid to set up a default Guzzle Client. Then a using a second function that can be called by tests to replace the Client with a new Client that has the mock adapter. I'm not sure if this is the best way to do things.
You can use the MockPlugin API, like so:
$plugin = new MockPlugin();
$plugin->addResponse(__DIR__.'/twitter_200_response.txt');
The txt file then contains everything from your response, including headers.
There are also good approaches available here: http://www.sitepoint.com/unit-testing-guzzlephp/
Also there are articles found here: http://guzzle3.readthedocs.io/testing/unit-testing.html

Send Gravity Forms data to redirection page

I have a very simple form created with Gravity Forms;
It submits two numbers and then redirects to a different result page.
How do I retrieve those two numbers on the result page?
add_filter("gform_confirmation_4", "custom_confirmation", 3, 4 );
function custom_confirmation($confirmation, $form, $lead, $ajax)
Gives a custom confirmation. Each field value can be retrieved by using $lead[{field ID}]
I have a solution for this based on using a combination of form submission hooks and the GForms API. It's a horrible plugin so I apologise for the messiness of the logic flow. It's important to use the framework methods rather than processing the data yourself since there are a good amount of hacks and shonky things going on in there to correctly match field IDs and so forth.
I will provide a solution to pass a submission from one form to pre-populate another. Changing the destination for POST data is pretty straightforward, they have an example for it on their gform_form_tag hook documentation page. Yes, that really is the only way of doing it.
Without further ado here is the code. I've set it up to work off form configuration to make things simpler for the end user, so it works like this:
Select "allow field to be populated dynamically" in your destination form field's advanced settings and choose a parameter name for each.
Add matching CSS classes on the source fields of the other form(s) to setup the associations.
Add a CSS class to the source forms themselves so that we can quickly check if the redirection is necessary.
.
$class = 'GForms_Redirector';
add_filter('gform_pre_submission', array($class, 'checkForSubmissionRedirection'), 10, 1);
add_filter('gform_confirmation', array($class, 'performSubmissionRedirection'), 10, 4);
abstract class GForms_Redirector
{
const SOURCE_FORMS_CLASS_MATCH = 'submission-redirect';
const DEST_PAGE_SLUG = 'submit-page-slug';
const DEST_FORM_ID = 1;
protected static $submissionRedirectUrl;
// first, read sent data and generate redirection URL
function checkForSubmissionRedirection($form)
{
if (false !== preg_match('#\W' . self::SOURCE_FORMS_CLASS_MATCH . '\W#', $form['cssClass'])) {
// load page for base redirect URL
$destPage = get_page_by_path(self::DEST_PAGE_SLUG);
// load form for reading destination form config
$destForm = RGFormsModel::get_form_meta(self::DEST_FORM_ID, true);
$destForm = RGFormsModel::add_default_properties($destForm);
// generate submission data for this form (there seem to be no hooks before gform_confirmation that allow access to this. DUMB.)
$formData = GFFormsModel::create_lead($form);
// create a querystring for the new form based on mapping dynamic population parameters to CSS class names in source form
$queryVars = array();
foreach ($destForm['fields'] as $destField) {
if (empty($destField['inputName'])) {
continue;
}
foreach ($form['fields'] as $field) {
if (preg_match('#(\s|^)' . preg_quote($destField['inputName'], '#') . '(\s|$)#', $field['cssClass'])) {
$queryVars[$destField['inputName']] = $formData[$field['id']];
break;
}
}
}
// set the redirect URL to be used later
self::$submissionRedirectUrl = get_permalink($destPage) . "?" . http_build_query($queryVars);
}
}
// when we get to the confirmation step we set the redirect URL to forward on to
function performSubmissionRedirection($confirmation, $form, $entry, $is_ajax = false)
{
if (self::$submissionRedirectUrl) {
return array('redirect' => self::$submissionRedirectUrl);
}
return $confirmation;
}
}
If you wanted to pass the form values someplace else via the querystring then you'd merely need to cut out my code from the callback and build your own URL to redirect to.
This is a very old question, now you can send it using a Query String on the confirmation settings.
They have the documentation on this link:
How to send data from a form using confirmations
Just follow the first step and it will be clear to you.

Phpunit testing with ZF2 Album Module fails while connecting to AlbumTable

I am trying the phpunit in the Zf2 album module by following the online ZF2 tutorial. Below is the debug information.
Album\Model\AlbumTableTest::testFetchAllReturnsAllAlbums
Argument 1 passed to Album\Model\AlbumTable::__construct() must be an instance of Zend\Db\Adapter\Adapter, instance of Mock_TableGateway_fb3537df given, called in D:\www\zend2\tests\module\Album\src\Album\Model\AlbumTableTest.php on line 26 and defined
And the function used is
public function testFetchAllReturnsAllAlbums()
{
$resultSet = new ResultSet();
$mockTableGateway = $this->getMock('Zend\Db\TableGateway\TableGateway',
array('select'), array(), '', false);
$mockTableGateway->expects($this->once())
->method('select')
->with()
->will($this->returnValue($resultSet));
$albumTable = new AlbumTable($mockTableGateway);
$this->assertSame($resultSet, $albumTable->fetchAll());
}
And the 26th line mentioned in the debug information is
$albumTable = new AlbumTable($mockTableGateway);
Which calls to the following functon in Album\Model\AlbumTable::__construct()
public function __construct(Adapter $adapter)
{
$this->adapter = $adapter;
$this->resultSetPrototype = new ResultSet();
$this->resultSetPrototype->setArrayObjectPrototype(new Album());
$this->initialize();
}
Any help to over come this failed test is much appreciated.
Got it solved. I happened to see that the Album module given in the Zend Framework2 tutorial has been changed. I followed it once again to correct the changed codes. Now the mentioned issue has been sorted out.

Is it possible to find the function and/or line number that caused an error in ActionScript 3.0 without using debug mode?

I'm currently trying to implement an automated bug reporter for a Flex application, and would like to return error messages to a server along with the function/line number that caused the error. Essentially, I'm trying to get the getStackTrace() information without going into debug mode, because most users of the app aren't likely to have the debug version of flash player.
My current method is using the UncaughtErrorEvent handler to catch errors that occur within the app, but the error message only returns the type of error that has occurred, and not the location (which means it's useless). I have tried implementing getStackTrace() myself using a function name-grabber such as
private function getFunctionName (callee:Function, parent:Object):String {
for each ( var m:XML in describeType(parent)..method) {
if ( this[m.#name] == callee) return m.#name;
}
return "private function!";
}
but that will only work because of arguments.callee, and so won't go through multiple levels of function calls (it would never get above my error event listener).
So! Anyone have any ideas on how to get informative error messages through the global
error event handler?
EDIT: There seems to be some misunderstanding. I'm explicitly avoiding getStackTrace() because it returns 'null' when not in debug mode. Any solution that uses this function is what I'm specifically trying to avoid.
Just noticed the part about "I don't want to use debug." Well, that's not an option, as the non-debug version of Flash does not have any concept of a stack trace at all. Sucks, don't it?
Not relevant but still cool.
The rest is just for with the debug player.
This is part of my personal debug class (strangely enough, it is added to every single project I work on). It returns a String which represents the index in the stack passed -- class and method name. Once you have those, line number is trivial.
/**
* Returns the function name of whatever called this function (and whatever called that)...
*/
public static function getCaller( index:int = 0 ):String
{
try
{
throw new Error('pass');
}
catch (e:Error)
{
var arr:Array = String(e.getStackTrace()).split("\t");
var value:String = arr[3 + index];
// This pattern matches a standard function.
var re:RegExp = /^at (.*?)\/(.*?)\(\)/ ;
var owner:Array = re.exec(value);
try
{
var cref:Array = owner[1].split('::');
return cref[ 1 ] + "." + owner[2];
}
catch( e:Error )
{
try
{
re = /^at (.*?)\(\)/; // constructor.
owner = re.exec(value);
var tmp:Array = owner[1].split('::');
var cName:String = tmp.join('.');
return cName;
}
catch( error:Error )
{
}
}
}
return "No caller could be found.";
}
As a side note: this is not set up properly to handle an event model -- sometimes events present themselves as either not having callers or as some very weird alternate syntax.
You don't have to throw an error to get the stack trace.
var myError:Error = new Error();
var theStack:String = myError.getStackTrace();
good reference on the Error class
[EDIT]
Nope after reading my own reference getStackTrace() is only available in debug versions of the flash player.
So it looks like you are stuck with what you are doing now.

Resources