Google Calendar API - Updating an Events start & end date/time - php

The sample/demo code for Google's API is pretty clear about updating an event title, and it seems like everyone loves copying it into their own tutorials... I can use that example to easily update the title, description, and location of an event, but I cannot use it to update the "when" attribute, which is made up of an array with start and end date/time.
The following code does not return an error but it does not update the date and time as well:
if ($eventOld = getEvent($client, $eventId)) {
//echo "Old title: " . $eventOld->title->text . "<br />\n";
$eventOld->title = $gdataCal->newTitle($title);
$eventOld->where = array($gdataCal->newWhere($where));
$eventOld->content = $gdataCal->newContent("$description");
$eventOld->when[startTime] = "{$startDate}T{$startTime}:00.000{$tzOffset}:00";
$eventOld->when[endTime] = "{$endDate}T{$endTime}:00.000{$tzOffset}:00";
print $startDate;
try
{
$eventOld->save();
}
catch (Zend_Gdata_App_Exception $e)
{
var_dump($e);
return null;
}
//return $eventNew;
}
else
{
return null;
}

You're submitting to the wrong var. $eventOld is previous to make changes
create a new var. Then submit your data for ex.
$eventNew = getEvent($client, $eventId)
$eventNew->when[startTime] = "{$startDate}T{$startTime}:00.000{$tzOffset}:00";
$eventNew->when[endTime] = "{$endDate}T{$endTime}:00.000{$tzOffset}:00";

when is an array of startTime/endTime pairs.

Related

Display pho echo list in Descending order

Am displaying list haviing
Date
News Heading
Short Descrption
The list is spread to around 100 pages, having 20 news in each page
Issue is: This is working absolute fine in php 7.3, 7.4 in joomla 3.10 where on clicking url - list is shown spread over multiple pages having sort by date wise as first criteria, latest date of publishing is coming
But when same used on php 8.0.x - its showing incorrectly, where on clicking URL - last page of list having page number 100 is shown first. Now when i add on limitstart=0 in url then its showing correctly as the first page.
Now when i change from descending to ascending - its bringing the content on last page and its opening, but page number is 100 again
Seems like URL when opened is directly taking to last page of news item as published (although no limitstart is mentioned in it), which is incorrect as ideally should open in descending order and open the page having latest one
Below is code of views/list/tmpl/default.php
if(count($this->items) >0){
//$i=1;
foreach($this->items as $newslist)
{
$date = JFactory::getDate($newslist->n_date);
$list .='<h3><strong>'.$newslist->v_heading.'</strong></h3>
<p>'. $date->format('F j, Y').'</p>
<p>'.substr($newslist->v_short_description,0,100).'</p>
<p><i>Know More on:- </i><b><i>'.$newslist->v_heading.'</i></b></p><hr/><br>';
//$i=$i+1;
}
}else{
JError::raiseError(404, "Message");
}
<?php echo $list?>
and for models/list.php this is the function
protected function getListQuery()
{
// Create a new query object.
$db = $this->getDbo();
$query = $db->getQuery(true);
// Select the required fields from the table.
$query
->select(
$this->getState(
'list.select', 'DISTINCT a.*'
)
);
$query->from('`#__news` AS a');
if (!JFactory::getUser()->authorise('core.edit', 'com_news'))
{
$query->where('a.state = 1');
}
// Filter by search in title
$search = $this->getState('filter.search');
if (!empty($search))
{
if (stripos($search, 'id:') === 0)
{
$query->where('a.id = ' . (int) substr($search, 3));
}
else
{
$search = $db->Quote('%' . $db->escape($search, true) . '%');
$query->where('( a.n_heading LIKE ' . $search . ' )');
}
}
/*
// Add the list ordering clause.
$orderCol = $this->state->get('list.ordering');
$orderDirn = $this->state->get('list.direction');
if ($orderCol && $orderDirn)
{
$query->order($db->escape($orderCol . ' ' . $orderDirn));
}
*/ //Order by date
$query->order ('a.n_date DESC');
$query->order ('a.id DESC');
return $query;
}
This is the code for views/list/view.html.php
public function display($tpl = null)
{
$app = JFactory::getApplication();
$this->state = $this->get('State');
$this->items = $this->get('Items');
$this->pagination = $this->get('Pagination');
$this->params = $app->getParams('com_news');
$this->filterForm = $this->get('FilterForm');
$this->activeFilters = $this->get('ActiveFilters');
// Check for errors.
if (count($errors = $this->get('Errors')))
{
throw new Exception(implode("\n", $errors));
}
$this->_prepareDocument();
parent::display($tpl);
}
Unsure how to achieve in and why its not working in php 8.0 where url should open the 1st page and not last page

How to get AdSchedule object with Google Ads API

I am trying to get all Ad Schedules placed in Google Ads through the Google Ads API and obtain the start and end times (hour and minute) to compare it with some existing values and depending on whether they differ update accordingly.
Here is my code showing where I am iterating over returned Ad Schedules.
foreach($campaigns as $camp) {
// Get restaurant and details
$res = RestaurantsService::getRestaurantByName($camp->getName());
$hours =$res->getHours()->dequeue();
$start = explode("-",$hours)[0];
$end = explode("-",$hours)[1];
// Get current ad schedules as they are now
$campaignAdSchedules = self::getCampaignAdSchedule($campaignCriterionService,$camp->getId());
if ($campaignAdSchedules == null){
$operations = [];
$schedule = new AdSchedule();
$schedule->setDayOfWeek(self::DAYS[date("N")-1]);
$schedule->setStartHour((int)substr($start,0,2));
$schedule->setStartMinute(MinuteOfHour::ZERO);
$schedule->setEndHour((int)substr($end,0,2));
$schedule->setEndMinute(MinuteOfHour::ZERO);
$operation = new CampaignCriterionOperation();
$criterion = new CampaignCriterion();
$criterion->setCampaignId($camp->getId());
$criterion->setCriterion($schedule);
$operation->setOperand($criterion);
$operation->setOperator(Operator::ADD);
$operations[] = $operation;
$campaignCriterionService->mutate($operations);
} else {
foreach($campaignAdSchedules as $adSchedule){
---> $schedule = $adSchedule->getCriterion(); <---
}
}
}
Here the line marked with arrows is the line I am having problems with. The getCriterion() function returns a Criterion object which does not have the methods getStartHour() etc. I have tried casting it but haven't found the correct way.
Help is much appreciated!
Try check the instance:
$result = $campaignCriterionService->get($serviceSelector);
$campaignAdSchedules = $result->getEntries();
foreach ($campaignAdSchedules as $criterion) {
$adSchedule = $criterion->getCriterion();
if ($adSchedule instanceof AdSchedule) {
$adSchedule->getStartHour();
}
}

How to optimize api call PHP

