provider.class.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  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(PluginSinglesignonToolbox::getPictureUrl($this->fields['picture']), [
  152. 'style' => '
  153. max-width: 100px;
  154. max-height: 100px;
  155. background-image: linear-gradient(45deg, #b0b0b0 25%, transparent 25%), linear-gradient(-45deg, #b0b0b0 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #b0b0b0 75%), linear-gradient(-45deg, transparent 75%, #b0b0b0 75%);
  156. background-size: 10px 10px;
  157. background-position: 0 0, 0 5px, 5px -5px, -5px 0px;',
  158. 'class' => 'picture_square'
  159. ]);
  160. echo "&nbsp;";
  161. echo Html::getCheckbox([
  162. 'title' => __('Clear'),
  163. 'name' => '_blank_picture'
  164. ]);
  165. echo "&nbsp;" . __('Clear');
  166. } else {
  167. echo Html::file([
  168. 'name' => 'picture',
  169. 'onlyimages' => true,
  170. ]);
  171. }
  172. echo "</td>";
  173. echo "</tr>\n";
  174. echo '<script type="text/javascript">
  175. $("[name=bgcolor]").on("change", function (e) {
  176. $("[name=_blank_bgcolor]").prop("checked", false).attr("checked", false);
  177. });
  178. $("[name=color]").on("change", function (e) {
  179. $("[name=_blank_color]").prop("checked", false).attr("checked", false);
  180. });
  181. </script>';
  182. if ($ID) {
  183. echo "<tr class='tab_bg_1'>";
  184. echo "<th colspan='4'>" . __('Test') . "</th>";
  185. echo "</tr>\n";
  186. $url = PluginSinglesignonToolbox::getCallbackUrl($ID);
  187. $fullUrl = $this->getBaseURL() . $url;
  188. echo "<tr class='tab_bg_1'>";
  189. echo "<td>" . __sso('Callback URL') . "</td>";
  190. echo "<td colspan='3'><a id='singlesignon_callbackurl' href='$fullUrl' data-url='$url'>$fullUrl</a></td>";
  191. echo "</tr>\n";
  192. $options['addbuttons'] = ['test_singlesignon' => __sso('Test Single Sign-on')];
  193. }
  194. $this->showFormButtons($options);
  195. if ($ID) {
  196. echo '<script type="text/javascript">
  197. $("[name=test_singlesignon]").on("click", function (e) {
  198. e.preventDefault();
  199. var url = $("#singlesignon_callbackurl").attr("data-url") + "/test/1";
  200. var left = ($(window).width()/2)-(600/2);
  201. var top = ($(window).height()/2)-(800/2);
  202. var newWindow = window.open(url, "singlesignon", "width=600,height=800,left=" + left + ",top=" + top);
  203. if (window.focus) {
  204. newWindow.focus();
  205. }
  206. });
  207. </script>';
  208. }
  209. return true;
  210. }
  211. function prepareInputForAdd($input) {
  212. return $this->prepareInput($input);
  213. }
  214. function prepareInputForUpdate($input) {
  215. return $this->prepareInput($input);
  216. }
  217. function cleanDBonPurge() {
  218. PluginSinglesignonToolbox::deletePicture($this->fields['picture']);
  219. $this->deleteChildrenAndRelationsFromDb(
  220. [
  221. 'PluginSinglesignonProvider_User',
  222. ]
  223. );
  224. }
  225. /**
  226. * Prepares input (for update and add)
  227. *
  228. * @param array $input Input data
  229. *
  230. * @return array
  231. */
  232. private function prepareInput($input) {
  233. $error_detected = [];
  234. $type = '';
  235. //check for requirements
  236. if (isset($input['type'])) {
  237. $type = $input['type'];
  238. }
  239. if (!isset($input['name']) || empty($input['name'])) {
  240. $error_detected[] = __sso('A Name is required');
  241. }
  242. if (empty($type)) {
  243. $error_detected[] = __('An item type is required');
  244. } else if (!isset(static::getTypes()[$type])) {
  245. $error_detected[] = sprintf(__sso('The "%s" is a Invalid type'), $type);
  246. }
  247. if (!isset($input['client_id']) || empty($input['client_id'])) {
  248. $error_detected[] = __sso('A Client ID is required');
  249. }
  250. if (!isset($input['client_secret']) || empty($input['client_secret'])) {
  251. $error_detected[] = __sso('A Client Secret is required');
  252. }
  253. if ($type === 'generic') {
  254. if (!isset($input['url_authorize']) || empty($input['url_authorize'])) {
  255. $error_detected[] = __sso('An Authorize URL is required');
  256. } else if (!filter_var($input['url_authorize'], FILTER_VALIDATE_URL)) {
  257. $error_detected[] = __sso('The Authorize URL is invalid');
  258. }
  259. if (!isset($input['url_access_token']) || empty($input['url_access_token'])) {
  260. $error_detected[] = __sso('An Access Token URL is required');
  261. } else if (!filter_var($input['url_access_token'], FILTER_VALIDATE_URL)) {
  262. $error_detected[] = __sso('The Access Token URL is invalid');
  263. }
  264. if (!isset($input['url_resource_owner_details']) || empty($input['url_resource_owner_details'])) {
  265. $error_detected[] = __sso('A Resource Owner Details URL is required');
  266. } else if (!filter_var($input['url_resource_owner_details'], FILTER_VALIDATE_URL)) {
  267. $error_detected[] = __sso('The Resource Owner Details URL is invalid');
  268. }
  269. }
  270. if (count($error_detected)) {
  271. foreach ($error_detected as $error) {
  272. Session::addMessageAfterRedirect(
  273. $error,
  274. true,
  275. ERROR
  276. );
  277. }
  278. return false;
  279. }
  280. if (isset($input["_blank_bgcolor"])
  281. && $input["_blank_bgcolor"]
  282. ) {
  283. $input['bgcolor'] = '';
  284. }
  285. if (isset($input["_blank_color"])
  286. && $input["_blank_color"]
  287. ) {
  288. $input['color'] = '';
  289. }
  290. if (isset($input["_blank_picture"])
  291. && $input["_blank_picture"]
  292. ) {
  293. $input['picture'] = '';
  294. if (array_key_exists('picture', $this->fields)) {
  295. PluginSinglesignonToolbox::deletePicture($this->fields['picture']);
  296. }
  297. }
  298. if (isset($input["_picture"])) {
  299. $picture = array_shift($input["_picture"]);
  300. if ($dest = PluginSinglesignonToolbox::savePicture(GLPI_TMP_DIR . '/' . $picture)) {
  301. $input['picture'] = $dest;
  302. } else {
  303. Session::addMessageAfterRedirect(__('Unable to save picture file.'), true, ERROR);
  304. }
  305. if (array_key_exists('picture', $this->fields)) {
  306. PluginSinglesignonToolbox::deletePicture($this->fields['picture']);
  307. }
  308. }
  309. return $input;
  310. }
  311. function getSearchOptions() {
  312. // For GLPI <= 9.2
  313. $options = [];
  314. foreach ($this->rawSearchOptions() as $opt) {
  315. if (!isset($opt['id'])) {
  316. continue;
  317. }
  318. $optid = $opt['id'];
  319. unset($opt['id']);
  320. if (isset($options[$optid])) {
  321. $message = "Duplicate key $optid ({$options[$optid]['name']}/{$opt['name']}) in " .
  322. get_class($this) . " searchOptions!";
  323. Toolbox::logDebug($message);
  324. }
  325. foreach ($opt as $k => $v) {
  326. $options[$optid][$k] = $v;
  327. }
  328. }
  329. return $options;
  330. }
  331. function rawSearchOptions() {
  332. $tab = [];
  333. $tab[] = [
  334. 'id' => 'common',
  335. 'name' => __('Characteristics'),
  336. ];
  337. $tab[] = [
  338. 'id' => 1,
  339. 'table' => $this->getTable(),
  340. 'field' => 'name',
  341. 'name' => __('Name'),
  342. 'datatype' => 'itemlink',
  343. ];
  344. $tab[] = [
  345. 'id' => 2,
  346. 'table' => $this->getTable(),
  347. 'field' => 'type',
  348. 'name' => __('Type'),
  349. 'searchtype' => 'equals',
  350. 'datatype' => 'specific',
  351. ];
  352. $tab[] = [
  353. 'id' => 3,
  354. 'table' => $this->getTable(),
  355. 'field' => 'client_id',
  356. 'name' => __sso('Client ID'),
  357. 'datatype' => 'text',
  358. ];
  359. $tab[] = [
  360. 'id' => 4,
  361. 'table' => $this->getTable(),
  362. 'field' => 'client_secret',
  363. 'name' => __sso('Client Secret'),
  364. 'datatype' => 'text',
  365. ];
  366. $tab[] = [
  367. 'id' => 5,
  368. 'table' => $this->getTable(),
  369. 'field' => 'scope',
  370. 'name' => __sso('Scope'),
  371. 'datatype' => 'text',
  372. ];
  373. $tab[] = [
  374. 'id' => 6,
  375. 'table' => $this->getTable(),
  376. 'field' => 'extra_options',
  377. 'name' => __sso('Extra Options'),
  378. 'datatype' => 'specific',
  379. ];
  380. $tab[] = [
  381. 'id' => 7,
  382. 'table' => $this->getTable(),
  383. 'field' => 'url_authorize',
  384. 'name' => __sso('Authorize URL'),
  385. 'datatype' => 'weblink',
  386. ];
  387. $tab[] = [
  388. 'id' => 8,
  389. 'table' => $this->getTable(),
  390. 'field' => 'url_access_token',
  391. 'name' => __sso('Access Token URL'),
  392. 'datatype' => 'weblink',
  393. ];
  394. $tab[] = [
  395. 'id' => 9,
  396. 'table' => $this->getTable(),
  397. 'field' => 'url_resource_owner_details',
  398. 'name' => __sso('Resource Owner Details URL'),
  399. 'datatype' => 'weblink',
  400. ];
  401. $tab[] = [
  402. 'id' => 10,
  403. 'table' => $this->getTable(),
  404. 'field' => 'is_active',
  405. 'name' => __('Active'),
  406. 'searchtype' => 'equals',
  407. 'datatype' => 'bool',
  408. ];
  409. $tab[] = [
  410. 'id' => 30,
  411. 'table' => $this->getTable(),
  412. 'field' => 'id',
  413. 'name' => __('ID'),
  414. 'datatype' => 'itemlink',
  415. ];
  416. return $tab;
  417. }
  418. static function getSpecificValueToDisplay($field, $values, array $options = []) {
  419. if (!is_array($values)) {
  420. $values = [$field => $values];
  421. }
  422. switch ($field) {
  423. case 'type':
  424. return self::getTicketTypeName($values[$field]);
  425. case 'extra_options':
  426. return '<pre>' . $values[$field] . '</pre>';
  427. }
  428. return '';
  429. }
  430. static function getSpecificValueToSelect($field, $name = '', $values = '', array $options = []) {
  431. if (!is_array($values)) {
  432. $values = [$field => $values];
  433. }
  434. $options['display'] = false;
  435. switch ($field) {
  436. case 'type':
  437. $options['value'] = $values[$field];
  438. return self::dropdownType($name, $options);
  439. }
  440. return parent::getSpecificValueToSelect($field, $name, $values, $options);
  441. }
  442. /**
  443. * Get ticket types
  444. *
  445. * @return array of types
  446. * */
  447. static function getTypes() {
  448. $options['generic'] = __sso('Generic');
  449. $options['facebook'] = __sso('Facebook');
  450. $options['github'] = __sso('GitHub');
  451. $options['google'] = __sso('Google');
  452. $options['instagram'] = __sso('Instagram');
  453. $options['linkedin'] = __sso('LinkdeIn');
  454. return $options;
  455. }
  456. /**
  457. * Get ticket type Name
  458. *
  459. * @param $value type ID
  460. * */
  461. static function getTicketTypeName($value) {
  462. $tab = static::getTypes();
  463. // Return $value if not defined
  464. return (isset($tab[$value]) ? $tab[$value] : $value);
  465. }
  466. /**
  467. * Dropdown of ticket type
  468. *
  469. * @param $name select name
  470. * @param $options array of options:
  471. * - value : integer / preselected value (default 0)
  472. * - toadd : array / array of specific values to add at the begining
  473. * - on_change : string / value to transmit to "onChange"
  474. * - display : boolean / display or get string (default true)
  475. *
  476. * @return string id of the select
  477. * */
  478. static function dropdownType($name, $options = []) {
  479. $params['value'] = 0;
  480. $params['toadd'] = [];
  481. $params['on_change'] = '';
  482. $params['display'] = true;
  483. if (is_array($options) && count($options)) {
  484. foreach ($options as $key => $val) {
  485. $params[$key] = $val;
  486. }
  487. }
  488. $items = [];
  489. if (count($params['toadd']) > 0) {
  490. $items = $params['toadd'];
  491. }
  492. $items += self::getTypes();
  493. return Dropdown::showFromArray($name, $items, $params);
  494. }
  495. /**
  496. * Get an history entry message
  497. *
  498. * @param $data Array from glpi_logs table
  499. *
  500. * @since GLPI version 0.84
  501. *
  502. * @return string
  503. * */
  504. static function getHistoryEntry($data) {
  505. switch ($data['linked_action'] - Log::HISTORY_PLUGIN) {
  506. case 0:
  507. return __('History from plugin example', 'example');
  508. }
  509. return '';
  510. }
  511. //////////////////////////////
  512. ////// SPECIFIC MODIF MASSIVE FUNCTIONS ///////
  513. /**
  514. * @since version 0.85
  515. *
  516. * @see CommonDBTM::getSpecificMassiveActions()
  517. * */
  518. function getSpecificMassiveActions($checkitem = null) {
  519. $actions = parent::getSpecificMassiveActions($checkitem);
  520. $actions['Document_Item' . MassiveAction::CLASS_ACTION_SEPARATOR . 'add'] = _x('button', 'Add a document'); // GLPI core one
  521. $actions[__CLASS__ . MassiveAction::CLASS_ACTION_SEPARATOR . 'do_nothing'] = __('Do Nothing - just for fun', 'example'); // Specific one
  522. return $actions;
  523. }
  524. /**
  525. * @since version 0.85
  526. *
  527. * @see CommonDBTM::showMassiveActionsSubForm()
  528. * */
  529. static function showMassiveActionsSubForm(MassiveAction $ma) {
  530. switch ($ma->getAction()) {
  531. case 'DoIt':
  532. echo "&nbsp;<input type='hidden' name='toto' value='1'>" .
  533. Html::submit(_x('button', 'Post'), ['name' => 'massiveaction']) .
  534. " " . __('Write in item history', 'example');
  535. return true;
  536. case 'do_nothing':
  537. echo "&nbsp;" . Html::submit(_x('button', 'Post'), ['name' => 'massiveaction']) .
  538. " " . __('but do nothing :)', 'example');
  539. return true;
  540. }
  541. return parent::showMassiveActionsSubForm($ma);
  542. }
  543. /**
  544. * @since version 0.85
  545. *
  546. * @see CommonDBTM::processMassiveActionsForOneItemtype()
  547. * */
  548. static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item, array $ids) {
  549. global $DB;
  550. switch ($ma->getAction()) {
  551. case 'DoIt':
  552. if ($item->getType() == 'Computer') {
  553. Session::addMessageAfterRedirect(__("Right it is the type I want...", 'example'));
  554. Session::addMessageAfterRedirect(__('Write in item history', 'example'));
  555. $changes = [0, 'old value', 'new value'];
  556. foreach ($ids as $id) {
  557. if ($item->getFromDB($id)) {
  558. Session::addMessageAfterRedirect("- " . $item->getField("name"));
  559. Log::history($id, 'Computer', $changes, 'PluginExampleExample', Log::HISTORY_PLUGIN);
  560. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
  561. } else {
  562. // Example of ko count
  563. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
  564. }
  565. }
  566. } else {
  567. // When nothing is possible ...
  568. $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);
  569. }
  570. return;
  571. case 'do_nothing':
  572. if ($item->getType() == 'PluginExampleExample') {
  573. Session::addMessageAfterRedirect(__("Right it is the type I want...", 'example'));
  574. Session::addMessageAfterRedirect(__("But... I say I will do nothing for:", 'example'));
  575. foreach ($ids as $id) {
  576. if ($item->getFromDB($id)) {
  577. Session::addMessageAfterRedirect("- " . $item->getField("name"));
  578. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
  579. } else {
  580. // Example for noright / Maybe do it with can function is better
  581. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
  582. }
  583. }
  584. } else {
  585. $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);
  586. }
  587. return;
  588. }
  589. parent::processMassiveActionsForOneItemtype($ma, $item, $ids);
  590. }
  591. static function getIcon() {
  592. return "fas fa-user-lock";
  593. }
  594. public static function getDefault($type, $key, $default = null) {
  595. if (static::$default === null) {
  596. $content = file_get_contents(dirname(__FILE__) . '/../providers.json');
  597. static::$default = json_decode($content, true);
  598. }
  599. if (isset(static::$default[$type]) && static::$default[$type][$key]) {
  600. return static::$default[$type][$key];
  601. }
  602. return $default;
  603. }
  604. public function getClientType() {
  605. $value = "generic";
  606. if (isset($this->fields['type']) && !empty($this->fields['type'])) {
  607. $value = $this->fields['type'];
  608. }
  609. return $value;
  610. }
  611. public function getClientId() {
  612. $value = "";
  613. if (isset($this->fields['client_id']) && !empty($this->fields['client_id'])) {
  614. $value = $this->fields['client_id'];
  615. }
  616. return $value;
  617. }
  618. public function getClientSecret() {
  619. $value = "";
  620. if (isset($this->fields['client_secret']) && !empty($this->fields['client_secret'])) {
  621. $value = $this->fields['client_secret'];
  622. }
  623. return $value;
  624. }
  625. public function getScope() {
  626. $type = $this->getClientType();
  627. $value = static::getDefault($type, "scope");
  628. $fields = $this->fields;
  629. if (!isset($fields['scope']) || empty($fields['scope'])) {
  630. $fields['scope'] = $value;
  631. }
  632. $fields = Plugin::doHookFunction("sso:scope", $fields);
  633. return $fields['scope'];
  634. }
  635. public function getAuthorizeUrl() {
  636. $type = $this->getClientType();
  637. $value = static::getDefault($type, "url_authorize");
  638. $fields = $this->fields;
  639. if (!isset($fields['url_authorize']) || empty($fields['url_authorize'])) {
  640. $fields['url_authorize'] = $value;
  641. }
  642. $fields = Plugin::doHookFunction("sso:url_authorize", $fields);
  643. return $fields['url_authorize'];
  644. }
  645. public function getAccessTokenUrl() {
  646. $type = $this->getClientType();
  647. $value = static::getDefault($type, "url_access_token");
  648. $fields = $this->fields;
  649. if (!isset($fields['url_access_token']) || empty($fields['url_access_token'])) {
  650. $fields['url_access_token'] = $value;
  651. }
  652. $fields = Plugin::doHookFunction("sso:url_access_token", $fields);
  653. return $fields['url_access_token'];
  654. }
  655. public function getResourceOwnerDetailsUrl($access_token) {
  656. $type = $this->getClientType();
  657. $value = static::getDefault($type, "url_resource_owner_details", "");
  658. $fields = $this->fields;
  659. $fields['access_token'] = $access_token;
  660. if (!isset($fields['url_resource_owner_details']) || empty($fields['url_resource_owner_details'])) {
  661. $fields['url_resource_owner_details'] = $value;
  662. }
  663. $fields = Plugin::doHookFunction("sso:url_resource_owner_details", $fields);
  664. $url = $fields['url_resource_owner_details'];
  665. $url = str_replace("<access_token>", $access_token, $url);
  666. $url = str_replace("<appsecret_proof>", hash_hmac('sha256', $access_token, $this->getClientSecret()), $url);
  667. return $url;
  668. }
  669. /**
  670. * Get current URL without query string
  671. * @return string
  672. */
  673. private function getBaseURL() {
  674. $baseURL = "";
  675. if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
  676. $baseURL = ($_SERVER["HTTP_X_FORWARDED_PROTO"] == "https") ? "https://" : "http://";
  677. } else if (isset($_SERVER["HTTPS"])) {
  678. $baseURL = ($_SERVER["HTTPS"] == "on") ? "https://" : "http://";
  679. } else {
  680. $baseURL = "http://";
  681. }
  682. if (isset($_SERVER["HTTP_X_FORWARDED_HOST"])) {
  683. $baseURL .= $_SERVER["HTTP_X_FORWARDED_HOST"];
  684. } else if (isset($_SERVER["HTTP_X_FORWARDED_HOST"])) {
  685. $baseURL .= $_SERVER["HTTP_X_FORWARDED_HOST"];
  686. } else {
  687. $baseURL .= $_SERVER["SERVER_NAME"];
  688. }
  689. $port = $_SERVER["SERVER_PORT"];
  690. if (isset($_SERVER["HTTP_X_FORWARDED_PORT"])) {
  691. $port = $_SERVER["HTTP_X_FORWARDED_PORT"];
  692. }
  693. if ($port != "80" && $port != "443") {
  694. $baseURL .= ":" . $_SERVER["SERVER_PORT"];
  695. }
  696. return $baseURL;
  697. }
  698. /**
  699. * Get current URL without query string
  700. * @return string
  701. */
  702. private function getCurrentURL() {
  703. $currentURL = $this->getBaseURL();
  704. // $currentURL .= $_SERVER["REQUEST_URI"];
  705. // Ignore Query String
  706. if (isset($_SERVER["SCRIPT_NAME"])) {
  707. $currentURL .= $_SERVER["SCRIPT_NAME"];
  708. }
  709. if (isset($_SERVER["PATH_INFO"])) {
  710. $currentURL .= $_SERVER["PATH_INFO"];
  711. }
  712. return $currentURL;
  713. }
  714. /**
  715. *
  716. * @return boolean|string
  717. */
  718. public function checkAuthorization() {
  719. if (isset($_GET['error'])) {
  720. $error_description = isset($_GET['error_description']) ? $_GET['error_description'] : __("The action you have requested is not allowed.");
  721. Html::displayErrorAndDie(__($error_description), true);
  722. }
  723. if (!isset($_GET['code'])) {
  724. $params = [
  725. 'client_id' => $this->getClientId(),
  726. 'scope' => $this->getScope(),
  727. 'state' => Session::getNewCSRFToken(),
  728. 'response_type' => 'code',
  729. 'approval_prompt' => 'auto',
  730. 'redirect_uri' => $this->getCurrentURL(),
  731. ];
  732. $params = Plugin::doHookFunction("sso:authorize_params", $params);
  733. $url = $this->getAuthorizeUrl();
  734. $glue = strstr($url, '?') === false ? '?' : '&';
  735. $url .= $glue . http_build_query($params);
  736. header('Location: ' . $url);
  737. exit;
  738. }
  739. // Check given state against previously stored one to mitigate CSRF attack
  740. $state = isset($_GET['state']) ? $_GET['state'] : '';
  741. Session::checkCSRF([
  742. '_glpi_csrf_token' => $state,
  743. ]);
  744. $this->_code = $_GET['code'];
  745. return $_GET['code'];
  746. }
  747. /**
  748. *
  749. * @return boolean|string
  750. */
  751. public function getAccessToken() {
  752. if ($this->_token !== null) {
  753. return $this->_token;
  754. }
  755. if ($this->_code === null) {
  756. return false;
  757. }
  758. $params = [
  759. 'client_id' => $this->getClientId(),
  760. 'client_secret' => $this->getClientSecret(),
  761. 'redirect_uri' => $this->getCurrentURL(),
  762. 'grant_type' => 'authorization_code',
  763. 'code' => $this->_code,
  764. ];
  765. $params = Plugin::doHookFunction("sso:access_token_params", $params);
  766. $url = $this->getAccessTokenUrl();
  767. $content = Toolbox::callCurl($url, [
  768. CURLOPT_HTTPHEADER => [
  769. "Accept: application/json",
  770. ],
  771. CURLOPT_POST => true,
  772. CURLOPT_POSTFIELDS => http_build_query($params),
  773. CURLOPT_SSL_VERIFYHOST => false,
  774. CURLOPT_SSL_VERIFYPEER => false,
  775. ]);
  776. try {
  777. $data = json_decode($content, true);
  778. if (!isset($data['access_token'])) {
  779. return false;
  780. }
  781. $this->_token = $data['access_token'];
  782. } catch (\Exception $ex) {
  783. return false;
  784. }
  785. return $this->_token;
  786. }
  787. /**
  788. *
  789. * @return boolean|array
  790. */
  791. public function getResourceOwner() {
  792. if ($this->_resource_owner !== null) {
  793. return $this->_resource_owner;
  794. }
  795. $token = $this->getAccessToken();
  796. if (!$token) {
  797. return false;
  798. }
  799. $url = $this->getResourceOwnerDetailsUrl($token);
  800. $headers = [
  801. "Accept:application/json",
  802. "Authorization:Bearer $token",
  803. ];
  804. $headers = Plugin::doHookFunction("sso:resource_owner_header", $headers);
  805. $content = Toolbox::callCurl($url, [
  806. CURLOPT_HTTPHEADER => $headers,
  807. CURLOPT_SSL_VERIFYHOST => false,
  808. CURLOPT_SSL_VERIFYPEER => false,
  809. ]);
  810. try {
  811. $data = json_decode($content, true);
  812. $this->_resource_owner = $data;
  813. } catch (\Exception $ex) {
  814. return false;
  815. }
  816. if ($this->getClientType() === "linkedin") {
  817. $email_url = "https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))";
  818. $content = Toolbox::callCurl($email_url, [
  819. CURLOPT_HTTPHEADER => $headers,
  820. CURLOPT_SSL_VERIFYHOST => false,
  821. CURLOPT_SSL_VERIFYPEER => false,
  822. ]);
  823. try {
  824. $data = json_decode($content, true);
  825. $this->_resource_owner['email-address'] = $data['elements'][0]['handle~']['emailAddress'];
  826. } catch (\Exception $ex) {
  827. return false;
  828. }
  829. }
  830. return $this->_resource_owner;
  831. }
  832. public function findUser() {
  833. $resource_array = $this->getResourceOwner();
  834. if (!$resource_array) {
  835. return false;
  836. }
  837. $user = new User();
  838. //First: check linked user
  839. $id = Plugin::doHookFunction("sso:find_user", $resource_array);
  840. if (is_numeric($id) && $user->getFromDB($id)) {
  841. return $user;
  842. }
  843. $remote_id = false;
  844. $remote_id_fields = ['id', 'username'];
  845. foreach ($remote_id_fields as $field) {
  846. if (isset($resource_array[$field]) && !empty($resource_array[$field])) {
  847. $remote_id = $resource_array[$field];
  848. break;
  849. }
  850. }
  851. if ($remote_id) {
  852. $link = new PluginSinglesignonProvider_User();
  853. $condition = "`remote_id` = '{$remote_id}' AND `plugin_singlesignon_providers_id` = {$this->fields['id']}";
  854. if (version_compare(GLPI_VERSION, '9.4', '>=')) {
  855. $condition = [$condition];
  856. }
  857. $links = $link->find($condition);
  858. if (!empty($links) && $first = reset($links)) {
  859. $id = $first['users_id'];
  860. }
  861. $remote_id;
  862. }
  863. if (is_numeric($id) && $user->getFromDB($id)) {
  864. return $user;
  865. }
  866. $email = false;
  867. $email_fields = ['email', 'e-mail', 'email-address', 'mail'];
  868. foreach ($email_fields as $field) {
  869. if (isset($resource_array[$field]) && is_string($resource_array[$field])) {
  870. $email = $resource_array[$field];
  871. break;
  872. }
  873. }
  874. $default_condition = '';
  875. if (version_compare(GLPI_VERSION, '9.3', '>=')) {
  876. $default_condition = [];
  877. }
  878. if ($email && $user->getFromDBbyEmail($email, $default_condition)) {
  879. return $user;
  880. }
  881. $login = false;
  882. $login_fields = ['login', 'username', 'id'];
  883. foreach ($login_fields as $field) {
  884. if (isset($resource_array[$field]) && is_string($resource_array[$field])) {
  885. $login = $resource_array[$field];
  886. break;
  887. }
  888. }
  889. if ($login && $user->getFromDBbyName($login)) {
  890. return $user;
  891. }
  892. return false;
  893. }
  894. public function login() {
  895. $user = $this->findUser();
  896. if (!$user) {
  897. return false;
  898. }
  899. //Create fake auth
  900. $auth = new Auth();
  901. $auth->user = $user;
  902. $auth->auth_succeded = true;
  903. $auth->extauth = 1;
  904. $auth->user_present = $auth->user->getFromDBbyName(addslashes($user->fields['name']));
  905. $auth->user->fields['authtype'] = Auth::DB_GLPI;
  906. Session::init($auth);
  907. return $auth->auth_succeded;
  908. }
  909. public function linkUser($user_id) {
  910. $user = new User();
  911. if (!$user->getFromDB($user_id)) {
  912. return false;
  913. }
  914. $resource_array = $this->getResourceOwner();
  915. if (!$resource_array) {
  916. return false;
  917. }
  918. $remote_id = false;
  919. $id_fields = ['id', 'sub', 'username'];
  920. foreach ($id_fields as $field) {
  921. if (isset($resource_array[$field]) && !empty($resource_array[$field])) {
  922. $remote_id = $resource_array[$field];
  923. break;
  924. }
  925. }
  926. if (!$remote_id) {
  927. return false;
  928. }
  929. $link = new PluginSinglesignonProvider_User();
  930. // Unlink from another user
  931. $link->deleteByCriteria([
  932. 'plugin_singlesignon_providers_id' => $this->fields['id'],
  933. 'remote_id' => $remote_id,
  934. ]);
  935. return $link->add([
  936. 'plugin_singlesignon_providers_id' => $this->fields['id'],
  937. 'users_id' => $user_id,
  938. 'remote_id' => $remote_id,
  939. ]);
  940. }
  941. }