среда, 8 октября 2014 г.

Что нового?...

Прошёл очередной год моей жизни, задаюсь вопросом - что изменилось за этот год? Пришёл определённый опыт, пришёл вместе с болью утрат, из моей жизни один за другим уходят люди, которые мне были дороги. Немногие остались, и только мысли о них согревают сердце, покрывшееся инеем от холода и запекшейся кровью от ран, нанесенных вчерашними "близкими". Ищу спасения в работе, иногда получается). Остаётся горечь памяти, с которой мне жить до конца жизни, впрочем, жизнь идёт своим чередом, и каждый новый день наполняет жизнь чем-то новым, неведомым, иногда пугающим, как тёмная комната для ребёнка. Когда я уже повзрослею?...).

Хреново...

Очередные посиделки)... Вижу, что ребята пытаются как-то развеселить, но на душе по-прежнему кошки скребут... И неловко от того, что ребята стараются... И ни фига... Ухожу в работу, ухожу с головой. Хочу забыть весь негатив, но эта сволочь, как заноза в мозгу, вытащить можно только плоскогубцами. Ничего, вытравлю, каленым железом иронии и разума. Лишь бы не было поздно, впрочем, "не стоит задаваться слишком большими планами, мой дорогой сосед!"... Смирение не принесло утешения, но дало душевный покой, хотя бы отчасти...

среда, 24 сентября 2014 г.

Переход на MODx Revo

В связи с возросшим количеством страниц на сайте (<16 000)  возникла необходимость смены платформы, однако уходить с MODx совсем не хотелось (слишком мощная и удобная система). В связи с этим нашлась альтернатива, а именно MODx Revolution. Админка впечатлила навороченным Ajax-нтерфейсом, обратной стороной которого явилось усложнение изначально интуитивно понятного интерфейса. В то же время, внутренняя система установки расширений из репозитория MODx очень порадовала. Основным же критерием в пользу Revo стала переработанная система кэширования страниц. Однако возникли определенного рода проблемы, в частности, отличия синтаксиса внутренних тэгов MODx:

Content Elements Evolution (Old) Revolution (New)
Templates no tag representation no tag representation
Template Variables [*templatevar*] [[*templatevar]]
Chunks {{chunk }} [[$chunk]]
Snippets [[snippet]] [[snippet]]
Plugins no tag representation no tag representation
Modules no tag representation does not exist in Revolution
Content Tags
Placeholders [+placeholder+] [[+placeholder]]
Links [~link~] [[~link]]
System Settings [(system_setting)] [[++system_setting]]
Language no tag representation [[%language_string_key]] 



Итак, перввым препятствием стало полное отсутствие знакомого до дрожи в коленках Ditto. В качестве замены ему решил использовать снипет getResources. Вызов оного осуществляется так:

[[getResources? &param1=`value1`,&param2=`value2`]]

Параметры следующие:

