Retrieve firebase server time without setting it first - php

Is there a way to obtain the server time without having to first set it? For example, I can simply do:
curl -X PUT -d '{".sv": "timestamp"}' https://SampleChat.firebaseIO-demo.com/servertime.json
which will return the server time, but this sets the value servertime within my firebase instance. I should note that I'm using the REST API.

You can retrieve the server time without writing it by using .info/serverTimeOffset:
var fbRef = new Firebase(URL);
var getServerTime = (function(ref) {
var offset = 0;
ref.child('.info/serverTimeOffset').on('value', function(snap) {
offset = snap.val();
});
return function() {
return Date.now() + offset;
}
})(fbRef);
var now = getServerTime();

Related

Google-App-Script vs php in encoding base64

This php code decodes the secret key before hashing with SHA 512
$API_SECRET_KEY="W0+m0Dc9GMN9yDVeq3GMDsJ49WasEhQHkNHNuDw3wNg=";
$BDAPI_SECRET_KEY=base64_decode($API_SECRET_KEY);
$HMAC_SIGN = base64_encode(hash_hmac('sha512',$MESSAGE,$BDAPI_SECRET_KEY,true));
echo $HMAC_SIGN;
BfVNi21gY09c8M18cWBRBgo1W9pAlXM99ZVoF7Kz2ETFnIuvXjj8NRvRgn/GaT/m6YJ8efsr5s9EDbIhznAaag==
I want to replicate this in google app script
var Secret = "W0+m0Dc9GMN9yDVeq3GMDsJ49WasEhQHkNHNuDw3wNg="
var BDSecret= Utilities.base64Decode(Secret)
var hmac = Utilities.base64Encode(Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, message, BDSecret ));
Logger.log(hmac)
ew5KhLWSJixn8zw4s6VkpYIwvGBjrmjY3LhNWZr9CVEw6W22LOGg+lVzA3uQgOVyICSCffw2bzTepnBdoYtldw==
If I do not decode the API before hashing they return the same result. But for this particular purpose, the key needs to be decoded. The message variable is just my first name "Parit" in case someone wants to replicate.
I thought that Utilities.computeHmacSignature() might not be able to use []byte for the value. So as a workaround, how about using jsSHA? I think that in your case, you can use https://github.com/Caligatio/jsSHA/blob/master/src/sha512.js.
The flow for using jsSHA is as follows.
Flow :
Download sha512.js.
On script editor, create new script as for example, the filename of sha512.js.
Copy and paste the script of sha512.js to the created script.
Copy and paste the sample script to Code.gs of the script editor.
Run myFunction() of the sample script.
Sample script :
function myFunction() {
var message = "Parit";
var secret = "W0+m0Dc9GMN9yDVeq3GMDsJ49WasEhQHkNHNuDw3wNg=";
var obj = new jsSHA("SHA-512", "TEXT");
obj.setHMACKey(secret, "B64");
obj.update(message);
Logger.log(obj.getHMAC("B64"))
}
Note :
When I tested Parit for message, I got BfVNi21gY09c8M18cWBRBgo1W9pAlXM99ZVoF7Kz2ETFnIuvXjj8NRvRgn/GaT/m6YJ8efsr5s9EDbIhznAaag==.
It this was not useful for you, I'm sorry.
Update :
By the Google's update at June 19, 2018, Utilities.computeHmacSignature() got to be able to use the byte arrays. By this, using only native Google Apps Scvript, the result can be retrieved without using jsSHA. So I would like to update my answer.
Modified script :
function myFunction() {
var message = "Parit";
var secret = "W0+m0Dc9GMN9yDVeq3GMDsJ49WasEhQHkNHNuDw3wNg=";
var value = Utilities.base64Decode(Utilities.base64Encode(message));
var key = Utilities.base64Decode(secret);
var out = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, value, key);
var res = Utilities.base64Encode(out)
Logger.log(res)
}
Result :
BfVNi21gY09c8M18cWBRBgo1W9pAlXM99ZVoF7Kz2ETFnIuvXjj8NRvRgn/GaT/m6YJ8efsr5s9EDbIhznAaag==

Detect feature suport with modernizer and process with PHP based on result

