PHP- Google Api getting goal completed amount - php

Im using this code from google api
I am getting all of the goals names and number
But I cant see a way to get the goal completed amount
This is what I get:
Account ID = xxx
Web Property ID = xxx
Internal Web Property ID = xxx
Profile ID = xxx
Goal Number = 1
Goal Name = Open User (MT Register)
Goal Value = 0
Goal Active = 1
Goal Type = URL_DESTINATION
Created = 2012-07-22T10:20:02.183Z
Updated = 2012-08-15T12:43:06.045Z
Goal URL = /04_thankyou.php
Case Sensitive =
Match Type = REGEX
First Step Required = 1
Destination Goal Steps
Step Number = 1
Step Name = abc
Step URL = /01_insert_phone.php
Step Number = 2
Step Name = abcd
Step URL = /02_progress.step
Step Number = 3
Step Name = abcde
Step URL = /03_insert_pincode.php
This is the code:
function getEventDetailsHtml(&$details) {
$html = '<h4>Event Goal</h4><pre>' .
'Use Event Value = ' . $details->getUseEventValue();
// Get all the event goal conditions.
$conditions = $details->getEventConditions();
foreach ($conditions as &$condition) {
$html .= "Event Type = $condition->getEventType()";
$eventType = $condition->getType();
if ($condition->getType() == 'VALUE') {
// Process VALUE.
$html .= "Comparison Type = $condition->getComparisonType()" .
"Comparison Value = $condition->getComparisonValue()";
} else {
// Process CATEGORY, ACTION, LABEL.
$html .= "Match Type = $condition->getMatchType()" .
"Expression = $condition->getExpression()";
}
}
return $html . '</pre>';
}
function getVisitNumPagesDetailsHtml(&$details) {
$html = '<h4>Visit Num Pages Goal</h4>';
$html .= <<<HTML
<pre>
Comparison Type = {$details->getComparisonType()}
Comparison Value = {$details->getComparisonValue()}
</pre>
HTML;
return $html;
}
function getVisitTimeOnSiteDetailsHtml(&$details) {
$html = '<h4>Visit Time On Site Goal</h4>';
$html .= <<<HTML
<pre>
Comparison Type = {$details->getComparisonType()}
Comparison Value = {$details->getComparisonValue()}
</pre>
HTML;
return $html;
}
function getUrlDestinationDetailsHtml(&$details) {
$html .= <<<HTML
<pre>
Goal URL = {$details->getUrl()}
Case Sensitive = {$details->getCaseSensitive()}
Match Type = {$details->getMatchType()}
First Step Required = {$details->getFirstStepRequired()}
</pre>
HTML;
$html .= '<h4>Destination Goal Steps</h4>';
$steps = $details->getSteps();
if (count($steps) == 0) {
$html .= '<p>No Steps Configured</p>';
} else {
foreach ($steps as &$step) {
$html .= <<<HTML
<pre>
Step Number = {$step->getNumber()}
Step Name = {$step->getName()}
Step URL = {$step->getUrl()}
</pre>
HTML;
}
}
return $html;
}
require_once 'google_api.php';
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (!$client->getAccessToken()) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
} else {
$analytics = new Google_AnalyticsService($client);
try {
$goals = $analytics->management_goals
->listManagementGoals('25788360',
'UA-25788360-20',
'~all');
} catch (Exception $e) {
print 'There was a general API error '
. $e->getCode() . ':' . $e->getMessage();
}
$html = '';
$items = $goals->getItems();
foreach ($items as &$goal) {
$html .= "
<pre>
Account ID = {$goal->getAccountId()}
Web Property ID = {$goal->getWebPropertyId()}
Internal Web Property ID = {$goal->getInternalWebPropertyId()}
Profile ID = {$goal->getProfileId()}
Goal Number = {$goal->getId()}
Goal Name = {$goal->getName()}
Goal Value = {$goal->getValue()}
Goal Active = {$goal->getActive()}
Goal Type = {$goal->getType()}
Created = {$goal->getCreated()}
Updated = {$goal->getUpdated()}
</pre>";
// Now get the HTML for the type of goal.
switch($goal->getType()) {
case 'URL_DESTINATION':
$html .= getUrlDestinationDetailsHtml(
$goal->getUrlDestinationDetails());
break;
case 'VISIT_TIME_ON_SITE':
$html .= getVisitTimeOnSiteDetailsHtml(
$goal->getVisitTimeOnSiteDetails());
break;
case 'VISIT_NUM_PAGES':
$html .= getVisitNumPagesDetailsHtml(
$goal->getVisitNumPagesDetails());
break;
case 'EVENT':
$html .= getEventDetailsHtml(
$goal->getEventDetails());
break;
}
echo $html;
}

It seems like you are using the Management API. This is meant for management purposes only. Getting and setting goals.
If you want data from goals as well you want to be looking at the Core Reporting API.
The available data for goals can be found here:
https://developers.google.com/analytics/devguides/reporting/core/dimsmets/goalconversions
The implementation guide can be found here:
https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide
I did not provide a full implementation example seeing that you already know how to setup the use of a Google API.
Good luck with you quest!
EDIT:
Added an example on how to use it:
<?php
$client = new apiAnalyticsService();
function queryCoreReportingApi() {
$optParams = array( //OPTINAL SETTINGS
'dimensions' => '', //A comma-separated list of Multi-Channel Funnels dimensions. E.g., 'mcf:source,mcf:medium'. (string)
'sort' => '', //A comma-separated list of dimensions or metrics that determine the sort order for the Analytics data. (string)
'filters' => '', //A comma-separated list of dimension or metric filters to be applied to the Analytics data. (string)
'start-index' => '', //An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. (integer, 1+)
'fields' => '', //Selector specifying which fields to include in a partial response.
'max-results' => '25'); //The maximum number of entries to include in this feed. (integer)
return $service->data_mcf->get(
$id, //Unique table ID for retrieving Analytics data. Table ID is of the form ga:XXXX, where XXXX is the Analytics profile ID. (string)
'2010-01-01', //Start date for fetching Analytics data. All requests should specify a start date formatted as YYYY-MM-DD. (string)
'2010-01-15', //End date for fetching Analytics data. All requests should specify an end date formatted as YYYY-MM-DD. (string)
'ga:totalConversions', //A comma-separated list of Multi-Channel Funnels metrics. E.g., 'mcf:totalConversions,mcf:totalConversionValue'. At least one metric must be specified. (string)
$optParams);
}

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

Getting full list of contacts from Hubspot API

Hubspot's API allows you retrieve a list of contacts, however it only allows a max of 100 per call.
I do that with this call:
$contacts_batch1 = $contacts->get_all_contacts(array( 'count' => '100'));
And then if I want to get the next 100 I do this:
$offset1 = $contacts_batch1->{'vid-offset'};
$contacts_batch2 = $contacts->get_all_contacts(array('count' => '100', 'vidOffset'=>$offset1));
I am trying to get all the contacts without having to create a new variable each time I want the next 100. My first question would be how would I go about getting the vid-offset of the last set, and then how would I put that as a parameter into the next variable automatically.
Here's an example of getting all contacts into one array using HubSpot's API.
<?php
require "haPiHP/class.contacts.php";
require "haPiHP/class.exception.php";
define("HUBSPOT_API_KEY", "<YOUR API KEY HERE>");
$contacts = new HubSpot_Contacts(HUBSPOT_API_KEY);
$all_contacts = array();
do
{
$params = array("count" => 100);
if (isset($vidOffset))
{
$params["vidOffset"] = $vidOffset;
}
echo "count=" . $params["count"] . (isset($params["vidOffset"]) ? ", vidOffset=" . $params["vidOffset"] : "") . "\n";
$some_contacts = $contacts->get_all_contacts($params);
if ($some_contacts !== NULL)
{
$all_contacts = array_merge($all_contacts, $some_contacts->contacts);
}
else
{
break;
}
$vidOffset = $some_contacts->{'vid-offset'};
} while ($some_contacts->{'has-more'});
echo "Received " . count($all_contacts) . " contacts.\n";
?>

PHP Search Script Enhancement

I have a website that has a built in search function. It allows the users to search for keywords from within the main page header. When a user searches any keyword, the result is always:
There are no results matching your query.
In order to find any item, the user must go to the advanced search options and enter the keyword in the search box, select the checkbox for "Search item title and description" and select "Both" from the drop down box for "Listed In".
I cannot figure out how to automatically set the main page search box to search each of these options.
Below is the code that I have for the search function. Any help would be GREATLY APPRECIATED:
<?php
session_start();
define ('IN_SITE', 1);
include_once ('includes/global.php');
include_once ('includes/class_formchecker.php');
include_once ('includes/class_custom_field.php');
include_once ('global_header.php');
$option = $db->rem_special_chars($_REQUEST['option']);
$option = (empty($option)) ? 'auction_search' : $option;
$template->set('option', $option);
$item_details = $db->rem_special_chars_array($_POST);
$template->set('item_details', $item_details);
$header_search_page = header5(GMSG_ADVANCED_SEARCH);
$template->set('header_search_page', $header_search_page);
if ($_REQUEST['search_empty'] == 1)
{
$template->set('no_results_message', '<p align="center" class="errormessage">' . MSG_NO_RESULTS_QUERY . '</p>');
}
(string) $search_options_menu = null;
$search_options_menu .= display_link(process_link('search', array('option' => 'auction_search')), MSG_AUCTION_SEARCH, (($option = 'auction_search') ? false : true)) . ' | ';
$search_options_menu .= display_link(process_link('search', array('option' => 'seller_search')), MSG_SELLER_SEARCH, (($option = 'seller_search') ? false : true)) . ' | ';
$search_options_menu .= display_link(process_link('search', array('option' => 'buyer_search')), MSG_BUYER_SEARCH, (($option = 'buyer_search') ? false : true));
if ($setts['enable_stores'])
$template->set('search_options_menu', $search_options_menu);
switch ($option)
{
case 'auction_search':
$search_options_title = MSG_AUCTION_SEARCH;
$custom_fld = new custom_field();
$custom_fld->new_table = false;
$custom_fld->field_colspan = 2;
$custom_fld->box_search = 1;
$custom_sections_table = $custom_fld->display_sections($item_details, 'auction', false, 1, 0);
$template->set('custom_sections_table', $custom_sections_table);
$tax = new tax();
$template->set('country_dropdown', $tax->countries_dropdown('country', $item_details['country'], null, '', true));
//$template->set('state_box', $tax->states_box('state', $item_details['state'], $item_details['country']));
break;
case 'seller_search':
$search_options_title = MSG_SELLER_SEARCH;
break;
case 'buyer_search':
$search_options_title = MSG_BUYER_SEARCH;
break;
case 'store_search':
$search_options_title = MSG_STORE_SEARCH;
break;
}
$template->set('search_options_title', $search_options_title);
$template_output .= $template->process('search.tpl.php');
include_once ('global_footer.php');
echo $template_output;
?>
This issue after doing research was the result in a standard setting for MySQL. Minimum search length had to be longer than 3 characters. A search length of 3 characters or less yielded no search results.

Incorporating next/ previous in my 'foreach statement

I want to have a previous|next link on my page to change pictures.
I use a function to get relevent elements. However, I do not know what additional code is require in my function and where to place it. Also what should be in the html section.
I have looked at many pages on next/previous from 'foreach' but I cannot seem to relate to them.
Code:
function image_data($image_album_id) {
$image_album__id = (int)$image_album_id;
$args = func_get_args();
unset($args[0]);
$fields = '`'.implode('`, `', $args).'`';
$query = mysql_query("SELECT $fields FROM `album_images`
WHERE `image_album_id`=$image_album_id AND `member_id`= '1'");
$ query_result = mysql_fetch_assoc($query);
foreach ($args as $field) {
$args[$field] = $query_result[$field];
}
return $args;
}
Html Page:
Last|
Next
</div>
<?php
$image_album_id =$_GET['image_album_id'];
$image_data = image_data($image_album_id, 'album_id', 'albumname', 'ext', 'timestamp');
echo '';
?>
<td class="smallfont albumthumb2" align="center" valign="middle" >
<img alt="" class="album_cover" src="<?php echo 'images/albums/thumbs/'. $image_data['album_id']. '/'. $image_album_id. '.' .$image_data['ext'];?> " height="175px" width="175px">
</td>
Many thanks. I hope I make sense.
Thanks for the speedy response.
Since there is a lot to look at and digest I thought I would just see if it works.
Alas no.
There is a parse error: syntax error, unexpected
'<' on line
$prev_link = Previous;
The only thing I notice within that section was an extra curly bracket after 'title="$prev_name"}'
I see there is the same for the 'title="$next_name"}'
WIth reference to your specific questions.
I get to the album_viewT page when I click on a link in a previous page. This contains tiny thumbnails. The link being localhost/Testing/album_view.php?artist_id=4&image_album_id=4 as an example.
Not sure if I fully understand "order of date is by image_album_data
Yes there are almost 3,000 rows in the database.
I should also mention that album_id has been replaced by artist_id.
Should the href be changed to "album_view.php/id/...
Your question lacks some data i.e. what is the page you are visiting that produces this code (the URL that is) and how is your data sorted. For instance I can see that you are providing potentially more information using the album_viewT.php? script but that is not necessarily the one that displays the HTML that you have produced.
So after all this I will make some assumptions and hopefully that will give you the right guidance to get to the solution.
I am assuming that your visiting page is http://mysite.com/albums/id/25
I am also assuming that the order of the data is by image_album_id.
Finally I am assuming that you have data in your db and I don't need to check whether there are returned data in the template for the current image. You will need to sort that out yourself.
You will need to get the data first from the database:
function image_data($image_album_id)
{
$results = array(
'previous' => FALSE,
'current' => FALSE,
'next' => FALSE,
);
$image_album__id = (int)$image_album_id;
$args = func_get_args();
unset($args[0]);
$fields = '`'.implode('`, `', $args).'`';
// Current record
$results['current'] = get_data(
$fields,
"AND image_album_id = {$image_album_id}"
);
// Previous - no need to run this if we don't have a current
if ($results['current'])
{
// Current record
$results['previous'] = get_data(
$fields,
"AND image_album_id < {$image_album_id} " .
"LIMIT 1"
);
}
// Next - no need to run this if we don't have a current
if ($results['current'])
{
// Current record
$results['next'] = get_data(
$fields,
"AND image_album_id > {$image_album_id} " .
"LIMIT 1"
);
}
// If all went well the $results array will contain the data
// for the 3 records. If we are at the beginning or the end,
// the previous and/or next will be FALSE
return $results;
}
function get_data($fields, $where = '')
{
$return = FALSE;
// Template
$template = "SELECT %s "
. "FROM album_images "
. "WHERE member_id = 1 %s";
// Current record
$sql = sprintf($template, $fields, $where);
$query = mysql_query($sql);
$query_result = mysql_fetch_assoc($query);
// If data has been found
if ($query_result)
{
$return = $query_result;
}
return $return;
}
For your HTML page:
<?php
$image_album_id = $_GET['image_album_id'];
$image_data = image_data(
$image_album_id,
'album_id', 'albumname', 'ext', 'timestamp'
);
$prev_link = '';
$next_link = '';
if ($image_data['previous'])
{
$prev_id = $image_data['previous']['album_id'];
$prev_name = $image_data['previous']['albumname'];
$prev_link = <a href="/albums/id/{$prev_id}" title="$prev_name"}>Previous</a>";
}
if ($image_data['next'])
{
$next_id = $image_data['next']['album_id'];
$next_name = $image_data['next']['albumname'];
$next_link = <a href="/albums/id/{$next_id}" title="$next_name"}>Next</a>";
}
$curr_id = $image_data['current']['album_id'];
$curr_ext = $image_data['current']['ext'];
?>
<?php echo $prev_link; ?>|<?php echo $next_link; ?>
</div>
<td class="smallfont albumthumb2" align="center" valign="middle">
<a href="album_viewT.php?images/albums/thumbs/
<?php echo "{$curr_id}/{$image_album_id}.{$curr_ext}; ?>
<img alt="" class="album_cover"
src="images/albums/thumbs/
<?php echo "{$curr_id}/{$image_album_id}.{$curr_ext}"; ?>
height="175px"
width="175px" />
</a>
</td>
Note: I have split the line for the img and a tags in the HTML file for clarity.

