Skip to content

Commit a1ababb

Browse files
committed
SharePoint API: file/folder addressing enhancements
1 parent fccca6c commit a1ababb

File tree

6 files changed

+96
-25
lines changed

6 files changed

+96
-25
lines changed

examples/SharePoint/Files/DownloadFileAsContent.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,13 @@
88
require_once '../../vendor/autoload.php';
99
$settings = include('../../../tests/Settings.php');
1010

11-
$sourceFileUrl = "/Shared Documents/SharePoint User Guide.docx";
11+
$sourceFileUrl = "/sites/team/Shared Documents/sample.txt";
1212
$targetPath = "../data/SharePoint User Guide.docx";
1313

1414
$appCreds = new ClientCredential($settings['ClientId'], $settings['ClientSecret']);
15-
$ctx = (new ClientContext($settings['Url']))->withCredentials($appCreds);
15+
$ctx = (new ClientContext($settings['TeamSiteUrl']))->withCredentials($appCreds);
1616
$fileContent = Office365\SharePoint\File::openBinary($ctx, $sourceFileUrl);
1717
print "File {$targetPath} has been downloaded successfully\r\n";
18-
$fileName = join(DIRECTORY_SEPARATOR,[sys_get_temp_dir(),"SharePoint User Guide.docx"]);
18+
$fileName = join(DIRECTORY_SEPARATOR,[sys_get_temp_dir(),basename($sourceFileUrl)]);
1919
file_put_contents($fileName,$fileContent);
2020

examples/SharePoint/Files/DownloadFiles.php

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,28 @@
1212
$creds = new ClientCredential($settings['ClientId'], $settings['ClientSecret']);
1313
$ctx = (new ClientContext($settings['TeamSiteUrl']))->withCredentials($creds);
1414

15-
$lib_title = "Documents";
15+
/*$lib_title = "Documents";
1616
$lib = $ctx->getWeb()->getLists()->getByTitle($lib_title);
17-
$folder = $lib->getRootFolder()->expand("Files")->get()->executeQuery();
17+
$rootFolder = $lib->getRootFolder()->expand("Files")->get()->executeQuery();*/
18+
19+
$rootFolder = $ctx
20+
->getWeb()
21+
->getFolderByServerRelativeUrl('Shared Documents')
22+
->expand('Files')
23+
->get()
24+
->executeQuery();
25+
1826

