Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Spo Laravel Package

vgrem/php-spo

REST/OData client library for Microsoft 365 in PHP. Access SharePoint Online/On-Prem (2013-2019), OneDrive for Business, Teams, and Outlook APIs with supported auth flows (client credentials, certificates, etc.). Install via Composer.

View on GitHub
Deep Wiki
Context7
v3.2.0

Changelog

New Features

  • Planner API: Enhanced support for Microsoft Graph Planner API

Fixes & Improvements

  • PR #352: Fix OneDrive file upload session retry logic (by @it-can)
  • PR #350: Improve error handling for SharePoint API requests (by @VincentFoulon80)
  • PR #348: Fix metadata handling in file uploads (by @JensDeMuynck)
  • PR #129: Fix OneDrive large file upload session
v3.1.2

Added

  • GraphServiceClient::withUserCredentials and GraphServiceClient::withClientSecret methods introduced

Fixed

  • #337: Don't try to retrieve next set of items when using an iterator, if no next items are expected to exist
v3.1.1

Changelog

  • SharePoint model updated to 16.0.24106.12014 version
  • import fixes (patches for 3.1.0 version)
v3.1.0

Changelog

  • support for authenticate SharePoint API via client certificate flow
  • validate access token response in GraphServiceClient

Example: how to authenticate SharePoint API via client certificate flow

$siteUrl = "https://contoso.sharepoint.com";  //site or web absolute url 
$tenant = "contoso.onmicrosoft.com"; //tenant id or name
$thumbprint = "--thumbprint goes here--";
$clientId = "--client app id goes here--";
$privateKetPath = "-- path to private.key file--"
$privateKey = file_get_contents($privateKetPath);

$ctx = (new ClientContext($siteUrl))->withClientCertificate(
    $tenant, $clientId, $privateKey, $thumbprint);

$whoami = $ctx->getWeb()->getCurrentUser()->get()->executeQuery();
print $whoami->getLoginName();
v3.0.3

Changelog

  • support for document sets in SharePoint API
  • fix addering issue with web resource

Example: create a Document Set

$credentials = new ClientCredential($clientId, $clientSecret);
$client = (new ClientContext($siteUrl))->withCredentials($credentials);

$docSetName = "Orders"; 
$lib = $client->getWeb()->defaultDocumentLibrary();
$docSet = DocumentSet::create($client, $lib->getRootFolder(), $docSetName)->executeQuery();
print($docSet->getProperty("ServerRelativeUrl"));
v3.0.2

Changelog

v3.0.1

Changelog

  • #300: add CcRecipients property to Message class by @DavidBrogli
  • #304: Http Response improvements by @lbuchs
  • #307 add example to obtain available fields of a list by @cweiske
  • #318 Support for custom curl options by @drml
  • ClientObjectCollection class enhancements, introduced getAll method by @vgrem

Example: read list items in a large list via getAll method:

$ctx = (new ClientContext($siteUrl))->withCredentials($credentials);
$list = $ctx->getWeb()->getLists()->getByTitle("--large list title--");

$allItems = $list->getItems()->getAll(5000, function ($returnType){
    print("{$returnType->getPageInfo()} items loaded...\n");
})->executeQuery();
v3.0.0

Changelog

  • #283: exception handling enhancements for authentication requests by @SuperDJ
  • #286: introduced client secret support for acquireTokenForPassword method in AADTokenProvider class by @R-Tech
  • #287 and #288: captures and validates if response failed by @fr3nch13
  • #297: remove minimum-stability from composer.json by @cweiske
  • #298 and #299: deprecation fixes for PHP 8 and drop PHP 5.5 requirement by @cweiske
v2.5.4

Changelog

v2.5.3

