Ubiquity  2.0.2
php rapid development framework
UbiquityMyAdminBaseController.php
Go to the documentation of this file.
1 <?php
2 
4 
21 
26 use Ajax\JsUtils;
39 
42 
48  private $adminData;
49 
54  private $adminViewer;
55 
60  private $adminFiles;
61  private $globalMessage;
62 
63  public function initialize() {
64  parent::initialize();
65  if (URequest::isAjax() === false) {
66  $semantic=$this->jquery->semantic();
67  $mainMenuElements=$this->_getAdminViewer()->getMainMenuElements();
68  $elements=[ "UbiquityMyAdmin" ];
69  $dataAjax=[ "index" ];
70  foreach ( $mainMenuElements as $elm => $values ) {
71  $elements[]=$elm;
72  $dataAjax[]=$values[0];
73  }
74  $mn=$semantic->htmlMenu("mainMenu", $elements);
75  $mn->getItem(0)->addClass("header")->addIcon("home big link");
76  $mn->setPropertyValues("data-ajax", $dataAjax);
77  $mn->setActiveItem(0);
78  $mn->setSecondary();
79  $mn->getOnClick("Admin", "#main-content", [ "attr" => "data-ajax" ]);
80  $this->jquery->compile($this->view);
81  $this->loadView($this->_getAdminFiles()->getViewHeader());
82  }
83  }
84 
85  public function finalize() {
86  if (!URequest::isAjax()) {
87  $this->loadView("Admin/main/vFooter.html", [ "js" => $this->initializeJs() ]);
88  }
89  }
90 
91  protected function initializeJs() {
92  $js='var setAceEditor=function(elementId,readOnly,mode,maxLines){
93  mode=mode || "sql";readOnly=readOnly || false;maxLines=maxLines || 100;
94  var editor = ace.edit(elementId);
95  editor.setTheme("ace/theme/solarized_dark");
96  editor.getSession().setMode({path:"ace/mode/"+mode, inline:true});
97  editor.setOptions({
98  maxLines: maxLines,
99  minLines: 2,
100  showInvisibles: true,
101  showGutter: !readOnly,
102  showPrintMargin: false,
103  readOnly: readOnly,
104  showLineNumbers: !readOnly,
105  highlightActiveLine: !readOnly,
106  highlightGutterLine: !readOnly
107  });
108  };';
109  return $this->jquery->inline($js);
110  }
111 
112  public function index() {
113  $semantic=$this->jquery->semantic();
114  $array=$this->_getAdminViewer()->getMainMenuElements();
115  $this->_getAdminViewer()->getMainIndexItems("part1", \array_slice($array, 0,4));
116  $this->_getAdminViewer()->getMainIndexItems("part2", \array_slice($array, 4,4));
117  $this->jquery->compile($this->view);
118  $this->loadView($this->_getAdminFiles()->getViewIndex());
119  }
120 
121  public function models($hasHeader=true) {
122  $semantic=$this->jquery->semantic();
123  $header="";
124  if ($hasHeader === true) {
125  $header=$this->getHeader("models");
126  $stepper=$this->_getModelsStepper();
127  }
128  if ($this->_isModelsCompleted() || $hasHeader !== true) {
129  try {
130  $dbs=$this->getTableNames();
131  $menu=$semantic->htmlMenu("menuDbs");
132  $menu->setVertical()->setInverted();
133  foreach ( $dbs as $table ) {
134  $model=$this->getModelsNS() . "\\" . ucfirst($table);
135  $file=\str_replace("\\", DS, ROOT . DS . $model) . ".php";
136  $find=UFileSystem::tryToRequire($file);
137  if ($find) {
138  $count=DAO::count($model);
139  $item=$menu->addItem(ucfirst($table));
140  $item->addLabel($count);
141  $tbl=OrmUtils::getTableName($model);
142  $item->setProperty("data-ajax", $tbl);
143  }
144  }
145  $menu->getOnClick($this->_getAdminFiles()->getAdminBaseRoute() . "/showTable", "#divTable", [ "attr" => "data-ajax" ]);
146  $menu->onClick("$('.ui.label.left.pointing.teal').removeClass('left pointing teal');$(this).find('.ui.label').addClass('left pointing teal');");
147  } catch ( \Exception $e ) {
148  throw $e;
149  $this->showSimpleMessage("Models cache is not created!&nbsp;", "error", "warning circle", null, "errorMsg");
150  }
151  $this->jquery->compile($this->view);
152  $this->loadView($this->_getAdminFiles()->getViewDataIndex());
153  } else {
154  echo $header;
155  echo $stepper;
156  echo "<div id='models-main'>";
157  $this->_loadModelStep();
158  echo "</div>";
159  echo $this->jquery->compile($this->view);
160  }
161  }
162 
163  public function controllers() {
164  $this->getHeader("controllers");
165  $controllersNS=Startup::getNS('controllers');
166  $controllersDir=ROOT . str_replace("\\", DS, $controllersNS);
167  $this->showSimpleMessage("Controllers directory is <b>" . UFileSystem::cleanPathname($controllersDir) . "</b>", "info", "info circle", null, "msgControllers");
168  $frm=$this->jquery->semantic()->htmlForm("frmCtrl");
169  $frm->setValidationParams([ "on" => "blur","inline" => true ]);
170  $input=$frm->addInput("name", null, "text", "", "Controller name")->addRules([ [ "empty","Controller name must have a value" ],"regExp[/^[A-Za-z]\w*$/]" ])->setWidth(8);
171  $input->labeledCheckbox(Direction::LEFT, "View", "v", "slider");
172  $input->addAction("Create controller", true, "plus", true)->addClass("teal")->asSubmit();
173  $frm->setSubmitParams($this->_getAdminFiles()->getAdminBaseRoute() . "/createController", "#main-content");
174  $this->_refreshControllers();
175  $this->jquery->compile($this->view);
176  $this->loadView($this->_getAdminFiles()->getViewControllersIndex());
177  }
178 
179  public function _refreshControllers($refresh=false) {
180  $dt=$this->_getAdminViewer()->getControllersDataTable(ControllerAction::init());
181  $this->jquery->postOnClick("._route[data-ajax]", $this->_getAdminFiles()->getAdminBaseRoute() . "/routes", "{filter:$(this).attr('data-ajax')}", "#main-content");
182  $this->jquery->postOnClick("._create-view", $this->_getAdminFiles()->getAdminBaseRoute() . "/_createView", "{action:$(this).attr('data-action'),controller:$(this).attr('data-controller'),controllerFullname:$(this).attr('data-controllerFullname')}", '$(self).closest("._views-container")', [ 'hasLoader' => false ]);
183  $this->jquery->execAtLast("$('#bt-0-controllersAdmin._clickFirst').click();");
184  $this->jquery->postOnClick("._add-new-action", $this->_getAdminFiles()->getAdminBaseRoute() . "/_newActionFrm", "{controller:$(this).attr('data-controller')}", "#modal", [ "hasLoader" => false ]);
185  $this->addNavigationTesting();
186  if ($refresh === "refresh") {
187  echo $dt;
188  echo $this->jquery->compile($this->view);
189  }
190  }
191 
192  public function routes() {
193  $this->getHeader("routes");
194  $this->showSimpleMessage("Router cache entry is <b>" . CacheManager::$cache->getEntryKey("controllers\\routes.default") . "</b>", "info", "info circle", null, "msgRoutes");
195  $routes=CacheManager::getRoutes();
196  $this->_getAdminViewer()->getRoutesDataTable(Route::init($routes));
197  $this->jquery->getOnClick("#bt-init-cache", $this->_getAdminFiles()->getAdminBaseRoute() . "/initCacheRouter", "#divRoutes", [ "dataType" => "html","attr" => "" ]);
198  $this->jquery->postOnClick("#bt-filter-routes", $this->_getAdminFiles()->getAdminBaseRoute() . "/filterRoutes", "{filter:$('#filter-routes').val()}", "#divRoutes", [ "ajaxTransition" => "random" ]);
199  if (isset($_POST["filter"]))
200  $this->jquery->exec("$(\"tr:contains('" . $_POST["filter"] . "')\").addClass('warning');", true);
201  $this->addNavigationTesting();
202  $this->jquery->compile($this->view);
203  $this->loadView($this->_getAdminFiles()->getViewRoutesIndex(), [ "url" => Startup::getConfig()["siteUrl"] ]);
204  }
205 
206  protected function addNavigationTesting() {
207  $this->jquery->postOnClick("._get", $this->_getAdminFiles()->getAdminBaseRoute() . "/_runAction", "{method:'get',url:$(this).attr('data-url')}", "#modal", [ "hasLoader" => false ]);
208  $this->jquery->postOnClick("._post", $this->_getAdminFiles()->getAdminBaseRoute() . "/_runAction", "{method:'post',url:$(this).attr('data-url')}", "#modal", [ "hasLoader" => false ]);
209  $this->jquery->postOnClick("._postWithParams", $this->_getAdminFiles()->getAdminBaseRoute() . "/_runPostWithParams", "{url:$(this).attr('data-url')}", "#modal", [ "attr" => "","hasLoader" => false ]);
210  }
211 
212  public function cache() {
213  $this->getHeader("cache");
214  $this->showSimpleMessage(CacheManager::$cache->getCacheInfo(), "info", "info circle", null, "msgCache");
215 
216  $cacheFiles=CacheManager::$cache->getCacheFiles('controllers');
217  $cacheFiles=\array_merge($cacheFiles, CacheManager::$cache->getCacheFiles('models'));
218  $form=$this->jquery->semantic()->htmlForm("frmCache");
219  $radios=HtmlFormFields::checkeds("cacheTypes[]", [ "controllers" => "Controllers","models" => "Models","views" => "Views","queries" => "Queries","annotations" => "Annotations","seo"=>"SEO" ], "Display cache types: ", [ "controllers","models" ]);
220  $radios->postFormOnClick($this->_getAdminFiles()->getAdminBaseRoute() . "/setCacheTypes", "frmCache", "#dtCacheFiles tbody", [ "jqueryDone" => "replaceWith" ]);
221  $form->addField($radios)->setInline();
222  $this->_getAdminViewer()->getCacheDataTable($cacheFiles);
223  $this->jquery->compile($this->view);
224  $this->loadView($this->_getAdminFiles()->getViewCacheIndex());
225  }
226 
227  public function rest() {
228  $this->getHeader("rest");
229  $this->showSimpleMessage("Router Rest cache entry is <b>" . CacheManager::$cache->getEntryKey("controllers\\routes.rest") . "</b>", "info", "info circle", null, "msgRest");
230  $this->_refreshRest();
231  $this->jquery->getOnClick("#bt-init-rest-cache", $this->_getAdminFiles()->getAdminBaseRoute() . "/initRestCache", "#divRest", [ "attr" => "","dataType" => "html" ]);
232  $this->jquery->postOn("change", "#access-token", $this->_getAdminFiles()->getAdminBaseRoute() . "/_saveToken", "{_token:$(this).val()}");
233  $token="";
234  if (isset($_SESSION["_token"])) {
235  $token=$_SESSION["_token"];
236  }
237  $this->jquery->getOnClick("#bt-new-resource", $this->_getAdminFiles()->getAdminBaseRoute() . "/_frmNewResource", "#div-new-resource", [ "attr" => "" ]);
238  $this->jquery->compile($this->view);
239  $this->loadView($this->_getAdminFiles()->getViewRestIndex(), [ "token" => $token ]);
240  }
241 
242  public function config($hasHeader=true) {
243  global $config;
244  if ($hasHeader === true)
245  $this->getHeader("config");
246  $this->_getAdminViewer()->getConfigDataElement($config);
247  $this->jquery->compile($this->view);
248  $this->loadView($this->_getAdminFiles()->getViewConfigIndex());
249  }
250 
251  public function logs() {
252  $this->getHeader("logs");
253  $this->jquery->compile($this->view);
254 
255  $this->loadView($this->_getAdminFiles()->getViewLogsIndex());
256  }
257 
258  public function seo() {
259  $this->getHeader("seo");
260  $this->_seo();
261  $this->jquery->compile($this->view);
262  $this->loadView($this->_getAdminFiles()->getViewSeoIndex());
263  }
264 
265  protected function _seo(){
266  $ctrls=ControllerSeo::init();
267  $dtCtrl=$this->jquery->semantic()->dataTable("seoCtrls", "Ubiquity\controllers\admin\popo\ControllerSeo", $ctrls);
268  $dtCtrl->setFields(['name','urlsFile','siteMapTemplate','route','inRobots','see']);
269  $dtCtrl->setIdentifierFunction('getName');
270  $dtCtrl->setCaptions(['Controller name','Urls file','SiteMap template','Route','In robots?','']);
271  $dtCtrl->fieldAsLabel('route','car',['jsCallback'=>function($lbl,$instance,$i,$index){if($instance->getRoute()==""){$lbl->setProperty('style','display:none;');}}]);
272  $dtCtrl->fieldAsCheckbox('inRobots',['type'=>'toggle','disabled'=>true]);
273  $dtCtrl->setValueFunction('see',function($value,$instance,$index){
274  if($instance->urlExists()){
275  $bt=new HtmlButton('see-'.$index,'','_see circular basic right floated');
276  $bt->setProperty("data-ajax", $instance->getName());
277  $bt->asIcon('eye');
278  return $bt;
279  }
280  });
281  $dtCtrl->setValueFunction('urlsFile', function($value,$instance,$index){
282  if(!$instance->urlExists()){
283  $elm=new HtmlSemDoubleElement('urls-'.$index,'span','',$value);
284  $elm->addIcon("warning circle red");
285  $elm->addPopup("Missing",$value.' is missing!');
286  return $elm;
287  }
288  return $value;
289  });
290  $dtCtrl->addDeleteButton(false,[],function($bt){$bt->setProperty('class','ui circular basic red right floated icon button _delete');});
291  $dtCtrl->setTargetSelector(["delete"=>"#messages"]);
292  $dtCtrl->setUrls(["delete"=>$this->_getAdminFiles()->getAdminBaseRoute()."/deleteSeoController"]);
293  $dtCtrl->getOnRow('click', $this->_getAdminFiles()->getAdminBaseRoute().'/displaySiteMap','#seo-details',['attr'=>'data-ajax','hasLoader'=>false]);
294  $dtCtrl->setHasCheckboxes(true);
295  $dtCtrl->setSubmitParams($this->_getAdminFiles()->getAdminBaseRoute().'/generateRobots', "#messages",['attr'=>'','ajaxTransition'=>'random']);
296  $dtCtrl->setActiveRowSelector('error');
297  $this->jquery->getOnClick("._see", $this->_getAdminFiles()->getAdminBaseRoute()."/seeSeoUrl","#messages",["attr"=>"data-ajax"]);
298  $this->jquery->execOn('click', '#generateRobots', '$("#frm-seoCtrls").form("submit");');
299  $this->jquery->getOnClick('#addNewSeo', $this->_getAdminFiles()->getAdminBaseRoute().'/_newSeoController','#seo-details');
300  return $dtCtrl;
301  }
302 
303  protected function getHeader($key) {
304  $semantic=$this->jquery->semantic();
305  $header=$semantic->htmlHeader("header", 3);
306  $e=$this->_getAdminViewer()->getMainMenuElements()[$key];
307  $header->asTitle($e[0], $e[2]);
308  $header->addIcon($e[1]);
309  $header->setBlock()->setInverted();
310  return $header;
311  }
312 
313  public function _showDiagram() {
314  if (URequest::isPost()) {
315  if (isset($_POST["model"])) {
316  $model=$_POST["model"];
317  $model=\str_replace("|", "\\", $model);
318  $modal=$this->jquery->semantic()->htmlModal("diagram", "Class diagram : " . $model);
319  $yuml=$this->_getClassToYuml($model, $_POST);
320  $menu=$this->_diagramMenu("/_updateDiagram", "{model:'" . $_POST["model"] . "',refresh:'true'}", "#diag-class");
321  $modal->setContent([ $menu,"<div id='diag-class' class='ui center aligned grid' style='margin:10px;'>",$this->_getYumlImage("plain", $yuml . ""),"</div>" ]);
322  $modal->addAction("Close");
323  $this->jquery->exec("$('#diagram').modal('show');", true);
324  $modal->onHidden("$('#diagram').remove();");
325  echo $modal;
326  echo $this->jquery->compile($this->view);
327  }
328  }
329  }
330 
331  private function _getClassToYuml($model, $post) {
332  if (isset($post["properties"])) {
333  $props=\array_flip($post["properties"]);
334  $yuml=new ClassToYuml($model, isset($props["displayProperties"]), isset($props["displayAssociations"]), isset($props["displayMethods"]), isset($props["displayMethodsParams"]), isset($props["displayPropertiesTypes"]), isset($props["displayAssociationClassProperties"]));
335  if (isset($props["displayAssociations"])) {
336  $yuml->init(true, true);
337  }
338  } else {
339  $yuml=new ClassToYuml($model, !isset($_POST["refresh"]));
340  $yuml->init(true, true);
341  }
342  return $yuml;
343  }
344 
345  private function _getClassesToYuml($post) {
346  if (isset($post["properties"])) {
347  $props=\array_flip($post["properties"]);
348  $yuml=new ClassesToYuml(isset($props["displayProperties"]), isset($props["displayAssociations"]), isset($props["displayMethods"]), isset($props["displayMethodsParams"]), isset($props["displayPropertiesTypes"]));
349  } else {
350  $yuml=new ClassesToYuml(!isset($_POST["refresh"]), !isset($_POST["refresh"]));
351  }
352  return $yuml;
353  }
354 
355  public function _updateDiagram() {
356  if (URequest::isPost()) {
357  if (isset($_POST["model"])) {
358  $model=$_POST["model"];
359  $model=\str_replace("|", "\\", $model);
360  $type=$_POST["type"];
361  $size=$_POST["size"];
362  $yuml=$this->_getClassToYuml($model, $_POST);
363  echo $this->_getYumlImage($type . $size, $yuml . "");
364  echo $this->jquery->compile($this->view);
365  }
366  }
367  }
368 
377  private function _diagramMenu($url="/_updateDiagram", $params="{}", $responseElement="#diag-class", $type="plain", $size=";scale:100") {
378  $params=JsUtils::_implodeParams([ "$('#frmProperties').serialize()",$params ]);
379  $menu=new HtmlMenu("menu-diagram");
380  $popup=$menu->addPopupAsItem("Display", "Parameters");
381  $list=new HtmlList("lst-checked");
382  $list->addCheckedList([ "displayPropertiesTypes" => "Types" ], [ "Properties","displayProperties" ], [ "displayPropertiesTypes" ], true, "properties[]");
383  $list->addCheckedList([ "displayMethodsParams" => "Parameters" ], [ "Methods","displayMethods" ], [ ], true, "properties[]");
384  $list->addCheckedList([ "displayAssociationClassProperties" => "Associated class members" ], [ "Associations","displayAssociations" ], [ "displayAssociations" ], true, "properties[]");
385  $btApply=new HtmlButton("bt-apply", "Apply", "green fluid");
386  $btApply->postOnClick($this->_getAdminFiles()->getAdminBaseRoute() . $url, $params, $responseElement, [ "ajaxTransition" => "random","params" => $params,"attr" => "","jsCallback" => "$('#Parameters').popup('hide');" ]);
387  $list->addItem($btApply);
388  $popup->setContent($list);
389  $ddScruffy=new HtmlDropdown("ddScruffy", $type, [ "nofunky" => "Boring","plain" => "Plain","scruffy" => "Scruffy" ], true);
390  $ddScruffy->setValue("plain")->asSelect("type");
391  $this->jquery->postOn("change", "#type", $this->_getAdminFiles()->getAdminBaseRoute() . $url, $params, $responseElement, [ "ajaxTransition" => "random","attr" => "" ]);
392  $menu->addItem($ddScruffy);
393  $ddSize=new HtmlDropdown("ddSize", $size, [ ";scale:180" => "Huge",";scale:120" => "Big",";scale:100" => "Normal",";scale:80" => "Small",";scale:60" => "Tiny" ], true);
394  $ddSize->asSelect("size");
395  $this->jquery->postOn("change", "#size", $this->_getAdminFiles()->getAdminBaseRoute() . $url, $params, $responseElement, [ "ajaxTransition" => "random","attr" => "" ]);
396  $menu->wrap("<form id='frmProperties' name='frmProperties'>", "</form>");
397  $menu->addItem($ddSize);
398  return $menu;
399  }
400 
401  public function _showAllClassesDiagram() {
402  $yumlContent=new ClassesToYuml();
403  $menu=$this->_diagramMenu("/_updateAllClassesDiagram", "{refresh:'true'}", "#diag-class");
404  $this->jquery->exec('$("#modelsMessages-success").hide()', true);
405  $menu->compile($this->jquery, $this->view);
406  $form=$this->jquery->semantic()->htmlForm("frm-yuml-code");
407  $textarea=$form->addTextarea("yuml-code", "Yuml code", \str_replace(",", ",\n", $yumlContent . ""));
408  $textarea->getField()->setProperty("rows", 20);
409  $diagram=$this->_getYumlImage("plain", $yumlContent);
410  $this->jquery->execAtLast('$("#all-classes-diagram-tab .item").tab();');
411  $this->jquery->compile($this->view);
412  $this->loadView($this->_getAdminFiles()->getViewClassesDiagram(), [ "diagram" => $diagram ]);
413  }
414 
415  public function _updateAllClassesDiagram() {
416  if (URequest::isPost()) {
417  $type=$_POST["type"];
418  $size=$_POST["size"];
419  $yumlContent=$this->_getClassesToYuml($_POST);
420  $this->jquery->exec('$("#yuml-code").html("' . \htmlentities($yumlContent . "") . '")', true);
421  echo $this->_getYumlImage($type . $size, $yumlContent);
422  echo $this->jquery->compile();
423  }
424  }
425 
426  protected function _getYumlImage($sizeType, $yumlContent) {
427  return "<img src='http://yuml.me/diagram/" . $sizeType . "/class/" . $yumlContent . "'>";
428  }
429 
430  public function showDatabaseCreation() {
431  $config=Startup::getConfig();
432  $models=$this->getModels();
433  $segment=$this->jquery->semantic()->htmlSegment("menu");
434  $segment->setTagName("form");
435  $header=new HtmlHeader("", 5, "Database creation");
436  $header->addIcon("plus");
437  $segment->addContent($header);
438  $input=new HtmlFormInput("dbName");
439  $input->setValue($config["database"]["dbName"]);
440  $input->getField()->setFluid();
441  $segment->addContent($input);
442  $list=new HtmlList("lst-checked");
443  $list->addCheckedList([ "dbCreation" => "Creation","dbUse" => "Use" ], [ "Database","db" ], [ "use","creation" ], false, "dbProperties[]");
444  $list->addCheckedList($models, [ "Models [tables]","modTables" ], \array_keys($models), false, "tables[]");
445  $list->addCheckedList([ "manyToOne" => "ManyToOne","oneToMany" => "oneToMany" ], [ "Associations","displayAssociations" ], [ "displayAssociations" ], false, "associations[]");
446  $btApply=new HtmlButton("bt-apply", "Create SQL script", "green fluid");
447  $btApply->postFormOnClick($this->_getAdminFiles()->getAdminBaseRoute() . "/createSQLScript", "menu", "#div-create", [ "ajaxTransition" => "random","attr" => "" ]);
448  $list->addItem($btApply);
449 
450  $segment->addContent($list);
451  $this->jquery->compile($this->view);
452  $this->loadView($this->_getAdminFiles()->getViewDatabaseIndex());
453  }
454 
455  public function _runPostWithParams($method="post", $type="parameter", $origine="routes") {
456  if (URequest::isPost()) {
457  $model=null;
458  $actualParams=[ ];
459  $url=$_POST["url"];
460  if (isset($_POST["method"]))
461  $method=$_POST["method"];
462  if (isset($_POST["model"])) {
463  $model=$_POST["model"];
464  }
465 
466  if ($origine === "routes") {
467  $responseElement="#modal";
468  $responseURL="/_runAction";
469  $jqueryDone="html";
470  $toUpdate="";
471  } else {
472  $toUpdate=$_POST["toUpdate"];
473  $responseElement="#" . $toUpdate;
474  $responseURL="/_saveRequestParams/" . $type;
475  $jqueryDone="replaceWith";
476  }
477  if (isset($_POST["actualParams"])) {
478  $actualParams=$this->_getActualParamsAsArray($_POST["actualParams"]);
479  }
480  $modal=$this->jquery->semantic()->htmlModal("response-with-params", "Parameters for the " . \strtoupper($method) . ":" . $url);
481  $frm=$this->jquery->semantic()->htmlForm("frmParams");
482  $frm->addMessage("msg", "Enter your " . $type . "s.", \ucfirst($method) . " " . $type . "s", "info circle");
483  $index=0;
484  foreach ( $actualParams as $name => $value ) {
485  $this->_addNameValueParamFields($frm, $type, $name, $value, $index++);
486  }
487  $this->_addNameValueParamFields($frm, $type, "", "", $index++);
488 
489  $fieldsButton=$frm->addFields();
490  $fieldsButton->addClass("_notToClone");
491  $fieldsButton->addButton("clone", "Add " . $type, "yellow")->setTagName("div");
492  if (isset($model)) {
494  $modelFields=OrmUtils::getSerializableFields($model);
495  if (\sizeof($modelFields) > 0) {
496  $modelFields=\array_combine($modelFields, $modelFields);
497  $ddModel=$fieldsButton->addDropdown("bt-addModel", $modelFields, "Add " . $type . "s from " . $model);
498  $ddModel->asButton();
499  $this->jquery->click("#dropdown-bt-addModel .item", "
500  var text=$(this).text();
501  var count=0;
502  var empty=null;
503  $('#frmParams input[name=\'name[]\']').each(function(){
504  if($(this).val()==text) count++;
505  if($(this).val()=='') empty=this;
506  });
507  if(count<1){
508  if(empty==null){
509  $('#clone').click();
510  var inputs=$('.fields:not(._notToClone)').last().find('input');
511  inputs.first().val($(this).text());
512  }else{
513  $(empty).val($(this).text());
514  }
515  }
516  ");
517  }
518  }
519  if (isset($_COOKIE[$method]) && \sizeof($_COOKIE[$method]) > 0) {
520  $dd=$fieldsButton->addDropdownButton("btMem", "Memorized " . $type . "s", $_COOKIE[$method])->getDropdown()->setPropertyValues("data-mem", \array_map("addslashes", $_COOKIE[$method]));
521  $cookiesIndex=\array_keys($_COOKIE[$method]);
522  $dd->each(function ($i, $item) use ($cookiesIndex) {
523  $bt=new HtmlButton("bt-" . $item->getIdentifier());
524  $bt->asIcon("remove")->addClass("basic _deleteParam");
525  $bt->getOnClick($this->_getAdminFiles()->getAdminBaseRoute() . "/_deleteCookie", null, [ "attr" => "data-value" ]);
526  $bt->setProperty("data-value", $cookiesIndex[$i]);
527  $bt->onClick("$(this).parents('.item').remove();");
528  $item->addContent($bt, true);
529  });
530  $this->jquery->click("[data-mem]", "
531  var objects=JSON.parse($(this).text());
532  $.each(objects, function(name, value) {
533  $('#clone').click();
534  var inputs=$('.fields:not(._notToClone)').last().find('input');
535  inputs.first().val(name);
536  inputs.last().val(value);
537  });
538  $('.fields:not(._notToClone)').each(function(){
539  var inputs=$(this).find('input');
540  if(inputs.last().val()=='' && inputs.last().val()=='')
541  if($('.fields').length>2)
542  $(this).remove();
543  });
544  ");
545  }
546  $this->jquery->click("._deleteParameter", "
547  if($('.fields').length>2)
548  $(this).parents('.fields').remove();
549  ", true, true, true);
550  $this->jquery->click("#clone", "
551  var cp=$('.fields:not(._notToClone)').last().clone(true);
552  var num = parseInt( cp.prop('id').match(/\d+/g), 10 ) +1;
553  cp.find( '[id]' ).each( function() {
554  var num = $(this).attr('id').replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } );
555  $(this).attr( 'id', num );
556  $(this).val('');
557  });
558  cp.insertBefore($('#clone').closest('.fields'));");
559  $frm->setValidationParams([ "on" => "blur","inline" => true ]);
560  $frm->setSubmitParams($this->_getAdminFiles()->getAdminBaseRoute() . $responseURL, $responseElement, [ "jqueryDone" => $jqueryDone,"params" => "{toUpdate:'" . $toUpdate . "',method:'" . \strtoupper($method) . "',url:'" . $url . "'}" ]);
561  $modal->setContent($frm);
562  $modal->addAction("Validate");
563  $this->jquery->click("#action-response-with-params-0", "$('#frmParams').form('submit');", false, false, false);
564 
565  $modal->addAction("Close");
566  $this->jquery->exec("$('.dimmer.modals.page').html('');$('#response-with-params').modal('show');", true);
567  echo $modal->compile($this->jquery, $this->view);
568  echo $this->jquery->compile($this->view);
569  }
570  }
571 
572  protected function _getActualParamsAsArray($urlEncodedParams) {
573  $result=[ ];
574  $params=[ ];
575  \parse_str(urldecode($urlEncodedParams), $params);
576  if (isset($params["name"])) {
577  $names=$params["name"];
578  $values=$params["value"];
579  $count=\sizeof($names);
580  for($i=0; $i < $count; $i++) {
581  $name=$names[$i];
582  if (UString::isNotNull($name)) {
583  if (isset($values[$i]))
584  $result[$name]=$values[$i];
585  }
586  }
587  }
588  return $result;
589  }
590 
591  protected function _addNameValueParamFields($frm, $type, $name, $value, $index) {
592  $fields=$frm->addFields();
593  $fields->addInput("name[]", \ucfirst($type) . " name")->getDataField()->setIdentifier("name-" . $index)->setProperty("value", $name);
594  $input=$fields->addInput("value[]", \ucfirst($type) . " value");
595  $input->getDataField()->setIdentifier("value-" . $index)->setProperty("value", $value);
596  $input->addAction("", true, "remove")->addClass("icon basic _deleteParameter");
597  }
598 
599  public function _deleteCookie($index, $type="post") {
600  $name=$type . "[" . $index . "]";
601  if (isset($_COOKIE[$type][$index])) {
602  \setcookie($name, "", \time() - 3600, "/", "127.0.0.1");
603  }
604  }
605 
606  private function _setPostCookie($content, $method="post", $index=null) {
607  if (isset($_COOKIE[$method])) {
608  $cookieValues=\array_values($_COOKIE[$method]);
609  if ((\array_search($content, $cookieValues)) === false) {
610  if (!isset($index))
611  $index=\sizeof($_COOKIE[$method]);
612  setcookie($method . "[" . $index . "]", $content, \time() + 36000, "/", "127.0.0.1");
613  }
614  } else {
615  if (!isset($index))
616  $index=0;
617  setcookie($method . "[" . $index . "]", $content, \time() + 36000, "/", "127.0.0.1");
618  }
619  }
620 
621  private function _setGetCookie($index, $content) {
622  setcookie("get[" . $index . "]", $content, \time() + 36000, "/", "127.0.0.1");
623  }
624 
625  public function _runAction($frm=null) {
626  if (URequest::isPost()) {
627  $url=URequest::cleanUrl($_POST["url"]);
628  unset($_POST["url"]);
629  $method=$_POST["method"];
630  unset($_POST["method"]);
631  $newParams=null;
632  $postParams=$_POST;
633  if (\sizeof($_POST) > 0) {
634  if (\strtoupper($method) === "POST" && $frm !== "frmGetParams") {
635  $postParams=[ ];
636  $keys=$_POST["name"];
637  $values=$_POST["value"];
638  for($i=0; $i < \sizeof($values); $i++) {
639  if (JString::isNotNull($keys[$i]))
640  $postParams[$keys[$i]]=$values[$i];
641  }
642  if (\sizeof($postParams) > 0) {
643  $this->_setPostCookie(\json_encode($postParams));
644  }
645  } else {
646  $newParams=$_POST;
647  $this->_setGetCookie($url, \json_encode($newParams));
648  }
649  }
650  $modal=$this->jquery->semantic()->htmlModal("response", \strtoupper($method) . ":" . $url);
651  $params=$this->getRequiredRouteParameters($url, $newParams);
652  if (\sizeof($params) > 0) {
653  $toPost=\array_merge($postParams, [ "method" => $method,"url" => $url ]);
654  $frm=$this->jquery->semantic()->htmlForm("frmGetParams");
655  $frm->addMessage("msg", "You must complete the following parameters before continuing navigation testing", "Required URL parameters", "info circle");
656  $paramsValues=$this->_getParametersFromCookie($url, $params);
657  foreach ( $paramsValues as $param => $value ) {
658  $frm->addInput($param, \ucfirst($param))->addRule("empty")->setValue($value);
659  }
660  $frm->setValidationParams([ "on" => "blur","inline" => true ]);
661  $frm->setSubmitParams($this->_getAdminFiles()->getAdminBaseRoute() . "/_runAction", "#modal", [ "params" => \json_encode($toPost) ]);
662  $modal->setContent($frm);
663  $modal->addAction("Validate");
664  $this->jquery->click("#action-response-0", "$('#frmGetParams').form('submit');");
665  } else {
666  $this->jquery->ajax($method, $url, '#content-response.content', [ "params" => \json_encode($postParams) ]);
667  }
668  $modal->addAction("Close");
669  $this->jquery->exec("$('.dimmer.modals.page').html('');$('#response').modal('show');", true);
670  echo $modal;
671  echo $this->jquery->compile($this->view);
672  }
673  }
674 
675  private function _getParametersFromCookie($url, $params) {
676  $result=\array_fill_keys($params, "");
677  if (isset($_COOKIE["get"])) {
678  if (isset($_COOKIE["get"][$url])) {
679  $values=\json_decode($_COOKIE["get"][$url], true);
680  foreach ( $params as $p ) {
681  $result[$p]=@$values[$p];
682  }
683  }
684  }
685  return $result;
686  }
687 
688  private function getRequiredRouteParameters(&$url, $newParams=null) {
689  $url=stripslashes($url);
690  $route=Router::getRouteInfo($url);
691  if ($route === false) {
692  $ns=Startup::getNS();
693  $u=\explode("/", $url);
694  $controller=$ns . $u[0];
695  if (\sizeof($u) > 1)
696  $action=$u[1];
697  else
698  $action="index";
699  if (isset($newParams) && \sizeof($newParams) > 0) {
700  $url=$u[0] . "/" . $action . "/" . \implode("/", \array_values($newParams));
701  return [ ];
702  }
703  } else {
704  if (isset($newParams) && \sizeof($newParams) > 0) {
705  $routeParameters=$route["parameters"];
706  $i=0;
707  foreach ( $newParams as $v ) {
708  if (isset($routeParameters[$i]))
709  $result[( int ) $routeParameters[$i++]]=$v;
710  }
711  ksort($result);
712 
713  $url=vsprintf(\preg_replace('#\([^\)]+\)#', '%s', $url), $result);
714  return [ ];
715  }
716  $controller=$route["controller"];
717  $action=$route["action"];
718  }
719  if (\class_exists($controller)) {
720  if (\method_exists($controller, $action)) {
721  $method=new \ReflectionMethod($controller, $action);
722  return \array_map(function ($e) {
723  return $e->name;
724  }, \array_slice($method->getParameters(), 0, $method->getNumberOfRequiredParameters()));
725  }
726  }
727  return [ ];
728  }
729 
730  public function getIdentifierFunction($model) {
731  $pks=$this->getPks($model);
732  return function ($index, $instance) use ($pks) {
733  $values=[ ];
734  foreach ( $pks as $pk ) {
735  $getter="get" . ucfirst($pk);
736  if (method_exists($instance, $getter)) {
737  $values[]=$instance->{$getter}();
738  }
739  }
740  return implode("_", $values);
741  };
742  }
743 
744  protected function _createController($controllerName,$variables=[],$ctrlTemplate='controller.tpl',$hasView=false,$jsCallback=""){
745  $message="";
746  $frameworkDir=Startup::getFrameworkDir();
747  $controllersNS=\rtrim(Startup::getNS("controllers"),"\\");
748  $controllersDir=ROOT . DS . str_replace("\\", DS, $controllersNS);
749  $controllerName=\ucfirst($controllerName);
750  $filename=$controllersDir . DS . $controllerName . ".php";
751  if (\file_exists($filename) === false) {
752  if ($controllersNS !== ""){
753  $namespace="namespace " . $controllersNS . ";";
754  }
755  $msgView="";
756  $indexContent="";
757  if ($hasView) {
758  $viewDir=ROOT . DS . "views" . DS . $controllerName . DS;
759  UFileSystem::safeMkdir($viewDir);
760  $viewName=$viewDir . DS . "index.html";
761  UFileSystem::openReplaceWriteFromTemplateFile($frameworkDir . "/admin/templates/view.tpl", $viewName, [ "%controllerName%" => $controllerName,"%actionName%" => "index" ]);
762  $msgView="<br>The default view associated has been created in <b>" . UFileSystem::cleanPathname(ROOT . DS . $viewDir) . "</b>";
763  $indexContent="\$this->loadView(\"" . $controllerName . "/index.html\");";
764  }
765  $variables=\array_merge($variables,[ "%controllerName%" => $controllerName,"%indexContent%" => $indexContent,"%namespace%" => $namespace ]);
766  UFileSystem::openReplaceWriteFromTemplateFile($frameworkDir . "/admin/templates/".$ctrlTemplate, $filename, $variables);
767  $msgContent="The <b>" . $controllerName . "</b> controller has been created in <b>" . UFileSystem::cleanPathname($filename) . "</b>." . $msgView;
768  if(isset($variables["%path%"]) && $variables["%path%"]!==""){
769  $msgContent.=$this->_addMessageForRouteCreation($variables["%path%"],$jsCallback);
770  }
771  $message=$this->showSimpleMessage($msgContent, "success", "checkmark circle", NULL, "msgGlobal");
772  } else {
773  $message=$this->showSimpleMessage("The file <b>" . $filename . "</b> already exists.<br>Can not create the <b>" . $controllerName . "</b> controller!", "warning", "warning circle", 100000, "msgGlobal");
774  }
775  return $message;
776  }
777 
778  protected function _addMessageForRouteCreation($path,$jsCallback=""){
779  $msgContent="<br>Created route : <b>" . $path . "</b>";
780  $msgContent.="<br>You need to re-init Router cache to apply this update:";
781  $btReinitCache=new HtmlButton("bt-init-cache", "(Re-)Init router cache", "orange");
782  $btReinitCache->addIcon("refresh");
783  $msgContent.="&nbsp;" . $btReinitCache;
784  $this->jquery->getOnClick("#bt-init-cache", $this->_getAdminFiles()->getAdminBaseRoute() . "/_refreshCacheControllers", "#messages", [ "attr" => "","hasLoader" => false,"dataType" => "html","jsCallback"=>$jsCallback ]);
785  return $msgContent;
786  }
787 
788  public function showSimpleMessage($content, $type, $icon="info", $timeout=NULL, $staticName=null) {
789  $semantic=$this->jquery->semantic();
790  if (!isset($staticName))
791  $staticName="msg-" . rand(0, 50);
792  $message=$semantic->htmlMessage($staticName, $content, $type);
793  $message->setIcon($icon . " circle");
794  $message->setDismissable();
795  if (isset($timeout))
796  $message->setTimeout(3000);
797  return $message;
798  }
799 
800  protected function showConfMessage($content, $type, $url, $responseElement, $data, $attributes=NULL) {
801  $messageDlg=$this->showSimpleMessage($content, $type, "help circle");
802  $btOkay=new HtmlButton("bt-okay", "Confirm", "negative");
803  $btOkay->addIcon("check circle");
804  $btOkay->postOnClick($url, "{data:'" . $data . "'}", $responseElement, $attributes);
805  $btCancel=new HtmlButton("bt-cancel-" . UString::cleanAttribute($url), "Cancel");
806  $btCancel->addIcon("remove circle outline");
807  $btCancel->onClick($messageDlg->jsHide());
808  $messageDlg->addContent([ new HtmlDivider(""),new HtmlSemDoubleElement("", "div", "", [ $btOkay->floatRight(),$btCancel->floatRight() ]) ]);
809  return $messageDlg;
810  }
811 
812  protected function getUbiquityMyAdminData() {
813  return new UbiquityMyAdminData();
814  }
815 
816  protected function getUbiquityMyAdminViewer() {
817  return new UbiquityMyAdminViewer($this);
818  }
819 
820  protected function getUbiquityMyAdminFiles() {
821  return new UbiquityMyAdminFiles();
822  }
823 
824  private function getSingleton($value, $method) {
825  if (!isset($value)) {
826  $value=$this->$method();
827  }
828  return $value;
829  }
830 
835  public function _getAdminData() {
836  return $this->getSingleton($this->adminData, "getUbiquityMyAdminData");
837  }
838 
843  public function _getAdminViewer() {
844  return $this->getSingleton($this->adminViewer, "getUbiquityMyAdminViewer");
845  }
846 
851  public function _getAdminFiles() {
852  return $this->getSingleton($this->adminFiles, "getUbiquityMyAdminFiles");
853  }
854 
855  protected function getTableNames() {
856  return $this->_getAdminData()->getTableNames();
857  }
858 
859  public function getFieldNames($model) {
860  return $this->_getAdminData()->getFieldNames($model);
861  }
862 }
static isPost()
Returns true if the request is sent by the POST method.
Definition: URequest.php:109
loadView($viewName, $pData=NULL, $asString=false)
static getModelsName($config, $name)
static getRouteInfo($path)
Definition: Router.php:73
_diagramMenu($url="/_updateDiagram", $params="{}", $responseElement="#diag-class", $type="plain", $size=";scale:100")
_loadModelStep($engineering=null, $newStep=null)
The base class for displaying datas in UbiquityMyAdminController.
_createController($controllerName, $variables=[], $ctrlTemplate='controller.tpl', $hasView=false, $jsCallback="")
static getNS($part="controllers")
Definition: Startup.php:43
static cleanAttribute($attr, $replacement="_")
Definition: UString.php:84
static openReplaceWriteFromTemplateFile($source, $destination, $keyAndValues)
Definition: UFileSystem.php:62
static isAjax()
Returns true if the request is an Ajax request.
Definition: URequest.php:101
showSimpleMessage($content, $type, $icon="info", $timeout=NULL, $staticName=null)
static count($className, $condition='')
Returns the number of objects of $className from the database respecting the condition possibly passe...
Definition: DAO.php:332
static getTableName($class)
Definition: OrmUtils.php:61
showConfMessage($content, $type, $url, $responseElement, $data, $attributes=NULL)
static getSerializableFields($class)
Definition: OrmUtils.php:216
_runPostWithParams($method="post", $type="parameter", $origine="routes")