Giter VIP home page Giter VIP logo

phpspo's Introduction

About

Microsoft 365 Library for PHP. A REST/OData based client library for Microsoft 365.

Usage

  1. Installation
  2. Working with SharePoint API
  3. Working with Teams API
  4. Working with Outlook API
  5. Working with OneDrive API

Status

Total Downloads Latest Stable Version Build Status License

Installation

You can use Composer or simply Download the Release

Composer

The preferred method is via composer. Follow the installation instructions if you do not already have composer installed.

Once composer installed, execute the following command in your project root to install this library:

composer require vgrem/php-spo

or via composer.json file:

{
    "require": {
        "vgrem/php-spo": "^3"
    }
}

Finally, be sure to include the autoloader:

require_once '/path/to/your-project/vendor/autoload.php';

Requirements

PHP version: PHP 7.1 or later

Working with SharePoint API

The list of supported SharePoint versions:

  • SharePoint Online and OneDrive for Business
  • SharePoint On-Premises (2013-2019)

Authentication

The following auth flows supported:

1. app principal with client credentials:

  use Office365\Runtime\Auth\ClientCredential;
  use Office365\SharePoint\ClientContext;

  $credentials = new ClientCredential("{clientId}", "{clientSecret}");
  $ctx = (new ClientContext("{siteUrl}"))->withCredentials($credentials);

Documentation:

2. app principal with client certificate:

  use Office365\Runtime\Auth\ClientCredential;
  use Office365\SharePoint\ClientContext;


$tenant = "{tenant}.onmicrosoft.com"; //tenant id or name
$privateKetPath = "-- path to private.key file--"
$privateKey = file_get_contents($privateKetPath);

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

Documentation:

3. user credentials auth:

  use Office365\Runtime\Auth\UserCredentials;
  use Office365\SharePoint\ClientContext;

  $credentials = new UserCredentials("{userName}", "{password}");
  $ctx = (new ClientContext("{siteUrl}"))->withCredentials($credentials);

4. NTLM auth (for SharePoint On-Premises):

   use Office365\Runtime\Auth\UserCredentials;
   use Office365\SharePoint\ClientContext;

   $credentials = new UserCredentials("{userName}", "{password}");
   $ctx = (new ClientContext("{siteUrl}"))->withNtlm($credentials);

Examples

The following examples demonstrates how to perform basic CRUD operations against SharePoint list item resources:

Example 1. How to read SharePoint list items:

use Office365\SharePoint\ClientContext;
use Office365\Runtime\Auth\ClientCredential;
use Office365\SharePoint\ListItem;

$credentials = new ClientCredential("{client-id}", "{client-secret}");
$client = (new ClientContext("https://{your-tenant-prefix}.sharepoint.com"))->withCredentials($credentials);

$web = $client->getWeb();
$list = $web->getLists()->getByTitle("{list-title}"); //init List resource
$items = $list->getItems();  //prepare a query to retrieve from the
$client->load($items);  //save a query to retrieve list items from the server
$client->executeQuery(); //submit query to SharePoint server
/** @var ListItem $item */
foreach($items as $item) {
    print "Task: {$item->getProperty('Title')}\r\n";
}

or via fluent API syntax:

use Office365\SharePoint\ClientContext;
use Office365\Runtime\Auth\ClientCredential;
use Office365\SharePoint\ListItem;

$credentials = new ClientCredential("{client-id}", "{client-secret}");
$client = (new ClientContext("https://{your-tenant-prefix}.sharepoint.com"))->withCredentials($credentials);

$items = $client->getWeb()
                ->getLists()
                ->getByTitle("{list-title}")
                ->getItems()
                ->get()
                ->executeQuery();
/** @var ListItem $item */
foreach($items as $item) {
    print "Task: {$item->getProperty('Title')}\r\n";
}

Example 2. How to create SharePoint list item:

use Office365\SharePoint\ClientContext;
use Office365\Runtime\Auth\ClientCredential;

$credentials = new ClientCredential("{client-id}", "{client-secret}");
$client = (new ClientContext("https://{your-tenant-prefix}.sharepoint.com"))->withCredentials($credentials);

