Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- declare(strict_types = 1);
- // Set the script version
- $version = '1.3.0';
- error_reporting(E_STRICT);
- require_once __DIR__ . '/vendor/autoload.php';
- # To install Microsoft Graph SDK, execute the following commands:
- # curl -sS https://getcomposer.org/installer | php
- # php composer.phar require microsoft/microsoft-graph:1.60.0
- use Microsoft\Graph\Graph;
- use Microsoft\Graph\Model;
- function warning_handler($errno, $errstr) {
- throw new Exception('WARNING: ' . $errstr, $errno);
- }
- set_error_handler("warning_handler", E_WARNING);
- /**
- * Gets a password from input without echoing it
- * This function only works on *nix
- * @param string $prompt Prompt to display
- * @param bool $showAsterisks Whether to show asterisks after entering response
- * @param bool $trimResponse Whether to trim the response
- * @return string Returned response
- */
- function prompt_silent($prompt, $showAsterisks = false, $trimResponse = true) {
- fwrite(STDOUT, $prompt);
- system('stty -echo 2>/dev/null');
- $response = trim(fgets(STDIN));
- system('stty echo 2>/dev/null');
- if ($showAsterisks == true) {
- fwrite(STDOUT, '*****');
- }
- fwrite(STDOUT, PHP_EOL);
- if ($trimResponse == true) {
- $response = trim($response);
- }
- return $response;
- }
- /**
- * Show the help text
- * Usage example:
- * tenant = mytenant.onmicrosoft.com
- * client_id = my-client-id
- * remote_server = tenant.sharepoint.com/sites/MySite (tenant.sharepoint.com is the server, /sites/MySite is the path to the site)
- * remote_folder = Documents/MyFolder (Documents is the drive name, MyFolder is the folder name)
- * @param string $script filename of the script
- */
- function showHelp($script) {
- fwrite(STDOUT, 'Usage:' . PHP_EOL);
- fwrite(STDOUT, $script . ' <tenant> <client_id> <command>' . PHP_EOL . PHP_EOL);
- fwrite(STDOUT, 'Available commands:' . PHP_EOL);
- fwrite(STDOUT, ' get_profile <user_id>' . PHP_EOL);
- fwrite(STDOUT, ' list_drives <remote_server>' . PHP_EOL);
- fwrite(STDOUT, ' list_drive_items <remote_server> <remote_folder>' . PHP_EOL);
- fwrite(STDOUT, ' upload_file <remote_server> <remote_folder> <local_file_path> <remote_file_name>' . PHP_EOL);
- fwrite(STDOUT, ' create_folder <remote_server> <remote_folder> <new_folder_name>' . PHP_EOL);
- fwrite(STDOUT, ' delete_drive_item <remote_server> <remote_folder> <remote_file_name>' . PHP_EOL);
- fwrite(STDOUT, ' prune_folder <remote_server> <remote_folder> <regex_match> <days_to_keep>' . PHP_EOL);
- }
- /**
- * Parse the remote server into an array
- * @param string $server server/site string
- * @return array Remote path array
- */
- function parseRemoteServer($server) {
- if (substr_count($server, '/') < 1) {
- throw new Exception('Remote Server parameter must include one forward slash!' . PHP_EOL);
- }
- $remoteServer = substr($server, 0, strpos($server, '/'));
- $siteName = substr($server, strpos($server, '/'));
- $remotePath = array(
- "server" => $remoteServer,
- "site" => $siteName
- );
- return $remotePath;
- }
- /**
- * Parse the remote path into an array
- * @param string $path drive/path string
- * @return array Remote path array
- */
- function parseRemotePath($path) {
- // Remove first slash if it exists in the path
- $path = ltrim($path, '/');
- // Remove trailing slashes from the path
- $path = rtrim($path, '/');
- // A drive name is required for any path operations
- if ($path == null || $path == '') {
- throw new Exception('Remote Path drive name part not specified!' . PHP_EOL);
- }
- // If there is no folder specified, add a trailing slash to indicate the root folder
- if (substr_count($path, '/') < 1) {
- $path = $path . '/';
- }
- $driveName = substr($path, 0, strpos($path, '/'));
- $remoteFolder = substr($path, strpos($path, '/'));
- $remotePath = array(
- "drive" => $driveName,
- "folder" => $remoteFolder
- );
- return $remotePath;
- }
- /**
- * Connect to Microsoft Graph and get an access token
- * @param string $tenant Microsoft 365 Tenant
- * @param string $clientId Client ID to connect with
- * @param string $clientSecret Client Secret to connect with
- * @return Graph Graph object for the session
- */
- function connectToGraph($tenant, $clientId, $clientSecret) {
- $guzzle = new \GuzzleHttp\Client();
- $url = 'https://login.microsoftonline.com/' . $tenant . '/oauth2/v2.0/token';
- $token = json_decode($guzzle->post($url, [
- 'form_params' => [
- 'client_id' => $clientId,
- 'client_secret' => $clientSecret,
- 'scope' => 'https://graph.microsoft.com/.default',
- 'grant_type' => 'client_credentials',
- ]
- ], [
- "connect_timeout" => 30,
- "timeout" => 30
- ])->getBody()->getContents());
- $graph = new Graph();
- $graph->setAccessToken($token->access_token);
- // fwrite(STDERR, 'Token: ' . PHP_EOL . $token->access_token . PHP_EOL);
- return $graph;
- }
- /**
- * Gets a Microsoft profile
- * @param Graph $graph Graph object to use
- * @param string $userId User to retrieve
- * @return Model\Person Profile object
- */
- function getProfile($graph, $userId) {
- /** @var Model\Person $profile */
- $profile = $graph->createRequest('GET', '/users/' . $userId)
- ->setReturnType(Model\Person::class)
- ->execute();
- return $profile;
- }
- /**
- * Gets a SharePoint site
- * @param Graph $graph Graph object to use
- * @param string $siteDomain Domain of the site
- * @param string $siteName Path to the site
- * @return Model\Site Site object
- */
- function getSite($graph, $remoteServer, $siteName) {
- /** @var Model\Site $site */
- $site = $graph->createRequest('GET', '/sites/' . $remoteServer . ':' . $siteName)
- ->setReturnType(Model\Site::class)
- ->execute();
- return $site;
- }
- /**
- * Gets the default drive for a site
- * @param Graph $graph Graph object to use
- * @param Model\Site $site Site object
- * @return Model\Drive Drive object
- */
- function getDefaultDrive($graph, $site) {
- /** @var Model\Drive $drive */
- $drive = $graph->createRequest('GET', '/sites/' . $site->getId() . '/drive')
- ->setReturnType(Model\Drive::class)
- ->execute();
- return $drive;
- }
- /**
- * Gets the drives on a site
- * @param Graph $graph Graph object to use
- * @param Model\Site $site Site object
- * @return Model\Drive[] Drive object
- */
- function getDrives($graph, $site) {
- /** @var Model\Drives[] $drives */
- $drives = $graph->createRequest('GET', '/sites/' . $site->getId() . '/drives')
- ->setReturnType(Model\Drive::class)
- ->execute();
- return $drives;
- }
- /**
- * Gets a drive on a site
- * @param Graph $graph Graph object to use
- * @param Model\Site $site Site object
- * @param string $driveName Name of the drive
- * @return Model\Drive Drive object
- */
- function getDrive($graph, $site, $driveName) {
- /** @var Model\Drives[] $drives */
- $drives = $graph->createRequest('GET', '/sites/' . $site->getId() . '/drives')
- ->setReturnType(Model\Drive::class)
- ->execute();
- /** @var Model\Drive $drive */
- foreach ($drives as $drive) {
- if (strtoupper($drive->getName()) == strtoupper($driveName)) {
- return $drive;
- }
- }
- throw new Exception('Drive not found: ' . $driveName);
- }
- /**
- * Gets a collection of SharePoint DriveItems (files)
- * @param Graph $graph Graph object to use
- * @param Model\Drive $drive Drive that the files are located on
- * @param string $remoteFolder Path to retrieve
- * @return Model\DriveItem[] DriveItem objects representing the files on the server
- */
- function getDriveItems($graph, $drive, $remoteFolder, $pageSize = 100) {
- $remoteFolder = rtrim($remoteFolder, '/');
- $graphPath = null;
- if ($remoteFolder == null || $remoteFolder == '') {
- $graphPath = '/drives/' . $drive->getId() . '/root/children';
- } else {
- $graphPath = '/drives/' . $drive->getId() . '/root:' . $remoteFolder . ':/children';
- }
- $driveItemsPageIterator = $graph->createCollectionRequest('GET', $graphPath)
- ->setPageSize($pageSize)
- ->setReturnType(Model\DriveItem::class);
- /** @var Model\DriveItem[] $items */
- $items = [];
- /** @var Model\DriveItem[] $itemPage */
- $itemPage = $driveItemsPageIterator->getPage();
- /** @var Model\DriveItem $item */
- foreach ($itemPage as $item) {
- array_push($items, $item);
- }
- while (!$driveItemsPageIterator->isEnd())
- {
- /** @var Model\DriveItem[] $itemPage */
- $itemPage = $driveItemsPageIterator->getPage();
- /** @var Model\DriveItem $item */
- foreach ($itemPage as $item) {
- array_push($items, $item);
- }
- }
- return $items;
- }
- /**
- * Downloads a SharePoint file
- * @param Graph $graph Graph object to use
- * @param Model\Drive $drive Drive that the files are located on
- * @param string $remoteFolder Path to the file
- * @param string $remoteFileName File to retrieve
- * @return GuzzleHttp\Psr7\Stream Stream for the returned file
- */
- function downloadFile($graph, $drive, $remoteFolder, $remoteFileName) {
- $remoteFolder = rtrim($remoteFolder, '/');
- $graphPath = null;
- if ($remoteFileName == null || $remoteFileName == '') {
- throw new Exception("Remote filename must be specified!");
- } else if ($remoteFolder == null || $remoteFolder == '') {
- $graphPath = '/drives/' . $drive->getId() . '/root:' . $remoteFileName . ':/content';
- } else {
- $graphPath = '/drives/' . $drive->getId() . '/root:' . $remoteFolder . '/' . $remoteFileName . ':/content';
- }
- /** @var Model\DriveItem $item */
- $fileContent = $graph->createRequest('GET', $graphPath)
- ->setReturnType(GuzzleHttp\Psr7\Stream::class)
- ->execute();
- return $fileContent;
- }
- /**
- * Gets a SharePoint DriveItem (file)
- * @param Graph $graph Graph object to use
- * @param Model\Drive $drive Drive that the files are located on
- * @param string $remoteFolder Path to the file
- * @param string $remoteFileName File to retrieve
- * @return Model\DriveItem DriveItem objects representing the files on the server
- */
- function getDriveItem($graph, $drive, $remoteFolder, $remoteFileName) {
- $remoteFolder = rtrim($remoteFolder, '/');
- $graphPath = null;
- if ($remoteFolder == null || $remoteFolder == '') {
- $graphPath = '/drives/' . $drive->getId() . '/root';
- } else if ($remoteFileName == null || $remoteFileName == '') {
- $graphPath = '/drives/' . $drive->getId() . '/root:' . $remoteFolder;
- } else {
- $graphPath = '/drives/' . $drive->getId() . '/root:' . $remoteFolder . '/' . $remoteFileName;
- }
- /** @var Model\DriveItem $item */
- $item = $graph->createRequest('GET', $graphPath)
- ->setReturnType(Model\DriveItem::class)
- ->execute();
- return $item;
- }
- /**
- * Deletes a SharePoint DriveItem (file)
- * @param Graph $graph Graph object to use
- * @param Model\Drive $drive Drive that the files are located on
- * @param string $remoteFolder Path to the file
- * @param string $remoteFileName File to delete
- */
- function deleteDriveItem($graph, $drive, $remoteFolder, $remoteFileName) {
- $remoteFolder = rtrim($remoteFolder, '/');
- $graphPath = null;
- if ($remoteFileName == null || $remoteFileName == '') {
- $graphPath = '/drives/' . $drive->getId() . '/root:' . $remoteFolder;
- } else {
- $graphPath = '/drives/' . $drive->getId() . '/root:' . $remoteFolder . '/' . $remoteFileName;
- }
- $graph->createRequest('DELETE', $graphPath)
- ->execute();
- }
- /**
- * Creates a new folder in a SharePoint location
- * @param Graph $graph Graph object to use
- * @param Model\Drive $drive Drive that the files are located on
- * @param string $remoteFolder Path on the site that the file will be uploaded to
- * @param string $newFolderName Name of the new folder on the server
- */
- function createFolder($graph, $drive, $remoteFolder, $newFolderName) {
- $remoteFolder = rtrim($remoteFolder, '/');
- $graphPath = null;
- if ($remoteFolder == null || $remoteFolder == '') {
- $graphPath = '/drives/' . $drive->getId() . '/root/children';
- } else {
- $graphPath = '/drives/' . $drive->getId() . '/root:' . $remoteFolder . ':/children';
- }
- /** @var Model\UploadSession $uploadSession */
- $uploadSession = $graph->createRequest('POST', $graphPath)
- ->addHeaders(["Content-Type" => "application/json"])
- ->attachBody([
- "@microsoft.graph.conflictBehavior" => "replace",
- // "folder" => new stdClass(),
- "folder" => ["childCount" => '0'],
- "name" => $newFolderName
- ])
- ->setReturnType(Model\UploadSession::class)
- ->execute();
- }
- /**
- * Uploads a file to a SharePoint location
- * @param Graph $graph Graph object to use
- * @param Model\Drive $drive Drive that the files are located on
- * @param string $localFilePath Path to the local file
- * @param string $remoteFolder Path on the site that the file will be uploaded to
- * @param string $remoteFileName Name of the uploaded file on the server
- */
- function uploadDriveItem($graph, $drive, $localFilePath, $remoteFolder, $remoteFileName) {
- $remoteFolder = rtrim($remoteFolder, '/');
- $graphPath = '/drives/' . $drive->getId() . '/root:' . $remoteFolder . '/' . $remoteFileName . ':/createUploadSession';
- /** @var Model\UploadSession $uploadSession */
- $uploadSession = $graph->createRequest('POST', $graphPath)
- ->addHeaders(["Content-Type" => "application/json"])
- ->attachBody([
- "item" => [
- "@microsoft.graph.conflictBehavior" => "replace",
- "name" => $remoteFileName
- ]
- ])
- ->setReturnType(Model\UploadSession::class)
- ->execute();
- $fileLocation = $localFilePath;
- $fragSize = 1024*1024*4;
- $graph_url = $uploadSession->getUploadUrl();
- $fileSize = filesize($fileLocation);
- $numFragments = ceil($fileSize / $fragSize);
- $bytesRemaining = $fileSize;
- $i = 0;
- while ($i < $numFragments) {
- $chunkSize = $numBytes = $fragSize;
- $start = $i * $fragSize;
- $end = $i * $fragSize + $chunkSize - 1;
- $offset = $i * $fragSize;
- if ($bytesRemaining < $chunkSize) {
- $chunkSize = $numBytes = $bytesRemaining;
- $end = $fileSize - 1;
- }
- if ($stream = fopen($fileLocation, 'r')) {
- // get contents using offset
- $data = stream_get_contents($stream, $chunkSize, $offset);
- fclose($stream);
- }
- $content_range = "bytes " . $start . "-" . $end . "/" . $fileSize;
- $headers = array(
- "Content-Length"=> $numBytes,
- "Content-Range"=> $content_range
- );
- $uploadByte = $graph->createRequest("PUT", $graph_url)
- ->addHeaders($headers)
- ->attachBody($data)
- ->setReturnType(Model\UploadSession::class)
- ->setTimeout("1000")
- ->execute();
- $bytesRemaining = $bytesRemaining - $chunkSize;
- $i++;
- }
- }
- fwrite(STDOUT, 'MS Graph Functions v' . $version . PHP_EOL);
- // Copy the argv array into a new one that we will mess with
- $args = $argv;
- // Get the name of this script
- $script = array_shift($args);
- // Check if enough arguments have been passed
- if (count($args) < 3) {
- fwrite(STDOUT, 'Not enough arguments passed!' . PHP_EOL);
- showHelp($script);
- exit(1);
- }
- $clientSecret = prompt_silent("Enter client secret: ", true);
- if ($clientSecret == '') {
- fwrite(STDOUT, 'Client secret cannot be empty!' . PHP_EOL);
- showHelp($script);
- exit(1);
- }
- // Collect the command line arguments into variables
- $tenant = array_shift($args);
- $clientId = array_shift($args);
- $command = array_shift($args);
- fwrite(STDERR, 'Tenant: ' . $tenant . PHP_EOL);
- fwrite(STDERR, 'Client ID: ' . $clientId . PHP_EOL);
- fwrite(STDERR, 'Command: ' . $command . PHP_EOL);
- fwrite(STDERR, 'Getting Graph token...' . PHP_EOL);
- // Connect to Graph and get a token
- /** @var Graph $graph */
- $graph = null;
- try {
- $graph = connectToGraph($tenant, $clientId, $clientSecret);
- } catch (\GuzzleHttp\Exception\RequestException $e) {
- fwrite(STDERR, 'ERROR: Failed to connect to server! ' . $e->getResponse()->getBody() . PHP_EOL);
- exit(1);
- } catch (Throwable $e) {
- fwrite(STDERR, 'ERROR: Failed to connect to server! ' . $e->getMessage() . PHP_EOL);
- exit(1);
- }
- fwrite(STDOUT, 'Connected to Server!' . PHP_EOL);
- // Parse the command
- switch(strtolower($command)) {
- // Gets the user's profile
- case "get_profile":
- if (count($args) < 1) {
- fwrite(STDERR, 'ERROR: Not enough arguments given!' . PHP_EOL);
- showHelp($script);
- exit(1);
- }
- try {
- $userId = array_shift($args);
- $profile = getProfile($graph, $userId);
- var_dump($profile);
- } catch (\GuzzleHttp\Exception\RequestException $e) {
- fwrite(STDERR, 'ERROR: Failed to get profile! ' . $e->getResponse()->getBody() . PHP_EOL);
- exit(1);
- } catch (Throwable $e) {
- fwrite(STDERR, 'ERROR: Failed to get profile! ' . $e->getMessage() . PHP_EOL);
- exit(1);
- }
- break;
- // List the drives on a site
- case "list_drives":
- if (count($args) < 1) {
- fwrite(STDERR, 'ERROR: Not enough arguments given!' . PHP_EOL);
- showHelp($script);
- exit(1);
- }
- try {
- $server = array_shift($args);
- $path = null;
- $remoteServer = parseRemoteServer($server);
- fwrite(STDERR, 'Remote Server: ' . $remoteServer["server"] . PHP_EOL);
- fwrite(STDERR, 'Site Name: ' . $remoteServer["site"] . PHP_EOL);
- fwrite(STDERR, 'Getting Site...' . PHP_EOL);
- $site = getSite($graph, $remoteServer["server"], $remoteServer["site"]);
- fwrite(STDERR, 'Site URL: ' . $site->getWebUrl() . PHP_EOL);
- fwrite(STDERR, 'Getting drives...' . PHP_EOL);
- $drives = getDrives($graph, $site);
- fwrite(STDOUT, 'CSV:Name,Type,URL' . PHP_EOL);
- /** @var Model\Drive $drive */
- foreach ($drives as $drive) {
- fwrite(STDOUT, 'CSV:"' . $drive->getName() . '","' . $drive->getDriveType() . '","' . $drive->getWebUrl() . '"' . PHP_EOL);
- }
- } catch (\GuzzleHttp\Exception\RequestException $e) {
- fwrite(STDERR, 'ERROR: Failed to list drives! ' . $e->getResponse()->getBody() . PHP_EOL);
- exit(1);
- } catch (Throwable $e) {
- fwrite(STDERR, 'ERROR: Failed to list drives! ' . $e->getMessage() . PHP_EOL);
- exit(1);
- }
- break;
- // List the files in a folder
- case "list_drive_items":
- if (count($args) < 2) {
- fwrite(STDERR, 'ERROR: Not enough arguments given!' . PHP_EOL);
- showHelp($script);
- exit(1);
- }
- try {
- $server = array_shift($args);
- $path = array_shift($args);
- $remoteServer = parseRemoteServer($server);
- $remotePath = parseRemotePath($path);
- fwrite(STDERR, 'Remote Server: ' . $remoteServer["server"] . PHP_EOL);
- fwrite(STDERR, 'Site Name: ' . $remoteServer["site"] . PHP_EOL);
- fwrite(STDERR, 'Drive Name: ' . $remotePath["drive"] . PHP_EOL);
- fwrite(STDERR, 'Remote Folder: ' . $remotePath["folder"] . PHP_EOL);
- fwrite(STDERR, 'Getting Site...' . PHP_EOL);
- $site = getSite($graph, $remoteServer["server"], $remoteServer["site"]);
- fwrite(STDERR, 'Site URL: ' . $site->getWebUrl() . PHP_EOL);
- fwrite(STDERR, 'Getting drive...' . PHP_EOL);
- $drive = getDrive($graph, $site, $remotePath["drive"]);
- fwrite(STDERR, 'Getting folder...' . PHP_EOL);
- $folder = getDriveItem($graph, $drive, $remotePath["folder"], null);
- fwrite(STDERR, 'Folder URL: ' . $folder->getWebUrl() . PHP_EOL);
- fwrite(STDERR, 'Getting drive items...' . PHP_EOL);
- $items = getDriveItems($graph, $drive, $remotePath["folder"]);
- fwrite(STDOUT, 'CSV:Name,URL,File Size,Date Created,Date Modified' . PHP_EOL);
- /** @var Model\DriveItem $item */
- foreach ($items as $item) {
- $itemType = null;
- if ($item->getFolder() != null) {
- $itemType = "Folder";
- } else {
- $itemType = "File";
- }
- fwrite(STDOUT, 'CSV:"' . $itemType . '","' . $item->getName() . '","' . $item->getWebUrl() . '",' . $item->getSize() . ',' . $item->getCreatedDateTime()->format('Y-m-d\TH:i:sp') . ',' . $item->getLastModifiedDateTime()->format('Y-m-d\TH:i:sp') . PHP_EOL);
- }
- } catch (\GuzzleHttp\Exception\RequestException $e) {
- fwrite(STDERR, 'ERROR: Failed to list drive items! ' . $e->getResponse()->getBody() . PHP_EOL);
- exit(1);
- } catch (Throwable $e) {
- fwrite(STDERR, 'ERROR: Failed to list drive items! ' . $e->getMessage() . PHP_EOL);
- exit(1);
- }
- break;
- // Upload a file
- case "upload_file":
- if (count($args) < 4) {
- fwrite(STDERR, 'ERROR: Not enough arguments given!' . PHP_EOL);
- showHelp($script);
- exit(1);
- }
- try {
- $server = array_shift($args);
- $path = array_shift($args);
- $remoteServer = parseRemoteServer($server);
- $remotePath = parseRemotePath($path);
- fwrite(STDERR, 'Remote Server: ' . $remoteServer["server"] . PHP_EOL);
- fwrite(STDERR, 'Site Name: ' . $remoteServer["site"] . PHP_EOL);
- fwrite(STDERR, 'Drive Name: ' . $remotePath["drive"] . PHP_EOL);
- fwrite(STDERR, 'Remote Folder: ' . $remotePath["folder"] . PHP_EOL);
- $localFilePath = array_shift($args);
- $remoteFileName = array_shift($args);
- fwrite(STDERR, 'Local File Path: ' . $localFilePath . PHP_EOL);
- fwrite(STDERR, 'Remote File Name: ' . $remoteFileName . PHP_EOL);
- if (!file_exists($localFilePath)) {
- throw new Exception('Local file does not exist!');
- }
- fwrite(STDERR, 'Getting Site...' . PHP_EOL);
- $site = getSite($graph, $remoteServer["server"], $remoteServer["site"]);
- fwrite(STDERR, 'Site URL: ' . $site->getWebUrl() . PHP_EOL);
- fwrite(STDERR, 'Getting drive...' . PHP_EOL);
- $drive = getDrive($graph, $site, $remotePath["drive"]);
- fwrite(STDERR, 'Getting destination folder...' . PHP_EOL);
- $folder = getDriveItem($graph, $drive, $remotePath["folder"], null);
- fwrite(STDERR, 'Folder URL: ' . $folder->getWebUrl() . PHP_EOL);
- fwrite(STDERR, 'Uploading file (' . number_format(filesize($localFilePath), 0) . ' bytes)...' . PHP_EOL);
- uploadDriveItem($graph, $drive, $localFilePath, $remotePath["folder"], $remoteFileName);
- fwrite(STDERR, 'Upload complete!' . PHP_EOL);
- } catch (\GuzzleHttp\Exception\RequestException $e) {
- fwrite(STDERR, 'ERROR: Failed to upload file! ' . $e->getResponse()->getBody() . PHP_EOL);
- exit(1);
- } catch (Throwable $e) {
- fwrite(STDERR, 'ERROR: Failed to upload file! ' . $e->getMessage() . PHP_EOL);
- exit(1);
- }
- break;
- // Create a new folder
- case "create_folder":
- if (count($args) < 3) {
- fwrite(STDERR, 'ERROR: Not enough arguments given!' . PHP_EOL);
- showHelp($script);
- exit(1);
- }
- try {
- $server = array_shift($args);
- $path = array_shift($args);
- $remoteServer = parseRemoteServer($server);
- $remotePath = parseRemotePath($path);
- fwrite(STDERR, 'Remote Server: ' . $remoteServer["server"] . PHP_EOL);
- fwrite(STDERR, 'Site Name: ' . $remoteServer["site"] . PHP_EOL);
- fwrite(STDERR, 'Drive Name: ' . $remotePath["drive"] . PHP_EOL);
- fwrite(STDERR, 'Remote Folder: ' . $remotePath["folder"] . PHP_EOL);
- $newFolderName = array_shift($args);
- fwrite(STDERR, 'New Folder Name: ' . $newFolderName . PHP_EOL);
- if ($newFolderName == null || $newFolderName == "") {
- fwrite(STDERR, 'ERROR: Remote filename not specified!' . PHP_EOL);
- exit(1);
- }
- fwrite(STDERR, 'Getting Site...' . PHP_EOL);
- $site = getSite($graph, $remoteServer["server"], $remoteServer["site"]);
- fwrite(STDERR, 'Site URL: ' . $site->getWebUrl() . PHP_EOL);
- fwrite(STDERR, 'Getting drive...' . PHP_EOL);
- $drive = getDrive($graph, $site, $remotePath["drive"]);
- fwrite(STDERR, 'Creating folder...' . PHP_EOL);
- createFolder($graph, $drive, $remotePath["folder"], $newFolderName);
- fwrite(STDERR, 'Folder created' . PHP_EOL);
- } catch (\GuzzleHttp\Exception\RequestException $e) {
- fwrite(STDERR, 'ERROR: Failed to create folder! ' . $e->getResponse()->getBody() . PHP_EOL);
- exit(1);
- } catch (Throwable $e) {
- fwrite(STDERR, 'ERROR: Failed to create folder! ' . $e->getMessage() . PHP_EOL);
- exit(1);
- }
- break;
- // Download a file
- case "download_file":
- if (count($args) < 4) {
- fwrite(STDERR, 'ERROR: Not enough arguments given!' . PHP_EOL);
- showHelp($script);
- exit(1);
- }
- try {
- $server = array_shift($args);
- $path = array_shift($args);
- $remoteServer = parseRemoteServer($server);
- $remotePath = parseRemotePath($path);
- fwrite(STDERR, 'Remote Server: ' . $remoteServer["server"] . PHP_EOL);
- fwrite(STDERR, 'Site Name: ' . $remoteServer["site"] . PHP_EOL);
- fwrite(STDERR, 'Drive Name: ' . $remotePath["drive"] . PHP_EOL);
- fwrite(STDERR, 'Remote Folder: ' . $remotePath["folder"] . PHP_EOL);
- $remoteFileName = array_shift($args);
- $localFile = array_shift($args);
- fwrite(STDERR, 'Remote File Name: ' . $remoteFileName . PHP_EOL);
- fwrite(STDERR, 'Local File: ' . $localFile . PHP_EOL);
- if ($remoteFileName == null || $remoteFileName == "") {
- fwrite(STDERR, 'ERROR: Remote filename not specified!' . PHP_EOL);
- exit(1);
- }
- if ($localFile == null || $localFile == "") {
- fwrite(STDERR, 'ERROR: Local file not specified!' . PHP_EOL);
- exit(1);
- }
- fwrite(STDERR, 'Getting Site...' . PHP_EOL);
- $site = getSite($graph, $remoteServer["server"], $remoteServer["site"]);
- fwrite(STDERR, 'Site URL: ' . $site->getWebUrl() . PHP_EOL);
- fwrite(STDERR, 'Getting drive...' . PHP_EOL);
- $drive = getDrive($graph, $site, $remotePath["drive"]);
- fwrite(STDERR, 'Downloading file...' . PHP_EOL);
- $fileStream = downloadFile($graph, $drive, $remotePath["folder"], $remoteFileName);
- file_put_contents($localFile, $fileStream);
- fwrite(STDERR, 'File downloaded' . PHP_EOL);
- } catch (\GuzzleHttp\Exception\RequestException $e) {
- fwrite(STDERR, 'ERROR: Failed to download file! ' . $e->getResponse()->getBody() . PHP_EOL);
- exit(1);
- } catch (Throwable $e) {
- fwrite(STDERR, 'ERROR: Failed to download file! ' . $e->getMessage() . PHP_EOL);
- exit(1);
- }
- break;
- // Delete a drive item
- case "delete_drive_item":
- if (count($args) < 3) {
- fwrite(STDERR, 'ERROR: Not enough arguments given!' . PHP_EOL);
- showHelp($script);
- exit(1);
- }
- try {
- $server = array_shift($args);
- $path = array_shift($args);
- $remoteServer = parseRemoteServer($server);
- $remotePath = parseRemotePath($path);
- fwrite(STDERR, 'Remote Server: ' . $remoteServer["server"] . PHP_EOL);
- fwrite(STDERR, 'Site Name: ' . $remoteServer["site"] . PHP_EOL);
- fwrite(STDERR, 'Drive Name: ' . $remotePath["drive"] . PHP_EOL);
- fwrite(STDERR, 'Remote Folder: ' . $remotePath["folder"] . PHP_EOL);
- $remoteFileName = array_shift($args);
- fwrite(STDERR, 'Remote File Name: ' . $remoteFileName . PHP_EOL);
- if ($remoteFileName == null || $remoteFileName == "") {
- fwrite(STDERR, 'ERROR: Remote filename not specified!' . PHP_EOL);
- exit(1);
- }
- fwrite(STDERR, 'Getting Site...' . PHP_EOL);
- $site = getSite($graph, $remoteServer["server"], $remoteServer["site"]);
- fwrite(STDERR, 'Site URL: ' . $site->getWebUrl() . PHP_EOL);
- fwrite(STDERR, 'Getting drive...' . PHP_EOL);
- $drive = getDrive($graph, $site, $remotePath["drive"]);
- fwrite(STDERR, 'Deleting file...' . PHP_EOL);
- deleteDriveItem($graph, $drive, $remotePath["folder"], $remoteFileName);
- fwrite(STDERR, 'File deleted' . PHP_EOL);
- } catch (\GuzzleHttp\Exception\RequestException $e) {
- fwrite(STDERR, 'ERROR: Failed to delete file! ' . $e->getResponse()->getBody() . PHP_EOL);
- exit(1);
- } catch (Throwable $e) {
- fwrite(STDERR, 'ERROR: Failed to delete file! ' . $e->getMessage() . PHP_EOL);
- exit(1);
- }
- break;
- // Prune files in a folder older than a given number of days
- case "prune_folder":
- if (count($args) < 4) {
- fwrite(STDERR, 'ERROR: Not enough arguments given!' . PHP_EOL);
- showHelp($script);
- exit(1);
- }
- try {
- $server = array_shift($args);
- $path = array_shift($args);
- $remoteServer = parseRemoteServer($server);
- $remotePath = parseRemotePath($path);
- fwrite(STDERR, 'Remote Server: ' . $remoteServer["server"] . PHP_EOL);
- fwrite(STDERR, 'Site Name: ' . $remoteServer["site"] . PHP_EOL);
- fwrite(STDERR, 'Drive Name: ' . $remotePath["drive"] . PHP_EOL);
- fwrite(STDERR, 'Remote Folder: ' . $remotePath["folder"] . PHP_EOL);
- $regexMatch = array_shift($args);
- $daysToKeep = array_shift($args);
- fwrite(STDERR, 'Regex Match: ' . $regexMatch . PHP_EOL);
- fwrite(STDERR, 'Days to keep: ' . $daysToKeep . PHP_EOL);
- if ($regexMatch == null || $regexMatch == '') {
- fwrite(STDERR, "ERROR: No regular expression found!" . PHP_EOL);
- exit(1);
- }
- if (!is_numeric($daysToKeep)) {
- fwrite(STDERR, "ERROR: Days to keep is not numeric!" . PHP_EOL);
- exit(1);
- }
- fwrite(STDERR, 'Getting Site...' . PHP_EOL);
- $site = getSite($graph, $remoteServer["server"], $remoteServer["site"]);
- fwrite(STDERR, 'Site URL: ' . $site->getWebUrl() . PHP_EOL);
- fwrite(STDERR, 'Getting drive...' . PHP_EOL);
- $drive = getDrive($graph, $site, $remotePath["drive"]);
- fwrite(STDERR, 'Getting drive items...' . PHP_EOL);
- $items = getDriveItems($graph, $drive, $remotePath["folder"]);
- fwrite(STDERR, 'Pruning drive items...' . PHP_EOL);
- $deletedFileCount = 0;
- /** @var Model\DriveItem $item */
- foreach ($items as $item) {
- // Check if the item is a folder and go to the next item if it is
- if ($item->getFolder() != null) {
- continue;
- }
- $interval = $item->getLastModifiedDateTime()->diff(new DateTime());
- $daysOld = $interval->format('%a');
- if ($daysOld > $daysToKeep && preg_match($regexMatch, $item->getName())) {
- fwrite(STDOUT, 'Deleting: ' . $item->getName() . PHP_EOL);
- deleteDriveItem($graph, $drive, $remotePath["folder"], $item->getName());
- $deletedFileCount++;
- }
- }
- fwrite(STDERR, 'Drive items pruned: ' . $deletedFileCount . PHP_EOL);
- } catch (\GuzzleHttp\Exception\RequestException $e) {
- fwrite(STDERR, 'ERROR: Failed to prune drive items! ' . $e->getResponse()->getBody() . PHP_EOL);
- exit(1);
- } catch (Throwable $e) {
- fwrite(STDERR, 'ERROR: Failed to prune drive items! ' . $e->getMessage() . PHP_EOL);
- exit(1);
- }
- break;
- default:
- fwrite(STDOUT, 'ERROR: Unknown command: ' . strtolower($command) . PHP_EOL);
- showHelp($script);
- exit(1);
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement