8768 sujets

Développement web côté serveur, CMS

Bonsoir,

Je galère comme un fou avec le fichier php qui génère mon sitemap (je suis sur prestashop 1.5.4.1).

En gros, j'ai résolu tous les bugs sauf 1, qui consiste à écrire quelque chose dans image:title et image:caption sur mon sitemap (http://kosmeopolis.com/sitemap.xml).

Les lignes qui permettent ceci sont :
$legend_image = preg_replace('/(&+)/i', '&', $product['product_image']);
$image->addChild('caption', $legend_image, 'http://www.google.com/schemas/sitemap-image/1.1');
$image->addChild('title', $legend_image, 'http://www.google.com/schemas/sitemap-image/1.1');


Je dois donc modifier "$legend_image" par "aller chercher le nom du produit" en php. Mais voilà, je n'y connais rien en php !

Pouvez-vous m'aider svp ?

Merci d'avance !!
Modifié par camping44 (25 Mar 2014 - 18:59)
Bonjour,

Le code semble correct à première vue, $product['product_image'] contient bien le nom du produit ? (Tu peux ajouter un echo $product['product_image']; dans le code afin de vérifier ce que cela contient)
Bonjour,

Merci pour votre aide, je commençais à désespérer !

Quand je dis que je suis vraiment nul en php, c'est que vraiment je suis ... nul !

Pour le echo, je modifie juste le fichier en ajoutant echo ou bien j'ajoute echo $product['product_image']; quelque part ?

Désolé, la question semble bête mais que j'ajoute echo devant, soit
$legend_image = preg_replace('/(&+)/i', '&', echo $product['product_image']);
j'obtiens :

"[PrestaShop] Fatal error in module gsitemap:
syntax error, unexpected 'echo' (T_ECHO)"
Re,

Il faut ajouter une nouvelle ligne :
echo $product['product_image'];
$legend_image = preg_replace('/(&+)/i', '&', $product['product_image']);
$image->addChild('caption', $legend_image, 'http://www.google.com/schemas/sitemap-image/1.1');
$image->addChild('title', $legend_image, 'http://www.google.com/schemas/sitemap-image/1.1');
Bonsoir,

J'ai rajouté echo, mais rien ne semble avoir bougé dans mon sitemap.

Si cela peut aider, la page est codée comme suit :

if (!defined('_PS_VERSION_'))
	exit;

class Gsitemap extends Module
{
	private $_html = '';
	private $_postErrors = array();

	public function __construct()
	{
		$this->name = 'gsitemap';
		$this->tab = 'seo';
		$this->version = '1.9';
		$this->author = 'PrestaShop';
		$this->need_instance = 0;

		parent::__construct();

		$this->displayName = $this->l('Google sitemap');
		$this->description = $this->l('Generate your Google sitemap file');

		if (!defined('GSITEMAP_FILE'))
			define('GSITEMAP_FILE', dirname(__FILE__).'/../../sitemap.xml');
	}

	public function uninstall()
	{
		file_put_contents(GSITEMAP_FILE, '');
		return parent::uninstall();
	}

	private function _postValidation()
	{
		file_put_contents(GSITEMAP_FILE, '');
		if (!($fp = fopen(GSITEMAP_FILE, 'w')))
			$this->_postErrors[] = $this->l('Cannot create').' '.realpath(dirname(__FILE__.'/../..')).'/'.$this->l('sitemap.xml file.');
		else
			fclose($fp);
	}

	private function getUrlWith($url, $key, $value)
	{
		if (empty($value))
			return $url;
		if (strpos($url, '?') !== false)
			return $url.'&'.$key.'='.$value;
		return $url.'?'.$key.'='.$value;
	}