$list = $client->getWeb()->getLists()->getByTitle("Tasks");
$itemProperties = array('Title' => 'Order Approval', 'Body' => 'Order approval task');
$item = $list->addItem($itemProperties);
$client->executeQuery();
print "Task {$item->getProperty('Title')} has been created.\r\n";

Example 3. How to delete a SharePoint list item:

use Office365\SharePoint\ClientContext;
use Office365\Runtime\Auth\ClientCredential;

$credentials = new ClientCredential("{client-id}", "{client-secret}");
$client = (new ClientContext("https://{your-tenant-prefix}.sharepoint.com"))->withCredentials($credentials);

$list = $client->getWeb()->getLists()->getByTitle("Tasks");
$listItem = $list->getItemById("{item-id-to-delete}");
$listItem->deleteObject();
$client->executeQuery();

Example 4. How to update SharePoint list item:

use Office365\SharePoint\ClientContext;
use Office365\Runtime\Auth\ClientCredential;

$credentials = new ClientCredential("{client-id}", "{client-secret}");
$client = (new ClientContext("https://{your-tenant-prefix}.sharepoint.com"))->withCredentials($credentials);

$list = $client->getWeb()->getLists()->getByTitle("Tasks");
$listItem = $list->getItemById("{item-id-to-update}");
$listItem->setProperty('PercentComplete',1);
$listItem->update();
$client->executeQuery();

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();

Working with Outlook API

Supported list of APIs:

The following example demonstrates how to send a message via Outlook Mail API:

 use Office365\GraphServiceClient;
 use Office365\Outlook\Message;
 use Office365\Outlook\ItemBody;
 use Office365\Outlook\BodyType;
 use Office365\Outlook\EmailAddress;
 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");
/** @var Message $message */
$message = $client->getMe()->getMessages()->createType();
$message->setSubject("Meet for lunch?");
$message->setBody(new ItemBody(BodyType::Text,"The new cafeteria is open."));
$message->setToRecipients([new EmailAddress(null,"[email protected]")]);
$client->getMe()->sendEmail($message,true)->executeQuery();

Working with OneDrive API

The following example demonstrates how retrieve My drive Url via OneDrive API:

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");
$drive = $client->getMe()->getDrive();
$client->load($drive);
$client->executeQuery();
print $drive->getWebUrl();

phpspo's People

Contributors

andreybolonin avatar blizzz avatar changingterry avatar ctcudd avatar cweiske avatar davidbrogli avatar drml avatar fr3nch13 avatar johnpc avatar la-costa avatar landrok avatar lbuchs avatar mahmudz avatar martijnboers avatar menegain-mathieu avatar mpastas avatar nkgokul avatar pockemul avatar prog-24 avatar rtech91 avatar rvitaliy avatar superdj avatar thijsvdanker avatar vgrem avatar vroomfondle avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

phpspo's Issues

datetime column filter [solved]

I'm trying to filter a sharepoint list rows based on a datetime column.
this piece of code doesn't filter entries newer than 2017-01-10T00:00:00Z

$ctx = $this->_ctx;
        $web = $ctx->getWeb();
        //listWebFields($web);
        $list = $web->getLists()->getByTitle($listTitle);


        $items = $list->getItems()
            ->filter("e6c3 gt '2017-01-10T00:00:00Z'")
            ->filter("by1e eq 'Approved'");
//            ->top(5);
        $ctx->load($items);
        $ctx->executeQuery();
        foreach ($items->getData() as $item) {
//            print "Task: '{$item->Title}'\r\n";

            echo "***********************  " . $item->getProperty('e6c3') . "  *****************************" . "\r\n";
            echo "Total Normal Time: " . $item->getProperty('z33p') . "\r\n";
            echo "Double Time: " . $item->getProperty('yums') . "\r\n";
            echo "One and a Half Time: " . $item->getProperty('o4e7') . "\r\n";
            echo "Status: " . $item->getProperty('by1e') . "\r\n";
//            var_dump($item->getProperties());
            echo "PM: " . $item->getProperty('Project_x0020_Manager') . "\r\n";
            echo "Resource : " . $item->getProperty('qzwc') . "\r\n";
        }

any advice on how to do this?
thanks in advance

Consuming "_api/contextinfo" fails due to issue "Http 411 - length required"

Hello Sir,
This is Ruban Joshva again.
When I try uploading files on my SP server(uses NTLM auth), I could not upload the file. When I tried debugging through library I found that, in the file ClientContext.php at line 173 the response is given as "Http 411 - length required" (library trying to consume _api/contextinfo here). But I see the content length is set to 0 in curl. When I try with one of the other site I am able to get the correct response(content length :0 here too), and able to upload files. When I tried it on REST Client with setting the content length 0, it gives the same response. Why this site is returning this response ? How do I solve this ? Or is there any work around how I can upload the file ?(I am getting issue only when uploading, other functions work fine). And this site(where I face issue) is a SP subsite using NTLM authentication. Thanks.

Updating an item won't work.

The function update in the class \Office365\PHP\Client\SharePoint\ListItem has no arguments. The example indicates it should have.

The update code is broken or the documentation is outdated.

How to add an attachment to a list item

Hello Vadim,

I'm integrating the phpSPO library in a WordPress plugin. This allows me to publish posts from WordPress to SPO. So far I'm able to create, update and delete posts in SPO. The step I'm struggling with is adding attachments (images and zip files) to the list items in SPO. Below my code, I guess I'm overlooking the obvious. Can you give me a push into the right direction?

Erik

function addPostAttachment(\Office365\PHP\Client\SharePoint\ListItem $item)
{
$attCreationInformation = new \Office365\PHP\Client\SharePoint\AttachmentCreationInformation();
$attCreationInformation->FileName = "foobar.png";
$attCreationInformation->ContentStream = file_get_contents("http://somewebsite/foobar.png");

$ctx = $item->getContext();
$item->getAttachmentFiles()->add($attCreationInformation);
$ctx->executeQuery();
}

Office365 access_token

Is it possible to get access_token from Office365 OAuth login to use Office365 API without forcing user to login every time to MS account? (for exapmle I have login(mail), password to office365 account and I wanna get my Calendar events via curl in cron script without any user interaction)?
R.

Is autoload config right?

I can't get this to work with composer autoload. Shouldn't the configuration be:

"autoload": {
"psr-4": {
"SharePoint\PHP\Client": ["src/", "src/auth", "src/utilities"]
}
}
?

Add item to Document Library

i have a document library as list. how can i to add new row to document library?

i tried this:

$web = $this->connect->getWeb();
$conn = $this->connect;
$list = $web->getLists()->getByTitle($list);
$itemProperties = $item;
$item = $list->addItem($itemProperties);
$conn->executeQuery();

but its fail, "use SPFileCollection.Add()".

Collection(Int 32) missing element

Hi,
I am having an issue with Collections, in detail when SharePoint returns a Collection(Int 32).
I'm trying to take from the website all the supported UI languages, which by documentation is returned as a Collection of Int 32 at the following endpoint: https://<website.link>/_api/Web/SupportedUILanguageIds

I noticed that there wasn't a method in this library to retrieve this kind of information, so I implemented a fairly simple one following the implementation of getRoleDefinitions and other methods available in the Web class.

The collection is declared as a "ClientObjectCollection", even if I'm not sure that is the right kind of object.

Here is the code (note I am passing the Web object to avoid modify the library directly):

public function getSupportedUILanguageIds(Web $web)
    {
        if(!$web->isPropertyAvailable('SupportedUILanguageIds')){
            $collection= new ClientObjectCollection($web->getContext(),new ResourcePathEntity($web->getContext(),$web->getResourcePath(),"SupportedUILanguageIds"));
            $web->setProperty("SupportedUILanguageIds", $collection);
        }
        return $web->getProperty("SupportedUILanguageIds");
    }

So, first question: is that the right object to use? If not, what is the right one?

The call seems to work fine, however due to a validation check in the ODataPayload class, specifically this function:

    /**
     * @param string $key
     * @return bool
     */
    protected function isMetadataProperty($key)
    {
        return $key == "__metadata";
    }

and due to PHP considering 0 equal to every string no matter what, and the return value parsed as an array with key as an integer starting with 0, I am always missing the first value.

Is that intended?
Or should be the function changed with the added condition && is_string($key)?

Thank you.

File Upload - Unable to set property

Hi,
I trying to upload file with properties. Here is my code,
function uploadFiles($localPath, \Office365\PHP\Client\SharePoint\SPList $targetList){
$ctx = $targetList->getContext();
$searchPrefix = $localPath . '.';
foreach(glob($searchPrefix) as $filename) {
$fileCreationInformation = new \Office365\PHP\Client\SharePoint\FileCreationInformation();
$fileCreationInformation->Content = file_get_contents($filename);
$fileCreationInformation->Url = basename($filename);
$uploadFile = $targetList->getRootFolder()->getFiles()->add($fileCreationInformation);
$uploadFile->setProperty('Title','It is a test');//setting the property
$ctx->executeQuery();
print "File {$uploadFile->getProperty('Name')} has been uploaded\r\n";
}
}
after running this code, I see only the file is uploded, but no property is set. What am I missing here ?

Code Sample for Creating Document Sets?

Hey,

Just wondering if there are any code samples available for creating a document set within a library? I have not been able to find anything online and PHP is definitely not a strong skill of mine.

Cheers

Get multiple value field

Hi,

I try to get the multiple selected values of a field called 'Docset'. Therfore I use the code below;

$items = $list->getItems()->select('Title,EncodedAbsUrl,Documentstatus,Docset/Title')->expand('Docset/Title')->filter("Docset eq 5 and Documentstatus ne 'Te verwijderen' and Documentstatus ne 'Vervallen'")->orderby('Title');  //apply filter query option
    $ctx->load($items);
    $ctx->executeQuery();
    foreach( $items->getData() as $item ) {
var_dump($item->Docset);
        print 'Task: <a href="'.$item->EncodedAbsUrl.'" target="_blank">'.$item->Title.' ('.$item->Documentstatus.')</a> '.$item->Docset->results[0]->Title<br />';
    }

The var dump in the code above returns NULL. Also the title of the Docset isn't displayed.

When I execute the url below, the Docset title is presented in the output.

https://bla.sharepoint.com/sites/bla/_api/Web/Lists/getByTitle('Documenten')/items?$select=Title,EncodedAbsUrl,Docset/Title&$expand=Docset/Title&$filter=Docset%20eq%205

I don't know what I'm doing wrong. Maybe you can help me guys.

Thanks.

Download files from subfolder

Hi, i am trying to download files inside a subfolder like "Documents/FolderA/file.xls" and i can find any example how to do it.

I am using your file_examples.php as a guide but when a change $targetLibraryTitle to Documents/FolderA the files cant find the folder (it exists, i cant access ir by web browser).

Any example or help?

can not get value of child items if using expand function

