Разделы

  
 

SBShop 0.1a - альфа-версия электронного магазина для MODx

Спешу поделиться с вами очень радостной новостью. Наконец-то разработка электронного магазина для MODx под кодовым названием SBShop приобрела некий ощутимый и рабочий вид. Первая альфа!

Информации очень много, поэтому не буду вдаваться в лирику и перейду к делу. Описывать буду как все устроено, а не «как сделать магазин».

( Читать дальше )
  • +9
  • 20 июня 2010, 00:57
  • Carw
  • 83

Делаем xml-карту сайта для Google и Яндекса на Evo

Недавно после создания сайта озаботился проблемой xml карты для Гугла и Яндекса. Решение нашел, правда доя старой версии МОДх, порывшись на англо-форумах нашел решение на базе старых разработок:

Создаем сниппет Sitemap и вставляем в него код:

<?php
/*
==================================================
	sitemap
==================================================

Outputs a machine readable site map for search
engines and robots. Supports the following
formats:

- Sitemap Protocol used by Google Sitemaps
  (http://www.google.com/webmasters/sitemaps/)

- URL list in text format
  (e.g. Yahoo! submission)

Author: Grzegorz Adamiak [grad]
Version: 1.0.8 @ 22-AUG-2008
License: LGPL
MODx: 0.9.2.1, 0.9.6.1

History:
# 1.0.8
- excludeTemplates can now also be specified as a template ID instead of template name. 
  Useful if you change the names of your templates frequently. (ncrossland)
  e.g. &excludeTemplates=`myTemplateName,3,4`
# 1.0.7
- Unpublished and deleted documents were showing up in the sitemap. Even though they could not be viewed, 
  they were showing up as broken links to search engines. (ncrossland)
# 1.0.6
- Add optional parameter (excludeWeblinks) to exclude weblinks from the sitemap, since they often point to external
  sites (which don't belong on your sitemap), or redirecting to other internal pages (which are already
  in the sitemap). Google Webmaster Tools generates warnings for excessive redirects.	
  Default is false - e.g. default behaviour remains unchanged. (ncrossland)
# 1.0.5
- Modification about non searchable documents, as suggested by forum user JayBee
  (http://modxcms.com/forums/index.php/topic,5754.msg99895.html#msg99895)
# 1.0.4 (By Bert Catsburg, bert@catsburg.com)
- Added display option 'ulli'. 
  An <ul><li> list of all published documents.
# 1.0.3
- Added ability to specify the XSL URL - you don't always need one and it 
  seems to create a lot of support confusion!
  It is now a parameter (&xsl=``) which can take either an alias or a doc ID (ncrossland)
- Modifications suggested by forum users Grad and Picachu incorporated
  (http://modxcms.com/forums/index.php/topic,5754.60.html)
# 1.0.2
- Reworked fetching of template variable value to
  get INHERITED value.
# 1.0.1
- Reworked fetching of template variable value,
  now it gets computed value instead of nominal;
  however, still not the inherited value.
# 1.0
- First public release.

TODO:
- provide output for ROR
--------------------------------------------------
*/

/* Parameters
----------------------------------------------- */

# $startid [ int ]
# Id of the 'root' document from which the sitemap
# starts.
# Default: 0

$startid = (isset($startid)) ? $startid : 0;

# $format [ sp | txt | ror ]
# Which format of sitemap to use:
# - sp <- Sitemap Protocol used by Google
# - txt <- text file with list of URLs
# TODO - ror <- Resource Of Resources
# Default: sp

$format = (isset($format) && ($format != 'ror')) ? $format : 'sp';

# $priority [ str ]
# Name of TV which sets the relative priority of
# the document. If there is no such TV, this
# parameter will not be used.
# Default: sitemap_priority

$priority = (isset($priority)) ? $priority : 'sitemap_priority';

# $changefreq [ str ]
# Name of TV which sets the change frequency. If
# there is no such TV this parameter will not be
# used.
# Default: sitemap_changefreq

$changefreq = (isset($changefreq)) ? $changefreq : 'sitemap_changefreq';

# $excludeTemplates [ str ]
# Documents based on which templates should not be
# included in the sitemap. Comma separated list
# with names of templates.
# Default: empty

