Skip to content

Instantly share code, notes, and snippets.

@giltotherescue
Created March 19, 2015 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giltotherescue/f5877919086f69e6369a to your computer and use it in GitHub Desktop.
Save giltotherescue/f5877919086f69e6369a to your computer and use it in GitHub Desktop.
<?
/*
==== Custom Google Drive Wrapper ====
By: Gil Hildebrand (https://github.com/giltotherescue)
Google Drive authentication setup instructions:
https://developers.google.com/api-client-library/php/auth/service-accounts
*/
class Drive {
const MIME_FOLDER = 'application/vnd.google-apps.folder';
const MIME_PLAIN = 'text/plain';
public $client, $service, $q, $res;
function __construct($client_email = null, $private_key = null, $user_email = null) {
$this->connect($client_email, $private_key, $user_email);
}
/**
* Connect to the specified Google Drive account
* @param $client_email
* @param $private_key
* @param $user_email
* @return bool
*/
function connect($client_email, $private_key, $user_email) {
if ($client_email && $private_key && $user_email) {
$scopes = array('https://www.googleapis.com/auth/drive');
$credentials = new Google_Auth_AssertionCredentials($client_email, $scopes, $private_key);
$credentials->sub = $user_email;
$this->client = new Google_Client();
$this->client->setAssertionCredentials($credentials);
if ($this->client->getAuth()->isAccessTokenExpired()) {
$this->client->getAuth()->refreshTokenWithAssertion();
}
$this->service = new Google_Service_Drive($this->client);
return true;
}
$this->client = $this->service = null;
return false;
}
/**
* Search/List files
*
* @param null $query Leave empty to just list files
* @param string $sort (alpha, recent)
* @param bool $exclude_hidden_trash True to exclude hidden and/or trashed files
* @see https://developers.google.com/drive/web/search-parameters
* @return object
*/
function search($query = null, $sort = 'alpha', $exclude_hidden_trash = true) {
$params = array();
if ($query) {
$params[] = $query;
// "title = 'My document'"
}
$q = implode(' and ', $params);
do {
$pageToken = null;
$result = array();
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
if ($q) {
$parameters['q'] = $q;
}
$files = $this->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);
$tree = $parents = array();
foreach ($result as $file) {
if ($exclude_hidden_trash && ($file->labels->trashed || $file->labels->hidden)) {
continue;
}
$type = $file->mimeType == self::MIME_FOLDER ? 'folder' : 'file';
if ($type == 'folder') {
$download = '';
} else if (!$download = $file->getWebContentLink()) {
$export = array_shift($file->exportLinks);
$download = $export;
}
$row = array(
'id' => $file->id,
'type' => $type,
'mime' => $file->mimeType,
'title' => $file->title,
'description' => $file->description,
'root' => null,
'icon' => $file->iconLink,
'link' => $file->alternateLink,
'download' => $download,
'date_created' => $file->createdDate,
'date_modified' => $file->modifiedDate
);
if ($file->getParents()) {
foreach ($file->getParents() as $p) {
if ($p->kind == 'drive#parentReference') {
$row['parent'] = $p->id;
if ($p->isRoot) {
$row['root'] = 1;
}
if (!isset($parents[$p->id])) {
$parents[$p->id] = array();
}
$parents[$p->id][] = (object) $row;
}
}
}
$tree[] = (object) $row;
}
switch ($sort) {
case 'alpha':
usort($tree, function($a, $b) {
return strcmp($a->title, $b->title);
});
break;
case 'recent':
usort($tree, function($a, $b) {
return strtotime($a->date_modified) < strtotime($b->date_modified);
});
break;
default:
}
return (object) array('files' => $tree, 'parents' => $parents);
}
/**
* Create a file or directory
*
* @param string $mime
* @param string $parent_id
* @param string $title
* @param string $desc
* @param string $contents
* @param string $filename
* @return mixed
*/
function create($mime = self::MIME_PLAIN, $parent_id = null, $title, $desc, $contents = null, $filename = null) {
$file = new Google_Service_Drive_DriveFile();
$file->setTitle($title);
$file->setDescription($desc);
$file->setMimeType($mime);
if ($parent_id) {
$parent = new Google_Service_Drive_ParentReference();
$parent->setId($parent_id);
$file->setParents(array($parent));
}
$params = array('mimeType' => $mime, 'uploadType' => 'media');
try {
if ($contents) {
$params['data'] = $contents;
} else if ($filename && file_exists($filename)) {
$params['data'] = file_get_contents($filename);
}
$newfile = $this->service->files->insert($file, $params);
return $newfile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
return null;
}
}
/**
* Delete a file or directory
* @param $id
*/
function delete($id) {
//$service->files->trash($item['id']);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment