How to allow user to download private document in Scribd - javascript

I would like to ask for any suggestion on how to implement PDF download with private document in Scribd.
Code to upload the document with Scribd using PHP.
function allowPdf($doc_ids) {
$method = "docs.changeSettings";
$params['doc_ids'] = $doc_ids;
$params['access'] = 'private';
$params['download_formats'] = 'pdf';
$params['disable_select_text'] = 1;
// Method from Scribd Developer
// http://www.scribd.com/clients/scribd_php_client.zip
$result = $this->postRequest($method, $params);
return $result;
}
In the Front End code to render out the Scribd JS.
function renderScribdDoc(doc_id, access_key, id) {
id = id || 'embedded_doc';
var scribd_doc = scribd.Document.getDoc(doc_id, access_key),
onDocReady = function(e) {};
scribd_doc.addParam('jsapi_version', 2);
scribd_doc.addParam('hide_disabled_buttons', false);
scribd_doc.addParam('public', true);
scribd_doc.addParam('width', 520);
scribd_doc.addParam('height', 390);
scribd_doc.addEventListener('docReady', onDocReady);
scribd_doc.write(id);
}
I don't know what is the correct way to pass the parameter in Scribd to allow user to download private document as PDF.
Thank you very much.

Related

access php file only from index.php?p=test

