Ubiquity  2.0.0
php rapid development framework
SeoTrait.php
Go to the documentation of this file.
1 <?php
2 
4 
5 use Ajax\JsUtils;
16 
22 class SeoTrait{
23 
24  abstract public function _getAdminData();
25 
26  abstract public function _getAdminViewer();
27 
28  abstract public function _getAdminFiles();
29 
30  abstract public function loadView($viewName, $pData=NULL, $asString=false);
31 
32  abstract public function seo();
33 
34  abstract protected function showSimpleMessage($content, $type, $icon="info", $timeout=NULL, $staticName=null);
35 
36  abstract protected function _createController($controllerName, $variables=[], $ctrlTemplate='controller.tpl', $hasView=false);
37 
38  public function displaySiteMap(...$params) {
39  $controllerClass=\implode("\\", $params);
40  $controllerSeo=new $controllerClass();
41  USession::set("seo-sitemap", $controllerSeo);
42  $array=$controllerSeo->_getArrayUrls();
43  $parser=new UrlParser();
44  $parser->parseArray($array, true);
45  $parser->parse();
46  $urls=$parser->getUrls();
47  $dt=$this->jquery->semantic()->dataTable("dtSiteMap", 'Ubiquity\seo\Url', $urls);
48  $dt->setFields([ 'location','lastModified','changeFrequency','priority','delete' ]);
49  $dt->setCaptions([ 'Location','Last Modified','Change Frequency','Priority','' ]);
50  $dt->fieldAsInput("location");
51  $dt->setValueFunction("lastModified", function ($v, $o, $i) {
52  $d=date('Y-m-d\TH:i', $v);
53  $input=new HtmlInput("date-" . $i, 'datetime-local', $d);
54  $input->setName("lastModified[]");
55  return $input;
56  });
58  $dt->fieldAsDropDown('changeFrequency', \array_combine($freq, $freq));
59  $dt->setValueFunction("priority", function ($v, $o, $i) {
60  $input=new HtmlInput("priority-" . $i, 'number', $v);
61  $f=$input->getDataField();
62  $f->setProperty('name', 'priority[]');
63  $f->setProperty('max', '1')->setProperty('min', '0')->setProperty('step', '0.1');
64  return $input;
65  });
66  $dt->onNewRow(function ($row, $instance) {
67  if ($instance->getExisting()) {
68  $row->addClass('positive');
69  } else {
70  $row->setProperty('style', 'display: none;')->addClass('toToggle');
71  }
72  });
73 
74  $dt->setHasCheckboxes(true);
75  $dt->setCheckedCallback(function ($object) {
76  return $object->getExisting();
77  });
78  $dt->asForm();
79  $dt->setSubmitParams($this->_getAdminFiles()->getAdminBaseRoute() . "/saveUrls", "#seo-details", [ 'attr' => '' ]);
80  $this->jquery->execOn("click", "#saveUrls", '$("#frm-dtSiteMap").form("submit");');
81 
82  $this->jquery->click('#displayAllRoutes', '$(".toToggle").toggle();$(this).toggleClass("active");');
83  $this->jquery->compile($this->view);
84 
85  $this->loadView($this->_getAdminFiles()->getViewSeoDetails(), [ "controllerClass" => $controllerClass,"urlsFile" => $controllerSeo->_getUrlsFilename() ]);
86  }
87 
88  public function generateRobots() {
89  $frameworkDir=Startup::getFrameworkDir();
90  $config=Startup::getConfig();
91  $siteUrl=$config["siteUrl"];
92  $content=[ ];
93  if (URequest::isPost()) {
94  $template=UFileSystem::load($frameworkDir . "/admin/templates/robots.tpl");
95  $urls=URequest::post('selection', [ ]);
96  foreach ( $urls as $url ) {
97  $content[]=\str_replace("%url%", URequest::cleanUrl($siteUrl . $url), $template);
98  }
99  if (\sizeof($content) > 0) {
100  $appDir=Startup::getApplicationDir() . './../';
101  $content=\implode("\n", $content);
102  UFileSystem::save($appDir . DS . 'robots.txt', $content);
103  $msg=$this->showSimpleMessage("The file <b>robots.txt</b> has been generated in " . $appDir, "success", "info circle");
104  } else {
105  $msg=$this->showSimpleMessage("Can not generate <b>robots.txt</b> if no SEO controller is selected.", "warning", "warning circle");
106  }
107  echo $msg;
108  echo $this->jquery->compile($this->view);
109  }
110  }
111 
112  public function _newSeoController() {
113  $modal=$this->jquery->semantic()->htmlModal("modalNewSeo", "Creating a new Seo controller");
114  $modal->setInverted();
115  $frm=$this->jquery->semantic()->htmlForm("frmNewSeo");
116  $fc=$frm->addField('controllerName')->addRule([ "checkController","Controller {value} already exists!" ]);
117  $fc->labeled(Startup::getNS());
118  $fields=$frm->addFields([ "urlsFile","sitemapTemplate" ], "Urls file & sitemap twig template");
119  $fields->setFieldsPropertyValues("value", [ "urls","Seo/sitemap.xml.html" ]);
120  $fields->getItem(0)->addRules([ "empty" ]);
121 
122  $frm->addCheckbox("ck-add-route", "Add route...");
123 
124  $frm->addContent("<div id='div-new-route' style='display: none;'>");
125  $frm->addDivider();
126  $frm->addInput("path", "", "text", "")->addRule([ "checkRoute","Route {value} already exists!" ]);
127  $frm->addContent("</div>");
128 
129  $frm->setValidationParams([ "on" => "blur","inline" => true ]);
130  $frm->setSubmitParams($this->_getAdminFiles()->getAdminBaseRoute() . "/createSeoController", "#main-content");
131  $modal->setContent($frm);
132  $modal->addAction("Validate");
133  $this->jquery->click("#action-modalNewSeo-0", "$('#frmNewSeo').form('submit');", false, false);
134  $modal->addAction("Close");
135  $this->jquery->change('#controllerName', 'if($("#ck-add-route").is(":checked")){$("#path").val($(this).val());}');
136  $this->jquery->exec("$('.dimmer.modals.page').html('');$('#modalNewSeo').modal('show');", true);
137  $this->jquery->jsonOn("change", "#ck-add-route", $this->_getAdminFiles()->getAdminBaseRoute() . "/_addRouteWithNewAction", "post", [ "context" => "$('#frmNewSeo')","params" => "$('#frmNewSeo').serialize()","jsCondition" => "$('#ck-add-route').is(':checked')" ]);
138  $this->jquery->exec(Rule::ajax($this->jquery, "checkRoute", $this->_getAdminFiles()->getAdminBaseRoute() . "/_checkRoute", "{}", "result=data.result;", "postForm", [ "form" => "frmNewSeo" ]), true);
139  $this->jquery->exec(Rule::ajax($this->jquery, "checkController", $this->_getAdminFiles()->getAdminBaseRoute() . "/_checkController", "{}", "result=data.result;", "postForm", [ "form" => "frmNewSeo" ]), true);
140  $this->jquery->change("#ck-add-route", '$("#div-new-route").toggle($(this).is(":checked"));if($(this).is(":checked")){$("#path").val($("#controllerName").val());}');
141  echo $modal;
142  echo $this->jquery->compile($this->view);
143  }
144 
145  public function createSeoController($force=null) {
146  if (URequest::isPost()) {
147  $variables=[ ];
148  $path=URequest::post("path");
149  $variables["%path%"]=$path;
150  if (isset($path)) {
151  $variables["%route%"]='@route("' . $path . '")';
152  }
153  $variables["%urlsFile%"]=URequest::post("urlsFile", "urls");
154  $variables["%sitemapTemplate%"]=URequest::post("sitemapTemplate", "Seo/sitemap.xml.html");
155 
156  $this->_createController($_POST["controllerName"], $variables, 'seoController.tpl');
157  }
158  $this->seo();
159  }
160 
161  public function _checkController() {
162  if (URequest::isPost()) {
163  $result=[ ];
164  $controllers=CacheManager::getControllers();
165  $ctrlNS=Startup::getNS();
166  header('Content-type: application/json');
167  $controller=$ctrlNS . $_POST["controllerName"];
168  $routes=CacheManager::getRoutes();
169  $result["result"]=(\array_search($controller, $controllers) === false);
170  echo json_encode($result);
171  }
172  }
173 
174  public function saveUrls() {
175  $result=[ ];
176  $selections=URequest::post("selection", [ ]);
177  $locations=URequest::post("location", [ ]);
178  $lastModified=URequest::post("lastModified", [ ]);
179  $changeFrequency=URequest::post("changeFrequency", [ ]);
180  $priority=URequest::post("priority", [ ]);
181  foreach ( $selections as $index ) {
182  $result[]=[ "location" => $locations[$index - 1],"lastModified" => \strtotime($lastModified[$index - 1]),"changeFrequency" => $changeFrequency[$index - 1],"priority" => $priority[$index - 1] ];
183  }
184  $seoController=USession::get("seo-sitemap");
185  if (isset($seoController) && $seoController instanceof SeoController) {
186  $seoController->_save($result);
187  $r=new \ReflectionClass($seoController);
188  $this->displaySiteMap($r->getNamespaceName(), $r->getShortName());
189  }
190  }
191 }
static isPost()
Returns true if the request is sent by the POST method.
Definition: URequest.php:91
_createController($controllerName, $variables=[], $ctrlTemplate='controller.tpl', $hasView=false)
loadView($viewName, $pData=NULL, $asString=false)
static post($key, $default=NULL)
Returns the value of the $key variable passed by the post method or $default if the $key variable doe...
Definition: URequest.php:128
static getNS($part="controllers")
Definition: Startup.php:43
showSimpleMessage($content, $type, $icon="info", $timeout=NULL, $staticName=null)
static set($key, $value)
Adds or sets a value to the Session at position $key.
Definition: USession.php:124
static get($key, $default=NULL)
Returns the value stored at the key position in session.
Definition: USession.php:114
static save($filename, $content, $flags=LOCK_EX)
Definition: UFileSystem.php:95