	private function _postProcess()
	{
		Configuration::updateValue('GSITEMAP_ALL_CMS', (int)Tools::getValue('GSITEMAP_ALL_CMS'));
		Configuration::updateValue('GSITEMAP_ALL_PRODUCTS', (int)Tools::getValue('GSITEMAP_ALL_PRODUCTS'));
		$link = new Link();
		$langs = Language::getLanguages();

		$xmlString = <<<XML
<?xml version="1.0" encoding="UTF-8" ?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
</urlset>
XML;

		$xml = new SimpleXMLElement($xmlString);

		if (Configuration::get('PS_REWRITING_SETTINGS') && count($langs) > 1)
			foreach($langs as $lang)
				$this->_addSitemapNode($xml, Tools::getShopDomain(true, true).__PS_BASE_URI__.$lang['iso_code'].'/', '1.00', 'daily', date('Y-m-d'));
		else
			$this->_addSitemapNode($xml, Tools::getShopDomain(true, true).__PS_BASE_URI__, '1.00', 'daily', date('Y-m-d'));

		/* Product Generator */
		$sql = '
		SELECT p.id_product, pl.link_rewrite, DATE_FORMAT(IF(date_upd,date_upd,date_add), \'%Y-%m-%d\') date_upd, pl.id_lang, cl.`link_rewrite` category, ean13, i.id_image, il.legend legend_image, (
			SELECT MIN(level_depth)
			FROM '._DB_PREFIX_.'product p2
			LEFT JOIN '._DB_PREFIX_.'category_product cp2 ON p2.id_product = cp2.id_product
			LEFT JOIN '._DB_PREFIX_.'category c2 ON cp2.id_category = c2.id_category
			WHERE p2.id_product = p.id_product AND p2.`active` = 1 AND c2.`active` = 1) AS level_depth
		FROM '._DB_PREFIX_.'product p
		LEFT JOIN '._DB_PREFIX_.'product_lang pl ON (p.id_product = pl.id_product)
		LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (p.`id_category_default` = cl.`id_category` AND pl.`id_lang` = cl.`id_lang`)
		LEFT JOIN '._DB_PREFIX_.'image i ON p.id_product = i.id_product
		LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND pl.`id_lang` = il.`id_lang`)
		LEFT JOIN '._DB_PREFIX_.'lang l ON (pl.id_lang = l.id_lang)
		WHERE l.`active` = 1 AND p.`active` = 1
		'.(Configuration::get('GSITEMAP_ALL_PRODUCTS') ? '' : 'HAVING level_depth IS NOT NULL').'
		ORDER BY pl.id_product, pl.id_lang ASC';

		$resource = Db::getInstance()->ExecuteS($sql, false);

		// array used to know which product/image was already added (blacklist)
		$done = null;
		$sitemap = null;

		// iterates on the products, to gather the image ids
		while ($product = Db::getInstance()->nextRow($resource))
		{
			// if the product has not been added
			if (!isset($done[$product['id_product'].'_'.$product['id_lang']]['added']))
			{
				// priority
				if (($priority = 0.7 - ($product['level_depth'] / 10)) < 0.1)
					$priority = 0.1;

				// adds the product
				$tmpLink = $this->context->link->getProductLink($product, $product['link_rewrite'], $product['category'], $product['ean13'], (int)($product['id_lang']), $id_shop, 0, true);
				$sitemap = $this->_addSitemapNode($xml, $tmpLink, $priority, 'weekly', substr($product['date_upd'], 0, 10));

				// considers the product has added
				$done[$product['id_product'].'_'.$product['id_lang']]['added'] = true;
			}

			// if the image has not been added
			if (!isset($done[$product['id_product'].'_'.$product['id_lang']][$product['id_image']]) && (int)$product['id_image'])
			{
				// adds the image
				$this->_addSitemapNodeImage($sitemap, $product);

				// considers the image as added
				$done[$product['id_product'].'_'.$product['id_lang']][$product['id_image']] = true;
			}
		}