im using winwheel.js + custom.js , i have also test.php where file is called by Custom.js to get random StopPosition, all works fine, my question is how can i restrict accessing file test.php?action=try directly, because if i access that file it calls php functions (payWheel(),getReward())
test.php generate an item that will be won if someone will spin the wheel
Custom.js:
function startSpin() {
if (wheelSpinning == false)
{
var jsonData = null;
$.getJSON("wheel-responder.php?action=rotate", function (data)
{
console.log(data);
WheelOfFortune.rotationAngle = 0;
WheelOfFortune.animation.spins = 10;
WheelOfFortune.animation.stopAngle = data["lastPosition"];
WheelOfFortune.startAnimation();
wheelSpinning = true;
});
} }
test.php
if(isset($_GET['action']))
{
if($mycredit>= 100){
if($_GET['action'] == 'try')
_Spin(rand(1, 10), 100);
}
}
If you want to restrict the casual user make it a POST request. That would prevent random access thru address bar.
JS FILE
$.post("wheel-responder.php?action=rotate", function (data) {}
PHP FILE
if(isset($_POST['action'])) {}
Not tested but should be trivial.

Tokbox one to one video calling

I am working on Tokbox video calling process. Now I am using the sample kit of Tokbox which is working properly but it is showing me all active user video.
but I need one user can video calling to another user.
I mean I need one to one video calling process. Is It possible in Tokbox. So please help to solve out it.
This is My code
use Slim\Slim;
use Gregwar\Cache\Cache;
use OpenTok\OpenTok;
if(!empty($userid))
{
$autoloader = __DIR__.'/../../../component/tokbox/vendor/autoload.php';
if (!file_exists($autoloader)) {
die('You must run `composer install` in the sample app directory');
}
require($autoloader);
// PHP CLI webserver compatibility, serving static files
$filename = __DIR__.preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']);
if (php_sapi_name() === 'cli-server' && is_file($filename)) {
return false;
}
// Initialize Slim application
$app = new Slim(array(
'templates.path' => __DIR__
));
// Intialize a cache, store it in the app container
$app->container->singleton('cache', function() {
return new Cache;
});
// Initialize OpenTok instance, store it in the app contianer
$app->container->singleton('opentok', function () {
return new OpenTok('***', '****');
});
// Store the API Key in the app container
$app->apiKey = '45833942';
$id=$this->uri->segment('3');
$urlname=$this->uri->segment('4');
// Configure routes
$app->get('/home/livechat/'.$id.'/'.$urlname.'/', function () use ($app) {
// If a sessionId has already been created, retrieve it from the cache
$sessionId = $app->cache->getOrCreate('sessionId', array(), function() use ($app) {
// If the sessionId hasn't been created, create it now and store it
$session = $app->opentok->createSession();
return $session->getSessionId();
});
// Generate a fresh token for this client
$token = $app->opentok->generateToken($sessionId);
/*$this->db->select('activemember');
$this->db->from('pshy_videocat');
$psychics=$this->db->get();
$totaluseractive= $psychics->row();
$totalactivevideouser=$totaluseractive->activemember;*/
?>
<input type="hidden" id="connectionCountField" value="0"></input>
<!--button onclick="myFunction()">Toggle Video</button-->
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://static.opentok.com/v2/js/opentok.js" charset="utf-8"></script>
<script charset="utf-8">
var publisher;
var connectionCount = 0;
var apiKey = '<?php echo '45833942'; ?>';
var sessionId = '<?php echo $sessionId; ?>';
var token = '<?php echo $token; ?>';
var subscribeoptions = {width: 664, height: 421, insertMode: 'append'}
var session = OT.initSession(apiKey, sessionId)
.on('streamCreated', function(event) {
session.subscribe(event.stream,'myPublisherDiv', subscribeoptions);
})
.connect(token, function(error) {
var publisherOptions = {
insertMode: 'append',
width: 150,
height: 150,
publishAudio:true,
publishVideo:true,
name: "You"
};
publisher = OT.initPublisher('mycam', publisherOptions);
session.publish(publisher);
});
session.on("connectionCreated", function(event) {
connectionCount++;
displayConnectionCount();
});
session.on("connectionDestroyed", function(event) {
connectionCount--;
displayConnectionCount();
});
function displayConnectionCount() {
document.getElementById("connectionCountField").value = connectionCount.toString();
/*var newdata=connectionCount.toString();
$.ajax({
url:$('#baseUrl').val()+"home/updateactiveuser",
type:'post',
data: {newdata:newdata}
})*/
}
var enableVideo=true;
function myFunction() {
if(enableVideo)
{
publisher.publishVideo(false);
enableVideo=false;
} else
{
publisher.publishVideo(true);
enableVideo=true;
}
}
</script>
<?php
});
$app->run();
}
?>
Thanks
Here is a sample code. I've not used SLIM for this. But this can be done with Slim also. I've executed the script 5 times & each time I got a unique Session-Id.
Session Id Received -
Session Id Got : 1_MX40NTgzMzk0Mn5-MTQ5NDMyMzQ0NzU0NH5KNk9Gcy9FSktPSlUwdldUbURwazJ0Umd-QX4
Session Id Got : 2_MX40NTgzMzk0Mn5-MTQ5NDMyMzQ3ODMzM35rWWU5NDV1ZjZPMGhLc3pCS3pRSERJY0h-QX4
Session Id Got : 1_MX40NTgzMzk0Mn5-MTQ5NDMyMzQ5NTcwOX5kc0Q3NDBjQSthOWJaMEk1eUllU3dCY0t-QX4
Session Id Got : 2_MX40NTgzMzk0Mn5-MTQ5NDMyMzUwNzExOH5NMEZuZWRyejBZYnZRVk1zSEczNldocmV-QX4
Session Id Got : 1_MX40NTgzMzk0Mn5-MTQ5NDMyMzUxNzE3NH5Yc0hyMUlacmFqK25pVzhXNDI5NTV6eDB-QX4
Vanilla PHP Script -
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require 'vendor/autoload.php';
use OpenTok\OpenTok;
$apiKey = '45833942';
$apiSecret = '9727d4ae20e8695a8f787bc58c0b4a9ebf6aae6e';
$opentok = new OpenTok($apiKey, $apiSecret);
use OpenTok\MediaMode;
use OpenTok\ArchiveMode;
// An automatically archived session:
$sessionOptions = array(
'archiveMode' => ArchiveMode::ALWAYS,
'mediaMode' => MediaMode::ROUTED
);
$session = $opentok->createSession($sessionOptions);
// Store this sessionId in the database for later use
$sessionId = $session->getSessionId();
echo "Session Id Got : $sessionId";
SLIM Version -
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use OpenTok\OpenTok;
use OpenTok\MediaMode;
use OpenTok\ArchiveMode;
require 'vendor/autoload.php';
$app = new \Slim\App;
$container = $app->getContainer();
$container['opentok'] = function ($c) {
$apiKey = '45833942';
$apiSecret = '9727d4ae20e8695a8f787bc58c0b4a9ebf6aae6e';
$opentok = new OpenTok($apiKey, $apiSecret);
return $opentok;
};
$app->get('/', function (Request $request, Response $response) {
// An automatically archived session:
$sessionOptions = array(
'archiveMode' => ArchiveMode::ALWAYS,
'mediaMode' => MediaMode::ROUTED
);
$session = $this->opentok->createSession($sessionOptions);
// Store this sessionId in the database for later use
$sessionId = $session->getSessionId();
$response->getBody()->write("Session Id Got : $sessionId");
return $response;
});
$app->run();
Hope, it'll help you.
Ref : https://tokbox.com/developer/sdks/php/
Looks like you have based your code on the OpenTok Hello World PHP sample. This sample is written to support a single session only, for demonstration purposes. Your issue here is that you are retrieving the same key (sessionId) from cache every time, which is what the sample does.
You are close. The simplest way to extend this sample to multiple sessions is to store your new session IDs in the cache as different keys. You need to change your code to use different key for storing and retrieving session ID. So, you can change the cache retrieval logic from:
<?php
$sessionId = $app->cache->getOrCreate('sessionId', array(), function() use ($app) {
# ...
}
?>
to something like:
<?php
# Here we add `$id` from the URI segment to create a unique key
# Notice the change in the key name to `'session' . $id'`
$sessionId = $app->cache->getOrCreate('session' . $id, array(), function() use ($app) {
# ...
}
?>
At the simplest, your code needs to map your application's live chat ID to an OpenTok session internally. Everytime you request for a new livechat ID, it will create a new OpenTok session and store the new OpenTok session ID internally for that livechat ID.
So, you should have two different sessions if you request:
/home/livechat/foo/bar
/home/livechat/baz/bar
Bonus
A quick tip on creating OpenTok sessions: This is all you need to create a new session using OpenTok PHP SDK:
<?php
use OpenTok\OpenTok;
$apiObj = new OpenTok($API_KEY, $API_SECRET);
# This function creates an OpenTok session and returns a new session ID
function createOTSession() {
$session = $apiObj->createSession(array('mediaMode' => MediaMode::ROUTED));
return $session->getSessionId();
}
?>
Everytime you call $apiObj->createSession(), it creates a new session and you can access the session id by calling getSessionId() on the returned object. If you have a function like createOTSession() above, you can call that function from a route that needs to creates new sessions.
See: Creating OpenTok sessions in PHP

Singleton class not just once instantiated in php

I need a help with a singleton class. I`m creating a wordpress plugin, and need to have live notifications from server. For that I used AJAX long polling and my code looks like this.
This is a php code used for serving AJAX request and for LOG class which is singleton and called from many different places in project
if (isset($_GET['log']) && $_GET['log'] == 'true')
{
$response = array();
$response['msg'] = SI_log::get_instance()->get_message();
$response['type'] = 'something';
echo json_encode($response);
}
class SI_log{
private $log_messages = array();
private static $instance = NULL;
private $log_file;
public static function get_instance()
{
if (static::$instance === NULL) {
static::$instance = new static();
}
return static::$instance;
}
public function add_message( $message, $type )
{
array_push($this -> log_messages, $message);
}
public function get_message()
{
return end($this->log_messages);
}}?>
This is javascript for retrieving notifications and its a part of admin section in the wordpress.
<script type="text/javascript" charset="utf-8">
function waitForMsg(){
setTimeout(waitForMsg,5000);
document.getElementById("alerts").childNodes = new Array();
var request = new XMLHttpRequest();
request.open('GET', '<?php echo get_site_url() . '/wp-content/plugins/si/admin/c-si-log.php?log=true'?>', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var resp = request.responseText;
alert(resp);
var json = eval('('+resp+ ')');
document.getElementById("alerts").innerHTML= json['type'] +"<hr>";
if (json['type'] == 'WARNING'){
var html_element = '<div class="alert-message warning" id = "alert_warning"><div class="box-icon"></div><p>'+json['msg']+'</p></div>';
}
if (json['type'] == 'INFO'){
var html_element = '<div class="alert-message info" id = "alert_info"><div class="box-icon"></div><p>'+json['msg']+'</p></div>';
}
if (json['type'] == 'ERROR'){
var html_element = '<div class="alert-message errorr" id = "alert_error"><div class="box-icon"></div><p>'+json['msg']+'</p></div>';
}
document.getElementById("alerts") . innerHTML= html_element;
}else{
alert('<?php echo get_site_url() . '/wp-content/plugins/si/admin/c-si-log.php?log=true' ?>');
}
};
request.onerror = function() {
// There was a connection error of some sort
alert("request isnt good");
};
request.send();
}
window.onload = function (){
if (document.readyState != 'loading'){
waitForMsg();
} else {
document.addEventListener('DOMContentLoaded', waitForMsg);
}
}
</script>
This is how is singleton class called from another class for notification input
SI_log::get_instance()->add_message("action triggered", 'INFO');
I assume the problem is singleton pattern implementation in SI_log class, so there is not only one instance of that class but many more, and when i try to retrieve the notification ie. when I trigger some action, notification isn`t stored in the same object. I used alert(resp); in cilent page to display response and response looks like this
{
"msg":false,
"type":"something"
}
and in log.php you can see that the type value is fine, so it's not communication problem. Can anyone help me please?
NOTE: I must use Javascript because versioning problems so don't ask me why i didn't use JQuery
The singleton pattern is useful when we need to make sure we only have a single instance of a class for the entire request lifecycle in a web application.
So, you can't do the thing you want to achieve in this way.
Instead, use it as a base/parent class and extend it on other classes when you need it.

local file system access - solutions?

2nd question I've posted. still very new to web programming so excuse my ignorance.
I have a web based javascript which accesses a users Gmail account and downloads attachments to the local downloads folder as assigned in Chrome.
These files are then manually transferred to another directory and an Excel VBA script processes the files.
I'd like to be able to skip the manual transfer step and save the files directly to to the folder that Excel is looking at. I can get the Excel script to move the files but it only works if the user has not changed the Chrome default downloads folder location so it's not foolproof.
I believe this is impossible with javascript but is it possible with other languages or do I need a completely different approach? if it is possible with other languages which one and which methods do I need to be looking at?
This is the download section of the code as it stands at the minute at the request of a user OmegaStripes below:
<html>
<head>Google Drive File Download Process:
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<script type="text/javascript">
var CLIENT_ID = 'XXXXXXXXXXX';//removed for privacy
var SCOPES = 'https://www.googleapis.com/auth/drive';
/**
* Called when the client library is loaded to start the auth flow.
*/
function handleClientLoad() {
window.setTimeout(checkAuth, 1);
}
/**
* Check if the current user has authorized the application.
*/
function checkAuth() {
gapi.auth.authorize({
'client_id': CLIENT_ID,
'scope': SCOPES,
'immediate': true
},
handleAuthResult);
}
/**
* Called when authorization server replies.
*
*/
function handleAuthResult(authResult) {
var authButton = document.getElementById('authorizeButton');
var filePicker = document.getElementById('filePicker');
authButton.style.display = 'none';
filePicker.style.display = 'none';
if (authResult && !authResult.error) {
// Access token has been successfully retrieved, requests can be sent to the API.
filePicker.style.display = 'block';
filePicker.onclick = downloadFile; // to allow for manual start of downloads
window.setTimeout(downloadFile(), 5000);
} else {
// No access token could be retrieved, show the button to start the authorization flow.
authButton.style.display = 'block';
authButton.onclick = function() {
gapi.auth.authorize({
'client_id': CLIENT_ID,
'scope': SCOPES,
'immediate': false
},
handleAuthResult);
};
}
}
/**
* Start the file download.
*
*
*/
function downloadFile() {
console.log("call drive api");
gapi.client.load('drive', 'v2', makeRequest);
}
function makeRequest() {
console.log("make request");
var request = gapi.client.drive.files.list();
request.execute(function(resp) {
var x = []; //array for revised list of files to only include those not in the trash and those which have a suffix #FHM#
for (i = 0; i < resp.items.length; i++) {
if (resp.items[i].labels.trashed != true && resp.items[i].title.substring(0, 5) == "#FHM#") {
x.push([resp.items[i].title, resp.items[i].webContentLink, resp.items[i].id]);
}
}
if (x.length == 0) {
document.getElementById("filePicker").value = "There are no files to download";
}
for (i = 0; i < x.length; i++) {
console.log(x.length);
var dlUrl = x[i][1];
fileIdentity = x[i][2];
downloadUrl(dlUrl);
trashFile(fileIdentity);
filePicker.style.display = 'none';
document.getElementById("bodyText").innerHTML = "<br>Download " + (i + 1) + " of " + x.length + " completed.";
}
});
//window.setTimeout(function() {
// self.close;
//}, 5000);
}
function downloadUrl(url) {
var iframe = document.createElement("iframe");
iframe.src = url;
iframe.style.display = "none";
document.body.appendChild(iframe);
}
function trashFile(id) {
var requestTrash = gapi.client.drive.files.trash({
'fileId': id
});
requestTrash.execute(function(resp) {});
}
</script>
<script type="text/javascript" src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
</head>
<body>
<!--Add buttons for the user to start the process -->
<input type="button" id="filePicker" style="display: none" value="If download does not start after 5 seconds, click here" />
<input type="button" id="authorizeButton" style="display: none" value="Authorize" />
<b id="bodyText"></b>
</body>
thanks
Your code could try to copy the files and if unsuccessful, ask the user to provide the correct path to the extracted file(s). You are right it cannot be done by Javascript. If you want to avoid having to ask the user for the path, you can implement a module to search for the file.
Is there a way you could know whether a file was extracted? If so, you can use this knowledge to know whether the lack of successful copying should trigger a file search or file path requesting.

Popup with POST method Invokes in the test Azure but fails in the real Azure

I want my Silverlight cloudapp to use the SSRS Reportviewer control hosted in a WebForm called Reportviewer.aspx, and this is working well from the test Azure "127.0.0.1" environment when Invoking the javascript OpenReportviewer function from my SL C# class:
<script type="text/javascript" src="Silverlight.js"></script>
<script type="text/javascript">
function OpenReportViewer(ReportViewerURL, TabHeading, EstId, ShowExtraDetail, ReportTypeID, PreExpandSections) {
var form = document.createElement('form');
form.action = ReportViewerURL; //'http://endorphin.cloudapp.net/Reporting/ReportViewer.aspx';
form.method = "POST";
form.target = '_blank'; // this is important to open a new window
var tabHeading = document.createElement('input');
tabHeading.name = 'TabHeading';
tabHeading.value = TabHeading;
form.appendChild(tabHeading);
var estID = document.createElement('input');
estID.name = 'EstID';
estID.value = EstId;
form.appendChild(estID);
var showExtraDetail = document.createElement('input');
showExtraDetail.name = 'ShowExtraDetail';
showExtraDetail.value = ShowExtraDetail;
form.appendChild(showExtraDetail);
var reportTypeID = document.createElement('input');
reportTypeID.name = 'ReportTypeID';
reportTypeID.value = ReportTypeID;
form.appendChild(reportTypeID);
var preExpandSections = document.createElement('input');
preExpandSections.name = 'PreExpandSections';
preExpandSections.value = PreExpandSections;
form.appendChild(preExpandSections);
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
function onSilverlightError(sender, args) {...
However I've now deployed to the real Azure and it says: "Failed to Invoke: OpenReportviewer"
The above function is now pasted exactly.
The calling code is:
//**********************************************************************************
public void Invoke3(string tabHeading, int estID, int reportTypeID, bool showExtraDetail, bool preExpandSections)
{
if (true == HtmlPage.IsPopupWindowAllowed)
{
string strBaseWebAddress = App.Current.Host.Source.AbsoluteUri;
int PositionOfClientBin =
App.Current.Host.Source.AbsoluteUri.ToLower().IndexOf(#"/clientbin");
strBaseWebAddress = Strings.Left(strBaseWebAddress, PositionOfClientBin);
string ReportViewerURL = String.Format(#"{0}/Reporting/ReportViewer.aspx", strBaseWebAddress);
try
{
HtmlPage.Window.Invoke("OpenReportViewer", ReportViewerURL, tabHeading, estID.ToString(),
showExtraDetail.ToString(), reportTypeID.ToString(), preExpandSections.ToString());
}
catch (Exception ex)
{
My.ShowError("Failed to invoke Webform for Report Viewer.", ex);
}
}
else
{
MessageBox.Show("You must enable popups to view reports. Safari browser is not supported.",
"Error", MessageBoxButton.OK);
}
}
There are 2 possibilities:
The difference between the local Azure and real Azure could be the security zone.
There could be some hard coded link that points to the local Azure.

Categories