applicationextension.inc.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  1. <?php
  2. // Copyright (C) 2010-2012 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. * Get the list of items to be added to a menu.
  297. *
  298. * This method is called by the framework for each menu.
  299. * The items will be inserted in the menu in the order of the returned array.
  300. * @param int $iMenuId The identifier of the type of menu, as listed by the constants MENU_xxx
  301. * @param mixed $param Depends on $iMenuId, see the constants defined above
  302. * @return object[] An array of ApplicationPopupMenuItem or an empty array if no action is to be added to the menu
  303. */
  304. public static function EnumItems($iMenuId, $param);
  305. }
  306. /**
  307. * Base class for the various types of custom menus
  308. *
  309. * @package Extensibility
  310. * @internal
  311. * @since 2.0
  312. */
  313. abstract class ApplicationPopupMenuItem
  314. {
  315. /** @ignore */
  316. protected $sUID;
  317. /** @ignore */
  318. protected $sLabel;
  319. /**
  320. * Constructor
  321. *
  322. * @param string $sUID The unique identifier of this menu in iTop... make sure you pass something unique enough
  323. * @param string $sLabel The display label of the menu (must be localized)
  324. */
  325. public function __construct($sUID, $sLabel)
  326. {
  327. $this->sUID = $sUID;
  328. $this->sLabel = $sLabel;
  329. }
  330. /**
  331. * Get the UID
  332. *
  333. * @return string The unique identifier
  334. * @ignore
  335. */
  336. public function GetUID()
  337. {
  338. return $this->sUID;
  339. }
  340. /**
  341. * Get the label
  342. *
  343. * @return string The label
  344. * @ignore
  345. */
  346. public function GetLabel()
  347. {
  348. return $this->sLabel;
  349. }
  350. /**
  351. * Returns the components to create a popup menu item in HTML
  352. * @return Hash A hash array: array('label' => , 'url' => , 'target' => , 'onclick' => )
  353. * @ignore
  354. */
  355. abstract public function GetMenuItem();
  356. /** @ignore */
  357. public function GetLinkedScripts()
  358. {
  359. return array();
  360. }
  361. }
  362. /**
  363. * Class for adding an item into a popup menu that browses to the given URL
  364. *
  365. * @package Extensibility
  366. * @api
  367. * @since 2.0
  368. */
  369. class URLPopupMenuItem extends ApplicationPopupMenuItem
  370. {
  371. /** @ignore */
  372. protected $sURL;
  373. /** @ignore */
  374. protected $sTarget;
  375. /**
  376. * Constructor
  377. *
  378. * @param string $sUID The unique identifier of this menu in iTop... make sure you pass something unique enough
  379. * @param string $sLabel The display label of the menu (must be localized)
  380. * @param string $sURL If the menu is an hyperlink, provide the absolute hyperlink here
  381. * @param string $sTarget In case the menu is an hyperlink and a specific target is needed (_blank for example), pass it here
  382. */
  383. public function __construct($sUID, $sLabel, $sURL, $sTarget = '_top')
  384. {
  385. parent::__construct($sUID, $sLabel);
  386. $this->sURL = $sURL;
  387. $this->sTarget = $sTarget;
  388. }
  389. /** @ignore */
  390. public function GetMenuItem()
  391. {
  392. return array ('label' => $this->GetLabel(), 'url' => $this->sURL, 'target' => $this->sTarget);
  393. }
  394. }
  395. /**
  396. * Class for adding an item into a popup menu that triggers some Javascript code
  397. *
  398. * @package Extensibility
  399. * @api
  400. * @since 2.0
  401. */
  402. class JSPopupMenuItem extends ApplicationPopupMenuItem
  403. {
  404. /** @ignore */
  405. protected $sJSCode;
  406. /** @ignore */
  407. protected $aIncludeJSFiles;
  408. /**
  409. * Class for adding an item that triggers some Javascript code
  410. * @param string $sUID The unique identifier of this menu in iTop... make sure you pass something unique enough
  411. * @param string $sLabel The display label of the menu (must be localized)
  412. * @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
  413. * @param array $aIncludeJSFiles An array of file URLs to be included (once) to provide some JS libraries for the page.
  414. */
  415. public function __construct($sUID, $sLabel, $sJSCode, $aIncludeJSFiles = array())
  416. {
  417. parent::__construct($sUID, $sLabel);
  418. $this->sJSCode = $sJSCode;
  419. $this->aIncludeJSFiles = $aIncludeJSFiles;
  420. }
  421. /** @ignore */
  422. public function GetMenuItem()
  423. {
  424. return array ('label' => $this->GetLabel(), 'onclick' => $this->sJSCode, 'url' => '#');
  425. }
  426. /** @ignore */
  427. public function GetLinkedScripts()
  428. {
  429. return $this->aIncludeJSFiles;
  430. }
  431. }
  432. /**
  433. * Class for adding a separator (horizontal line, not selectable) the output
  434. * will automatically reduce several consecutive separators to just one
  435. *
  436. * @package Extensibility
  437. * @api
  438. * @since 2.0
  439. */
  440. class SeparatorPopupMenuItem extends ApplicationPopupMenuItem
  441. {
  442. /**
  443. * Constructor
  444. */
  445. public function __construct()
  446. {
  447. parent::__construct('', '');
  448. }
  449. /** @ignore */
  450. public function GetMenuItem()
  451. {
  452. return array ('label' => '<hr class="menu-separator">', 'url' => '');
  453. }
  454. }
  455. /**
  456. * Implement this interface to add content to any iTopWebPage
  457. *
  458. * There are 3 places where content can be added:
  459. *
  460. * * The north pane: (normaly empty/hidden) at the top of the page, spanning the whole
  461. * width of the page
  462. * * The south pane: (normaly empty/hidden) at the bottom of the page, spanning the whole
  463. * width of the page
  464. * * The admin banner (two tones gray background) at the left of the global search.
  465. * Limited space, use it for short messages
  466. *
  467. * Each of the methods of this interface is supposed to return the HTML to be inserted at
  468. * the specified place and can use the passed iTopWebPage object to add javascript or CSS definitions
  469. *
  470. * @package Extensibility
  471. * @api
  472. * @since 2.0
  473. */
  474. interface iPageUIExtension
  475. {
  476. /**
  477. * Add content to the North pane
  478. * @param iTopWebPage $oPage The page to insert stuff into.
  479. * @return string The HTML content to add into the page
  480. */
  481. public function GetNorthPaneHtml(iTopWebPage $oPage);
  482. /**
  483. * Add content to the South pane
  484. * @param iTopWebPage $oPage The page to insert stuff into.
  485. * @return string The HTML content to add into the page
  486. */
  487. public function GetSouthPaneHtml(iTopWebPage $oPage);
  488. /**
  489. * Add content to the "admin banner"
  490. * @param iTopWebPage $oPage The page to insert stuff into.
  491. * @return string The HTML content to add into the page
  492. */
  493. public function GetBannerHtml(iTopWebPage $oPage);
  494. }
  495. /**
  496. * Implement this interface to add new operations to the REST/JSON web service
  497. *
  498. * @package Extensibility
  499. * @api
  500. * @since 2.0.1
  501. */
  502. interface iRestServiceProvider
  503. {
  504. /**
  505. * Enumerate services delivered by this class
  506. * @param string $sVersion The version (e.g. 1.0) supported by the services
  507. * @return array An array of hash 'verb' => verb, 'description' => description
  508. */
  509. public function ListOperations($sVersion);
  510. /**
  511. * Enumerate services delivered by this class
  512. * @param string $sVersion The version (e.g. 1.0) supported by the services
  513. * @return RestResult The standardized result structure (at least a message)
  514. * @throws Exception in case of internal failure.
  515. */
  516. public function ExecOperation($sVersion, $sVerb, $aParams);
  517. }
  518. /**
  519. * Minimal REST response structure. Derive this structure to add response data and error codes.
  520. *
  521. * @package Extensibility
  522. * @api
  523. * @since 2.0.1
  524. */
  525. class RestResult
  526. {
  527. /**
  528. * Result: no issue has been encountered
  529. */
  530. const OK = 0;
  531. /**
  532. * Result: missing/wrong credentials or the user does not have enough rights to perform the requested operation
  533. */
  534. const UNAUTHORIZED = 1;
  535. /**
  536. * Result: the parameter 'version' is missing
  537. */
  538. const MISSING_VERSION = 2;
  539. /**
  540. * Result: the parameter 'json_data' is missing
  541. */
  542. const MISSING_JSON = 3;
  543. /**
  544. * Result: the input structure is not a valid JSON string
  545. */
  546. const INVALID_JSON = 4;
  547. /**
  548. * Result: no operation is available for the specified version
  549. */
  550. const UNSUPPORTED_VERSION = 10;
  551. /**
  552. * Result: the requested operation is not valid for the specified version
  553. */
  554. const UNKNOWN_OPERATION = 11;
  555. /**
  556. * Result: the requested operation cannot be performed because it can cause data (integrity) loss
  557. */
  558. const UNSAFE = 12;
  559. /**
  560. * Result: the operation could not be performed, see the message for troubleshooting
  561. */
  562. const INTERNAL_ERROR = 100;
  563. /**
  564. * Default constructor - ok!
  565. *
  566. * @param DBObject $oObject The object being reported
  567. * @param string $sAttCode The attribute code (must be valid)
  568. * @return string A scalar representation of the value
  569. */
  570. public function __construct()
  571. {
  572. $this->code = RestResult::OK;
  573. }
  574. public $code;
  575. public $message;
  576. }
  577. /**
  578. * Helpers for implementing REST services
  579. *
  580. * @package Extensibility
  581. * @api
  582. */
  583. class RestUtils
  584. {
  585. /**
  586. * Registering tracking information. Any further object modification be associated with the given comment, when the modification gets recorded into the DB
  587. *
  588. * @param StdClass $oData Structured input data. Must contain 'comment'.
  589. * @return void
  590. * @throws Exception
  591. * @api
  592. */
  593. public static function InitTrackingComment($oData)
  594. {
  595. $sComment = self::GetMandatoryParam($oData, 'comment');
  596. CMDBObject::SetTrackInfo($sComment);
  597. }
  598. /**
  599. * Read a mandatory parameter from from a Rest/Json structure.
  600. *
  601. * @param StdClass $oData Structured input data. Must contain the entry defined by sParamName.
  602. * @param string $sParamName Name of the parameter to fetch from the input data
  603. * @return void
  604. * @throws Exception If the parameter is missing
  605. * @api
  606. */
  607. public static function GetMandatoryParam($oData, $sParamName)
  608. {
  609. if (isset($oData->$sParamName))
  610. {
  611. return $oData->$sParamName;
  612. }
  613. else
  614. {
  615. throw new Exception("Missing parameter '$sParamName'");
  616. }
  617. }
  618. /**
  619. * Read an optional parameter from from a Rest/Json structure.
  620. *
  621. * @param StdClass $oData Structured input data.
  622. * @param string $sParamName Name of the parameter to fetch from the input data
  623. * @param mixed $default Default value if the parameter is not found in the input data
  624. * @return void
  625. * @throws Exception
  626. * @api
  627. */
  628. public static function GetOptionalParam($oData, $sParamName, $default)
  629. {
  630. if (isset($oData->$sParamName))
  631. {
  632. return $oData->$sParamName;
  633. }
  634. else
  635. {
  636. return $default;
  637. }
  638. }
  639. /**
  640. * Read a class from a Rest/Json structure.
  641. *
  642. * @param StdClass $oData Structured input data. Must contain the entry defined by sParamName.
  643. * @param string $sParamName Name of the parameter to fetch from the input data
  644. * @return void
  645. * @throws Exception If the parameter is missing or the class is unknown
  646. * @api
  647. */
  648. public static function GetClass($oData, $sParamName)
  649. {
  650. $sClass = self::GetMandatoryParam($oData, $sParamName);
  651. if (!MetaModel::IsValidClass($sClass))
  652. {
  653. throw new Exception("$sParamName: '$sClass' is not a valid class'");
  654. }
  655. return $sClass;
  656. }
  657. /**
  658. * Read a list of attribute codes from a Rest/Json structure.
  659. *
  660. * @param string $sClass Name of the class
  661. * @param StdClass $oData Structured input data.
  662. * @param string $sParamName Name of the parameter to fetch from the input data
  663. * @return void
  664. * @throws Exception
  665. * @api
  666. */
  667. public static function GetFieldList($sClass, $oData, $sParamName)
  668. {
  669. $sFields = self::GetOptionalParam($oData, $sParamName, '*');
  670. $aShowFields = array();
  671. if ($sFields == '*')
  672. {
  673. foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  674. {
  675. $aShowFields[] = $sAttCode;
  676. }
  677. }
  678. else
  679. {
  680. foreach(explode(',', $sFields) as $sAttCode)
  681. {
  682. $sAttCode = trim($sAttCode);
  683. if (($sAttCode != 'id') && (!MetaModel::IsValidAttCode($sClass, $sAttCode)))
  684. {
  685. throw new Exception("$sParamName: invalid attribute code '$sAttCode'");
  686. }
  687. $aShowFields[] = $sAttCode;
  688. }
  689. }
  690. return $aShowFields;
  691. }
  692. /**
  693. * Read and interpret object search criteria from a Rest/Json structure
  694. *
  695. * @param string $sClass Name of the class
  696. * @param StdClass $oCriteria Hash of attribute code => value (can be a substructure or a scalar, depending on the nature of the attriute)
  697. * @return object The object found
  698. * @throws Exception If the input structure is not valid or it could not find exactly one object
  699. */
  700. protected static function FindObjectFromCriteria($sClass, $oCriteria)
  701. {
  702. $aCriteriaReport = array();
  703. if (isset($oCriteria->finalclass))
  704. {
  705. $sClass = $oCriteria->finalclass;
  706. if (!MetaModel::IsValidClass($sClass))
  707. {
  708. throw new Exception("finalclass: Unknown class '$sClass'");
  709. }
  710. }
  711. $oSearch = new DBObjectSearch($sClass);
  712. foreach ($oCriteria as $sAttCode => $value)
  713. {
  714. $realValue = self::MakeValue($sClass, $sAttCode, $value);
  715. $oSearch->AddCondition($sAttCode, $realValue);
  716. $aCriteriaReport[] = "$sAttCode: $value ($realValue)";
  717. }
  718. $oSet = new DBObjectSet($oSearch);
  719. $iCount = $oSet->Count();
  720. if ($iCount == 0)
  721. {
  722. throw new Exception("No item found with criteria: ".implode(', ', $aCriteriaReport));
  723. }
  724. elseif ($iCount > 1)
  725. {
  726. throw new Exception("Several items found ($iCount) with criteria: ".implode(', ', $aCriteriaReport));
  727. }
  728. $res = $oSet->Fetch();
  729. return $res;
  730. }
  731. /**
  732. * Find an object from a polymorph search specification (Rest/Json)
  733. *
  734. * @param string $sClass Name of the class
  735. * @param mixed $key Either search criteria (substructure), or an object or an OQL string.
  736. * @return DBObject The object found
  737. * @throws Exception If the input structure is not valid or it could not find exactly one object
  738. * @api
  739. */
  740. public static function FindObjectFromKey($sClass, $key)
  741. {
  742. if (is_object($key))
  743. {
  744. $res = self::FindObjectFromCriteria($sClass, $key);
  745. }
  746. elseif (is_numeric($key))
  747. {
  748. $res = MetaModel::GetObject($sClass, $key, false);
  749. if (is_null($res))
  750. {
  751. throw new Exception("Invalid object $sClass::$key");
  752. }
  753. }
  754. elseif (is_string($key))
  755. {
  756. // OQL
  757. $oSearch = DBObjectSearch::FromOQL($key);
  758. $oSet = new DBObjectSet($oSearch);
  759. $iCount = $oSet->Count();
  760. if ($iCount == 0)
  761. {
  762. throw new Exception("No item found for query: $key");
  763. }
  764. elseif ($iCount > 1)
  765. {
  766. throw new Exception("Several items found ($iCount) for query: $key");
  767. }
  768. $res = $oSet->Fetch();
  769. }
  770. else
  771. {
  772. throw new Exception("Wrong format for key");
  773. }
  774. return $res;
  775. }
  776. /**
  777. * Search objects from a polymorph search specification (Rest/Json)
  778. *
  779. * @param string $sClass Name of the class
  780. * @param mixed $key Either search criteria (substructure), or an object or an OQL string.
  781. * @return DBObjectSet The search result set
  782. * @throws Exception If the input structure is not valid
  783. */
  784. public static function GetObjectSetFromKey($sClass, $key)
  785. {
  786. if (is_object($key))
  787. {
  788. if (isset($oCriteria->finalclass))
  789. {
  790. $sClass = $oCriteria->finalclass;
  791. if (!MetaModel::IsValidClass($sClass))
  792. {
  793. throw new Exception("finalclass: Unknown class '$sClass'");
  794. }
  795. }
  796. $oSearch = new DBObjectSearch($sClass);
  797. foreach ($key as $sAttCode => $value)
  798. {
  799. $realValue = self::MakeValue($sClass, $sAttCode, $value);
  800. $oSearch->AddCondition($sAttCode, $realValue);
  801. }
  802. }
  803. elseif (is_numeric($key))
  804. {
  805. $oSearch = new DBObjectSearch($sClass);
  806. $oSearch->AddCondition('id', $key);
  807. }
  808. elseif (is_string($key))
  809. {
  810. // OQL
  811. $oSearch = DBObjectSearch::FromOQL($key);
  812. $oObjectSet = new DBObjectSet($oSearch);
  813. }
  814. else
  815. {
  816. throw new Exception("Wrong format for key");
  817. }
  818. $oObjectSet = new DBObjectSet($oSearch);
  819. return $oObjectSet;
  820. }
  821. /**
  822. * Interpret the Rest/Json value and get a valid attribute value
  823. *
  824. * @param string $sClass Name of the class
  825. * @param string $sAttCode Attribute code
  826. * @param mixed $value Depending on the type of attribute (a scalar, or search criteria, or list of related objects...)
  827. * @return mixed The value that can be used with DBObject::Set()
  828. * @throws Exception If the specification of the value is not valid.
  829. * @api
  830. */
  831. public static function MakeValue($sClass, $sAttCode, $value)
  832. {
  833. try
  834. {
  835. if (!MetaModel::IsValidAttCode($sClass, $sAttCode))
  836. {
  837. throw new Exception("Unknown attribute");
  838. }
  839. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  840. if ($oAttDef instanceof AttributeExternalKey)
  841. {
  842. $oExtKeyObject = self::FindObjectFromKey($oAttDef->GetTargetClass(), $value);
  843. $value = $oExtKeyObject->GetKey();
  844. }
  845. elseif ($oAttDef instanceof AttributeLinkedSet)
  846. {
  847. if (!is_array($value))
  848. {
  849. throw new Exception("A link set must be defined by an array of objects");
  850. }
  851. $sLnkClass = $oAttDef->GetLinkedClass();
  852. $aLinks = array();
  853. foreach($value as $oValues)
  854. {
  855. $oLnk = self::MakeObjectFromFields($sLnkClass, $oValues);
  856. $aLinks[] = $oLnk;
  857. }
  858. $value = DBObjectSet::FromArray($sLnkClass, $aLinks);
  859. }
  860. }
  861. catch (Exception $e)
  862. {
  863. throw new Exception("$sAttCode: ".$e->getMessage(), $e->getCode());
  864. }
  865. return $value;
  866. }
  867. /**
  868. * Interpret a Rest/Json structure that defines attribute values, and build an object
  869. *
  870. * @param string $sClass Name of the class
  871. * @param array $aFields A hash of attribute code => value specification.
  872. * @return DBObject The newly created object
  873. * @throws Exception If the specification of the values is not valid
  874. * @api
  875. */
  876. public static function MakeObjectFromFields($sClass, $aFields)
  877. {
  878. $oObject = MetaModel::NewObject($sClass);
  879. foreach ($aFields as $sAttCode => $value)
  880. {
  881. $realValue = self::MakeValue($sClass, $sAttCode, $value);
  882. $oObject->Set($sAttCode, $realValue);
  883. }
  884. return $oObject;
  885. }
  886. /**
  887. * Interpret a Rest/Json structure that defines attribute values, and update the given object
  888. *
  889. * @param DBObject $oObject The object being modified
  890. * @param array $aFields A hash of attribute code => value specification.
  891. * @return DBObject The object modified
  892. * @throws Exception If the specification of the values is not valid
  893. * @api
  894. */
  895. public static function UpdateObjectFromFields($oObject, $aFields)
  896. {
  897. $sClass = get_class($oObject);
  898. foreach ($aFields as $sAttCode => $value)
  899. {
  900. $realValue = self::MakeValue($sClass, $sAttCode, $value);
  901. $oObject->Set($sAttCode, $realValue);
  902. }
  903. return $oObject;
  904. }
  905. }