Суперглобальный массив $_SERVER

MediaWiki pages name encoding is a complicated topic. MediaWiki magic words PAGENAME, PAGENAMEE and urlencode have distinct implementations, each with their own peculiarities.

A MediaWiki page name can have a leading space but not a trailing space. The ASCII characters that are not allowed in MediaWiki page names are the three types of brackets, sharp sign, underscore and vertical bar, and all control characters (including tabs and newlines).

# < > _ { | } Note that the underscore is not really disallowed, but is treated like a space without distinction in MediaWiki page names, so "A_B" and "A B" are referencing exactly the same page name (pages will be created, searched, and displayed (with their title) using spaces, never using underscores).

This article shall refer to these as the "not-allowed pagename characters". For clarity, we will present other ASCII 7-bit values for characters as the URL-style encoding of percent-hex-hex form known as percent-encoding .

Contents

PAGENAME [ edit ]

Otherwise these dots are left intact by {{urlencode:...}} and {{anchorencode:...}} , but slashes may be converted.

Also the sequence of two successive slashes //) may not be accepted in page names, depending on the configuration of the wiki. Usually this is an indicator that the name is an URL, when it is preceded by a valid URI scheme (or no URI scheme at all where it means a default "http:" or "https:" URI scheme will be used, depending on user"s preference). An URI scheme should then contain a colon (:), but MediaWiki currently recognizes only URI schemes where the colon is final, in a restricted list; otherwise.

For example on this wiki,

"{{PAGENAME|//www.сайт/}}"

"//www.сайт/" .

On Wikimedia sites, such as сайт, the double slashes are recognized as URIs, and most valid URIs are disallowed as page names (if an URI scheme is present, it coud be recognized as a name space it it has been configured, otherwise the page name will fall into the main name space of the wiki):

  • Creating a link to these URI-like page names uses:
    • [[ page name in double brackets | with optional displayed text ]] .
  • But links to the effective target of the URI uses either:
    • [ URL-without-spaces-in-single -brackets with optional displayed text ] , or
    • URI-without-spaces (also displayed show verbatim, but the link will be conditionally activated as it is subject to restrictions of recognized URI schemes).

So on this wiki on сайт, the following code

[]

unexpectely creates a direct link to the external URL, surrounded by verbatim single brackets:

URIs are not recognized by URL-encoding and anchor-encoding (this means that valid full URLs cannot be safely created with urlencode!).

Документация

Шаблон {{When pagename is }} предназначен для использования внутри других шаблонов. Он помогает другим шаблонам определить, на какой странице они выполняются. Шаблон проверяет на совпадение имя страницы по заданному образцу {{When on page }} .

Использование

Шаблон может обрабатывать более одного параметра. Большинство параметров не имеют определенного имени, поскольку их имена используются для введения образца поиска. Например:

{{When pagename is | /doc = Doc page text | other = Other pages text }}

Если шаблон включен на странице "Template:Example/doc" код выше вернет текст для страницы документации.

Doc page text

Если шаблон включен на другой странице, имя которой не содержит /doc, то код вернет текст для остальных страниц.