I'm working (for fun), with an API (Riot API), and I made something to retrieve match histories (it's in the game). And I've a problem, everything works really fine, but I don't know how to optimize it, what I mean is : I do the call every time the user refresh the page, and it takes loooong looong time. I tried to call it with AJAX, but didn't find a good way, AJAX dont find my objects.
Here is the code :
$match_history = [];
$api = "";
if (!empty($region)) {
try {
$api = new App\Library\RiotAPI\RiotAPI([
App\Library\RiotAPI\RiotAPI::SET_KEY =>
App\Config::API_KEY,
App\Library\RiotAPI\RiotAPI::SET_CACHE_RATELIMIT => true,
App\Library\RiotAPI\RiotAPI::SET_CACHE_CALLS => true,
App\Library\RiotAPI\RiotAPI::SET_REGION =>
App\Library\RiotAPI\Definitions\Region::getRegion($region),
]);
} catch (\Exception $e) {
// die($e->getMessage());
}
}
if ($api) {
// Insert current rank etc...
try {
$summoner = $api-
>getSummonerByName(App\Repository\UserRepository::getInstance()-
>getUserDetail($_SESSION['user']['id'], 'summoner_name'));
} catch (\Exception $e) {
$summoner = null;
}
// Match history
if (!empty($summoner)) {
try {
$matches = $api->getRecentMatchlistByAccount($summoner->accountId);
// For every matches
foreach ($matches as $match) {
$a_match = $api->getMatch($match->gameId);
if ($a_match->gameType === "MATCHED_GAME") {
$gameCreation = date("d-M-Y H:i:s", substr($a_match-
>gameCreation, 0, 10));
if ($gameCreation >= date("d-M-Y",
strtotime($user['created_at']))) {
// Get the participant ID of the customer
foreach ($a_match->participantIdentities as
$participantIdentity) {
if ($participantIdentity->player->currentAccountId
=== $summoner->accountId) {
$participantId = $participantIdentity-
>participantId;
}
}
// Get stats of the participant
foreach ($a_match->participants as $participant) {
if ($participant->participantId === $participantId)
{
$match_history[$match->gameId]['gameCreation'] =
$gameCreation;
$match_history[$match->gameId]['championId'] =
$participant->championId;
$match_history[$match->gameId]['spells']
['spell1'] = $participant->spell1Id;
$match_history[$match->gameId]['spells']
['spell2'] = $participant->spell2Id;
$match_history[$match->gameId]['win'] =
$participant->stats->win;
$match_history[$match->gameId]['kills'] =
$participant->stats->kills;
$match_history[$match->gameId]['deaths'] =
$participant->stats->deaths;
$match_history[$match->gameId]['assists'] =
$participant->stats->assists;
$match_history[$match->gameId]['goldEarned'] =
$participant->stats->goldEarned;
$match_history[$match->gameId]
['totalMinionsKilled'] = $participant->stats->totalMinionsKilled;
$match_history[$match->gameId]['items']['item0']
= $participant->stats->item0;
$match_history[$match->gameId]['items']['item1']
= $participant->stats->item1;
$match_history[$match->gameId]['items']['item2']
= $participant->stats->item2;
$match_history[$match->gameId]['items']['item3']
= $participant->stats->item3;
$match_history[$match->gameId]['items']['item4']
= $participant->stats->item4;
$match_history[$match->gameId]['items']['item5']
= $participant->stats->item5;
$match_history[$match->gameId]['items']['item6']
= $participant->stats->item6;
}
}
}
}
}
} catch (\Exception $e) {
// die($e->getMessage());
}
}
}
I would like to know if there's a way to : - Run it in background, without AJAX or something like : Keep in mind the match_history for X time, and then after X time, do the call again when the user refresh the page.
Thanks for your help!
Best Regards.

How do I set a DB2_SCROLLABLE with hold in PHP?

I've been working on creating an object oriented database call class for practice and I've been trying to figure out how to incorporate a scrollable cursor properly. I would like to be able to call this function in order to grab the next 10 records or a different function for the previous 10 records. I've gotten to the point where I can specify an offset for the records through the scrollable cursor but I cannot call the same function again to get the next set without passing in an incremented offset value.
How would I go about being able to specify a number of records per page and simply call getNextSet() or getPrevSet() in order to get the results I want.
My current line of thinking is setting a static variable somewhere and incrementing/deincrementing or resetting it accordingly then use that as the offset value in the functions. However, I believe I heard there was an issue with using static variables in instantiated classes.
Here's the code so far:
<?php
$i5DBconn = db2_connect("*LOCAL", "", "");
if (!$i5DBconn) {
echo "Database Connection failed. SQL Err:";
echo db2_conn_error();
echo "<br>";
echo db2_conn_errormsg();
die();
}
class queryDB{
var $query;
var $outputFunction;
var $parameters;
function performDBCall(){
global $i5DBconn;
$dbStatement = db2_prepare($i5DBconn, $this->query, array('cursor' => DB2_SCROLLABLE));
$i = 1;
foreach ($this->parameters as $param) {
db2_bind_param($dbStatement, $i, 'param', DB2_PARAM_IN);
$i++;
}
$result = db2_execute($dbStatement);
if (!$result){
echo "$this->query failed!. ";
echo 'SQLSTATE value: ' . db2_stmt_error();
echo ' Message: ' . db2_stmt_errormsg();
}
return $dbStatement;
}
}
class invoiceCall extends queryDB {
function testQueryFormatter($dbResultSet, $dataOffset){
$zebraStriping = 1;
?>
//snipped header row formatting
<?php
$rowLimit = 10;
while(($rowData = db2_fetch_array($dbResultSet, $dataOffset)) && ($zebraStriping < $rowLimit)){
list($dataNames) = $rowData;
?>
//snipped data formatting
<?php
$dataOffset++;
}
}
}
$offsetVal = 5;
$testQuery = new invoiceCall();
$testQuery->query = "select invoice#, status, amountpaid, amountbilled, invoicedate, paydate, custname, termofpay, balance from TESTSCHEMA.SAMPLE_INVOICE_TABLE";
//$testQuery->parameters = [8000001];
$resultSet = $testQuery->performDBCall();
$testQuery->testQueryFormatter($resultSet, $offsetVal);
?>
If there are also some coding practices I could improve on, let me know as I am starting my first real journey into Object Oriented PHP.