$excludeTemplates = (isset($excludeTemplates)) ? $excludeTemplates : array();

# $excludeTV [ str ]
# Name of TV (boolean type) which sets document
# exclusion form sitemap. If there is no such TV
# this parameter will not be used.
# Default: 'sitemap_exclude'

$excludeTV = (isset($excludeTV)) ? $excludeTV : 'sitemap_exclude';

# $xsl [ str ] 
# URL to the XSL style sheet
# or
# $xsl [ int ]
# doc ID of the XSL style sheet

$xsl = (isset($xsl)) ? $xsl : '';
if (is_numeric($xsl)) { $xsl = $modx->makeUrl($xsl); }


# $excludeWeblinks [ bool ]
# Should weblinks be excluded?
# You may not want to include links to external sites in your sitemap,
# and Google gives warnings about multiple redirects to pages 
# within your site.
# Default: false
$excludeWeblinks = (isset($excludeWeblinks)) ? $excludeWeblinks : false;


/* End parameters
----------------------------------------------- */

# get list of documents
# ---------------------------------------------
$docs = getDocs($modx,$startid,$priority,$changefreq,$excludeTV);


# filter out documents by template or TV
# ---------------------------------------------
// get all templates
$select = $modx->db->select("id, templatename", $modx->getFullTableName('site_templates'));
while ($query = $modx->db->getRow($select)) {
	$allTemplates[$query['id']] = $query['templatename'];
}

$remainingTemplates = $allTemplates;

// get templates to exclude, and remove them from the all templates list
if (!empty ($excludeTemplates)) {
	
	$excludeTemplates = explode(",", $excludeTemplates);	
	
	// Loop through each template we want to exclude
	foreach ($excludeTemplates as $template) {
		$template = trim($template);
		
		// If it's numeric, assume it's an ID, and remove directly from the $allTemplates array
		if (is_numeric($template) && isset($remainingTemplates[$template])) {
			unset($remainingTemplates[$template]);
		} else if (trim($template) && in_array($template, $remainingTemplates)) { // If it's text, and not empty, assume it's a template name
			unset($remainingTemplates[array_search($template, $remainingTemplates)]);			
		}
	} // end foreach
}

$output= array();
// filter out documents which shouldn't be included
foreach ($docs as $doc)
{
	if (isset($remainingTemplates[$doc['template']]) && !$doc[$excludeTV] && $doc['published'] && $doc['template']!=0 && $doc['searchable']) {
		if (!$excludeWeblinks || ($excludeWeblinks && $doc['type'] != 'reference')) {
			$output[] = $doc;		
		}
	}
}
$docs = $output;
unset ($output, $allTemplates, $excludeTemplates);


# build sitemap in specified format
# ---------------------------------------------

switch ($format)
{
	// Next case added in version 1.0.4
	case 'ulli': // UL List
		$output .= "<ul class=\"sitemap\">\n";
		// TODO: Sort the array on Menu Index
		// TODO: Make a nested ul-li based on the levels in the document tree.
		foreach ($docs as $doc)
		{
			$s  = "  <li class=\"sitemap\">";
			$s .= "<a href=\"[(site_url)][~" . $doc['id'] . "~]\" class=\"sitemap\">" . $doc['pagetitle'] . "</a>";
			$s .= "</li>\n";
			$output .= $s;
		} // end foreach
		$output .= "</ul>\n";
		break;
		
	case 'txt': // plain text list of URLs

		foreach ($docs as $doc)
		{
			$url = '[(site_url)][~'.$doc['id'].'~]';

			$output .= $url."\n";
		} // end foreach
		break;

	case 'ror': // TODO
	default: // Sitemap Protocol

	
	$output = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
	if ($xsl != '') {
		$output .='<?xml-stylesheet type="text/xsl" href="'.$xsl.'"?>'."\n";
	}
	$output .='<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'."\n";
	
	
	foreach ($docs as $doc)	{
		$url = '[(site_url)][~'.$doc['id'].'~]';
		$date = $doc['editedon'];
		$date = date("Y-m-d", $date);
		$docPriority = ($doc[$priority]) ? $doc[$priority] : 0; // false if TV doesn't exist
		$docChangefreq = ($doc[$changefreq]) ? $doc[$changefreq] : 0; // false if TV doesn't exist

		$output .= "\t".'<url>'."\n";
		$output .= "\t\t".'<loc>'.$url.'</loc>'."\n";
		$output .= "\t\t".'<lastmod>'.$date.'</lastmod>'."\n";
		$output .= ($docPriority) ? ("\t\t".'<priority>'.$docPriority.'</priority>'."\n") : ''; // don't output anything if TV doesn't exist
		$output .= ($docChangefreq) ? ("\t\t".'<changefreq>'.$docChangefreq.'</changefreq>'."\n") : ''; // don't output anything if TV doesn't exist
		$output .= "\t".'</url>'."\n";
	} // end foreach
	$output .= '</urlset>';

} // end switch

