%PDF- %PDF-
Direktori : /home/waritko/jetty-distribution-9.4.21.v20190926/webapps/ROOT/templates/ |
Current File : //home/waritko/jetty-distribution-9.4.21.v20190926/webapps/ROOT/templates/macros.vm |
############################################################### ## Contains various standard Velocity macros automatically ## loaded and usable everywhere (in Velocity). ## ## Note that if you modify that file you will need to restart. ############################################################### ## ## #template("name.vm") ## Searches for the given velocity template and interprets it. ## Only the velocity parser is executed on the file. ## The template is searched in the following locations, in this order: ## - as a property of the XWikiSkins object attached to the current skin document ## - as an attachment to the current skin document ## - as a file in the directory corresponding to the current skin ## - the above 3 locations corresponding to the base skin ## - the above 3 locations corresponding to the default skin ## - as a file in the /templates/ directory ## #macro(template $tname) $xwiki.parseTemplate($tname) #end ## ## ## #renderTemplate("name.vm") ## Searches for the given velocity template and renders it. ## The template is searched in the following locations, in this order: ## - as a property of the XWikiSkins object attached to the current skin document ## - as an attachment to the current skin document ## - as a file in the directory corresponding to the current skin ## - the above 3 locations corresponding to the base skin ## - the above 3 locations corresponding to the default skin ## - as a file in the /templates/ directory ## #macro(renderTemplate $tname ) $xwiki.renderTemplate($tname) #end ## ## ## #includeTopic("Space.Document") ## Includes another fully rendered document inside the current response. ## The topic is interpreted and rendered exactly as if it were viewed in a separate response, ## meaning that the $doc variable will point to the included document. The resulting string is ## wrapped with {pre}...{/pre}, in order to prevent double-rendering. ## The platform prevents recursive includes. ## This macro is useful for creating composite documents from smaller parts, or the other way around, ## splitting a large document into smaller distinct chunks which can be edited in parallel. ## #macro(includeTopic $topic) $xwiki.includeTopic($topic) #end ## ## ## #includeMacros("Space.Document") ## Includes the content of another document as velocity macros. Because of the way the velocity ## engine works, trying to place macros in another document and including it with another method ## will not have the expected result. Other than making the macros available, it works just as ## #includeForm($topic) ## #macro(includeMacros $topic) $xwiki.includeForm($topic) #end ## ## ## #includeForm("Space.Document") ## Includes another fully rendered document inside the current response. ## The included content is interpreted and rendered in the current context, meaning that $doc will ## point to the current document (the includer), and not the included one. The resulting string is ## wrapped with {pre}...{/pre}, in order to prevent double-rendering. ## The platform prevents recursive includes. ## This macro is the core of the document-template-sheet functionality of XWiki, where a document ## has an XObject attached to it, its content consists of the "#includeForm('Some.Sheet')" statement, ## and the sheet works just as if it were actually inside the document's content. ## #macro(includeForm $topic) $xwiki.includeForm($topic) #end ## ## ## #includeInContext("Some.Document") ## Alias for #includeForm ## #macro(includeInContext $topic) $xwiki.includeForm($topic) #end ## ## ## #includeServlet("/xwiki/bin/view/Some/Document?params") ## Invokes on the server another servlet corresponding to the passed URL, and returns the output. ## This is done using standard servlet mechanisms (javax.servlet.RequestDispatcher#include). ## #macro(includeServlet $url) <!-- including $url --> $xwiki.invokeServletAndReturnAsString($url) <!-- included $url --> #end ## ## ## ## ## #skype("skypeId") ## Displays the status for the given Skype id ## ## @Deprecated #macro(skype $id) <a href="skype:${id}?call"><img width="182" height="44" src="http://mystatus.skype.com/bigclassic/${id}" style="border: none;"></a> #end ## ## ## #yahoo("yahooId") ## Displays the status for the given Yahoo! id ## ## @Deprecated #macro(yahoo $id) <img border="0" src="http://opi.yahoo.com/online?u=${id}&m=g&t=1" alt="yahoo $id" /> #end ## #sign("XWiki.Username") ## Displays a "signature", a link to the user's profile page. ## #macro(sign $username) #if($username.indexOf(".")==-1) #set($username = "XWiki.${username}") #end #if($xwiki.exists("$username")) $xwiki.getUserName("$username") #else $xwiki.getUserName("xwiki:${username}") #end #end #macro(includeHelp $pagename) #if($xwiki.exists("xwiki:XWiki.${pagename}")) $xwiki.includeForm("xwiki:XWiki.${pagename}",false) #else #if($xwiki.exists("XWiki.${pagename}")) $xwiki.includeForm("XWiki.${pagename}",false) #end #end #end #macro(toc $pinit $pmax $pnumbered) #set($init = $pinit) #set($max = $pmax) #set($numbered = $pnumbered) #set ($int = 0) #set ($boolean = false) #if ($init == "") #set ($init = 2) #else #set ($init = $int.valueOf($init)) #end #if ($max == "") #set ($max = 6) #else #set ($max = $int.valueOf($max)) #end #if ($numbered == "") #set ($numbered = false) #else #set ($numbered = $boolean.valueOf($numbered)) #end #set ($tocData = ${tdoc.getTOC($init, $max, $numbered)}) #set ($xcontext.tocData = $tocData) #set ($lastLevel = $init - 1) #set ($depth = 0) #set ($openeditem = true) <div class="toc"> #foreach ($tocEntry in $tocData.entrySet()) #set ($level = $tocEntry.value.level) #if ($level > $lastLevel) #set ($to = $lastLevel + 1) #set ($iter = [$level .. $to]) #foreach ($n in $iter) #if($openeditem) #set($openeditem = false) #else <li> #end <ul class="tocLevel"> #set ($depth = $depth + 1) #end #elseif ($level < $lastLevel) #set ($to = $level + 1) #set ($iter = [$lastLevel .. $to]) </li> #foreach ($n in $iter) </ul> </li> #set ($depth = $depth - 1) #end #else </li> #end <li class="tocEntry"><a href="#$tocEntry.key">$!tocEntry.value.numbering #evaluate($tocEntry.value.text)</a> #set ($lastLevel = $level) #set($openeditem = true) #end #if ($depth > 0) #set ($levels = [1 .. $depth]) #foreach($level in $levels) </li> </ul>#end #end </div> #end ### ### Separator ### ### Insert a span containing a | ### #macro(sep) <span class="separator"> | </span> #end #** * Displays the user avatar and name, linked to the user profile page. * * @param arg could be either a string, a reference or a list of them * @param options various configuration options; default values are { * showAlias: false, // whether to show the user alias or not * useInlineHTML: false, // whether to use in-line HTML elements to display the user or not * wrapAvatar: false // whether to wrap the avatar image with a span or not * } *# #macro (displayUser $arg $options) #set ($isList = $arg.iterator()) #if ($isList) #set ($usersList = $arg) #else #set ($usersList = [$arg]) #end #set ($macro.options = { 'showAlias': false, 'useInlineHTML': false, 'wrapAvatar': false }) #if ($options.entrySet()) #set ($discard = $macro.options.putAll($options)) #end #set ($usersTag = 'ul') #set ($userTag = 'li') #if ($macro.options.useInlineHTML) #set ($usersTag = 'span') #set ($userTag = 'span') #elseif (!$isList) #set ($userTag = 'div') #end #set ($types = $collectionstool.set) #set ($output = []) #foreach ($user in $usersList) ## Since we accept both a String or an EntityReference as input, we first check if we have an Entity Reference ## to a Document and if not then we resolve the String to convert it to a Document Reference. #set ($userReference = $user.extractReference('DOCUMENT')) #if (!$userReference) #set ($userReference = $services.model.resolveDocument($user, 'user/current')) #end #set ($userAlias = $userReference.name) #if ($userAlias == $services.model.getEntityReference('DOCUMENT', 'default')) #set ($userAlias = $userReference.lastSpaceReference.name) #end #set ($userDocument = $xwiki.getDocument($userReference)) #if ($userDocument.getObject('XWiki.XWikiGroups')) #set ($type = 'group') #set ($userName = $userDocument.plainTitle) #if ("$!userName" == '') #set ($userName = $userAlias) #end #else #set ($type = 'user') #set ($userName = $xwiki.getPlainUserName($userReference)) #end #set ($discard = $types.add("${type}s")) #set ($userAliasDisplay = '') #if ($macro.options.showAlias && $userAlias != $userName) #set ($userAliasDisplay = "<span class=""${type}-alias"">" + $escapetool.xml($userAlias) + '</span>') #end #set ($escapedUserName = $escapetool.xml($userName)) #getUserAvatarURL($userReference $avatarURL 120) #set ($avatarWrapperStart = '') #set ($avatarWrapperEnd = '') #if ($macro.options.wrapAvatar) #set ($avatarWrapperStart = "<span class=""${type}-avatar-wrapper"">") #set ($avatarWrapperEnd = '</span>') #end ## We avoid the whitespace because the users are displayed as inline blocks. #set ($discard = $output.addAll([ "<$userTag class=""$type"" data-reference=""$escapetool.xml($userReference)"">", $avatarWrapperStart, "<img class=""${type}-avatar"" src=""$escapetool.xml($avatarURL.url)"" alt=""$escapedUserName"" />", $avatarWrapperEnd, "<a class=""${type}-name"" href=""$escapetool.xml($xwiki.getURL($userReference))"">$escapedUserName</a>", $userAliasDisplay, "</$userTag>" ])) #end #if ($isList && $output.size() > 0) #set ($discard = $output.add(0, "<$usersTag class=""$stringtool.join($types, ' ')"">")) #set ($discard = $output.add("</$usersTag>")) #end $stringtool.join($output, '') #end #** * Displays the group avatar and name, linked to the group profile page. * * @param arg could be either a string, a reference or a list of them * @param options various configuration options; default values are { * showAlias: false, // whether to show the group alias or not * useInlineHTML: false, // whether to use in-line HTML elements to display the group or not * wrapAvatar: false // whether to wrap the avatar image with a span or not * } *# #macro (displayGroup $arg $options) #displayUser($arg $options) #end ### ### useravatar ### ### Display the avatar of a user or a group, or a default image if the user/group has no avatar ### ### @param username The name of the user or group whose avatar will be displayed ### #macro(getUserAvatarURL $userName $return $size) #set ($specified = false) #set ($profileDoc = $xwiki.getDocument($userName)) #if ($profileDoc.getObject('XWiki.XWikiGroups')) #set ($url = $xwiki.getSkinFile('icons/xwiki/noavatargroup.png', true)) #else #set ($url = $xwiki.getSkinFile('icons/xwiki/noavatar.png', true)) #end #if ($profileDoc && !$profileDoc.isNew() && $profileDoc.attachmentList.size() > 0) #set ($profileObj = $profileDoc.getObject('XWiki.XWikiUsers', 0)) #set ($avatarFileName = $profileObj.getProperty('avatar').value) #if ("$!avatarFileName" != '') #set ($avatarAttachment = $profileDoc.getAttachment($avatarFileName)) #elseif ($profileDoc.getObject('XWiki.XWikiGroups')) ## Look for the first image attachment. #foreach ($attachment in $profileDoc.attachmentList) #if ($attachment.isImage()) #set ($avatarAttachment = $attachment) #break #end #end #else ## This ensures that $avatarAttachment is always set before the following "if" is called, preventing a previous ## call to this macro from leaking... #set ($avatarAttachment = $NULL) #end #if ($avatarAttachment && $avatarAttachment.isImage()) #set ($queryString = '') #if ($size > 0) #set ($queryString = "width=$size&height=$size&keepAspectRatio=true") #end #set ($url = $profileDoc.getAttachmentURL($avatarAttachment.filename, 'download', $queryString)) #set ($specified = true) #end #end #set ($return = $NULL) #setVariable ("$return" {'url': $url, 'specified': $specified}) #end #macro(resizedUserAvatar $username $size) #if(!$picturelist) #set($picturelist = {}) #end #if(!$picturelist.containsKey("${username}--${size}")) #getUserAvatarURL($username $avatarURL $size) #if ($avatarURL.specified) #set ($picture = "<img src='") #set ($picture = $picture.concat($escapetool.xml($avatarURL.url))) #set ($picture = $picture.concat("' alt='")) #set ($picture = $picture.concat(${xwiki.getUserName($username, false)})) #set ($picture = $picture.concat("' title='")) #set ($picture = $picture.concat(${xwiki.getUserName($username, false)})) #set ($picture = $picture.concat("'/>")) #else #set ($picture = "<img class='avatar avatar_${escapetool.xml(${size})}' src='") #set ($picture = $picture.concat($avatarURL.url)) #set ($picture = $picture.concat("' alt='${xwiki.getUserName($username, false)}' title='${xwiki.getUserName($username, false)}'/>")) #end #set ($discard = $!picturelist.put("${username}--${size}", $picture)) #end $picturelist.get("${username}--${size}")## #end #macro(largeUserAvatar $username) #resizedUserAvatar($username 120) #end #macro(mediumUserAvatar $username) #resizedUserAvatar($username 50) #end #macro(smallUserAvatar $username) #resizedUserAvatar($username 30) #end ### ### useravatar ### ### Display the avatar of a user, or a standard image if the user has no avatar ### ### @param username The name of the user whose avatar will be displayed ### #macro(useravatar $username) #resizedUserAvatar($username 0) #end ### ### mimetypeimg ### ### Display an icon according to the mimetype ### ### @param mime The reported mimetype of the file ### @param fname The name of the file ### #macro(mimetypeimg $mime $fname) #set($idx = $fname.lastIndexOf('.')) #set($idx = $idx + 1) #if(($idx != 0) && ($idx != -1)) #set($ext = $fname.substring($idx)) #else #set($ext = '') #end ## Map mimetypes to their corresponding icons #if(!$mimetypeMap) #set($mimetypeMap = {}) ## images #set($discard = $mimetypeMap.put('image/svg+xml', ['vector', 'svg'])) #set($discard = $mimetypeMap.put('application/svg+xml', ['vector', 'svg'])) #set($discard = $mimetypeMap.put('image/svg', ['vector', 'svg'])) #set($discard = $mimetypeMap.put('image/svg+xml', ['vector', 'svg'])) #set($discard = $mimetypeMap.put('image/', ['image', 'image'])) ## text #set($discard = $mimetypeMap.put('text/html', ['file-code', 'html'])) #set($discard = $mimetypeMap.put('text/css', ['file-code', 'css'])) #set($discard = $mimetypeMap.put('text/', ['file-text', 'text'])) ## documents #set($discard = $mimetypeMap.put('application/xml', ['file-code', 'xml'])) #set($discard = $mimetypeMap.put('application/pdf', ['file-pdf', 'pdf'])) #set($discard = $mimetypeMap.put('application/postscript', ['file-pdf', 'ps'])) #set($discard = $mimetypeMap.put('application/msword', ['file-word', 'document'])) #set($discard = $mimetypeMap.put('application/powerpoint', ['file-powerpoint', 'presentation'])) #set($discard = $mimetypeMap.put('application/vnd.ms-powerpoint', ['file-powerpoint', 'presentation'])) #set($discard = $mimetypeMap.put('application/vnd.oasis.opendocument', ['file', 'office'])) #set($discard = $mimetypeMap.put('application/x-shockwave-flash', ['film', 'flash'])) ## archives #set($discard = $mimetypeMap.put('application/x-tar', ['file-archive', 'tar'])) #set($discard = $mimetypeMap.put('application/x-gzip', ['file-archive', 'gz'])) #set($discard = $mimetypeMap.put('application/x-gtar', ['file-archive', 'gz'])) #set($discard = $mimetypeMap.put('application/zip', ['file-archive', 'zip'])) #set($discard = $mimetypeMap.put('application/java-archive', ['coffee', 'jar'])) #set($discard = $mimetypeMap.put('audio/', ['music', 'audio'])) #set($discard = $mimetypeMap.put('video/', ['film', 'video'])) #end #if(!$extensionMap) ## Map extensions to their corresponding icons #set($extensionMap = {}) ## media #set($discard = $extensionMap.put('ogg', ['music', 'audio'])) #set($discard = $extensionMap.put('flac', ['music', 'audio'])) #set($discard = $extensionMap.put('ogv', ['film', 'video'])) #set($discard = $extensionMap.put('mk', ['film', 'video'])) #set($discard = $extensionMap.put('avi', ['film', 'video'])) #set($discard = $extensionMap.put('divx', ['film', 'video'])) #set($discard = $extensionMap.put('mov', ['film', 'video'])) #set($discard = $extensionMap.put('flv', ['film', 'flash'])) #set($discard = $extensionMap.put('fla', ['film', 'flash'])) #set($discard = $extensionMap.put('swf', ['film', 'flash'])) ## office #set($discard = $extensionMap.put('ppt', ['file-powerpoint', 'presentation'])) #set($discard = $extensionMap.put('odp', ['file-powerpoint', 'presentation'])) #set($discard = $extensionMap.put('doc', ['file-word', 'document'])) #set($discard = $extensionMap.put('odf', ['file', 'document'])) #set($discard = $extensionMap.put('ods', ['file-excel', 'spreadsheet'])) #set($discard = $extensionMap.put('xls', ['file-excel', 'spreadsheet'])) #set($discard = $extensionMap.put('odt', ['file-word', 'odt'])) #set($discard = $extensionMap.put('sxw', ['file-word', 'office'])) #set($discard = $extensionMap.put('stw', ['file-word', 'office'])) ## archives #set($discard = $extensionMap.put('bz', ['file-archive', 'bz'])) #set($discard = $extensionMap.put('bz2', ['file-archive', 'bz'])) #set($discard = $extensionMap.put('tbz', ['file-archive', 'bz'])) #set($discard = $extensionMap.put('gz', ['file-archive', 'gz'])) #set($discard = $extensionMap.put('tgz', ['file-archive', 'gz'])) #set($discard = $extensionMap.put('rar', ['file-archive', 'rar'])) #set($discard = $extensionMap.put('7z', ['file-archive', 'zip'])) ## development #set($discard = $extensionMap.put('sql', ['database', 'sql'])) #set($discard = $extensionMap.put('php', ['file-code', 'php'])) #set($discard = $extensionMap.put('c', ['file-code', 'c'])) #set($discard = $extensionMap.put('cpp', ['file-code', 'cpp'])) #set($discard = $extensionMap.put('c++', ['file-code', 'cpp'])) #set($discard = $extensionMap.put('cs', ['file-code', 'cs'])) #set($discard = $extensionMap.put('h', ['file-code', 'h'])) #set($discard = $extensionMap.put('ruby', ['file-code', 'ruby'])) #set($discard = $extensionMap.put('java', ['coffee', 'java'])) #set($discard = $extensionMap.put('js', ['file-code', 'js'])) #set($discard = $extensionMap.put('csproj', ['file-code', 'vs'])) #set($discard = $extensionMap.put('sln', ['file-code', 'vs'])) #set($discard = $extensionMap.put('res', ['file-code', 'vs'])) ## data #set($discard = $extensionMap.put('ics', ['calendar', 'calendar'])) #set($discard = $extensionMap.put('eml', ['email', 'email'])) #set($discard = $extensionMap.put('vcf', ['vcard', 'vcard'])) #set($discard = $extensionMap.put('vcard', ['vcard', 'vcard'])) ## executables #set($discard = $extensionMap.put('exe', ['cog', 'exe'])) #set($discard = $extensionMap.put('bat', ['terminal', 'script'])) #set($discard = $extensionMap.put('sh', ['terminal', 'script'])) #end #if($mimetypeMap.containsKey($mime)) #set ($image = $mimetypeMap.get($mime).get(0)) #set ($text = $mimetypeMap.get($mime).get(1)) #elseif ($extensionMap.containsKey($ext)) #set ($image = $extensionMap.get($ext).get(0)) #set ($text = $extensionMap.get($ext).get(1)) #else #set ($mimetypePrefix = $mime.indexOf('/')) #set ($mimetypePrefix = $mimetypePrefix + 1) #set ($mimetypePrefix = $mime.substring(0, $mimetypePrefix)) #if ($mimetypeMap.containsKey($mimetypePrefix)) #set ($image = $mimetypeMap.get($mimetypePrefix).get(0)) #set ($text = $mimetypeMap.get($mimetypePrefix).get(1)) #else #set ($image = 'attach') #set ($text = 'attachment') #end #end <span title="${services.localization.render("core.viewers.attachments.mime.${text}")}">$!services.icon.renderHTML($image)</span> #end ### ### packName ### ### Display a shorter version of a string ### ### @param name The processed string ### #macro(packName $name) #if(!$maxnamelength) #set($maxnamelength = 25) #end #set($idx = $name.lastIndexOf(".")) #if(($idx != 0) && ($idx != -1)) #set($ext = $name.substring($idx)) #else #set($ext = "") #set($idx = $name.length()) #end #set($fname = $name.substring(0, $idx)) #if($fname.length() > $maxnamelength)$fname.substring(0, $maxnamelength)~$ext#else$name#end #end #macro(xwikiobjectfield $fielddoc $fieldname $fieldtext $action) <div class="xmblabel">$fieldtext</div> <div class="xmbfield"> #if($fieldname!="") $fielddoc.display($fieldname, $action) #end </div> #end ## ## Formats a date according to the ISO8601 standard ## #macro(formatdateISO $date) #set($tz = $xwiki.formatDate($date, "Z")) #set($tz = "${tz.substring(0, 3)}:${tz.substring(3)}") $xwiki.formatDate($date, "yyyy-MM-dd")T$xwiki.formatDate($date, "HH:mm:ss")$tz#end ## ## Formats a username like a fn (hCard microformat) ## #macro(userfn $username) #set($fn = $xwiki.getUserName($username)) #if($fn.indexOf("<a") >= 0) #set($fn = $fn.replaceAll("<a", '<a class="url fn"')) #else #set($fn = "<span class='fn'>$fn</span>") #end $fn #end ### ### ### Macros for "foot notes" ### ### TODO: ### Make Radeox macros ### Support in wysiwyg ### ### #macro(footnote $text) #if(!$page_footnotes) #set($page_footnotes = []) #set($footnote_group_id = 1) #end #set($discard = $page_footnotes.add($text)) #set($processedText = $text.replaceAll('[*~<>_-]', '')) #set($footnote_id = $page_footnotes.size()) <sup class="footnoteRef" id="footnoteref_${footnote_group_id}_${footnote_id}"><a href="#footnote_${footnote_group_id}_${footnote_id}" title="$services.localization.render('core.footnotes.gotofootnote', [${footnote_id}]): {pre}$processedText{/pre}">$footnote_id</a></sup>#end ## ## ## #macro(putFootnotes) #if($page_footnotes && ($page_footnotes.size() > 0)) <ol class="footnotes"> #foreach($footnote in $page_footnotes) <li id="footnote_${footnote_group_id}_${velocityCount}"> <a class="footnoteBackRef" title="$services.localization.render('core.footnotes.backtoref')" href="#footnoteref_${footnote_group_id}_${velocityCount}">^</a> $footnote</li> #end </ol> #set($discard = $page_footnotes.clear()) #set($footnote_group_id = $footnote_group_id + 1) #end #end ## ## Generate navigation links for paged documents. It will use the URL parameters "ipp" to forward ## the number of items per page, and "page" to indicate a certain page. The actual range (in items, ## not in pages) can be computer using #preparePagedViewParams. The macro does not print anything ## if only one page exists and $alwaysDisplay is not set to true. Does not alter any variables. ## ## @param itemsPerPage The number of items per page, will be forwarded in the links to other pages. ## @param totalPages The total number of pages, starting at 1. ## @param currentPageNumber The currently displayed page, starting at 1. ## @param additionalQueryParams Query string fragment that should be put in the links. Should not ## start or end with ? or & ## @param alwaysDisplay Force display of the links, even if there is only one page in total. ## #macro(printPagedViewLinks $itemsPerPage $totalPages $currentPageNumber $additionalQueryParams $alwaysDisplay) ## Only display if there are more than 1 pages or we explicitely require it. #if(($totalPages > 1) || $alwaysDisplay) <div class="pagedNavigation"> #if($currentPageNumber > 1) #set($currentPageNumber = $currentPageNumber - 1) <span class="pagedLink"><a href="$doc.getURL($xcontext.action, "page=1&ipp=${itemsPerPage}")#if("$!additionalQueryParams" != "")&$additionalQueryParams#end">$services.localization.render('web.paging.firstPage')</a></span> <span class="pagedLink"><a href="$doc.getURL($xcontext.action, "page=${currentPageNumber}&ipp=${itemsPerPage}")#if("$!additionalQueryParams" != "")&$additionalQueryParams#end">$services.localization.render('web.paging.previousPage')</a></span> #set($currentPageNumber = $currentPageNumber + 1) #else <span class="pagedLink inactive">$services.localization.render('web.paging.firstPage')</span> <span class="pagedLink inactive">$services.localization.render('web.paging.previousPage')</span> #end <span class="pagedStatus">$services.localization.render('web.paging.pageNumberOf', [$currentPageNumber, $totalPages])</span> #if($currentPageNumber < $totalPages) #set($currentPageNumber = $currentPageNumber + 1) <span class="pagedLink"><a href="$doc.getURL($xcontext.action, "page=${currentPageNumber}&ipp=${itemsPerPage}")#if("$!additionalQueryParams" != "")&$additionalQueryParams#end">$services.localization.render('web.paging.nextPage')</a></span> <span class="pagedLink"><a href="$doc.getURL($xcontext.action, "page=${totalPages}&ipp=${itemsPerPage}")#if("$!additionalQueryParams" != "")&$additionalQueryParams#end">$services.localization.render('web.paging.lastPage')</a></span> #set($currentPageNumber = $currentPageNumber - 1) #else <span class="pagedLink inactive">$services.localization.render('web.paging.nextPage')</span> <span class="pagedLink inactive">$services.localization.render('web.paging.lastPage')</span> #end </div> #end #end ## ## ## Used together with #printPagedViewLinks, computes the range of items to show and the ## variables used by #printPagedViewLinks, $currentPageNumber, $itemsPerPage, $totalPages. ## ## @param totalItems The total number of items that need to be displayed. ## @param defaultItemsPerPage The default number of items per page, if no override is found in the ## URL. If 0, then display all items. ## @sets startAt The first item to display (inclusive). ## @sets endAt The last item to display (exclusive). ## @sets itemsPerPage The requested number of items per page. ## @sets totalPages The total number of pages according to the requested number of items per page ## and total items. Starts at 1. ## @sets currentPageNumber The current page displayed. If the requested page is not available (out ## of range), then it will be corrected to a valid number. Starts at 1. ## #macro(preparePagedViewParams $totalItems $defaultItemsPerPage) ## Reuse existing variable, in case it is manually overriden somewhere else #if(!$itemsPerPage) #if($request.ipp) #set($itemsPerPage = $mathtool.toInteger($request.ipp)) #else #set($itemsPerPage = $defaultItemsPerPage) #end #end ## Page numbers start at 1 outside this macro, but for internal computations we use 0-indexed values. #set($currentPageNumber = $mathtool.toInteger($request.page) - 1) #if(!$currentPageNumber || $currentPageNumber < 0) #set($currentPageNumber = 0) #end ## The first item to show. Must be >= 0. #set($startAt = $itemsPerPage * $currentPageNumber) #if($startAt < 0) #set($startAt = 0) #end ## The last item to show (exclusive). Must be <= total number of items. #set($endAt = $itemsPerPage * ($currentPageNumber + 1)) #if(($endAt > $totalItems) || ($itemsPerPage == 0)) #set($endAt = $totalItems) #end ## Never show the items after the last one... They don't exist! #if($startAt >= $endAt) #set($startAt = $endAt - 1) #end ## Compute the total number of pages. #if($itemsPerPage == 0) #set($totalPages = 1) #else #set($totalPages = ($totalItems - 1) / $itemsPerPage + 1) #end ## The requested page might not be available, so correct it to correspond to the displayed items. #set($currentPageNumber = $startAt / $itemsPerPage + 1) #end ## ## ## Macro to set a page break used in print, pdf and rtf mode ## #macro(pagebreak) <p style="page-break-before: always;" /> #end ## ## ## Macro to include children of a page ## #set($clevel = 1) #** * Macro to include children at multiple levels. The children are rendered in the generated output. The number of nested levels to * render is defined in a global variable called "$clevel". * * @param $page the document whose children should be rendered; preferably a Document object, but a document name works as well * @param $withPageBreaks a boolean indicating whether a page break should be generated before each new child document *### #macro(includeChildren $page $withPageBreaks) #if ($clevel && $clevel > 0) #if ("$!page.fullName" == '') ## Not a Document, probably a String (document name) ## Make it backwards compatible with older versions of the macro #set ($page = $xwiki.getDocument($page)) #end #foreach ($childDocName in $page.children) #set ($childDoc = $xwiki.getDocument($childDocName)) #if ($childDoc && !$blacklistedSpaces.contains($childDoc.getSpace())) #if ($withPageBreaks) #pagebreak() #end $childDoc.getRenderedContent() #set ($clevel = $clevel - 1) #includeChildren($childDoc $withPageBreaks) #set ($clevel = $clevel + 1) #end #end #end #end ## ## Macro to include linked pages at multiple levels #macro(includeLinks $page $withPageBreaks) #if($clevel && $clevel!=0) #set($pageDoc = $xwiki.getDocument($page)) #foreach($child in $pageDoc.getLinks()) #set($childDocName = $child.getLink()) #set($childDoc = $xwiki.getDocument($childDocName)) #if(($childDoc)&&($childDoc.getSpace()!="Panels")&&($childDoc.getSpace()!="XWiki")) #if($withPageBreaks) #pagebreak() #end $childDoc.getRenderedContent() #set($clevel = $xwiki.add($clevel,-1)) #includeLinks($childDocName $withPageBreaks) #set($clevel = $xwiki.add($clevel,1)) #end #end #end #end ### ### Panel header ### ### Generate the starting html code for a panel ### ### @param title The panel caption title ### @param isLarge True if the panel should be larger (default: false) ### @param isHeaderHidden True if the header should be hidden (default: false) ### #macro(panelheader $title $isLarge $isHeaderHidden) ## Note: We pass the Panel name as an HTML class attribute so that it's possible to style the Panels selectively using ## CSS. ## We want to avoid showing the "WebHome" suffix in the generated class since we're working to remove it from the UI ## and from the APIs. In addition it generates class names longer than they are needed. Thus for nested pages we strip ## it. We also strip the wiki prefix to have a shorter generated class name and because they're not needed to provide ## per-wiki styling of Panels. #set ($defaultDocumentName = $services.model.getEntityReference('DOCUMENT', 'default').name) #if ($paneldoc.documentReference.name == $defaultDocumentName) #set ($serializedDocument = $services.model.serialize($paneldoc.documentReference.parent, 'compactwiki')) #else #set ($serializedDocument = $services.model.serialize($paneldoc.documentReference, 'compactwiki')) #end ## We keep only alphanumeric characters so it can be used as a CSS class. ## For instance: "xwiki:A.B.WebHome" will become "AB" #set ($specialClassAttribute = $stringtool.toAlphaNumeric("$!serializedDocument")) ## We keep this class for compatibility purpose but the previous one should be used instead. #set ($deprecatedClassAttribute = $stringtool.toAlphaNumeric("$!paneldoc.documentReference.name")) #if ($paneldoc.syntax.toIdString() == 'xwiki/1.0') <div class="#if ($isLarge)large #{end}panel expanded $!specialClassAttribute $!deprecatedClassAttribute"> <h1 class="xwikipaneltitle#if ($isHeaderHidden) hidden#end">$title</h1> <div class="xwikipanelcontents"> #else (% class="#if ($isLarge)large#{end}panel expanded $!specialClassAttribute $!deprecatedClassAttribute" %)((( {{html}}<h1 class="xwikipaneltitle#if ($isHeaderHidden) hidden#end">$title</h1>{{/html}} (% class="xwikipanelcontents" %)((( #end #end #macro(panelhiddenheader $title) #panelheader($title, false, true) #end #macro(largepanelheader $title) #panelheader($title, true, false) #end ### ### Panel footer ### ### Generate the ending html code for a panel ### #macro(panelfooter) #if ($paneldoc.syntax.toIdString() == 'xwiki/1.0') </div> </div> #else ))) ))) #end #end ### ### Display Panel ### ### Extract and display the panel code from the panel object ### ### @Deprecated #macro(displaypanel $name) #set ($paneldoc = $xwiki.getDocument($name)) #if ($paneldoc) #set ($pobj = $paneldoc.getObject('Panels.PanelClass')) #if ($pobj) $!doc.display('content', 'view', $pobj) #end #end #end #macro(displayPropName $prop) #if($services.localization.render("${class.getName()}_${prop.name}") == "${class.getName()}_${prop.name}") $prop.prettyName#else $services.localization.render($prop.name)#end #end ### ### Display Panel content ### ### #macro(displaypanelcontent $doc $obj) $doc.display("content", $obj) #end ### ### Message box ### #macro(xwikimessageboxstart $title $message) <div class="centered"> <fieldset class="xwikimessage"> <legend><span>$title</span></legend> <p class="xwikimessage">$message</p> #end #macro(xwikimessageboxend) </fieldset> </div> #end #macro(xwikimessagebox $title $message $urlyes $urlno $msgyes $msgno) #xwikimessageboxstart($title $message) <div class="buttons"><a href="$urlyes" class="buttonwrapper"><input type="button" class="button" value="$msgyes" onclick="location='$urlyes'; return false;"/></a><a href="$urlno" class="buttonwrapper"><input type="button" class="button" value="$msgno" onclick="location='$urlno'; return false;"/></a></div> #xwikimessageboxend() #end #macro(xwikimessageboxfield $fielddoc $fieldname $fieldtext $html) <div class="xmblabel">$fieldtext</div> <div class="xmbfield"> #if($fieldname!="") $fielddoc.display($fieldname, "edit") #end #if($html!="") $html #end </div> #end #macro(xwikimessageboxsubmit $submittext) <div class="xmbbutton"> <input type="submit" value="$submittext" /> </div> #end ### ### message ### #macro(warning $text) <div class="warningmessage"><span class="messagetype">$services.localization.render('warning'): </span>$text</div> #end #macro(error $text) <div class="errormessage"><span class="messagetype">$services.localization.render('error'): </span>$text</div> #end #macro(info $text) <div class="infomessage">$text</div> #end #macro(message $text) <div class="plainmessage">$text</div> #end #macro (floatingbox $text) <div class="floatinginfobox">$text</div> #end #macro (startfloatingbox) <div class="floatinginfobox"> #end #macro (endfloatingbox) </div> #end ### ### Display in page panels layout ### ### #macro(displayPanelLayout $nbcolumns $panelNameList) <div class="panellayoutcontainer-${nbcolumns}col"> #set($lastColumnId = ($nbcolumns - 1)) #foreach($colId in [0..$lastColumnId]) <div class="panellayoutcol"> #foreach($panelName in $panelNameList) #if($panelName && ($panelName != "") && (((($velocityCount - 1) + $nbcolumns) % $nbcolumns) == $colId)) #displaypanel($panelName) #end #end </div> #end </div> #end #** * Displays a public google calendar with all buttons and displays * The size of the display is 800x600 * * This macro displays the public part of the calendar specified. However if the visiting user is logged in in Google Calendar and has rights to the private part of the calendar then the information will be displayed. * * @param id ID of the google account to display the calendar for *# #macro(googlecal $id) {pre} <iframe src="http://www.google.com/calendar/embed?height=600&wkst=1&bgcolor=%23FFFFFF&src=${id.replaceAll("@","%40")}&color=%232952A3" style=" border-width:0 " width="800" height="600" frameborder="0" scrolling="no"></iframe> {/pre} #end #** * Displays a public google calendar with all buttons and displays and a custom size * * @param id ID of the google account to display the calendar for * @param width Width of the calendar * @param height Height of the calendar *# #macro(googlecalsize $id $width $height) #if($width=="") #set($width = "800") #end #if($height=="") #set($height = "600") #end {pre} <iframe src="http://www.google.com/calendar/embed?height=${height}&wkst=1&bgcolor=%23FFFFFF&src=${id.replaceAll("@","%40")}&color=%232952A3" style=" border-width:0 " width="${width}" height="${height}" frameborder="0" scrolling="no"></iframe> {/pre} #end #** * Displays a private google calendar with all buttons * * @param id ID of the google account to display the calendar for * @param token Private token giving access to the Calendar. This token is 32 chars long and can be retrieved in the "Agenda Details" when accessing your "Private URL" of your calendar. You should use this parameter with care as it will display all your calendar events to anybody that can access the page in which you use this macro *# #macro(googlecalprivate $id $token) {pre} <iframe src="http://www.google.com/calendar/embed?pvttk=${token}&height=600&wkst=1&bgcolor=%23FFFFFF&src=${id.replaceAll("@","%40")}&color=%232952A3" style=" border-width:0 " width="800" height="600" frameborder="0" scrolling="no"></iframe> {/pre} #end #** * Displays a private google calendar with all buttons * * @param id ID of the google account to display the calendar for * @param token Private token giving access to the Calendar. This token is 32 chars long and can be retrieved in the "Agenda Details" when accessing your "Private URL" of your calendar. You should use this parameter with care as it will display all your calendar events to anybody that can access the page in which you use this macro * @param width Width of the calendar * @param height Height of the calendar *# #macro(googlecalprivatesize $id $token $width $height) #if($width=="") #set($width = "800") #end #if($height=="") #set($height = "600") #end {pre} <iframe src="http://www.google.com/calendar/embed?pvttk=${token}&height=${height}&wkst=1&bgcolor=%23FFFFFF&src=${id.replaceAll("@","%40")}&color=%232952A3" style=" border-width:0 " width="${width}" height="${height}" frameborder="0" scrolling="no"></iframe> {/pre} #end #** * Displays a public or private google calendar with a wide range of settings * You can check the effect of these settings using the Google Calendar Embed Helper * http://www.google.com/calendar/embedhelper * * @param id ID of the google account to display the calendar for * @param token Private token giving access to the Calendar. This token is 32 chars long and can be retrieved in the "Agenda Details" when accessing your "Private URL" of your calendar. You should use this parameter with care as it will display all your calendar events to anybody that can access the page in which you use this macro * @param width Width of the calendar * @param height Height of the calendar * @param showTitle 0 to not show the title * @param showNav 0 to not show the navigation buttons allowing to switch to previous/next week or month * @param showDate 0 to not show the current period displayed * @param showPrint 0 to not show the print button * @param showTabs 0 to not show the tabs allowing to switch between MONTH,WEEK,AGENDA mode * @param showCalendars 0 to not show the calendars list drop down button * @param showTz Show a message saying the timezone of the dates/hours * @param mode Default mode to display (empty is Month display, WEEK is Week dispaly, AGENDA is the event display) * @param language Language to display in (en,fr,de,..) * @param bgcolor Background color of the calendar in the form #255455 * @param color Color of the events in the form #234567 * @param ctz Timezone in which to display the calendar. Leave empty for default calendar Timezone * @param border Border in pixels (1,2,3) *# #macro(googlecalcustom $id $token $width $height $showTitle $showNav $showDate $showPrint $showTabs $showCalendars $showTz $mode $language $bgcolor $color $ctz $border) #if($width=="") #set($width = "800") #end #if($height=="") #set($height = "600") #end #if($color!="") #set($color = $color.replaceAll("#","%23")) #else #set($color = "%232952A3") #end #if($bgcolor!="") #set($bgcolor = $bgcolor.replaceAll("#","%23")) #else #set($bgcolor = "%232952A3") #end {pre} <iframe src="//www.google.com/calendar/embed?showTitle=${showTitle}&showNav=${showNav}&showDate=${showDate}&showPrint=${showPrint}&showTabs=${showTabs}&showCalendars=${showCalendars}&showTz=${showTz}&mode=${mode}&height=${height}&wkst=2&hl=${language}&bgcolor=${bgcolor}&src=${id.replaceAll("@","%40")}&color=${color}&ctz=${ctz}" style=" border:solid ${border}px #777 " width="${width}" height="${height}" frameborder="0" scrolling="no"></iframe> {/pre} #end #** * Displays a list of documents. * Only documents that the current user is allowed to view will be displayed. * * @param docNames list of document names. * @param displaySpaces true to group documents by space. * @param blacklistedSpaces spaces to exclude from the list. *# #macro(displayDocumentList $docNames $displaySpaces $blacklistedSpaces) #set($documentList = []) #foreach($docName in $docNames) #if($xwiki.hasAccessLevel("view", $xcontext.user, $docName)) #set($document = $xwiki.getDocument($docName).getTranslatedDocument()) #if(!$blacklistedSpaces.contains($document.getSpace())) #set($discard = $documentList.add($document)) #end #end #end #if($documentList.size() > 0) #set($previousSpace = "") <ul class="xlist"> #foreach($document in $documentList) #if ($document.getSpace() != $previousSpace && $displaySpaces) #if($velocityCount > 1) </ul></div></li> #end ## Close previous space item if needed <li class="xitem space"><div class="xitemcontainer">${escapetool.xml($document.getSpace())}<ul class="xlist"> ## Open new space item #set($previousSpace = $document.getSpace()) #end <li class="xitem page"><div class="xitemcontainer"><a href="$document.getURL()">${escapetool.xml($document.getPlainTitle())}</a></div></li> #end #if($displaySpaces) </ul></div></li> ## Close last space item #end </ul> #end #end #** * Set a variable from request parameters. * If the parameter is not present in the request, set it to the default value. * * Note that request parameters will be cast to the type of the defaultValue. * Handled types: ArrayList, Boolean, Integer, Float, Long, Double. * * @param variable the variable to set. * @param parameterName name of the parameter to look for in the request. * @param defaultValue if the parameter is not set in the HTTP request, the variable is assigned this value. * @deprecated since Velocity 1.7 (XWiki 3.0) it is no longer possible to use macros this way. * Setting $variable will not be observed outside the macro unless the actual parameter is also called $variable. * Use #readVariableFromRequest instead. *### #macro(setVariableFromRequest $variable $parameterName $defaultValue) ## Trick: when null, "$variable" will print the actual parameter name, so "$abc" if the macro was called with $abc as a parameter. ## Use this hack to extract the actual parameter name, and use #evaluate to set it. #set ($variable = $NULL) #set ($varName = "$variable") #readVariableFromRequest($varName $parameterName $defaultValue) #end ## ## ## #** * Set a variable from request parameters. * If the parameter is not present in the request, set it to the default value. * * Note that request parameters will be cast to the type of the defaultValue. * Handled types: ArrayList, Boolean, Integer, Float, Long, Double. * * @param resultVariableName the name of the variable to set, a String; when the macro returns, a variable named that way will be created with the output value * @param parameterName name of the parameter to look for in the request. * @param defaultValue if the parameter is not set in the HTTP request, the variable is assigned this value. *### #macro(readVariableFromRequest $resultVariableName $parameterName $defaultValue) ## Try to get the variable value from HTTP request. #if ($defaultValue.class == 'class java.util.ArrayList') #set ($result = []) #foreach ($param in $request.getParameterValues($parameterName)) #set ($discard = $result.add($param)) #end #if ($result.size() == 0) #set ($discard = $result.addAll($defaultValue)) #end #else #set ($result = $request.getParameter("${parameterName}")) #if ("$!result" != '') #if ($defaultValue.class == 'class java.lang.Boolean') #set ($result = $util.parseBoolean($result)) #elseif ($defaultValue.class == 'class java.lang.Integer') #set ($result = $mathtool.toInteger($result)) #elseif ($defaultValue.class == 'class java.lang.Float') #set ($result = $mathtool.toNumber($result).floatValue()) #elseif ($defaultValue.class == 'class java.lang.Long') #set ($result = $mathtool.toNumber($result).longValue()) #elseif ($defaultValue.class == 'class java.lang.Double') #set ($result = $mathtool.toDouble($result)) #end #end #if ("$!result" == '') #set ($result = $defaultValue) #end #end #setVariable($resultVariableName $result) #end ## ## ## #** * Assign a value to a variable, given by its name. The purpose of this macro is to emulate call by macro expansion, * which was available in velocity versions up to 1.6, but was removed in 1.7. * * @param variableName the name of the variable to set, a String; when the macro returns, a variable named that way will be created with the output value * @param value the value to assign *### #macro(setVariable $variableName $value) ## Only do this if the variable name is really a valid variable name #if ($variableName.matches('[a-zA-Z_][a-zA-Z0-9_-]*')) #evaluate("${escapetool.h}set(${escapetool.d}${variableName}=${escapetool.d}value)") #elseif ($variableName.matches('\$[a-zA-Z_][a-zA-Z0-9_-]*')) #evaluate("${escapetool.h}set(${variableName}=${escapetool.d}value)") #end #end ## ## ## #** * Displays a submit button, i.e. an <tt>input</tt> element with <tt>type=submit</tt>. * For styling purposes, the button is wrapped in a span element. * @param name The value of the <tt>name</tt> attribute * @param shortcut The keyboard shortcut for this button. The value will be displayed * as the title of the element. The actual shortcut is attached elsewhere, in * the javascript code. * @param value The value of the <tt>value</tt> attribute, i.e. the text displayed on * the button. *# #macro(submitButton $name $shortcut $value) <span class="buttonwrapper"><input class="button" type="submit" name="$name"#if($keyboardShortcutsEnabled) title="$shortcut"#end value="$value"/></span> #end #** * Displays a submit button for the editor. This macro calls submitButton, * composing all its parameters based on the action's identifier and the * identifier of the corresponding localized resources. * @param action The identifier of the button's action. * @param resourceIdentifier The key used to identify the localized resources. *# #macro(editActionButton $action $resourceIdentifier) #submitButton("action_${action}", $services.localization.render("core.shortcuts.edit.${resourceIdentifier}"), $services.localization.render($resourceIdentifier)) #end #** * Display a human-readable file size * * @param $size the size in bytes to display in a human readable format *# #macro(dynamicsize $sz) #if($sz < 1024) $sz bytes## #else #set($ksz = $mathtool.div($sz, 1024)) #set($ksz = $mathtool.roundTo(1, $ksz)) #if($ksz < 1024) $ksz KB## #else #set($Msz = $mathtool.div($sz, 1048576)) #set($Msz = $mathtool.roundTo(1, $Msz)) $Msz MB## #end## #end## #end #** * AJAX Live table that displays XWiki data. * * Example of usage, in syntax 2.0: * <code> * {{velocity}} * #set($columns = [ "_avatar", "first_name", "last_name", "email"]) * #set($columnsProperties = { * "first_name" : { "type" : "text" , "size" : 10, "link" : "view"}, * "last_name" : { "type" : "text" , "size" : 10, "link" : "view"}, * "email" : { "type" : "text" , "size" : 20, "link" : "editor"}, * "_avatar" : { "type" : "none" , "size" : 20, "link" : "none", "html" : "true", "sortable":false } * }) * #set($options = { "className":"XWiki.XWikiUsers", * "translationPrefix" : "platform.index.", * "tagCloud" : true, * "rowCount": 15, * "javascriptName" : "MyModule.myTable", * "description: "The description of this table here", }) * #livetable("userstable" $columns $columnsProperties $options) * {{/velocity}} * </code> * * @param divid the id of the table div * @param collist the column list * @param colprops the columns properties * @param options the livetable options. *# #macro(livetable $divid $collist $colprops $options) ## Open wiki syntax wrappers. #if("$!options.outputOnlyHtml" != 'true') ## Do not indent: #if($xwiki.getCurrentContentSyntaxId() != "xwiki/1.0") ## We don't clean the HTML because we control the markup and because we want to preserve the whitespace characters in the ## attribute values (e.g. if the live table id contains whitespaces) {{html clean="false"}} #else {pre} #end #end ## ## SX deps. ## #set($ok = $xwiki.jsfx.use('js/xwiki/table/livetable.js', true)) #set($ok = $xwiki.ssfx.use('js/xwiki/table/livetable.css', true)) ## ## Options / defaults ## #if("$!options.translationPrefix" != '') #set($transprefix = $options.translationPrefix) #else #set($transprefix = '') #end #if("$!options.defaultOrder" == 'desc') #set($defaultOrder = 'desc') #else #set($defaultOrder = 'asc') #end #if("$!options.rowCount" != '') #set($count = $options.rowCount) #else #set($count = 15) #end #if("$!options.maxPages" != '') #set($maxPages = $options.maxPages) #else #set($maxPages = 10) #end #if("$!options.selectedColumn" != '') #set($selectedColumn = $options.selectedColumn) #end #if("$!options.callback" != '') #set($callback = $options.callback) #else #set($callback = '') #end #if("$!options.tagCloud" == '' || $options.tagCloud == false) #set($tagcloud=false) #else #set($tagcloud = true) #end #if ($options.selectedTags && $options.selectedTags.size() > 0) #set ($selectedTags = $options.selectedTags) #else #set ($selectedTags = []) #end #if("$!options.javascriptName" != '') #set($jsName = $options.javascriptName) #else #set($jsName = "livetable_$divid") #end #set ($topfilters = $options.topFilters) #if("$options.pageSize" == '' || $!options.pageSize == false) #set($hasPageSize=false) #else #set($hasPageSize = true) #end #if("$!options.pageSizeBounds" != '') #set($pageSizeBounds = $options.pageSizeBounds) #end #set ($queryFilters = $options.queryFilters) #if (!$queryFilters) #set ($queryFilters = 'currentlanguage,hidden') #end #set($classname = "$!options.className") ## ## Columns informations ## #set ($dataColumns = []) #set ($classParams = {}) #foreach($colname in $collist) ## If the live table options don't specify which column to select then select the first non-special column. #if("$!selectedColumn" == '' && !$colname.startsWith('_')) #set($selectedColumn = $colname) #end #if($colname != '_actions') #set ($discard = $dataColumns.add($colname)) #set($propClassName = "$!{colprops.get($colname).get('class')}") #if($propClassName != '') #set ($discard = $classParams.put("${colname}_class", $propClassName)) #end #set ($propMatchType = "$!colprops.get($colname).match") #if ($propMatchType != '') #set ($discard = $classParams.put("${colname}_match", $propMatchType)) #end #end #end #if("$!options.url" != '') #set($dataurl = $options.url) #else #set ($parameters = { 'outputSyntax': 'plain', 'transprefix': $transprefix, 'classname': $classname, 'collist': $stringtool.join($dataColumns, ','), 'queryFilters': $queryFilters }) #set ($discard = $parameters.putAll($classParams)) #set ($resultPage = $options.resultPage) #if ("$!resultPage" == '') #set ($resultPage = 'XWiki.LiveTableResults') #end #set ($dataurl = $xwiki.getURL($resultPage, 'get', "$escapetool.url($parameters)&$!options.extraParams")) #end ## ## HTML Table ## #set ($htmlLiveTableId = $escapetool.xml($divid)) <div class="xwiki-livetable-container"> #if("$!topfilters" !='') #set($hasTopFilters = true) #else #set($hasTopFilters = false) #end #if($tagcloud || $hasTopFilters) <div class="tipfilters"> #end #if($hasTopFilters) <div id="${htmlLiveTableId}-topfilters" class="xwiki-livetable-topfilters-tip #if($tagcloud)splitted#end"> <div> <div class="xwiki-livetable-topfilters-container"> $topfilters </div> <div class="tippointer"> <div></div> </div> </div> </div> #end #if($tagcloud) #set($discard = $xwiki.ssx.use('XWiki.TagCloud')) <div id="${htmlLiveTableId}-tagcloud" class="xwiki-livetable-tagcloud-tip hidden #if($hasTopFilters)splitted#end"> <div> <div class="xwiki-livetable-tagcloud-container"> <h2>$services.localization.render('platform.livetable.tagsHelp') $services.localization.render('platform.livetable.tagsHelpCancel')</h2> <div class="xwiki-livetable-tagcloud"></div> </div> <div class="tippointer"> <div></div> </div> </div> </div> #end #if($tagcloud || $hasTopFilters) </div> #end <table id="${htmlLiveTableId}" class="xwiki-livetable"#if("$!options.description" != '') summary="$options.description"#end> <tr> <td class="xwiki-livetable-pagination"> <span id="${htmlLiveTableId}-limits" class="xwiki-livetable-limits"></span> #if($hasPageSize) <span id="${htmlLiveTableId}-pagesize" class="xwiki-livetable-pagesize"> <span>$services.localization.render('platform.livetable.pagesizeLabel')</span> <span class="xwiki-livetable-pagesize-content" ></span> </span> #end <span id="${htmlLiveTableId}-ajax-loader" class="xwiki-livetable-loader hidden"> <img src="$xwiki.getSkinFile('icons/xwiki/ajax-loader-large.gif')" alt="$escapetool.xml($services.localization.render('platform.livetable.loading'))" title="" /> </span> <span class="controlPagination"> <a title="$escapetool.xml($services.localization.render('platform.livetable.paginationPagePrevTitle'))" class="prevPagination" href="#"><span class="hidden">$services.localization.render('platform.livetable.paginationPagePrevTitle')</span></a> <a title="$escapetool.xml($services.localization.render('platform.livetable.paginationPageNextTitle'))" class="nextPagination" href="#"><span class="hidden">$services.localization.render('platform.livetable.paginationPageNextTitle')</span></a> </span> <span class="pagination"> <span class="xwiki-livetable-pagination-text">$services.localization.render('platform.livetable.paginationPage')</span> <span class="xwiki-livetable-pagination-content" ></span> </span> </td> </tr> <tr> <td class="xwiki-livetable-display-container"> <table class="xwiki-livetable-display"> <thead class="xwiki-livetable-display-header"> <tr> #set($columnCount = 0) #foreach($colname in $collist) #set($colprop = $colprops.get($colname)) #set ($isFilterable = $colprop.filterable != false && $colname != '_actions' && $colprop.type != 'hidden') #set ($isSortable = $colprop.sortable != false && $colname != '_actions' && $colprop.type != 'hidden') ## Get the column's display name to use in the header. #set($displayName = "#getLivetableColumnDisplayName($colname, $colprop, $transprefix)") #set ($defaultHeaderClass = {'_actions': 'actions', '_avatar': 'avatar'}) #set ($discard = $colprop.putIfAbsent('headerClass', $defaultHeaderClass.get($colname))) <th scope="col" class="xwiki-livetable-display-header-text $!colprop.headerClass #if ($!colprop.type == 'hidden')hidden#end #if ($isSortable)sortable #if ($colname == $selectedColumn)selected $defaultOrder#else asc#end#end"> #if($isSortable)<a rel="${colname}">#end #if($isFilterable)<label for="xwiki-livetable-${htmlLiveTableId}-filter-${velocityCount}">#end $displayName #if($isFilterable)</label>#end #if($isSortable)</a>#end #set($columnCount = $mathtool.add($columnCount, 1)) </th> #end </tr> #livetable_filters($collist $colprops $classname) <tr class="xwiki-livetable-initial-message"> <td colspan="${columnCount}"> <div class="warningmessage">$services.localization.render('platform.livetable.environmentCannotLoadTableMessage')</div> </td> </tr> </thead> <tbody id="${htmlLiveTableId}-display" class="xwiki-livetable-display-body"><tr><td> </td></tr></tbody> </table> </td> </tr> <tr> <td class="xwiki-livetable-pagination"> <span class="xwiki-livetable-limits"></span> <span class="controlPagination"> <a title="$escapetool.xml($services.localization.render('platform.livetable.paginationPagePrevTitle'))" class="prevPagination" href="#"><span class="hidden">$services.localization.render('platform.livetable.paginationPagePrevTitle')</span></a> <a title="$escapetool.xml($services.localization.render('platform.livetable.paginationPageNextTitle'))" class="nextPagination" href="#"><span class="hidden">$services.localization.render('platform.livetable.paginationPageNextTitle')</span></a> </span> <span class="pagination"> <span class="xwiki-livetable-pagination-text">$services.localization.render('platform.livetable.paginationPage')</span> <span class="xwiki-livetable-pagination-content" ></span> </span> </td> </tr> </table> <div id="${htmlLiveTableId}-inaccessible-docs" class="hidden"> #info($services.localization.render('rightsmanager.documentrequireviewrights')) </div> <div id="${htmlLiveTableId}-computed-title-docs" class="hidden"> #info("(<span class='docTitleComputed'></span>) $services.localization.render('platform.livetable.docTitleComputedHint')") </div> <script type="text/javascript"> //<![CDATA[ (function() { var startup = function(container) { // Make sure the LiveTable code is loaded (the WYSIWYG editor doesn't load the JavaScript code for instance). var liveTableCodeLoaded = XWiki && XWiki.widgets && XWiki.widgets.LiveTable; // Also make sure the live table is not already initialized. #set ($jsLiveTableId = $escapetool.javascript($divid)) var liveTableElement = $('$jsLiveTableId'); if (liveTableCodeLoaded && liveTableElement && !liveTableElement.__liveTable && (liveTableElement == container || liveTableElement.descendantOf(container))) { #set ($liveTableParams = { 'maxPages': $maxPages, 'limit': $count, 'selectedTags': $selectedTags }) #if ($hasTopFilters) #set ($cssLiveTableId = $escapetool.css($divid)) #set ($discard = $liveTableParams.put('filterNodes', [ "$escapetool.h$cssLiveTableId .xwiki-livetable-display-filters", "${jsLiveTableId}-topfilters" ])) #end #if ($hasPageSize && "$!pageSizeBounds" != '') #set ($discard = $liveTableParams.put('pageSizeBounds', $pageSizeBounds)) #end #set ($callbackParam = "#livetablecallback($divid $collist $colprops $transprefix), ") #if ($!callback != '') #set ($callbackParam = "$callback, ") #end window[$jsontool.serialize($jsName)] = liveTableElement.__liveTable = new XWiki.widgets.LiveTable("$dataurl", "$jsLiveTableId", $callbackParam$jsontool.serialize($liveTableParams)); #if ($hasPageSize) document.observe("xwiki:livetable:${jsLiveTableId}:loadingEntries", function() { $('${jsLiveTableId}-pagesize').addClassName("hidden"); }); document.observe("xwiki:livetable:${jsLiveTableId}:loadingComplete", function() { $('${jsLiveTableId}-pagesize').removeClassName("hidden"); }); #end return true; } return false; }; var init = function(event) { var elements = (event && event.memo.elements) || [$('body')]; return elements.length > 0 && elements.some(startup); }; // Initialize the live table on page load or after the live table code has been loaded. (XWiki && XWiki.isInitialized && init()) || document.observe('xwiki:livetable:loading', init); // Initialize the live table when it is added after the page is loaded. document.observe('xwiki:dom:updated', init); })(); //]]> </script> </div>## xwiki-livetable-container ## Close wiki syntax wrappers. Do not modify the indentation below or it will generate unwanted paragraphs! #if("$!options.outputOnlyHtml" != 'true')#if($xwiki.getCurrentContentSyntaxId() != "xwiki/1.0"){{/html}} #else{/pre}#end## #end## end-wrappers #end## end-livetable-macro #macro (livetable_filters $columns $columnsProperties $xclassName) <tr class="xwiki-livetable-display-filters"> #foreach ($column in $columns) #set ($columnProperties = $columnsProperties.get($column)) #if ($columnProperties.type != 'hidden') <td class="xwiki-livetable-display-header-filter"> #if ($columnProperties.filterable != false && "$!column" != '_actions') #set ($columnXClassName = $columnProperties.get('class')) #set ($columnXPropertyName = $column) #if (!$columnXClassName) #if ($column.startsWith('doc.')) #set ($columnXClassName = 'XWiki.DocumentClass') #set ($columnXPropertyName = $column.substring(4)) #else #set ($columnXClassName = $xclassName) #end #end #set ($xclass = $xwiki.getDocument($columnXClassName).getxWikiClass()) #set ($xproperty = $xclass.get($columnXPropertyName)) #livetable_filter($column $columnProperties $xproperty) #end </td> #end #end </tr> #end #macro (livetable_filter $column $columnProperties $xproperty) #set ($filterType = $columnProperties.type) #if ("$!filterType" == '') ## Determine the filter type from the xproperty type. #set ($filterTypeByXPropertyType = { 'Boolean': 'boolean', 'DBList': 'suggest', 'DBTreeList': 'suggest', 'Date': 'date', 'Email': 'text', 'Groups': 'suggest', 'Number': 'number', 'Page': 'suggest', 'StaticList': 'list', 'String': 'text', 'TextArea': 'text', 'Users': 'suggest' }) #set ($filterType = $filterTypeByXPropertyType.get($xproperty.classType)) #if ("$!filterType" == '') ## If we get here then it means the column is filterable but we could not determine the filter type. Use the text ## filter in this case because it is the most generic. #set ($filterType = 'text') #end #end #set($escapedTitle = $escapetool.xml($services.localization.render('platform.livetable.filtersTitle', [$services.localization.render("${transprefix}$column")]))) #if ($filterType == 'list' || $filterType == 'multilist') <select id="xwiki-livetable-${htmlLiveTableId}-filter-$velocityCount" name="$column" #if ($filterType == 'multilist') class="xwiki-livetable-multilist" multiple="multiple"> #else ><option value="">$services.localization.render('platform.livetable.selectAll')</option> <option disabled="disabled">────</option> #end #set ($storedValues = $xproperty.listValues) #set ($displayedValues = $xproperty.mapValues) #foreach ($storedValue in $storedValues) #set ($l10nKey = "${xproperty.className}_${column}_$storedValue") #set ($displayedValue = $services.localization.render($l10nKey)) #if ($displayedValue == $l10nKey) #set ($displayedValue = $displayedValues.get($storedValue).value) #end <option value="$storedValue">$displayedValue</option> #end </select> #elseif ($filterType == 'boolean') <select id="xwiki-livetable-${htmlLiveTableId}-filter-$velocityCount" name="$column"> <option value="">$services.localization.render('platform.livetable.selectAll')</option> <option value="0">$services.localization.render('no')</option> <option value="1">$services.localization.render('yes')</option> </select> #elseif ($filterType == 'text' || $filterType == 'number') <input id="xwiki-livetable-${htmlLiveTableId}-filter-$velocityCount" name="$column" type="text" #if ("$!columnProperties.size" != '')size="$!escapetool.xml($columnProperties.size)"#end title="$escapedTitle"/> #elseif ($filterType == 'suggest' && $xproperty) #set ($discard = $xwiki.linkx.use($services.webjars.url('selectize.js', 'css/selectize.css'), {'type': 'text/css', 'rel': 'stylesheet'})) #set ($discard = $xwiki.ssfx.use('uicomponents/suggest/xwiki.selectize.css', true)) #set ($discard = $xwiki.jsfx.use('uicomponents/suggest/suggestPropertyValues.js', {'forceSkinAction' : true, 'language' : $xcontext.locale})) <select id="xwiki-livetable-${htmlLiveTableId}-filter-$velocityCount" name="$!escapetool.xml($column)" class="suggest-propertyValues" multiple="multiple" size="1" data-className="$!escapetool.xml($xproperty.className)" data-propertyName="$!escapetool.xml($xproperty.name)" title="$escapedTitle"> </select> #end #end #** * Internal macro - Determine the name to be displayed in a livetable's column header. Strategy is as follows : * - If defined, the 'displayName' passed as a column option wins. * - If not, and if a i18n prefix has been passed, we use the localization tool with the prefix + the column name. * - Finally, we fall back on the column name. * * @param colname the column name * @param colprop the column properties map * @param transprefix the translations prefix to use * * @internal *# ## #macro(getLivetableColumnDisplayName $colname $colprop $transprefix) #if("$!colprop.displayName" != '') #set($displayName = $colprop.displayName)## #elseif($transprefix != '') #set($displayName = $services.localization.render("${transprefix}${colname}"))## #else #set($displayName = $colname)## #end $displayName## #end #** * Internal macro - Used by the livetable macro to generate a JavaScript anonymous function * that is passed to the LiveTable object constructor. This is function is dynamically written * according to columns properties passed to the livetable macro. * * @param collist the list of columns * @param colprops the columns properties * @param transprefix the translation prefix * * @internal *# #macro(livetablecallback $divid $collist $colprops $transprefix) function (row, i, table) { // This callback method has been generated from Velocity. ## Clone the column properties because we modify them. #set ($columnDescriptors = $jsontool.fromString($jsontool.serialize($colprops))) #livetable_normalizeColumnDescriptors($columnDescriptors $collist $transprefix) var columns = $jsontool.serialize($collist); var columnDescriptors = $jsontool.serialize($columnDescriptors); var className = $jsontool.serialize($classname); var showFilterNote = false; if (!row['doc_viewable']) { $($jsontool.serialize("${divid}-inaccessible-docs")).removeClassName('hidden'); } #if ($collist.contains('doc.title')) #set($titleOpts = $columnDescriptors['doc.title']) #if ("$!{titleOpts}" == "" || ($titleOpts['filterable'] == $NULL || $titleOpts['filterable'] == true) || ($titleOpts['sortable'] == $NULL || $titleOpts['sortable'] == true)) showFilterNote = true; if (row['doc_title_raw'] !== undefined) { $($jsontool.serialize("${divid}-computed-title-docs")).removeClassName('hidden'); } #end #end ## NOTE: Don't use Velocity code below this line! var tr = new Element('tr'); columns.forEach(function(column) { var descriptor = columnDescriptors[column] || {}; if (descriptor.type === 'hidden') { return; } // The column's display name to be used when displaying the reponsive version. var displayName = descriptor.displayName || column; var fieldName = column.replace(/^doc\./, 'doc_'); if (column === '_actions') { var adminActions = ['admin', 'rename', 'rights']; var td = new Element('td', { 'class': 'actions', 'data-title': displayName }); td.toggleClassName('hide-labels', descriptor.labels === false); (descriptor.actions || []).forEach(function(action, index) { if (row['doc_has' + action.id] || action.id === 'view' || (row['doc_has' + action.id] === undefined && (row['doc_hasadmin'] || adminActions.indexOf(action.id) < 0))) { var link = new Element('a', { 'href': row['doc_' + action.id + '_url'], 'class': 'action action' + action.id }).update('<span class="action-icon"></span><span class="action-label"></span>'); link.down('.action-icon').update(action.icon).writeAttribute('title', action.label); link.down('.action-label').update(action.label.escapeHTML()); if (action.async) { link.observe('click', function(event) { event.stop(); new Ajax.Request(this.href, { onSuccess: function() { eval(action.callback); } }); }.bindAsEventListener(link)); } td.insert(link); } }); tr.appendChild(td); } else { var td = new Element('td', { 'class': [ fieldName, 'link' + (descriptor.link || ''), 'type' + (descriptor.type || '') ].join(' '), 'data-title': displayName }); var container = td; if (descriptor.link && row['doc_viewable']) { var link = new Element(descriptor.link === 'editor' ? 'span' : 'a'); // Automatic: the link URL is in JSON results, with the '_url' sufix. if (descriptor.link === 'auto') { link.href = row[fieldName + '_url'] || row['doc_url']; } else if (descriptor.link === 'field') { if (row[fieldName + '_url']) { link.href = row[fieldName + '_url']; } // Property editor } else if (descriptor.link === 'editor') { var propertyClassName = descriptor['class'] || className; td.observe('click', function(event) { var tag = event.element().down('span') || event.element(); editProperty(row['doc_fullName'], propertyClassName, column, function(value) { tag.innerHTML = value; }); }); // Author, space or wiki link. } else if (row['doc_' + descriptor.link + '_url']) { link.href = row['doc_' + descriptor.link + '_url']; } else { link.href = row['doc_url']; } td.appendChild(link); container = link; } // The value can be passed as a string.. if (descriptor.html + '' === 'true') { container.innerHTML = row[fieldName] || ''; } else if (row[fieldName] !== undefined && row[fieldName] !== null) { var text = row[fieldName] + ''; if (fieldName === 'doc_name' && !row['doc_viewable']) { text += '*'; } if (showFilterNote && fieldName === 'doc_title' && row['doc_title_raw'] !== undefined) { container.addClassName('docTitleComputed'); } container.update(text.escapeHTML()); } tr.appendChild(td); } }); return tr; } #end #macro (livetable_normalizeColumnDescriptors $columnDescriptors $colList $transPrefix) ## Make sure the columns containing HTML are formatted in HTML indeed #set ($htmlColumnKeys = ['doc.location']) #foreach($htmlColumnKey in $htmlColumnKeys) #if ($colList.contains($htmlColumnKey)) #set ($htmlColumnProps = $columnDescriptors[$htmlColumnKey]) #if (!$htmlColumnProps) #set ($htmlColumnProps = {}) #set ($columnDescriptors[$htmlColumnKey] = $htmlColumnProps) #end #if ($htmlColumnProps.html == $NULL) #set ($htmlColumnProps.html = true) #end #end #end ## Translate the column descriptor. #foreach ($entry in $columnDescriptors.entrySet()) #if ("$!entry.value.displayName" == '' && "$!transPrefix" != '') #set ($entry.value.displayName = $services.localization.render("${transPrefix}$entry.key")) #end #end #livetable_normalizeActionsDescriptor($columnDescriptors $transPrefix) #end #macro (livetable_normalizeActionsDescriptor $columnDescriptors $transPrefix) #set ($actionsDescriptor = $columnDescriptors.get('_actions')) #if ($actionsDescriptor) #foreach ($action in $actionsDescriptor.actions) ## If the action is specified as a string then only the action id is specified. #if ($action.equals("$!action")) ## Note that 'labels' and 'actionCallbacks' are deprecated. #set ($action = { 'id': $action, 'label': $actionsDescriptor.labels.get($action), 'async': $actionsDescriptor.ajaxActions.get($action), 'callback': $actionsDescriptor.actionCallbacks.get($action) }) #set ($discard = $actionsDescriptor.actions.set($foreach.index, $action)) #end #if ("$!action.label" == '') #if ("$!transPrefix" != '' && $services.localization.get("${transPrefix}_actions.$action.id")) #set ($action.label = $services.localization.render("${transPrefix}_actions.$action.id")) #elseif ($services.localization.get("platform.livetable._actions.$action.id")) #set ($action.label = $services.localization.render("platform.livetable._actions.$action.id")) #else #set ($action.label = $action.id) #end #end #if ("$!action.icon" == '') #set ($defaultActionIcons = { 'rename': 'move', 'delete': 'cross', 'restore': 'refresh', 'undelete': 'refresh', 'rights': 'lock', 'edit': 'pencil' }) #set ($action.icon = $defaultActionIcons.getOrDefault($action.id, $action.id)) #end #set ($action.icon = "$!services.icon.renderHTML($action.icon)") #end #end #end #** * Modifies the passed where clause of the query (and its parameters) to add a "location" filter. * * @param whereQL existing where clause to augment * @param whereParams existing query params to augment * @param filterWebHome if true then treat "WebHome" as a normal input string like any other (defaults to false) * @param customWhereQL if defined then use that query instead of computing it ourselves. In this case the filterWebHome * parameter value is ignored * @internal *# #macro(addLivetableLocationFilter $whereQL $whereParams $locationValue $filterWebHome $customWhereQL) #if ("$!locationValue" != '') ## Location is a special case, that we need to handle separatly. ## It is actually not a real field, but a special request on doc.fullName, more user-friendly. #set ($locationFilterValue = $locationValue) ## Note: the "_", "[", and the "%" characters have special meanings in standard SQL servers (they behave as ## wildcards). However, it is not what the user expects (e.g. https://jira.xwiki.org/browse/XWIKI-12608). ## As a consequence, we must escape these characters. ## See http://www.jguru.com/faq/view.jsp?EID=8881 to understand why we use the special clause 'escape' above. ## Since we use '!' for the escaping, we also double existing ones. #set ($locationFilterValue = $locationFilterValue.replaceAll('([\[%_!])', '!$1')) ## Because the user might filter with "/" as separator we replace that by "%", because it could be "." ## (the space separator) or "/" (as it is in the document name). ## In addition, using "%" (any sequence of character) instead of "_" (any single character) gives the ability ## to filter on different levels: ## e.g. filtering on "Blog/Intro" will return "Blog.BlogIntroduction". #set ($locationFilterValue = $locationFilterValue.replaceAll('/', '%.%')) #if ("$!customWhereQL" != '') #set ($internalWhereQL = "${whereQL} $customWhereQL") #else #if ($whereParams.entrySet()) #set ($discard = $whereParams.put('locationFilterValue', "%${locationFilterValue}%")) #else #set ($discard = $whereParams.add("%${locationFilterValue}%")) #end #if ($filterWebHome == true) #if ($whereParams.entrySet()) #set ($matchNestedDocument = "(doc.name = 'WebHome' AND LOWER(doc.space) LIKE LOWER(:locationFilterValue) ESCAPE '!')") #set ($matchTerminalDocument = "(doc.name <> 'WebHome' AND LOWER(doc.fullName) LIKE LOWER(:locationFilterValue) ESCAPE '!')") #set ($internalWhereQL = "${whereQL} AND ($matchNestedDocument OR $matchTerminalDocument)") #else #set ($matchNestedDocument = "(doc.name = 'WebHome' AND LOWER(doc.space) LIKE LOWER(?) ESCAPE '!')") #set ($matchTerminalDocument = "(doc.name <> 'WebHome' AND LOWER(doc.fullName) LIKE LOWER(?) ESCAPE '!')") #set ($internalWhereQL = "${whereQL} AND ($matchNestedDocument OR $matchTerminalDocument)") #set ($discard = $whereParams.add("%${locationFilterValue}%")) #end #else #if ($whereParams.entrySet()) #set ($internalWhereQL = "${whereQL} AND LOWER(doc.fullName) LIKE LOWER(:locationFilterValue) ESCAPE '!'") #else #set ($internalWhereQL = "${whereQL} AND LOWER(doc.fullName) LIKE LOWER(?) ESCAPE '!'") #end #end #end #set ($whereQL = $NULL) #setVariable("$whereQL", $internalWhereQL) #end #end ## ## #** * Modifies the passed where clause of the query (and its parameters) to add a "location" filter. * * @param whereQL existing where clause to augment * @param whereParams existing query params to augment * @param filterWebHome if true then treat "WebHome" as a normal input string like any other (defaults to false) * @param customWhereQL if defined then use that query instead of computing it ourselves. In this case the filterWebHome * parameter value is ignored * @internal * @since 11.6 *# #macro(addLocationFilter $whereQL $whereParams $locationValue $filterWebHome $customWhereQL) #if ("$!locationValue" != '') ## Location is a special case, that we need to handle separatly. ## It is actually not a real field, but a special request on doc.fullName, more user-friendly. #set ($locationFilterValue = $locationValue) ## Note: the "_", "[", and the "%" characters have special meanings in standard SQL servers (they behave as ## wildcards). However, it is not what the user expects (e.g. https://jira.xwiki.org/browse/XWIKI-12608). ## As a consequence, we must escape these characters. ## See http://www.jguru.com/faq/view.jsp?EID=8881 to understand why we use the special clause 'escape' above. ## Since we use '!' for the escaping, we also double existing ones. #set ($locationFilterValue = $locationFilterValue.replaceAll('([\[%_!])', '!$1')) ## Because the user might filter with "/" as separator we replace that by "%", because it could be "." ## (the space separator) or "/" (as it is in the document name). ## In addition, using "%" (any sequence of character) instead of "_" (any single character) gives the ability ## to filter on different levels: ## e.g. filtering on "Blog/Intro" will return "Blog.BlogIntroduction". #set ($locationFilterValue = $locationFilterValue.replaceAll('/', '%.%')) #if ("$!customWhereQL" != '') #set ($internalWhereQL = "${whereQL} $customWhereQL") #else #set ($discard = $whereParams.add("%${locationFilterValue}%")) #if ($filterWebHome == true) #set ($matchNestedDocument = "(doc.name = 'WebHome' AND LOWER(doc.space) LIKE LOWER(?${whereParams.size()}) ESCAPE '!')") #set ($matchTerminalDocument = "(doc.name <> 'WebHome' AND LOWER(doc.fullName) LIKE LOWER(?${whereParams.size()}) ESCAPE '!')") #set ($internalWhereQL = "${whereQL} AND ($matchNestedDocument OR $matchTerminalDocument)") #else #set ($internalWhereQL = "${whereQL} AND LOWER(doc.fullName) LIKE LOWER(?${whereParams.size()}) ESCAPE '!'") #end #end #set ($whereQL = $NULL) #setVariable("$whereQL", $internalWhereQL) #end #end ## ## #** * Pagination 2.0 * * Displays a generic pagination widget for browsing a collection of items. * The macro is responsible for displaying browsing links, and does not involve the actual display of the browsed items. * * @param parameters A map of parameters: * <dl> * <dt>url</dt> * <dd>The base url of the document displaying the collection.</dd> * <dd>Default: $doc.getURL('view')</dd> * <dt>totalItems</dt> * <dd>The total number number of items in the collection.</dd> * <dd>Default: none, this parameter is mandatory.</dd> * <dt>defaultItemsPerPage</dt> * <dd>The number of items per page. This value is overwritten by the request parameter "perPage", if it exists and * has a valid positive integer value.</dd> * <dd>Default: 20</dd> * <dt>position</dt> * <dd>The placement of the pagination widget. Supported values: "top", "bottom". The bottom widget only displays * pages, while the top widget also provides a information about the item range on the current page.</dd> * <dd>Default: top</dd> * <dt>itemParamName</dt> * <dd>The name of the request parameter for the index of the first displayed item.</dd> * <dd>Default: firstIndex</dd> * <dt>itemsPerPageParamName</dt> * <dd>The name of the request parameter for the number of items displayed on a page.</dd> * <dd>Default: perPage</dd> * <dt>noSx</dt> * <dd>Do not force to use the pagination Skin Extension</dd> * <dd>Default: false</dd> * <dt>hash</dt> * <dd>An optional URL hash to be appended to all pagination links generated by this macro.</dd> * <dd>Default: none</dd> * </dl> *# #macro(pagination $parameters) #if(!$parameters.noSx) $xwiki.ssfx.use('uicomponents/pagination/pagination.css', true)## #end #if("$!{parameters.url}" == '') #set($parameters.url = $doc.getURL('view')) #end #if(!$parameters.url.contains('?')) #set($parameters.url = "${parameters.url}?") #end #if($parameters.position != 'bottom') #set($parameters.position = 'top') #end #paginationPrepareParams($parameters) #paginationDisplay($parameters) #end #** * Pagination : request parameters preparation * * Used internally by the pagination macro. Retrieves pagination parameter values from the request: * "firstIndex" = the index of the first displayed item; "perPage" = number of items per page * * @see #pagination * @internal *# #macro(paginationPrepareParams $parameters) ## Setting some defaults #if("$!{parameters.itemParamName}" == '') #set($parameters.itemParamName = 'firstIndex') #end #if("$!{parameters.itemsPerPageParamName}" == '') #set($parameters.itemsPerPageParamName = 'perPage') #end ## Adding the hash sign to the hash parameter if it is not present already #if("$!{parameters.hash}" != '' && !$parameters.hash.startsWith($escapetool.H)) #set($parameters.hash = "${escapetool.H}${parameters.hash}") #end ## Get starting item number from request #set ($parameters.firstItem = "$!{request.get($parameters.itemParamName)}") #set ($parameters.firstItem = $mathtool.toInteger($parameters.firstItem)) #if (!$parameters.firstItem) #set ($parameters.firstItem = 0) #end ## Get number of items per page from request #if (!$parameters.defaultItemsPerPage || $mathtool.toInteger($parameters.defaultItemsPerPage) <= 0) #set ($parameters.defaultItemsPerPage = 20) #end #set ($parameters.itemsPerPage = "$!{request.get($parameters.itemsPerPageParamName)}") #set ($parameters.itemsPerPage = $mathtool.toInteger($parameters.itemsPerPage)) #if (!$parameters.itemsPerPage || $parameters.itemsPerPage <= 0) #set ($parameters.itemsPerPage = $parameters.defaultItemsPerPage) #end #end #** * Pagination : display the pagination widget after all parameters have been computed * * Used internally by the pagination macro. * * @see #pagination * @internal *# #macro(paginationDisplay $parameters) #set($parameters.pageCount = ($parameters.totalItems + $parameters.itemsPerPage - 1) / $parameters.itemsPerPage) #if($parameters.firstItem >= $parameters.totalItems) #set($parameters.firstItem = ($parameters.pageCount - 1) * $parameters.itemsPerPage) #elseif($parameters.firstItem < 0) #set($parameters.firstItem = 0) #end #set($parameters.crtPage = $parameters.firstItem / $parameters.itemsPerPage) ## Make firstItem a multiple of itemsPerPage #set($parameters.firstItem = $parameters.crtPage * $parameters.itemsPerPage) #set($parameters.lastPage = $parameters.pageCount - 1) <div class="paginationFilter"> #if($parameters.position == 'top') #paginationResultsRange($parameters) #end #if($parameters.totalItems > 0) #if($parameters.controlsAround == true) #paginationControlLeft($parameters) #paginationPages($parameters) #paginationControlRight($parameters) #else #paginationControl($parameters) #paginationPages($parameters) #end #end </div> #end #** * Pagination : display links for browsing pages * * Used internally by the pagination macro. * * @see #pagination * @internal *# #macro(paginationPages $parameters) ## $url $crtPage $itemsPerPage $lastPage $pageCount $itemParamName $itemsPerPageParamName) #set($contextLeft = 4) #set($contextRight = 4) #set($contextWidth = $contextLeft + 1 + $contextRight) #if($parameters.pageCount <= $contextWidth) #set($contextFirstPage = 0) #set($contextLastPage = $parameters.pageCount - 1) #else #set($contextFirstPage = $parameters.crtPage - $contextLeft) #set($contextLastPage = $parameters.crtPage + $contextRight) #if($contextFirstPage < 0) #set($contextFirstPage = 0) #end #if($contextLastPage >= $parameters.pageCount) #set($contextLastPage = $parameters.pageCount - 1) #end #if($contextLastPage < $contextWidth) #set($contextLastPage = $contextWidth - 1) #end #if($contextFirstPage > $parameters.pageCount - $contextWidth) #set($contextFirstPage = $parameters.pageCount - $contextWidth) #end #end <span class="pagination">$services.localization.render('platform.livetable.paginationPage') #if($contextFirstPage != 0) #paginationPageLink(0 $parameters) #end #if($contextFirstPage > 1) ... #end #foreach ($i in [$contextFirstPage .. $contextLastPage]) #paginationPageLink($i $parameters) #end #if($parameters.lastPage - $contextLastPage > 1) ... #end #if($contextLastPage != $parameters.lastPage) #paginationPageLink($parameters.lastPage $parameters) #end </span> #end #** * Pagination : display the link to a certain page (indicated by $pageNumber) * * Used internally by the pagination macro. * * @see #pagination * @internal *# #macro(paginationPageLink $pageNumber $parameters) #set($firstItem = $pageNumber * $parameters.itemsPerPage) #set($displayedPageNumber = $pageNumber + 1) #if($pageNumber == $parameters.crtPage) <span class="currentPage">$displayedPageNumber</span> #else <a href="${parameters.url}&${parameters.itemParamName}=${firstItem}#if($parameters.itemsPerPage != $parameters.defaultItemsPerPage)&${parameters.itemsPerPageParamName}=${parameters.itemsPerPage}#end$!{parameters.hash}" title="$services.localization.render('platform.livetable.paginationPageTitle', [$displayedPageNumber])">$displayedPageNumber</a> #end #end #** * Pagination : display prev / next links * * Used internally by the pagination macro. * * @see #pagination * @internal *# #macro(paginationControl $parameters) <span class="controlPagination"> #paginationControlLeft($parameters) #paginationControlRight($parameters) </span> #end #** * Pagination : display prev link * * Used internally by the pagination macro. * * @see #pagination * @internal *# #macro(paginationControlLeft $parameters) #if($parameters.crtPage > 0) #set($prevPage = $parameters.crtPage - 1) #set($firstItem = $prevPage * $parameters.itemsPerPage) <a href="${parameters.url}&${parameters.itemParamName}=${firstItem}#if($parameters.itemsPerPage != $parameters.defaultItemsPerPage)&${parameters.itemsPerPageParamName}=${parameters.itemsPerPage}#end$!{parameters.hash}" title="$services.localization.render('platform.livetable.paginationPagePrevTitle')" class="prevPagination">$services.localization.render('platform.livetable.paginationPagePrevious')</a> #else <span class="noPrevPagination"> </span> #end #end #** * Pagination : display next link * * Used internally by the pagination macro. * * @see #pagination * @internal *# #macro(paginationControlRight $parameters) #if($parameters.crtPage < $parameters.lastPage) #set($nextPage = $parameters.crtPage + 1) #set($firstItem = $nextPage * $parameters.itemsPerPage) <a href="${parameters.url}&${parameters.itemParamName}=${firstItem}#if($parameters.itemsPerPage != $parameters.defaultItemsPerPage)&${parameters.itemsPerPageParamName}=${parameters.itemsPerPage}#end$!{parameters.hash}" title="$services.localization.render('platform.livetable.paginationPageNextTitle')" class="nextPagination">$services.localization.render('platform.livetable.paginationPageNext')</a> #else <span class="noNextPagination"> </span> #end #end #** * Pagination : message informing the user which items are being displayed on the current page (Results i - j of N) * * Used internally by the pagination macro. * * @see #pagination * @internal *# #macro(paginationResultsRange $parameters) #set($from = $parameters.firstItem + 1) #set($to = $parameters.firstItem + $parameters.itemsPerPage) #if ($to > $parameters.totalItems) #set($to = $parameters.totalItems) #end <span class="resultsNo"> #if($parameters.totalItems == 0) <span class='currentResultsNo'>$services.localization.render('platform.livetable.paginationResultsNone')</span> #elseif($parameters.totalItems == 1) <span class='currentResultsNo'>$services.localization.render('platform.livetable.paginationResultsOne')</span> #elseif($from == $parameters.totalItems) $services.localization.render('platform.livetable.paginationResultsSingle', [$from, $parameters.totalItems]) #else $services.localization.render('platform.livetable.paginationResultsMany', [$from, $to, $parameters.totalItems]) #end </span> #end #** * Generates a vertical menu from an object describing the categories * * Expected format of the object: * menu = vector of items * item = map with the following fields: * 'id' : mandatory * 'name' : the text displayed for the corresponding menu item; * optional, defaults to * $services.localization.render("$!{translationPrefix}${item.id}") * 'url' : the "action" of the menu item; optional, defaults to # * 'cssClass' : a specific css class for the menu item for custom * styling; optional, defaults to '' * 'children' : vector of items, allowing to recursively define submenus * * @param $menu the menu object, in the format described above * @param $options a map of options, where the following entries are currently used: * 'translationPrefix' : the translation prefix added to the id of each * item, in order to generate the name; ignored for items whose * name is specified * 'crtItemId': identifier of the current menu item (for differential styling) * 'cssClass' : specific css class for this menu *# #macro(verticalNavigation $menu $options) (% class="vertical-menu $!{options.cssClass}" %)((( #foreach ($item in $menu) #verticalNavigationItem($item '*' $options) #end ))) #end #** * Generates a vertical menu item from an object (a map) * * Expected format: * item = map with the following fields: * 'id' : mandatory * 'name' : the text displayed for the corresponding menu item; * optional, defaults to * $services.localization.render("$!{translationPrefix}${item.id}") * 'url' : the "action" of the menu item; optional * 'cssClass' : a specific css class for the menu item for custom * styling; optional, defaults to '' * 'children' : vector of items, allowing to recursively define submenus * * @param $item the menu item object, in the format described above * @param $level the current level of the item, of the form '\*+'; the number of * stars indicates the depth of the item in the menu * @param $options a map of options, where the following entries are currently used: * 'translationPrefix' : the translation prefix added to the id of each * item, in order to generate the name; ignored for items whose * name is specified * 'crtItemId': identifier of the current menu item (for differential styling) *# #macro(verticalNavigationItem $item $level $options) #set ($class = "$!{item.cssClass}") #set ($hasChildren = ($item.children && $item.children.size() > 0)) #if ($hasChildren) #set ($class = "$class group") #end #if ($options.crtItemId == $item.id) #set ($class = "$class current") #if ($hasChildren) #set ($class = "$class current-group") #end #end #set ($class = $class.trim()) #set ($name = "$!{item.name}") #if ($name == '') #set ($name = $services.localization.render("$!{options.translationPrefix}${item.id}")) #end $level (% id="vertical-menu-${item.id}" class="${class}" %){{html}}<a #if ("$!{item.url}" != '')href="$item.url"#{end}>$name</a>{{/html}} #if ($hasChildren) #set ($children = []) #sortCollectionOfMapsByField($item.children, 'order', 99999, 'asc', $children) #foreach ($child in $children) #verticalNavigationItem($child $level.concat('*') $options) #end #end #end #** * Sort a collection containing maps by a field. * * * @param $collection - List - Collection to sort. * * @param $field - String - Name of the field of the map to sort on. * * @param $defaultValue - Any - The default value for the sort if one of the elements has a NULL field * * @param $order - String - Must be 'asc' for ascending, or 'desc' for descending * * @param $outList - List - The returns from this macro will be put in this list, passing the list as a parameter * a safety measure because macros can't return values. *# #macro (sortCollectionOfMapsByField $collection $field $defaultValue $order $outputList) ## If an alement has a null field, $sorttool.sort() won't return anything. ## To avoid this situation, we create a new list that contains the elements with a default field if it is missing #set ($newList = []) #foreach ($element in $collection) #if ("$!element.get($field)" == '') #set ($elementCopy = {}) #set ($discard = $elementCopy.putAll($element)) #set ($discard = $elementCopy.put($field, $defaultValue)) #set ($discard = $newList.add($elementCopy)) #else #set ($discard = $newList.add($element)) #end #end #set ($discard = $outputList.addAll($sorttool.sort($newList, "${field}:${order}"))) #end #** * Sets a gradient-based styling for CSS backgrounds * * * @param $icon the path to an additional icon image * @param $gradientData a map of gradients, where the following entries are currently used: * 'angle' : an angle of direction for the gradient * 'colors': a list of maps of color-stops for the gradient, where the following entries are currently used: * 'color' : color value * 'position' : stop position for the color (between 0% and 100% or a lenght) *# #macro (css3_backgroundIconAndLinearGradient $icon $gradientData) ## Older color themes don't have values defined for the gradients, so we'll use a simple background-color instead #set ($validColors = 0) #set ($validColor = '') #foreach ($colorEntry in $gradientData.colors) #if ("$!{colorEntry.color}" != '') #set ($validColors = $validColors + 1) #set ($validColor = $colorEntry.color) #end #end #if ($validColors <= 1) #if ("$!{icon}" != '') background-image: ${icon}; #end #if ("$!{validColor}" != '') background-color: ${validColor}; #end #break($macro) #end #set ($colors = '') #set ($position = '') #if ($gradientData.angle) #if ($stringtool.indexOfAny($gradientData.angle, 'top', 'right', 'bottom', 'left') != -1) #set ($position = "to $!{gradientData.angle}") #else #set ($position = "$!{gradientData.angle}") #end #elseif ($gradientData.to) #set ($position = "to $!{gradientData.to}") #end #foreach ($colorEntry in $gradientData.colors) #set ($colors = "$!{colors}, $!{colorEntry.color} $!{colorEntry.position}") #end #if ("$!{colors}" != '' && "$!{position}" == '') #set ($colors = $colors.substring(2)) #end background-image:#if ("$!{icon}" != '') $icon,#end linear-gradient($!{position}$!{colors}); #end ## ## ## #macro (css3_backgroundLinearGradient $gradientData) #css3_backgroundIconAndLinearGradient ('' $gradientData) #end #** * Macro that displays a gradient specific to IE browsers (IE6-IE9) * * @param $startColor initial color for a gradient, format #AARRGGBB, range from #FF000000 to #FFFFFFFF * @param $endColor final color for the gradient *# #macro (css_filterGradient $startColor $endColor) #if (("$!{startColor}" != '') && ("$!{endColor}" != '')) filter: progid:DXImageTransform.Microsoft.gradient( startColorstr=${startColor}, endColorstr=${endColor},GradientType=0 ); #end #end #** * Macro that adds the prefixes for box-sizing CSS property that alters the default CSS box model used to calculate widths and heights of elements * * * @param $value should take the following values: content-box | padding-box | border-box *# #macro (css3_boxSizing $value) #if ("$!{value}" != '') #set ($browserVariants = ['-moz-', '']) #foreach ($bvar in $browserVariants) ${bvar}box-sizing: $value; #end #end #end #** * Macro for text-shadow CSS property that adds shadows to text * * * @param $offsetX shadow's horizontal offset value from the text * @param $offsetY shadow's vertical offset value from the text * @param $blurRadius the blur radius value of the text-shadow * @param $color the color of the text-shadow *# #macro (css_textShadow $offsetX $offsetY $blurRadius $color) ## In order to ensure consistency across browsers and also to accommodate old ColorThemes that might not have gradientColor defined, we test the existence of $color param #if (("$!{offsetX}" != '') && ("$!{offsetY}" != '') && ("$!{color}" != '')) text-shadow: ${offsetX} ${offsetY} ${blurRadius} ${color}; #end #end #** * Transforms the given string to an XML name by filtering all the characters that are not allowed in an XML name. If * the given string contains only invalid characters then the result is the empty string. * * @param $string the string to be transformed to an XML name *# #macro(toXMLName $string) ## Keep only Unicode letters and digits plus the hyphen and the underscore characters. #set($string = $string.replaceAll('[^\p{L}\p{N}_\-]+', '')) ## Make sure the string doesn't start with a number or the hyphen character. #set($string = $string.replaceAll('^[\p{N}\-]+', '')) $string## #end #** * Pulls all the JavaScript and CSS resources needed by pickers. *# #macro (picker_import) #set ($discard = $xwiki.linkx.use($services.webjars.url('selectize.js', 'css/selectize.bootstrap3.css'), {'type': 'text/css', 'rel': 'stylesheet'})) #set ($discard = $xwiki.ssfx.use('uicomponents/suggest/xwiki.selectize.css', true)) #end #** * Pulls all the JavaScript and CSS resources needed by the user and group picker. *# #macro (userPicker_import) #picker_import #set ($discard = $xwiki.jsfx.use('uicomponents/suggest/suggestUsersAndGroups.js', {'forceSkinAction': true, 'language': $xcontext.locale})) #end #macro (userPicker_input $multiSelect $parameters) #if ($multiSelect) #set ($discard = $parameters.put('multiple', 'multiple')) #end #set ($discard = $parameters.putIfAbsent('data-userScope', "$!services.wiki.user.userScope")) #suggestInput($parameters) #end #macro (userPicker $multiSelect $parameters) #userPicker_import #set ($discard = $parameters.put('class', "$!parameters.get('class') suggest-users")) #userPicker_input($multiSelect $parameters) #end #macro (groupPicker $multiSelect $parameters) #userPicker_import #set ($discard = $parameters.put('class', "$!parameters.get('class') suggest-groups")) #userPicker_input($multiSelect $parameters) #end #** * Pulls all the JavaScript and CSS resources needed by the page picker. *# #macro (pagePicker_import) #picker_import #set ($discard = $xwiki.jsfx.use('uicomponents/suggest/suggestPages.js', {'forceSkinAction': true, 'language': $xcontext.locale})) #end #macro (pagePicker $parameters) #pagePicker_import #if ("$!parameters" == "") #set ($parameters = {}) #end #set ($discard = $parameters.put('class', "$!parameters.get('class') suggest-pages")) #suggestInput($parameters) #end #** * Pulls all the JavaScript and CSS resources needed by the attachment picker. *# #macro (attachmentPicker_import) #picker_import #set ($discard = $xwiki.jsfx.use('uicomponents/suggest/suggestAttachments.js', {'forceSkinAction': true, 'language': $xcontext.locale})) ## Pull the resources required by the configured icon set in order to display attachment icons. #set ($discard = $services.icon.use()) #end #macro (attachmentPicker $parameters) #attachmentPicker_import #if ("$!parameters" == "") #set ($parameters = {}) #end #set ($discard = $parameters.put('class', "$!parameters.get('class') suggest-attachments")) #suggestInput($parameters) #end #** * Displays the given title (i.e. the title of the sheet) if the condition is true. Otherwise displays the title of the * current document (i.e. the document the sheet is applied to). If the condition is not specified then it checks if the * current document is a sheet by looking for an object of type 'XWiki.SheetDescriptorClass'. You can pass a traslation * key for the sheet title. This macro makes sure the document title is not displayed recursively. * * @param $title the sheet title, you can pass a translation key * @param $condition optional condition, whether to display the sheet title or the document title *# #macro (sheetTitle $title $condition) ## NOTE: Don't format the code because spaces are preserved in document title. #if (!$condition && "$!condition" == '')## ## Undefined condition. Use the default condition. #set ($condition = $doc.getObject('XWiki.SheetDescriptorClass')) #elseif ($condition.getClass().getName() == 'java.lang.String')## ## The condition is the name of an xclass. Display the sheet title if the current document doesn't have such an object. #set ($condition = !$doc.getObject($condition)) #end## ## #if ($condition)## ## Display the sheet title. $services.localization.render($title)## ## #elseif (!$sheetTitle_displayingDocumentTitle)## ## Display the document title without going through the sheet and preventing recursion. #set ($sheetTitle_displayingDocumentTitle = true) $services.display.title($doc, { 'displayerHint': 'default', 'outputSyntaxId': 'plain/1.0' })## #set ($sheetTitle_displayingDocumentTitle = false) ## #else## Recursive title display detected!## #end## #end #** * Outputs the skin extension hooks, for both Stylesheet and JavaScript extensions. This is useful when the HTML response * of an AJAX request needs to pull some CSS and JavaScript resources. The code that makes the AJAX request should move * the 'includes' (i.e. the link and script tags) to the head of the HTML page after receiving the HTML response. *# #macro (skinExtensionHooks) #styleSheetExtensionHooks #javaScriptExtensionHooks #end #** * Hook for inserting CSS skin extensions. *# #macro (styleSheetExtensionHooks) ## - Skin JAR extension hook. Placed first to allow other skin extensions to override it. <!-- com.xpn.xwiki.plugin.skinx.CssResourceSkinExtensionPlugin --> ## - Skin file extension hook. <!-- com.xpn.xwiki.plugin.skinx.CssSkinFileExtensionPlugin --> ## - Skin extension hook, placed at the last to be able to override previous css rules with a Skin Extension Object <!-- com.xpn.xwiki.plugin.skinx.CssSkinExtensionPlugin --> #end #** * Hooks for inserting JavaScript skin extensions. *# #macro (javaScriptExtensionHooks) ## - Skin JAR extension hook. Placed first to allow other skin extensions to override it. <!-- com.xpn.xwiki.plugin.skinx.JsResourceSkinExtensionPlugin --> ## - Skin file extension hook. <!-- com.xpn.xwiki.plugin.skinx.JsSkinFileExtensionPlugin --> ## - Skin extension hook <!-- com.xpn.xwiki.plugin.skinx.JsSkinExtensionPlugin --> #end ### ### Displays an exception. ### ### @param title the message to display to the user ### @param exception the exception to display when the user clicks on the message #macro(displayException $title $exception) <div class="xwikirenderingerror" title="Click to get more details about the error" style="cursor: pointer;"> $title </div> <div class="xwikirenderingerrordescription hidden"> <pre>$escapetool.xml($exceptiontool.getStackTrace($exception))</pre> </div> #end ### ### Generically display exceptions that have not been handled at the right level and have now bubbled up to the UI. ### ### This is a convenience macro, see #displayException. ### ### @param exception The exception to format for displaying #macro(displayUnhandledException $exception) #set ($sentence1 = 'Unexpected error.') #set ($sentence2 = 'Contact your administrator or <a href="https://jira.xwiki.org">report the issue</a>.') #set ($sentence3 = 'Click this box to get technical details.') #displayException("${sentence1} ${sentence2} ${sentence3}", $exception) #end ### ### Display a rich select input (with icon, description, etc...) ### ### ### @param $fieldName name of the input field ### @param $options an array of maps describing a category of options, which contains an array of options ### @param $defaultValue the default value to use ### @param $firstIsDefaultIfDefaultNull if defaultValue is null, select the first option ### @param $cssClass class to add to the div (could be 'xwiki-select-small', 'xwiki-select-medium', 'xwiki-select-tall' or any other class) ### @param $id (optional) id to give to the widget ### @param $enableFilter (optional) enable the filtering of the options ### ### Example of use: ### ### #set($options = [ ### { ### 'name': 'Category 1', ### 'options': [ ### { 'name': 'Option 1', 'value': 'option1', 'description': 'Description of the option 1', 'icon': 'wiki', 'data': {'some-data': 'some-value'}}, ### { 'name': 'Option 2', 'value': 'option2', 'description': 'Description of the option 2', 'icon': 'page'} ### ] ### }, ### { ### 'name': 'Category 2', ### 'options': [ ### { 'name': 'Option 3', 'value': 'option3', 'description': 'Description of the option 3', 'icon': 'check'} ### ] ### } ### ]) ### #xwikiSelect('nameOfTheField', $options, 'option1', false, 'xwiki-select-small', '', true) ######################################################### #macro(xwikiSelect $fieldName $options $defaultValue $firstIsDefaultIfDefaultNull $cssClass $id $enableFilter $filterPlaceHolder) ## TODO: put this in a webjar instead #set ($discard = $xwiki.ssfx.use('uicomponents/widgets/select/select.css', {'forceSkinAction': true})) #set ($discard = $xwiki.jsfx.use('uicomponents/widgets/select/select.js' , {'forceSkinAction': true})) <div class="xwiki-select $!cssClass" #if("$!id" != '')id="$id"#end> ## Here we let a place to add a filter in the future, that is why the options are inside the following div block. <p><input type="text" class="xwiki-select-filter" placeholder="$escapetool.xml($services.localization.render('web.widgets.select.filter.placeholder'))"/></p> <div class="xwiki-select-options"> <ul> #set ($count = 0) #foreach ($category in $options) <li class="xwiki-select-category">$category.name (<span class="xwiki-select-category-count">$category.options.size()</span>) <ul> #foreach ($option in $category.options) #if ("$!defaultValue" == $$option.value || ($count == 0 && $firstIsDefaultIfDefaultNull && "$!defaultValue" == '')) #set ($checked = 'checked="checked"') #set ($class = 'xwiki-select-option-selected') #else #set ($checked = '') #set ($class = '') #end #set ($otherData = '') #foreach($data in $option.data.keySet()) #set ($otherData = "$otherData data-${escapetool.xml($data)} = '$escapetool.xml($option.data.get($data))'") #end <li class="xwiki-select-option $class"> <input type="radio" name="$fieldName" value="$escapetool.xml($option.value)" id="${fieldName}_${count}" $checked $otherData/> <span class="xwiki-select-option-icon">$!services.icon.renderHTML($option.icon)</span> <div> <label for="${fieldName}_${count}">$escapetool.xml($option.name)</label> #if ("$!option.description" != '') <p class="xHint">$escapetool.xml($option.description)</p> #end </div> </li> #set ($count = $count + 1) #end </ul> </li> #end </ul> </div> </div> #end #** * Used by custom property displayers that need a generic suggest input. *# #macro (xpropertySuggestInputDisplayer $field $prefix $name $value) #set ($discard = $xwiki.jsfx.use('uicomponents/suggest/suggestPropertyValues.js', {'forceSkinAction': true, 'language': $xcontext.locale})) #set ($id = "${prefix}${name}") #set ($freeText = $!field.getValue('freeText')) #set ($parameters = { 'id': $id, 'name': $id, 'value': $value, 'class': 'suggest-propertyValues', 'data-className': $field.className, 'data-propertyName': $name }) #if ("$!freeText" != '') #set ($discard = $parameters.put('data-freeText', $freeText)) #end #if ($field.getProperty('disabled').value == 1) #set ($parameters.disabled = 'disabled') #end #if ($field.getProperty('multiSelect').value == 1) #set ($parameters.multiple = 'multiple') #set ($separators = $field.getProperty('separators').value) #if ("$!separators" != '') #set ($parameters.separators = $separators) #end #end #suggestInput($parameters) #end #** * Utility macro to output a generic suggest input. * * @param $parameters the parameters (most of them are treated as HTML attributes) *# #macro (suggestInput $parameters $optionsDisplayerMacroName) #set ($discard = $xwiki.linkx.use($services.webjars.url('selectize.js', 'css/selectize.bootstrap3.css'), {'type': 'text/css', 'rel': 'stylesheet'})) #set ($discard = $xwiki.ssfx.use('uicomponents/suggest/xwiki.selectize.css', true)) #set ($discard = $parameters.put('size', 1)) #set ($attributes = []) ## Note: Remove placeholder since it's not valid to have it on an HTML SELECT element. #set ($nonAttributes = ['value', 'separators', 'placeholder']) #foreach ($entry in $parameters.entrySet()) #if (!$nonAttributes.contains($entry.key)) #if ($entry.value.equals($entry.value.toString())) #set ($stringValue = $entry.value) #else ## Serialize non-string values as JSON. #set ($stringValue = $jsontool.serialize($entry.value)) #end #set ($discard = $attributes.add("$escapetool.xml($entry.key)='$!escapetool.xml($stringValue)'")) #end #end #if ("$!parameters.value.size()" != '') #set ($values = $parameters.value) #elseif ($parameters.multiple) #set ($values = $stringtool.split($parameters.value, $parameters.getOrDefault('separators', '|,'))) #elseif ("$!parameters.value" != '') #set ($values = [$parameters.value]) #else #set ($values = []) #end <select $stringtool.join($attributes, ' ')> #if ("$!parameters.placeholder" != '') <option value="">$escapetool.xml($parameters.placeholder)</option> #end #if ("$!optionsDisplayerMacroName" != '') #evaluate("${escapetool.h}${optionsDisplayerMacroName}(${escapetool.d}values)") #else #foreach ($selectedValue in $values) <option value="$!escapetool.xml($selectedValue)" selected="selected">$!escapetool.xml($selectedValue)</option> #end #end </select> #if ($parameters.multiple) ## We need a hidden input with an empty value to be able to clear the selected values when no value is selected. <input type="hidden" name="$!escapetool.xml($parameters.name)" /> #end #end #** * Serializes the given data as JSON and writes the result on the HTTP response, setting the proper content type and * length. * * @param $data the data to be written as JSON on the HTTP response *# #macro (jsonResponse $data) #set ($json = $jsontool.serialize($data)) ## We write the output directly to the HTTP response in order to avoid going through the Rendering which executes ## transformations that could break the JSON (e.g. the icon transformation). Another option would be to specify which ## Rendering Transformations to execute in the query string (XWIKI-13167). #set ($discard = $response.setContentType('application/json')) ## Make sure the Character Encoding response header matches the character encoding used to write the response and ## compute its length. #set ($characterEncoding = 'utf-8') #set ($discard = $response.setCharacterEncoding($characterEncoding)) #set ($discard = $response.writer.write($json)) ## The content length is measured in bytes and one character can use more than one byte. #set ($discard = $response.setContentLength($json.getBytes($characterEncoding).size())) ## Make sure the entire content is send back to the client. #set ($discard = $response.flushBuffer()) ## Make sure XWiki doesn't write any more content to the response. #set ($discard = $xcontext.setFinished(true)) #end #macro (classPicker $parameters) #classPicker_import #if ("$!parameters" == "") #set ($parameters = {}) #end #set ($discard = $parameters.put('class', "$!parameters.get('class') xwiki-selectize suggest-classes")) #suggestInput($parameters 'classPicker_displayOptions') #end #macro (classPicker_import) #picker_import #set ($discard = $xwiki.jsfx.use('uicomponents/suggest/xwiki.selectize.js', true)) #end #macro (classPicker_displayOptions $selectedValues) #set ($selectedClassReferences = $collectionstool.set) #foreach ($selectedValue in $selectedValues) #set ($discard = $selectedClassReferences.add($services.model.resolveDocument($selectedValue))) #end #set ($optionGroups = $collectionstool.orderedMap) #classPicker_getOptionGroups($optionGroups $selectedClassReferences) #classPicker_displayOptionGroups($optionGroups $selectedClassReferences) #end #macro (classPicker_getOptionGroups $optionGroups $selectedClassReferences) #set ($classReferences = $collectionstool.set) ## Make sure the selected classes are listed as options. #set ($discard = $classReferences.addAll($selectedClassReferences)) #foreach ($className in $xwiki.classList) #set ($classReference = $services.model.resolveDocument($className)) #if ($services.security.authorization.hasAccess('view', $classReference)) #set ($discard = $classReferences.add($classReference)) #end #end #set ($classReferenceTree = $services.model.toTree($classReferences)) #classPicker_addOptionGroups($classReferenceTree $optionGroups) #end #** * Flatten the class reference tree into a list of class reference groups. *# #macro (classPicker_addOptionGroups $parentNode $optionGroups) ## Look for direct child class nodes and create an option group. #set ($classNodes = $parentNode.getChildren($doc.documentReference.type)) #if ($classNodes.size() > 0) #set ($classReferences = []) #foreach ($classNode in $classNodes) #set ($discard = $classReferences.add($classNode.reference)) #end #set ($discard = $optionGroups.put($parentNode.reference, $classReferences)) #end #foreach ($childNode in $parentNode.children) #if ($childNode.children.size() > 0) #classPicker_addOptionGroups($childNode $optionGroups) #end #end #end #macro (classPicker_displayOptionGroups $optionGroups $selectedClassReferences) #foreach ($entry in $optionGroups.entrySet()) ## Use the location as group label. #set ($path = []) #set ($referenceChain = $entry.key.reversedReferenceChain) ## Skip the wiki reference because classes are local. #foreach ($reference in $referenceChain.subList(1, $referenceChain.size())) #set ($discard = $path.add($reference.name)) #end <optgroup label="$escapetool.xml($stringtool.join($path, ' / '))"> #foreach ($classReference in $entry.value) #set ($optionData = { 'url': $xwiki.getURL($classReference) }) <option value="$escapetool.xml($services.model.serialize($classReference, 'local'))" #if ($selectedClassReferences.contains($classReference))selected="selected"#end data-data="$escapetool.xml($jsontool.serialize($optionData))"> ## We display the class title instead of the class name because classes can be defined in nested (WebHome) ## documents. We could also display the last space name but then we would need an option group for the top ## level classes and a label for this group that doesn't confuse the users. #set ($classDoc = $xwiki.getDocument($classReference)) $escapetool.xml($classDoc.plainTitle) </option> #end </optgroup> #end #end #** * Pulls all the JavaScript and CSS resources needed by the date & time picker. *# #macro (dateTimePicker_import) ## A simple date picker widget. #set ($discard = $xwiki.ssfx.use('uicomponents/widgets/datepicker/calendarDateSelect.css', true)) #set ($discard = $xwiki.jsfx.use('uicomponents/widgets/datepicker/calendarDateSelect.js', {'forceSkinAction': true, 'language': $xcontext.locale})) ## Used to parse and serialize the selected date using the date format specified in the XClass. #set ($discard = $xwiki.jsfx.use('uicomponents/widgets/datepicker/simpleDateFormat.js', {'forceSkinAction': true, 'language': $xcontext.locale})) ## A wrapper over the CalendarDateSelect widget that uses the SimpleDateFormat to parse/serialize the dates. #set ($discard = $xwiki.ssfx.use('uicomponents/widgets/datepicker/dateTimePicker.css', true)) #set ($discard = $xwiki.jsfx.use('uicomponents/widgets/datepicker/dateTimePicker.js')) #end #macro (dateTimePicker_input $parameters) #set ($discard = $parameters.putIfAbsent('class', 'datetime')) #set ($discard = $parameters.putIfAbsent('data-timestamp', $parameters.value.time)) #set ($discard = $parameters.putIfAbsent('data-locale', $services.localization.currentLocale)) #if ("$!parameters.get('data-format')" != '' && "$!parameters.value.time" != '') #set ($parameters.value = $datetool.format($parameters.get('data-format'), $parameters.value, $services.localization.currentLocale)) #end #if ("$!parameters.disabled" == 'true') #set ($parameters.disabled = 'disabled') #else #set ($discard = $parameters.remove('disabled')) #end <input type="text" #foreach ($parameter in $parameters.entrySet()) $escapetool.xml($parameter.key)="$!escapetool.xml($parameter.value)" #end /> #end #macro (dateTimePicker $parameters) #dateTimePicker_import #dateTimePicker_input($parameters) #end #** * Pulls all the JavaScript and CSS resources needed by the color picker. *# #macro (colorPicker_import) #set ($discard = $xwiki.jsfx.use('uicomponents/widgets/colorpicker/colorPicker.js', true)) #end #macro (colorPicker_input $parameters) #set ($discard = $parameters.putIfAbsent('class', 'color-picker type-color')) #if ("$!parameters.disabled" == 'true') #set ($parameters.disabled = 'disabled') #else #set ($discard = $parameters.remove('disabled')) #end <input type="text" #foreach ($parameter in $parameters.entrySet()) $escapetool.xml($parameter.key)="$!escapetool.xml($parameter.value)" #end /> #end #macro (colorPicker $parameters) #colorPicker_import #colorPicker_input($parameters) #end