{{When pagename is | User:Example/test = Text for "User:Example/test". | User:Example = Text for "User:Example". | User talk:Example = Text for "User talk:Example". | User:Example/+ = Matches "User:Example" and "User:Example/test". | Example = Matches "User:Example", "User talk:Example", "Template:Example" and so on, but not "User:Example/something". | User:Example/* = Matches "User:Example/something", but not "User:Example". | User talk:Example/* = Matches "User talk:Example/something". | Example/* = Matches "User:Example/something" and "User talk:Example/something". | /something = Any pagename that ends in "/something". | /doc = Any pagename that ends in "/doc". | /some* = Any subpage name beginning with "/some" or "/Some". | /arch* = Matches "User talk:Example/Archive 1". | basepage = Text for any basepage. | subpage = Text for any subpage. | other = Text for any page. }}

Сравнение производится сверху вниз и возвращается тот вариант, в котором произошло совпадение. Под словами «сверху вниз» подразумевается порядок вариантов выше, а не порядок параметров передаваемых в шаблон. У шаблона нет ограничений на количество параметров, которые можно передать, кроме ограничений наложенных сервером и движком MediaWiki.

Большинство проверок не зависят от регистра букв. Однако вроде " /test " совпадет с "User:Example/test", но не из "User:Example/Test".

Проверка на совпадение с частью имени подстраницы, такой как " /some* " имеет некоторые ограничения. См. посвященный этому разделу ниже.

Дозволяется задавать пустое значение в параметре сравнения, при совпадении с образцом дальнейшее сравнение прекращается и шаблон возвращает пустую строку. Это может использоваться для следующих целей:

{{When pagename is | /doc = | /sandbox = Sandbox text | other = Other pages text }}

Код выше ничего не отобразит, если шаблон вызовется на странице /doc, но на странице /sandbox он вернет текст для страницы песочницы. А на других страницах отобразится:

Sandbox text

And when on any other page it will return this:

Other pages text

Частичные имена подстраниц

Также этот шаблон может сравнивать часть имени подстраницы. Например:

{{When pagename is | /archiv* = Archive page text | other = Other pages text }}

На странице "User:Example/Archive 1" код выше вернет текст для остальных страниц:

Archive page text

Название параметра образца сравнения " /some* " не должно содержать заглавных букв, но совпадение будет на подстранице содержать как большие, так и маленькие буквы, как "User:Example/SomeThing" и "User:Example/something".

Сопоставимая часть имени страницы в образце может содержать 4, 6 и 8 символов. Сравнение с "/some*", "/someth*" и "/somethin*" works, but using "/som*" или "/somet*" doesn"t work.

Сначала сравниваются длинные образцы, например если заданы оба образца "somethin*" и "/some*", и текущая станица называется "User:Example/Something", то шаблон вернет то, что задано в параметре"/somethin*".

Параметр "page"

Для проверки и демонстрации работы шаблон обрабатывает параметр page. Например:

{{When pagename is | /test = Test pages text | other = Other pages text | page = Template:Example/test }}

No matter on what kind of page the code above is used it will return this:

Test pages text

The page parameter makes this template behave exactly as if on that page. The pagename doesn"t have to be an existing page.

If the page parameter is empty or undefined, the name of the current page determines the result.

You can make it so your template also understands the page parameter. That means you can demonstrate the different appearances of your template in the documentation for your template. Then do like this:

{{When pagename is | /test = Test pages text | other = Other pages text | page = {{{page|}}} }}

Пространство имён соответствия

This template doesn"t have namespace matching. If you need that then combine this template with one of the namespace-detection templates such as {{When on template page }} . Like this:

{{When on template page | {{When pagename is | /doc = Template doc page text. }} | }}

Так на странице "User:Example/doc" код ничего не вернет, но на странице "Template:Example/doc" вернет:

Шаблон:When on template page

Технические подробности

Это шаблон определяет дополнительные страницы даже если он используется на страницах в пространстве имен, для которых запрещено создание дополнительных страниц. Таким образом, он все равно работает во всех пространствах имен.

См. также

Из вашего комментария:

Привет Crayon спасибо за ваш ответ 1.yup мой клиент запросил для пользовательского имени страницы для всех страниц через сайт. Мы используем инструмент CMS для сайта над кодом, который жестко закодирован в главном шаблоне 2. да, я вызываю другую st() на загрузку страницы для захвата других событий, prop, evar.. 3. Если я передаю s.PageName = "abc.com:home" всякий раз, когда я вызываю другое st() PageName, получает захват в другой st(), чтобы уменьшить дублирование имени страницы. Я передаю ее как параметр. 4. Я также перекрестно проверил с другими инструментами отладки только в одном маяке, я передаю pagename

Хорошо, поэтому причина, по которой вы видите как значение pageName, так и URL-адрес в отчетах ваших страниц, состоит в том, что у вас есть два вызова st() , и только 1 из них имеет значение для s.pageName . Вы сказали, что pageName значение pageName чтобы не допустить, чтобы страница подсчитывалась дважды. Ну, это уже происходит, потому что вы используете два вызова st() . Поскольку вы не указываете имя pageName во втором, URL-адрес по умолчанию.

Идеальное решение состоит в том, чтобы перестроить ваш код, чтобы иметь только один вызов st() . Вы сказали, что работаете с CMS. Поэтому в идеале вы должны использовать s_code.js сценария в глобальном заголовке. то вы должны иметь один вызов st() в глобальном нижнем колонтитуле. Вы также можете поместить глобальные вары в раздел нижнего колонтитула (или в s_code.js > s_doPlugins). Затем между этими двумя является то, где вы бы поместили какой-либо специальный код на странице. Мне кажется, что вы уже делаете это... но вам просто нужно удалить первый вызов st() .

Если по какой-либо причине вы не можете достичь идеального решения, вместо этого вы должны использовать s.tl() для второго запроса. Чтобы использовать s.tl() , вы сделали бы что-то вроде этого:

S.prop1="foo"; s.eVar1="bar"; s.events="event1"; s.linkTrackVars="prop1,eVar1,events"; s.linkTrackEvents="event1"; s.tl(true,"o","description");

В принципе, любые реквизиты, eVars и события, которые вы хотите отслеживать в вызове s.tl , должны быть объявлены в linkTrackVars и linkTrackEvents .

ПРИМЕЧАНИЕ . Вы должны действительно стремиться к идеальному решению. Это не только отчет о страницах, который может завысить. Любые другие варны, которые вы установили, тоже будут завышены. Кроме того, платежная модель Adobe должна взимать плату за каждый отдельный запрос на свой сервер, поэтому вашему клиенту, вероятно, не понравится тот факт, что вы удваиваете свой счет, делая это.

Метод s.tl отнюдь не идеален, но лучше, чем вы сейчас делаете. поскольку это уменьшит инфляцию отчета, а запросы s.tl стоить меньше, чем запросы st .

Depending on the namespace and the settings, a forward slash in the pagename provides special functionality, see subpage feature .

Namespace prefixes [ edit ]

Also, the first part of a page name may not coincide with a project-independent namespace prefix that is automatically converted to another one . As an example, the name Project: A-Kon on Wikipedia is not possible.

The first part of a page name can coincide with a namespace prefix that is not converted. For example, there might be articles in the English Wikipedia about books called Wikipedia: The Big Adventure and Talk: Secrets are Bad (but only without the space after the colon). However, in that case the pages are in the wrong namespace. This may be inconvenient in searching or displaying a list of pages. Also, in the second case there is no link to a Talk page about the book. (As explained above, the second page name is not possible on e.g. the German Wikipedia: see w:de:Talk: Secrets are Bad).

Prefixes referring to other projects or pseudo-namespaces [ edit ]

A page name cannot start with a prefix that is in use to refer to another project, including language codes, e.g. "en:" (list), or one of the pseudo-namespaces "Media:" and "Special:".

Thus e.g. an article about the album "Q: Are We Not Men? A: We Are Devo!" can not have that exact name. An attempt to create the article, whether by a link Q: Are We Not Men? A: We Are Devo! or a URL http://en.wikipedia.org/wiki/Q:Are_We_Not_Men%3F_A:_We_Are_Devo%21 leads to Wikiquote.

With regard to using the prefix of the project itself there is no consistency: a name like en:a cannot be used on en: (try w:en:a and w:en:en:a), while "Q: Are We Not Men? A: We Are Devo!" can exist on Wikiquote: q:Q: Are We Not Men? A: We Are Devo! .

Maximum page name length [ edit ]

The maximum page name length is 255 bytes (excluding the namespace prefix). Be aware that non-ASCII characters may take up to four bytes in UTF-8 encoding, so the total number of characters you can fit into a title may be less than 255 depending on the language it"s in.

Spaces vs. underscores [ edit ]

In page names , a blank space is equivalent with an underscore. A blank space is displayed in the large font title at the top of the page, the URLs show an underscore. See also below.

Case-sensitivity [ edit ]

Currently the first character of the page name is case-in sensitive, except in the following Wiktionaries:

Case where the first character is case-insensitive

The canonical form is with a capital.

Note that in the case of a prefix that is not a namespace for the software, and in the case of a second prefix, the case-insensitivity does not apply to the first character after this prefix, e.g. Template:H:Interwiki linking and Template:H:interwiki linking are distinguished.

Case-sensitivity of the file name extension of an image [ edit ]

Note that even the file name extension of an image is case-sensitive: compare image:Stop_sign_us.jpg and image:Stop_sign_us.JPG 748410449856

Ignored spaces/underscores [ edit ]

Spaces/underscores which are ignored:

  • those at the start and end of a full page name
  • those at the end of a namespace prefix, before the colon
  • those after the colon of the namespace prefix
  • duplicate consecutive spaces

Some show up in the link label, e.g. [[___help__ :_ _template_ _]] becomes ___help__ :_ _template_ _ , linking to Help:Template .

However, a space before or after a "normal" colon makes a difference, e.g. and MediaWiki User"s Guide: Editing overview , and MediaWiki User"s Guide:Editing overview are all distinguished, because "MediaWiki User"s Guide:" is a pseudo-namespace, not a real one.

Coding of characters [ edit ]

A page name can not contain e.g. %41, because that is automatically converted to the character A, for which %41 is the code. [[%41]] is rendered as . Similarly %C3%80 is automatically converted to the character À. [[%C3%80]] is rendered as . The URL of the page is http://meta.wikipedia.org/wiki/%C3%80 . One can argue what is the real name of the page, %C3%80 or À (a user will say the latter), but anyway there can not be distinct pages with these names.

Canonical form [ edit ]

The inclusion tag for a non-existing page shows a link with the canonical form of the page name: {{qwsazx}}, {{:qwsazx}}, {{project:qws azx}} give Template:Qwsazx , Qwsazx , Wikiquote:Qws azx ; compare with ordinary links Template:qwsazx , qwsazx , project:qws azx ; these work like Piped links , e.g. []; in this case the conversion shows up on the referring page only when pointing at it: in the pop-up and in the status bar (if applicable for the browser); whether the target is a redirect, and what the final target is, is not shown at all.

An attempt to include a page from another project results in just displaying the wikitext, e.g. Template:Qwsazx ; ordinary interwiki links do not show existence and do not show a canonical form in the hover box or status bar: en:project:qwsazx . The same applies if interwiki link style is used for a link to a page in the same project: m:project:qwsazx .

A saved redirect page shows the canonical form of the target, even though the preview renders the link in the usual way, compare with the preview of .

Alphabetical order [ edit ]

Thus we have the following partial list showing the order:

!"#$%&"()*+,-./0123456789:;<=>?@
ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_"
abcdefghijklmnopqrstuvwxyz{|}~
¡¢£¤¥¦§¨©ª«­®¯°±²³´µ ¸¹º»¼½¾¿
ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ
ĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋ
ŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſ
ǺǻǼǽǾǿ΄΅Ά·ΈΉΊΌΎΏΐ
ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩΪΫάέήίΰ
αβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ

Note in particular that "Z" comes before "a", and "z" before "é". The blank space within a page name is treated as an underscore, and therefore comes after the capitals, and before the lower case letters. However, a "blank space" after the name comes before any character. Sometimes a special character looks like a regular letter, but has a special code anyway.

Thus we have the order PC, PCX, PC Bruno, PCjr, Κύρια Σελίδα.

Variables PAGENAME and PAGENAMEE [ edit ]

Within localurl, {{PAGENAME}} should be used in the first part (because it is converted by localurl), or {{PAGENAMEE}} in the second part:

  • {{SERVER}}{{localurl:Special:Allpages|namespace=12&from={{PAGENAMEE}}}} gives here:

//сайт/w/index.php?title=Special:Allpages&namespace=12&from=Page_name

  • {{SERVER}}{{localurl:Special:Allpages/{{PAGENAME}}|namespace=12}} gives here:

//сайт/w/index.php?title=Special:Allpages/Page_name&namespace=12

  • {{SERVER}}{{localurl:Special:Allpages|namespace=12&from={{PAGENAME}}}} gives here:

//сайт/w/index.php?title=Special:Allpages&namespace=12&from=Page name (wrong link)

  • {{SERVER}}{{localurl:Special:Allpages/{{PAGENAMEE}}|namespace=12}} gives here:

//en.wikiquote.org/w/index.php?title=Special:Allpages/Page_name&namespace=12 (works here, the underscore, converted from a space, is not affected by the second conversion, but it does not work with special characters).

Flector 5

Обновлено:

При установке структуры постоянных ссылок в виде "/%category%/%postname%.html " все ссылки на записи начинают заканчиваться на ".html ". Однако, этот формат ссылок никак не влияет на ссылки страниц. Что немного раздражает – подобной структурой ссылок мы подчеркиваем, что на нашем сайте является страницей, а что нет. Страница это то, что с ".html " в конце, а все остальное это рубрики, метки или еще какие другие таксономии. Ссылки на страницы в данном контексте выбиваются из общей картины – они кажутся ссылками на рубрики, хотя это и не так. Плагин эту неприятную ситуацию исправляет, добавляя ссылкам на страницы окончание ".html ".

1 Распаковываем архив.

2 Копируем файл в папку /wp-content/plugins/ .

3 Заходим в админку блога на вкладку "Плагины " и активируем плагин.

Настроек в плагине нет и сразу после своей активации он начинает работать. Теперь все ссылки на страницы превратятся из таких:

Вот в такие:

Но как быть в том случае, если вам надо изменить ".html " на ".htm " или вообще на ".php "? В плагине совсем нет никаких настроек, поэтому его придется отредактировать вручную. Для этого откройте файл плагина и измените в нем следующие строчки:

13 $wp_rewrite ->

$wp_rewrite->

18 $wp_rewrite -> page_structure = "%pagename%.html" ;

$wp_rewrite->page_structure="%pagename%.html";

Вместо ".html " пропишите нужное вам окончание. После этого вам необходимо будет деактивировать и активировать плагин заново. Сразу после повторной активации плагина все ссылки на ваши страницы будут содержать то окончание, которое вы прописали в файле плагина.

Я отнес данный плагин к рубрике "SEO ", но формально, конечно, он к этой рубрике не имеет никакого отношения. Поисковикам откровенно наплевать, как выглядят ссылки на ваши записи, страницы или рубрики. Да и вашим посетителям, по большому счету, это тоже неважно. Но с точки зрения эстетичности ссылок данный плагин необходим. В конце концов, вы же изменили структуру постоянных ссылок на более красивую, хотя это и не имеет никакого смысла с точки зрения SEO-оптимизации блога.



Понравилась статья? Поделиться с друзьями: