How to get all work logs for a period of time from the Jira REST API? - rest

I'm writing an application using PHP and the Jira REST API which is required to generate a report for a particular period of time with the accumulation of hours spent by a person on a particular project.
For this I will need a call which will give something like this.
e.g: For the period 01/01/2012 - 31/01/2012 give me the worklogs for project X.
The method I found so far, was to get the updated issues after the start date and filter the worklogs for each issue by the period again.
Is there a better alternative?

As many have said, there's no direct way. However, if you narrow down the search space efficiently, it's not so bad. The following PHP code runs quite fast on my setup, but of course, your mileage may vary:
<?php
$server = 'jira.myserver.com';
$fromDate = '2012-01-01';
$toDate = '2012-01-31';
$project = 'X';
$assignee = 'bob';
$username = 'my_name';
$password = 'my_password';
$curl = curl_init();
curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
# Give me up to 1000 search results with the Key, where
# assignee = $assignee AND project = $project
# AND created < $toDate AND updated > $fromDate
# AND timespent > 0
curl_setopt($curl, CURLOPT_URL,
"https://$server/rest/api/2/search?startIndex=0&jql=".
"assignee+%3D+$assignee+and+project+%3D+$project+".
"and+created+%3C+$toDate+and+updated+%3E+$fromDate+".
"and+timespent+%3E+0&fields=key&maxResults=1000");
$issues = json_decode(curl_exec($curl), true);
foreach ($issues['issues'] as $issue) {
$key = $issue['key'];
# for each issue in result, give me the full worklog for that issue
curl_setopt($curl, CURLOPT_URL,
"https://$server/rest/api/2/issue/$key/worklog");
$worklog = json_decode(curl_exec($curl), true);
foreach ($worklog['worklogs'] as $entry) {
$shortDate = substr($entry['started'], 0, 10);
# keep a worklog entry on $key item,
# iff within the search time period
if ($shortDate >= $fromDate && $shortDate <= $toDate)
$periodLog[$key][] = $entry;
}
}
# Show Result:
# echo json_encode($periodLog);
# var_dump($periodLog);
?>

If you can't find the an out-of-the-box function that does what you've asked for, I can think of three other solutions other than yours:
Query the DB directly so you could get the work logs using one query. Be sure not to insert/delete/update the DB directly, but only to query it.
Use something like Jira Scripting Suite or Behaviours Plugin to add scripts that will write the work-logs somewhere on the disk. Then use another app to read the written information from the disk and display it to the users.
Use the Tempo plugin

It is worth pointing out that Jira queries have an expand option which allows you to specify which fields you want attached to your search:
// Javascript
$jql = 'project = MyProject and updated > 2016-02-01 and updated < 2016-03-01';
// note this definition
$fields = 'key,summary,worklog';
$query = "https://{server}/rest/api/2/search?maxResults=100&fields={fields}&jql={jql}"
.replace(/{server}/g,$server)
.replace(/{jql}/g,encodeURIComponent($jql))
.replace(/{fields}/g,$fields)
;
The returned JSON object returned will be a list of tickets, and each ticket will have a collection of work items attached (potentially zero length).
Javascript rather than PHP, but the same idea holds:
function getJql(params){
$.ajax({
url: getJiraUrl()
+ "/rest/api/2/search?startIndex=0&fields=worklog,assignee,status,key,summary&maxResults=1000&jql="
+ encodeURI(params.jql),
success: function (resp) {
resp.issues.forEach(function(issue) {
issue.fields.worklog.worklogs.forEach(function(work){
alert(JSON.stringify(work));
db.AddWork(work);
});
});
}
});
}
posted on GitLab: https://gitlab.com/jefferey-cave/ProductivityBlockers/blob/5c4cb33276e8403443d4d766fc94ab2f92292da6/plugin-data-jira.js

The approach I've personally used for the same kind of an application is to get ALL records from JIRA on a weekly basis and then generate reports from the database they're stored in.
This way you will also have the data available if a major JIRA crash occurs. Our company went through such a problem with a OnDemand instance when a RAID Array burned and most of the data was unrecoverable.

Related

PayPal List Transactions API for subscriptions takes too long to respond with new subscriptions' data

I am using the PayPal REST API to get information about a subscription after the user purchases.
The JS of Paypal suggests that on the onApprove event, we can for example redirect to a thank you page, and it provides us the Subscription ID.
Thus, one would assume the Subscription is done at this point, and one would assume that calling this REST route https://developer.paypal.com/docs/api/subscriptions/v1/#subscriptions_transactions would return results. Yet, it does not -- initially.
It takes up to 10 minutes for the https://developer.paypal.com/docs/api/subscriptions/v1/#subscriptions_transactions call to return anything else than an empty JSON string.
My code is pretty simple:
On onApprove I pass the approved subscription ID in a redirect to a page. When that page loads, I use https://developer.paypal.com/docs/api/subscriptions/v1/#subscriptions_transactions via PHP cURL to get details of that transaction (buyer email) and check in my database if that email exists. If it exists, I redirect to another page, if not, I stay on this page.
Dead simple, and it works just fine - apart of course that PayPal takes about 10 minutes to actually return the transaction results.
Yes, I could add delays, but this is not the point. The point is that PayPal says the transaction is made, when the onApprove event happens. Thus, the data must be available in the REST API too. Is this a known issue? What can be done to avoid this delay? I fear the delay is probably arbitrary and might be more than 10 minutes for other users?
Here is the code I use:
JS button approval flow
<div id="paypal-button-container-P-1UU44524AX8090809MMVRJ3Y"></div>
<script src="https://www.paypal.com/sdk/js?client-id=AS-0AbQhD8wSxv0XMvjeRTAUsa-aZtSZm3fSq-qDp_ibhlq9S5XrkgCVDjchICdKS2IZP7IKVo-MTdz7&vault=true&intent=subscription" data-sdk-integration-source="button-factory" data-namespace = "paypal_sdk"></script>
<script>
paypal_sdk.Buttons({
style: {
shape: 'rect',
color: 'white',
layout: 'vertical',
label: 'subscribe'
},
createSubscription: function(data, actions) {
return actions.subscription.create({
/* Creates the subscription */
plan_id: 'P-1UU44524AX8090809MMVRJ3Y'
});
},
onApprove: function(data, actions) {
window.location.replace("https://www.my-site.com/create-account/?subscription_id=" + data.subscriptionID);
}
}).render('#paypal-button-container-P-1UU44524AX8090809MMVRJ3Y'); // Renders the PayPal button
</script>
Server-side process when loading https://www.my-site.com/create-account/?subscription_id=" + data.subscriptionID
<?php
if ( isset( $_GET['subscription_id'] )
&& ! empty( $_GET['subscription_id'] )
&& is_page( 'create-account' )
) {
/**
* Get Access Token
*/
$ch_auth = curl_init();
curl_setopt($ch_auth, CURLOPT_URL, 'https://api-m.sandbox.paypal.com/v1/oauth2/token');
curl_setopt($ch_auth, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch_auth, CURLOPT_POST, 1);
curl_setopt($ch_auth, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
curl_setopt($ch_auth, CURLOPT_USERPWD, 'USR' . ':' . 'PWD');
$headers_auth = array();
$headers_auth[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch_auth, CURLOPT_HTTPHEADER, $headers_auth);
$result_auth = curl_exec($ch_auth);
if (curl_errno($ch_auth)) {
echo 'Error:' . curl_error($ch_auth);
}
curl_close($ch_auth);
$auth_arr = json_decode($result_auth);
$auth = $auth_arr->access_token;
/**
* Get Subscription details
*/
$ch_sub = curl_init();
curl_setopt($ch_sub, CURLOPT_URL, 'https://api-m.sandbox.paypal.com/v1/billing/subscriptions/'.$_GET['subscription_id'].'/transactions?start_time=2022-01-21T07:50:20.940Z&end_time=2022-09-24T07:50:20.940Z');
curl_setopt($ch_sub, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch_sub, CURLOPT_CUSTOMREQUEST, 'GET');
$headers_sub = array();
$headers_sub[] = 'Content-Type: application/json';
$headers_sub[] = 'Authorization: Bearer ' . $auth;
curl_setopt($ch_sub, CURLOPT_HTTPHEADER, $headers_sub);
$result_sub = curl_exec($ch_sub);
if (curl_errno($ch_sub)) {
echo 'Error:' . curl_error($ch_sub);
}
curl_close($ch_sub);
$first = end(json_decode($result_sub)->transactions)->payer_name->given_name;
$last = end(json_decode($result_sub)->transactions)->payer_name->surname;
$mail = end(json_decode($result_sub)->transactions)->payer_email;
$exists = email_exists( $mail );
if ( $exists ) {
header('Location: '.'https://www.my-site.com/account/?subscription_id=' . $_GET['subscription_id'] . '&account=' . $exists);
die();
}
}
This always fails until I reload the page something between once and 100 times (it varies)
Don't use list transactions, use the get subscription details API to confirm the status of a subscription after approval.
To log all transactions, implement webhooks for the event PAYMENT.SALE.COMPLETED. This is the only webhook you need to listen to for subscriptions, it will record every transaction made and when it does you can update your "good until" date for the subscription to 1 month in the future or whatever.
To aid in reconciliation, add a unique custom_id value during subscription creation (alongside the plan_id) that correlates with the user (in your system) who subscribed. This value will be returned in all future webhooks for the subscription, and can be referenced if for whatever reason you don't have a record of which user a subscription ID (I-xxxxxxxxxxxx) belongs to
I don't know exactly what you are doing, but I recently worked with a frontend application that used a PayPal drop-in form and subscribed to its relative events to trigger calls to our backend.
The calls would take several seconds at max.
Maybe have a look at your event subscribers and make sure they are subscribed to the correct events?
You could incorporate an optimistic redirect and collect the REST reference via a webhook to have it update your existing record once it's ready on their end.
Although I'm not really familiar with the flow you are using, and I have not heard about these delays, you can trust that the transaction is (being) processed if PayPal returns you with an approved event.

Get Email state using codeigniter & sendgrid Webhook

I have integrated sendgrid for send mail. I also want to track whether a user has opened the mail and click the link inside the mail or not.
that's why I used sendgrid.
using it I can send mail, but can't track mail states(mail is opened or not, the link is clicked or not).
I tried the below code for sending mail.
function sendMail($toMails, $body, $subject, $ccMails = array(), $bccMails = array()) {
$ci = &get_instance();
if (empty($toName)) {
$toName = $toMails;
}
$sendMail = $ci->config->item('sendMail');
$email = new \SendGrid\Mail\Mail();
$email->setFrom($ci->config->item('from'), "From User name");
$email->setSubject($subject);
$email->addTos($toMails); //for multiple user pass array with emails and names
$email->addCcs($ccMails);
$email->addBccs($bccMails);
$email->addContent("text/html", $body);
$email->setFooter(false, "", "<strong>If you don't want to receive this type of email in the future, please <a href='http://w3schools.com'>Unsubscribe</a>.</strong>");
//$email->setSpamCheck(true, 1, "http://localhost:8081/");
// Tracking Settings
$email->setClickTracking(true, true);
//$email->setOpenTracking(true, true);
$sendgrid = new \SendGrid($ci->config->item('key'));
try {
$response = $sendgrid->send($email);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
if ($sendMail) :
if (!$response->statusCode()) :
_pre($response->headers());
return false;
else :
return true;
endif;
endif;
}
which is working fine, except it is going in the spam.
now below code, I am using to get details as per email id.
$sendgrid = new \SendGrid($this->config->item('key'));
$query_params = json_decode('{"start_date": "2019-10-07","end_date": "2019-10-07","to_email": "cadmin1#getnada.com","subject":"This is a subject test"}');
$response = $sendgrid->client->stats()->get(null, $query_params);
_pre($response->body());
exit;
above code only gives me date wise data, but I also want email id wise.
but in spite of adding a parameter for that, still, I am not getting desired output.
https://sendgrid.com/docs/for-developers/sending-email/getting-started-email-activity-api/#filter-by-recipient-email
I have used the above demo, in that demo, they have used curl but I am using CodeIgniter's way.
I am not sure about sendgrid version that's why I added both version tag, I used API one.
anyone having a proper solution regarding it?
I have implemented webhooks to archive my desire output.
for that need to follow steps as per documentation shows
after that need to create a page from where we can get mails status.
on executing that page it returns data as per activity.
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: *');
$data = file_get_contents("php://input");
$events = json_encode($data, true);
$requestData = array('response' => $events);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "<url which we earlier set for webhook as per documentation>");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close($ch);
?>
i have used Curl for getting desire output.

Facebook developer roadmap: Deprecating 'comments' field & Removing 'count' from 'comments'

I have noticed the [new changes in FB Developer]: https://developers.facebook.com/roadmap/
I'd like to know what you think I need to change in my code.
I have wordpress and I have a function that counts the total number of comments, and of course it still need to works also after July 10.
function full_comment_count() {
global $post;
$url = get_permalink($post->ID);
$filecontent = file_get_contents('https://graph.facebook.com/?ids=' . $url);
$json = json_decode($filecontent);
$count = $json->$url->comments;
$wpCount = get_comments_number();
$realCount = $count + $wpCount;
if ($realCount == 0 || !isset($realCount)) {
$realCount = 0;
}
return $realCount;
}
Is it as simple as changing:
$count
to
$total_count
or something else needs to be changed as well in the code?
Thank you
Facebook Roadmap:
We are removing the undocumented 'count' field on the 'comments'
connection in the Graph API. Please request
'{id}/comments?summary=true' explicitly if you would like the summary
field which contains the count (now called 'total_count')
...file_get_contents is VERY bad, CURL would be better, but more complicated. the best way to use the graph api in this case is the php sdk: https://github.com/facebook/facebook-php-sdk
anyway, i guess those changes are needed:
$filecontent = file_get_contents('https://graph.facebook.com/?ids=' . $url);
...this is still correct, with a var_dump right after this line (or after the json decode) you see that there is an "id". with that id, you have to make a second call to the graph api:
$comments= file_get_contents('https://graph.facebook.com/' . $id . '/comments?summary=true);
the rest is easy-peasy basic php stuff, just do a var_dump of $comments after using json_decode again.

How to use dodirect payment paypal on form submission?

I have to use dodirect payment method after the form submission. The form will be displayed on the site for all the card detail such as card type (visa or master), card card no, security number, expiration date, name on card, address, state, postal, country, phone, email etc.
I searched how to use the dodirect method and found as below
<?php
/** DoDirectPayment NVP example; last modified 08MAY23.
*
* Process a credit card payment.
*/
$environment = 'sandbox'; // or 'beta-sandbox' or 'live'
/**
* Send HTTP POST Request
*
* #param string The API method name
* #param string The POST Message fields in &name=value pair format
* #return array Parsed HTTP Response body
*/
function PPHttpPost($methodName_, $nvpStr_) {
global $environment;
// Set up your API credentials, PayPal end point, and API version.
$API_UserName = urlencode('my_api_username');
$API_Password = urlencode('my_api_password');
$API_Signature = urlencode('my_api_signature');
$API_Endpoint = "https://api-3t.paypal.com/nvp";
if("sandbox" === $environment || "beta-sandbox" === $environment) {
$API_Endpoint = "https://api-3t.$environment.paypal.com/nvp";
}
$version = urlencode('51.0');
// Set the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Turn off the server and peer verification (TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// Set the API operation, version, and API signature in the request.
$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";
// Set the request as a POST FIELD for curl.
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
// Get response from the server.
$httpResponse = curl_exec($ch);
if(!$httpResponse) {
exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
}
// Extract the response details.
$httpResponseAr = explode("&", $httpResponse);
$httpParsedResponseAr = array();
foreach ($httpResponseAr as $i => $value) {
$tmpAr = explode("=", $value);
if(sizeof($tmpAr) > 1) {
$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
}
}
if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
}
return $httpParsedResponseAr;
}
// Set request-specific fields.
$paymentType = urlencode('Authorization'); // or 'Sale'
$firstName = urlencode('customer_first_name');
$lastName = urlencode('customer_last_name');
$creditCardType = urlencode('customer_credit_card_type');
$creditCardNumber = urlencode('customer_credit_card_number');
$expDateMonth = 'cc_expiration_month';
// Month must be padded with leading zero
$padDateMonth = urlencode(str_pad($expDateMonth, 2, '0', STR_PAD_LEFT));
$expDateYear = urlencode('cc_expiration_year');
$cvv2Number = urlencode('cc_cvv2_number');
$address1 = urlencode('customer_address1');
$address2 = urlencode('customer_address2');
$city = urlencode('customer_city');
$state = urlencode('customer_state');
$zip = urlencode('customer_zip');
$country = urlencode('customer_country'); // US or other valid country code
$amount = urlencode('example_payment_amuont');
$currencyID = urlencode('USD'); // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
// Add request-specific fields to the request string.
$nvpStr = "&PAYMENTACTION=$paymentType&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber".
"&EXPDATE=$padDateMonth$expDateYear&CVV2=$cvv2Number&FIRSTNAME=$firstName&LASTNAME=$lastName".
"&STREET=$address1&CITY=$city&STATE=$state&ZIP=$zip&COUNTRYCODE=$country&CURRENCYCODE=$currencyID";
// Execute the API operation; see the PPHttpPost function above.
$httpParsedResponseAr = PPHttpPost('DoDirectPayment', $nvpStr);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
exit('Direct Payment Completed Successfully: '.print_r($httpParsedResponseAr, true));
} else {
exit('DoDirectPayment failed: ' . print_r($httpParsedResponseAr, true));
}
?>
I didn't get an idea how to use this code on submission of the form that I have on my site. Can anyone help me out how to use this after submitting form.
Thanks in advance :)
That's really not a very well built function. It's basically wanting you to just fill in the values within the function rather than pass them in. It's a pretty rough example and you can see it was last updated in 2008 according to the comments.
If you want to use it, though, you can simply fill in all those placeholders where they show things like "my_api_username" with the data that you want to actually include.
If you want something a lot easier to work with, I would recommend using this PHP library for PayPal that I developed and have maintained for years. It's current and contains straight forward samples for running DoDirectPayment. You could have it up-and-running within minutes.
I offer 30 min of free training via screen share, too, if you're interested in that.
Actually there are samples available for DoDirectPayment as part of the official SDKs available at https://www.x.com/developers/paypal/documentation-tools/paypal-sdk-index#expresscheckoutnew
Suggest using the official SDK and check the samples inside them. In case of any issues please post back here or open an issue at https://github.com/paypal/merchant-sdk-php/issues