Google Calendar EventId issues (PHP Api)

I've been working with the PHP api for google Calendar, and have been getting quite frustrated.
I downloaded the zend package with all the libraries from google's page, and have been working off the provided code to make sure it can meet my requirements.
The issue I'm running into involves getting an event back from the system. The provided code includes a demo with function getEvent($clientId, $eventId), which based on the documentation and reading the code, i would expect to return an event that is in my calendar that matches the provided Id.
So in my tests, I create a new event, and then I try to retrieve it. However, whenever I retrieve the event, Zend_data_Gdata_App_HttpException is:
function processPageLoad()
{
global $_SESSION, $_GET;
if (!isset($_SESSION['sessionToken']) && !isset($_GET['token'])) {
requestUserLogin('Please login to your Google Account.');
} else {
$client = getAuthSubHttpClient();
$id = createEvent ($client, 'Tennis with Beth',
'Meet for a quick lesson', 'On the courts',
'2010-10-20', '10:00',
'2010-10-20', '11:00', '-08');
$newEvent = getEvent($client, $id);
}
}
the code for createEvent( ) is :
function createEvent ($client, $title = 'Tennis with Beth',
$desc='Meet for a quick lesson', $where = 'On the courts',
$startDate = '2008-01-20', $startTime = '10:00',
$endDate = '2008-01-20', $endTime = '11:00', $tzOffset = '-08')
{
$gc = new Zend_Gdata_Calendar($client);
$newEntry = $gc->newEventEntry();
$newEntry->title = $gc->newTitle(trim($title));
$newEntry->where = array($gc->newWhere($where));
$newEntry->content = $gc->newContent($desc);
$newEntry->content->type = 'text';
$when = $gc->newWhen();
$when->startTime = "{$startDate}T{$startTime}:00.000{$tzOffset}:00";
$when->endTime = "{$endDate}T{$endTime}:00.000{$tzOffset}:00";
$newEntry->when = array($when);
$createdEntry = $gc->insertEvent($newEntry);
return $createdEntry->id->text;
}
And finally the code for getEvent() is:
function getEvent($client, $eventId)
{
$gdataCal = new Zend_Gdata_Calendar($client);
$query = $gdataCal->newEventQuery();
$query->setUser('default');
$query->setVisibility('private');
$query->setProjection('full');
$query->setEvent($eventId);
try {
$eventEntry = $gdataCal->getCalendarEventEntry($query);
return $eventEntry;
} catch (Zend_Gdata_App_Exception $e) {
var_dump($e);
return null;
}
}
we have the same problem, just share my solution. since you assign $id = createEvent()
$id will have a URL values. then you use $id getEvent($client, $id);
the solution is that getCalendarEventEntry() can have a $query or just a URL.
function getEvent($client, $eventId)
{
$gdataCal = new Zend_Gdata_Calendar($client);
try {
$eventEntry = $gdataCal->getCalendarEventEntry($eventId);
return $eventEntry;
} catch (Zend_Gdata_App_Exception $e) {
var_dump($e);
return null;
}
Hope it helps!!

Categories