ui.linksdirectwidget.class.inc.php 17 KB

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