Looping through pages from API

I'm trying to get all the gameids for a particular player. The API I am working with only returns 24 games per page. I just cant figure out how to loop though the pages.
When a player no longer has anymore pages $mPages will be equal to false.
The problem is adding 1 to $iPages so it can get the next page..
My current script:
<?php
//incude sql database connection
include_once('sql.php');
//include api key
include_once('api.php');
//gamertag
$gamertag = "jam1efoster";
//variant- Valid values are "Campaign", "Firefight", "Competitive", "Arena", "Invasion", "Custom", "Unknown". "Unknown" returns all games.
$variant = "Unknown";
//page number 0 = most recent
$iPage = 0;
while(!$endPages == "stop"){
$iPage = $iPage++;
$GetGameHistory = "http://www.bungie.net/api/reach/reachapijson.svc/player/gamehistory/".$apiKey."/".rawurlencode($gamertag)."/".$variant."/".$iPage;
$output = file_get_contents($GetGameHistory);
$obj = json_decode($output);
echo $output;
$mPages = $obj->HasMorePages;
if($mPages == false){$endPages = "stop";}
foreach($obj->RecentGames as $recentgames) {
$gameid = $recentgames->GameId;
echo $gameid."<br/>";
}
}
?>
Perhaps a while loop?
while (!endOfPages) {
getMoreGames();
}

Categories