<?php

/* graph.php Graph API class
 *
 * Katy Nicholson, last updated 01/09/2021
 *
 * https://github.com/CoasterKaty
 * https://katytech.blog/
 * https://twitter.com/coaster_katy
 *
 * Sample class to retrieve data through Graph API once logged in
 */


$MIOLO = MIOLO::getInstance();
$MIOLO->getClass('gnuteca3', 'azure/Oauth');

class Graph 
{
    private $Token;

    public function __construct($token) 
    {
        $this->Token = $token;
    }
    
    function getProfile() 
    {
        $profile = json_decode($this->sendGetRequest('https://graph.microsoft.com/v1.0/me/'));

        return $profile;
    }
    
    public function getPhoto()
    {
        //Photo is a bit different, we need to request the image data which will include content type, size etc, then request the image
        $photoType = json_decode($this->sendGetRequest('https://graph.microsoft.com/v1.0/me/photo/'));
        $photo = $this->sendGetRequest('https://graph.microsoft.com/v1.0/me/photo/%24value');
        
        if (isset($photoType->{'@odata.mediaContentType'})) 
        {
            return '<img src="data:' . $photoType->{'@odata.mediaContentType'} . ';base64,' . base64_encode($photo) . '" alt="User Photo" />';
        }
        
        return;
    }

    public function getUsers()
    {
        $usersReturn = [];
        $url = 'https://graph.microsoft.com/v1.0/users';

        do {
             $users = json_decode($this->sendGetRequest($url));
             $url = isset($users->{'@odata.nextLink'}) ? $users->{'@odata.nextLink'} : null;

             if ( isset($users->value) )
             {
                 $users = $users->value;
                 $usersReturn = array_merge($usersReturn, $users);
             }

        } while ($url);

        return count($usersReturn) > 0 ? $usersReturn : null;
    }

    public function getGroups($id)
    {
        $groups = json_decode($this->sendGetRequest("https://graph.microsoft.com/v1.0/users/{$id}/memberOf"));
        
        return $groups;
    }

    public function sendGetRequest($URL, $ContentType = 'application/json') 
    {
        $ch = curl_init($URL);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $this->Token, 'Content-Type: ' . $ContentType));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);

        curl_close($ch);
        return $response;
    }

}
?>