return $output;

# functions
# ---------------------------------------------

# gets (inherited) value of template variable
function getTV($modx,$docid,$doctv)
{
/* apparently in 0.9.2.1 the getTemplateVarOutput function doesn't work as expected and doesn't return INHERITED value; this is probably to be fixed for next release; see http://modxcms.com/bugs/task/464
	$output = $modx->getTemplateVarOutput($tv,$docid);
	return $output[$tv];
*/
	
	while ($pid = $modx->getDocument($docid,'parent'))
	{
		$tv = $modx->getTemplateVar($doctv,'*',$docid);
		if (($tv['value'] && substr($tv['value'],0,8) != '@INHERIT') or !$tv['value']) // tv default value is overriden (including empty)
		{
			$output = $tv['value'];
			break;
		}
		else // there is no parent with default value overriden 
		{
			$output = trim(substr($tv['value'],8));
		}
		$docid = $pid['parent']; // move up one document in document tree
	} // end while
	
	return $output;
}

# gets list of published documents with properties
function getDocs($modx,$startid,$priority,$changefreq,$excludeTV)
{
	// get children documents
	$docs = $modx->getActiveChildren($startid,'menuindex','asc','id,editedon,template,published,searchable,pagetitle,type'); 
	// add sub-children to the list
	foreach ($docs as $key => $doc)
	{
		$id = $doc['id'];
		$docs[$key][$priority] = getTV($modx,$id,$priority); // add priority property
		$docs[$key][$changefreq] = getTV($modx,$id,$changefreq); // add changefreq property
		$docs[$key][$excludeTV] = getTV($modx,$id,$excludeTV); // add excludeTV property
		
		if ($modx->getActiveChildren($id))
			$docs = array_merge($docs, getDocs($modx,$id,$priority,$changefreq,$excludeTV));
	} // end foreach
	return $docs;
}
?>
?>

Пусть Вас не смущает то, что в коде указаны старые версии. Просто не стал править=) В самом коде внесены пара строчек изменений по сравнению с эталонным от старых МОДх.


Далее создаем в корне сайта документ «Карта сайта»:
— тип содержимого html/xml
— убрать галочку у html-редкатора (Очень важно!!!)
— псеводним sitemap.xml
— шаблон blank
— в тело документа вставляем: [!Sitemap!]

!!! Индекс в ЧПУ должен быть отключен, иначе получится sitemap.xml.tml например.

Все, сохраняем и радуемся жизни.
Работает в 1.0.2 и 1.0.3

Шпаргалки для MODx Evolution

Сегодня попались интересная страница на Вики с подборкой свежих шпаргалок.

Есть там следующее (в PDF):

Wayfinder & Breadcrumbs Cheatsheet 1.1
Ditto & Reflect Cheatsheet 1.2
DocParsers API Cheatsheet 1.0
Basic Cheatsheet 1.3

Правда, советую периодически посещать саму страницу т.к. она может обновляться.
  • +9
  • 6 февраля 2010, 16:48
  • iJack
  • 7

Релиз MODx Evolution 1.0.1 + MODx Revolution 2.0.0-beta-4

Вечернее посещение оф. форума привело к двум чудесным темам:
1) MODx Evo 1.0.1 Release Candidate is Ready
2) Help us test 1.0.1 RC