Changelog

  • SharePoint API: improved support for composite field values namely FieldLookupValue/FieldMultiLookupValue, FieldMultiChoiceValue , refer example 1 below ( related issues: #261)
  • OData request/response serialization optimizations (namely excluding metadata annotations from response by default)

Example : create list item and specify multi lookup & choice fields values:

$list = $ctx->getWeb()->getLists()->getByTitle("Tasks");

$taskProps = array(
    'Title' => "New task",
    'ParentTask' => new FieldLookupValue($taskLookupId),
    'PrimaryManager' => new FieldUserValue($userId),
    'Managers' => new FieldMultiLookupValue([$userId]),
    'TaskCategories' => new FieldMultiChoiceValue(["Event", "Reminder"])
);
$item = $list->addItem($taskProps)->executeQuery();
2.5.2

Changelog

  • introduced Reports namespace, refer official documentation for a more details
  • Outlook namespace model updates
  • SharePoint API: model updated to 16.0.21729.12001 version

Example: Get details about Microsoft 365 active users

Documentation: reportRoot: getOffice365ActiveUserDetail


use Office365\GraphServiceClient;
use Office365\Runtime\Auth\AADTokenProvider;
use Office365\Runtime\Auth\ClientCredential;


function acquireToken()
{
   $resource = "https://graph.microsoft.com";
   $provider = new AADTokenProvider($tenantName);
   return $provider->acquireTokenForClientCredential($resource,
       new ClientCredential($clientId, $clientSecret),["/.default"]);
}

$client = new GraphServiceClient("acquireToken");
$result = $client->getReports()->getOffice365ActivationCounts()->executeQuery();
var_dump($result->getValue());

$result = $client->getReports()->getOffice365ActiveUserDetail("D7")->executeQuery();
var_dump($result->getValue());

2.5.1

Changelog

Example: Create a modern (communication) site

$credentials = new ClientCredential($ClientId, $ClientSecret);
$ctx = (new ClientContext($Url))->withCredentials($credentials);

$siteManager = new SPSiteManager($ctx);

$result = $siteManager->create("MyCommSite", $ownerEmail, "Low Business Impact");
$siteManager->executeQuery();
print("Site has been created: {$result->getValue()->SiteUrl} \n");
v2.5.0

Changelog

  • introduced a support for Teams API
  • performance improvements and better support for Fluent API syntax
  • introduced ClientRuntimeContext.executeQueryRetry method to submit queries which supports transparently retrying a failed operation (retry pattern)

Working with Teams API

Example: create a Team

The following is an example of a minimal request to create a Team (via delegated permissions)


use Office365\GraphServiceClient;
use Office365\Runtime\Auth\AADTokenProvider;
use Office365\Runtime\Auth\UserCredentials;

function acquireToken()
{
    $tenant = "{tenant}.onmicrosoft.com";
    $resource = "https://graph.microsoft.com";
  
    $provider = new AADTokenProvider($tenant);
    return $provider->acquireTokenForPassword($resource, "{clientId}",
        new UserCredentials("{UserName}", "{Password}"));
}

$client = new GraphServiceClient("acquireToken");
$teamName = "My Sample Team";
$newTeam = $client->getTeams()->add($teamName)->executeQuery();

Example: list all Teams


use Office365\GraphServiceClient;
use Office365\Runtime\Auth\AADTokenProvider;
use Office365\Runtime\Auth\UserCredentials;

function acquireToken()
{
    $tenant = "{tenant}.onmicrosoft.com";
    $resource = "https://graph.microsoft.com";
  
    $provider = new AADTokenProvider($tenant);
    return $provider->acquireTokenForPassword($resource, "{clientId}",
        new UserCredentials("{UserName}", "{Password}"));
}

$client = new GraphServiceClient("acquireToken");
$teams = $client->getTeams()->getAll(array("displayName"))->executeQuery();

ClientRuntimeContext.executeQueryRetry method usage

Once Team is created, it might not be immediately available due to replication delay and calling getting team endpoint could fail with a 404 error, the recommended pattern is to retry the get team call three times, with a 10 second delay between calls:


$team = $graphClient->getTeams()->getById($Id)->get()->executeQueryRetry();

v2.4.5

Changelog

  • #231: introduced support for IPResolve and ForbidReuse options for RequestOptions class by @tommy2d

  • various bug fixes, including #230

  • SharePoint API support for Taxonomy namespace, refer example 1 below

  • SharePoint API model has been updated to 16.0.21221.12006

  • fluent API improvements, a simplified way to initialize GraphServiceClient and OutlookClient clients by passing acquire token function, AADTokenProvider class which contains built-in support for Client credentials, Username/password flows, refer example 2 below

Examples

Example 1: export taxonomy data via SharePoint API


use Office365\Runtime\Auth\ClientCredential;
use Office365\SharePoint\ClientContext;
use Office365\SharePoint\Taxonomy\TaxonomyService;
use Office365\SharePoint\Taxonomy\TermGroup;

$appPrincipal = new ClientCredential($clientId,$clientSecret);
$ctx = (new ClientContext($settings['Url']))->withCredentials($appPrincipal);
$taxSvc = new TaxonomyService($ctx);
$groups = $taxSvc->getTermStore()->getTermGroups()->get()->executeQuery();

$fp = fopen('./SiteTaxonomy.csv', 'w');

/** [@var](https://github.com/var) TermGroup $group */
foreach ($groups as $group){
    fputcsv($fp, $group->toJson());
}

fclose($fp);

Example 2: Initialize Graph client


use Office365\Graph\GraphServiceClient;
use Office365\Runtime\Auth\AADTokenProvider;
use Office365\Runtime\Auth\UserCredentials;


function acquireToken()
{
    $tenant = "{tenant}.onmicrosoft.com";
    $resource = "https://graph.microsoft.com";
  
    $provider = new AADTokenProvider($tenant);
    return $provider->acquireTokenForPassword($resource, "{clientId}",
        new UserCredentials("{UserName}", "{Password}"));
}

$client = new GraphServiceClient("acquireToken");

v2.4.4

Changelog

  • OData request headers adjustments (for compatibility with SharePoint 2013 REST Service implementation) #222 by @blizzz

  • #212: GroupCollection.getByName fix to safely address group by name by @mahmudz

  • #213: File.finishUpload method fix by @ChangingTerry

  • SharePoint API model has been updated to 16.0.21103.12002 version

v2.4.3

Changelog

  • Exclude non-essential files from dist #210 Credit goes to @rvitaliy

  • SharePoint API model has been updated to 16.0.20628.12006 version

  • Error handling: validate() method for class Response introduced which throws an exception if the HTTP response was unsuccessful, usage:

        $response = Requests::execute($request);
        $response->validate();
v2.4.2

Changelog

  • API support for Fluent interface which offers a more compact way of calling operations, for example, file could be downloaded like this:
$file = (new ClientContext($settings['Url']))->withCredentials($credentials)
    ->getWeb()->getFileByServerRelativePath(new SPResourcePath($fileUrl))->get()->executeQuery();
  • SharePoint API model has been updated to 16.0.20405.12008 version and introduced a new types and methods:

    • Web.getFileByServerRelativePath($resourcePath)
    • Web.getFolderByServerRelativePath($resourcePath)
  • Support for addressing Web and File resources by absolute Url

    $fileAbsUrl = "https://contoso.sharepoint.com/sites/team/Shared Documents/sample.docx"
    $credentials = UserCredential(username, password)
    
    $fh = fopen($fileName, 'w+');
    File::fromUrl($fileAbsUrl)->withCredentials($credentials)->download($fh)->executeQuery();
    fclose($fh);
    
  • Support for simplified ways of authenticating against SharePoint

    $credentials = new ClientCredential($clientId, $clientSecret);
    $ctx = (new ClientContext($url))->withCredentials($credentials);
    
v2.4.1

List of changes

  • SharePoint (for version 16.0.20106.12008) and OutlookServices models have been updated

  • built-in support to retrieve large collections (or paged data) via lazy loading approach

  • support for upload "large" file (chunked upload)

Working with SharePoint large lists and libraries (which contains more than 5000 items)

Due to built-in support, nothing has changed in terms how list items are retrieved to preserve API simplicity, no matter how many items list contains (unless $top query option is provided to restrict the amount of items to load) Behind the scene, lazy loading approach is utilized to retrieve paged data, which offers optimal performance since the data is getting load only when requested.

$list = $ctx->getWeb()->getLists()->getByTitle("--Large List Title--");
$items = $list->getItems();
$ctx->load($items);
$ctx->executeQuery();

print $items->getCount() . PHP_EOL;  //prints the actual amount of items in list/library

//iterate across all list items 
foreach ($items as $index => $item){
    print($index . ":" . $item->getProperty('Title') . PHP_EOL);
}

Upload large files

Note: Use this solution if you want to upload files that are larger than 2 MB to SharePoint.

$ctx = ClientContext::connectWithClientCredentials($Url, $ClientId, $ClientSecret);
$localPath = "../data/big_buck_bunny.mp4";
$targetLibraryTitle = "Documents";
$targetList = $ctx->getWeb()->getLists()->getByTitle($targetLibraryTitle);

$session = $targetList->getRootFolder()->getFiles()->createUploadSession($localPath, "big_buck_bunny.mp4",
  function ($uploadedBytes) {
        echo "Progress: $uploadedBytes bytes uploaded .." . PHP_EOL;
});

$ctx->executeQuery();
$targetFileName = $session->getFile()->getName();
echo "File $targetFileName has been uploaded.";
v2.4.0
  • model has been updated from 16.0.20008.12009 API version
  • refactorings and root namespace changed from Office365\PHP\Client\SharePoint into Office365\SharePoint
  • introduced a simplified way to initialize SharePoint client

a simplified way to initialize SharePoint client

from now on instead of

$authCtx = new AuthenticationContext($url); $authCtx->acquireTokenForUser($username,$password); $ctx = new ClientContext($url,$authCtx);

an authenticated client could be instantiated like this:

$ctx = ClientContext::connectWithUserCredentials($url, $username,$password);

and

$authCtx = new AuthenticationContext($url); $authCtx->acquireAppOnlyAccessToken($clientId,$clientSecret); $ctx = new ClientContext($url,$authCtx);

like this:

$ctx = ClientContext::connectWithClientCredentials($url, $clientId,$clientSecret);

v2.3.1

introduced a support to generate SharePoint model (complex & entity types) from EDMX metadata

v2.3.0
  • introduced a partial support (complex types at the moment) for generating SharePoint model from EDMX metadata
  • ability to specify chunked transfer encoding (by @Deuchnord)
v2.2.5

The list of changes:

Types:

  • RoleType - Specifies the types of roles that are available for users and groups.

  • RoleDefinitionCreationInformation - Contains properties that are used as parameters to initialize a role definition.

Methods:

  • RoleAssignmentCollection.addRoleAssignment - Adds a role assignment to the collection of role assignment objects

  • RoleAssignmentCollection.getByPrincipalId - Gets the role assignment associated with the specified principal ID from the collection

  • RoleAssignmentCollection.removeRoleAssignment - Removes the role assignment with the specified principal and role definition from the collection.

  • RoleDefinitionCollection.getById - Gets the role definition with the specified ID from the collect

  • RoleDefinitionCollection.getByName - Gets the role definition with the specified name.

  • RoleDefinitionCollection.getByType - Gets the role definition with the specified role type.

v2.2.4

Introduced support to set cURL timeout option and bug fixes.

All credit goes to @Deuchnord for those changes.

v2.2.3

Introduced support for the resource owner password credential (ROPC) grant, which allows an application to sign in the user by directly handling their password. Could be utilized instead of Basic Authentication which was discontinued in Office 365

v2.2.2

The list of changes:

Introduced support for skiptoken operation in query options #118

Added support for managing requests state ( e.g. skipping failed requests)

Updated Travis config file for unit testing against PHP 7.3

v2.2.1

The list of resolved issues:

#115 - process error from STS response

JSON formats mapper improvements

v2.2.0

Added support for federated STS authentication

v2.1.9
v2.1.8
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor