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