Last active
January 7, 2023 16:42
-
-
Save joelmiguelvalente/b2b0440410cb8a5b1798d696ebe2078a to your computer and use it in GitHub Desktop.
Algunos cambios realizado para la "mejora" del sitemap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if (!defined('TS_HEADER')) | |
exit('No se permite el acceso directo al script'); | |
/** | |
* Modelo para el control del registro de usuarios | |
* | |
* @name c.sitemap.php | |
* @author aperpen | |
* @upgrade Miguel92 | |
*/ | |
define("ROOTAPP", realpath(dirname(dirname(__DIR__))) . DIRECTORY_SEPARATOR); | |
class tsSiteMap { | |
private $admin; | |
private $frecs = ['never', 'always', 'daily', 'hourly', 'weekly', 'monthly', 'yearly']; | |
private $prioridades = ['1', '0.9', '0.8', '0.7', '0.6', '0.5', '0.4', '0.3', '0.2', '0.1', '0']; | |
public function __construct() { | |
$this->admin["inst"] = self::getInst(); | |
$this->admin["sitemap"] = ROOTAPP . "sitemap.xml"; | |
$this->admin["robots"] = ROOTAPP . "robots.txt"; | |
} | |
/** | |
* @name getInst - Obtener las fechas de instalación y fundado | |
* @access public | |
* @params none | |
* @return array asociativo | |
*/ | |
public function getInst() { | |
return db_exec('fetch_assoc', db_exec([__FILE__, __LINE__], 'query', 'SELECT stats_time_foundation FROM w_stats WHERE stats_no = 1'))['stats_time_foundation']; | |
} | |
private function getUrlBasic() { | |
return [ | |
"/" => ["never", 1], | |
"/posts/" => ["hourly", 0.9], | |
"/fotos/" => ["daily", 0.9], | |
"/tops/" => ["never", 0.9], | |
"/tops/posts" => ["daily", 0.6], | |
"/tops/usuarios" => ["daily", 0.6], | |
"/buscador/" => ["never", 0.8], | |
"/usuarios/" => ["daily", 0.8], | |
"pages/" => [ | |
"ayuda/" => ["never", 0.5], | |
"chat/" => ["never", 0.5], | |
"dmca/" => ["never", 0.5], | |
"privacidad/" => ["never", 0.5], | |
"protocolo/posts" => ["never", 0.5], | |
"terminos-y-condiciones/" => ["never", 0.5] | |
] | |
]; | |
} | |
private function createFileXML() { | |
if(!file_exists( $this->admin["sitemap"] )) fopen($this->admin["sitemap"], 'w'); | |
} | |
private function getURL_tag($url, $date, $change, $priority, $exist = false) { | |
global $tsCore; | |
$url = $exist ? $url : $tsCore->settings['url'] . $url; | |
$priority = ($priority === '1.0') ? 1 : $priority; | |
return "\t<url>\n\t\t<loc>{$url}</loc>\n\t\t<lastmod>{$date}</lastmod>\n\t\t<changefreq>{$change}</changefreq>\n\t\t<priority>{$priority}</priority>\n\t</url>" . PHP_EOL; | |
} | |
private function createSitemapXML() { | |
$other = func_get_args()[0]; | |
// Solo si existe un segundo parametro | |
if(isset(func_get_args()[1])) $date_page = func_get_args()[1]; | |
$diames = date('dm'); | |
$sitemap = <<<SITEMAP_TOP | |
<!-- | |
* Sistema mejorado por Miguel92 | |
* Para los scripts: | |
* Cerberus 3.0.{$diames} | |
* PHPost <nueva generación> [proximamente] | |
--> | |
<?xml version="1.0" encoding="UTF-8"?> | |
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n | |
SITEMAP_TOP; | |
if(is_array($other)) { | |
foreach($other as $l) { | |
//getURL_tag(url, fecha, frecuencia, prioridad, ruta completa/parcial) | |
$sitemap .= self::getURL_tag($l['url'], date('Y-m-d', $l['fecha']), $l['frecuencia'], $l['prioridad'], true); | |
} | |
} else { | |
foreach (self::getUrlBasic() as $key => $url) { | |
if(count($url) <= 2) { | |
//getURL_tag(url, fecha, frecuencia, prioridad) | |
$sitemap .= self::getURL_tag($key, $other, $url[0], $url[1]); | |
} elseif(count($url) > 2) { | |
foreach($url as $subkey => $page) { | |
//getURL_tag(url, fecha, frecuencia, prioridad) | |
$sitemap .= self::getURL_tag($key.$subkey, $date_page, $page[0], $page[1]); | |
} | |
} | |
} | |
} | |
$sitemap .= <<<SITEMAP_BOTTOM | |
</urlset> | |
SITEMAP_BOTTOM; | |
$new_file_sitemap = fopen($this->admin["sitemap"], 'w'); | |
fwrite($new_file_sitemap, $sitemap); | |
fclose($new_file_sitemap); | |
} | |
private function setData(string $url = '', string $frecuencia = '', string $prioridad = '') { | |
global $tsCore; | |
$url = filter_var($tsCore->setSecure($url), FILTER_VALIDATE_URL) or die('URL Inválida'); | |
if(!in_array($tsCore->setSecure($frecuencia), $this->frecs)) die('Frecuencia inválida.'); | |
if(!in_array($tsCore->setSecure($prioridad), $this->prioridades)) die('Prioridad inválida.'); | |
return $url; | |
} | |
private function createRobots() { | |
global $tsCore; | |
// Añadimos el User-agent | |
$robots[] = "User-agent: *\n"; | |
// Añadimos los Disallows | |
$extensions = ['*.php', '*.txt']; | |
$disallow = ['admin', 'agregar', 'ajax_files', 'cache', 'cuenta', 'files/uploads', 'fotos/agregar', 'fotos/editar', 'inc', 'mensajes', 'moderacion', 'monitor', 'password', 'themes', 'upgrade', 'validar']; | |
foreach([...$extensions, ...$disallow] as $dw => $d): | |
$robots[] = "disallow: " . (in_array($d, $extensions) ? $d : "/{$d}/"); | |
endforeach; | |
// Añadimos el sitemap | |
$robots[] = "\nSitemap: {$tsCore->settings['url']}/sitemap.xml"; | |
// Automatizado | |
$robotsTXT = fopen($this->admin["robots"], 'w'); | |
fwrite($robotsTXT, join("\n", $robots)); | |
fclose($robotsTXT); | |
var_dump(file_exists($this->admin["robots"])); | |
return file_exists($this->admin["robots"]); | |
} | |
public function CreateSiteMap() { | |
global $tsCore; | |
// Creamos el archivo "sitemap.xml" | |
self::createFileXML(); | |
$date = date('Y-m-d', time()); | |
$date_page = date('Y-m-d', $this->admin["inst"]); | |
// Creamos el archivo sitemap.xml | |
self::createSitemapXML($date, $date_page); | |
$u = []; | |
foreach (self::getUrlBasic() as $uu => $url) { | |
if(count($url) <= 2) { | |
$u[] = "('{$tsCore->settings['url']}{$uu}', '{$url[0]}', ".time().", '{$url[1]}')"; | |
} elseif(count($url) > 2) { | |
foreach($url as $pu => $page) { | |
$u[] = "('{$tsCore->settings['url']}/{$uu}{$pu}', '{$page[0]}', '{$this->admin["inst"]}', '{$page[1]}')"; | |
} | |
} | |
} | |
if(db_exec([__FILE__, __LINE__], 'query', 'TRUNCATE TABLE w_sitemap')) { | |
$ins = "INSERT INTO w_sitemap (url, frecuencia, fecha, prioridad) VALUES " . join(',', $u); | |
db_exec([__FILE__, __LINE__], 'query', $ins) or die(show_error('Error al ejecutar la consulta de la línea '.__LINE__.' de '.__FILE__.'.', 'db')); | |
} | |
return true; | |
} | |
/** | |
* @name getSiteMap() | |
* @access public | |
* @return array-urls | |
*/ | |
public function getSitemap(){ | |
$xml = simplexml_load_file($this->admin["sitemap"]); | |
$total = 0; | |
// Recorrer cada elemento <url> del objeto | |
foreach ($xml->url as $url) { | |
// Obtener el valor del atributo 'loc' | |
$valores[$total] = ['url' => $url->loc]; | |
$total++; | |
} | |
return $valores; | |
} | |
public function removeUrlBD(int $id = 0){ | |
if( | |
db_exec([__FILE__, __LINE__], 'query', "DELETE FROM w_sitemap WHERE id = $id") or | |
die(show_error('Error al ejecutar la consulta de la línea '.__LINE__.' de '.__FILE__.'.', 'db')) | |
) return true; | |
} | |
public function getURLsBD() { | |
return result_array(db_exec([__FILE__, __LINE__], 'query', 'SELECT id, url, frecuencia, fecha, prioridad FROM w_sitemap')); | |
} | |
public function generateSiteMap(){ | |
self::createSitemapXML(self::getURLsBD()); | |
return true; | |
} | |
public function addURL(string $url = '', string $frecuencia = '', string $prioridad = ''){ | |
global $tsCore; | |
$time = time(); | |
self::setData($url, $frecuencia, $prioridad); | |
// Comprobar si ya existe | |
$select = db_exec('fetch_assoc', db_exec([__FILE__, __LINE__], 'query', "SELECT url FROM w_sitemap WHERE url LIKE '%$url%'"))["url"]; | |
// Evitamos que lo añada otra vez | |
if($select !== $url) { | |
db_exec([__FILE__, __LINE__], 'query', "INSERT INTO w_sitemap (url, frecuencia, fecha, prioridad) VALUES ('{$url}', '{$frecuencia}', {$time}, '{$prioridad}')") or die(show_error('Error al ejecutar la consulta de la línea '.__LINE__.' de '.__FILE__.'.', 'db')); | |
return true; | |
} else return false; | |
} | |
public function getUrl(int $id = 0){ | |
return db_exec('fetch_assoc', db_exec([__FILE__, __LINE__], 'query', "SELECT url, frecuencia, fecha, prioridad FROM w_sitemap WHERE id = {$id} LIMIT 1")); | |
} | |
public function editUrl(int $id = 0, string $url = '', string $frecuencia = '', string $prioridad = '') { | |
global $tsCore; | |
//FILTRAMOS DATOS | |
self::setData($url, $frecuencia, $prioridad); | |
$datas = [ | |
"url" => $url, | |
"frecuencia" => $tsCore->setSecure($frecuencia), | |
"fecha" => time(), | |
"prioridad" => $tsCore->setSecure($prioridad) | |
]; | |
$columns = $tsCore->setUpdate($datas); | |
db_exec([__FILE__, __LINE__], 'query', "UPDATE w_sitemap SET $columns WHERE id = $id") or | |
die(show_error('Error al ejecutar la consulta de la línea '.__LINE__.' de '.__FILE__.'.', 'db')); | |
return true; | |
} | |
public function addUrlsm(string $url = '', int $priority = 1) { | |
$sm = fopen($this->admin["sitemap"], 'r'); | |
$content = fread($sm, filesize($this->admin["sitemap"])); | |
fclose($sm); | |
// Tipo de prioridad | |
$priority = $priority ? 0.6 : 0.4; | |
// Verificamos si existe, en caso que exista ya no se agregará | |
if(self::addURL($url, 'monthly', $priority)) { | |
$url = self::getURL_tag($url, date('Y-m-d', time()), 'monthly', $priority, true); | |
$url .= '</urlset>'; | |
$sitemap = fopen($this->admin["sitemap"], 'w'); | |
fwrite($sitemap, str_replace('</urlset>', $url, $content)); | |
fclose($sitemap); | |
return true; | |
} else return false; | |
} | |
public function updateLM($url){ | |
global $tsCore; | |
$url = $tsCore->setSecure(filter_var($url, FILTER_VALIDATE_URL)); | |
$time = time(); | |
db_exec([__FILE__, __LINE__], 'query', "UPDATE w_sitemap SET fecha = $time WHERE url = '{$url}'") or | |
die(show_error('Error al ejecutar la consulta de la línea '.__LINE__.' de '.__FILE__.'.', 'db')); | |
$this->generateSiteMap(); | |
return true; | |
} | |
public function setAuto() { | |
global $tsUser; | |
if(isset($_GET["sitemap"]) OR isset($_GET["robots"]) AND isset($_GET["uid"])) { | |
if(((int)$tsUser->uid === (int)$_GET["uid"]) AND (int)$tsUser->is_admod === 1) { | |
if(!(bool)$_GET["sitemap"] AND !(bool)$_GET["robots"] AND !(int)$_GET["uid"]) return; | |
// Solo sitemap | |
if((bool)$_GET["sitemap"]) { | |
if(self::CreateSiteMap()) $msg = "Sitemap.xml instalado correctamente!"; | |
} | |
// Solo robots | |
if((bool)$_GET["robots"]) { | |
if(self::createRobots()) $msg = "Robots.txt instalado correctamente!"; | |
} | |
// Ambos | |
if((bool)$_GET["sitemap"] AND (bool)$_GET["robots"]) { | |
if(self::CreateSiteMap()) $msg = "Sitemap.xml y Robots.txt instalados correctamente!"; | |
} | |
} else $msg = "Tú no puedes utilizar estos parámetros!"; | |
echo "<div id=\"stickymsg\">{$msg}</div>"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment