provider.class.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  1. <?php
  2. class PluginSinglesignonProvider extends CommonDBTM {
  3. // From CommonDBTM
  4. public $dohistory = true;
  5. static $rightname = 'config';
  6. /**
  7. * @var array
  8. */
  9. static $default = null;
  10. /**
  11. *
  12. * @var string
  13. */
  14. protected $_code = null;
  15. /**
  16. *
  17. * @var null|string
  18. */
  19. protected $_token = null;
  20. /**
  21. *
  22. * @var null|array
  23. */
  24. protected $_resource_owner = null;
  25. public static function canCreate() {
  26. return static::canUpdate();
  27. }
  28. public static function canDelete() {
  29. return static::canUpdate();
  30. }
  31. public static function canPurge() {
  32. return static::canUpdate();
  33. }
  34. public static function canView() {
  35. return static::canUpdate();
  36. }
  37. // Should return the localized name of the type
  38. static function getTypeName($nb = 0) {
  39. return __sso('Single Sign-on Provider');
  40. }
  41. /**
  42. * @see CommonGLPI::getMenuName()
  43. * */
  44. static function getMenuName() {
  45. return __sso('Single Sign-on');
  46. }
  47. function defineTabs($options = []) {
  48. $ong = [];
  49. $this->addDefaultFormTab($ong);
  50. $this->addStandardTab(__CLASS__, $ong, $options);
  51. $this->addStandardTab('Log', $ong, $options);
  52. return $ong;
  53. }
  54. function post_getEmpty() {
  55. $this->fields["type"] = 'generic';
  56. $this->fields["is_active"] = 1;
  57. }
  58. function showForm($ID, $options = []) {
  59. global $CFG_GLPI;
  60. $this->initForm($ID, $options);
  61. $this->showFormHeader($options);
  62. if (empty($this->fields["type"])) {
  63. $this->fields["type"] = 'generic';
  64. }
  65. echo "<tr class='tab_bg_1'>";
  66. echo "<td>" . __('Name') . "</td>";
  67. echo "<td>";
  68. Html::autocompletionTextField($this, "name");
  69. echo "</td>";
  70. echo "<td>" . __('Comments') . "</td>";
  71. echo "<td>";
  72. echo "<textarea name='comment' >" . $this->fields["comment"] . "</textarea>";
  73. echo "</td></tr>";
  74. $on_change = 'var _value = this.options[this.selectedIndex].value; $(".sso_url").toggle(_value == "generic");';
  75. echo "<tr class='tab_bg_1'>";
  76. echo "<td>" . __sso('SSO Type') . "</td><td>";
  77. self::dropdownType('type', ['value' => $this->fields["type"], 'on_change' => $on_change]);
  78. echo "<td>" . __('Active') . "</td>";
  79. echo "<td>";
  80. Dropdown::showYesNo("is_active", $this->fields["is_active"]);
  81. echo "</td></tr>\n";
  82. echo "<tr class='tab_bg_1'>";
  83. echo "<td>" . __sso('Client ID') . "</td>";
  84. echo "<td><input type='text' style='width:96%' name='client_id' value='" . $this->fields["client_id"] . "'></td>";
  85. echo "<td>" . __sso('Client Secret') . "</td>";
  86. echo "<td><input type='text' style='width:96%' name='client_secret' value='" . $this->fields["client_secret"] . "'></td>";
  87. echo "</tr>\n";
  88. echo "<tr class='tab_bg_1'>";
  89. echo "<td>" . __sso('Scope') . "</td>";
  90. echo "<td><input type='text' style='width:96%' name='scope' value='" . $this->fields["scope"] . "'></td>";
  91. echo "<td>" . __sso('Extra Options') . "</td>";
  92. echo "<td><input type='text' style='width:96%' name='extra_options' value='" . $this->fields["extra_options"] . "'></td>";
  93. echo "</tr>\n";
  94. $url_style = "";
  95. if ($this->fields["type"] != 'generic') {
  96. $url_style = 'style="display: none;"';
  97. }
  98. echo "<tr class='tab_bg_1 sso_url' $url_style>";
  99. echo "<td>" . __sso('Authorize URL') . "</td>";
  100. echo "<td colspan='3'><input type='text' style='width:96%' name='url_authorize' value='" . $this->fields["url_authorize"] . "'></td>";
  101. echo "</tr>\n";
  102. echo "<tr class='tab_bg_1 sso_url' $url_style>";
  103. echo "<td>" . __sso('Access Token URL') . "</td>";
  104. echo "<td colspan='3'><input type='text' style='width:96%' name='url_access_token' value='" . $this->fields["url_access_token"] . "'></td>";
  105. echo "</tr>\n";
  106. echo "<tr class='tab_bg_1 sso_url' $url_style>";
  107. echo "<td>" . __sso('Resource Owner Details URL') . "</td>";
  108. echo "<td colspan='3'><input type='text' style='width:96%' name='url_resource_owner_details' value='" . $this->fields["url_resource_owner_details"] . "'></td>";
  109. echo "</tr>\n";
  110. echo "<tr class='tab_bg_1'>";
  111. echo "<th colspan='4'>" . __('Personalization') . "</th>";
  112. echo "</tr>\n";
  113. echo "<tr class='tab_bg_1'>";
  114. echo "<td>" . __('Background color') . "</td>";
  115. echo "<td>";
  116. Html::showColorField(
  117. 'bgcolor',
  118. [
  119. 'value' => $this->fields['bgcolor'],
  120. ]
  121. );
  122. echo "&nbsp;";
  123. echo Html::getCheckbox([
  124. 'title' => __('Clear'),
  125. 'name' => '_blank_bgcolor',
  126. 'checked' => empty($this->fields['bgcolor']),
  127. ]);
  128. echo "&nbsp;" . __('Clear');
  129. echo "</td>";
  130. echo "<td>" . __('Color') . "</td>";
  131. echo "<td>";
  132. Html::showColorField(
  133. 'color',
  134. [
  135. 'value' => $this->fields['color'],
  136. ]
  137. );
  138. echo "&nbsp;";
  139. echo Html::getCheckbox([
  140. 'title' => __('Clear'),
  141. 'name' => '_blank_color',
  142. 'checked' => empty($this->fields['color']),
  143. ]);
  144. echo "&nbsp;" . __('Clear');
  145. echo "</td>";
  146. echo "</tr>\n";
  147. echo "<tr class='tab_bg_1'>";
  148. echo "<td>" . __('Picture') . "</td>";
  149. echo "<td colspan='3'>";
  150. if (!empty($this->fields['picture'])) {
  151. echo Html::image(static::getPictureUrl($this->fields['picture']), [
  152. 'style' => 'max-width: 100px; max-height: 50px;',
  153. 'class' => 'picture_square'
  154. ]);
  155. echo "&nbsp;";
  156. echo Html::getCheckbox([
  157. 'title' => __('Clear'),
  158. 'name' => '_blank_picture'
  159. ]);
  160. echo "&nbsp;" . __('Clear');
  161. } else {
  162. echo Html::file([
  163. 'name' => 'picture',
  164. 'onlyimages' => true,
  165. ]);
  166. }
  167. echo "</td>";
  168. echo "</tr>\n";
  169. echo '<script type="text/javascript">
  170. $("[name=bgcolor]").on("change", function (e) {
  171. $("[name=_blank_bgcolor]").prop("checked", false).attr("checked", false);
  172. });
  173. $("[name=color]").on("change", function (e) {
  174. $("[name=_blank_color]").prop("checked", false).attr("checked", false);
  175. });
  176. </script>';
  177. if ($ID) {
  178. echo "<tr class='tab_bg_1'>";
  179. echo "<th colspan='4'>" . __('Test') . "</th>";
  180. echo "</tr>\n";
  181. $url = self::getCallbackUrl($ID);
  182. $fullUrl = $this->getBaseURL() . $url;
  183. echo "<tr class='tab_bg_1'>";
  184. echo "<td>" . __sso('Callback URL') . "</td>";
  185. echo "<td colspan='3'><a id='singlesignon_callbackurl' href='$fullUrl' data-url='$url'>$fullUrl</a></td>";
  186. echo "</tr>\n";
  187. $options['addbuttons'] = ['test_singlesignon' => __sso('Test Single Sign-on')];
  188. }
  189. $this->showFormButtons($options);
  190. if ($ID) {
  191. echo '<script type="text/javascript">
  192. $("[name=test_singlesignon]").on("click", function (e) {
  193. e.preventDefault();
  194. var url = $("#singlesignon_callbackurl").attr("data-url") + "/test/1";
  195. var left = ($(window).width()/2)-(600/2);
  196. var top = ($(window).height()/2)-(800/2);
  197. var newWindow = window.open(url, "singlesignon", "width=600,height=800,left=" + left + ",top=" + top);
  198. if (window.focus) {
  199. newWindow.focus();
  200. }
  201. });
  202. </script>';
  203. }
  204. return true;
  205. }
  206. function prepareInputForAdd($input) {
  207. return $this->prepareInput($input);
  208. }
  209. function prepareInputForUpdate($input) {
  210. return $this->prepareInput($input);
  211. }
  212. function cleanDBonPurge() {
  213. static::deletePicture($this->fields['picture']);
  214. }
  215. /**
  216. * Prepares input (for update and add)
  217. *
  218. * @param array $input Input data
  219. *
  220. * @return array
  221. */
  222. private function prepareInput($input) {
  223. $error_detected = [];
  224. $type = '';
  225. //check for requirements
  226. if (isset($input['type'])) {
  227. $type = $input['type'];
  228. }
  229. if (!isset($input['name']) || empty($input['name'])) {
  230. $error_detected[] = __sso('A Name is required');
  231. }
  232. if (empty($type)) {
  233. $error_detected[] = __('An item type is required');
  234. } else if (!isset(static::getTypes()[$type])) {
  235. $error_detected[] = sprintf(__sso('The "%s" is a Invalid type'), $type);
  236. }
  237. if (!isset($input['client_id']) || empty($input['client_id'])) {
  238. $error_detected[] = __sso('A Client ID is required');
  239. }
  240. if (!isset($input['client_secret']) || empty($input['client_secret'])) {
  241. $error_detected[] = __sso('A Client Secret is required');
  242. }
  243. if ($type === 'generic') {
  244. if (!isset($input['url_authorize']) || empty($input['url_authorize'])) {
  245. $error_detected[] = __sso('An Authorize URL is required');
  246. } else if (!filter_var($input['url_authorize'], FILTER_VALIDATE_URL)) {
  247. $error_detected[] = __sso('The Authorize URL is invalid');
  248. }
  249. if (!isset($input['url_access_token']) || empty($input['url_access_token'])) {
  250. $error_detected[] = __sso('An Access Token URL is required');
  251. } else if (!filter_var($input['url_access_token'], FILTER_VALIDATE_URL)) {
  252. $error_detected[] = __sso('The Access Token URL is invalid');
  253. }
  254. if (!isset($input['url_resource_owner_details']) || empty($input['url_resource_owner_details'])) {
  255. $error_detected[] = __sso('A Resource Owner Details URL is required');
  256. } else if (!filter_var($input['url_resource_owner_details'], FILTER_VALIDATE_URL)) {
  257. $error_detected[] = __sso('The Resource Owner Details URL is invalid');
  258. }
  259. }
  260. if (count($error_detected)) {
  261. foreach ($error_detected as $error) {
  262. Session::addMessageAfterRedirect(
  263. $error,
  264. true,
  265. ERROR
  266. );
  267. }
  268. return false;
  269. }
  270. if (isset($input["_blank_bgcolor"])
  271. && $input["_blank_bgcolor"]
  272. ) {
  273. $input['bgcolor'] = '';
  274. }
  275. if (isset($input["_blank_color"])
  276. && $input["_blank_color"]
  277. ) {
  278. $input['color'] = '';
  279. }
  280. if (isset($input["_blank_picture"])
  281. && $input["_blank_picture"]
  282. ) {
  283. $input['picture'] = '';
  284. if (array_key_exists('picture', $this->fields)) {
  285. static::deletePicture($this->fields['picture']);
  286. }
  287. }
  288. if (isset($input["_picture"])) {
  289. $picture = array_shift($input["_picture"]);
  290. if ($dest = static::savePicture(GLPI_TMP_DIR . '/' . $picture)) {
  291. $input['picture'] = $dest;
  292. } else {
  293. Session::addMessageAfterRedirect(__('Unable to save picture file.'), true, ERROR);
  294. }
  295. if (array_key_exists('picture', $this->fields)) {
  296. static::deletePicture($this->fields['picture']);
  297. }
  298. }
  299. return $input;
  300. }
  301. function getSearchOptions() {
  302. // For GLPI <= 9.2
  303. $options = [];
  304. foreach ($this->rawSearchOptions() as $opt) {
  305. if (!isset($opt['id'])) {
  306. continue;
  307. }
  308. $optid = $opt['id'];
  309. unset($opt['id']);
  310. if (isset($options[$optid])) {
  311. $message = "Duplicate key $optid ({$options[$optid]['name']}/{$opt['name']}) in " .
  312. get_class($this) . " searchOptions!";
  313. Toolbox::logDebug($message);
  314. }
  315. foreach ($opt as $k => $v) {
  316. $options[$optid][$k] = $v;
  317. }
  318. }
  319. return $options;
  320. }
  321. function rawSearchOptions() {
  322. $tab = [];
  323. $tab[] = [
  324. 'id' => 'common',
  325. 'name' => __('Characteristics'),
  326. ];
  327. $tab[] = [
  328. 'id' => 1,
  329. 'table' => $this->getTable(),
  330. 'field' => 'name',
  331. 'name' => __('Name'),
  332. 'datatype' => 'itemlink',
  333. ];
  334. $tab[] = [
  335. 'id' => 2,
  336. 'table' => $this->getTable(),
  337. 'field' => 'type',
  338. 'name' => __('Type'),
  339. 'searchtype' => 'equals',
  340. 'datatype' => 'specific',
  341. ];
  342. $tab[] = [
  343. 'id' => 3,
  344. 'table' => $this->getTable(),
  345. 'field' => 'client_id',
  346. 'name' => __sso('Client ID'),
  347. 'datatype' => 'text',
  348. ];
  349. $tab[] = [
  350. 'id' => 4,
  351. 'table' => $this->getTable(),
  352. 'field' => 'client_secret',
  353. 'name' => __sso('Client Secret'),
  354. 'datatype' => 'text',
  355. ];
  356. $tab[] = [
  357. 'id' => 5,
  358. 'table' => $this->getTable(),
  359. 'field' => 'scope',
  360. 'name' => __sso('Scope'),
  361. 'datatype' => 'text',
  362. ];
  363. $tab[] = [
  364. 'id' => 6,
  365. 'table' => $this->getTable(),
  366. 'field' => 'extra_options',
  367. 'name' => __sso('Extra Options'),
  368. 'datatype' => 'specific',
  369. ];
  370. $tab[] = [
  371. 'id' => 7,
  372. 'table' => $this->getTable(),
  373. 'field' => 'url_authorize',
  374. 'name' => __sso('Authorize URL'),
  375. 'datatype' => 'weblink',
  376. ];
  377. $tab[] = [
  378. 'id' => 8,
  379. 'table' => $this->getTable(),
  380. 'field' => 'url_access_token',
  381. 'name' => __sso('Access Token URL'),
  382. 'datatype' => 'weblink',
  383. ];
  384. $tab[] = [
  385. 'id' => 9,
  386. 'table' => $this->getTable(),
  387. 'field' => 'url_resource_owner_details',
  388. 'name' => __sso('Resource Owner Details URL'),
  389. 'datatype' => 'weblink',
  390. ];
  391. $tab[] = [
  392. 'id' => 10,
  393. 'table' => $this->getTable(),
  394. 'field' => 'is_active',
  395. 'name' => __('Active'),
  396. 'searchtype' => 'equals',
  397. 'datatype' => 'bool',
  398. ];
  399. $tab[] = [
  400. 'id' => 30,
  401. 'table' => $this->getTable(),
  402. 'field' => 'id',
  403. 'name' => __('ID'),
  404. 'datatype' => 'itemlink',
  405. ];
  406. return $tab;
  407. }
  408. static function getSpecificValueToDisplay($field, $values, array $options = []) {
  409. if (!is_array($values)) {
  410. $values = [$field => $values];
  411. }
  412. switch ($field) {
  413. case 'type':
  414. return self::getTicketTypeName($values[$field]);
  415. case 'extra_options':
  416. return '<pre>' . $values[$field] . '</pre>';
  417. }
  418. return '';
  419. }
  420. static function getSpecificValueToSelect($field, $name = '', $values = '', array $options = []) {
  421. if (!is_array($values)) {
  422. $values = [$field => $values];
  423. }
  424. $options['display'] = false;
  425. switch ($field) {
  426. case 'type':
  427. $options['value'] = $values[$field];
  428. return self::dropdownType($name, $options);
  429. }
  430. return parent::getSpecificValueToSelect($field, $name, $values, $options);
  431. }
  432. /**
  433. * Get ticket types
  434. *
  435. * @return array of types
  436. * */
  437. static function getTypes() {
  438. $options['generic'] = __sso('Generic');
  439. $options['facebook'] = __sso('Facebook');
  440. $options['github'] = __sso('GitHub');
  441. $options['google'] = __sso('Google');
  442. $options['instagram'] = __sso('Instagram');
  443. $options['linkedin'] = __sso('LinkdeIn');
  444. return $options;
  445. }
  446. /**
  447. * Get ticket type Name
  448. *
  449. * @param $value type ID
  450. * */
  451. static function getTicketTypeName($value) {
  452. $tab = static::getTypes();
  453. // Return $value if not defined
  454. return (isset($tab[$value]) ? $tab[$value] : $value);
  455. }
  456. /**
  457. * Dropdown of ticket type
  458. *
  459. * @param $name select name
  460. * @param $options array of options:
  461. * - value : integer / preselected value (default 0)
  462. * - toadd : array / array of specific values to add at the begining
  463. * - on_change : string / value to transmit to "onChange"
  464. * - display : boolean / display or get string (default true)
  465. *
  466. * @return string id of the select
  467. * */
  468. static function dropdownType($name, $options = []) {
  469. $params['value'] = 0;
  470. $params['toadd'] = [];
  471. $params['on_change'] = '';
  472. $params['display'] = true;
  473. if (is_array($options) && count($options)) {
  474. foreach ($options as $key => $val) {
  475. $params[$key] = $val;
  476. }
  477. }
  478. $items = [];
  479. if (count($params['toadd']) > 0) {
  480. $items = $params['toadd'];
  481. }
  482. $items += self::getTypes();
  483. return Dropdown::showFromArray($name, $items, $params);
  484. }
  485. /**
  486. * Get an history entry message
  487. *
  488. * @param $data Array from glpi_logs table
  489. *
  490. * @since GLPI version 0.84
  491. *
  492. * @return string
  493. * */
  494. static function getHistoryEntry($data) {
  495. switch ($data['linked_action'] - Log::HISTORY_PLUGIN) {
  496. case 0:
  497. return __('History from plugin example', 'example');
  498. }
  499. return '';
  500. }
  501. //////////////////////////////
  502. ////// SPECIFIC MODIF MASSIVE FUNCTIONS ///////
  503. /**
  504. * @since version 0.85
  505. *
  506. * @see CommonDBTM::getSpecificMassiveActions()
  507. * */
  508. function getSpecificMassiveActions($checkitem = null) {
  509. $actions = parent::getSpecificMassiveActions($checkitem);
  510. $actions['Document_Item' . MassiveAction::CLASS_ACTION_SEPARATOR . 'add'] = _x('button', 'Add a document'); // GLPI core one
  511. $actions[__CLASS__ . MassiveAction::CLASS_ACTION_SEPARATOR . 'do_nothing'] = __('Do Nothing - just for fun', 'example'); // Specific one
  512. return $actions;
  513. }
  514. /**
  515. * @since version 0.85
  516. *
  517. * @see CommonDBTM::showMassiveActionsSubForm()
  518. * */
  519. static function showMassiveActionsSubForm(MassiveAction $ma) {
  520. switch ($ma->getAction()) {
  521. case 'DoIt':
  522. echo "&nbsp;<input type='hidden' name='toto' value='1'>" .
  523. Html::submit(_x('button', 'Post'), ['name' => 'massiveaction']) .
  524. " " . __('Write in item history', 'example');
  525. return true;
  526. case 'do_nothing':
  527. echo "&nbsp;" . Html::submit(_x('button', 'Post'), ['name' => 'massiveaction']) .
  528. " " . __('but do nothing :)', 'example');
  529. return true;
  530. }
  531. return parent::showMassiveActionsSubForm($ma);
  532. }
  533. /**
  534. * @since version 0.85
  535. *
  536. * @see CommonDBTM::processMassiveActionsForOneItemtype()
  537. * */
  538. static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item, array $ids) {
  539. global $DB;
  540. switch ($ma->getAction()) {
  541. case 'DoIt':
  542. if ($item->getType() == 'Computer') {
  543. Session::addMessageAfterRedirect(__("Right it is the type I want...", 'example'));
  544. Session::addMessageAfterRedirect(__('Write in item history', 'example'));
  545. $changes = [0, 'old value', 'new value'];
  546. foreach ($ids as $id) {
  547. if ($item->getFromDB($id)) {
  548. Session::addMessageAfterRedirect("- " . $item->getField("name"));
  549. Log::history($id, 'Computer', $changes, 'PluginExampleExample', Log::HISTORY_PLUGIN);
  550. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
  551. } else {
  552. // Example of ko count
  553. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
  554. }
  555. }
  556. } else {
  557. // When nothing is possible ...
  558. $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);
  559. }
  560. return;
  561. case 'do_nothing':
  562. if ($item->getType() == 'PluginExampleExample') {
  563. Session::addMessageAfterRedirect(__("Right it is the type I want...", 'example'));
  564. Session::addMessageAfterRedirect(__("But... I say I will do nothing for:", 'example'));
  565. foreach ($ids as $id) {
  566. if ($item->getFromDB($id)) {
  567. Session::addMessageAfterRedirect("- " . $item->getField("name"));
  568. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
  569. } else {
  570. // Example for noright / Maybe do it with can function is better
  571. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
  572. }
  573. }
  574. } else {
  575. $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);
  576. }
  577. return;
  578. }
  579. parent::processMassiveActionsForOneItemtype($ma, $item, $ids);
  580. }
  581. static function getIcon() {
  582. return "fas fa-user-lock";
  583. }
  584. public static function getDefault($type, $key, $default = null) {
  585. if (static::$default === null) {
  586. $content = file_get_contents(dirname(__FILE__) . '/../providers.json');
  587. static::$default = json_decode($content, true);
  588. }
  589. if (isset(static::$default[$type]) && static::$default[$type][$key]) {
  590. return static::$default[$type][$key];
  591. }
  592. return $default;
  593. }
  594. public function getClientType() {
  595. $value = "generic";
  596. if (isset($this->fields['type']) && !empty($this->fields['type'])) {
  597. $value = $this->fields['type'];
  598. }
  599. return $value;
  600. }
  601. public function getClientId() {
  602. $value = "";
  603. if (isset($this->fields['client_id']) && !empty($this->fields['client_id'])) {
  604. $value = $this->fields['client_id'];
  605. }
  606. return $value;
  607. }
  608. public function getClientSecret() {
  609. $value = "";
  610. if (isset($this->fields['client_secret']) && !empty($this->fields['client_secret'])) {
  611. $value = $this->fields['client_secret'];
  612. }
  613. return $value;
  614. }
  615. public function getScope() {
  616. $type = $this->getClientType();
  617. $value = static::getDefault($type, "scope");
  618. $fields = $this->fields;
  619. if (!isset($fields['scope']) || empty($fields['scope'])) {
  620. $fields['scope'] = $value;
  621. }
  622. $fields = Plugin::doHookFunction("sso:scope", $fields);
  623. return $fields['scope'];
  624. }
  625. public function getAuthorizeUrl() {
  626. $type = $this->getClientType();
  627. $value = static::getDefault($type, "url_authorize");
  628. $fields = $this->fields;
  629. if (!isset($fields['url_authorize']) || empty($fields['url_authorize'])) {
  630. $fields['url_authorize'] = $value;
  631. }
  632. $fields = Plugin::doHookFunction("sso:url_authorize", $fields);
  633. return $fields['url_authorize'];
  634. }
  635. public function getAccessTokenUrl() {
  636. $type = $this->getClientType();
  637. $value = static::getDefault($type, "url_access_token");
  638. $fields = $this->fields;
  639. if (!isset($fields['url_access_token']) || empty($fields['url_access_token'])) {
  640. $fields['url_access_token'] = $value;
  641. }
  642. $fields = Plugin::doHookFunction("sso:url_access_token", $fields);
  643. return $fields['url_access_token'];
  644. }
  645. public function getResourceOwnerDetailsUrl($access_token) {
  646. $type = $this->getClientType();
  647. $value = static::getDefault($type, "url_resource_owner_details", "");
  648. $fields = $this->fields;
  649. $fields['access_token'] = $access_token;
  650. if (!isset($fields['url_resource_owner_details']) || empty($fields['url_resource_owner_details'])) {
  651. $fields['url_resource_owner_details'] = $value;
  652. }
  653. $fields = Plugin::doHookFunction("sso:url_resource_owner_details", $fields);
  654. $url = $fields['url_resource_owner_details'];
  655. $url = str_replace("<access_token>", $access_token, $url);
  656. $url = str_replace("<appsecret_proof>", hash_hmac('sha256', $access_token, $this->getClientSecret()), $url);
  657. return $url;
  658. }
  659. /**
  660. * Get current URL without query string
  661. * @return string
  662. */
  663. private function getBaseURL() {
  664. $baseURL = "";
  665. if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
  666. $baseURL = ($_SERVER["HTTP_X_FORWARDED_PROTO"] == "https") ? "https://" : "http://";
  667. } else if (isset($_SERVER["HTTPS"])) {
  668. $baseURL = ($_SERVER["HTTPS"] == "on") ? "https://" : "http://";
  669. } else {
  670. $baseURL = "http://";
  671. }
  672. if (isset($_SERVER["HTTP_X_FORWARDED_HOST"])) {
  673. $baseURL .= $_SERVER["HTTP_X_FORWARDED_HOST"];
  674. } else if (isset($_SERVER["HTTP_X_FORWARDED_HOST"])) {
  675. $baseURL .= $_SERVER["HTTP_X_FORWARDED_HOST"];
  676. } else {
  677. $baseURL .= $_SERVER["SERVER_NAME"];
  678. }
  679. $port = $_SERVER["SERVER_PORT"];
  680. if (isset($_SERVER["HTTP_X_FORWARDED_PORT"])) {
  681. $port = $_SERVER["HTTP_X_FORWARDED_PORT"];
  682. }
  683. if ($port != "80" && $port != "443") {
  684. $baseURL .= ":" . $_SERVER["SERVER_PORT"];
  685. }
  686. return $baseURL;
  687. }
  688. /**
  689. * Get current URL without query string
  690. * @return string
  691. */
  692. private function getCurrentURL() {
  693. $currentURL = $this->getBaseURL();
  694. // $currentURL .= $_SERVER["REQUEST_URI"];
  695. // Ignore Query String
  696. if (isset($_SERVER["SCRIPT_NAME"])) {
  697. $currentURL .= $_SERVER["SCRIPT_NAME"];
  698. }
  699. if (isset($_SERVER["PATH_INFO"])) {
  700. $currentURL .= $_SERVER["PATH_INFO"];
  701. }
  702. return $currentURL;
  703. }
  704. /**
  705. *
  706. * @return boolean|string
  707. */
  708. public function checkAuthorization() {
  709. if (isset($_GET['error'])) {
  710. $error_description = isset($_GET['error_description']) ? $_GET['error_description'] : __("The action you have requested is not allowed.");
  711. Html::displayErrorAndDie(__($error_description), true);
  712. }
  713. if (!isset($_GET['code'])) {
  714. $params = [
  715. 'client_id' => $this->getClientId(),
  716. 'scope' => $this->getScope(),
  717. 'state' => Session::getNewCSRFToken(),
  718. 'response_type' => 'code',
  719. 'approval_prompt' => 'auto',
  720. 'redirect_uri' => $this->getCurrentURL(),
  721. ];
  722. $params = Plugin::doHookFunction("sso:authorize_params", $params);
  723. $url = $this->getAuthorizeUrl();
  724. $glue = strstr($url, '?') === false ? '?' : '&';
  725. $url .= $glue . http_build_query($params);
  726. header('Location: ' . $url);
  727. exit;
  728. }
  729. // Check given state against previously stored one to mitigate CSRF attack
  730. $state = isset($_GET['state']) ? $_GET['state'] : '';
  731. Session::checkCSRF([
  732. '_glpi_csrf_token' => $state,
  733. ]);
  734. $this->_code = $_GET['code'];
  735. return $_GET['code'];
  736. }
  737. /**
  738. *
  739. * @return boolean|string
  740. */
  741. public function getAccessToken() {
  742. if ($this->_token !== null) {
  743. return $this->_token;
  744. }
  745. if ($this->_code === null) {
  746. return false;
  747. }
  748. $params = [
  749. 'client_id' => $this->getClientId(),
  750. 'client_secret' => $this->getClientSecret(),
  751. 'redirect_uri' => $this->getCurrentURL(),
  752. 'grant_type' => 'authorization_code',
  753. 'code' => $this->_code,
  754. ];
  755. $params = Plugin::doHookFunction("sso:access_token_params", $params);
  756. $url = $this->getAccessTokenUrl();
  757. $content = Toolbox::callCurl($url, [
  758. CURLOPT_HTTPHEADER => [
  759. "Accept: application/json",
  760. ],
  761. CURLOPT_POST => true,
  762. CURLOPT_POSTFIELDS => http_build_query($params),
  763. CURLOPT_SSL_VERIFYHOST => false,
  764. CURLOPT_SSL_VERIFYPEER => false,
  765. ]);
  766. try {
  767. $data = json_decode($content, true);
  768. if (!isset($data['access_token'])) {
  769. return false;
  770. }
  771. $this->_token = $data['access_token'];
  772. } catch (\Exception $ex) {
  773. return false;
  774. }
  775. return $this->_token;
  776. }
  777. /**
  778. *
  779. * @return boolean|array
  780. */
  781. public function getResourceOwner() {
  782. if ($this->_resource_owner !== null) {
  783. return $this->_resource_owner;
  784. }
  785. $token = $this->getAccessToken();
  786. if (!$token) {
  787. return false;
  788. }
  789. $url = $this->getResourceOwnerDetailsUrl($token);
  790. $headers = [
  791. "Accept:application/json",
  792. "Authorization:Bearer $token",
  793. ];
  794. $headers = Plugin::doHookFunction("sso:resource_owner_header", $headers);
  795. $content = Toolbox::callCurl($url, [
  796. CURLOPT_HTTPHEADER => $headers,
  797. CURLOPT_SSL_VERIFYHOST => false,
  798. CURLOPT_SSL_VERIFYPEER => false,
  799. ]);
  800. try {
  801. $data = json_decode($content, true);
  802. $this->_resource_owner = $data;
  803. } catch (\Exception $ex) {
  804. return false;
  805. }
  806. if ($this->getClientType() === "linkedin") {
  807. $email_url = "https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))";
  808. $content = Toolbox::callCurl($email_url, [
  809. CURLOPT_HTTPHEADER => $headers,
  810. CURLOPT_SSL_VERIFYHOST => false,
  811. CURLOPT_SSL_VERIFYPEER => false,
  812. ]);
  813. try {
  814. $data = json_decode($content, true);
  815. $this->_resource_owner['email-address'] = $data['elements'][0]['handle~']['emailAddress'];
  816. } catch (\Exception $ex) {
  817. return false;
  818. }
  819. }
  820. return $this->_resource_owner;
  821. }
  822. public function findUser() {
  823. $resource_array = $this->getResourceOwner();
  824. if (!$resource_array) {
  825. return false;
  826. }
  827. $user = new User();
  828. //First: check linked user
  829. $id = Plugin::doHookFunction("sso:find_user", $resource_array);
  830. if (is_numeric($id) && $user->getFromDB($id)) {
  831. return $user;
  832. }
  833. $email = false;
  834. $email_fields = ['email', 'e-mail', 'email-address', 'mail'];
  835. foreach ($email_fields as $field) {
  836. if (isset($resource_array[$field]) && is_string($resource_array[$field])) {
  837. $email = $resource_array[$field];
  838. break;
  839. }
  840. }
  841. $default_condition = '';
  842. if (version_compare(GLPI_VERSION, '9.3', '>=')) {
  843. $default_condition = [];
  844. }
  845. if ($email && $user->getFromDBbyEmail($email, $default_condition)) {
  846. return $user;
  847. }
  848. $login = false;
  849. $login_fields = ['login', 'username', 'id'];
  850. foreach ($login_fields as $field) {
  851. if (isset($resource_array[$field]) && is_string($resource_array[$field])) {
  852. $login = $resource_array[$field];
  853. break;
  854. }
  855. }
  856. if ($login && $user->getFromDBbyName($login)) {
  857. return $user;
  858. }
  859. return false;
  860. }
  861. public function login() {
  862. $user = $this->findUser();
  863. if (!$user) {
  864. return false;
  865. }
  866. //Create fake auth
  867. $auth = new Auth();
  868. $auth->user = $user;
  869. $auth->auth_succeded = true;
  870. $auth->extauth = 1;
  871. $auth->user_present = $auth->user->getFromDBbyName(addslashes($user->fields['name']));
  872. $auth->user->fields['authtype'] = Auth::DB_GLPI;
  873. Session::init($auth);
  874. return $auth->auth_succeded;
  875. }
  876. /**
  877. * Generate a URL to callback
  878. * Some providers don't accept query string, it convert to PATH
  879. * @global array $CFG_GLPI
  880. * @param integer $id
  881. * @param array $query
  882. * @return string
  883. */
  884. public static function getCallbackUrl($id, $query = []) {
  885. global $CFG_GLPI;
  886. $url = $CFG_GLPI['root_doc'] . '/plugins/singlesignon/front/callback.php';
  887. $url .= "/provider/$id";
  888. if (!empty($query)) {
  889. $url .= "/q/" . base64_encode(http_build_query($query));
  890. }
  891. return $url;
  892. }
  893. public static function getCallbackParameters($name = null) {
  894. $data = [];
  895. if (isset($_SERVER['PATH_INFO'])) {
  896. $path_info = trim($_SERVER['PATH_INFO'], '/');
  897. $parts = explode('/', $path_info);
  898. $key = null;
  899. foreach ($parts as $part) {
  900. if ($key === null) {
  901. $key = $part;
  902. } else {
  903. if ($key === "provider" || $key === "test") {
  904. $part = intval($part);
  905. } else {
  906. $tmp = base64_decode($part);
  907. parse_str($tmp, $part);
  908. }
  909. if ($key === $name) {
  910. return $part;
  911. }
  912. $data[$key] = $part;
  913. $key = null;
  914. }
  915. }
  916. }
  917. if (!isset($data[$name])) {
  918. return null;
  919. }
  920. return $data;
  921. }
  922. static public function startsWith($haystack, $needle) {
  923. $length = strlen($needle);
  924. return (substr($haystack, 0, $length) === $needle);
  925. }
  926. static function getPictureUrl($path) {
  927. global $CFG_GLPI;
  928. $path = Html::cleanInputText($path); // prevent xss
  929. if (empty($path)) {
  930. return null;
  931. }
  932. return $CFG_GLPI['root_doc'] . '/plugins/singlesignon/front/picture.send.php?path=' . $path;
  933. }
  934. static public function savePicture($src, $uniq_prefix = null) {
  935. if (function_exists('Document::isImage') && !Document::isImage($src)) {
  936. return false;
  937. }
  938. $filename = uniqid($uniq_prefix);
  939. $ext = pathinfo($src, PATHINFO_EXTENSION);
  940. $subdirectory = substr($filename, -2); // subdirectory based on last 2 hex digit
  941. $basePath = GLPI_PLUGIN_DOC_DIR . "/singlesignon";
  942. $i = 0;
  943. do {
  944. // Iterate on possible suffix while dest exists.
  945. // This case will almost never exists as dest is based on an unique id.
  946. $dest = $basePath
  947. . '/' . $subdirectory
  948. . '/' . $filename . ($i > 0 ? '_' . $i : '') . '.' . $ext;
  949. $i++;
  950. } while (file_exists($dest));
  951. if (!is_dir($basePath . '/' . $subdirectory) && !mkdir($basePath . '/' . $subdirectory)) {
  952. return false;
  953. }
  954. if (!rename($src, $dest)) {
  955. return false;
  956. }
  957. return substr($dest, strlen($basePath . '/')); // Return dest relative to GLPI_PICTURE_DIR
  958. }
  959. public static function deletePicture($path) {
  960. $basePath = GLPI_PLUGIN_DOC_DIR . "/singlesignon";
  961. $fullpath = $basePath . '/' . $path;
  962. if (!file_exists($fullpath)) {
  963. return false;
  964. }
  965. $fullpath = realpath($fullpath);
  966. if (!static::startsWith($fullpath, realpath($basePath))) {
  967. return false;
  968. }
  969. return @unlink($fullpath);
  970. }
  971. public static function renderButton($url, $data, $class = 'oauth-login') {
  972. $btn = '<span><a href="' . $url . '" class="singlesignon vsubmit ' . $class . '"';
  973. $style = '';
  974. if ((isset($data['bgcolor']) && $data['bgcolor'])) {
  975. $style .= 'background-color: ' . $data['bgcolor'] . ';';
  976. }
  977. if ((isset($data['color']) && $data['color'])) {
  978. $style .= 'color: ' . $data['color'] . ';';
  979. }
  980. if ($style) {
  981. $btn .= ' style="' . $style . '"';
  982. }
  983. $btn .= '>';
  984. if (isset($data['picture']) && $data['picture']) {
  985. $btn .= Html::image(
  986. static::getPictureUrl($data['picture']),
  987. [
  988. 'style' => 'max-height: 20px;',
  989. ]
  990. );
  991. $btn .= ' ';
  992. }
  993. $btn .= sprintf(__sso('Login with %s'), $data['name']);
  994. $btn .= '</a></span>';
  995. return $btn;
  996. }
  997. }