Параметры для шаблонов
NameDescriptionDefault ValueAdded in version
tplName of a chunk serving as a resource template. If not provided, properties are dumped to output for each resource
tplOddName of a chunk serving as resource template for resources with an odd idx value (see idx property)
tplFirstName of a chunk serving as resource template for the first resource
tplLastName of a chunk serving as resource template for the last resource
tpl_NName of a chunk serving as resource template for the Nth resource, for example &tpl_4=`tpl4th`
tpl_nNName of a chunk serving as resource template for every Nth resource, for example &tpl_n4=`tpl4th` would apply to any item divisible by 41.4.1
tplConditionDefines a field of the resource to evaluate against keys defined in the &conditionalTpls property. Must be a resource field; does not work with Template Variables.1.5.0
conditionalTplsA JSON object defining a map of field values and the associated tpl Chunks to use when the field defined by &tplCondition matches the value&conditionalTpls=`{"1":"tplA","2":"tplB","3":"tplC"}`
[NOTE: tplOdd, tplFirst, tplLast, * and tpl_{n} will take precedence over any defined conditionalTpls]
1.5.0
tplPathAn optional directory to look for file-based chunks when using @FILEassets_path+ "elements/chunks/"
tplWrapperName of a chunk serving as a wrapper template for the output [NOTE: Does not work with toSeparatePlaceholders]. The placeholder where the items are inserted is [[+output]].1.6.0 
wrapIfEmptyIf true, will output the wrapper specified in &tplWrapper even if the output is empty.false1.6.0 
outputSeparatorAn optional string to separate each tpl instance"\n"
toPlaceholderIf set, will assign the result to this placeholder instead of outputting it directly.
toSeparatePlaceholdersIf set, will assign EACH result to a separate placeholder named by this param suffixed with a sequential number (starting from 0).1.3.0
Параметры для секций (фильтрация вывода)
NameDescriptionDefault ValueAdded in version
parentsComma-delimited list of ids serving as parents. Use -1
to ignore parents when specifying resourcesto include.
If this is not done, getResources assumes &parents
as the current resource and reads its children from there
(plus the resources given in &resources = unexpected results).
current Resource id
resourcesComma-delimited list of ids to include in the results.
Prefix an id with a dash to exclude the resource from the result.
depthInteger value indicating depth to search for resources
from each parent. First level of resources beneath parent is depth
10
tvFiltersCan be used to filter resources by certain TV values.
These are entered as [( tvname)( operator)]( value). There are two
delimiters you can use to combine filter conditions.
You can have "OR" filters using two pipe symbols.
An OR filter fetches resources that has one of the listed TV values.
?
1
2
mytv==somevalue||mytv==othervalue
You can also use an "and" filter using a comma.
This will make sure that all the conditions are met.
?
1
2
mytv==somevalue,othertv==othervalue
For advanced filtering you can also group these. It is important
to know that conditions are first separated based
on the OR (||) delimiter, and after that on the AND (,) delimiter.
So let's take this hypothetical example:
?
1
2
mytv==foo||mytv==bar,bartv==3||bartv==1
This will filter resources to meet one of the following conditions:
  • mytv is LIKE foo, or
  • mytv is LIKE bar AND bartv is LIKE 3, or
  • bartv is LIKE 1 
    The examples above search for exact values.
    You can also use the percentage sign (%) as a wildcard. For example:
?
1
2
mytv==%a%
Matches any resources that has an "a" in the mytv value.
?
1
2
mytv==a%
Matches any resources that have a mytv value that starts with an "a"
?
1
2
mytv==%a
Matches any resources that have a mytv value that ends with an "a".
You can also combine this with the OR (||) and AND (,) delimiters explained above.
It is important to know that this function looks at the raw value
of a template variable
for a specific resource.
This means that the value has been explicitly set for the resource,
and that it has not been processed by a template variable
output type
or is the default value in releases prior to 1.4.2-pl;
this release adds support for filtering that includes default values
).
So if you have an "autotag" tv, this means the raw value
is a comma delimited list, and it is not split up in tags
like you see it in the manager.
New filter operators available in 1.4.2-pl
Starting with release 1.4.2-pl of getResources, there are a number
of new comparison operators for use when creating filter conditions.
In addition, when using many of these new operators, numeric
comparison values are automatically CAST TV values to numeric
before comparison. Here is a list of the valid operators:
Filter OperatorSQL OperatorCASTs numericsNotes
<=><=>YesNULL safe equals
====Yes
!==!=Yes
<><>Yes
==LIKENo
!=NOT LIKENo
<<<Yes
<=<=Yes
=<=<Yes
>>>Yes
>=>=Yes
=>=>Yes
sortbyAny Resource Field (excluding Template Variables) to sort by.
Some common fields to sort on are publishedon, menuindex,
pagetitle etc, but see the Resources documentation for all fields.
Specify fields with the name only, not using the tag syntax.
Note that when using fields like template, publishedby
and the likes for sorting, it will be sorted on the raw values,
so the template or user ID, and NOT their names.
You can also sort randomly by specifying RAND(), like so:
?
1
2
&sortby=`RAND()`
From version 1.3.0 this can also be a JSON array to sort on multiple fields, e.g.
?
1
2
&sortby=`{"publishedon":"ASC","createdon":"DESC"}`
To sort in a specific order, specify a resource id-list, e.g.
?
1
2
&sortby=`FIELD(modResource.id, 4,7,2,5,1 )`
The same thing is possible if you put the sorted IDs in a template variable, like this:
?
1
2
&sortby=`FIELD(modResource.id,[[*templateVariable]])`
createdon
publishedonModified in 1.3.0
sortbyAliasQuery alias for sortby field
sortbyEscapedEscapes the field name specified in sortby
sortdirOrder which to sort byDESC
sortbyTVTemplate Variable to sort by1.2.0
sortdirTVOrder which to sort by when using sortbyTVDESC1.2.0
sortbyTVTypeSpecify the data type of the sortby TV.
Possible values are string, integer, decimal, datetime
string1.3.0
limitLimits the number of resources returned. Use `0` for unlimited results.5
offsetAn offset of resources returned by the criteria to skip0
whereA JSON-style expression of criteria to build
any additional where clauses from.
See below for an example.
Seedisplay/xPDO20/xPDOQuery.where
contextComma-delimited list of context keys to limit results by;
if empty, contexts for all specified parents will be used
(all contexts if 0 is specified)

