restservices.class.inc.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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. elseif ($oAttDef->IsExternalKey())
  96. {
  97. $value = $oObject->Get($sAttCode);
  98. }
  99. else
  100. {
  101. // Still to be refined...
  102. $value = $oObject->GetEditValue($sAttCode);
  103. }
  104. }
  105. return $value;
  106. }
  107. /**
  108. * Report the value for the given object attribute
  109. *
  110. * @param DBObject $oObject The object being reported
  111. * @param string $sAttCode The attribute code (must be valid)
  112. * @return void
  113. */
  114. public function AddField(DBObject $oObject, $sAttCode)
  115. {
  116. $this->fields[$sAttCode] = $this->MakeResultValue($oObject, $sAttCode);
  117. }
  118. }
  119. /**
  120. * REST response for services managing objects. Derive this structure to add information and/or constants
  121. *
  122. * @package Extensibility
  123. * @package REST Services
  124. * @api
  125. */
  126. class RestResultWithObjects extends RestResult
  127. {
  128. public $objects;
  129. /**
  130. * Report the given object
  131. *
  132. * @param int An error code (RestResult::OK is no issue has been found)
  133. * @param string $sMessage Description of the error if any, an empty string otherwise
  134. * @param DBObject $oObject The object being reported
  135. * @param array $aFields An array of attribute codes. List of the attributes to be reported.
  136. * @return void
  137. */
  138. public function AddObject($iCode, $sMessage, $oObject = null, $aFields = null)
  139. {
  140. $oObjRes = new ObjectResult();
  141. $oObjRes->code = $iCode;
  142. $oObjRes->message = $sMessage;
  143. if ($oObject)
  144. {
  145. $oObjRes->class = get_class($oObject);
  146. foreach ($aFields as $sAttCode)
  147. {
  148. $oObjRes->AddField($oObject, $sAttCode);
  149. }
  150. }
  151. $this->objects[] = $oObjRes;
  152. }
  153. }
  154. class RestResultWithRelations extends RestResultWithObjects
  155. {
  156. public $relations;
  157. public function __construct()
  158. {
  159. parent::__construct();
  160. $this->relations = array();
  161. }
  162. public function AddRelation($sSrcKey, $sDestKey)
  163. {
  164. if (!array_key_exists($sSrcKey, $this->relations))
  165. {
  166. $this->relations[$sSrcKey] = array();
  167. }
  168. $this->relations[$sSrcKey][] = $sDestKey;
  169. }
  170. }
  171. /**
  172. * Deletion result codes for a target object (either deleted or updated)
  173. *
  174. * @package Extensibility
  175. * @api
  176. * @since 2.0.1
  177. */
  178. class RestDelete
  179. {
  180. /**
  181. * Result: Object deleted as per the initial request
  182. */
  183. const OK = 0;
  184. /**
  185. * Result: general issue (user rights or ... ?)
  186. */
  187. const ISSUE = 1;
  188. /**
  189. * Result: Must be deleted to preserve database integrity
  190. */
  191. const AUTO_DELETE = 2;
  192. /**
  193. * Result: Must be deleted to preserve database integrity, but that is NOT possible
  194. */
  195. const AUTO_DELETE_ISSUE = 3;
  196. /**
  197. * Result: Must be deleted to preserve database integrity, but this must be requested explicitely
  198. */
  199. const REQUEST_EXPLICITELY = 4;
  200. /**
  201. * Result: Must be updated to preserve database integrity
  202. */
  203. const AUTO_UPDATE = 5;
  204. /**
  205. * Result: Must be updated to preserve database integrity, but that is NOT possible
  206. */
  207. const AUTO_UPDATE_ISSUE = 6;
  208. }
  209. /**
  210. * Implementation of core REST services (create/get/update... objects)
  211. *
  212. * @package Core
  213. */
  214. class CoreServices implements iRestServiceProvider
  215. {
  216. /**
  217. * Enumerate services delivered by this class
  218. *
  219. * @param string $sVersion The version (e.g. 1.0) supported by the services
  220. * @return array An array of hash 'verb' => verb, 'description' => description
  221. */
  222. public function ListOperations($sVersion)
  223. {
  224. $aOps = array();
  225. if ($sVersion == '1.0')
  226. {
  227. $aOps[] = array(
  228. 'verb' => 'core/create',
  229. 'description' => 'Create an object'
  230. );
  231. $aOps[] = array(
  232. 'verb' => 'core/update',
  233. 'description' => 'Update an object'
  234. );
  235. $aOps[] = array(
  236. 'verb' => 'core/apply_stimulus',
  237. 'description' => 'Apply a stimulus to change the state of an object'
  238. );
  239. $aOps[] = array(
  240. 'verb' => 'core/get',
  241. 'description' => 'Search for objects'
  242. );
  243. $aOps[] = array(
  244. 'verb' => 'core/delete',
  245. 'description' => 'Delete objects'
  246. );
  247. $aOps[] = array(
  248. 'verb' => 'core/get_related',
  249. 'description' => 'Get related objects through the specified relation'
  250. );
  251. }
  252. return $aOps;
  253. }
  254. /**
  255. * Enumerate services delivered by this class
  256. * @param string $sVersion The version (e.g. 1.0) supported by the services
  257. * @return RestResult The standardized result structure (at least a message)
  258. * @throws Exception in case of internal failure.
  259. */
  260. public function ExecOperation($sVersion, $sVerb, $aParams)
  261. {
  262. $oResult = new RestResultWithObjects();
  263. switch ($sVerb)
  264. {
  265. case 'core/create':
  266. RestUtils::InitTrackingComment($aParams);
  267. $sClass = RestUtils::GetClass($aParams, 'class');
  268. $aFields = RestUtils::GetMandatoryParam($aParams, 'fields');
  269. $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields');
  270. $oObject = RestUtils::MakeObjectFromFields($sClass, $aFields);
  271. $oObject->DBInsert();
  272. $oResult->AddObject(0, 'created', $oObject, $aShowFields);
  273. break;
  274. case 'core/update':
  275. RestUtils::InitTrackingComment($aParams);
  276. $sClass = RestUtils::GetClass($aParams, 'class');
  277. $key = RestUtils::GetMandatoryParam($aParams, 'key');
  278. $aFields = RestUtils::GetMandatoryParam($aParams, 'fields');
  279. $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields');
  280. $oObject = RestUtils::FindObjectFromKey($sClass, $key);
  281. RestUtils::UpdateObjectFromFields($oObject, $aFields);
  282. $oObject->DBUpdate();
  283. $oResult->AddObject(0, 'updated', $oObject, $aShowFields);
  284. break;
  285. case 'core/apply_stimulus':
  286. RestUtils::InitTrackingComment($aParams);
  287. $sClass = RestUtils::GetClass($aParams, 'class');
  288. $key = RestUtils::GetMandatoryParam($aParams, 'key');
  289. $aFields = RestUtils::GetMandatoryParam($aParams, 'fields');
  290. $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields');
  291. $sStimulus = RestUtils::GetMandatoryParam($aParams, 'stimulus');
  292. $oObject = RestUtils::FindObjectFromKey($sClass, $key);
  293. RestUtils::UpdateObjectFromFields($oObject, $aFields);
  294. $aTransitions = $oObject->EnumTransitions();
  295. $aStimuli = MetaModel::EnumStimuli(get_class($oObject));
  296. if (!isset($aTransitions[$sStimulus]))
  297. {
  298. // Invalid stimulus
  299. $oResult->code = RestResult::INTERNAL_ERROR;
  300. $oResult->message = "Invalid stimulus: '$sStimulus' on the object ".$oObject->GetName()." in state '".$oObject->GetState()."'";
  301. }
  302. else
  303. {
  304. $aTransition = $aTransitions[$sStimulus];
  305. $sTargetState = $aTransition['target_state'];
  306. $aStates = MetaModel::EnumStates($sClass);
  307. $aTargetStateDef = $aStates[$sTargetState];
  308. $aExpectedAttributes = $aTargetStateDef['attribute_list'];
  309. $aMissingMandatory = array();
  310. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  311. {
  312. if ( ($iExpectCode & OPT_ATT_MANDATORY) && ($oObject->Get($sAttCode) == ''))
  313. {
  314. $aMissingMandatory[] = $sAttCode;
  315. }
  316. }
  317. if (count($aMissingMandatory) == 0)
  318. {
  319. // If all the mandatory fields are already present, just apply the transition silently...
  320. if ($oObject->ApplyStimulus($sStimulus))
  321. {
  322. $oObject->DBUpdate();
  323. $oResult->AddObject(0, 'updated', $oObject, $aShowFields);
  324. }
  325. }
  326. else
  327. {
  328. // Missing mandatory attributes for the transition
  329. $oResult->code = RestResult::INTERNAL_ERROR;
  330. $oResult->message = 'Missing mandatory attribute(s) for applying the stimulus: '.implode(', ', $aMissingMandatory).'.';
  331. }
  332. }
  333. break;
  334. case 'core/get':
  335. $sClass = RestUtils::GetClass($aParams, 'class');
  336. $key = RestUtils::GetMandatoryParam($aParams, 'key');
  337. $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields');
  338. $oObjectSet = RestUtils::GetObjectSetFromKey($sClass, $key);
  339. while ($oObject = $oObjectSet->Fetch())
  340. {
  341. $oResult->AddObject(0, '', $oObject, $aShowFields);
  342. }
  343. $oResult->message = "Found: ".$oObjectSet->Count();
  344. break;
  345. case 'core/delete':
  346. $sClass = RestUtils::GetClass($aParams, 'class');
  347. $key = RestUtils::GetMandatoryParam($aParams, 'key');
  348. $bSimulate = RestUtils::GetOptionalParam($aParams, 'simulate', false);
  349. $oObjectSet = RestUtils::GetObjectSetFromKey($sClass, $key);
  350. $aObjects = $oObjectSet->ToArray();
  351. $this->DeleteObjects($oResult, $aObjects, $bSimulate);
  352. break;
  353. case 'core/get_related':
  354. $oResult = new RestResultWithRelations();
  355. $sClass = RestUtils::GetClass($aParams, 'class');
  356. $key = RestUtils::GetMandatoryParam($aParams, 'key');
  357. $sRelation = RestUtils::GetMandatoryParam($aParams, 'relation');
  358. $iMaxRecursionDepth = RestUtils::GetOptionalParam($aParams, 'depth', 20 /* = MAX_RECUSTION_DEPTH */);
  359. $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields');
  360. $oObjectSet = RestUtils::GetObjectSetFromKey($sClass, $key);
  361. while ($oObject = $oObjectSet->Fetch())
  362. {
  363. $aRelated = array();
  364. $aGraph = array();
  365. $oResult->AddObject(0, '', $oObject, $aShowFields);
  366. $this->GetRelatedObjects($oObject, $sRelation, $iMaxRecursionDepth, $aRelated, $aGraph);
  367. foreach($aRelated as $sClass => $aObjects)
  368. {
  369. foreach($aObjects as $oRelatedObj)
  370. {
  371. $oResult->AddObject(0, '', $oRelatedObj, $aShowFields);
  372. }
  373. }
  374. foreach($aGraph as $sSrcKey => $sDestKey)
  375. {
  376. $oResult->AddRelation($sSrcKey, $sDestKey);
  377. }
  378. }
  379. $oResult->message = "Found: ".$oObjectSet->Count();
  380. break;
  381. default:
  382. // unknown operation: handled at a higher level
  383. }
  384. return $oResult;
  385. }
  386. /**
  387. * Helper for object deletion
  388. */
  389. public function DeleteObjects($oResult, $aObjects, $bSimulate)
  390. {
  391. $oDeletionPlan = new DeletionPlan();
  392. foreach($aObjects as $oObj)
  393. {
  394. if ($bSimulate)
  395. {
  396. $oObj->CheckToDelete($oDeletionPlan);
  397. }
  398. else
  399. {
  400. $oObj->DBDelete($oDeletionPlan);
  401. }
  402. }
  403. foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes)
  404. {
  405. foreach ($aDeletes as $iId => $aData)
  406. {
  407. $oToDelete = $aData['to_delete'];
  408. $bAutoDel = (($aData['mode'] == DEL_SILENT) || ($aData['mode'] == DEL_AUTO));
  409. if (array_key_exists('issue', $aData))
  410. {
  411. if ($bAutoDel)
  412. {
  413. if (isset($aData['requested_explicitely'])) // i.e. in the initial list of objects to delete
  414. {
  415. $iCode = RestDelete::ISSUE;
  416. $sPlanned = 'Cannot be deleted: '.$aData['issue'];
  417. }
  418. else
  419. {
  420. $iCode = RestDelete::AUTO_DELETE_ISSUE;
  421. $sPlanned = 'Should be deleted automatically... but: '.$aData['issue'];
  422. }
  423. }
  424. else
  425. {
  426. $iCode = RestDelete::REQUEST_EXPLICITELY;
  427. $sPlanned = 'Must be deleted explicitely... but: '.$aData['issue'];
  428. }
  429. }
  430. else
  431. {
  432. if ($bAutoDel)
  433. {
  434. if (isset($aData['requested_explicitely']))
  435. {
  436. $iCode = RestDelete::OK;
  437. $sPlanned = '';
  438. }
  439. else
  440. {
  441. $iCode = RestDelete::AUTO_DELETE;
  442. $sPlanned = 'Deleted automatically';
  443. }
  444. }
  445. else
  446. {
  447. $iCode = RestDelete::REQUEST_EXPLICITELY;
  448. $sPlanned = 'Must be deleted explicitely';
  449. }
  450. }
  451. $oResult->AddObject($iCode, $sPlanned, $oToDelete, array('id', 'friendlyname'));
  452. }
  453. }
  454. foreach ($oDeletionPlan->ListUpdates() as $sRemoteClass => $aToUpdate)
  455. {
  456. foreach ($aToUpdate as $iId => $aData)
  457. {
  458. $oToUpdate = $aData['to_reset'];
  459. if (array_key_exists('issue', $aData))
  460. {
  461. $iCode = RestDelete::AUTO_UPDATE_ISSUE;
  462. $sPlanned = 'Should be updated automatically... but: '.$aData['issue'];
  463. }
  464. else
  465. {
  466. $iCode = RestDelete::AUTO_UPDATE;
  467. $sPlanned = 'Reset external keys: '.$aData['attributes_list'];
  468. }
  469. $oResult->AddObject($iCode, $sPlanned, $oToUpdate, array('id', 'friendlyname'));
  470. }
  471. }
  472. if ($oDeletionPlan->FoundStopper())
  473. {
  474. if ($oDeletionPlan->FoundSecurityIssue())
  475. {
  476. $iRes = RestResult::UNAUTHORIZED;
  477. $sRes = 'Deletion not allowed on some objects';
  478. }
  479. elseif ($oDeletionPlan->FoundManualOperation())
  480. {
  481. $iRes = RestResult::UNSAFE;
  482. $sRes = 'The deletion requires that other objects be deleted/updated, and those operations must be requested explicitely';
  483. }
  484. else
  485. {
  486. $iRes = RestResult::INTERNAL_ERROR;
  487. $sRes = 'Some issues have been encountered. See the list of planned changes for more information about the issue(s).';
  488. }
  489. }
  490. else
  491. {
  492. $iRes = RestResult::OK;
  493. $sRes = 'Deleted: '.count($aObjects);
  494. $iIndirect = $oDeletionPlan->GetTargetCount() - count($aObjects);
  495. if ($iIndirect > 0)
  496. {
  497. $sRes .= ' plus (for DB integrity) '.$iIndirect;
  498. }
  499. }
  500. $oResult->code = $iRes;
  501. if ($bSimulate)
  502. {
  503. $oResult->message = 'SIMULATING: '.$sRes;
  504. }
  505. else
  506. {
  507. $oResult->message = $sRes;
  508. }
  509. }
  510. /**
  511. * Helper function to get the related objects up to the given depth along with the "graph" of the relation
  512. * @param DBObject $oObject Starting point of the computation
  513. * @param string $sRelation Code of the relation (i.e; 'impact', 'depends on'...)
  514. * @param integer $iMaxRecursionDepth Maximum level of recursion
  515. * @param Hash $aRelated Two dimensions hash of the already related objects: array( 'class' => array(key => ))
  516. * @param Hash $aGraph Hash array for the topology of the relation: source => related: array('class:key' => array( DBObjects ))
  517. * @param integer $iRecursionDepth Current level of recursion
  518. */
  519. protected function GetRelatedObjects(DBObject $oObject, $sRelation, $iMaxRecursionDepth, &$aRelated, &$aGraph, $iRecursionDepth = 1)
  520. {
  521. // Avoid loops
  522. if ((array_key_exists(get_class($oObject), $aRelated)) && (array_key_exists($oObject->GetKey(), $aRelated[get_class($oObject)]))) return;
  523. // Stop at maximum recursion level
  524. if ($iRecursionDepth > $iMaxRecursionDepth) return;
  525. $sSrcKey = get_class($oObject).'::'.$oObject->GetKey();
  526. $aNewRelated = array();
  527. $oObject->GetRelatedObjects($sRelation, 1, $aNewRelated);
  528. foreach($aNewRelated as $sClass => $aObjects)
  529. {
  530. if (!array_key_exists($sSrcKey, $aGraph))
  531. {
  532. $aGraph[$sSrcKey] = array();
  533. }
  534. foreach($aObjects as $oRelatedObject)
  535. {
  536. $aRelated[$sClass][$oRelatedObject->GetKey()] = $oRelatedObject;
  537. $aGraph[$sSrcKey][] = get_class($oRelatedObject).'::'.$oRelatedObject->GetKey();
  538. $this->GetRelatedObjects($oRelatedObject, $sRelation, $iMaxRecursionDepth, $aRelated, $aGraph, $iRecursionDepth+1);
  539. }
  540. }
  541. }
  542. }