How can I fetch information about the app/song/video etc. from iTunes Store?

I need to get an info about the app/song/video by item id from iTunes Store.
I've found this
But it doesn't work with apps.
Is there any public API?
UPD: I can get info using this link
, but this is not a structured data it's just a markup for iTunes to display stuff. I can't rely on that - it can be changed anytime and is hard to parse because it has no consistent structure...
Apple now seems to offer a friendlier search service returning JSON. NB: the documentation does stipulate that the API is for use in connection with promoting the search results (i.e. it's designed for affiliate links).
Example, fetching info about an app if you know its Apple ID:
http://itunes.apple.com/lookup?id=[appleID]
General keyword search
http://itunes.apple.com/search?term=[query]
As far as I know (and I've done a lot of looking), there isn't a public API.
You're right that the HTML isn't semantically structured, so parsing it won't be very robust. But I think it's your only option. Here are a few links which might help :-
A Python script which parses reviews.
An Ars Technica article: Linking to the stars: hacking iTunes to solicit reviews.
An Inside iPhone article: Scraping AppStore Reviews.
There is a public API into iTunes called "iTunes Store Web Service Search API" that returns quite a bit of information. Some of it is documented here but that documentation is incomplete.
You can use the API to get information about everything for sale in iTunes Store and App Store including urls for the artwork, links directly into iTunes, all the apps by a developer, and so on. It's very robust and I'd love to find updated documentation.
I'm currently writing an article at the iPhone Dev FAQ to show how a few things are done and extend the available documentation.
That link you have there is JSON! You've got the solution right here. You just need JSON.framework
I wrote this script for myself. It's not optimized or future-proof, but it's working for me in the meantime...
<?php
ini_set('display_errors', false);
if(isset($_GET['appID']) && isset($_GET['format']))
{
$appID = (int)stripslashes($_GET['appID']);
$format = stripslashes($_GET['format']);
$url = "http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=$appID&mt=8";
$useragent = "iTunes/4.2 (Macintosh; U; PPC Mac OS X 10.2";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
$result = curl_exec($ch);
curl_close($ch);
$temp = str_replace("½","",strip_tags(substr($result,
strpos($result,"Average rating for the current version:"),
strpos($result,"Rate this application:")-strpos($result,"Average rating for the current version:"))));
$temp1 = explode("ratings",$temp);
if(strpos($temp1[2], "Average rating for all versions:"))
$temp1[2] = substr($temp1[2],0,stripos($temp1[2],"Average rating for all versions:"));
$temp1[2] = preg_replace('/\s\s+/', ' ', $temp1[2]);
$temp2 = explode(" ",$temp1[2]);
$ratings[0] = $temp2[1];
$ratings[1] = $temp2[2];
$ratings[2] = $temp2[3];
$ratings[3] = $temp2[4];
$ratings[4] = $temp2[5];
if($format == "prettyPrint")
printRatings($ratings);
else if($format == "XML");
getXML($ratings);
}
else
{
echo "Enter the app id and format (http://iblackjackbuddy.com/getAppRatings.php?appID=###&format=###";
}
function printRatings($ratings)
{
echo "Five stars: " . $ratings[0];
echo "<br>Four stars: " . $ratings[1];
echo "<br>Three stars: " . $ratings[2];
echo "<br>Two stars: " . $ratings[3];
echo "<br>One star: " . $ratings[4];
echo "<hr>Total ratings: " . getTotalRatings($ratings);
echo "<br>Average rating: " . getAverageRating($ratings);
}
function getTotalRatings($ratings)
{
$temp = 1;
for($i=0; $i < count($ratings); ++$i)
$temp+=$ratings[$i];
return $temp;
}
function getAverageRating($ratings)
{
$totalRatings = getTotalRatings($ratings);
return round(5*($ratings[0]/$totalRatings)
+ 4*($ratings[1]/$totalRatings)
+ 3*($ratings[2]/$totalRatings)
+ 2*($ratings[3]/$totalRatings)
+ 1*($ratings[4]/$totalRatings),2);
}
function getXML($ratings)
{
header('Content-type: text/xml');
header('Pragma: public');
header('Cache-control: private');
header('Expires: -1');
echo '<?xml version="1.0" encoding="utf-8"?>';
echo '<Rating>';
echo '<FiveStars>'.$ratings[0].'</FiveStars>';
echo '<FourStars>'.$ratings[1].'</FourStars>';
echo '<ThreeStars>'.$ratings[2].'</ThreeStars>';
echo '<TwoStars>'.$ratings[3].'</TwoStars>';
echo '<OneStar>'.$ratings[4].'</OneStar>';
echo '<TotalRatings>'.getTotalRatings($ratings).'</TotalRatings>';
echo '<AverageRating>'.getAverageRating($ratings).'</AverageRating>';
echo '</Rating>';
}
?>