1927
/** @var File $file */
20-
foreach ($folder->getFiles() as $file) {
28+
foreach ($rootFolder->getFiles() as $file) {
2129
try {
2230
$localPath = join(DIRECTORY_SEPARATOR, [sys_get_temp_dir(), $file->getName()]);
2331
$fh = fopen($localPath, 'w+');
2432
$file->download($fh)->executeQuery();
2533
fclose($fh);
2634
print "File: {$file->getServerRedirectedUrl()} has been downloaded into {$localPath}\r\n";
27-
} catch (\Throwable $th) {
28-
print "Error {$th->getCode()} - File download failed: {$th->getMessage()}";
35+
} catch (Exception $ex) {
36+
print "Error {$ex->getCode()} - File download failed: {$ex->getMessage()}";
2937
}
3038
}
3139

src/SharePoint/File.php

Lines changed: 38 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
namespace Office365\SharePoint;
77

88
use Exception;
9-
use Office365\Runtime\Actions\InvokeMethodQuery;
109
use Office365\Runtime\Actions\InvokePostMethodQuery;
1110
use Office365\Runtime\ClientResult;
1211
use Office365\Runtime\ClientRuntimeContext;
@@ -16,6 +15,7 @@
1615
use Office365\Runtime\Paths\ServiceOperationPath;
1716
use Office365\Runtime\ResourcePath;
1817
use Office365\Runtime\Types\Guid;
18+
use Office365\SharePoint\Internal\Paths\FileContentPath;
1919
use Office365\SharePoint\WebParts\LimitedWebPartManager;
2020

2121
/**
@@ -177,17 +177,25 @@ public function recycle()
177177
$this->getContext()->addQuery($qry);
178178
return $this;
179179
}
180+
181+
180182
/**
181183
* Opens the file
182-
* @param ClientRuntimeContext $ctx
183-
* @param $serverRelativeUrl
184+
* @param ClientContext $ctx
185+
* @param string $serverRelativeUrl
186+
* @param bool $usePath
184187
* @return mixed|string
185188
* @throws Exception
186189
*/
187-
public static function openBinary(ClientRuntimeContext $ctx, $serverRelativeUrl)
190+
public static function openBinary(ClientRuntimeContext $ctx, $serverRelativeUrl, $usePath=true)
188191
{
189-
$serverRelativeUrl = rawurlencode($serverRelativeUrl);
190-
$url = $ctx->getServiceRootUrl() . "/web/getfilebyserverrelativeurl('{$serverRelativeUrl}')/\$value";
192+
$file = new File($ctx);
193+
if($usePath)
194+
$file->setProperty("ServerRelativePath",new SPResourcePath($serverRelativeUrl));
195+
else
196+
$file->setProperty("ServerRelativeUrl",$serverRelativeUrl);
197+
$contentPath = new FileContentPath($file->getResourcePath());
198+
$url = $ctx->getServiceRootUrl() . $contentPath->toUrl();
191199
$options = new RequestOptions($url);
192200
$options->TransferEncodingChunkedAllowed = true;
193201
$response = $ctx->executeQueryDirect($options);
@@ -199,15 +207,21 @@ public static function openBinary(ClientRuntimeContext $ctx, $serverRelativeUrl)
199207
/**
200208
* Saves the file
201209
* Note: it is supported to update the existing file only. For adding a new file see FileCollection.add method
202-
* @param ClientRuntimeContext $ctx
210+
* @param ClientContext $ctx
203211
* @param string $serverRelativeUrl
204212
* @param string $content file content
213+
* @param bool $usePath
205214
* @throws Exception
206215
*/
207-
public static function saveBinary(ClientRuntimeContext $ctx, $serverRelativeUrl, $content)
216+
public static function saveBinary(ClientRuntimeContext $ctx, $serverRelativeUrl, $content, $usePath=true)
208217
{
209-
$serverRelativeUrl = rawurlencode($serverRelativeUrl);
210-
$url = $ctx->getServiceRootUrl() . "/web/getfilebyserverrelativeurl('{$serverRelativeUrl}')/\$value";
218+
$file = new File($ctx);
219+
if($usePath)
220+
$file->setProperty("ServerRelativePath",new SPResourcePath($serverRelativeUrl));
221+
else
222+
$file->setProperty("ServerRelativeUrl",$serverRelativeUrl);
223+
$contentPath = new FileContentPath($file->getResourcePath());
224+
$url = $ctx->getServiceRootUrl() . $contentPath->toUrl();
211225
$request = new RequestOptions($url);
212226
$request->Method = HttpMethod::Post;
213227
$request->ensureHeader('X-HTTP-Method', 'PUT');
@@ -259,7 +273,8 @@ public function getCheckOutType()
259273
*/
260274
public function getListItemAllFields()
261275
{
262-
return $this->getProperty("ListItemAllFields", new ListItem($this->getContext(), new ResourcePath("ListItemAllFields", $this->getResourcePath())));
276+
return $this->getProperty("ListItemAllFields",
277+
new ListItem($this->getContext(), new ResourcePath("ListItemAllFields", $this->getResourcePath())));
263278
}
264279
/**
265280
* Starts a new chunk upload session and uploads the first fragment
@@ -298,18 +313,23 @@ public function continueUpload($uploadId, $fileOffset, $content)
298313
*/
299314
public function finishUpload($uploadId, $fileOffset, $content)
300315
{
301-
$qry = new InvokePostMethodQuery($this, "finishupload", array('uploadId' => $uploadId->toString(), 'fileOffset' => $fileOffset), null, $content);
316+
$qry = new InvokePostMethodQuery($this, "finishupload",
317+
array('uploadId' => $uploadId->toString(), 'fileOffset' => $fileOffset), null, $content);
302318
$this->getContext()->addQueryAndResultObject($qry, $this);
303319
return $this;
304320
}
305321
function setProperty($name, $value, $persistChanges = true)
306322
{
307323
parent::setProperty($name, $value, $persistChanges);
308324
if ($name === "UniqueId") {
309-
$this->resourcePath = new ResourcePath("GetFileById(guid'{$value}')", new ResourcePath("Web"));
310-
} else {
325+
$this->resourcePath = $this->getParentWeb()->getFileById($value)->getResourcePath();
326+
}
327+
if (is_null($this->resourcePath)) {
311328
if ($name === "ServerRelativeUrl") {
312-
$this->resourcePath = new ResourcePath("GetFileByServerRelativeUrl('{$value}')", new ResourcePath("Web"));
329+
$this->resourcePath = $this->getParentWeb()->getFileByServerRelativeUrl($value)->getResourcePath();
330+
}
331+
elseif ($name === "ServerRelativePath") {
332+
$this->resourcePath = $this->getParentWeb()->getFileByServerRelativePath($value)->getResourcePath();
313333
}
314334
}
315335
return $this;
@@ -889,7 +909,9 @@ public function getModifiedBy()
889909
*/
890910
public function getEffectiveInformationRightsManagementSettings()
891911
{
892-
return $this->getProperty("EffectiveInformationRightsManagementSettings", new EffectiveInformationRightsManagementSettings($this->getContext(), new ResourcePath("EffectiveInformationRightsManagementSettings", $this->getResourcePath())));
912+
return $this->getProperty("EffectiveInformationRightsManagementSettings",
913+
new EffectiveInformationRightsManagementSettings($this->getContext(),
914+
new ResourcePath("EffectiveInformationRightsManagementSettings", $this->getResourcePath())));
893915
}
894916
/**
895917
* @return Web|null

src/SharePoint/Folder.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ public function getListItemAllFields()
143143
function setProperty($name, $value, $persistChanges = true)
144144
{
145145
if ($name == "UniqueId") {
146-
$this->resourcePath = new ResourcePath("GetFolderById(guid'{$value}')", new ResourcePath("Web"));
146+
$this->resourcePath = $this->getContext()->getWeb()->getFolderById($value)->getResourcePath();
147147
}
148148
parent::setProperty($name, $value, $persistChanges);
149149
return $this;
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
3+
namespace Office365\SharePoint\Internal\Paths;
4+
5+
6+
use Office365\Runtime\ResourcePath;
7+
8+
9+
class FileContentPath extends ResourcePath
10+
{
11+
/***
12+
* @param ResourcePath|null $parent
13+
*/
14+
public function __construct(ResourcePath $parent = null)
15+
{
16+
parent::__construct("\$value", $parent);
17+
}
18+
19+
20+
}

src/SharePoint/Web.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,17 @@ public function getFileByServerRelativePath($serverRelativePath)
192192
$params = array("decodedUrl" => rawurlencode($serverRelativePath->DecodedUrl));
193193
return new File($this->getContext(), new ServiceOperationPath("getFileByServerRelativePath", $params, $this->getResourcePath()));
194194
}
195+
196+
/**
197+
* Returns the file object with the specified GUID.
198+
* @param string uniqueId A GUID that identifies the file object.
199+
* @return File
200+
*/
201+
public function getFileById($uniqueId)
202+
{
203+
return new File($this->getContext(),
204+
new ServiceOperationPath("GetFileById", array($uniqueId), $this->getResourcePath()));
205+
}
195206
/**
196207
* Returns the folder object located at the specified server-relative URL.
197208
* @param string $serverRelativeUrl The server relative URL of the folder.
@@ -210,6 +221,16 @@ public function getFolderByServerRelativePath($serverRelativePath)
210221
{
211222
return new Folder($this->getContext(), new ServiceOperationPath("getFolderByServerRelativePath", array("decodedUrl" => rawurlencode($serverRelativePath->DecodedUrl)), $this->getResourcePath()));
212223
}
224+
/**
225+
* Returns the folder object with the specified GUID.
226+
* @param string uniqueId A GUID that identifies the folder object.
227+
* @return Folder
228+
*/
229+
public function getFolderById($uniqueId)
230+
{
231+
return new Folder($this->getContext(),
232+
new ServiceOperationPath("GetFolderById", array($uniqueId), $this->getResourcePath()));
233+
}
213234
/**
214235
* @return ContentTypeCollection
215236
*/

0 commit comments

Comments
 (0)