I had this code:
$list->getItems()
->select("BuyerName,BuyerTitle,BuyerAddress,BuyerMobile,TrackingCodeTitle,"
. "BuyerPostalCode,Amount,ServiceCode/ServiceCode,Advisor/Title,CourseCode/Title")
->expand("ServiceCode,Advisor,CourseCode")
->filter($filter)
->top(1);
But, I can not get $item->Advisor[0]->Title.
As I saw in your code JsonPayloadSerializer.php:
in convertToClientObject function had this line code:
else {
$propertyObject = $targetObject->getProperty($key);
....
It's alway null, so you can get their value.
Can you fix that?

GroupCollection getters wrong resourceUrl

Hey,

Somewhere in the code the resourceUrl for a getById and a getByName GroupCollection call get appended with a /group. Example:

Right call

https://company.sharepoint.com/_api/web/sitegroups/getbyid('21')

Current call

https://company.sharepoint.com/_api/web/sitegroups/getbyid('21')/group

Exception

Error: Cannot find resource for the request group.

I've been looking for the code responsible for this mistake but can't seem to find such an easy string concat.

Edit: After some digging I found that resourcePath in ClientObject is group which gets appended in getResourcePath.

Error after uploading to server

Hi Guys

After creating a working test on my Windows 10 development machine, connecting to a remote Office 365 SP environment and displaying the contents of a list

To finish the test I uploaded the complete file set to a different (development, Windows 2016) server.
On that server I get the message Error: Class 'Office365\PHP\Client\Runtime\Auth\AuthenticationContext' not found in ....

Both are windows machines running a WordPress site. The test code is in a plugin,

I tried running composer on the new environment, but that stated "nothing to update"

Am I missing something in the new environment?

Typo in ClientContext.php - Fatal error: required_once

on line 111 require_once('Utilities\Utility.php'); theres an invalid use of "" it should read require_once('Utilities/Utility.php'); => "/"
the typo produces the following error:

Fatal error: require_once(): Failed opening required 'Utilities\Utility.php' (include_path

updating to read as mentioned above: require_once('Utilities/Utility.php'); fixes the issue

Please use version branches

Hello.

Could you consider using version branches? This way I wont have to constantly change my code if composer updates this upstream and I can specify which version I want to develop with.

Handle OData Query operators ($expand, $filter) on getitems

[Great project, saves me from migrating my sites to Azure]

Note that the batch methods are capped at returning 100 items.

Are you planning on a syntax?

And for now, how can I add them myself; this gives me an error

public function getItems()
    {
        $filter='$top=10';
        return new ListItemCollection($this->getContext(),$this->getResourcePath(),"items".$filter);
    }

How to get folders into document library

I'm currently working on listing files and folders on a document library.
I can list all files into root folder with $list->getRootFolder()->getFiles();.
But when I use $list->getRootFolder()->getFolders(); it just return nothing :/

What am I doing wrong?
Thx!

Unable to upload the files to sharepoint lists

Hi ,
We have used your script to retrieve and update the share point folders and files . But we are unable to download and upload the files by using your class files.Please let me know how to use your script for upload and download the files.

The partner DNS used in the login request cannot be found.

Hi Sir,
When I try to login onto my SP server I get this issue "The partner DNS used in the login request cannot be found." In my site is using ADFS authentication. Does your library support ADFS authentication? I am using the same code as it is in the ConnectExample.php file. And also this is a custom SP site. I am able to run the same site URL from my browser but it is failing only on my PHP application using the library. What Should I do now? Thanks.

Failed to open autoload_real.php

Hi Vadim,

Thanks for posting this very useful project!

When I run the ConnectExample.php it is giving:

_"Warning: require_once(.:/phpSPO/phpSPO-master/vendor/composer/autoload_real.php): failed to open stream: No such file or directory in /Users/vsivasubram3/htdocs/phpSPO/phpSPO-master/vendor/autoload.php on line 5

Fatal error: require_once(): Failed opening required '.:/phpSPO/phpSPO-master/vendor/composer/autoload_real.php' (include_path='.:/usr/local/pear/share/pear') in /Users/vsivasubram3/htdocs/phpSPO/phpSPO-master/vendor/autoload.php on line 5"_

I have installed/updated mcrypt and composer successfully, so not sure what the issue is. Can you please guide me.

Thanks very much,
Vaidya.

Error reading list on Sharepoint on premise

Hi, I need to read listitem from a Sharepoint onpremise (not online), so I start from the example NtlmConnectExample.php and the authentication seems to work correctly.
When I try to read the items on the list I receive this error:
"Unknown Authentication Provider"

This is a snippet of my code:
try {
$authCtx = new NtlmAuthenticationContext($Settings['Url'], $Settings['UserName'], $Settings['Password']);
$authCtx->acquireTokenForUser($Settings['UserName'],$Settings['Password']);
$ctx = new ClientContext($Settings['Url'],$authCtx);
$listTitle = 'Tasks';
$list = ensureList($ctx,$listTitle);
//printTasks($list);
//queryListViaCAMLQuery($list);
generateTasks($list);
//$itemId = createTask($list);
//$item = getTask($list,$itemId);
//updateTask($item);
//deleteTask($item);
//queryListItems($list);
}
catch (Exception $e) {
echo 'Error: ', $e->getMessage(), "\n";
}

How can i solve? Thanks

Can't Add list items when using NTLM auth

Connection works
Reading list items works

Connecting to a SharePoint 2013 site.

When I attempt to add items I get these errors:

Warning: First parameter must either be an object or the name of an existing class in /vendor/vgrem/php-spo/src/Runtime/OData/JsonPayloadSerializer.php on line 52

Warning: First parameter must either be an object or the name of an existing class in /vendor/vgrem/php-spo/src/Runtime/OData/JsonPayloadSerializer.php on line 55

Notice: Trying to get property of non-object in /vendor/vgrem/php-spo/src/Runtime/OData/JsonPayloadSerializer.php on line 72

Warning: Invalid argument supplied for foreach() in /vendor/vgrem/php-spo/src/Runtime/ClientValueObject.php on line 39

Warning: First parameter must either be an object or the name of an existing class in /vendor/vgrem/php-spo/src/Runtime/OData/JsonPayloadSerializer.php on line 52

Warning: First parameter must either be an object or the name of an existing class in /vendor/vgrem/php-spo/src/Runtime/OData/JsonPayloadSerializer.php on line 55

Warning: Invalid argument supplied for foreach() in /vendor/vgrem/php-spo/src/Runtime/ClientObject.php on line 129

Code:

$authCtx = new NetworkCredentialContext($username, $password);
$authCtx->AuthType = CURLAUTH_NTLM; //NTML auth schema
$ctx = new ClientContext($url,$authCtx);
$list = $ctx->getWeb()->getLists()->getByTitle($listtitle);
$itemProperties = array('Title' => 'Tester','__metadata' => array('type' => 'SP.Data.TestListItem'));
$item = $list->addItem($itemProperties);
$ctx->executeQuery();

External Single Sign On for SPO

Hello,

we are using this Class to check SPO Credentials of our Clients and direct them to their "personal" SPO area.

Actually our Clients need to Sign in on our Website (authentification via SPO) and than we Redirect them to the "personal" SharePoint (for example Company.sharepoint.com/customer1). - On this Page they need to Login again (SharePoint Online Authentification itself).

We tried to redirect / pass the Login of our form into the Login.aspx of SPO. But this dont work.
We also tried to use an Iframe and Javascript - didnt work either.

Any ideas how to realise an external single sign on ?

Thank you!

Class not found

Hi,

I'm trying to use the very first example but I'm getting Class 'AuthenticationContext' not found despite I load the vendor/autoload.php:

require_once './vendor/autoload.php';
$Url="https://myorganisation.sharepoint.com";
$Username="username";
$Password="password";
$authCtx = new AuthenticationContext($Url);
...
Any idea about what I'm missing?

Installed through Composer.

Thx

EDIT: nevermind, wasn't using it correctly...

Connection failed: Invalid STS request

Hi vgrem,

I got this error:

"Connection failed: Invalid STS request"

The sharepoint I'm trying to connect to has a self-sign certificate. Do I have to do something extra?

Best regards!

ErrorException in ClientRequest.php line 45: Undefined index: headers

ErrorException in ClientRequest.php line 45:
Undefined index: headers

After running the following code.

\SharePoint\PHP\Client\File::openBinary($ctx, $item->ServerRelativeUrl);

The method openBinary misses the option headers ($options["headers"]) which seems to be required by executeQueryDirect. I solved it temporary by doing the following.

public function executeQueryDirect($options)
{
    if (!isset($options["headers"])) {
        $options["headers"] = [];
    }
    ...

Error using filter

Hello, i want to get data using filter() but i get some error
$nik = '5171041305650002';
$items = $list->getItems()->filter("NIK eq '$nik'");
$itemdata = $items; //prepare a query to retrieve from the
$ctx->load($items); //save a query to retrieve list items from the server
$ctx->executeQuery(); //submit query to SharePoint Online REST service

but i get error like this

Fatal error: Uncaught exception 'Exception' with message 'The operation tried prevented therefore exceeds the list view threshold imposed by the administrator.' in C:\AppServ\www\phpSPO\src\Runtime\ClientRequest.php:186
Stack trace:
#0 C:\AppServ\www\phpSPO\src\Runtime\ClientRequest.php(138): Office365\PHP\Client\Runtime\ClientRequest->validateResponse('{"error":{"code...')
#1 C:\AppServ\www\phpSPO\src\Runtime\ClientRuntimeContext.php(133): Office365\PHP\Client\Runtime\ClientRequest->executeQuery()
#2 C:\AppServ\www\phpSPO\src\SharePoint\ClientContext.php(83): Office365\PHP\Client\Runtime\ClientRuntimeContext->executeQuery()
#3 C:\AppServ\www\phpSPO\app\data_ktp.php(25): Office365\PHP\Client\SharePoint\ClientContext->executeQuery()
#4 {main}
thrown in C:\AppServ\www\phpSPO\src\Runtime\ClientRequest.php on line 186

adding a filter to query not returning result

wondering if you have used filters in any queries as when I add a filter, like below, there is no result.

`$query = '$select=ClientJobNumber,ID,ClientJobNumber,ClientPassword,ClientUserName,ClientUserName,ClientsFirstName,ClientsLastName';

$filter = '?$filter=ClientJobNumber eq '56654'';`

If I run only the query everything works fine. I have also tested the query with the filter using REST API tester and everything works great

How to Set ContentType Property while uploading file?

Hello Sir,
I am able to upload the file to my site and set the meta data, but I also want to set ContentType property, how do I do that ? I am trying the same setProperty(name, value); statement to set the value, I am passing the ContentType object in the value parameter but it gives me this error "A node of type 'StartArray' was read from the JSON reader when trying to read the contents of a resource reference navigation link:..." , What am I missing here ? Thanks.

Renaming folder name not working

Hi i am trying to rename folder by using your code below is my option header array and data json. please let me know what is wrong in my request ?

options :
Array
(
[list] => Create Folder
[data] => Array
(
[__metadata] => Array
(
[type] => SP.Folder
)

        [Name] => Documents/test2
        [ServerRelativeUrl] => Documents/test1
    )

[method] => POST
[xhttpmethod] => MERGE
[formdigest] => 0xC72DCCC62E851F4E382A76A2970AA85E370D1A430BCF0636F12E745BBA1DAD4DFDCBF1FD1710E735DC06E10304B4B9F2FB6F1457386A89879674DA1457EBF754,30 Sep 2014 13:16:49 -0000
[etag] => etag
[url] => https://intellobuild-my.sharepoint.com/personal/rchouhan_intellobuild_onmicrosoft_com/_api/web/GetFolderByServerRelativeUrl('Documents/test1')

)

headers :
Array
(
[0] => Accept: application/json; odata=verbose
[1] => Content-type: application/json; odata=verbose
[2] => Cookie: FedAuth=77u/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48U1A+RmFsc2UsMGguZnxtZW1iZXJzaGlwfDEwMDM3ZmZlOGJjNzcyNWFAbGl2ZS5jb20sMCMuZnxtZW1iZXJzaGlwfHJjaG91aGFuQGludGVsbG9idWlsZC5vbm1pY3Jvc29mdC5jb20sMTMwNTY5ODg2MDI4NDA1NDUzLEZhbHNlLE8xQnBhQ2tQdUlWbmdjajRXaWNBZkFmZDJLM2k0dnBwODA4WmNOVUhiREJzRGs2TW1tNm9BbmVSZmc1RWI0bXhtM1J1WXFFeXdqSmdIVVdpLzgxcDVtQlVyZm1nUlRuS201ODFEQlRtSVJIWldRU2ZCZm5qUEVPQkdRMU54MXBPOFU0cERYaVkvRG9qbnZTdGFwN1N2ZmI2MGI2L1hNRTdYU3VqU2RtVW1VU3Iyb3lXbkhwWEZrNUxqQ0FpdE5XS2hPSERhTTM5MDVhNnRhSWFybnF2OU1peFFOTlBiSXpld1dlRjd1UjI3QXp4UmRrNGZhNk4xNU5YRittOThJKzNFL0J0bUgwQk9aRnpCcWYwQk1kNVVJK2dvWnlPZzMrTXlGaGdOSkdoRVNPNTJ6SThkMStzdjdCRms3a29YVnFKS3ZHMzhRWVlCZklqUGM2QXFUQlIrUT09LGh0dHBzOi8vaW50ZWxsb2J1aWxkLW15LnNoYXJlcG9pbnQuY29tLzwvU1A+; rtFa=MbRZobUS3IsD5r/bzt141hdAWq9DbRhvLl1bN6cC7YAgaEfYq1DPFa+kVKJEoqa4cgyaRvjt/yG/oZ9u0e40sttjnlzlkvKeuwbeFr/kNt8BSMNky1YQ3leiyhXFRIj/LX2otpPlhTY1Ie8O9FzJ/N+RQaAG8mXNWnSCKYRbPiS4fNawUv+Zme5xbXesHQXi4/3Tihp35jhHU0LvN15ebldmPuzWVUrkjOsBn7knfjQ04U0u6oGjfbn1fvPT3A5/bQFInO1lOiIj8ZafqEB7cmb3uV+YJbAeUCnmRjorD96M6CY9SgWdbe5IIRqE03S6E05eeOzIIRkSD/HeE+qFCZiyPIGGdQ98SFzENBr0yzi4jR8snHWBpkNfkX92BU/iIAAAAA==
[3] => Content-length:100
[4] => If-Match: etag
[5] => X-RequestDigest: 0xC72DCCC62E851F4E382A76A2970AA85E370D1A430BCF0636F12E745BBA1DAD4DFDCBF1FD1710E735DC06E10304B4B9F2FB6F1457386A89879674DA1457EBF754,30 Sep 2014 13:16:49 -0000
[6] => X-Http-Method: MERGE
)

data:
{"__metadata":{"type":"SP.Folder"},"Name":"Documents/test2","ServerRelativeUrl":"Documents/test1"}

How to create a folder in a Document Library?

HI !

Im trying to create a Folder in my Document Library called Tfts.
I'm ussing this code
eiic and 2017 folders are already create. My goal is to create test folder.

	$authCtx = new AuthenticationContext($Settings['Url']);
	$authCtx->acquireTokenForUser($Settings['UserName'],$Settings['Password']);  
        $folderUrl = "Tfts/eiic/2017/test";

    $url = $Settings['Url'] . "/_api/web/folders";
    $request = new RequestOptions($url);
    $ctx = new ClientContext($url,$authCtx);
  
    $itemPayload = array( 
        '__metadata' => array ('type' => 'SP.Folder', 'ServerRelativeUrl' => $folderUrl)
        );

    $request->addCustomHeader("If-Match", "*");
    $request->Data = $itemPayload;
    $request->Method = 'POST';
    $data = $ctx->executeQueryDirect($request);
    var_dump($data);

I had the following error:

**Notice: Array to string conversion in C:\wamp64\www\phpSPO\src\Runtime\Utilities\Requests.php on line 111
Warning: strlen() expects parameter 1 to be string, array given in C:\wamp64\www\phpSPO\src\Runtime\Utilities\Requests.php on line 112**

the dump content:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Length Required</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Length Required</h2>
<hr><p>HTTP Error 411. The request must be chunked or have a content length.</p>
</BODY></HTML>

Thank u very much :) !

cannot install it via composer in command line or composer.json

I keep receiving the error that

[InvalidArgumentException] Could not find package vgrem/php-spo at any version for your minimum-stability (stable). Check the package spelling or your minimum-stability

...whenever I do composer require vgrem/php-spo I have tried it with --dev and still get the same problem.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.