		/* Categories Generator */
		if (Configuration::get('PS_REWRITING_SETTINGS'))
			$categories = Db::getInstance()->ExecuteS('
			SELECT c.id_category, c.level_depth, link_rewrite, DATE_FORMAT(IF(date_upd,date_upd,date_add), \'%Y-%m-%d\') AS date_upd, cl.id_lang
			FROM '._DB_PREFIX_.'category c
			LEFT JOIN '._DB_PREFIX_.'category_lang cl ON c.id_category = cl.id_category
			LEFT JOIN '._DB_PREFIX_.'lang l ON cl.id_lang = l.id_lang
			WHERE l.`active` = 1 AND c.`active` = 1 AND c.id_category != 1
			ORDER BY cl.id_category, cl.id_lang ASC');
		else
			$categories = Db::getInstance()->ExecuteS(
			'SELECT c.id_category, c.level_depth, DATE_FORMAT(IF(date_upd,date_upd,date_add), \'%Y-%m-%d\') AS date_upd
			FROM '._DB_PREFIX_.'category c
			ORDER BY c.id_category ASC');

		foreach ($categories as $category)
		{
			if (($priority = 0.9 - ($category['level_depth'] / 10)) < 0.1)
				$priority = 0.1;

			$tmpLink = Configuration::get('PS_REWRITING_SETTINGS') ? $link->getCategoryLink((int)$category['id_category'], $category['link_rewrite'], (int)$category['id_lang']) : $link->getCategoryLink((int)$category['id_category']);
			$this->_addSitemapNode($xml, htmlspecialchars($tmpLink), $priority, 'weekly', substr($category['date_upd'], 0, 10));
		}

		/* CMS Generator */
		if (Configuration::get('GSITEMAP_ALL_CMS') || !Module::isInstalled('blockcms'))
			$sql_cms = '
			SELECT DISTINCT '.(Configuration::get('PS_REWRITING_SETTINGS') ? 'cl.id_cms, cl.link_rewrite, cl.id_lang' : 'cl.id_cms').
			' FROM '._DB_PREFIX_.'cms_lang cl
			LEFT JOIN '._DB_PREFIX_.'lang l ON (cl.id_lang = l.id_lang)
			WHERE l.`active` = 1
			ORDER BY cl.id_cms, cl.id_lang ASC';
		elseif (Module::isInstalled('blockcms'))
			$sql_cms = '
			SELECT DISTINCT '.(Configuration::get('PS_REWRITING_SETTINGS') ? 'cl.id_cms, cl.link_rewrite, cl.id_lang' : 'cl.id_cms').
			' FROM '._DB_PREFIX_.'cms_block_page b
			LEFT JOIN '._DB_PREFIX_.'cms_lang cl ON (b.id_cms = cl.id_cms)
			LEFT JOIN '._DB_PREFIX_.'lang l ON (cl.id_lang = l.id_lang)
			WHERE l.`active` = 1
			ORDER BY cl.id_cms, cl.id_lang ASC';

		foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql_cms) as $cms)
			$this->_addSitemapNode($xml, Configuration::get('PS_REWRITING_SETTINGS') ? $link->getCMSLink((int)$cms['id_cms'], $cms['link_rewrite'], false, (int)$cms['id_lang']) : $link->getCMSLink((int)$cms['id_cms']), '0.8', 'daily');

		/* Add classic pages (contact, best sales, new products...) */
		$pages = array('supplier' => false, 'manufacturer' => false, 'new-products' => false, 'prices-drop' => false, 'stores' => false, 'authentication' => true, 'best-sales' => false, 'contact-form' => true);

		// Don't show suppliers and manufacturers if they are disallowed
		if (!Module::getInstanceByName('blockmanufacturer')->id && !Configuration::get('PS_DISPLAY_SUPPLIERS'))
			unset($pages['manufacturer']);

		if (!Module::getInstanceByName('blocksupplier')->id && !Configuration::get('PS_DISPLAY_SUPPLIERS'))
			unset($pages['supplier']);

		// Generate nodes for pages
		if (Configuration::get('PS_REWRITING_SETTINGS'))
			foreach ($pages as $page => $ssl)
				foreach($langs as $lang)
				$this->_addSitemapNode($xml, $link->getPageLink($page.'.php', $ssl, (int)$lang['id_lang']), '0.5', 'monthly');
		else
			foreach($pages as $page => $ssl)
				$this->_addSitemapNode($xml, $link->getPageLink($page.'.php', $ssl), '0.5', 'monthly');

		$xmlString = $xml->asXML();

		$fp = fopen(GSITEMAP_FILE, 'w');
		fwrite($fp, $xmlString);
		fclose($fp);

		$res = file_exists(GSITEMAP_FILE);
		$this->_html .= '<h3 class="'. ($res ? 'conf confirm' : 'alert error') .'" style="margin-bottom: 20px">';
		$this->_html .= $res ? $this->l('Sitemap file generated') : $this->l('Error while creating sitemap file');
		$this->_html .= '</h3>';
	}

	private function _addSitemapNode($xml, $loc, $priority, $change_freq, $last_mod = NULL)
	{
		$sitemap = $xml->addChild('url');
		$sitemap->addChild('loc', $loc);
		$sitemap->addChild('priority', number_format($priority,1,'.',''));
		if ($last_mod)
			$sitemap->addChild('lastmod', $last_mod);
		$sitemap->addChild('changefreq', $change_freq);
		return $sitemap;
	}