О чём речь, думаю, всем понятно :) А для тех, кто в танке немного русских букав о том, что написано в этих темах.


( Читать дальше )
  • +7
  • 16 октября 2009, 19:18
  • iJack
  • 42

Phx плюс Modx Evo -- не работают ?

Разговори идёт о последних версиях: Phx 2.1.3 / Modx 1.0

Кто-что посоветует?..
  • -1
  • 16 октября 2009, 14:57
  • doc555
  • 2

MODx Evolution изнутри - Как работает modx [перевод]

MODx изнутри – как работает MODx?

MODx Evolution - Logo

Основной функционал MODx состоит из двух частей. Первая часть парсит документы и генерирует страницы, отображаемые пользователю, вторая обеспечивает интерфейс администратора. (Собственно front end и back end, прим. Пер.).

Для начала рассмотрим как MODx генерирует страницы во front end.
Как работает парсер MODx

При открытии страницы сайта запрос отправляется файлу index.php. Строка запроса, в зависимости от настроек сайта содержит ID документа или его алиас. Файл index.php инициализирует объект MODx и запускает парсер.
Парсер принимает ряд мер, чтобы точно определить какой результат возвратить посетителю.


( Читать дальше )
  • +3
  • 7 августа 2009, 10:24
  • pitbull
  • 4

MODx Evolution изнутри - Введение [перевод]

Прекрасный человек потратил уйму времени на то, чтобы разобраться в том, как работает MODx, ну а я решил потратить немножко времени на перевод его статей.

Итак, представляю Вашему вниманию цикл переводов «MODx изнутри»:


( Читать дальше )
  • +1
  • 7 августа 2009, 09:00
  • pitbull
  • 5

MODx Evolution: Порядок выполнения (перевод)

Оригинал статьи в MODx wiki

Порядок выполнения
  1. Содержание
  2. Введение
  3. Порядок выполнения
  4. Порядок работы парсера
  5. Благодарности


Введение

Modx выводит содержимое страницы, возвращая буфер (имеется в виду output bufer, прим пер.) объекта (функции ob_*, прим. пер.). Как разработчику, Вам может пригодиться порядок работы MODx, совершаемой для отображения страницы.


( Читать дальше )

MODx Evolution 1.0 На всех мониторах страны !

Вот мы и дождались.


Баг лист сиротливо опустел (пока :) ), по жилам серверов заструились во все стороны света архивы релиза, а разработчики, наверно, распечатали бутылёк шампанского.
И нам как-то радостно стало, хотя… это ж снова нужно обновления заливать на сайт :)

З.Ы. Carw — готова уже новая демка? :D
  • +3
  • 31 июля 2009, 11:53
  • iJack
  • 84

Вышли в свет MODx Evolution 1.0.0 RC3 и Revolution 2.0.0 beta 3

Пока мы все мирно сопели в своих кроватях — мир изменился… ну почти :) И товарищи разработчики из modxcms.com очень тихо и без лишнего шума подкинули нам много хвороста в костёр обсуждений «какими классными будут новые версии» выпустив в одну ночь релиз кандидаты к Эво и Рево версиям, при этом почему-то Эво обзавелась сразу 3-ей релиз версией, а RC2 выпущена в тот же день лежит в разделе Older releases.

Итак пройдёмся по чэйнджлогам и анонсам систем, для того чтобы понять что нового они нам несут.
Начнём с Revolution 2.0.0 beta 3
МакКормик сразу говорит о том, что этот релиз направлен в первую очередь на залатывание уязвимости, посему строго рекомендует обновиться.
В остальном же релизноутс говорят о интерфейсно-косметических изменениях.

Пройдёмся по MODx Evolution 1.0.0 RC3
Почитав анонс на форуме стал понятен столь быстрый скачок аж до RC3. Похоже в RC2 почти сразу нашёлся баг с парсингом адресов документов при включенном ЧПУ и разрабы очень оперативно всё подправили.
И списка исправлений/дополнений можно выделить появление события OnWelcomePageRender в остальном я заметил только мелки правки… но ведь зачастую глючные мелочи и доставляли(яют) большинство неудобств ;)
  • +1
  • 25 июля 2009, 15:15
  • iJack
  • 30