List of files from my google drive - google-drive-api

I am writing PHP script which get files from my Google Drive folder and write list of them with download links on my website, but can not find solution which take files from my folder. Every solution I found need sign up from user, that is viewing page and get list of files from his google drive. Can anyone help me with solution?
Here is my code.
function printFilesInFolder($service, $folderId) {
$pageToken = NULL;
do {
try {
$parameters = array();
$parameters = array(
'q' => "'0B5NCdsbrL1VfQ00xY3pFS3BtOE0' in parents"
);
$children = $service->files->listFiles($parameters);
var_dump($children);
foreach ($children->getFiles() as $child) {
print 'File Id: ' . $child->getId();
}
$pageToken = $children->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
}
$client = new Google_Client();
$client->setApplicationName("Web client 1");
$client->setClientId('CLIENTID');
$client->setClientSecret('SECRET');
$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
$client->setRedirectUri('http://localhost/googledrive/drive/drive.php');
if (isset($_GET['code']) || (isset($_SESSION['access_token']) && $_SESSION['access_token'])) {
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
} else
$client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_Drive($client);
$ret = printFilesInFolder($service,"FOLDERID");
} else {
$authUrl = $client->createAuthUrl();
header('Location: ' . $authUrl);
exit();
}
But i still dont getting right data.
Second think is, that i want to remove need of authentication on every refresh of page, but i dont know how to do that.

Related

MediaWiki - Hook to edit/alter page title on creation

I'm looking to (programmatically) edit/alter the title of a page when its created and before its saved. I've tried a couple hooks to no avail. I can access the title being saved along with other info which ill be used to alter the title, but can not find the right call to save the altered title.
It is for a private/local lan wiki (currently MediaWiki version 1.38.1 ).
When a new article is created with in a certon category I want to number it with a prefix of #### - based on the number of articles already in the category. At the top of the category page itself I have a <inputbox> which pulls a template that has the wiki syntax for the category in it [[Category:BlaBla]]. When the article is saved I'm doing a check to make sure its a new article and some ofther checks for the info I need, which is working fine, but I can not save the new altered page name.
I've tried the following hooks to no avail.
onMultiContentSave
onArticlePrepareTextForEdit
https://www.mediawiki.org/wiki/Manual:Hooks/MultiContentSave
https://www.mediawiki.org/wiki/Manual:Hooks/ArticlePrepareTextForEdit
Heres acouple snippets ive been testing with, both do as i want, aside from saving the altered page name.
public static function onArticlePrepareTextForEdit( WikiPage $wikiPage, ParserOptions $parserOptions ) {
return;
$exists = $wikiPage->exists();
if ($exists == 1) {
#return true;
}
$getTitle = $wikiPage->getTitle();
# check if title starts with 0000, exit if so, no work needs to be done
if (self::titleCheck($getTitle)) {
#return true;
}
$checkCategories = $wikiPage->getCategories();
$inMalak = false;
foreach ($checkCategories as $value) {
if ($value == "Category:Malak") {
$inMalak = true;
}
}
if ($inMalak == 1) {
$newTitle = self::newTitlePre() . $getTitle;
#$wikiPage->setTitle($newTitle);
print(">" . $newTitle . "<br>");
}
self::pr($newTitle);
}
public static function onMultiContentSave(RenderedRevision $renderedRevision, UserIdentity $user, CommentStoreComment $summary, $flags, Status $hookStatus){
#return;
$revision = $renderedRevision->getRevision();
$getTitle = $revision->getPageAsLinkTarget();
if (self::titleCheck($getTitle)) {
return true;
}
#$titleOBJ = $revision->Title();
$title = $revision->getId();
$parent_id = $revision->getId();
$content = $revision->getContent( SlotRecord::MAIN );
$new_content = $content->getText();
#$test = $revision->ParserOutput();
$parent_id = "";
if ($parent_id == "") {
$pos = strpos($new_content, "[[Category:Malak]]");
if ($pos) {
$newTitle = self::newTitlePre() . $getTitle;
#$wikiPage->setTitle($newTitle);
}
}
self::pr($newTitle);
}
EDIT........
Still have not found the proper way to do this, but came up with a work around (hackery) which works for my needs.
Using the onEditFormPreloadText hook, change the url and added a new parameter ('MalakHere'), edited the 'title' parameter to the altered title, then do a redirect with the new page name. In the hook function there is a check for the 'MalakHere' parameter, if found (only cause of redirect) then it will exit the function so not to create a loop.
public static function onEditFormPreloadText(string &$text, Title &$title ) {
global $wgOut;
if ( isset( $_GET["MalakHere"] ) ) {
return true;
}
$pos = strpos($text, "[[Category:Malak]]");
if ($pos) {
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$urlTitle = urlencode($_GET["title"]);
$newURL = str_replace("title=" . $urlTitle,"MalakHere=yes",$url);
$newTitle = self::newTitlePre() . $title->prefixedText;
$url = $newURL . "&title=" . $newTitle;
return $wgOut->redirect($url);
}
return true;
}
Still have not found the proper way to do this, but came up with a work around (hackery) which works for my needs.
Using the onEditFormPreloadText hook, change the url and added a new parameter ('MalakHere'), edited the 'title' parameter to the altered title, then do a redirect with the new page name. In the hook function there is a check for the 'MalakHere' parameter, if found (only cause of redirect) then it will exit the function so not to create a loop.
public static function onEditFormPreloadText(string &$text, Title &$title ) {
global $wgOut;
if ( isset( $_GET["MalakHere"] ) ) {
return true;
}
$pos = strpos($text, "[[Category:Malak]]");
if ($pos) {
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$urlTitle = urlencode($_GET["title"]);
$newURL = str_replace("title=" . $urlTitle,"MalakHere=yes",$url);
$newTitle = self::newTitlePre() . $title->prefixedText;
$url = $newURL . "&title=" . $newTitle;
return $wgOut->redirect($url);
}
return true;
}

Using Google Open ID Connect to Access User's Gmail Account

How can I run a google apps script API on multiple gmail accounts? I currently have a script that accesses a user's gmail when it is authorized by the two files shown below. I store the refresh token for the client once the code asks for authorization. However, how can I use Open ID to get authorization for various users' accounts? Do I need to store a client id in addition to a refresh token to gain authorization for a user's gmail account? Thanks for taking the time to help in advance!
read_email.php
<?php
require_once '../google-api-php-client/src/Google/autoload.php';
function getEmails (){
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->setScopes(array(
'https://mail.google.com/'
));
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
if($client->isAccessTokenExpired()){
header('Location: http://' . $_SERVER['HTTP_HOST'] . '/email_database/php/oauth2callback.php');
}
// Get the API client and construct the service object.
$service = new Google_Service_Script($client);
$scriptId = '**********************';
// Create an execution request object.
$request = new Google_Service_Script_ExecutionRequest();
set_time_limit(0);
$request->setFunction('test');
$response = $service->scripts->run($scriptId, $request);
$response = $response->getResponse();
$response = $response['result'];
return ($response);
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/email_database/php/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
}
?>
oauth2callback.php
<?php
require_once '../google-api-php-client/src/Google/autoload.php';
include 'functions.php';
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/email_database/dashboard/php/oauth2callback.php');
$client->setScopes(array(
'https://mail.google.com/'
));
$client->setAccessType('offline');
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/email_database/dashboard/php/read_email.php';
$username = $_SESSION['username'];
$user = getUser($username);
if($user['refresh_token'] == null){
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
//echo $_GET['code'];
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$google_token = json_decode($_SESSION['access_token']);
print_r($google_token);
$refresh_token = $google_token->refresh_token;
addRefreshToken($username,$refresh_token);
//header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
}
else {
$refresh_token = $user['refresh_token'];
$client->refreshToken($refresh_token);
$_SESSION['access_token']= $client->getAccessToken();
// header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
?>

Google Drive API: Get titles of the parent folders

I have this code from google:
function retrieveAllFiles($service) {
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$result = array_merge($result, $files->getItems());
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $result;
}
I know i can do this:
$files = retrieveAllFiles($service);
foreach($files as $file){
$id = $file->getId();
$title = $file->getTitle()
}
We can also fetch the parents of the file by:
foreach($files as $file){
$parents = $file->getParents();
}
Is it possible to get the titles of the parent folders without calling another request? like:
foreach($files as $file){
$parents = $file->getParents();
foreach($parents as $parent){
$parent_title = $parent->getTitle(); //NOT EXISTING
}
}
I know that it throws an error but is there other alternative to achieve this requirement?
No it's not possible. Embedding the meta data of one file within another would make for an ugly API. The Drive API is a very clean REST API, which means that you'll need to make multiple requests.
I've edited your question slightly to clarify that a file can have more than one parent.

Show Chrome extension version on options page?

I've got my manifest file with my version number and an options page. Is there a way to display the installed version and latest available version on the options page without needing to do it manually?
You can get the current version of your extension using chrome.runtime.getManifest().version.
In order to get the "latest version" of your extension, you need to download updates.xml, and extract the version number:
var extensionID = chrome.i18n.getMessage('##extension_id');
var currentVersion = chrome.runtime.getManifest().version;
var url = 'https://clients2.google.com/service/update2/crx?x=id%3D' + extensionID + '%26v%3D' + currentVersion;
var x = new XMLHttpRequest();
x.open('GET', url);
x.onload = function() {
var doc = new DOMParser().parseFromString(x.responseText, 'text/xml');
// Get and show version info. Exercise for the reader.
};
x.send();
If you want to customize your request with PHP, avoiding to update the extension every time Google changes the API, I suggest the following
update_info.php (from your site):
<?php
$last_ver;
$googleupdate = 'http://clients2.google.com/service/update2/crx?response=updatecheck&x=id%3D__id__%26uc';
$ver = $_POST['ver'];
$id = $_POST['id'];
//filter/control for post request very fast for this example
if(isset($id) && isset($ver)){
if(strlen($id)>0){
$urlupdate = str_replace('__id__', $id, $googleupdate);
$last_ver = _GetLastVersion($urlupdate);
if($last_ver>0 && $last_ver>$ver){
echo 'New version available, v'.$last_ver;
}else{
echo 'Your version is update';
}
}else{
echo 'Insert id for response';
}
}else{
echo 'Insert data for response';
}
//if your server do not connect with file_get_contents() use this function
function getContent ($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
$output = curl_exec($ch);
$info = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($output === false || $info != 200) {
$output = null;
}
return $output;
}
//this function return 0 if error or not content load
function _GetLastVersion($url){
try {
$last=0;
//if you have proble you can use getContent($url)
$xmlcontent = file_get_contents($url);
if($xmlcontent){
$doc = new DOMDocument();
$doc->loadXML($xmlcontent);
$items = $doc->getElementsByTagName('updatecheck');
foreach ($items as $item) {
if($item->getAttribute('version')>0){
return $item->getAttribute('version');
}
}
return $last;
}else{
return 0;
}
} catch (Exception $e) {
return 0;
}
}
?>
in your extension send request to your webpage, now you are in control of your script, you can decide which answer back every time

google drive api dont know where it saves the file but when fetched it shows the saved but not the others

I used the google drive api to insert a text file...
Build Service
function buildService() {
$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = 'xxxx#developer.gserviceaccount.com';
if($_SERVER['HTTP_HOST'] == 'localhost')
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'xxxxxxxx-privatekey.p12';
else
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = $_SERVER['DOCUMENT_ROOT'].'/xxxxx-privatekey.p12';
$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_AssertionCredentials(
$SERVICE_ACCOUNT_EMAIL,
array($DRIVE_SCOPE),
$key);
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
return new Google_DriveService($client);
}
Retrieve Files
function retrieveAllFiles($service) {
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$result = array_merge($result, $files->getItems());
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $result;
}
Creating an instance and inserting
$service = buildService();
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = "contents";
$createdFile = $service->files->insert($file, array('data' => $data,'mimeType' =>'text/plain',));
print_r($createdFile);
echo '<br>------<br>';
Retrieving files
$ret = retrieveAllFiles($service);
echo '<pre>';
print_r($ret);
As in the fist call i insert a file...
in the second call i am trying to list all files...
when i try to list i could see only the inserted file but not the others which i could see in my drive by logging into docs.google.com. i am already having 6 files online
as per the documentation i created service account with the private keys and the service account email.
so where will that file be store and how do i list all other files in the root of google drive?
You are inserting files in the application-owned account represented by the service account.
If you want to manage (insert/list/...) files in another domain user's Drive account, you'll have to perform Domain-wide delegation: https://developers.google.com/drive/delegation