ui.linksdirectwidget.class.inc.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. <?php
  2. // Copyright (C) 2010-2017 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. * Class UILinksWidgetDirect
  20. *
  21. * @copyright Copyright (C) 2010-2017 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. class UILinksWidgetDirect
  25. {
  26. protected $sClass;
  27. protected $sAttCode;
  28. protected $sInputid;
  29. protected $sNameSuffix;
  30. protected $sLinkedClass;
  31. public function __construct($sClass, $sAttCode, $sInputId, $sNameSuffix = '')
  32. {
  33. $this->sClass = $sClass;
  34. $this->sAttCode = $sAttCode;
  35. $this->sInputid = $sInputId;
  36. $this->sNameSuffix = $sNameSuffix;
  37. $this->aZlist = array();
  38. $this->sLinkedClass = '';
  39. // Compute the list of attributes visible from the given objet:
  40. // All the attributes from the "list" Zlist of the Link class except
  41. // the ExternalKey that points to the current object and its related external fields
  42. $oLinksetDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  43. $this->sLinkedClass = $oLinksetDef->GetLinkedClass();
  44. $sExtKeyToMe = $oLinksetDef->GetExtKeyToMe();
  45. switch($oLinksetDef->GetEditMode())
  46. {
  47. case LINKSET_EDITMODE_INPLACE: // The whole linkset can be edited 'in-place'
  48. $aZList = MetaModel::FlattenZList(MetaModel::GetZListItems($this->sLinkedClass, 'details'));
  49. break;
  50. default:
  51. $aZList = MetaModel::FlattenZList(MetaModel::GetZListItems($this->sLinkedClass, 'list'));
  52. array_unshift($aZList, 'friendlyname');
  53. }
  54. foreach($aZList as $sLinkedAttCode)
  55. {
  56. if ($sLinkedAttCode != $sExtKeyToMe)
  57. {
  58. $oAttDef = MetaModel::GetAttributeDef($this->sLinkedClass, $sLinkedAttCode);
  59. if ((!$oAttDef->IsExternalField() || ($oAttDef->GetKeyAttCode() != $sExtKeyToMe)) &&
  60. (!$oAttDef->IsLinkSet()) )
  61. {
  62. $this->aZlist[] = $sLinkedAttCode;
  63. }
  64. }
  65. }
  66. }
  67. /**
  68. * @param WebPage $oPage
  69. * @param DBObjectSet $oValue
  70. * @param array $aArgs
  71. * @param $sFormPrefix
  72. * @param $oCurrentObj
  73. */
  74. public function Display(WebPage $oPage, DBObjectSet $oValue, $aArgs = array(), $sFormPrefix, $oCurrentObj)
  75. {
  76. $oLinksetDef = MetaModel::GetAttributeDef($this->sClass, $this->sAttCode);
  77. switch($oLinksetDef->GetEditMode())
  78. {
  79. case LINKSET_EDITMODE_NONE: // The linkset is read-only
  80. $this->DisplayAsBlock($oPage, $oValue, $aArgs = array(), $sFormPrefix, $oCurrentObj, false /* bDisplayMenu*/);
  81. break;
  82. case LINKSET_EDITMODE_ADDONLY: // The only possible action is to open (in a new window) the form to create a new object
  83. if ($oCurrentObj && !$oCurrentObj->IsNew())
  84. {
  85. $sTargetClass = $oLinksetDef->GetLinkedClass();
  86. $sExtKeyToMe = $oLinksetDef->GetExtKeyToMe();
  87. $sDefault = "default[$sExtKeyToMe]=".$oCurrentObj->GetKey();
  88. $oAppContext = new ApplicationContext();
  89. $sParams = $oAppContext->GetForLink();
  90. $oPage->p("<a target=\"_blank\" href=\"".utils::GetAbsoluteUrlAppRoot()."pages/UI.php?operation=new&class=$sTargetClass&$sParams&{$sDefault}\">".Dict::Format('UI:ClickToCreateNew', Metamodel::GetName($sTargetClass))."</a>\n");
  91. }
  92. $this->DisplayAsBlock($oPage, $oValue, $aArgs = array(), $sFormPrefix, $oCurrentObj, false /* bDisplayMenu*/);
  93. break;
  94. case LINKSET_EDITMODE_INPLACE: // The whole linkset can be edited 'in-place'
  95. $this->DisplayEditInPlace($oPage, $oValue, $aArgs, $sFormPrefix, $oCurrentObj);
  96. break;
  97. case LINKSET_EDITMODE_ADDREMOVE: // The whole linkset can be edited 'in-place'
  98. $sTargetClass = $oLinksetDef->GetLinkedClass();
  99. $sExtKeyToMe = $oLinksetDef->GetExtKeyToMe();
  100. $oExtKeyDef = MetaModel::GetAttributeDef($sTargetClass, $sExtKeyToMe);
  101. $aButtons = array('add');
  102. if ($oExtKeyDef->IsNullAllowed())
  103. {
  104. $aButtons = array('add', 'remove');
  105. }
  106. $this->DisplayEditInPlace($oPage, $oValue, $aArgs, $sFormPrefix, $oCurrentObj, $aButtons);
  107. break;
  108. case LINKSET_EDITMODE_ACTIONS:
  109. default:
  110. $this->DisplayAsBlock($oPage, $oValue, $aArgs = array(), $sFormPrefix, $oCurrentObj, true /* bDisplayMenu*/);
  111. }
  112. }
  113. /**
  114. * @param WebPage $oPage
  115. * @param DBObjectSet $oValue
  116. * @param array $aArgs
  117. * @param $sFormPrefix
  118. * @param $oCurrentObj
  119. * @param $bDisplayMenu
  120. */
  121. protected function DisplayAsBlock(WebPage $oPage, DBObjectSet $oValue, $aArgs = array(), $sFormPrefix, $oCurrentObj, $bDisplayMenu)
  122. {
  123. $oLinksetDef = MetaModel::GetAttributeDef($this->sClass, $this->sAttCode);
  124. $sTargetClass = $oLinksetDef->GetLinkedClass();
  125. if ($oCurrentObj && $oCurrentObj->IsNew() && $bDisplayMenu)
  126. {
  127. $oPage->p(Dict::Format('UI:BeforeAdding_Class_ObjectsSaveThisObject', MetaModel::GetName($sTargetClass)));
  128. }
  129. else
  130. {
  131. $oFilter = new DBObjectSearch($sTargetClass);
  132. $oFilter->AddCondition($oLinksetDef->GetExtKeyToMe(), $oCurrentObj->GetKey(),'=');
  133. $aDefaults = array($oLinksetDef->GetExtKeyToMe() => $oCurrentObj->GetKey());
  134. $oAppContext = new ApplicationContext();
  135. foreach($oAppContext->GetNames() as $sKey)
  136. {
  137. // The linked object inherits the parent's value for the context
  138. if (MetaModel::IsValidAttCode($this->sClass, $sKey) && $oCurrentObj)
  139. {
  140. $aDefaults[$sKey] = $oCurrentObj->Get($sKey);
  141. }
  142. }
  143. $aParams = array(
  144. 'target_attr' => $oLinksetDef->GetExtKeyToMe(),
  145. 'object_id' => $oCurrentObj ? $oCurrentObj->GetKey() : null,
  146. 'menu' => $bDisplayMenu,
  147. 'default' => $aDefaults,
  148. 'table_id' => $this->sClass.'_'.$this->sAttCode,
  149. );
  150. $oBlock = new DisplayBlock($oFilter, 'list', false);
  151. $oBlock->Display($oPage, $this->sInputid, $aParams);
  152. }
  153. }
  154. /**
  155. * @param WebPage $oPage
  156. * @param DBObjectSet $oValue
  157. * @param array $aArgs
  158. * @param $sFormPrefix
  159. * @param $oCurrentObj
  160. * @param array $aButtons
  161. */
  162. protected function DisplayEditInPlace(WebPage $oPage, DBObjectSet $oValue, $aArgs = array(), $sFormPrefix, $oCurrentObj, $aButtons = array('create', 'delete'))
  163. {
  164. $aAttribs = $this->GetTableConfig();
  165. $oValue->Rewind();
  166. $oPage->add('<table class="listContainer" id="'.$this->sInputid.'"><tr><td>');
  167. $aData = array();
  168. while($oLinkObj = $oValue->Fetch())
  169. {
  170. $aRow = array();
  171. $aRow['form::select'] = '<input type="checkbox" class="selectList'.$this->sInputid.'" value="'.$oLinkObj->GetKey().'"/>';
  172. foreach($this->aZlist as $sLinkedAttCode)
  173. {
  174. $aRow[$sLinkedAttCode] = $oLinkObj->GetAsHTML($sLinkedAttCode);
  175. }
  176. $aData[] = $aRow;
  177. }
  178. $oPage->table($aAttribs, $aData);
  179. $oPage->add('</td></tr></table>'); //listcontainer
  180. $sInputName = $sFormPrefix.'attr_'.$this->sAttCode;
  181. $aLabels = array(
  182. 'delete' => Dict::S('UI:Button:Delete'),
  183. // 'modify' => 'Modify...' ,
  184. 'creation_title' => Dict::Format('UI:CreationTitle_Class', MetaModel::GetName($this->sLinkedClass)),
  185. 'create' => Dict::Format('UI:ClickToCreateNew', MetaModel::GetName($this->sLinkedClass)),
  186. 'remove' => Dict::S('UI:Button:Remove'),
  187. 'add' => Dict::Format('UI:AddAnExisting_Class', MetaModel::GetName($this->sLinkedClass)),
  188. 'selection_title' => Dict::Format('UI:SelectionOf_Class', MetaModel::GetName($this->sLinkedClass)),
  189. );
  190. $oContext = new ApplicationContext();
  191. $sSubmitUrl = utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php?'.$oContext->GetForLink();
  192. $sJSONLabels = json_encode($aLabels);
  193. $sJSONButtons = json_encode($aButtons);
  194. $sWizHelper = 'oWizardHelper'.$sFormPrefix;
  195. $oPage->add_ready_script("$('#{$this->sInputid}').directlinks({class_name: '$this->sClass', att_code: '$this->sAttCode', input_name:'$sInputName', labels: $sJSONLabels, submit_to: '$sSubmitUrl', buttons: $sJSONButtons, oWizardHelper: $sWizHelper });");
  196. }
  197. public function GetObjectCreationDlg(WebPage $oPage, $sProposedRealClass = '')
  198. {
  199. // For security reasons: check that the "proposed" class is actually a subclass of the linked class
  200. // and that the current user is allowed to create objects of this class
  201. $sRealClass = '';
  202. $oPage->add('<div class="wizContainer" style="vertical-align:top;"><div>');
  203. $aSubClasses = MetaModel::EnumChildClasses($this->sLinkedClass, ENUM_CHILD_CLASSES_ALL); // Including the specified class itself
  204. $aPossibleClasses = array();
  205. foreach($aSubClasses as $sCandidateClass)
  206. {
  207. if (!MetaModel::IsAbstract($sCandidateClass) && (UserRights::IsActionAllowed($sCandidateClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
  208. {
  209. if ($sCandidateClass == $sProposedRealClass)
  210. {
  211. $sRealClass = $sProposedRealClass;
  212. }
  213. $aPossibleClasses[$sCandidateClass] = MetaModel::GetName($sCandidateClass);
  214. }
  215. }
  216. // Only one of the subclasses can be instantiated...
  217. if (count($aPossibleClasses) == 1)
  218. {
  219. $aKeys = array_keys($aPossibleClasses);
  220. $sRealClass = $aKeys[0];
  221. }
  222. if ($sRealClass != '')
  223. {
  224. $oPage->add("<h1>".MetaModel::GetClassIcon($sRealClass)."&nbsp;".Dict::Format('UI:CreationTitle_Class', MetaModel::GetName($sRealClass))."</h1>\n");
  225. $oLinksetDef = MetaModel::GetAttributeDef($this->sClass, $this->sAttCode);
  226. $sExtKeyToMe = $oLinksetDef->GetExtKeyToMe();
  227. $aFieldFlags = array( $sExtKeyToMe => OPT_ATT_HIDDEN);
  228. cmdbAbstractObject::DisplayCreationForm($oPage, $sRealClass, null, array(), array('formPrefix' => $this->sInputid, 'noRelations' => true, 'fieldsFlags' => $aFieldFlags));
  229. }
  230. else
  231. {
  232. $sClassLabel = MetaModel::GetName($this->sLinkedClass);
  233. $oPage->add('<p>'.Dict::Format('UI:SelectTheTypeOf_Class_ToCreate', $sClassLabel));
  234. $oPage->add('<nobr><select name="class">');
  235. asort($aPossibleClasses);
  236. foreach($aPossibleClasses as $sClassName => $sClassLabel)
  237. {
  238. $oPage->add("<option value=\"$sClassName\">$sClassLabel</option>");
  239. }
  240. $oPage->add('</select>');
  241. $oPage->add('&nbsp; <button type="button" onclick="$(\'#'.$this->sInputid.'\').directlinks(\'subclassSelected\');">'.Dict::S('UI:Button:Apply').'</button><span class="indicator" style="display:inline-block;width:16px"></span></nobr></p>');
  242. }
  243. $oPage->add('</div></div>');
  244. }
  245. public function GetObjectsSelectionDlg($oPage, $oCurrentObj)
  246. {
  247. $sHtml = "<div class=\"wizContainer\" style=\"vertical-align:top;\">\n";
  248. $oLinksetDef = MetaModel::GetAttributeDef($this->sClass, $this->sAttCode);
  249. $valuesDef = $oLinksetDef->GetValuesDef();
  250. if ($valuesDef === null)
  251. {
  252. $oFilter = new DBObjectSearch($this->sLinkedClass);
  253. }
  254. else
  255. {
  256. if (!$valuesDef instanceof ValueSetObjects)
  257. {
  258. throw new Exception('Error: only ValueSetObjects are supported for "allowed_values" in AttributeLinkedSet ('.$this->sClass.'/'.$this->sAttCode.').');
  259. }
  260. $oFilter = DBObjectSearch::FromOQL($valuesDef->GetFilterExpression());
  261. }
  262. if ($oCurrentObj != null)
  263. {
  264. $this->SetSearchDefaultFromContext($oCurrentObj, $oFilter);
  265. }
  266. $bOpen = MetaModel::GetConfig()->Get('legacy_search_drawer_open');
  267. $oBlock = new DisplayBlock($oFilter, 'search', false);
  268. $sHtml .= $oBlock->GetDisplay($oPage, "SearchFormToAdd_{$this->sInputid}", array('open' => $bOpen));
  269. $sHtml .= "<form id=\"ObjectsAddForm_{$this->sInputid}\">\n";
  270. $sHtml .= "<div id=\"SearchResultsToAdd_{$this->sInputid}\" style=\"vertical-align:top;background: #fff;height:100%;overflow:auto;padding:0;border:0;\">\n";
  271. $sHtml .= "<div style=\"background: #fff; border:0; text-align:center; vertical-align:middle;\"><p>".Dict::S('UI:Message:EmptyList:UseSearchForm')."</p></div>\n";
  272. $sHtml .= "</div>\n";
  273. $sHtml .= "<input type=\"hidden\" id=\"count_{$this->sInputid}\" value=\"0\"/>";
  274. $sHtml .= "<button type=\"button\" class=\"cancel\">".Dict::S('UI:Button:Cancel')."</button>&nbsp;&nbsp;<button type=\"button\" class=\"ok\" disabled=\"disabled\">".Dict::S('UI:Button:Add')."</button>";
  275. $sHtml .= "</div>\n";
  276. $sHtml .= "</form>\n";
  277. $oPage->add($sHtml);
  278. }
  279. /**
  280. * Search for objects to be linked to the current object (i.e "remote" objects)
  281. * @param WebPage $oP The page used for the output (usually an AjaxWebPage)
  282. * @param string $sRemoteClass Name of the "remote" class to perform the search on, must be a derived class of $this->sLinkedClass
  283. * @param array $aAlreadyLinked Array of indentifiers of objects which are already linke to the current object (or about to be linked)
  284. * @param DBObject $oCurrentObj The object currently being edited... if known...
  285. */
  286. public function SearchObjectsToAdd(WebPage $oP, $sRemoteClass = '', $aAlreadyLinked = array(), $oCurrentObj = null)
  287. {
  288. if ($sRemoteClass == '')
  289. {
  290. $sRemoteClass = $this->sLinkedClass;
  291. }
  292. $oLinksetDef = MetaModel::GetAttributeDef($this->sClass, $this->sAttCode);
  293. $valuesDef = $oLinksetDef->GetValuesDef();
  294. if ($valuesDef === null)
  295. {
  296. $oFilter = new DBObjectSearch($sRemoteClass);
  297. }
  298. else
  299. {
  300. if (!$valuesDef instanceof ValueSetObjects)
  301. {
  302. throw new Exception('Error: only ValueSetObjects are supported for "allowed_values" in AttributeLinkedSet ('.$this->sClass.'/'.$this->sAttCode.').');
  303. }
  304. $oFilter = DBObjectSearch::FromOQL($valuesDef->GetFilterExpression());
  305. }
  306. if (($oCurrentObj != null) && MetaModel::IsSameFamilyBranch($sRemoteClass, $this->sClass))
  307. {
  308. // Prevent linking to self if the linked object is of the same family
  309. // and laready present in the database
  310. if (!$oCurrentObj->IsNew())
  311. {
  312. $oFilter->AddCondition('id', $oCurrentObj->GetKey(), '!=');
  313. }
  314. }
  315. if (count($aAlreadyLinked) > 0)
  316. {
  317. $oFilter->AddCondition('id', $aAlreadyLinked, 'NOTIN');
  318. }
  319. if ($oCurrentObj != null)
  320. {
  321. $aArgs = array_merge($oCurrentObj->ToArgs('this'), $oFilter->GetInternalParams());
  322. $oFilter->SetInternalParams($aArgs);
  323. }
  324. $oBlock = new DisplayBlock($oFilter, 'list', false);
  325. $oBlock->Display($oP, "ResultsToAdd_{$this->sInputid}", array('menu' => false, 'cssCount'=> '#count_'.$this->sInputid , 'selection_mode' => true, 'table_id' => 'add_'.$this->sInputid)); // Don't display the 'Actions' menu on the results
  326. }
  327. public function DoAddObjects(WebPage $oP, $oFullSetFilter)
  328. {
  329. $aLinkedObjectIds = utils::ReadMultipleSelection($oFullSetFilter);
  330. foreach($aLinkedObjectIds as $iObjectId)
  331. {
  332. $oLinkObj = MetaModel::GetObject($this->sLinkedClass, $iObjectId);
  333. $oP->add($this->GetObjectRow($oP, $oLinkObj, $oLinkObj->GetKey()));
  334. }
  335. }
  336. public function GetObjectModificationDlg()
  337. {
  338. }
  339. protected function GetTableConfig()
  340. {
  341. $aAttribs = array();
  342. $aAttribs['form::select'] = array('label' => "<input type=\"checkbox\" onClick=\"CheckAll('.selectList{$this->sInputid}:not(:disabled)', this.checked);\" class=\"checkAll\"></input>", 'description' => Dict::S('UI:SelectAllToggle+'));
  343. foreach($this->aZlist as $sLinkedAttCode)
  344. {
  345. $oAttDef = MetaModel::GetAttributeDef($this->sLinkedClass, $sLinkedAttCode);
  346. $aAttribs[$sLinkedAttCode] = array('label' => MetaModel::GetLabel($this->sLinkedClass, $sLinkedAttCode), 'description' => $oAttDef->GetOrderByHint());
  347. }
  348. return $aAttribs;
  349. }
  350. public function GetRow($oPage, $sRealClass, $aValues, $iTempId)
  351. {
  352. if ($sRealClass == '')
  353. {
  354. $sRealClass = $this->sLinkedClass;
  355. }
  356. $oLinkObj = new $sRealClass();
  357. $oLinkObj->UpdateObjectFromPostedForm($this->sInputid);
  358. return $this->GetObjectRow($oPage, $oLinkObj, $iTempId);
  359. }
  360. protected function GetObjectRow($oPage, $oLinkObj, $iTempId)
  361. {
  362. $aAttribs = $this->GetTableConfig();
  363. $aRow = array();
  364. $aRow['form::select'] = '<input type="checkbox" class="selectList'.$this->sInputid.'" value="'.($iTempId).'"/>';
  365. foreach($this->aZlist as $sLinkedAttCode)
  366. {
  367. $aRow[$sLinkedAttCode] = $oLinkObj->GetAsHTML($sLinkedAttCode);
  368. }
  369. return $oPage->GetTableRow($aRow, $aAttribs);
  370. }
  371. /**
  372. * Initializes the default search parameters based on 1) a 'current' object and 2) the silos defined by the context
  373. * @param DBObject $oSourceObj
  374. * @param DBSearch $oSearch
  375. */
  376. protected function SetSearchDefaultFromContext($oSourceObj, &$oSearch)
  377. {
  378. $oAppContext = new ApplicationContext();
  379. $sSrcClass = get_class($oSourceObj);
  380. $sDestClass = $oSearch->GetClass();
  381. foreach($oAppContext->GetNames() as $key)
  382. {
  383. // Find the value of the object corresponding to each 'context' parameter
  384. $aCallSpec = array($sSrcClass, 'MapContextParam');
  385. $sAttCode = '';
  386. if (is_callable($aCallSpec))
  387. {
  388. $sAttCode = call_user_func($aCallSpec, $key); // Returns null when there is no mapping for this parameter
  389. }
  390. if (MetaModel::IsValidAttCode($sSrcClass, $sAttCode))
  391. {
  392. $oAttDef = MetaModel::GetAttributeDef($sSrcClass, $sAttCode);
  393. $defaultValue = $oSourceObj->Get($sAttCode);
  394. // Find the attcode for the same 'context' parameter in the destination class
  395. // and sets its value as the default value for the search condition
  396. $aCallSpec = array($sDestClass, 'MapContextParam');
  397. $sAttCode = '';
  398. if (is_callable($aCallSpec))
  399. {
  400. $sAttCode = call_user_func($aCallSpec, $key); // Returns null when there is no mapping for this parameter
  401. }
  402. if (MetaModel::IsValidAttCode($sDestClass, $sAttCode) && !empty($defaultValue))
  403. {
  404. $oSearch->AddCondition($sAttCode, $defaultValue);
  405. }
  406. }
  407. }
  408. }
  409. }