Другие параметры

NameDescriptionDefault ValueAdded in version
showUnpublishedIf true, will also show Resources if they are unpublished.0
showDeletedIf true, will also show Resources regardless if they are deleted.0
showHiddenIf true, will show Resources regardless if they are hidden from the menus.0
hideContainersIf set, will not show any Resources marked as a container (is_folder).0
includeContentIndicates if the content of each resource should be returned in the results0
includeTVsIndicates if TemplateVar values should be included in the properties available to each resource template0
includeTVListAn optional comma-delimited list of TemplateVar names to include explicitly if includeTVs is 11.4.0
prepareTVsPrepares media source-dependant TemplateVar values.11.5.0
prepareTVListLimits the TVs that are prepared to those specified by name in a comma-delimited list1.5.0
processTVsIndicates if TemplateVar values should be rendered as they would on the resource being summarized. TemplateVars must be included (see includeTVs/includeTVList) to be processed.0
processTVListAn optional comma-delimited list of TemplateVar names to process explicitly. TemplateVars specified here must be included via includeTVs/includeTVList1.4.0
tvPrefixThe prefix for TemplateVar propertiestv.
idxYou can define the starting idx of the resources, which is an property that is incremented as each resource is rendered1
firstDefine the idx which represents the first resource1
lastDefine the idx which represents the last resource. Default is # of resources being summarized + first - 1
totalVarDefine the key of a placeholder set by getResources indicating the total number of Resources that would be selectednotconsidering the limitvalue.total
debugIf true, will send the SQL query to the MODX log.false
Оригинал - здесь

Теперь о плейсхолдерах:

TagData TypeDescriptionExample Usage
[[*alias]]textAliasNormally, you will use the id to generate the URL, e.g. Click Here!, but this lets you print out the alias parameter.
[[*cacheable]]int 0/1Cacheable
[[*class_key]]intClass Key of the Resource, e.g. modDocument
[[*content]]textResource Content
[[*content_type]]intContent Type
[[*createdon]]dateCreated On date, e.g. 2011-04-14 20:40:50, often used in conjunction with the strtotime output filter[[*createdon:strtotime:date=`%a %b %e, %Y`]] See Date Formats.
[[*createdby]]intCreated By User ID Number
[[*deleted]]int 0/1Deleted
[[*deletedby]]intDeleted By User ID Number
[[*deletedon]]dateDate of Deletions[[*deletedon:strtotime:date=`%a %b %e, %Y`]] See Date Formats.
[[*description]]textDescription
[[*editedon]]dateEdited On date, e.g. 2011-04-18 09:06:08[[*editedon:strtotime:date=`%a %b %e, %Y`]] See Date Formats.
[[*editedby]]intEdited By User ID number
[[*hidemenu]]int 0/1Hide From Menus; this attribute is read by many Snippets, e.g. WayFinder
[[*id]]intResource IDUsed frequently to generate links to this page.
[[*introtext]]textSummary
[[*isfolder]]int 0/1Container
[[*link_attributes]]textLink attributes; these are inserted automatically when you use the [[~123]] syntax
[[*longtitle]]textLong Title
[[*menuindex]]intMenu Index
[[*menutitle]]textMenu Title
[[*pagetitle]]textPage Title
[[*parent]]intParent Resource
[[*pub_date]]date ---Publish Date
[[*published]]int 0/1Published
[[*publishedby]]intPublished By User ID Number
[[*publishedon]]datePublished On[[*publishedon:strtotime:date=`%a %b %e, %Y`]] See Date Formats.
[[*richtext]]int 0/1Rich Text
[[*searchable]]int 0/1Searchable
[[*template]]intTemplate ID number
[[*unpub_date]]date – Unpublish Date[[*unpub_date:strtotime:date=`%a %b %e, %Y`]] See Date Formats.
[[*uri_override]]int 0/1Freeze URI
[[*uri]]stringURI
Оригинал - здесь

Итак, начинаю колдовать...