Advertisement
EmilySamantha80

Microsoft Graph functions using Graph PHP SDK

Mar 31st, 2022 (edited)
1,159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 33.25 KB | None | 0 0
  1. <?php
  2.  
  3. declare(strict_types = 1);
  4.  
  5. // Set the script version
  6. $version = '1.3.0';
  7.  
  8. error_reporting(E_STRICT);
  9.  
  10. require_once __DIR__ . '/vendor/autoload.php';
  11.  
  12. # To install Microsoft Graph SDK, execute the following commands:
  13. # curl -sS https://getcomposer.org/installer | php
  14. # php composer.phar require microsoft/microsoft-graph:1.60.0
  15.  
  16. use Microsoft\Graph\Graph;
  17. use Microsoft\Graph\Model;
  18.  
  19. function warning_handler($errno, $errstr) {
  20.     throw new Exception('WARNING: ' . $errstr, $errno);
  21. }
  22. set_error_handler("warning_handler", E_WARNING);
  23.  
  24. /**
  25.  * Gets a password from input without echoing it
  26.  * This function only works on *nix
  27.  * @param string $prompt Prompt to display
  28.  * @param bool $showAsterisks Whether to show asterisks after entering response
  29.  * @param bool $trimResponse Whether to trim the response
  30.  * @return string Returned response
  31.  */
  32. function prompt_silent($prompt, $showAsterisks = false, $trimResponse = true) {
  33.     fwrite(STDOUT, $prompt);
  34.     system('stty -echo 2>/dev/null');
  35.     $response = trim(fgets(STDIN));
  36.     system('stty echo 2>/dev/null');
  37.     if ($showAsterisks == true) {
  38.         fwrite(STDOUT, '*****');
  39.     }
  40.     fwrite(STDOUT, PHP_EOL);
  41.  
  42.     if ($trimResponse == true) {
  43.         $response = trim($response);
  44.     }
  45.  
  46.     return $response;
  47. }
  48.  
  49. /**
  50.  * Show the help text
  51.  * Usage example:
  52.  *   tenant = mytenant.onmicrosoft.com
  53.  *   client_id = my-client-id
  54.  *   remote_server = tenant.sharepoint.com/sites/MySite (tenant.sharepoint.com is the server, /sites/MySite is the path to the site)
  55.  *   remote_folder = Documents/MyFolder (Documents is the drive name, MyFolder is the folder name)
  56.  * @param string $script filename of the script
  57.  */
  58. function showHelp($script) {
  59.     fwrite(STDOUT, 'Usage:' . PHP_EOL);
  60.     fwrite(STDOUT, $script . ' <tenant> <client_id> <command>' . PHP_EOL . PHP_EOL);
  61.     fwrite(STDOUT, 'Available commands:' . PHP_EOL);
  62.     fwrite(STDOUT, '  get_profile <user_id>' . PHP_EOL);
  63.     fwrite(STDOUT, '  list_drives <remote_server>' . PHP_EOL);
  64.     fwrite(STDOUT, '  list_drive_items <remote_server> <remote_folder>' . PHP_EOL);
  65.     fwrite(STDOUT, '  upload_file <remote_server> <remote_folder> <local_file_path> <remote_file_name>' . PHP_EOL);
  66.     fwrite(STDOUT, '  create_folder <remote_server> <remote_folder> <new_folder_name>' . PHP_EOL);
  67.     fwrite(STDOUT, '  delete_drive_item <remote_server> <remote_folder> <remote_file_name>' . PHP_EOL);
  68.     fwrite(STDOUT, '  prune_folder <remote_server> <remote_folder> <regex_match> <days_to_keep>' . PHP_EOL);
  69. }
  70.  
  71. /**
  72.  * Parse the remote server into an array
  73.  * @param string $server server/site string
  74.  * @return array Remote path array
  75.  */
  76. function parseRemoteServer($server) {
  77.     if (substr_count($server, '/') < 1) {
  78.         throw new Exception('Remote Server parameter must include one forward slash!' . PHP_EOL);
  79.     }
  80.     $remoteServer = substr($server, 0, strpos($server, '/'));
  81.     $siteName = substr($server, strpos($server, '/'));
  82.    
  83.     $remotePath = array(
  84.         "server" => $remoteServer,
  85.         "site" => $siteName
  86.     );
  87.    
  88.     return $remotePath;
  89. }
  90.  
  91. /**
  92.  * Parse the remote path into an array
  93.  * @param string $path drive/path string
  94.  * @return array Remote path array
  95.  */
  96. function parseRemotePath($path) {
  97.     // Remove first slash if it exists in the path
  98.     $path = ltrim($path, '/');
  99.     // Remove trailing slashes from the path
  100.     $path = rtrim($path, '/');
  101.     // A drive name is required for any path operations
  102.     if ($path == null || $path == '') {
  103.         throw new Exception('Remote Path drive name part not specified!' . PHP_EOL);
  104.     }
  105.     // If there is no folder specified, add a trailing slash to indicate the root folder
  106.     if (substr_count($path, '/') < 1) {
  107.         $path = $path . '/';
  108.     }
  109.     $driveName = substr($path, 0, strpos($path, '/'));
  110.     $remoteFolder = substr($path, strpos($path, '/'));
  111.    
  112.     $remotePath = array(
  113.         "drive" => $driveName,
  114.         "folder" => $remoteFolder
  115.     );
  116.    
  117.     return $remotePath;
  118. }
  119.  
  120. /**
  121.  * Connect to Microsoft Graph and get an access token
  122.  * @param string $tenant Microsoft 365 Tenant
  123.  * @param string $clientId Client ID to connect with
  124.  * @param string $clientSecret Client Secret to connect with
  125.  * @return Graph Graph object for the session
  126.  */
  127. function connectToGraph($tenant, $clientId, $clientSecret) {
  128.     $guzzle = new \GuzzleHttp\Client();
  129.     $url = 'https://login.microsoftonline.com/' . $tenant . '/oauth2/v2.0/token';
  130.     $token = json_decode($guzzle->post($url, [
  131.         'form_params' => [
  132.             'client_id' => $clientId,
  133.             'client_secret' => $clientSecret,
  134.             'scope' => 'https://graph.microsoft.com/.default',
  135.             'grant_type' => 'client_credentials',
  136.             ]
  137.         ], [
  138.             "connect_timeout" => 30,
  139.             "timeout" => 30
  140.         ])->getBody()->getContents());
  141.  
  142.     $graph = new Graph();
  143.     $graph->setAccessToken($token->access_token);
  144.     // fwrite(STDERR, 'Token: ' . PHP_EOL . $token->access_token . PHP_EOL);
  145.     return $graph;
  146. }
  147.  
  148. /**
  149.  * Gets a Microsoft profile
  150.  * @param Graph $graph Graph object to use
  151.  * @param string $userId User to retrieve
  152.  * @return Model\Person Profile object
  153.  */
  154. function getProfile($graph, $userId) {
  155.     /** @var Model\Person $profile */
  156.     $profile = $graph->createRequest('GET', '/users/' . $userId)
  157.         ->setReturnType(Model\Person::class)
  158.         ->execute();
  159.     return $profile;
  160. }
  161.  
  162. /**
  163.  * Gets a SharePoint site
  164.  * @param Graph $graph Graph object to use
  165.  * @param string $siteDomain Domain of the site
  166.  * @param string $siteName Path to the site
  167.  * @return Model\Site Site object
  168.  */
  169. function getSite($graph, $remoteServer, $siteName) {
  170.     /** @var Model\Site $site */
  171.     $site = $graph->createRequest('GET', '/sites/' . $remoteServer . ':' . $siteName)
  172.         ->setReturnType(Model\Site::class)
  173.         ->execute();
  174.     return $site;
  175. }
  176.  
  177. /**
  178.  * Gets the default drive for a site
  179.  * @param Graph $graph Graph object to use
  180.  * @param Model\Site $site Site object
  181.  * @return Model\Drive Drive object
  182.  */
  183. function getDefaultDrive($graph, $site) {
  184.     /** @var Model\Drive $drive */
  185.     $drive = $graph->createRequest('GET', '/sites/' . $site->getId() . '/drive')
  186.         ->setReturnType(Model\Drive::class)
  187.         ->execute();
  188.     return $drive;
  189. }
  190.  
  191. /**
  192.  * Gets the drives on a site
  193.  * @param Graph $graph Graph object to use
  194.  * @param Model\Site $site Site object
  195.  * @return Model\Drive[] Drive object
  196.  */
  197. function getDrives($graph, $site) {
  198.     /** @var Model\Drives[] $drives */
  199.     $drives = $graph->createRequest('GET', '/sites/' . $site->getId() . '/drives')
  200.         ->setReturnType(Model\Drive::class)
  201.         ->execute();
  202.  
  203.     return $drives;
  204. }
  205.  
  206. /**
  207.  * Gets a drive on a site
  208.  * @param Graph $graph Graph object to use
  209.  * @param Model\Site $site Site object
  210.  * @param string $driveName Name of the drive
  211.  * @return Model\Drive Drive object
  212.  */
  213. function getDrive($graph, $site, $driveName) {
  214.     /** @var Model\Drives[] $drives */
  215.     $drives = $graph->createRequest('GET', '/sites/' . $site->getId() . '/drives')
  216.         ->setReturnType(Model\Drive::class)
  217.         ->execute();
  218.  
  219.     /** @var Model\Drive $drive */
  220.     foreach ($drives as $drive) {
  221.         if (strtoupper($drive->getName()) == strtoupper($driveName)) {
  222.             return $drive;
  223.         }
  224.     }
  225.     throw new Exception('Drive not found: ' . $driveName);
  226. }
  227.  
  228. /**
  229.  * Gets a collection of SharePoint DriveItems (files)
  230.  * @param Graph $graph Graph object to use
  231.  * @param Model\Drive $drive Drive that the files are located on
  232.  * @param string $remoteFolder Path to retrieve
  233.  * @return Model\DriveItem[] DriveItem objects representing the files on the server
  234.  */
  235. function getDriveItems($graph, $drive, $remoteFolder, $pageSize = 100) {
  236.     $remoteFolder = rtrim($remoteFolder, '/');
  237.     $graphPath = null;
  238.     if ($remoteFolder == null || $remoteFolder == '') {
  239.         $graphPath = '/drives/' . $drive->getId() . '/root/children';
  240.     } else {
  241.         $graphPath = '/drives/' . $drive->getId() . '/root:' . $remoteFolder . ':/children';
  242.     }
  243.    
  244.     $driveItemsPageIterator = $graph->createCollectionRequest('GET', $graphPath)
  245.         ->setPageSize($pageSize)
  246.         ->setReturnType(Model\DriveItem::class);
  247.        
  248.     /** @var Model\DriveItem[] $items */
  249.     $items = [];
  250.    
  251.     /** @var Model\DriveItem[] $itemPage */
  252.     $itemPage = $driveItemsPageIterator->getPage();
  253.     /** @var Model\DriveItem $item */
  254.     foreach ($itemPage as $item) {
  255.         array_push($items, $item);
  256.     }
  257.  
  258.     while (!$driveItemsPageIterator->isEnd())
  259.     {
  260.         /** @var Model\DriveItem[] $itemPage */
  261.         $itemPage = $driveItemsPageIterator->getPage();
  262.         /** @var Model\DriveItem $item */
  263.         foreach ($itemPage as $item) {
  264.             array_push($items, $item);
  265.         }
  266.     }
  267.     return $items;
  268. }
  269.  
  270. /**
  271.  * Downloads a SharePoint file
  272.  * @param Graph $graph Graph object to use
  273.  * @param Model\Drive $drive Drive that the files are located on
  274.  * @param string $remoteFolder Path to the file
  275.  * @param string $remoteFileName File to retrieve
  276.  * @return GuzzleHttp\Psr7\Stream Stream for the returned file
  277.  */
  278. function downloadFile($graph, $drive, $remoteFolder, $remoteFileName) {
  279.     $remoteFolder = rtrim($remoteFolder, '/');
  280.     $graphPath = null;
  281.     if ($remoteFileName == null || $remoteFileName == '') {
  282.         throw new Exception("Remote filename must be specified!");
  283.     } else if ($remoteFolder == null || $remoteFolder == '') {
  284.         $graphPath = '/drives/' . $drive->getId() . '/root:' . $remoteFileName . ':/content';
  285.     } else {
  286.         $graphPath = '/drives/' . $drive->getId() . '/root:' . $remoteFolder . '/' . $remoteFileName . ':/content';
  287.     }
  288.     /** @var Model\DriveItem $item */
  289.     $fileContent = $graph->createRequest('GET', $graphPath)
  290.         ->setReturnType(GuzzleHttp\Psr7\Stream::class)
  291.         ->execute();
  292.    
  293.     return $fileContent;
  294. }
  295.  
  296. /**
  297.  * Gets a SharePoint DriveItem (file)
  298.  * @param Graph $graph Graph object to use
  299.  * @param Model\Drive $drive Drive that the files are located on
  300.  * @param string $remoteFolder Path to the file
  301.  * @param string $remoteFileName File to retrieve
  302.  * @return Model\DriveItem DriveItem objects representing the files on the server
  303.  */
  304. function getDriveItem($graph, $drive, $remoteFolder, $remoteFileName) {
  305.     $remoteFolder = rtrim($remoteFolder, '/');
  306.     $graphPath = null;
  307.     if ($remoteFolder == null || $remoteFolder == '') {
  308.         $graphPath = '/drives/' . $drive->getId() . '/root';
  309.     } else if ($remoteFileName == null || $remoteFileName == '') {
  310.         $graphPath = '/drives/' . $drive->getId() . '/root:' . $remoteFolder;
  311.     } else {
  312.         $graphPath = '/drives/' . $drive->getId() . '/root:' . $remoteFolder . '/' . $remoteFileName;
  313.     }
  314.     /** @var Model\DriveItem $item */
  315.     $item = $graph->createRequest('GET', $graphPath)
  316.         ->setReturnType(Model\DriveItem::class)
  317.         ->execute();
  318.     return $item;
  319. }
  320.  
  321. /**
  322.  * Deletes a SharePoint DriveItem (file)
  323.  * @param Graph $graph Graph object to use
  324.  * @param Model\Drive $drive Drive that the files are located on
  325.  * @param string $remoteFolder Path to the file
  326.  * @param string $remoteFileName File to delete
  327.  */
  328. function deleteDriveItem($graph, $drive, $remoteFolder, $remoteFileName) {
  329.     $remoteFolder = rtrim($remoteFolder, '/');
  330.     $graphPath = null;
  331.     if ($remoteFileName == null || $remoteFileName == '') {
  332.         $graphPath = '/drives/' . $drive->getId() . '/root:' . $remoteFolder;
  333.     } else {
  334.         $graphPath = '/drives/' . $drive->getId() . '/root:' . $remoteFolder . '/' . $remoteFileName;
  335.     }
  336.     $graph->createRequest('DELETE', $graphPath)
  337.         ->execute();
  338. }
  339.  
  340. /**
  341.  * Creates a new folder in a SharePoint location
  342.  * @param Graph $graph Graph object to use
  343.  * @param Model\Drive $drive Drive that the files are located on
  344.  * @param string $remoteFolder Path on the site that the file will be uploaded to
  345.  * @param string $newFolderName Name of the new folder on the server
  346.  */
  347. function createFolder($graph, $drive, $remoteFolder, $newFolderName) {
  348.     $remoteFolder = rtrim($remoteFolder, '/');
  349.     $graphPath = null;
  350.     if ($remoteFolder == null || $remoteFolder == '') {
  351.         $graphPath = '/drives/' . $drive->getId() . '/root/children';
  352.     } else {
  353.         $graphPath = '/drives/' . $drive->getId() . '/root:' . $remoteFolder . ':/children';
  354.     }
  355.  
  356.     /** @var Model\UploadSession $uploadSession */
  357.     $uploadSession = $graph->createRequest('POST', $graphPath)
  358.         ->addHeaders(["Content-Type" => "application/json"])
  359.         ->attachBody([
  360.             "@microsoft.graph.conflictBehavior" => "replace",
  361.             // "folder" => new stdClass(),
  362.             "folder" => ["childCount" => '0'],
  363.             "name" => $newFolderName
  364.         ])
  365.         ->setReturnType(Model\UploadSession::class)
  366.         ->execute();
  367. }
  368.  
  369. /**
  370.  * Uploads a file to a SharePoint location
  371.  * @param Graph $graph Graph object to use
  372.  * @param Model\Drive $drive Drive that the files are located on
  373.  * @param string $localFilePath Path to the local file
  374.  * @param string $remoteFolder Path on the site that the file will be uploaded to
  375.  * @param string $remoteFileName Name of the uploaded file on the server
  376.  */
  377. function uploadDriveItem($graph, $drive, $localFilePath, $remoteFolder, $remoteFileName) {
  378.     $remoteFolder = rtrim($remoteFolder, '/');
  379.     $graphPath = '/drives/' . $drive->getId() . '/root:' . $remoteFolder . '/' . $remoteFileName . ':/createUploadSession';
  380.     /** @var Model\UploadSession $uploadSession */
  381.     $uploadSession = $graph->createRequest('POST', $graphPath)
  382.         ->addHeaders(["Content-Type" => "application/json"])
  383.         ->attachBody([
  384.             "item" => [
  385.                 "@microsoft.graph.conflictBehavior" => "replace",
  386.                 "name" => $remoteFileName
  387.             ]
  388.         ])
  389.         ->setReturnType(Model\UploadSession::class)
  390.         ->execute();
  391.  
  392.     $fileLocation = $localFilePath;
  393.     $fragSize = 1024*1024*4;
  394.     $graph_url = $uploadSession->getUploadUrl();
  395.     $fileSize = filesize($fileLocation);
  396.     $numFragments = ceil($fileSize / $fragSize);
  397.     $bytesRemaining = $fileSize;
  398.     $i = 0;
  399.     while ($i < $numFragments) {
  400.         $chunkSize = $numBytes = $fragSize;
  401.         $start = $i * $fragSize;
  402.         $end = $i * $fragSize + $chunkSize - 1;
  403.         $offset = $i * $fragSize;
  404.         if ($bytesRemaining < $chunkSize) {
  405.             $chunkSize = $numBytes = $bytesRemaining;
  406.             $end = $fileSize - 1;
  407.         }
  408.         if ($stream = fopen($fileLocation, 'r')) {
  409.             // get contents using offset
  410.             $data = stream_get_contents($stream, $chunkSize, $offset);
  411.             fclose($stream);
  412.         }
  413.         $content_range = "bytes " . $start . "-" . $end . "/" . $fileSize;
  414.         $headers = array(
  415.             "Content-Length"=> $numBytes,
  416.             "Content-Range"=> $content_range
  417.         );
  418.         $uploadByte = $graph->createRequest("PUT", $graph_url)
  419.             ->addHeaders($headers)
  420.             ->attachBody($data)
  421.             ->setReturnType(Model\UploadSession::class)
  422.             ->setTimeout("1000")
  423.             ->execute();
  424.         $bytesRemaining = $bytesRemaining - $chunkSize;
  425.         $i++;
  426.     }
  427. }
  428.  
  429. fwrite(STDOUT, 'MS Graph Functions v' . $version . PHP_EOL);
  430.  
  431. // Copy the argv array into a new one that we will mess with
  432. $args = $argv;
  433.  
  434. // Get the name of this script
  435. $script = array_shift($args);
  436.  
  437. // Check if enough arguments have been passed
  438. if (count($args) < 3) {
  439.     fwrite(STDOUT, 'Not enough arguments passed!' . PHP_EOL);
  440.     showHelp($script);
  441.     exit(1);
  442. }
  443.  
  444. $clientSecret = prompt_silent("Enter client secret: ", true);
  445. if ($clientSecret == '') {
  446.     fwrite(STDOUT, 'Client secret cannot be empty!' . PHP_EOL);
  447.     showHelp($script);
  448.     exit(1);
  449. }
  450.  
  451. // Collect the command line arguments into variables
  452. $tenant = array_shift($args);
  453. $clientId = array_shift($args);
  454. $command = array_shift($args);
  455.  
  456. fwrite(STDERR, 'Tenant: ' . $tenant . PHP_EOL);
  457. fwrite(STDERR, 'Client ID: ' . $clientId . PHP_EOL);
  458. fwrite(STDERR, 'Command: ' . $command . PHP_EOL);
  459.  
  460. fwrite(STDERR, 'Getting Graph token...' . PHP_EOL);
  461. // Connect to Graph and get a token
  462. /** @var Graph $graph */
  463. $graph = null;
  464. try {
  465.     $graph = connectToGraph($tenant, $clientId, $clientSecret);
  466. } catch (\GuzzleHttp\Exception\RequestException $e) {
  467.     fwrite(STDERR, 'ERROR: Failed to connect to server! ' . $e->getResponse()->getBody() . PHP_EOL);
  468.     exit(1);
  469. } catch (Throwable $e) {
  470.     fwrite(STDERR, 'ERROR: Failed to connect to server! ' . $e->getMessage() . PHP_EOL);
  471.     exit(1);
  472. }
  473. fwrite(STDOUT, 'Connected to Server!' . PHP_EOL);
  474.  
  475. // Parse the command
  476. switch(strtolower($command)) {
  477.     // Gets the user's profile
  478.     case "get_profile":
  479.         if (count($args) < 1) {
  480.             fwrite(STDERR, 'ERROR: Not enough arguments given!' . PHP_EOL);
  481.             showHelp($script);
  482.             exit(1);
  483.         }
  484.         try {
  485.             $userId = array_shift($args);
  486.             $profile = getProfile($graph, $userId);
  487.             var_dump($profile);
  488.         } catch (\GuzzleHttp\Exception\RequestException $e) {
  489.             fwrite(STDERR, 'ERROR: Failed to get profile! ' . $e->getResponse()->getBody() . PHP_EOL);
  490.             exit(1);
  491.         } catch (Throwable $e) {
  492.             fwrite(STDERR, 'ERROR: Failed to get profile! ' . $e->getMessage() . PHP_EOL);
  493.             exit(1);    
  494.         }
  495.         break;
  496.     // List the drives on a site
  497.     case "list_drives":
  498.         if (count($args) < 1) {
  499.             fwrite(STDERR, 'ERROR: Not enough arguments given!' . PHP_EOL);
  500.             showHelp($script);
  501.             exit(1);
  502.         }
  503.         try {
  504.             $server = array_shift($args);
  505.             $path = null;
  506.             $remoteServer = parseRemoteServer($server);
  507.             fwrite(STDERR, 'Remote Server: ' . $remoteServer["server"] . PHP_EOL);
  508.             fwrite(STDERR, 'Site Name: ' . $remoteServer["site"] . PHP_EOL);
  509.  
  510.             fwrite(STDERR, 'Getting Site...' . PHP_EOL);
  511.             $site = getSite($graph, $remoteServer["server"], $remoteServer["site"]);
  512.             fwrite(STDERR, 'Site URL: ' . $site->getWebUrl() . PHP_EOL);
  513.  
  514.             fwrite(STDERR, 'Getting drives...' . PHP_EOL);
  515.             $drives = getDrives($graph, $site);
  516.  
  517.             fwrite(STDOUT, 'CSV:Name,Type,URL' . PHP_EOL);
  518.             /** @var Model\Drive $drive */
  519.             foreach ($drives as $drive) {
  520.                 fwrite(STDOUT, 'CSV:"' . $drive->getName() . '","' . $drive->getDriveType() . '","' . $drive->getWebUrl() . '"' . PHP_EOL);
  521.             }
  522.         } catch (\GuzzleHttp\Exception\RequestException $e) {
  523.             fwrite(STDERR, 'ERROR: Failed to list drives! ' . $e->getResponse()->getBody() . PHP_EOL);
  524.             exit(1);
  525.         } catch (Throwable $e) {
  526.             fwrite(STDERR, 'ERROR: Failed to list drives! ' . $e->getMessage() . PHP_EOL);
  527.             exit(1);    
  528.         }
  529.         break;
  530.     // List the files in a folder
  531.     case "list_drive_items":
  532.         if (count($args) < 2) {
  533.             fwrite(STDERR, 'ERROR: Not enough arguments given!' . PHP_EOL);
  534.             showHelp($script);
  535.             exit(1);
  536.         }
  537.         try {
  538.             $server = array_shift($args);
  539.             $path = array_shift($args);
  540.             $remoteServer = parseRemoteServer($server);
  541.             $remotePath = parseRemotePath($path);
  542.             fwrite(STDERR, 'Remote Server: ' . $remoteServer["server"] . PHP_EOL);
  543.             fwrite(STDERR, 'Site Name: ' . $remoteServer["site"] . PHP_EOL);
  544.             fwrite(STDERR, 'Drive Name: ' . $remotePath["drive"] . PHP_EOL);
  545.             fwrite(STDERR, 'Remote Folder: ' . $remotePath["folder"] . PHP_EOL);
  546.  
  547.             fwrite(STDERR, 'Getting Site...' . PHP_EOL);
  548.             $site = getSite($graph, $remoteServer["server"], $remoteServer["site"]);
  549.             fwrite(STDERR, 'Site URL: ' . $site->getWebUrl() . PHP_EOL);
  550.             fwrite(STDERR, 'Getting drive...' . PHP_EOL);
  551.             $drive = getDrive($graph, $site, $remotePath["drive"]);
  552.             fwrite(STDERR, 'Getting folder...' . PHP_EOL);
  553.             $folder = getDriveItem($graph, $drive, $remotePath["folder"], null);
  554.             fwrite(STDERR, 'Folder URL: ' . $folder->getWebUrl() . PHP_EOL);
  555.             fwrite(STDERR, 'Getting drive items...' . PHP_EOL);
  556.             $items = getDriveItems($graph, $drive, $remotePath["folder"]);
  557.  
  558.             fwrite(STDOUT, 'CSV:Name,URL,File Size,Date Created,Date Modified' . PHP_EOL);
  559.             /** @var Model\DriveItem $item */
  560.             foreach ($items as $item) {
  561.                 $itemType = null;
  562.                 if ($item->getFolder() != null) {
  563.                     $itemType = "Folder";
  564.                 } else {
  565.                     $itemType = "File";
  566.                 }
  567.                 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);
  568.             }
  569.         } catch (\GuzzleHttp\Exception\RequestException $e) {
  570.             fwrite(STDERR, 'ERROR: Failed to list drive items! ' . $e->getResponse()->getBody() . PHP_EOL);
  571.             exit(1);
  572.         } catch (Throwable $e) {
  573.             fwrite(STDERR, 'ERROR: Failed to list drive items! ' . $e->getMessage() . PHP_EOL);
  574.             exit(1);    
  575.         }
  576.         break;
  577.     // Upload a file
  578.     case "upload_file":
  579.         if (count($args) < 4) {
  580.             fwrite(STDERR, 'ERROR: Not enough arguments given!' . PHP_EOL);
  581.             showHelp($script);
  582.             exit(1);
  583.         }
  584.         try {
  585.             $server = array_shift($args);
  586.             $path = array_shift($args);
  587.             $remoteServer = parseRemoteServer($server);
  588.             $remotePath = parseRemotePath($path);
  589.             fwrite(STDERR, 'Remote Server: ' . $remoteServer["server"] . PHP_EOL);
  590.             fwrite(STDERR, 'Site Name: ' . $remoteServer["site"] . PHP_EOL);
  591.             fwrite(STDERR, 'Drive Name: ' . $remotePath["drive"] . PHP_EOL);
  592.             fwrite(STDERR, 'Remote Folder: ' . $remotePath["folder"] . PHP_EOL);
  593.  
  594.             $localFilePath = array_shift($args);
  595.             $remoteFileName = array_shift($args);
  596.             fwrite(STDERR, 'Local File Path: ' . $localFilePath . PHP_EOL);
  597.             fwrite(STDERR, 'Remote File Name: ' . $remoteFileName . PHP_EOL);
  598.  
  599.             if (!file_exists($localFilePath)) {
  600.                 throw new Exception('Local file does not exist!');
  601.             }
  602.  
  603.             fwrite(STDERR, 'Getting Site...' . PHP_EOL);
  604.             $site = getSite($graph, $remoteServer["server"], $remoteServer["site"]);
  605.             fwrite(STDERR, 'Site URL: ' . $site->getWebUrl() . PHP_EOL);
  606.             fwrite(STDERR, 'Getting drive...' . PHP_EOL);
  607.             $drive = getDrive($graph, $site, $remotePath["drive"]);
  608.             fwrite(STDERR, 'Getting destination folder...' . PHP_EOL);
  609.             $folder = getDriveItem($graph, $drive, $remotePath["folder"], null);
  610.             fwrite(STDERR, 'Folder URL: ' . $folder->getWebUrl() . PHP_EOL);
  611.             fwrite(STDERR, 'Uploading file (' . number_format(filesize($localFilePath), 0) . ' bytes)...' . PHP_EOL);
  612.             uploadDriveItem($graph, $drive, $localFilePath, $remotePath["folder"], $remoteFileName);
  613.             fwrite(STDERR, 'Upload complete!' . PHP_EOL);
  614.         } catch (\GuzzleHttp\Exception\RequestException $e) {
  615.             fwrite(STDERR, 'ERROR: Failed to upload file! ' . $e->getResponse()->getBody() . PHP_EOL);
  616.             exit(1);
  617.         } catch (Throwable $e) {
  618.             fwrite(STDERR, 'ERROR: Failed to upload file! ' . $e->getMessage() . PHP_EOL);
  619.             exit(1);    
  620.         }
  621.         break;
  622.     // Create a new folder
  623.     case "create_folder":
  624.         if (count($args) < 3) {
  625.             fwrite(STDERR, 'ERROR: Not enough arguments given!' . PHP_EOL);
  626.             showHelp($script);
  627.             exit(1);
  628.         }
  629.         try {
  630.             $server = array_shift($args);
  631.             $path = array_shift($args);
  632.             $remoteServer = parseRemoteServer($server);
  633.             $remotePath = parseRemotePath($path);
  634.             fwrite(STDERR, 'Remote Server: ' . $remoteServer["server"] . PHP_EOL);
  635.             fwrite(STDERR, 'Site Name: ' . $remoteServer["site"] . PHP_EOL);
  636.             fwrite(STDERR, 'Drive Name: ' . $remotePath["drive"] . PHP_EOL);
  637.             fwrite(STDERR, 'Remote Folder: ' . $remotePath["folder"] . PHP_EOL);
  638.  
  639.             $newFolderName = array_shift($args);
  640.             fwrite(STDERR, 'New Folder Name: ' . $newFolderName . PHP_EOL);
  641.  
  642.             if ($newFolderName == null || $newFolderName == "") {
  643.                 fwrite(STDERR, 'ERROR: Remote filename not specified!' . PHP_EOL);
  644.                 exit(1);
  645.             }
  646.  
  647.             fwrite(STDERR, 'Getting Site...' . PHP_EOL);
  648.             $site = getSite($graph, $remoteServer["server"], $remoteServer["site"]);
  649.             fwrite(STDERR, 'Site URL: ' . $site->getWebUrl() . PHP_EOL);
  650.             fwrite(STDERR, 'Getting drive...' . PHP_EOL);
  651.             $drive = getDrive($graph, $site, $remotePath["drive"]);
  652.             fwrite(STDERR, 'Creating folder...' . PHP_EOL);
  653.             createFolder($graph, $drive, $remotePath["folder"], $newFolderName);
  654.             fwrite(STDERR, 'Folder created' . PHP_EOL);
  655.         } catch (\GuzzleHttp\Exception\RequestException $e) {
  656.             fwrite(STDERR, 'ERROR: Failed to create folder! ' . $e->getResponse()->getBody() . PHP_EOL);
  657.             exit(1);
  658.         } catch (Throwable $e) {
  659.             fwrite(STDERR, 'ERROR: Failed to create folder! ' . $e->getMessage() . PHP_EOL);
  660.             exit(1);
  661.         }
  662.         break;
  663.     // Download a file
  664.     case "download_file":
  665.         if (count($args) < 4) {
  666.             fwrite(STDERR, 'ERROR: Not enough arguments given!' . PHP_EOL);
  667.             showHelp($script);
  668.             exit(1);
  669.         }
  670.         try {
  671.             $server = array_shift($args);
  672.             $path = array_shift($args);
  673.             $remoteServer = parseRemoteServer($server);
  674.             $remotePath = parseRemotePath($path);
  675.             fwrite(STDERR, 'Remote Server: ' . $remoteServer["server"] . PHP_EOL);
  676.             fwrite(STDERR, 'Site Name: ' . $remoteServer["site"] . PHP_EOL);
  677.             fwrite(STDERR, 'Drive Name: ' . $remotePath["drive"] . PHP_EOL);
  678.             fwrite(STDERR, 'Remote Folder: ' . $remotePath["folder"] . PHP_EOL);
  679.  
  680.             $remoteFileName = array_shift($args);
  681.             $localFile = array_shift($args);
  682.             fwrite(STDERR, 'Remote File Name: ' . $remoteFileName . PHP_EOL);
  683.             fwrite(STDERR, 'Local File: ' . $localFile . PHP_EOL);
  684.  
  685.             if ($remoteFileName == null || $remoteFileName == "") {
  686.                 fwrite(STDERR, 'ERROR: Remote filename not specified!' . PHP_EOL);
  687.                 exit(1);
  688.             }
  689.  
  690.             if ($localFile == null || $localFile == "") {
  691.                 fwrite(STDERR, 'ERROR: Local file not specified!' . PHP_EOL);
  692.                 exit(1);
  693.             }
  694.  
  695.             fwrite(STDERR, 'Getting Site...' . PHP_EOL);
  696.             $site = getSite($graph, $remoteServer["server"], $remoteServer["site"]);
  697.             fwrite(STDERR, 'Site URL: ' . $site->getWebUrl() . PHP_EOL);
  698.             fwrite(STDERR, 'Getting drive...' . PHP_EOL);
  699.             $drive = getDrive($graph, $site, $remotePath["drive"]);
  700.             fwrite(STDERR, 'Downloading file...' . PHP_EOL);
  701.             $fileStream = downloadFile($graph, $drive, $remotePath["folder"], $remoteFileName);
  702.             file_put_contents($localFile, $fileStream);
  703.             fwrite(STDERR, 'File downloaded' . PHP_EOL);
  704.         } catch (\GuzzleHttp\Exception\RequestException $e) {
  705.             fwrite(STDERR, 'ERROR: Failed to download file! ' . $e->getResponse()->getBody() . PHP_EOL);
  706.             exit(1);
  707.         } catch (Throwable $e) {
  708.             fwrite(STDERR, 'ERROR: Failed to download file! ' . $e->getMessage() . PHP_EOL);
  709.             exit(1);
  710.         }
  711.         break;
  712.     // Delete a drive item
  713.     case "delete_drive_item":
  714.         if (count($args) < 3) {
  715.             fwrite(STDERR, 'ERROR: Not enough arguments given!' . PHP_EOL);
  716.             showHelp($script);
  717.             exit(1);
  718.         }
  719.         try {
  720.             $server = array_shift($args);
  721.             $path = array_shift($args);
  722.             $remoteServer = parseRemoteServer($server);
  723.             $remotePath = parseRemotePath($path);
  724.             fwrite(STDERR, 'Remote Server: ' . $remoteServer["server"] . PHP_EOL);
  725.             fwrite(STDERR, 'Site Name: ' . $remoteServer["site"] . PHP_EOL);
  726.             fwrite(STDERR, 'Drive Name: ' . $remotePath["drive"] . PHP_EOL);
  727.             fwrite(STDERR, 'Remote Folder: ' . $remotePath["folder"] . PHP_EOL);
  728.  
  729.             $remoteFileName = array_shift($args);
  730.             fwrite(STDERR, 'Remote File Name: ' . $remoteFileName . PHP_EOL);
  731.  
  732.             if ($remoteFileName == null || $remoteFileName == "") {
  733.                 fwrite(STDERR, 'ERROR: Remote filename not specified!' . PHP_EOL);
  734.                 exit(1);
  735.             }
  736.  
  737.             fwrite(STDERR, 'Getting Site...' . PHP_EOL);
  738.             $site = getSite($graph, $remoteServer["server"], $remoteServer["site"]);
  739.             fwrite(STDERR, 'Site URL: ' . $site->getWebUrl() . PHP_EOL);
  740.             fwrite(STDERR, 'Getting drive...' . PHP_EOL);
  741.             $drive = getDrive($graph, $site, $remotePath["drive"]);
  742.             fwrite(STDERR, 'Deleting file...' . PHP_EOL);
  743.             deleteDriveItem($graph, $drive, $remotePath["folder"], $remoteFileName);
  744.             fwrite(STDERR, 'File deleted' . PHP_EOL);
  745.         } catch (\GuzzleHttp\Exception\RequestException $e) {
  746.             fwrite(STDERR, 'ERROR: Failed to delete file! ' . $e->getResponse()->getBody() . PHP_EOL);
  747.             exit(1);
  748.         } catch (Throwable $e) {
  749.             fwrite(STDERR, 'ERROR: Failed to delete file! ' . $e->getMessage() . PHP_EOL);
  750.             exit(1);
  751.         }
  752.         break;
  753.     // Prune files in a folder older than a given number of days
  754.     case "prune_folder":
  755.         if (count($args) < 4) {
  756.             fwrite(STDERR, 'ERROR: Not enough arguments given!' . PHP_EOL);
  757.             showHelp($script);
  758.             exit(1);
  759.         }
  760.         try {
  761.             $server = array_shift($args);
  762.             $path = array_shift($args);
  763.             $remoteServer = parseRemoteServer($server);
  764.             $remotePath = parseRemotePath($path);
  765.             fwrite(STDERR, 'Remote Server: ' . $remoteServer["server"] . PHP_EOL);
  766.             fwrite(STDERR, 'Site Name: ' . $remoteServer["site"] . PHP_EOL);
  767.             fwrite(STDERR, 'Drive Name: ' . $remotePath["drive"] . PHP_EOL);
  768.             fwrite(STDERR, 'Remote Folder: ' . $remotePath["folder"] . PHP_EOL);
  769.  
  770.             $regexMatch = array_shift($args);
  771.             $daysToKeep = array_shift($args);
  772.             fwrite(STDERR, 'Regex Match: ' . $regexMatch . PHP_EOL);
  773.             fwrite(STDERR, 'Days to keep: ' . $daysToKeep . PHP_EOL);
  774.  
  775.             if ($regexMatch == null || $regexMatch == '') {
  776.                 fwrite(STDERR, "ERROR: No regular expression found!" . PHP_EOL);
  777.                 exit(1);
  778.             }
  779.    
  780.             if (!is_numeric($daysToKeep)) {
  781.                 fwrite(STDERR, "ERROR: Days to keep is not numeric!" . PHP_EOL);
  782.                 exit(1);
  783.             }
  784.  
  785.             fwrite(STDERR, 'Getting Site...' . PHP_EOL);
  786.             $site = getSite($graph, $remoteServer["server"], $remoteServer["site"]);
  787.             fwrite(STDERR, 'Site URL: ' . $site->getWebUrl() . PHP_EOL);
  788.             fwrite(STDERR, 'Getting drive...' . PHP_EOL);
  789.             $drive = getDrive($graph, $site, $remotePath["drive"]);
  790.             fwrite(STDERR, 'Getting drive items...' . PHP_EOL);
  791.             $items = getDriveItems($graph, $drive, $remotePath["folder"]);
  792.             fwrite(STDERR, 'Pruning drive items...' . PHP_EOL);
  793.             $deletedFileCount = 0;
  794.             /** @var Model\DriveItem $item */
  795.             foreach ($items as $item) {
  796.                 // Check if the item is a folder and go to the next item if it is
  797.                 if ($item->getFolder() != null) {
  798.                     continue;
  799.                 }
  800.                 $interval = $item->getLastModifiedDateTime()->diff(new DateTime());
  801.                 $daysOld = $interval->format('%a');
  802.                 if ($daysOld > $daysToKeep && preg_match($regexMatch, $item->getName())) {
  803.                     fwrite(STDOUT, 'Deleting: ' . $item->getName() . PHP_EOL);
  804.                     deleteDriveItem($graph, $drive, $remotePath["folder"], $item->getName());
  805.                     $deletedFileCount++;
  806.                 }
  807.             }
  808.             fwrite(STDERR, 'Drive items pruned: ' . $deletedFileCount . PHP_EOL);
  809.         } catch (\GuzzleHttp\Exception\RequestException $e) {
  810.             fwrite(STDERR, 'ERROR: Failed to prune drive items! ' . $e->getResponse()->getBody() . PHP_EOL);
  811.             exit(1);
  812.         } catch (Throwable $e) {
  813.             fwrite(STDERR, 'ERROR: Failed to prune drive items! ' . $e->getMessage() . PHP_EOL);
  814.             exit(1);    
  815.         }
  816.         break;
  817.     default:
  818.         fwrite(STDOUT, 'ERROR: Unknown command: ' . strtolower($command) . PHP_EOL);
  819.         showHelp($script);
  820.         exit(1);
  821. }
  822.  
  823. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement