restservices.class.inc.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. <?php
  2. // Copyright (C) 2013 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * REST/json services
  20. *
  21. * Definition of common structures + the very minimum service provider (manage objects)
  22. *
  23. * @package REST Services
  24. * @copyright Copyright (C) 2013 Combodo SARL
  25. * @license http://opensource.org/licenses/AGPL-3.0
  26. * @api
  27. */
  28. /**
  29. * Element of the response formed by RestResultWithObjects
  30. *
  31. * @package REST Services
  32. */
  33. class ObjectResult
  34. {
  35. public $code;
  36. public $message;
  37. public $fields;
  38. /**
  39. * Default constructor
  40. */
  41. public function __construct()
  42. {
  43. $this->code = RestResult::OK;
  44. $this->message = '';
  45. $this->fields = array();
  46. }
  47. /**
  48. * Helper to make an output value for a given attribute
  49. *
  50. * @param DBObject $oObject The object being reported
  51. * @param string $sAttCode The attribute code (must be valid)
  52. * @return string A scalar representation of the value
  53. */
  54. protected function MakeResultValue(DBObject $oObject, $sAttCode)
  55. {
  56. if ($sAttCode == 'id')
  57. {
  58. $value = $oObject->GetKey();
  59. }
  60. else
  61. {
  62. $sClass = get_class($oObject);
  63. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  64. if ($oAttDef instanceof AttributeLinkedSet)
  65. {
  66. $value = array();
  67. // Make the list of required attributes
  68. // - Skip attributes pointing to the current object (redundant data)
  69. // - Skip link sets refering to the current data (infinite recursion!)
  70. $aRelevantAttributes = array();
  71. $sLnkClass = $oAttDef->GetLinkedClass();
  72. foreach (MetaModel::ListAttributeDefs($sLnkClass) as $sLnkAttCode => $oLnkAttDef)
  73. {
  74. // Skip any attribute of the link that points to the current object
  75. //
  76. if ($sLnkAttCode == $oAttDef->GetExtKeyToMe()) continue;
  77. if (method_exists($oLnkAttDef, 'GetKeyAttCode'))
  78. {
  79. if ($oLnkAttDef->GetKeyAttCode() ==$oAttDef->GetExtKeyToMe()) continue;
  80. }
  81. $aRelevantAttributes[] = $sLnkAttCode;
  82. }
  83. // Iterate on the set and build an array of array of attcode=>value
  84. $oSet = $oObject->Get($sAttCode);
  85. while ($oLnk = $oSet->Fetch())
  86. {
  87. $aLnkValues = array();
  88. foreach ($aRelevantAttributes as $sLnkAttCode)
  89. {
  90. $aLnkValues[$sLnkAttCode] = $this->MakeResultValue($oLnk, $sLnkAttCode);
  91. }
  92. $value[] = $aLnkValues;
  93. }
  94. }
  95. else
  96. {
  97. $value = $oAttDef->GetForJSON($oObject->Get($sAttCode));
  98. }
  99. }
  100. return $value;
  101. }
  102. /**
  103. * Report the value for the given object attribute
  104. *
  105. * @param DBObject $oObject The object being reported
  106. * @param string $sAttCode The attribute code (must be valid)
  107. * @return void
  108. */
  109. public function AddField(DBObject $oObject, $sAttCode)
  110. {
  111. $this->fields[$sAttCode] = $this->MakeResultValue($oObject, $sAttCode);
  112. }
  113. }
  114. /**
  115. * REST response for services managing objects. Derive this structure to add information and/or constants
  116. *
  117. * @package Extensibility
  118. * @package REST Services
  119. * @api
  120. */
  121. class RestResultWithObjects extends RestResult
  122. {
  123. public $objects;
  124. /**
  125. * Report the given object
  126. *
  127. * @param int An error code (RestResult::OK is no issue has been found)
  128. * @param string $sMessage Description of the error if any, an empty string otherwise
  129. * @param DBObject $oObject The object being reported
  130. * @param array $aFields An array of attribute codes. List of the attributes to be reported.
  131. * @return void
  132. */
  133. public function AddObject($iCode, $sMessage, $oObject, $aFields)
  134. {
  135. $oObjRes = new ObjectResult();
  136. $oObjRes->code = $iCode;
  137. $oObjRes->message = $sMessage;
  138. $oObjRes->class = get_class($oObject);
  139. foreach ($aFields as $sAttCode)
  140. {
  141. $oObjRes->AddField($oObject, $sAttCode);
  142. }
  143. $sObjKey = get_class($oObject).'::'.$oObject->GetKey();
  144. $this->objects[$sObjKey] = $oObjRes;
  145. }
  146. }
  147. class RestResultWithRelations extends RestResultWithObjects
  148. {
  149. public $relations;
  150. public function __construct()
  151. {
  152. parent::__construct();
  153. $this->relations = array();
  154. }
  155. public function AddRelation($sSrcKey, $sDestKey)
  156. {
  157. if (!array_key_exists($sSrcKey, $this->relations))
  158. {
  159. $this->relations[$sSrcKey] = array();
  160. }
  161. $this->relations[$sSrcKey][] = array('key' => $sDestKey);
  162. }
  163. }
  164. /**
  165. * Deletion result codes for a target object (either deleted or updated)
  166. *
  167. * @package Extensibility
  168. * @api
  169. * @since 2.0.1
  170. */
  171. class RestDelete
  172. {
  173. /**
  174. * Result: Object deleted as per the initial request
  175. */
  176. const OK = 0;
  177. /**
  178. * Result: general issue (user rights or ... ?)
  179. */
  180. const ISSUE = 1;
  181. /**
  182. * Result: Must be deleted to preserve database integrity
  183. */
  184. const AUTO_DELETE = 2;
  185. /**
  186. * Result: Must be deleted to preserve database integrity, but that is NOT possible
  187. */
  188. const AUTO_DELETE_ISSUE = 3;
  189. /**
  190. * Result: Must be deleted to preserve database integrity, but this must be requested explicitely
  191. */
  192. const REQUEST_EXPLICITELY = 4;
  193. /**
  194. * Result: Must be updated to preserve database integrity
  195. */
  196. const AUTO_UPDATE = 5;
  197. /**
  198. * Result: Must be updated to preserve database integrity, but that is NOT possible
  199. */
  200. const AUTO_UPDATE_ISSUE = 6;
  201. }
  202. /**
  203. * Implementation of core REST services (create/get/update... objects)
  204. *
  205. * @package Core
  206. */
  207. class CoreServices implements iRestServiceProvider
  208. {
  209. /**
  210. * Enumerate services delivered by this class
  211. *
  212. * @param string $sVersion The version (e.g. 1.0) supported by the services
  213. * @return array An array of hash 'verb' => verb, 'description' => description
  214. */
  215. public function ListOperations($sVersion)
  216. {
  217. $aOps = array();
  218. if ($sVersion == '1.0')
  219. {
  220. $aOps[] = array(
  221. 'verb' => 'core/create',
  222. 'description' => 'Create an object'
  223. );
  224. $aOps[] = array(
  225. 'verb' => 'core/update',
  226. 'description' => 'Update an object'
  227. );
  228. $aOps[] = array(
  229. 'verb' => 'core/apply_stimulus',
  230. 'description' => 'Apply a stimulus to change the state of an object'
  231. );
  232. $aOps[] = array(
  233. 'verb' => 'core/get',
  234. 'description' => 'Search for objects'
  235. );
  236. $aOps[] = array(
  237. 'verb' => 'core/delete',
  238. 'description' => 'Delete objects'
  239. );
  240. $aOps[] = array(
  241. 'verb' => 'core/get_related',
  242. 'description' => 'Get related objects through the specified relation'
  243. );
  244. }
  245. return $aOps;
  246. }
  247. /**
  248. * Enumerate services delivered by this class
  249. * @param string $sVersion The version (e.g. 1.0) supported by the services
  250. * @return RestResult The standardized result structure (at least a message)
  251. * @throws Exception in case of internal failure.
  252. */
  253. public function ExecOperation($sVersion, $sVerb, $aParams)
  254. {
  255. $oResult = new RestResultWithObjects();
  256. switch ($sVerb)
  257. {
  258. case 'core/create':
  259. RestUtils::InitTrackingComment($aParams);
  260. $sClass = RestUtils::GetClass($aParams, 'class');
  261. $aFields = RestUtils::GetMandatoryParam($aParams, 'fields');
  262. $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields');
  263. $oObject = RestUtils::MakeObjectFromFields($sClass, $aFields);
  264. $oObject->DBInsert();
  265. $oResult->AddObject(0, 'created', $oObject, $aShowFields);
  266. break;
  267. case 'core/update':
  268. RestUtils::InitTrackingComment($aParams);
  269. $sClass = RestUtils::GetClass($aParams, 'class');
  270. $key = RestUtils::GetMandatoryParam($aParams, 'key');
  271. $aFields = RestUtils::GetMandatoryParam($aParams, 'fields');
  272. $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields');
  273. $oObject = RestUtils::FindObjectFromKey($sClass, $key);
  274. RestUtils::UpdateObjectFromFields($oObject, $aFields);
  275. $oObject->DBUpdate();
  276. $oResult->AddObject(0, 'updated', $oObject, $aShowFields);
  277. break;
  278. case 'core/apply_stimulus':
  279. RestUtils::InitTrackingComment($aParams);
  280. $sClass = RestUtils::GetClass($aParams, 'class');
  281. $key = RestUtils::GetMandatoryParam($aParams, 'key');
  282. $aFields = RestUtils::GetMandatoryParam($aParams, 'fields');
  283. $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields');
  284. $sStimulus = RestUtils::GetMandatoryParam($aParams, 'stimulus');
  285. $oObject = RestUtils::FindObjectFromKey($sClass, $key);
  286. RestUtils::UpdateObjectFromFields($oObject, $aFields);
  287. $aTransitions = $oObject->EnumTransitions();
  288. $aStimuli = MetaModel::EnumStimuli(get_class($oObject));
  289. if (!isset($aTransitions[$sStimulus]))
  290. {
  291. // Invalid stimulus
  292. $oResult->code = RestResult::INTERNAL_ERROR;
  293. $oResult->message = "Invalid stimulus: '$sStimulus' on the object ".$oObject->GetName()." in state '".$oObject->GetState()."'";
  294. }
  295. else
  296. {
  297. $aTransition = $aTransitions[$sStimulus];
  298. $sTargetState = $aTransition['target_state'];
  299. $aStates = MetaModel::EnumStates($sClass);
  300. $aTargetStateDef = $aStates[$sTargetState];
  301. $aExpectedAttributes = $aTargetStateDef['attribute_list'];
  302. $aMissingMandatory = array();
  303. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  304. {
  305. if ( ($iExpectCode & OPT_ATT_MANDATORY) && ($oObject->Get($sAttCode) == ''))
  306. {
  307. $aMissingMandatory[] = $sAttCode;
  308. }
  309. }
  310. if (count($aMissingMandatory) == 0)
  311. {
  312. // If all the mandatory fields are already present, just apply the transition silently...
  313. if ($oObject->ApplyStimulus($sStimulus))
  314. {
  315. $oObject->DBUpdate();
  316. $oResult->AddObject(0, 'updated', $oObject, $aShowFields);
  317. }
  318. }
  319. else
  320. {
  321. // Missing mandatory attributes for the transition
  322. $oResult->code = RestResult::INTERNAL_ERROR;
  323. $oResult->message = 'Missing mandatory attribute(s) for applying the stimulus: '.implode(', ', $aMissingMandatory).'.';
  324. }
  325. }
  326. break;
  327. case 'core/get':
  328. $sClass = RestUtils::GetClass($aParams, 'class');
  329. $key = RestUtils::GetMandatoryParam($aParams, 'key');
  330. $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields');
  331. $oObjectSet = RestUtils::GetObjectSetFromKey($sClass, $key);
  332. while ($oObject = $oObjectSet->Fetch())
  333. {
  334. $oResult->AddObject(0, '', $oObject, $aShowFields);
  335. }
  336. $oResult->message = "Found: ".$oObjectSet->Count();
  337. break;
  338. case 'core/delete':
  339. $sClass = RestUtils::GetClass($aParams, 'class');
  340. $key = RestUtils::GetMandatoryParam($aParams, 'key');
  341. $bSimulate = RestUtils::GetOptionalParam($aParams, 'simulate', false);
  342. $oObjectSet = RestUtils::GetObjectSetFromKey($sClass, $key);
  343. $aObjects = $oObjectSet->ToArray();
  344. $this->DeleteObjects($oResult, $aObjects, $bSimulate);
  345. break;
  346. case 'core/get_related':
  347. $oResult = new RestResultWithRelations();
  348. $sClass = RestUtils::GetClass($aParams, 'class');
  349. $key = RestUtils::GetMandatoryParam($aParams, 'key');
  350. $sRelation = RestUtils::GetMandatoryParam($aParams, 'relation');
  351. $iMaxRecursionDepth = RestUtils::GetOptionalParam($aParams, 'depth', 20 /* = MAX_RECURSION_DEPTH */);
  352. $aShowFields = array('id', 'friendlyname');
  353. $oObjectSet = RestUtils::GetObjectSetFromKey($sClass, $key);
  354. $aIndexByClass = array();
  355. while ($oObject = $oObjectSet->Fetch())
  356. {
  357. $aRelated = array();
  358. $aGraph = array();
  359. $aIndexByClass[get_class($oObject)][$oObject->GetKey()] = null;
  360. $oResult->AddObject(0, '', $oObject, $aShowFields);
  361. $this->GetRelatedObjects($oObject, $sRelation, $iMaxRecursionDepth, $aRelated, $aGraph);
  362. foreach($aRelated as $sClass => $aObjects)
  363. {
  364. foreach($aObjects as $oRelatedObj)
  365. {
  366. $aIndexByClass[get_class($oRelatedObj)][$oRelatedObj->GetKey()] = null;
  367. $oResult->AddObject(0, '', $oRelatedObj, $aShowFields);
  368. }
  369. }
  370. foreach($aGraph as $sSrcKey => $aDestinations)
  371. {
  372. foreach ($aDestinations as $sDestKey)
  373. {
  374. $oResult->AddRelation($sSrcKey, $sDestKey);
  375. }
  376. }
  377. }
  378. if (count($aIndexByClass) > 0)
  379. {
  380. $aStats = array();
  381. foreach ($aIndexByClass as $sClass => $aIds)
  382. {
  383. $aStats[] = $sClass.'= '.count($aIds);
  384. }
  385. $oResult->message = "Scope: ".$oObjectSet->Count()."; Related objects: ".implode(', ', $aStats);
  386. }
  387. else
  388. {
  389. $oResult->message = "Nothing found";
  390. }
  391. break;
  392. default:
  393. // unknown operation: handled at a higher level
  394. }
  395. return $oResult;
  396. }
  397. /**
  398. * Helper for object deletion
  399. */
  400. public function DeleteObjects($oResult, $aObjects, $bSimulate)
  401. {
  402. $oDeletionPlan = new DeletionPlan();
  403. foreach($aObjects as $oObj)
  404. {
  405. if ($bSimulate)
  406. {
  407. $oObj->CheckToDelete($oDeletionPlan);
  408. }
  409. else
  410. {
  411. $oObj->DBDelete($oDeletionPlan);
  412. }
  413. }
  414. foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes)
  415. {
  416. foreach ($aDeletes as $iId => $aData)
  417. {
  418. $oToDelete = $aData['to_delete'];
  419. $bAutoDel = (($aData['mode'] == DEL_SILENT) || ($aData['mode'] == DEL_AUTO));
  420. if (array_key_exists('issue', $aData))
  421. {
  422. if ($bAutoDel)
  423. {
  424. if (isset($aData['requested_explicitely'])) // i.e. in the initial list of objects to delete
  425. {
  426. $iCode = RestDelete::ISSUE;
  427. $sPlanned = 'Cannot be deleted: '.$aData['issue'];
  428. }
  429. else
  430. {
  431. $iCode = RestDelete::AUTO_DELETE_ISSUE;
  432. $sPlanned = 'Should be deleted automatically... but: '.$aData['issue'];
  433. }
  434. }
  435. else
  436. {
  437. $iCode = RestDelete::REQUEST_EXPLICITELY;
  438. $sPlanned = 'Must be deleted explicitely... but: '.$aData['issue'];
  439. }
  440. }
  441. else
  442. {
  443. if ($bAutoDel)
  444. {
  445. if (isset($aData['requested_explicitely']))
  446. {
  447. $iCode = RestDelete::OK;
  448. $sPlanned = '';
  449. }
  450. else
  451. {
  452. $iCode = RestDelete::AUTO_DELETE;
  453. $sPlanned = 'Deleted automatically';
  454. }
  455. }
  456. else
  457. {
  458. $iCode = RestDelete::REQUEST_EXPLICITELY;
  459. $sPlanned = 'Must be deleted explicitely';
  460. }
  461. }
  462. $oResult->AddObject($iCode, $sPlanned, $oToDelete, array('id', 'friendlyname'));
  463. }
  464. }
  465. foreach ($oDeletionPlan->ListUpdates() as $sRemoteClass => $aToUpdate)
  466. {
  467. foreach ($aToUpdate as $iId => $aData)
  468. {
  469. $oToUpdate = $aData['to_reset'];
  470. if (array_key_exists('issue', $aData))
  471. {
  472. $iCode = RestDelete::AUTO_UPDATE_ISSUE;
  473. $sPlanned = 'Should be updated automatically... but: '.$aData['issue'];
  474. }
  475. else
  476. {
  477. $iCode = RestDelete::AUTO_UPDATE;
  478. $sPlanned = 'Reset external keys: '.$aData['attributes_list'];
  479. }
  480. $oResult->AddObject($iCode, $sPlanned, $oToUpdate, array('id', 'friendlyname'));
  481. }
  482. }
  483. if ($oDeletionPlan->FoundStopper())
  484. {
  485. if ($oDeletionPlan->FoundSecurityIssue())
  486. {
  487. $iRes = RestResult::UNAUTHORIZED;
  488. $sRes = 'Deletion not allowed on some objects';
  489. }
  490. elseif ($oDeletionPlan->FoundManualOperation())
  491. {
  492. $iRes = RestResult::UNSAFE;
  493. $sRes = 'The deletion requires that other objects be deleted/updated, and those operations must be requested explicitely';
  494. }
  495. else
  496. {
  497. $iRes = RestResult::INTERNAL_ERROR;
  498. $sRes = 'Some issues have been encountered. See the list of planned changes for more information about the issue(s).';
  499. }
  500. }
  501. else
  502. {
  503. $iRes = RestResult::OK;
  504. $sRes = 'Deleted: '.count($aObjects);
  505. $iIndirect = $oDeletionPlan->GetTargetCount() - count($aObjects);
  506. if ($iIndirect > 0)
  507. {
  508. $sRes .= ' plus (for DB integrity) '.$iIndirect;
  509. }
  510. }
  511. $oResult->code = $iRes;
  512. if ($bSimulate)
  513. {
  514. $oResult->message = 'SIMULATING: '.$sRes;
  515. }
  516. else
  517. {
  518. $oResult->message = $sRes;
  519. }
  520. }
  521. /**
  522. * Helper function to get the related objects up to the given depth along with the "graph" of the relation
  523. * @param DBObject $oObject Starting point of the computation
  524. * @param string $sRelation Code of the relation (i.e; 'impact', 'depends on'...)
  525. * @param integer $iMaxRecursionDepth Maximum level of recursion
  526. * @param Hash $aRelated Two dimensions hash of the already related objects: array( 'class' => array(key => ))
  527. * @param Hash $aGraph Hash array for the topology of the relation: source => related: array('class:key' => array( DBObjects ))
  528. * @param integer $iRecursionDepth Current level of recursion
  529. */
  530. protected function GetRelatedObjects(DBObject $oObject, $sRelation, $iMaxRecursionDepth, &$aRelated, &$aGraph, $iRecursionDepth = 1)
  531. {
  532. // Avoid loops
  533. if ((array_key_exists(get_class($oObject), $aRelated)) && (array_key_exists($oObject->GetKey(), $aRelated[get_class($oObject)]))) return;
  534. // Stop at maximum recursion level
  535. if ($iRecursionDepth > $iMaxRecursionDepth) return;
  536. $sSrcKey = get_class($oObject).'::'.$oObject->GetKey();
  537. $aNewRelated = array();
  538. $oObject->GetRelatedObjects($sRelation, 1, $aNewRelated);
  539. foreach($aNewRelated as $sClass => $aObjects)
  540. {
  541. if (!array_key_exists($sSrcKey, $aGraph))
  542. {
  543. $aGraph[$sSrcKey] = array();
  544. }
  545. foreach($aObjects as $oRelatedObject)
  546. {
  547. $aRelated[$sClass][$oRelatedObject->GetKey()] = $oRelatedObject;
  548. $aGraph[$sSrcKey][] = get_class($oRelatedObject).'::'.$oRelatedObject->GetKey();
  549. $this->GetRelatedObjects($oRelatedObject, $sRelation, $iMaxRecursionDepth, $aRelated, $aGraph, $iRecursionDepth+1);
  550. }
  551. }
  552. }
  553. }