So I need to detect webp support using modernizer, and then do some processign in PHP depending on the outcome of the result.
Now at first I thought I could set a cookie and get the cookie using PHP like so:
JS:
Modernizr.on('webp', function (result) {
if (result) {
setCookie("webpissupported", "yes", "365");
}
});
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
PHP:
$userAvatar = um_get_avatar_uri( um_profile('profile_photo'), 190 );
$patterns = array("/.jpg/", "/.jpeg/", "/.png/");
if (isset($_COOKIE['webpsupport']))
$userAvatar = preg_replace($patterns, "_result.webp", $userAvatar);
Now the problem with the above code is that I'm using the wordpress plugin w3 total cache, with the page cache enabled. this is causing the cookie to be cached and producing unexpected results.
So then I thought maybe I could do something like this:
<script type="text/javascript">
Modernizr.on("webp", function (result) {
if (result) {
<?php $webpSupport = true; ?>
}
});
</script>
But this will not work.
Anyone know how I might get around this problem.
You have mixed (client) browser-side processing with server-side (PHP). In your example, PHP block of code shall be executed regardless of what is to be processed later by browser/JS (or won't at all, in case of no JS browser). So, $webpSupport variable in this case and example shall be what you assign to it in order from top to bottom.
One way to achieve what you are after is to have JS cookie set, setCookie("webpissupported", "yes", "365"); and in the next page view read the $_COOKIE['webpissupported'] and serve images according to it.
Remember, webp is not a standard, although present in 72.85% browsers according to caniuse.com /StatCounter. You have to use it as progressive enhancement.

Calling data from Javascript through a proxy server

We have the following code in Javascript:
var speakMe = function (text) {
var key, lang, url, audio;
key = "key=1234567890";
lang = "sv_se";
url = "http://api.ttsengine.com/api/read?" + key + "&lang=en_us&voice=male1&speed=100&audioformat=ogg&oggbitrate=100&text=" + text;
audio = new Audio(url);
audio.play();
};
It functions well. However, I would like to mask the key. For this I have been advised to use a PHP proxy script.
I found this proxy but I don't know how to implement it. How do I get the data I normally get, but through this proxy?
Per the documentation of your proxy script. you can call your script and pass a url argument which then it will return the content back. you must also set mode=native as another url parameter.
// > ba-simple-proxy.php?url=http://example.com/&mode=native
//
// Response:
//
// > <html>...</html>
//
// Topic: Notes
//
// * Assumes magic_quotes_gpc = Off in php.ini

how to get hosted server(LAN) datetime in javascript

I have a web application, where users need to get the week number in a text box. Since the users/client machines are in different time zone, they are getting the week number based on their machine datetime. How can I call the hosted server datetime in javascript. So that I can convert the date to week in common, irrespective of client machine datetime.
Hosted server is only connected in LAN, no internet access. Server Side language is PHP
Please help.
<html>
<head>
<script>
window.date = new Date(<?php echo time();?> * 1000);
window.now = new Date();
window.getTime = function() {
var n = new Date();
n = n.getTime() - window.now.getTime();
return new Date(window.date.getTime() + n);
}
</script>
And then you can access it anywhere using window.getTime(), which uses your server time + how long they have been on your page
here is an ajax-only way:
<script>
function sTime(callback) {
callback=callback||alert;
var XHRt = new XMLHttpRequest;
XHRt.onreadystatechange = function() {
if (XHRt.readyState == 4 && XHRt.status == 200) {
callback( new Date(XHRt.getResponseHeader("date")) , XHRt);
}
};
XHRt.open("HEAD", location.href, true);
XHRt.send();
return XHRt;
} /* end aHead() */
//demo to show remote and local times:
sTime(function(dt){ alert( [dt, new Date].join("\n"));});
</script>
when i ran from firebug here, seems im about 1 second behind SO...

Implementing a counter on function returning files from gdrive

I want to implement a counter which keeps track of the number of times a file is downloaded. The function retrieves files from the google drive and it is printed on to the screen using for loop. Please help with a logic where to implement the counter to keep track of the count.
The function is as follows:
function makeRequest() {
var request = gapi.client.drive.files.list();
request.execute(function(resp) {
for (i=0; i<resp.items.length; i++) {
var titulo = resp.items[i].title;
var fechaUpd = resp.items[i].modifiedDate;
var userUpd = resp.items[i].lastModifyingUserName;
var userEmbed = resp.items[i].embedLink;
var userAltLink = resp.items[i].alternateLink;
var download = resp.items[i].webContentLink;
var hold="Download";
var flag=0;
<!-- var fileInfo = document.createElement('li');
<!-- fileInfo.appendChild(document.createTextNode('TITLE: ' + titulo + ' - LAST MODIF: ' + fechaUpd + ' - BY: ' + userUpd +' url: ' + hold.link(download)));
<!-- document.getElementById('content').appendChild(fileInfo);
document.write(titulo + " ");
document.write(hold.link(download) + "<br>");
<!--flag=1;
}
<!--if(flag!=1){
<!--document.write("not found!");
<!--}
}); ;
}
I am not sure I understand what you want to keep track off.
If you want to a single user to be able to see how many times that user has downloaded a file, it could be implemented in javascript and store the information in a cookie.
If you on the other hand want to see how many times a file has been downloaded by any user, it has to be implemented on the server side using PHP or whatever language you have available.
The key question here is if you can/want to implement the functions on the server or the client side. To do it on the client side you use javascript, to do it on the server side you can use PHP.

Categories