Marion Muszynski aec9fcfe34 sitemap
2015-10-14 14:39:48 +02:00

507 lines
18 KiB
PHP

<?php
if (!defined('_PS_VERSION_'))
exit;
//require _PS_MODULE_DIR_.'cmsps/cmsps.php';
class GsitemapOverride extends Gsitemap
{
/* @Override */
protected $metas_plus;
/* @Override */
public function __construct()
{
$this->name = 'gsitemap';
$this->tab = 'seo';
$this->version = '3.0.5';
$this->author = 'PrestaShop';
$this->need_instance = 0;
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Google sitemap');
$this->description = $this->l('Generate your Google sitemap file');
/* @Override */
$this->type_array = array('home', 'meta', 'product', 'category', 'manufacturer', 'supplier', 'cms', 'module');
$metas = Db::getInstance()->ExecuteS('SELECT * FROM `'._DB_PREFIX_.'meta` ORDER BY `id_meta` ASC');
$disabled_metas = explode(',', Configuration::get('GSITEMAP_DISABLE_LINKS'));
foreach ($metas as $meta)
if (in_array($meta['id_meta'], $disabled_metas))
if (($key = array_search($meta['page'], $this->type_array)) !== false)
unset($this->type_array[$key]);
/* @Override */
$this->metas_plus = array('cmspscategory', 'cmspspost', 'cmspsedito');
}
/* @Override */
public function getContent(){
/* Store the posted parameters and generate a new Google Sitemap files for the current Shop */
if (Tools::isSubmit('SubmitGsitemap'))
{
Configuration::updateValue('GSITEMAP_FREQUENCY', pSQL(Tools::getValue('gsitemap_frequency')));
Configuration::updateValue('GSITEMAP_INDEX_CHECK', '');
Configuration::updateValue('GSITEMAP_CHECK_IMAGE_FILE', pSQL(Tools::getValue('gsitemap_check_image_file')));
$meta = '';
if (Tools::getValue('gsitemap_meta'))
$meta .= implode(', ', Tools::getValue('gsitemap_meta'));
Configuration::updateValue('GSITEMAP_DISABLE_LINKS', $meta);
$this->emptySitemap();
$this->createSitemap();
}
elseif (Tools::isSubmit('SubmitBlogGsitemap'))
{
Configuration::updateValue('GSITEMAP_FREQUENCY', pSQL(Tools::getValue('gsitemap_frequency')));
$this->type_array = array('cmspscategory', 'cmspspost', 'cmspsedito');
$this->createSpecificSitemap(2);
}
elseif (Tools::isSubmit('SubmitImgGsitemap'))
{
Configuration::updateValue('GSITEMAP_FREQUENCY', pSQL(Tools::getValue('gsitemap_frequency')));
}
/* if no posted form and the variable [continue] is found in the HTTP request variable keep creating sitemap */
elseif (Tools::getValue('continue'))
$this->createSitemap();
/* Empty the Shop domain cache */
if (method_exists('ShopUrl', 'resetMainDomainCache'))
ShopUrl::resetMainDomainCache();
$this->context->smarty->assign(
array(
'gsitemap_form' => './index.php?tab=AdminModules&configure=gsitemap&token='.Tools::getAdminTokenLite('AdminModules').'&tab_module='.$this->tab.'&module_name=gsitemap',
'gsitemap_cron' => _PS_BASE_URL_._MODULE_DIR_.'gsitemap/gsitemap-cron.php?token='.substr(Tools::encrypt('gsitemap/cron'), 0, 10).'&id_shop='.$this->context->shop->id,
'gsitemap_feed_exists' => file_exists($this->normalizeDirectory(_PS_ROOT_DIR_).'index_sitemap.xml'),
'gsitemap_last_export' => Configuration::get('GSITEMAP_LAST_EXPORT'),
'gsitemap_frequency' => Configuration::get('GSITEMAP_FREQUENCY'),
'gsitemap_store_url' => 'http://'.Tools::getShopDomain(false, true).__PS_BASE_URI__,
'gsitemap_links' => Db::getInstance()->ExecuteS('SELECT * FROM `'._DB_PREFIX_.'gsitemap_sitemap` WHERE id_shop = '.(int)$this->context->shop->id),
'store_metas' => Meta::getMetasByIdLang((int)$this->context->cookie->id_lang),
'gsitemap_disable_metas' => explode(',', Configuration::get('GSITEMAP_DISABLE_LINKS')),
'gsitemap_disable_metas_plus' => explode(',', Configuration::get('GSITEMAP_DISABLE_LINKS_PLUS')),
'gsitemap_customer_limit' => array(
'max_exec_time' => (int)ini_get('max_execution_time'),
'memory_limit' => intval(ini_get('memory_limit'))
),
'prestashop_ssl' => Configuration::get('PS_SSL_ENABLED'),
'gsitemap_check_image_file' => Configuration::get('GSITEMAP_CHECK_IMAGE_FILE'),
'shop' => $this->context->shop
)
);
return $this->display(__FILE__, 'views/templates/admin/configuration.tpl');
}
public function createSpecificSitemap($index, $id_shop = 0)
{
if (@fopen($this->normalizeDirectory(_PS_ROOT_DIR_).'/test.txt', 'w') == false)
{
$this->context->smarty->assign('google_maps_error', $this->l('An error occured while trying to check your file permissions. Please adjust your permissions to allow PrestaShop to write a file in your root directory.'));
return false;
}
else
@unlink($this->normalizeDirectory(_PS_ROOT_DIR_).'test.txt');
if ($id_shop != 0)
$this->context->shop = new Shop((int)$id_shop);
$type = Tools::getValue('type') ? Tools::getValue('type') : '';
$languages = Language::getLanguages(true, $id_shop);
$lang_stop = Tools::getValue('lang') ? true : false;
$id_obj = Tools::getValue('id') ? (int)Tools::getValue('id') : 0;
foreach ($languages as $lang)
{
$i = 0;
// $index = (Tools::getValue('index') && Tools::getValue('lang') == $lang['iso_code']) ? (int)Tools::getValue('index') : 0;
if ($lang_stop && $lang['iso_code'] != Tools::getValue('lang'))
continue;
elseif ($lang_stop && $lang['iso_code'] == Tools::getValue('lang'))
$lang_stop = false;
$link_sitemap = array();
foreach ($this->metas_plus as $type_val)
{
if ($type == '' || $type == $type_val)
{
$function = '_get'.ucfirst($type_val).'Link';
if (!$this->$function($link_sitemap, $lang, $index, $i, $id_obj))
return false;
$type = '';
$id_obj = 0;
}
}
$this->_recursiveSitemapCreator($link_sitemap, $lang['iso_code'], $index);
$page = '';
$index = 0;
}
$this->_createIndexSitemap();
Configuration::updateValue('GSITEMAP_LAST_EXPORT', date('r'));
switch ($index) {
case 1:
Tools::file_get_contents('http://www.google.com/webmasters/sitemaps/ping?sitemap='.urlencode('http'.(Configuration::get('PS_SSL_ENABLED') ? 's' : '').'://'.Tools::getShopDomain(false, true).$this->context->shop->physical_uri.$this->context->shop->virtual_uri.$this->context->shop->id.'_blog_sitemap.xml'));
break;
case 2:
Tools::file_get_contents('http://www.google.com/webmasters/sitemaps/ping?sitemap='.urlencode('http'.(Configuration::get('PS_SSL_ENABLED') ? 's' : '').'://'.Tools::getShopDomain(false, true).$this->context->shop->physical_uri.$this->context->shop->virtual_uri.$this->context->shop->id.'_img_sitemap.xml'));
break;
default:
break;
}
/*if ($this->cron)
die();*/
if (!$this->cron){
header('location: ./index.php?tab=AdminModules&configure=gsitemap&token='.Tools::getAdminTokenLite('AdminModules').'&tab_module='.$this->tab.'&module_name=gsitemap&validation');
die();
}
}
/**
* @param array $link_sitemap contain all the links for the Google Sitemap file to be generated
* @param string $lang the language of link to add
* @param int $index the index of the current Google Sitemap file
*
* @return bool
*/
private function _recursiveSitemapCreator($link_sitemap, $lang, &$index)
{
if (!count($link_sitemap))
return false;
$sitemap_link = $this->context->shop->id.'_'.$lang.'_'.$index.'_sitemap.xml';
$write_fd = fopen($this->normalizeDirectory(_PS_ROOT_DIR_).$sitemap_link, 'w');
fwrite($write_fd, '<?xml version="1.0" encoding="UTF-8"?>'."\r\n".'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">'."\r\n");
foreach ($link_sitemap as $key => $file)
{
fwrite($write_fd, '<url>'."\r\n");
$lastmod = (isset($file['lastmod']) && !empty($file['lastmod'])) ? date('c', strtotime($file['lastmod'])) : null;
$this->_addSitemapNode($write_fd, htmlspecialchars(strip_tags($file['link'])), $this->_getPriorityPage($file['page']), Configuration::get('GSITEMAP_FREQUENCY'), $lastmod);
if ($file['image'])
{
$this->_addSitemapNodeImage(
$write_fd, htmlspecialchars(strip_tags($file['image']['link'])), isset($file['image']['title_img']) ? htmlspecialchars(
str_replace(
array(
"\r\n",
"\r",
"\n"
), '', strip_tags($file['image']['title_img'])
)
) : '', isset($file['image']['caption']) ? htmlspecialchars(
str_replace(
array(
"\r\n",
"\r",
"\n"
), '', strip_tags($file['image']['caption'])
)
) : ''
);
}
fwrite($write_fd, '</url>'."\r\n");
}
fwrite($write_fd, '</urlset>'."\r\n");
fclose($write_fd);
$this->_saveSitemapLink($sitemap_link);
$index++;
return true;
}
/**
* return the priority value set in the configuration parameters
*
* @param string $page
*
* @return float|string|bool
*/
private function _getPriorityPage($page)
{
return Configuration::get('GSITEMAP_PRIORITY_'.Tools::strtoupper($page)) ? Configuration::get('GSITEMAP_PRIORITY_'.Tools::strtoupper($page)) : 0.1;
}
/**
* Add a new line to the sitemap file
*
* @param resource $fd file system object resource
* @param string $loc string the URL of the object page
* @param string $priority
* @param string $change_freq
* @param int $last_mod the last modification date/time as a timestamp
*/
private function _addSitemapNode($fd, $loc, $priority, $change_freq, $last_mod = null)
{
fwrite($fd, '<loc>'.(Configuration::get('PS_REWRITING_SETTINGS') ? '<![CDATA['.$loc.']]>' : $loc).'</loc>'."\r\n".'<priority>'.number_format($priority, 1, '.', '').'</priority>'."\r\n".($last_mod ? '<lastmod>'.date('c', strtotime($last_mod)).'</lastmod>' : '')."\r\n".'<changefreq>'.$change_freq.'</changefreq>'."\r\n");
}
private function _addSitemapNodeImage($fd, $link, $title, $caption)
{
fwrite($fd, '<image:image>'."\r\n".'<image:loc>'.(Configuration::get('PS_REWRITING_SETTINGS') ? '<![CDATA['.$link.']]>' : $link).'</image:loc>'."\r\n".'<image:caption><![CDATA['.$caption.']]></image:caption>'."\r\n".'<image:title><![CDATA['.$title.']]></image:title>'."\r\n".'</image:image>'."\r\n");
}
/**
* Create the index file for all generated sitemaps
* @return boolean
*/
private function _createIndexSitemap()
{
$sitemaps = Db::getInstance()->ExecuteS('SELECT `link` FROM `'._DB_PREFIX_.'gsitemap_sitemap` WHERE id_shop = '.$this->context->shop->id);
if (!$sitemaps)
return false;
$xml = '<?xml version="1.0" encoding="UTF-8"?><sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></sitemapindex>';
$xml_feed = new SimpleXMLElement($xml);
foreach ($sitemaps as $link)
{
$sitemap = $xml_feed->addChild('sitemap');
$sitemap->addChild('loc', 'http'.(Configuration::get('PS_SSL_ENABLED') && Configuration::get('PS_SSL_ENABLED_EVERYWHERE') ? 's' : '').'://'.Tools::getShopDomain(false, true).__PS_BASE_URI__.$link['link']);
$sitemap->addChild('lastmod', date('c'));
}
file_put_contents($this->normalizeDirectory(_PS_ROOT_DIR_).$this->context->shop->id.'_index_sitemap.xml', $xml_feed->asXML());
return true;
}
private function tableColumnExists($table_name, $column = null)
{
if (array_key_exists($table_name, $this->sql_checks))
if (!empty($column) && array_key_exists($column, $this->sql_checks[$table_name]))
return $this->sql_checks[$table_name][$column];
else
return $this->sql_checks[$table_name];
$table = Db::getInstance()->ExecuteS('SHOW TABLES LIKE \''.$table_name.'\'');
if (empty($column))
if (count($table) < 1)
return $this->sql_checks[$table_name] = false;
else
$this->sql_checks[$table_name] = true;
else
{
$table = Db::getInstance()->ExecuteS('SELECT * FROM `'.$table_name.'` LIMIT 1');
return $this->sql_checks[$table_name][$column] = array_key_exists($column, current($table));
}
return true;
}
/**
* Store the generated Sitemap file to the database
*
* @param string $sitemap the name of the generated Google Sitemap file
*
* @return bool
*/
private function _saveSitemapLink($sitemap)
{
if ($sitemap)
return Db::getInstance()->Execute('INSERT INTO `'._DB_PREFIX_.'gsitemap_sitemap` (`link`, id_shop) VALUES (\''.pSQL($sitemap).'\', '.(int)$this->context->shop->id.')');
return false;
}
/**
* Hydrate $link_sitemap with cmspscategories link
*
* @param array $link_sitemap contain all the links for the Google Sitemap file to be generated
* @param string $lang language of link to add
* @param int $index index of the current Google Sitemap file
* @param int $i count of elements added to sitemap main array
* @param int $id_category cmspscategories object identifier
*
* @return bool
*/
protected function _getCmspscategoryLink(&$link_sitemap, $lang, &$index, &$i, $id_category = 0)
{
if(!class_exists('CmsPS')) {
require _PS_MODULE_DIR_.'cmsps/cmsps.php';
}
$link = new Link();
if (method_exists('ShopUrl', 'resetMainDomainCache'))
ShopUrl::resetMainDomainCache();
$categories_id = Db::getInstance()->ExecuteS(
'SELECT c.`id_category`
FROM `'._DB_PREFIX_.'cmsps_categories` c
LEFT JOIN `'._DB_PREFIX_.'cmsps_categories_shop` ls ON c.`id_category` = ls.`id_category`
WHERE c.`id_category`>'.(int)$id_category.'
AND ls.`id_shop` = '.(int)$this->context->shop->id.'
ORDER BY c.`id_category` ASC'
);
foreach ($categories_id as $category_id)
{
$category = new CmsPsCategory((int)$category_id['id_category'], (int)$lang['id_lang']);
$url = $link->getCategoryCmsLink((int)$category->id);
if(file_exists(_CMS_CAT_IMG_DIR_.(int)$category->id.'.jpg')) {
$image = _CMS_CAT_IMG_DIR_.(int)$category->id.'.jpg';
$image_url = ImageManager::thumbnail($image, 'cmsps_categories_'.(int)(int)$category->id.'.jpg', 350, 'jpg', true, true);
}
$file_headers = (Configuration::get('GSITEMAP_CHECK_IMAGE_FILE')) ? @get_headers($image_url) : true;
$image_category = array();
if (isset($image_url) && ($file_headers[0] != 'HTTP/1.1 404 Not Found' || $file_headers === true))
$image_category = array(
'title_img' => htmlspecialchars(strip_tags($category->title)),
'link' => $image_url
);
if (!$this->_addLinkToSitemap(
$link_sitemap, array(
'type' => 'cmspscategory',
'page' => 'categorycms',
'lastmod' => $category->date_upd,
'link' => $url,
'image' => $image_category
), $lang['iso_code'], $index, $i, (int)$category->id
))
return false;
unset($image_url);
}
return true;
}
/**
* Hydrate $link_sitemap with cmspsposts link
*
* @param array $link_sitemap contain all the links for the Google Sitemap file to be generated
* @param string $lang language of link to add
* @param int $index index of the current Google Sitemap file
* @param int $i count of elements added to sitemap main array
* @param int $id_post cmspsposts object identifier
*
* @return bool
*/
protected function _getCmspspostLink(&$link_sitemap, $lang, &$index, &$i, $id_post = 0)
{
if(!class_exists('CmsPS')) {
require _PS_MODULE_DIR_.'cmsps/cmsps.php';
}
$link = new Link();
if (method_exists('ShopUrl', 'resetMainDomainCache'))
ShopUrl::resetMainDomainCache();
$posts_id = Db::getInstance()->ExecuteS(
'SELECT p.`id_post`
FROM `'._DB_PREFIX_.'cmsps_posts` p
LEFT JOIN `'._DB_PREFIX_.'cmsps_posts_shop` ps ON p.`id_post` = ps.`id_post`
WHERE p.`id_post`>'.(int)$id_post.'
AND ps.`id_shop` = '.(int)$this->context->shop->id.'
ORDER BY p.`id_post` ASC'
);
foreach ($posts_id as $post_id)
{
$post = new CmsPsPost((int)$post_id['id_post'], (int)$lang['id_lang']);
$url = $link->getPostCmsLink((int)$post->id, (int)$lang['id_lang']);
if(file_exists(_CMS_CAT_IMG_DIR_.(int)$post->id.'.jpg')) {
$image = _CMS_CAT_IMG_DIR_.(int)$post->id.'.jpg';
$image_url = ImageManager::thumbnail($image, 'cmsps_posts_'.(int)(int)$post->id.'.jpg', 350, 'jpg', true, true);
}
$file_headers = (Configuration::get('GSITEMAP_CHECK_IMAGE_FILE')) ? @get_headers($image_url) : true;
$image_post = array();
if (isset($image_url) && ($file_headers[0] != 'HTTP/1.1 404 Not Found' || $file_headers === true))
$image_post = array(
'title_img' => htmlspecialchars(strip_tags($post->title)),
'link' => $image_url
);
if (!$this->_addLinkToSitemap(
$link_sitemap, array(
'type' => 'cmspspost',
'page' => 'postcms',
'lastmod' => $post->date_upd,
'link' => $url,
'image' => $image_post
), $lang['iso_code'], $index, $i, (int)$post->id
))
return false;
unset($image_url);
}
return true;
}
/**
* Hydrate $link_sitemap with cmspseditos link
*
* @param array $link_sitemap contain all the links for the Google Sitemap file to be generated
* @param string $lang language of link to add
* @param int $index index of the current Google Sitemap file
* @param int $i count of elements added to sitemap main array
* @param int $id_edito cmspseditos object identifier
*
* @return bool
*/
protected function _getCmspseditoLink(&$link_sitemap, $lang, &$index, &$i, $id_edito = 0)
{
if(!class_exists('CmsPS')) {
require _PS_MODULE_DIR_.'cmsps/cmsps.php';
}
$link = new Link();
if (method_exists('ShopUrl', 'resetMainDomainCache'))
ShopUrl::resetMainDomainCache();
$editos_id = Db::getInstance()->ExecuteS(
'SELECT e.`id_edito`
FROM `'._DB_PREFIX_.'cmsps_editos` e
LEFT JOIN `'._DB_PREFIX_.'cmsps_editos_shop` es ON e.`id_edito` = es.`id_edito`
WHERE e.`id_edito`>'.(int)$id_edito.'
AND es.`id_shop` = '.(int)$this->context->shop->id.'
ORDER BY e.`id_edito` ASC'
);
foreach ($editos_id as $edito_id)
{
$edito = new CmsPsEdito((int)$edito_id['id_edito'], (int)$lang['id_lang']);
$url = $link->getPostEditoLink((int)$edito->id);
if(file_exists(_CMS_CAT_IMG_DIR_.(int)$edito->id.'.jpg')) {
$image = _CMS_CAT_IMG_DIR_.(int)$edito->id.'.jpg';
$image_url = ImageManager::thumbnail($image, 'cmsps_editos_'.(int)(int)$edito->id.'.jpg', 350, 'jpg', true, true);
}
$file_headers = (Configuration::get('GSITEMAP_CHECK_IMAGE_FILE')) ? @get_headers($image_url) : true;
$image_edito = array();
if (isset($image_url) && ($file_headers[0] != 'HTTP/1.1 404 Not Found' || $file_headers === true))
$image_edito = array(
'title_img' => htmlspecialchars(strip_tags($edito->title)),
'link' => $image_url
);
if (!$this->_addLinkToSitemap(
$link_sitemap, array(
'type' => 'cmspsedito',
'page' => 'editocms',
'lastmod' => $edito->date_upd,
'link' => $url,
'image' => $image_edito
), $lang['iso_code'], $index, $i, (int)$edito->id
))
return false;
unset($image_url);
}
return true;
}
}