Google Drive API: Get titles of the parent folders - google-drive-api

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.

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;
}

List of files from my google drive

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.

Creating Json file from mysql

i can't get more than one return in this json. when the original query returns 90k results.
i can't figure out what's hapening.
also the return i get isn't organized as it should. it return the following
{"material":["R8190300000","0"],"grid":["R8190300000","0"]}
sorry to ask this i have been looking for an answer but couln't get it in the internet.
<?php
$link = mysqli_connect("localhost","blablabla","blablabla","blablabla");
if (mysqli_connect_error()) {
die("Could not connect to database");
}
$query =" SELECT material,grid FROM ZATPN";
if( $result = mysqli_query( $link, $query)){
while ($row = mysqli_fetch_row($result)) {
$resultado['material']=$row;
$resultado['grid']=$row;
}
} else {
echo"doesnt work";
}
file_put_contents("data.json", json_encode($resultado));
?>
The problem is that you are overriding the value for the array keys:
$resultado['material']=$row;
$resultado['grid']=$row;
At the end you will have only the last 2 rows; I suggest you to use something like:
$resultado['material'][] = $row;
$resultado['grid'][] = $row;
This will save you pair rows in $resultado['grid'] and unpaired rows in $resultado['material'];
After the information in comments you can use this code:
$allResults = array();
while ($object = mysqli_fetch_object($result)) {
$resultado['id'] = $object->id;
$resultado['name'] = $object->name;
$resultado['item'] = $object->item;
$resultado['price'] = $object->price;
$allResults[] = $resultado;
}
file_put_contents("data.json", json_encode($allResults));

Memory Efficient reading + writing of .csv and .xlsx data

I am looking to implement memory efficient reading and writing of .xlsx/.csv files.
I am currently using phpExcel and am having trouble with large files. (Known issue)
I found the following library for reading: https://github.com/nuovo/spreadsheet-reader
This seems that it will work.
For writing files currently I create an array and then loop the array to output the file. Is this why it uses a lot of memory? What is the best way to not use a lot of memory when writing csv/xlsx when getting data from mysql database using code igniter?
This is what I do now:
/* added for excel expert */
function excel_export() {
$data = $this->Customer->get_all($this->Customer->count_all())->result_object();
$this->load->helper('report');
$rows = array();
$header_row = $this->_excel_get_header_row();
$header_row[] = lang('customers_customer_id');
$rows[] = $header_row;
foreach ($data as $r) {
$row = array(
$r->first_name,
$r->last_name,
$r->email,
$r->phone_number,
$r->address_1,
$r->address_2,
$r->city,
$r->state,
$r->zip,
$r->country,
$r->comments,
$r->account_number,
$r->taxable ? 'y' : '',
$r->company_name,
$r->person_id
);
$rows[] = $row;
}
$content = array_to_spreadsheet($rows);
force_download('customers_export.'.($this->config->item('spreadsheet_format') == 'XLSX' ? 'xlsx' : 'csv'), $content);
exit;
}
function array_to_spreadsheet($arr)
{
$CI =& get_instance();
$objPHPExcel = new PHPExcel();
//Default all cells to text
$objPHPExcel->getDefaultStyle()->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
for($k = 0;$k < count($arr);$k++)
{
for($j = 0;$j < count($arr[$k]); $j++)
{
$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow($j, $k+1, $arr[$k][$j]);
}
}
if ($CI->config->item('spreadsheet_format') == 'XLSX')
{
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
}
else
{
$objWriter = new PHPExcel_Writer_CSV($objPHPExcel);
}
ob_start();
$objWriter->save('php://output');
$excelOutput = ob_get_clean();
return $excelOutput;
}

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