-
Notifications
You must be signed in to change notification settings - Fork 8
/
HeaderFooterTagLib.groovy
525 lines (472 loc) · 19.9 KB
/
HeaderFooterTagLib.groovy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
package au.org.ala.bootstrap3
import au.org.ala.cas.util.AuthenticationCookieUtils
import grails.util.Holders
import grails.util.TypeConvertingMap
import org.springframework.web.servlet.support.RequestContextUtils
class HeaderFooterTagLib {
static namespace = 'hf' // namespace for headers and footers
static returnObjectForTags = ['createLoginUrl']
static LOGGED_IN_CLASS = 'logged-in'
static LOGGED_OUT_CLASS = 'not-logged-in'
/**
* All the following statics can be overridden by the specified config declarations.
*
* The banner include assumes that ala-cas-client exists in the app library.
*/
def alaBaseURL = Holders.config.ala.baseURL ?: "https://www.ala.org.au"
def bieBaseURL = Holders.config.bie.baseURL ?: "https://bie.ala.org.au"
def grailServerURL = Holders.config.grails.serverURL ?: "http://bie.ala.org.au"
def bieSearchPath = Holders.config.bie.searchPath ?: "/search"
def headerAndFooterBaseURL = Holders.config.headerAndFooter.baseURL ?: "https://www.ala.org.au/commonui-bs3"
// the next two can also be overridden by tag attributes
def casLoginUrl = Holders.config.security.cas.loginUrl ?: "https://auth.ala.org.au/cas/login"
def casLogoutUrl = Holders.config.security.cas.logoutUrl ?: "https://auth.ala.org.au/cas/logout"
def cacheTimeout = (Holders.config.headerAndFooter.cacheTimeout ?: '1800000').toLong()
/**
* Display the page banner. Includes login/logout link and search box.
*
* Usage: <hf:banner [param=""]../>
*
* @attr logoutUrl the local url that should invalidate the session and redirect to the auth
* logout url - defaults to {CH.config.grails.serverURL}/session/logout
* @attr loginReturnToUrl where to go after logging in - defaults to current page
* @attr logoutReturnToUrl where to go after logging out - defaults to current page
* @attr loginReturnUrl where to go after login - defaults to current page
* @attr casLoginUrl - defaults to {CH.config.security.cas.loginUrl}
* @attr casLogoutUrl - defaults to {CH.config.security.cas.logoutUrl}
* @attr ignoreCookie - if true the helper cookie will not be used to determine login - defaults to false
* @attr fluidLayout - if true the BS CSS class of "container" is changed to "container-fluid"
*/
def banner = { attrs ->
out << load('banner', attrs)
}
/**
*
*/
def head = {
out << load('head', [:])
}
/**
* Display the main menu.
*
* Note that highlighting of the current menu item is done by including the appropriate class in the
* body tag, eg class="collections".
*
* Usage: <hf:menu/>
*
* @attr fluidLayout - if true the BS CSS class of "container" is changed to "container-fluid"
*/
def menu = { attrs ->
out << load('menu', attrs)
}
/**
* Displays the page footer.
*
* Usage: <hf:footer/>
*/
def footer = { attrs ->
out << load('footer', attrs)
}
/**
* Cache for includes. Expires after 30 mins or when clearCache is called.
*/
def hfCache = [
banner: [timestamp: new Date().time, content: ""],
menu: [timestamp: new Date().time, content: ""],
footer: [timestamp: new Date().time, content: ""],
head: [timestamp: new Date().time, content: ""]
]
/**
* Call this tag from a controller to clear the cache.
*/
def clearCache = {
hfCache.each { key, obj -> hfCache[key].content = ""}
log.info "cache cleared"
}
/**
* Generate the login/logout link
*
* @attr cssClass - CSS class to add to a tag
*
* plus
* @attr logoutUrl the local url that should invalidate the session and redirect to the auth
* logout url - defaults to {CH.config.grails.serverURL}/session/logout
* @attr loginReturnToUrl where to go after logging in - defaults to current page
* @attr logoutReturnToUrl where to go after logging out - defaults to current page
* @attr loginReturnUrl where to go after login - defaults to current page
* @attr casLoginUrl - defaults to {CH.config.security.cas.loginUrl}
* @attr casLogoutUrl - defaults to {CH.config.security.cas.logoutUrl}
* @attr ignoreCookie - if true the helper cookie will not be used to determine login - defaults to false
*/
def loginLogout = { attrs ->
out << buildLoginoutLink(attrs)
}
/**
* Generate a URL for logging in the user\. Generally used as a method call
* rather than a tag eg.<br/>
*
* <a href="${createLoginUrl()}">log in</a>
*
* @emptyTag
*
* @attr casLoginUrl - defaults to {CH.config.security.cas.loginUrl}
* @attr loginReturnToUrl where to go after logging in - defaults to current page
*/
Closure createLoginUrl = { attrs ->
String loginUrl = buildLoginLink(attrs)
return loginUrl
}
/**
* Get the content from cache of the web.
* @param which specifies the include
* @param attrs any specified params
* @return
*/
String load(which, attrs) {
def content
if (hfCache[which].content == "" || (new Date().time > hfCache[which].timestamp + cacheTimeout)) {
content = getContent(which)
hfCache[which].content = content
hfCache[which].timestamp = new Date().time
} else {
content = hfCache[which].content
}
return transform(content, attrs)
}
/**
* Loads the content from the web.
* @param which specifies the include
* @return
*/
String getContent(which) {
def url = headerAndFooterBaseURL + '/' + which + ".html" // Bootstrap versions
def conn = new URL(url).openConnection()
try {
conn.setConnectTimeout(10000)
conn.setReadTimeout(50000)
return conn.content.text
} catch (SocketTimeoutException e) {
log.warn "Timed out getting ${which} template. URL= ${url}."
} catch (Exception e) {
log.warn "Failed to get ${which} template. ${e.getClass()} ${e.getMessage()} URL= ${url}."
}
return ""
}
/**
* Does the appropriate substitutions on the included content.
* @param content
* @param attrs any specified params to override defaults
* @return
*/
String transform(content, attrs) {
switch ( Holders.config.headerAndFooter.version ) {
case "2":
return transformV2(content, attrs)
case "1":
default:
return transformV1(content, attrs)
}
}
/**
* @deprecated
* Does the appropriate substitutions on the included content.
* @param content
* @param attrs any specified params to override defaults
* @return
*/
String transformV1(content, attrs) {
content = content.replaceAll(/::headerFooterServer::/, headerAndFooterBaseURL)
content = content.replaceAll(/::centralServer::/, alaBaseURL)
content = content.replaceAll(/::searchServer::/, bieBaseURL) // change for BIE to grailServerURL
content = content.replaceAll(/::searchPath::/, bieSearchPath)
content = content.replaceAll(/::authStatusClass::/, isLoggedIn(attrs) ? LOGGED_IN_CLASS: LOGGED_OUT_CLASS)
if (attrs.fluidLayout) {
content = content.replaceAll('class="container"', 'class="container-fluid"')
}
if (content =~ "::loginLogoutListItem::") {
// only do the work if it is needed
content = content.replaceAll(/::loginLogoutListItem::/, buildLoginoutLink(attrs))
}
return content
}
/**
* Does the appropriate substitutions on the included content.
* @param content
* @param attrs any specified params to override defaults
* @return
*/
String transformV2(content, attrs) {
content = content.replaceAll(/::headerFooterServer::/, headerAndFooterBaseURL)
content = content.replaceAll(/::centralServer::/, alaBaseURL)
content = content.replaceAll(/::searchServer::/, bieBaseURL) // change for BIE to grailServerURL
content = content.replaceAll(/::searchPath::/, bieSearchPath)
if ((attrs.fluidLayout?:"true").toBoolean()) {
content = content.replaceAll('::containerClass::', "container-fluid")
} else {
content = content.replaceAll('::containerClass::', "container")
}
def signedInOutClass = isLoggedIn(attrs) ? 'signedIn' : 'signedOut'
content = content.replaceAll(/::loginURL::/, buildLoginLink(attrs))
content = content.replaceAll(/::logoutURL::/, buildLogoutLink(attrs))
content = content.replaceAll(/::loginStatus::/, signedInOutClass)
return content
}
boolean isLoggedIn(attrs) {
(attrs.ignoreCookie != "true" &&
AuthenticationCookieUtils.cookieExists(request, AuthenticationCookieUtils.ALA_AUTH_COOKIE)) ||
request.userPrincipal
}
/**
* Builds the login or logout link based on current login status.
* @param attrs any specified params to override defaults
* @return
*/
String buildLoginoutLink(attrs) {
switch ( Holders.config.headerAndFooter.version ) {
case "2":
return buildLoginoutLinkV2(attrs)
case "1":
default:
return buildLoginoutLinkV1(attrs)
}
}
/**
* @deprecated
* Builds the login or logout link based on current login status.
* @param attrs any specified params to override defaults
* @return
*/
String buildLoginoutLinkV1(attrs) {
def requestUri = removeContext(grailServerURL) + request.forwardURI
def logoutUrl = attrs.logoutUrl ?: grailServerURL + "/session/logout"
def logoutReturnToUrl = attrs.logoutReturnToUrl ?: requestUri
def casLogoutUrl = attrs.casLogoutUrl ?: casLogoutUrl
// TODO should this be attrs.logoutReturnToUrl?
if (!attrs.loginReturnToUrl && request.queryString) {
logoutReturnToUrl += "?" + URLEncoder.encode(request.queryString, "UTF-8")
}
if (isLoggedIn(attrs)) {
return "<a href='${logoutUrl}" +
"?casUrl=${casLogoutUrl}" +
"&appUrl=${logoutReturnToUrl}' " +
"class='${attrs.cssClass}'>Logout</a>"
} else {
// currently logged out
return "<a href='${buildLoginLink(attrs)}' class='${attrs.cssClass}'>Log in</a>"
}
}
/**
* Builds the login or logout link based on current login status.
* @param attrs any specified params to override defaults
* @return
*/
String buildLoginoutLinkV2(attrs) {
def requestUri = removeContext(grailServerURL) + request.forwardURI
def logoutUrl = attrs.logoutUrl ?: grailServerURL + "/session/logout"
def logoutReturnToUrl = attrs.logoutReturnToUrl ?: requestUri
def casLogoutUrl = attrs.casLogoutUrl ?: casLogoutUrl
// TODO should this be attrs.logoutReturnToUrl?
if (!attrs.loginReturnToUrl && request.queryString) {
logoutReturnToUrl += "?" + URLEncoder.encode(request.queryString, "UTF-8")
}
if (isLoggedIn(attrs)) {
return "<a href='${logoutUrl}" +
"?casUrl=${casLogoutUrl}" +
"&appUrl=${logoutReturnToUrl}' " +
"class='btn btn-outline-white btn-sm'>Logout</a>"
} else {
// currently logged out
return "<a href='${buildLoginLink(attrs)}' class='btn btn-primary btn-sm'>Login</a>"
}
}
/**
* Build the login link
* @param attrs any specified params to override defaults
* @return The login url
*/
String buildLoginLink(attrs) {
def casLoginUrl = attrs.casLoginUrl ?: casLoginUrl
def loginReturnToUrl = attrs.loginReturnToUrl ?: (removeContext(grailServerURL) + request.forwardURI + (request.queryString ? "?" + URLEncoder.encode(request.queryString, "UTF-8") : ""))
String loginUrl = "${casLoginUrl}?service=${loginReturnToUrl}"
return loginUrl
}
/**
* Build the logout link
* @param attrs any specified params to override defaults
* @return The logout url
*/
String buildLogoutLink(attrs) {
def requestUri = removeContext(grailServerURL) + request.forwardURI
def logoutUrl = attrs.logoutUrl ?: grailServerURL + "/session/logout"
def logoutReturnToUrl = attrs.logoutReturnToUrl ?: requestUri
String url = "${logoutUrl}?casUrl=${casLogoutUrl}&appUrl=${logoutReturnToUrl}"
return url
}
/**
* Remove the context path and params from the url.
* @param urlString
* @return
*/
private String removeContext(urlString) {
def url = urlString.toURL()
def protocol = url.protocol != -1 ? url.protocol + "://" : ""
def port = url.port != -1 ? ":" + url.port : ""
return protocol + url.host + port
}
/*
* This g:paginate tag fix is based on:
* https://github.com/grails/grails-core/blob/master/grails-plugin-gsp/src/main/groovy/org/codehaus/groovy/grails/plugins/web/taglib/RenderTagLib.groovy
*
* It has been moved into the hf taglib as the g.paginate override isn't working in Grails 3.2.11
*/
/**
* Creates next/previous links to support pagination for the current controller.<br/>
*
* <g:paginate total="${Account.count()}" /><br/>
*
* @emptyTag
*
* @attr total REQUIRED The total number of results to paginate
* @attr action the name of the action to use in the link, if not specified the default action will be linked
* @attr controller the name of the controller to use in the link, if not specified the current controller will be linked
* @attr id The id to use in the link
* @attr params A map containing request parameters
* @attr prev The text to display for the previous link (defaults to "Previous" as defined by default.paginate.prev property in I18n messages.properties)
* @attr next The text to display for the next link (defaults to "Next" as defined by default.paginate.next property in I18n messages.properties)
* @attr max The number of records displayed per page (defaults to 10). Used ONLY if params.max is empty
* @attr maxsteps The number of steps displayed for pagination (defaults to 10). Used ONLY if params.maxsteps is empty
* @attr offset Used only if params.offset is empty
* @attr fragment The link fragment (often called anchor tag) to use
*/
Closure paginate = { Map attrsMap ->
TypeConvertingMap attrs = (TypeConvertingMap)attrsMap
def writer = out
if (attrs.total == null) {
throwTagError("Tag [paginate] is missing required attribute [total]")
}
def messageSource = grailsAttributes.messageSource
def locale = RequestContextUtils.getLocale(request)
def total = attrs.int('total') ?: 0
def action = (attrs.action ? attrs.action : (params.action ? params.action : "index"))
def offset = params.int('offset') ?: 0
def max = params.int('max')
def maxsteps = (attrs.int('maxsteps') ?: 10)
if (!offset) offset = (attrs.int('offset') ?: 0)
if (!max) max = (attrs.int('max') ?: 10)
def linkParams = [:]
if (attrs.params) linkParams.putAll(attrs.params)
linkParams.offset = offset - max
linkParams.max = max
if (params.sort) linkParams.sort = params.sort
if (params.order) linkParams.order = params.order
def linkTagAttrs = [action: action]
if (attrs.namespace) {
linkTagAttrs.namespace = attrs.namespace
}
if (attrs.controller) {
linkTagAttrs.controller = attrs.controller
}
if (attrs.id != null) {
linkTagAttrs.id = attrs.id
}
if (attrs.fragment != null) {
linkTagAttrs.fragment = attrs.fragment
}
//add the mapping attribute if present
if (attrs.mapping) {
linkTagAttrs.mapping = attrs.mapping
}
linkTagAttrs.params = linkParams
def cssClasses = "pagination"
if (attrs.class) {
cssClasses = "pagination " + attrs.class
}
// determine paging variables
def steps = maxsteps > 0
int currentstep = (offset / max) + 1
int firststep = 1
int laststep = Math.round(Math.ceil(total / max))
writer << "<nav aria-label=\"Page navigation\">"
writer << "<ul class=\"${cssClasses}\">"
// display previous link when not on firststep
if (currentstep > firststep) {
linkParams.offset = offset - max
writer << '<li>'
writer << link(linkTagAttrs.clone()) {
(attrs.prev ?: messageSource.getMessage('paginate.prev', null, '«', locale))
}
writer << '</li>'
} else {
writer << '<li class="disabled">'
writer << '<span>'
writer << (attrs.prev ?: messageSource.getMessage('paginate.prev', null, '«', locale))
writer << '</span>'
writer << '</li>'
}
// display steps when steps are enabled and laststep is not firststep
if (steps && laststep > firststep) {
linkTagAttrs.class = 'step'
// determine begin and endstep paging variables
int beginstep = currentstep - Math.round(maxsteps / 2) + (maxsteps % 2)
int endstep = currentstep + Math.round(maxsteps / 2) - 1
if (beginstep < firststep) {
beginstep = firststep
endstep = maxsteps
}
if (endstep > laststep) {
beginstep = laststep - maxsteps + 1
if (beginstep < firststep) {
beginstep = firststep
}
endstep = laststep
}
// display firststep link when beginstep is not firststep
if (beginstep > firststep) {
linkParams.offset = 0
writer << '<li>'
writer << link(linkTagAttrs.clone()) { firststep.toString() }
writer << '</li>'
writer << '<li class="disabled"><span>...</span></li>'
}
// display paginate steps
(beginstep..endstep).each { i ->
if (currentstep == i) {
writer << "<li class=\"active\">"
writer << "<span>${i}</span>"
writer << "</li>";
} else {
linkParams.offset = (i - 1) * max
writer << "<li>";
writer << link(linkTagAttrs.clone()) { i.toString() }
writer << "</li>";
}
}
// display laststep link when endstep is not laststep
if (endstep < laststep) {
writer << '<li class="disabled"><span>...</span></li>'
linkParams.offset = (laststep - 1) * max
writer << '<li>'
writer << link(linkTagAttrs.clone()) { laststep.toString() }
writer << '</li>'
}
}
// display next link when not on laststep
if (currentstep < laststep) {
linkParams.offset = offset + max
writer << '<li>'
writer << link(linkTagAttrs.clone()) {
(attrs.next ? attrs.next : messageSource.getMessage('paginate.next', null, '»', locale))
}
writer << '</li>'
} else {
linkParams.offset = offset + max
writer << '<li class="disabled">'
writer << '<span>'
writer << (attrs.next ? attrs.next : messageSource.getMessage('paginate.next', null, '»', locale))
writer << '</span>'
writer << '</li>'
}
writer << '</ul>'
writer << '</nav>'
}
}