1<?php
2/*
3 * Copyright (C) 2015       Frederic France      <frederic.france@free.fr>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
19/**
20 *      \file       htdocs/core/modules/oauth/google_oauthcallback.php
21 *      \ingroup    oauth
22 *      \brief      Page to get oauth callback
23 */
24
25require '../../../main.inc.php';
26require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
27use OAuth\Common\Storage\DoliStorage;
28use OAuth\Common\Consumer\Credentials;
29use OAuth\OAuth2\Service\Google;
30
31// Define $urlwithroot
32$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
33$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
34//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
35
36
37
38$action = GETPOST('action', 'aZ09');
39$backtourl = GETPOST('backtourl', 'alpha');
40
41
42/**
43 * Create a new instance of the URI class with the current URI, stripping the query string
44 */
45$uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
46//$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
47//$currentUri->setQuery('');
48$currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/google_oauthcallback.php');
49
50
51/**
52 * Load the credential for the service
53 */
54
55/** @var $serviceFactory \OAuth\ServiceFactory An OAuth service factory. */
56$serviceFactory = new \OAuth\ServiceFactory();
57$httpClient = new \OAuth\Common\Http\Client\CurlClient();
58// TODO Set options for proxy and timeout
59// $params=array('CURLXXX'=>value, ...)
60//$httpClient->setCurlParameters($params);
61$serviceFactory->setHttpClient($httpClient);
62
63// Dolibarr storage
64$storage = new DoliStorage($db, $conf);
65
66// Setup the credentials for the requests
67$credentials = new Credentials(
68	$conf->global->OAUTH_GOOGLE_ID,
69	$conf->global->OAUTH_GOOGLE_SECRET,
70	$currentUri->getAbsoluteUri()
71);
72
73$requestedpermissionsarray = array();
74if (GETPOST('state')) {
75	$requestedpermissionsarray = explode(',', GETPOST('state')); // Example: 'userinfo_email,userinfo_profile,cloud_print'. 'state' parameter is standard to store a hash value and can be used to retrieve some parameters back
76}
77if ($action != 'delete' && empty($requestedpermissionsarray)) {
78	print 'Error, parameter state is not defined';
79	exit;
80}
81//var_dump($requestedpermissionsarray);exit;
82
83// Instantiate the Api service using the credentials, http client and storage mechanism for the token
84// $requestedpermissionsarray contains list of scopes.
85// Conversion into URL is done by Reflection on constant with name SCOPE_scope_in_uppercase
86$apiService = $serviceFactory->createService('Google', $credentials, $storage, $requestedpermissionsarray);
87
88// access type needed to have oauth provider refreshing token
89// also note that a refresh token is sent only after a prompt
90$apiService->setAccessType('offline');
91
92$apiService->setApprouvalPrompt('force');
93
94$langs->load("oauth");
95
96
97/*
98 * Actions
99 */
100
101
102if ($action == 'delete') {
103	$storage->clearToken('Google');
104
105	setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
106
107	header('Location: '.$backtourl);
108	exit();
109}
110
111if (!empty($_GET['code'])) {     // We are coming from oauth provider page
112	dol_syslog("We are coming from the oauth provider page");
113	//llxHeader('',$langs->trans("OAuthSetup"));
114
115	//$linkback='<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
116	//print load_fiche_titre($langs->trans("OAuthSetup"),$linkback,'title_setup');
117
118	//print dol_get_fiche_head();
119	// retrieve the CSRF state parameter
120	$state = isset($_GET['state']) ? $_GET['state'] : null;
121	//print '<table>';
122
123	// This was a callback request from service, get the token
124	try {
125		//var_dump($_GET['code']);
126		//var_dump($state);
127		//var_dump($apiService);      // OAuth\OAuth2\Service\Google
128
129		$token = $apiService->requestAccessToken($_GET['code'], $state);
130
131		setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token
132
133		$backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
134		unset($_SESSION["backtourlsavedbeforeoauthjump"]);
135
136		header('Location: '.$backtourl);
137		exit();
138	} catch (Exception $e) {
139		print $e->getMessage();
140	}
141} else // If entry on page with no parameter, we arrive here
142{
143	$_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
144
145	// This may create record into oauth_state before the header redirect.
146	// Creation of record with state in this tables depend on the Provider used (see its constructor).
147	if (GETPOST('state')) {
148		$url = $apiService->getAuthorizationUri(array('state'=>GETPOST('state')));
149	} else {
150		$url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
151	}
152
153	// we go on oauth provider authorization page
154	header('Location: '.$url);
155	exit();
156}
157
158
159/*
160 * View
161 */
162
163// No view at all, just actions
164
165$db->close();
166