ui.linksdirectwidget.class.inc.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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. 'menu_actions_target' => '_blank',
  148. 'default' => $aDefaults,
  149. 'table_id' => $this->sClass.'_'.$this->sAttCode,
  150. );
  151. $oBlock = new DisplayBlock($oFilter, 'list', false);
  152. $oBlock->Display($oPage, $this->sInputid, $aParams);
  153. }
  154. }
  155. /**
  156. * @param WebPage $oPage
  157. * @param DBObjectSet $oValue
  158. * @param array $aArgs
  159. * @param $sFormPrefix
  160. * @param $oCurrentObj
  161. * @param array $aButtons
  162. */
  163. protected function DisplayEditInPlace(WebPage $oPage, DBObjectSet $oValue, $aArgs = array(), $sFormPrefix, $oCurrentObj, $aButtons = array('create', 'delete'))
  164. {
  165. $aAttribs = $this->GetTableConfig();
  166. $oValue->Rewind();
  167. $oPage->add('<table class="listContainer" id="'.$this->sInputid.'"><tr><td>');
  168. $aData = array();
  169. while($oLinkObj = $oValue->Fetch())
  170. {
  171. $aRow = array();
  172. $aRow['form::select'] = '<input type="checkbox" class="selectList'.$this->sInputid.'" value="'.$oLinkObj->GetKey().'"/>';
  173. foreach($this->aZlist as $sLinkedAttCode)
  174. {
  175. $aRow[$sLinkedAttCode] = $oLinkObj->GetAsHTML($sLinkedAttCode);
  176. }
  177. $aData[] = $aRow;
  178. }
  179. $oPage->table($aAttribs, $aData);
  180. $oPage->add('</td></tr></table>'); //listcontainer
  181. $sInputName = $sFormPrefix.'attr_'.$this->sAttCode;
  182. $aLabels = array(
  183. 'delete' => Dict::S('UI:Button:Delete'),
  184. // 'modify' => 'Modify...' ,
  185. 'creation_title' => Dict::Format('UI:CreationTitle_Class', MetaModel::GetName($this->sLinkedClass)),
  186. 'create' => Dict::Format('UI:ClickToCreateNew', MetaModel::GetName($this->sLinkedClass)),
  187. 'remove' => Dict::S('UI:Button:Remove'),
  188. 'add' => Dict::Format('UI:AddAnExisting_Class', MetaModel::GetName($this->sLinkedClass)),
  189. 'selection_title' => Dict::Format('UI:SelectionOf_Class', MetaModel::GetName($this->sLinkedClass)),
  190. );
  191. $oContext = new ApplicationContext();
  192. $sSubmitUrl = utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php?'.$oContext->GetForLink();
  193. $sJSONLabels = json_encode($aLabels);
  194. $sJSONButtons = json_encode($aButtons);
  195. $sWizHelper = 'oWizardHelper'.$sFormPrefix;
  196. $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 });");
  197. }
  198. public function GetObjectCreationDlg(WebPage $oPage, $sProposedRealClass = '')
  199. {
  200. // For security reasons: check that the "proposed" class is actually a subclass of the linked class
  201. // and that the current user is allowed to create objects of this class
  202. $sRealClass = '';
  203. $oPage->add('<div class="wizContainer" style="vertical-align:top;"><div>');
  204. $aSubClasses = MetaModel::EnumChildClasses($this->sLinkedClass, ENUM_CHILD_CLASSES_ALL); // Including the specified class itself
  205. $aPossibleClasses = array();
  206. foreach($aSubClasses as $sCandidateClass)
  207. {
  208. if (!MetaModel::IsAbstract($sCandidateClass) && (UserRights::IsActionAllowed($sCandidateClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
  209. {
  210. if ($sCandidateClass == $sProposedRealClass)
  211. {
  212. $sRealClass = $sProposedRealClass;
  213. }
  214. $aPossibleClasses[$sCandidateClass] = MetaModel::GetName($sCandidateClass);
  215. }
  216. }
  217. // Only one of the subclasses can be instantiated...
  218. if (count($aPossibleClasses) == 1)
  219. {
  220. $aKeys = array_keys($aPossibleClasses);
  221. $sRealClass = $aKeys[0];
  222. }
  223. if ($sRealClass != '')
  224. {
  225. $oPage->add("<h1>".MetaModel::GetClassIcon($sRealClass)."&nbsp;".Dict::Format('UI:CreationTitle_Class', MetaModel::GetName($sRealClass))."</h1>\n");
  226. $oLinksetDef = MetaModel::GetAttributeDef($this->sClass, $this->sAttCode);
  227. $sExtKeyToMe = $oLinksetDef->GetExtKeyToMe();
  228. $aFieldFlags = array( $sExtKeyToMe => OPT_ATT_HIDDEN);
  229. cmdbAbstractObject::DisplayCreationForm($oPage, $sRealClass, null, array(), array('formPrefix' => $this->sInputid, 'noRelations' => true, 'fieldsFlags' => $aFieldFlags));
  230. }
  231. else
  232. {
  233. $sClassLabel = MetaModel::GetName($this->sLinkedClass);
  234. $oPage->add('<p>'.Dict::Format('UI:SelectTheTypeOf_Class_ToCreate', $sClassLabel));
  235. $oPage->add('<nobr><select name="class">');
  236. asort($aPossibleClasses);
  237. foreach($aPossibleClasses as $sClassName => $sClassLabel)
  238. {
  239. $oPage->add("<option value=\"$sClassName\">$sClassLabel</option>");
  240. }
  241. $oPage->add('</select>');
  242. $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>');
  243. }
  244. $oPage->add('</div></div>');
  245. }
  246. public function GetObjectsSelectionDlg($oPage, $oCurrentObj)
  247. {
  248. $sHtml = "<div class=\"wizContainer\" style=\"vertical-align:top;\">\n";
  249. $oLinksetDef = MetaModel::GetAttributeDef($this->sClass, $this->sAttCode);
  250. $valuesDef = $oLinksetDef->GetValuesDef();
  251. if ($valuesDef === null)
  252. {
  253. $oFilter = new DBObjectSearch($this->sLinkedClass);
  254. }
  255. else
  256. {
  257. if (!$valuesDef instanceof ValueSetObjects)
  258. {
  259. throw new Exception('Error: only ValueSetObjects are supported for "allowed_values" in AttributeLinkedSet ('.$this->sClass.'/'.$this->sAttCode.').');
  260. }
  261. $oFilter = DBObjectSearch::FromOQL($valuesDef->GetFilterExpression());
  262. }
  263. if ($oCurrentObj != null)
  264. {
  265. $this->SetSearchDefaultFromContext($oCurrentObj, $oFilter);
  266. }
  267. $bOpen = MetaModel::GetConfig()->Get('legacy_search_drawer_open');
  268. $oBlock = new DisplayBlock($oFilter, 'search', false);
  269. $sHtml .= $oBlock->GetDisplay($oPage, "SearchFormToAdd_{$this->sInputid}", array('open' => $bOpen));
  270. $sHtml .= "<form id=\"ObjectsAddForm_{$this->sInputid}\">\n";
  271. $sHtml .= "<div id=\"SearchResultsToAdd_{$this->sInputid}\" style=\"vertical-align:top;background: #fff;height:100%;overflow:auto;padding:0;border:0;\">\n";
  272. $sHtml .= "<div style=\"background: #fff; border:0; text-align:center; vertical-align:middle;\"><p>".Dict::S('UI:Message:EmptyList:UseSearchForm')."</p></div>\n";
  273. $sHtml .= "</div>\n";
  274. $sHtml .= "<input type=\"hidden\" id=\"count_{$this->sInputid}\" value=\"0\"/>";
  275. $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>";
  276. $sHtml .= "</div>\n";
  277. $sHtml .= "</form>\n";
  278. $oPage->add($sHtml);
  279. }
  280. /**
  281. * Search for objects to be linked to the current object (i.e "remote" objects)
  282. * @param WebPage $oP The page used for the output (usually an AjaxWebPage)
  283. * @param string $sRemoteClass Name of the "remote" class to perform the search on, must be a derived class of $this->sLinkedClass
  284. * @param array $aAlreadyLinked Array of indentifiers of objects which are already linke to the current object (or about to be linked)
  285. * @param DBObject $oCurrentObj The object currently being edited... if known...
  286. */
  287. public function SearchObjectsToAdd(WebPage $oP, $sRemoteClass = '', $aAlreadyLinked = array(), $oCurrentObj = null)
  288. {
  289. if ($sRemoteClass == '')
  290. {
  291. $sRemoteClass = $this->sLinkedClass;
  292. }
  293. $oLinksetDef = MetaModel::GetAttributeDef($this->sClass, $this->sAttCode);
  294. $valuesDef = $oLinksetDef->GetValuesDef();
  295. if ($valuesDef === null)
  296. {
  297. $oFilter = new DBObjectSearch($sRemoteClass);
  298. }
  299. else
  300. {
  301. if (!$valuesDef instanceof ValueSetObjects)
  302. {
  303. throw new Exception('Error: only ValueSetObjects are supported for "allowed_values" in AttributeLinkedSet ('.$this->sClass.'/'.$this->sAttCode.').');
  304. }
  305. $oFilter = DBObjectSearch::FromOQL($valuesDef->GetFilterExpression());
  306. }
  307. if (($oCurrentObj != null) && MetaModel::IsSameFamilyBranch($sRemoteClass, $this->sClass))
  308. {
  309. // Prevent linking to self if the linked object is of the same family
  310. // and laready present in the database
  311. if (!$oCurrentObj->IsNew())
  312. {
  313. $oFilter->AddCondition('id', $oCurrentObj->GetKey(), '!=');
  314. }
  315. }
  316. if (count($aAlreadyLinked) > 0)
  317. {
  318. $oFilter->AddCondition('id', $aAlreadyLinked, 'NOTIN');
  319. }
  320. if ($oCurrentObj != null)
  321. {
  322. $aArgs = array_merge($oCurrentObj->ToArgs('this'), $oFilter->GetInternalParams());
  323. $oFilter->SetInternalParams($aArgs);
  324. }
  325. $oBlock = new DisplayBlock($oFilter, 'list', false);
  326. $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
  327. }
  328. public function DoAddObjects(WebPage $oP, $oFullSetFilter)
  329. {
  330. $aLinkedObjectIds = utils::ReadMultipleSelection($oFullSetFilter);
  331. foreach($aLinkedObjectIds as $iObjectId)
  332. {
  333. $oLinkObj = MetaModel::GetObject($this->sLinkedClass, $iObjectId);
  334. $oP->add($this->GetObjectRow($oP, $oLinkObj, $oLinkObj->GetKey()));
  335. }
  336. }
  337. public function GetObjectModificationDlg()
  338. {
  339. }
  340. protected function GetTableConfig()
  341. {
  342. $aAttribs = array();
  343. $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+'));
  344. foreach($this->aZlist as $sLinkedAttCode)
  345. {
  346. $oAttDef = MetaModel::GetAttributeDef($this->sLinkedClass, $sLinkedAttCode);
  347. $aAttribs[$sLinkedAttCode] = array('label' => MetaModel::GetLabel($this->sLinkedClass, $sLinkedAttCode), 'description' => $oAttDef->GetOrderByHint());
  348. }
  349. return $aAttribs;
  350. }
  351. public function GetRow($oPage, $sRealClass, $aValues, $iTempId)
  352. {
  353. if ($sRealClass == '')
  354. {
  355. $sRealClass = $this->sLinkedClass;
  356. }
  357. $oLinkObj = new $sRealClass();
  358. $oLinkObj->UpdateObjectFromPostedForm($this->sInputid);
  359. return $this->GetObjectRow($oPage, $oLinkObj, $iTempId);
  360. }
  361. protected function GetObjectRow($oPage, $oLinkObj, $iTempId)
  362. {
  363. $aAttribs = $this->GetTableConfig();
  364. $aRow = array();
  365. $aRow['form::select'] = '<input type="checkbox" class="selectList'.$this->sInputid.'" value="'.($iTempId).'"/>';
  366. foreach($this->aZlist as $sLinkedAttCode)
  367. {
  368. $aRow[$sLinkedAttCode] = $oLinkObj->GetAsHTML($sLinkedAttCode);
  369. }
  370. return $oPage->GetTableRow($aRow, $aAttribs);
  371. }
  372. /**
  373. * Initializes the default search parameters based on 1) a 'current' object and 2) the silos defined by the context
  374. * @param DBObject $oSourceObj
  375. * @param DBSearch $oSearch
  376. */
  377. protected function SetSearchDefaultFromContext($oSourceObj, &$oSearch)
  378. {
  379. $oAppContext = new ApplicationContext();
  380. $sSrcClass = get_class($oSourceObj);
  381. $sDestClass = $oSearch->GetClass();
  382. foreach($oAppContext->GetNames() as $key)
  383. {
  384. // Find the value of the object corresponding to each 'context' parameter
  385. $aCallSpec = array($sSrcClass, 'MapContextParam');
  386. $sAttCode = '';
  387. if (is_callable($aCallSpec))
  388. {
  389. $sAttCode = call_user_func($aCallSpec, $key); // Returns null when there is no mapping for this parameter
  390. }
  391. if (MetaModel::IsValidAttCode($sSrcClass, $sAttCode))
  392. {
  393. $oAttDef = MetaModel::GetAttributeDef($sSrcClass, $sAttCode);
  394. $defaultValue = $oSourceObj->Get($sAttCode);
  395. // Find the attcode for the same 'context' parameter in the destination class
  396. // and sets its value as the default value for the search condition
  397. $aCallSpec = array($sDestClass, 'MapContextParam');
  398. $sAttCode = '';
  399. if (is_callable($aCallSpec))
  400. {
  401. $sAttCode = call_user_func($aCallSpec, $key); // Returns null when there is no mapping for this parameter
  402. }
  403. if (MetaModel::IsValidAttCode($sDestClass, $sAttCode) && !empty($defaultValue))
  404. {
  405. $oSearch->AddCondition($sAttCode, $defaultValue);
  406. }
  407. }
  408. }
  409. }
  410. }