	private function _addSitemapNodeImage($xml, $product)
	{
		$link = new Link();
		$image = $xml->addChild('image', null, 'http://www.google.com/schemas/sitemap-image/1.1');
		$image->addChild('loc', 'http://'.htmlspecialchars($link->getImageLink($product['link_rewrite'], (int)$product['id_product'].'-'.(int)$product['id_image'])), 'http://www.google.com/schemas/sitemap-image/1.1');

		echo $product['product_image'];
		$legend_image = preg_replace('/(&+)/i', '&amp;', $product['product_image']);
		$image->addChild('caption', $legend_image, 'http://www.google.com/schemas/sitemap-image/1.1');
		$image->addChild('title', $legend_image, 'http://www.google.com/schemas/sitemap-image/1.1');
	}

	private function _displaySitemap()
	{
		if (file_exists(GSITEMAP_FILE) && filesize(GSITEMAP_FILE))
		{
			$fp = fopen(GSITEMAP_FILE, 'r');
			$fstat = fstat($fp);
			fclose($fp);
			$xml = simplexml_load_file(GSITEMAP_FILE);

			$nbPages = count($xml->url);

			$this->_html .= '<p>'.$this->l('Your Google sitemap file is online at the following address:').'<br />
			<a href="'.Tools::getShopDomain(true, true).__PS_BASE_URI__.'sitemap.xml" target="_blank"><b>'.Tools::getShopDomain(true, true).__PS_BASE_URI__.'sitemap.xml</b></a></p><br />';

			$this->_html .= $this->l('Update:').' <b>'.utf8_encode(strftime('%A %d %B %Y %H:%M:%S', $fstat['mtime'])).'</b><br />';
			$this->_html .= $this->l('Filesize:').' <b>'.number_format(($fstat['size']*.000001), 3).'MB</b><br />';
			$this->_html .= $this->l('Indexed pages:').' <b>'.$nbPages.'</b><br /><br />';
		}
	}

	private function _displayForm()
	{
		$this->_html .=
		'<form action="'.Tools::htmlentitiesUTF8($_SERVER['REQUEST_URI']).'" method="post">
			<div style="margin:0 0 20px 0;">
				<input type="checkbox" name="GSITEMAP_ALL_PRODUCTS" id="GSITEMAP_ALL_PRODUCTS" style="vertical-align: middle;" value="1" '.(Configuration::get('GSITEMAP_ALL_PRODUCTS') ? 'checked="checked"' : '').' /> <label class="t" for="GSITEMAP_ALL_PRODUCTS">'.$this->l('Sitemap also includes products from inactive categories').'</label>
			</div>
			<div style="margin:0 0 20px 0;">
				<input type="checkbox" name="GSITEMAP_ALL_CMS" id="GSITEMAP_ALL_CMS" style="vertical-align: middle;" value="1" '.(Configuration::get('GSITEMAP_ALL_CMS') ? 'checked="checked"' : '').' /> <label class="t" for="GSITEMAP_ALL_CMS">'.$this->l('Sitemap also includes CMS pages which are not in a CMS block').'</label>
			</div>
			<input name="btnSubmit" class="button" type="submit"
			value="'.((!file_exists(GSITEMAP_FILE)) ? $this->l('Generate sitemap file') : $this->l('Update sitemap file')).'" />
		</form>';
	}

	public function getContent()
	{
		if (Tools::isSubmit('btnSubmit'))
		{
			$this->_postValidation();
			if (!count($this->_postErrors))
				$this->_postProcess();
			else
				foreach ($this->_postErrors as $err)
					$this->_html .= '<div class="alert error">'.$err.'</div>';
		}

		$this->_html .= '
			<fieldset>
				<legend>'.$this->l('Search Engine Optimization').'</legend>
				<br />
				'.$this->l('See').' <a href="http://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=156184&from=40318&rd=1" style="font-weight:bold;text-decoration:underline;" target="_blank">
				'.$this->l('this page').'</a> '.$this->l('for more information').'
				<br />';

		$this->_displaySitemap();
		$this->_displayForm();

		$this->_html .= '</fieldset>';
		return $this->_html;
	}
}