applicationextension.inc.php 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  1. <?php
  2. // Copyright (C) 2010-2015 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. * Management of application plugins
  20. *
  21. * Definition of interfaces that can be implemented to customize iTop.
  22. * You may implement such interfaces in a module file (e.g. main.mymodule.php)
  23. *
  24. * @package Extensibility
  25. * @copyright Copyright (C) 2010-2012 Combodo SARL
  26. * @license http://opensource.org/licenses/AGPL-3.0
  27. * @api
  28. */
  29. /**
  30. * Implement this interface to change the behavior of the GUI for some objects.
  31. *
  32. * All methods are invoked by iTop for a given object. There are basically two usages:
  33. *
  34. * 1) To tweak the form of an object, you will have to implement a specific behavior within:
  35. *
  36. * * OnDisplayProperties (bEditMode = true)
  37. * * OnFormSubmit
  38. * * OnFormCancel
  39. *
  40. * 2) To tune the display of the object details, you can use:
  41. *
  42. * * OnDisplayProperties
  43. * * OnDisplayRelations
  44. * * GetIcon
  45. * * GetHilightClass
  46. *
  47. * Please note that some of the APIs can be called several times for a single page displayed.
  48. * Therefore it is not recommended to perform too many operations, such as querying the database.
  49. * A recommended pattern is to cache data by the mean of static members.
  50. *
  51. * @package Extensibility
  52. * @api
  53. */
  54. interface iApplicationUIExtension
  55. {
  56. /**
  57. * Invoked when an object is being displayed (wiew or edit)
  58. *
  59. * The method is called right after the main tab has been displayed.
  60. * You can add output to the page, either to change the display, or to add a form input
  61. *
  62. * Example:
  63. * <code>
  64. * if ($bEditMode)
  65. * {
  66. * $oPage->p('Age of the captain: &lt;input type="text" name="captain_age"/&gt;');
  67. * }
  68. * else
  69. * {
  70. * $oPage->p('Age of the captain: '.$iCaptainAge);
  71. * }
  72. * </code>
  73. *
  74. * @param DBObject $oObject The object being displayed
  75. * @param WebPage $oPage The output context
  76. * @param boolean $bEditMode True if the edition form is being displayed
  77. * @return void
  78. */
  79. public function OnDisplayProperties($oObject, WebPage $oPage, $bEditMode = false);
  80. /**
  81. * Invoked when an object is being displayed (wiew or edit)
  82. *
  83. * The method is called rigth after all the tabs have been displayed
  84. *
  85. * @param DBObject $oObject The object being displayed
  86. * @param WebPage $oPage The output context
  87. * @param boolean $bEditMode True if the edition form is being displayed
  88. * @return void
  89. */
  90. public function OnDisplayRelations($oObject, WebPage $oPage, $bEditMode = false);
  91. /**
  92. * Invoked when the end-user clicks on Modify from the object edition form
  93. *
  94. * The method is called after the changes from the standard form have been
  95. * taken into account, and before saving the changes into the database.
  96. *
  97. * @param DBObject $oObject The object being edited
  98. * @param string $sFormPrefix Prefix given to the HTML form inputs
  99. * @return void
  100. */
  101. public function OnFormSubmit($oObject, $sFormPrefix = '');
  102. /**
  103. * Invoked when the end-user clicks on Cancel from the object edition form
  104. *
  105. * Implement here any cleanup. This is necessary when you have injected some
  106. * javascript into the edition form, and if that code requires to store temporary data
  107. * (this is the case when a file must be uploaded).
  108. *
  109. * @param string $sTempId Unique temporary identifier made of session_id and transaction_id. It identifies the object in a unique way.
  110. * @return void
  111. */
  112. public function OnFormCancel($sTempId);
  113. /**
  114. * Not yet called by the framework!
  115. *
  116. * Sorry, the verb has been reserved. You must implement it, but it is not called as of now.
  117. *
  118. * @param DBObject $oObject The object being displayed
  119. * @return type desc
  120. */
  121. public function EnumUsedAttributes($oObject); // Not yet implemented
  122. /**
  123. * Not yet called by the framework!
  124. *
  125. * Sorry, the verb has been reserved. You must implement it, but it is not called as of now.
  126. *
  127. * @param DBObject $oObject The object being displayed
  128. * @return string Path of the icon, relative to the modules directory.
  129. */
  130. public function GetIcon($oObject); // Not yet implemented
  131. /**
  132. * Invoked when the object is displayed alone or within a list
  133. *
  134. * Returns a value influencing the appearance of the object depending on its
  135. * state.
  136. *
  137. * Possible values are:
  138. *
  139. * * HILIGHT_CLASS_CRITICAL
  140. * * HILIGHT_CLASS_WARNING
  141. * * HILIGHT_CLASS_OK
  142. * * HILIGHT_CLASS_NONE
  143. *
  144. * @param DBObject $oObject The object being displayed
  145. * @return integer The value representing the mood of the object
  146. */
  147. public function GetHilightClass($oObject);
  148. /**
  149. * Called when building the Actions menu for a single object or a list of objects
  150. *
  151. * Use this to add items to the Actions menu. You will have to specify a label and an URL.
  152. *
  153. * Example:
  154. * <code>
  155. * $oObject = $oSet->fetch();
  156. * if ($oObject instanceof Sheep)
  157. * {
  158. * return array('View in my app' => 'http://myserver/view_sheeps?id='.$oObject->Get('name'));
  159. * }
  160. * else
  161. * {
  162. * return array();
  163. * }
  164. * </code>
  165. *
  166. * See also iPopupMenuExtension for greater flexibility
  167. *
  168. * @param DBObjectSet $oSet A set of persistent objects (DBObject)
  169. * @return string[string]
  170. */
  171. public function EnumAllowedActions(DBObjectSet $oSet);
  172. }
  173. /**
  174. * Implement this interface to perform specific things when objects are manipulated
  175. *
  176. * Note that those methods will be called when objects are manipulated, either in a programmatic way
  177. * or through the GUI.
  178. *
  179. * @package Extensibility
  180. * @api
  181. */
  182. interface iApplicationObjectExtension
  183. {
  184. /**
  185. * Invoked to determine wether an object has been modified in memory
  186. *
  187. * The GUI calls this verb to determine the message that will be displayed to the end-user.
  188. * Anyhow, this API can be called in other contexts such as the CSV import tool.
  189. *
  190. * If the extension returns false, then the framework will perform the usual evaluation.
  191. * Otherwise, the answer is definitively "yes, the object has changed".
  192. *
  193. * @param DBObject $oObject The target object
  194. * @return boolean True if something has changed for the target object
  195. */
  196. public function OnIsModified($oObject);
  197. /**
  198. * Invoked to determine wether an object can be written to the database
  199. *
  200. * The GUI calls this verb and reports any issue.
  201. * Anyhow, this API can be called in other contexts such as the CSV import tool.
  202. *
  203. * @param DBObject $oObject The target object
  204. * @return string[] A list of errors message. An error message is made of one line and it can be displayed to the end-user.
  205. */
  206. public function OnCheckToWrite($oObject);
  207. /**
  208. * Invoked to determine wether an object can be deleted from the database
  209. *
  210. * The GUI calls this verb and stops the deletion process if any issue is reported.
  211. *
  212. * Please not that it is not possible to cascade deletion by this mean: only stopper issues can be handled.
  213. *
  214. * @param DBObject $oObject The target object
  215. * @return string[] A list of errors message. An error message is made of one line and it can be displayed to the end-user.
  216. */
  217. public function OnCheckToDelete($oObject);
  218. /**
  219. * Invoked when an object is updated into the database
  220. *
  221. * The method is called right <b>after</b> the object has been written to the database.
  222. *
  223. * @param DBObject $oObject The target object
  224. * @param CMDBChange|null $oChange A change context. Since 2.0 it is fine to ignore it, as the framework does maintain this information once for all the changes made within the current page
  225. * @return void
  226. */
  227. public function OnDBUpdate($oObject, $oChange = null);
  228. /**
  229. * Invoked when an object is created into the database
  230. *
  231. * The method is called right <b>after</b> the object has been written to the database.
  232. *
  233. * @param DBObject $oObject The target object
  234. * @param CMDBChange|null $oChange A change context. Since 2.0 it is fine to ignore it, as the framework does maintain this information once for all the changes made within the current page
  235. * @return void
  236. */
  237. public function OnDBInsert($oObject, $oChange = null);
  238. /**
  239. * Invoked when an object is deleted from the database
  240. *
  241. * The method is called right <b>before</b> the object will be deleted from the database.
  242. *
  243. * @param DBObject $oObject The target object
  244. * @param CMDBChange|null $oChange A change context. Since 2.0 it is fine to ignore it, as the framework does maintain this information once for all the changes made within the current page
  245. * @return void
  246. */
  247. public function OnDBDelete($oObject, $oChange = null);
  248. }
  249. /**
  250. * New extension to add menu items in the "popup" menus inside iTop. Provides a greater flexibility than
  251. * iApplicationUIExtension::EnumAllowedActions.
  252. *
  253. * To add some menus into iTop, declare a class that implements this interface, it will be called automatically
  254. * by the application, as long as the class definition is included somewhere in the code
  255. *
  256. * @package Extensibility
  257. * @api
  258. * @since 2.0
  259. */
  260. interface iPopupMenuExtension
  261. {
  262. /**
  263. * Insert an item into the Actions menu of a list
  264. *
  265. * $param is a DBObjectSet containing the list of objects
  266. */
  267. const MENU_OBJLIST_ACTIONS = 1;
  268. /**
  269. * Insert an item into the Toolkit menu of a list
  270. *
  271. * $param is a DBObjectSet containing the list of objects
  272. */
  273. const MENU_OBJLIST_TOOLKIT = 2;
  274. /**
  275. * Insert an item into the Actions menu on an object details page
  276. *
  277. * $param is a DBObject instance: the object currently displayed
  278. */
  279. const MENU_OBJDETAILS_ACTIONS = 3;
  280. /**
  281. * Insert an item into the Dashboard menu
  282. *
  283. * The dashboad menu is shown on the top right corner when a dashboard
  284. * is being displayed.
  285. *
  286. * $param is a Dashboard instance: the dashboard currently displayed
  287. */
  288. const MENU_DASHBOARD_ACTIONS = 4;
  289. /**
  290. * Insert an item into the User menu (upper right corner)
  291. *
  292. * $param is null
  293. */
  294. const MENU_USER_ACTIONS = 5;
  295. /**
  296. * Insert an item into the Action menu on an object details page in the portal
  297. *
  298. * $param is an array('portal_id' => $sPortalId, 'object' => $oObject) containing the portal id and a DBObject instance (the object currently displayed)
  299. */
  300. const PORTAL_OBJDETAILS_ACTIONS = 7;
  301. /**
  302. * Insert an item into the Actions menu of a list in the portal
  303. * Note: This is not implemented yet !
  304. *
  305. * $param is an array('portal_id' => $sPortalId, 'object_set' => $oSet) containing DBObjectSet containing the list of objects
  306. * @todo
  307. */
  308. const PORTAL_OBJLIST_ACTIONS = 6;
  309. /**
  310. * Insert an item into the user menu of the portal
  311. * Note: This is not implemented yet !
  312. *
  313. * $param is the portal id
  314. * @todo
  315. */
  316. const PORTAL_USER_ACTIONS = 8;
  317. /**
  318. * Insert an item into the navigation menu of the portal
  319. * Note: This is not implemented yet !
  320. *
  321. * $param is the portal id
  322. * @todo
  323. */
  324. const PORTAL_MENU_ACTIONS = 9;
  325. /**
  326. * Get the list of items to be added to a menu.
  327. *
  328. * This method is called by the framework for each menu.
  329. * The items will be inserted in the menu in the order of the returned array.
  330. * @param int $iMenuId The identifier of the type of menu, as listed by the constants MENU_xxx
  331. * @param mixed $param Depends on $iMenuId, see the constants defined above
  332. * @return object[] An array of ApplicationPopupMenuItem or an empty array if no action is to be added to the menu
  333. */
  334. public static function EnumItems($iMenuId, $param);
  335. }
  336. /**
  337. * Base class for the various types of custom menus
  338. *
  339. * @package Extensibility
  340. * @internal
  341. * @since 2.0
  342. */
  343. abstract class ApplicationPopupMenuItem
  344. {
  345. /** @ignore */
  346. protected $sUID;
  347. /** @ignore */
  348. protected $sLabel;
  349. /** @ignore */
  350. protected $aCssClasses;
  351. /**
  352. * Constructor
  353. *
  354. * @param string $sUID The unique identifier of this menu in iTop... make sure you pass something unique enough
  355. * @param string $sLabel The display label of the menu (must be localized)
  356. * @param array $aCssClasses The CSS classes to add to the menu
  357. */
  358. public function __construct($sUID, $sLabel)
  359. {
  360. $this->sUID = $sUID;
  361. $this->sLabel = $sLabel;
  362. $this->aCssClasses = array();
  363. }
  364. /**
  365. * Get the UID
  366. *
  367. * @return string The unique identifier
  368. * @ignore
  369. */
  370. public function GetUID()
  371. {
  372. return $this->sUID;
  373. }
  374. /**
  375. * Get the label
  376. *
  377. * @return string The label
  378. * @ignore
  379. */
  380. public function GetLabel()
  381. {
  382. return $this->sLabel;
  383. }
  384. /**
  385. * Get the CSS classes
  386. *
  387. * @return array
  388. * @ignore
  389. */
  390. public function GetCssClasses()
  391. {
  392. return $this->aCssClasses;
  393. }
  394. /**
  395. * @param $aCssClasses
  396. */
  397. public function SetCssClasses($aCssClasses)
  398. {
  399. $this->aCssClasses = $aCssClasses;
  400. }
  401. /**
  402. * Adds a CSS class to the CSS classes that will be put on the menu item
  403. *
  404. * @param $sCssClass
  405. */
  406. public function AddCssClass($sCssClass)
  407. {
  408. $this->aCssClasses[] = $sCssClass;
  409. }
  410. /**
  411. * Returns the components to create a popup menu item in HTML
  412. * @return Hash A hash array: array('label' => , 'url' => , 'target' => , 'onclick' => )
  413. * @ignore
  414. */
  415. abstract public function GetMenuItem();
  416. /** @ignore */
  417. public function GetLinkedScripts()
  418. {
  419. return array();
  420. }
  421. }
  422. /**
  423. * Class for adding an item into a popup menu that browses to the given URL
  424. *
  425. * @package Extensibility
  426. * @api
  427. * @since 2.0
  428. */
  429. class URLPopupMenuItem extends ApplicationPopupMenuItem
  430. {
  431. /** @ignore */
  432. protected $sURL;
  433. /** @ignore */
  434. protected $sTarget;
  435. /**
  436. * Constructor
  437. *
  438. * @param string $sUID The unique identifier of this menu in iTop... make sure you pass something unique enough
  439. * @param string $sLabel The display label of the menu (must be localized)
  440. * @param string $sURL If the menu is an hyperlink, provide the absolute hyperlink here
  441. * @param string $sTarget In case the menu is an hyperlink and a specific target is needed (_blank for example), pass it here
  442. */
  443. public function __construct($sUID, $sLabel, $sURL, $sTarget = '_top')
  444. {
  445. parent::__construct($sUID, $sLabel);
  446. $this->sURL = $sURL;
  447. $this->sTarget = $sTarget;
  448. }
  449. /** @ignore */
  450. public function GetMenuItem()
  451. {
  452. return array ('label' => $this->GetLabel(), 'url' => $this->sURL, 'target' => $this->sTarget, 'css_classes' => $this->aCssClasses);
  453. }
  454. }
  455. /**
  456. * Class for adding an item into a popup menu that triggers some Javascript code
  457. *
  458. * @package Extensibility
  459. * @api
  460. * @since 2.0
  461. */
  462. class JSPopupMenuItem extends ApplicationPopupMenuItem
  463. {
  464. /** @ignore */
  465. protected $sJSCode;
  466. /** @ignore */
  467. protected $aIncludeJSFiles;
  468. /**
  469. * Class for adding an item that triggers some Javascript code
  470. * @param string $sUID The unique identifier of this menu in iTop... make sure you pass something unique enough
  471. * @param string $sLabel The display label of the menu (must be localized)
  472. * @param string $sJSCode In case the menu consists in executing some havascript code inside the page, pass it here. If supplied $sURL ans $sTarget will be ignored
  473. * @param array $aIncludeJSFiles An array of file URLs to be included (once) to provide some JS libraries for the page.
  474. */
  475. public function __construct($sUID, $sLabel, $sJSCode, $aIncludeJSFiles = array())
  476. {
  477. parent::__construct($sUID, $sLabel);
  478. $this->sJSCode = $sJSCode;
  479. $this->aIncludeJSFiles = $aIncludeJSFiles;
  480. }
  481. /** @ignore */
  482. public function GetMenuItem()
  483. {
  484. // Note: the semicolumn is a must here!
  485. return array ('label' => $this->GetLabel(), 'onclick' => $this->sJSCode.'; return false;', 'url' => '#', 'css_classes' => $this->aCssClasses);
  486. }
  487. /** @ignore */
  488. public function GetLinkedScripts()
  489. {
  490. return $this->aIncludeJSFiles;
  491. }
  492. }
  493. /**
  494. * Class for adding a separator (horizontal line, not selectable) the output
  495. * will automatically reduce several consecutive separators to just one
  496. *
  497. * @package Extensibility
  498. * @api
  499. * @since 2.0
  500. */
  501. class SeparatorPopupMenuItem extends ApplicationPopupMenuItem
  502. {
  503. static $idx = 0;
  504. /**
  505. * Constructor
  506. */
  507. public function __construct()
  508. {
  509. parent::__construct('_separator_'.(self::$idx++), '');
  510. }
  511. /** @ignore */
  512. public function GetMenuItem()
  513. {
  514. return array ('label' => '<hr class="menu-separator">', 'url' => '', 'css_classes' => $this->aCssClasses);
  515. }
  516. }
  517. /**
  518. * Class for adding an item as a button that browses to the given URL
  519. *
  520. * @package Extensibility
  521. * @api
  522. * @since 2.0
  523. */
  524. class URLButtonItem extends URLPopupMenuItem
  525. {
  526. }
  527. /**
  528. * Class for adding an item as a button that runs some JS code
  529. *
  530. * @package Extensibility
  531. * @api
  532. * @since 2.0
  533. */
  534. class JSButtonItem extends JSPopupMenuItem
  535. {
  536. }
  537. /**
  538. * Implement this interface to add content to any iTopWebPage
  539. *
  540. * There are 3 places where content can be added:
  541. *
  542. * * The north pane: (normaly empty/hidden) at the top of the page, spanning the whole
  543. * width of the page
  544. * * The south pane: (normaly empty/hidden) at the bottom of the page, spanning the whole
  545. * width of the page
  546. * * The admin banner (two tones gray background) at the left of the global search.
  547. * Limited space, use it for short messages
  548. *
  549. * Each of the methods of this interface is supposed to return the HTML to be inserted at
  550. * the specified place and can use the passed iTopWebPage object to add javascript or CSS definitions
  551. *
  552. * @package Extensibility
  553. * @api
  554. * @since 2.0
  555. */
  556. interface iPageUIExtension
  557. {
  558. /**
  559. * Add content to the North pane
  560. * @param iTopWebPage $oPage The page to insert stuff into.
  561. * @return string The HTML content to add into the page
  562. */
  563. public function GetNorthPaneHtml(iTopWebPage $oPage);
  564. /**
  565. * Add content to the South pane
  566. * @param iTopWebPage $oPage The page to insert stuff into.
  567. * @return string The HTML content to add into the page
  568. */
  569. public function GetSouthPaneHtml(iTopWebPage $oPage);
  570. /**
  571. * Add content to the "admin banner"
  572. * @param iTopWebPage $oPage The page to insert stuff into.
  573. * @return string The HTML content to add into the page
  574. */
  575. public function GetBannerHtml(iTopWebPage $oPage);
  576. }
  577. /**
  578. * Implement this interface to add new operations to the REST/JSON web service
  579. *
  580. * @package Extensibility
  581. * @api
  582. * @since 2.0.1
  583. */
  584. interface iRestServiceProvider
  585. {
  586. /**
  587. * Enumerate services delivered by this class
  588. * @param string $sVersion The version (e.g. 1.0) supported by the services
  589. * @return array An array of hash 'verb' => verb, 'description' => description
  590. */
  591. public function ListOperations($sVersion);
  592. /**
  593. * Enumerate services delivered by this class
  594. * @param string $sVersion The version (e.g. 1.0) supported by the services
  595. * @return RestResult The standardized result structure (at least a message)
  596. * @throws Exception in case of internal failure.
  597. */
  598. public function ExecOperation($sVersion, $sVerb, $aParams);
  599. }
  600. /**
  601. * Minimal REST response structure. Derive this structure to add response data and error codes.
  602. *
  603. * @package Extensibility
  604. * @api
  605. * @since 2.0.1
  606. */
  607. class RestResult
  608. {
  609. /**
  610. * Result: no issue has been encountered
  611. */
  612. const OK = 0;
  613. /**
  614. * Result: missing/wrong credentials or the user does not have enough rights to perform the requested operation
  615. */
  616. const UNAUTHORIZED = 1;
  617. /**
  618. * Result: the parameter 'version' is missing
  619. */
  620. const MISSING_VERSION = 2;
  621. /**
  622. * Result: the parameter 'json_data' is missing
  623. */
  624. const MISSING_JSON = 3;
  625. /**
  626. * Result: the input structure is not a valid JSON string
  627. */
  628. const INVALID_JSON = 4;
  629. /**
  630. * Result: the parameter 'auth_user' is missing, authentication aborted
  631. */
  632. const MISSING_AUTH_USER = 5;
  633. /**
  634. * Result: the parameter 'auth_pwd' is missing, authentication aborted
  635. */
  636. const MISSING_AUTH_PWD = 6;
  637. /**
  638. * Result: no operation is available for the specified version
  639. */
  640. const UNSUPPORTED_VERSION = 10;
  641. /**
  642. * Result: the requested operation is not valid for the specified version
  643. */
  644. const UNKNOWN_OPERATION = 11;
  645. /**
  646. * Result: the requested operation cannot be performed because it can cause data (integrity) loss
  647. */
  648. const UNSAFE = 12;
  649. /**
  650. * Result: the operation could not be performed, see the message for troubleshooting
  651. */
  652. const INTERNAL_ERROR = 100;
  653. /**
  654. * Default constructor - ok!
  655. *
  656. * @param DBObject $oObject The object being reported
  657. * @param string $sAttCode The attribute code (must be valid)
  658. * @return string A scalar representation of the value
  659. */
  660. public function __construct()
  661. {
  662. $this->code = RestResult::OK;
  663. }
  664. public $code;
  665. public $message;
  666. }
  667. /**
  668. * Helpers for implementing REST services
  669. *
  670. * @package Extensibility
  671. * @api
  672. */
  673. class RestUtils
  674. {
  675. /**
  676. * Registering tracking information. Any further object modification be associated with the given comment, when the modification gets recorded into the DB
  677. *
  678. * @param StdClass $oData Structured input data. Must contain 'comment'.
  679. * @return void
  680. * @throws Exception
  681. * @api
  682. */
  683. public static function InitTrackingComment($oData)
  684. {
  685. $sComment = self::GetMandatoryParam($oData, 'comment');
  686. CMDBObject::SetTrackInfo($sComment);
  687. }
  688. /**
  689. * Read a mandatory parameter from from a Rest/Json structure.
  690. *
  691. * @param StdClass $oData Structured input data. Must contain the entry defined by sParamName.
  692. * @param string $sParamName Name of the parameter to fetch from the input data
  693. * @return void
  694. * @throws Exception If the parameter is missing
  695. * @api
  696. */
  697. public static function GetMandatoryParam($oData, $sParamName)
  698. {
  699. if (isset($oData->$sParamName))
  700. {
  701. return $oData->$sParamName;
  702. }
  703. else
  704. {
  705. throw new Exception("Missing parameter '$sParamName'");
  706. }
  707. }
  708. /**
  709. * Read an optional parameter from from a Rest/Json structure.
  710. *
  711. * @param StdClass $oData Structured input data.
  712. * @param string $sParamName Name of the parameter to fetch from the input data
  713. * @param mixed $default Default value if the parameter is not found in the input data
  714. * @return void
  715. * @throws Exception
  716. * @api
  717. */
  718. public static function GetOptionalParam($oData, $sParamName, $default)
  719. {
  720. if (isset($oData->$sParamName))
  721. {
  722. return $oData->$sParamName;
  723. }
  724. else
  725. {
  726. return $default;
  727. }
  728. }
  729. /**
  730. * Read a class from a Rest/Json structure.
  731. *
  732. * @param StdClass $oData Structured input data. Must contain the entry defined by sParamName.
  733. * @param string $sParamName Name of the parameter to fetch from the input data
  734. * @return void
  735. * @throws Exception If the parameter is missing or the class is unknown
  736. * @api
  737. */
  738. public static function GetClass($oData, $sParamName)
  739. {
  740. $sClass = self::GetMandatoryParam($oData, $sParamName);
  741. if (!MetaModel::IsValidClass($sClass))
  742. {
  743. throw new Exception("$sParamName: '$sClass' is not a valid class'");
  744. }
  745. return $sClass;
  746. }
  747. /**
  748. * Read a list of attribute codes from a Rest/Json structure.
  749. *
  750. * @param string $sClass Name of the class
  751. * @param StdClass $oData Structured input data.
  752. * @param string $sParamName Name of the parameter to fetch from the input data
  753. * @return An array of class => list of attributes (see RestResultWithObjects::AddObject that uses it)
  754. * @throws Exception
  755. * @api
  756. */
  757. public static function GetFieldList($sClass, $oData, $sParamName)
  758. {
  759. $sFields = self::GetOptionalParam($oData, $sParamName, '*');
  760. $aShowFields = array();
  761. if ($sFields == '*')
  762. {
  763. foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  764. {
  765. $aShowFields[$sClass][] = $sAttCode;
  766. }
  767. }
  768. elseif ($sFields == '*+')
  769. {
  770. foreach (MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL) as $sRefClass)
  771. {
  772. foreach (MetaModel::ListAttributeDefs($sRefClass) as $sAttCode => $oAttDef)
  773. {
  774. $aShowFields[$sRefClass][] = $sAttCode;
  775. }
  776. }
  777. }
  778. else
  779. {
  780. foreach(explode(',', $sFields) as $sAttCode)
  781. {
  782. $sAttCode = trim($sAttCode);
  783. if (($sAttCode != 'id') && (!MetaModel::IsValidAttCode($sClass, $sAttCode)))
  784. {
  785. throw new Exception("$sParamName: invalid attribute code '$sAttCode'");
  786. }
  787. $aShowFields[$sClass][] = $sAttCode;
  788. }
  789. }
  790. return $aShowFields;
  791. }
  792. /**
  793. * Read and interpret object search criteria from a Rest/Json structure
  794. *
  795. * @param string $sClass Name of the class
  796. * @param StdClass $oCriteria Hash of attribute code => value (can be a substructure or a scalar, depending on the nature of the attriute)
  797. * @return object The object found
  798. * @throws Exception If the input structure is not valid or it could not find exactly one object
  799. */
  800. protected static function FindObjectFromCriteria($sClass, $oCriteria)
  801. {
  802. $aCriteriaReport = array();
  803. if (isset($oCriteria->finalclass))
  804. {
  805. if (!MetaModel::IsValidClass($oCriteria->finalclass))
  806. {
  807. throw new Exception("finalclass: Unknown class '".$oCriteria->finalclass."'");
  808. }
  809. if (!MetaModel::IsParentClass($sClass, $oCriteria->finalclass))
  810. {
  811. throw new Exception("finalclass: '".$oCriteria->finalclass."' is not a child class of '$sClass'");
  812. }
  813. $sClass = $oCriteria->finalclass;
  814. }
  815. $oSearch = new DBObjectSearch($sClass);
  816. foreach ($oCriteria as $sAttCode => $value)
  817. {
  818. $realValue = static::MakeValue($sClass, $sAttCode, $value);
  819. $oSearch->AddCondition($sAttCode, $realValue, '=');
  820. if (is_object($value) || is_array($value))
  821. {
  822. $value = json_encode($value);
  823. }
  824. $aCriteriaReport[] = "$sAttCode: $value ($realValue)";
  825. }
  826. $oSet = new DBObjectSet($oSearch);
  827. $iCount = $oSet->Count();
  828. if ($iCount == 0)
  829. {
  830. throw new Exception("No item found with criteria: ".implode(', ', $aCriteriaReport));
  831. }
  832. elseif ($iCount > 1)
  833. {
  834. throw new Exception("Several items found ($iCount) with criteria: ".implode(', ', $aCriteriaReport));
  835. }
  836. $res = $oSet->Fetch();
  837. return $res;
  838. }
  839. /**
  840. * Find an object from a polymorph search specification (Rest/Json)
  841. *
  842. * @param string $sClass Name of the class
  843. * @param mixed $key Either search criteria (substructure), or an object or an OQL string.
  844. * @param bool $bAllowNullValue Allow the cases such as key = 0 or key = {null} and return null then
  845. * @return DBObject The object found
  846. * @throws Exception If the input structure is not valid or it could not find exactly one object
  847. * @api
  848. */
  849. public static function FindObjectFromKey($sClass, $key, $bAllowNullValue = false)
  850. {
  851. if (is_object($key))
  852. {
  853. $res = static::FindObjectFromCriteria($sClass, $key);
  854. }
  855. elseif (is_numeric($key))
  856. {
  857. if ($bAllowNullValue && ($key == 0))
  858. {
  859. $res = null;
  860. }
  861. else
  862. {
  863. $res = MetaModel::GetObject($sClass, $key, false);
  864. if (is_null($res))
  865. {
  866. throw new Exception("Invalid object $sClass::$key");
  867. }
  868. }
  869. }
  870. elseif (is_string($key))
  871. {
  872. // OQL
  873. $oSearch = DBObjectSearch::FromOQL($key);
  874. $oSet = new DBObjectSet($oSearch);
  875. $iCount = $oSet->Count();
  876. if ($iCount == 0)
  877. {
  878. throw new Exception("No item found for query: $key");
  879. }
  880. elseif ($iCount > 1)
  881. {
  882. throw new Exception("Several items found ($iCount) for query: $key");
  883. }
  884. $res = $oSet->Fetch();
  885. }
  886. else
  887. {
  888. throw new Exception("Wrong format for key");
  889. }
  890. return $res;
  891. }
  892. /**
  893. * Search objects from a polymorph search specification (Rest/Json)
  894. *
  895. * @param string $sClass Name of the class
  896. * @param mixed $key Either search criteria (substructure), or an object or an OQL string.
  897. * @return DBObjectSet The search result set
  898. * @throws Exception If the input structure is not valid
  899. */
  900. public static function GetObjectSetFromKey($sClass, $key)
  901. {
  902. if (is_object($key))
  903. {
  904. if (isset($key->finalclass))
  905. {
  906. $sClass = $key->finalclass;
  907. if (!MetaModel::IsValidClass($sClass))
  908. {
  909. throw new Exception("finalclass: Unknown class '$sClass'");
  910. }
  911. }
  912. $oSearch = new DBObjectSearch($sClass);
  913. foreach ($key as $sAttCode => $value)
  914. {
  915. $realValue = static::MakeValue($sClass, $sAttCode, $value);
  916. $oSearch->AddCondition($sAttCode, $realValue, '=');
  917. }
  918. }
  919. elseif (is_numeric($key))
  920. {
  921. $oSearch = new DBObjectSearch($sClass);
  922. $oSearch->AddCondition('id', $key);
  923. }
  924. elseif (is_string($key))
  925. {
  926. // OQL
  927. $oSearch = DBObjectSearch::FromOQL($key);
  928. $oObjectSet = new DBObjectSet($oSearch);
  929. }
  930. else
  931. {
  932. throw new Exception("Wrong format for key");
  933. }
  934. $oObjectSet = new DBObjectSet($oSearch);
  935. return $oObjectSet;
  936. }
  937. /**
  938. * Interpret the Rest/Json value and get a valid attribute value
  939. *
  940. * @param string $sClass Name of the class
  941. * @param string $sAttCode Attribute code
  942. * @param mixed $value Depending on the type of attribute (a scalar, or search criteria, or list of related objects...)
  943. * @return mixed The value that can be used with DBObject::Set()
  944. * @throws Exception If the specification of the value is not valid.
  945. * @api
  946. */
  947. public static function MakeValue($sClass, $sAttCode, $value)
  948. {
  949. try
  950. {
  951. if (!MetaModel::IsValidAttCode($sClass, $sAttCode))
  952. {
  953. throw new Exception("Unknown attribute");
  954. }
  955. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  956. if ($oAttDef instanceof AttributeExternalKey)
  957. {
  958. $oExtKeyObject = static::FindObjectFromKey($oAttDef->GetTargetClass(), $value, true /* allow null */);
  959. $value = ($oExtKeyObject != null) ? $oExtKeyObject->GetKey() : 0;
  960. }
  961. elseif ($oAttDef instanceof AttributeLinkedSet)
  962. {
  963. if (!is_array($value))
  964. {
  965. throw new Exception("A link set must be defined by an array of objects");
  966. }
  967. $sLnkClass = $oAttDef->GetLinkedClass();
  968. $aLinks = array();
  969. foreach($value as $oValues)
  970. {
  971. $oLnk = static::MakeObjectFromFields($sLnkClass, $oValues);
  972. $aLinks[] = $oLnk;
  973. }
  974. $value = DBObjectSet::FromArray($sLnkClass, $aLinks);
  975. }
  976. else
  977. {
  978. $value = $oAttDef->FromJSONToValue($value);
  979. }
  980. }
  981. catch (Exception $e)
  982. {
  983. throw new Exception("$sAttCode: ".$e->getMessage(), $e->getCode());
  984. }
  985. return $value;
  986. }
  987. /**
  988. * Interpret a Rest/Json structure that defines attribute values, and build an object
  989. *
  990. * @param string $sClass Name of the class
  991. * @param array $aFields A hash of attribute code => value specification.
  992. * @return DBObject The newly created object
  993. * @throws Exception If the specification of the values is not valid
  994. * @api
  995. */
  996. public static function MakeObjectFromFields($sClass, $aFields)
  997. {
  998. $oObject = MetaModel::NewObject($sClass);
  999. foreach ($aFields as $sAttCode => $value)
  1000. {
  1001. $realValue = static::MakeValue($sClass, $sAttCode, $value);
  1002. try
  1003. {
  1004. $oObject->Set($sAttCode, $realValue);
  1005. }
  1006. catch (Exception $e)
  1007. {
  1008. throw new Exception("$sAttCode: ".$e->getMessage(), $e->getCode());
  1009. }
  1010. }
  1011. return $oObject;
  1012. }
  1013. /**
  1014. * Interpret a Rest/Json structure that defines attribute values, and update the given object
  1015. *
  1016. * @param DBObject $oObject The object being modified
  1017. * @param array $aFields A hash of attribute code => value specification.
  1018. * @return DBObject The object modified
  1019. * @throws Exception If the specification of the values is not valid
  1020. * @api
  1021. */
  1022. public static function UpdateObjectFromFields($oObject, $aFields)
  1023. {
  1024. $sClass = get_class($oObject);
  1025. foreach ($aFields as $sAttCode => $value)
  1026. {
  1027. $realValue = static::MakeValue($sClass, $sAttCode, $value);
  1028. try
  1029. {
  1030. $oObject->Set($sAttCode, $realValue);
  1031. }
  1032. catch (Exception $e)
  1033. {
  1034. throw new Exception("$sAttCode: ".$e->getMessage(), $e->getCode());
  1035. }
  1036. }
  1037. return $oObject;
  1038. }
  1039. }