001/* 002 * This library is part of OpenCms - 003 * the Open Source Content Management System 004 * 005 * Copyright (c) Alkacon Software GmbH & Co. KG (https://www.alkacon.com) 006 * 007 * This library is free software; you can redistribute it and/or 008 * modify it under the terms of the GNU Lesser General Public 009 * License as published by the Free Software Foundation; either 010 * version 2.1 of the License, or (at your option) any later version. 011 * 012 * This library is distributed in the hope that it will be useful, 013 * but WITHOUT ANY WARRANTY; without even the implied warranty of 014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 015 * Lesser General Public License for more details. 016 * 017 * For further information about Alkacon Software GmbH & Co. KG, please see the 018 * company website: https://www.alkacon.com 019 * 020 * For further information about OpenCms, please see the 021 * project website: https://www.opencms.org 022 * 023 * You should have received a copy of the GNU Lesser General Public 024 * License along with this library; if not, write to the Free Software 025 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 026 */ 027 028package org.opencms.workplace.tools.searchindex; 029 030import org.opencms.file.CmsProject; 031import org.opencms.i18n.CmsEncoder; 032import org.opencms.i18n.CmsLocaleManager; 033import org.opencms.i18n.CmsMessages; 034import org.opencms.jsp.CmsJspActionElement; 035import org.opencms.main.CmsException; 036import org.opencms.main.OpenCms; 037import org.opencms.search.CmsSearch; 038import org.opencms.search.CmsSearchResult; 039import org.opencms.search.fields.CmsSearchField; 040import org.opencms.util.CmsStringUtil; 041import org.opencms.workplace.CmsWidgetDialog; 042 043import java.util.Collections; 044import java.util.Iterator; 045import java.util.List; 046import java.util.Locale; 047import java.util.Map; 048import java.util.SortedMap; 049import java.util.StringTokenizer; 050import java.util.TreeMap; 051 052import jakarta.servlet.http.HttpServletRequest; 053import jakarta.servlet.http.HttpServletResponse; 054import jakarta.servlet.jsp.PageContext; 055 056/** 057 * Displays the result of a <code>{@link org.opencms.search.CmsSearch}</code>.<p> 058 * 059 * Requires the following request parameters (see constructor): 060 * <ul> 061 * <li> 062 * index:<br>the String identifying the required search index. 063 * <li> 064 * query:<br>the search query to run. 065 * </ul> 066 * <p> 067 * 068 * @since 6.0.0 069 */ 070public class CmsSearchResultView { 071 072 /** 073 * A simple wrapper around html for a form and it's name for value 074 * side of form cache, necessary as order in Map is arbitrary, 075 * SortedMap unusable as backlinks have higher order, lower formname... <p> 076 */ 077 private final class HTMLForm { 078 079 /** The html of the generated form. **/ 080 String m_formHtml; 081 082 /** The name of the generated form. **/ 083 String m_formName; 084 085 /** 086 * Creates an instance with the given formname and the given html code for the form. <p> 087 * 088 * @param formName the form name of the form 089 * @param formHtml the form html of the form 090 */ 091 HTMLForm(String formName, String formHtml) { 092 093 m_formName = formName; 094 m_formHtml = formHtml; 095 } 096 097 /** 098 * Returns the form html.<p> 099 * 100 * @return the form html 101 * 102 * @see java.lang.Object#toString() 103 */ 104 @Override 105 public String toString() { 106 107 return m_formHtml; 108 } 109 } 110 111 /** The project that forces evaluation of all dynamic content. */ 112 protected CmsProject m_offlineProject; 113 114 /** The project that allows static export. */ 115 protected CmsProject m_onlineProject; 116 117 /** The flag that decides whether links to search result point to their exported version or not. */ 118 private boolean m_exportLinks; 119 120 /** 121 * A small cache for the forms generated by <code>{@link #toPostParameters(String, CmsSearch)}</code> during a request. <p> 122 * 123 * Avoids duplicate forms.<p> 124 */ 125 private SortedMap<String, HTMLForm> m_formCache; 126 127 /** The CmsJspActionElement to use. **/ 128 private CmsJspActionElement m_jsp; 129 130 /** The url to a proprietary search url (different from m_jsp.getRequestContext().getUri). **/ 131 private String m_searchRessourceUrl; 132 133 /** 134 * Constructor with the action element to use. <p> 135 * 136 * @param action the action element to use 137 */ 138 public CmsSearchResultView(CmsJspActionElement action) { 139 140 m_jsp = action; 141 m_formCache = new TreeMap<String, HTMLForm>(); 142 try { 143 m_onlineProject = m_jsp.getCmsObject().readProject(CmsProject.ONLINE_PROJECT_ID); 144 m_offlineProject = m_jsp.getRequestContext().getCurrentProject(); 145 } catch (CmsException e) { 146 // failed to get online project, at least avoid NPE 147 m_onlineProject = m_offlineProject; 148 } 149 150 } 151 152 /** 153 * Constructor with arguments for construction of a <code>{@link CmsJspActionElement}</code>. <p> 154 * 155 * @param pageContext the page context to use 156 * @param request the current request 157 * @param response the current response 158 */ 159 public CmsSearchResultView(PageContext pageContext, HttpServletRequest request, HttpServletResponse response) { 160 161 this(new CmsJspActionElement(pageContext, request, response)); 162 163 } 164 165 /** 166 * Returns the formatted search results.<p> 167 * 168 * @param search the pre-configured search bean 169 * @return the formatted search results 170 */ 171 public String displaySearchResult(CmsSearch search) { 172 173 StringBuffer result = new StringBuffer(800); 174 Locale locale = m_jsp.getRequestContext().getLocale(); 175 CmsMessages messages = org.opencms.search.Messages.get().getBundle(locale); 176 177 result.append("<h3>\n"); 178 result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_RESULT_TITLE_0)); 179 result.append("\n</h1>\n"); 180 List<CmsSearchResult> searchResult; 181 if (CmsStringUtil.isEmptyOrWhitespaceOnly(search.getQuery())) { 182 search.setQuery(""); 183 searchResult = Collections.emptyList(); 184 } else { 185 search.setMatchesPerPage(5); 186 searchResult = search.getSearchResult(); 187 } 188 189 HttpServletRequest request = m_jsp.getRequest(); 190 // get the action to perform from the request 191 String action = request.getParameter("action"); 192 193 if ((action != null) && (searchResult == null)) { 194 result.append("<p class=\"formerror\">\n"); 195 if (search.getLastException() != null) { 196 197 result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_UNAVAILABLE_0)); 198 result.append("\n<!-- ").append(search.getLastException().toString()); 199 result.append(" //-->\n"); 200 } else { 201 result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_NOMATCH_1, search.getQuery())); 202 result.append("\n"); 203 } 204 result.append("</p>\n"); 205 } else if ((action != null) && (searchResult.size() <= 0)) { 206 result.append("<p class=\"formerror\">\n"); 207 result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_NOMATCH_1, search.getQuery())); 208 result.append("\n"); 209 result.append("</p>\n"); 210 } else if ((action != null) && (searchResult.size() > 0)) { 211 result.append("<p>\n"); 212 result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_RESULT_START_0)); 213 result.append("\n"); 214 result.append("</p>\n<p>\n"); 215 216 Iterator<CmsSearchResult> iterator = searchResult.iterator(); 217 218 try { 219 if (m_exportLinks) { 220 m_jsp.getRequestContext().setCurrentProject(m_onlineProject); 221 } 222 223 String name; 224 String path; 225 while (iterator.hasNext()) { 226 CmsSearchResult entry = iterator.next(); 227 result.append("\n<div class=\"searchResult\">"); 228 result.append("<a class=\"navhelp\" href=\"#\" onclick=\"javascript:window.open('"); 229 // CmsJspActionElement.link() is not programmed for using from root site 230 // because it assumes the "default CmsSite" when no configured site matches the 231 // root site "/": 232 if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_jsp.getRequestContext().getSiteRoot())) { 233 // link will always cut off "/sites/default" if we are in the 234 // root site, this call is only used to get the scheme, host, context name and servlet name... 235 path = m_jsp.link(OpenCms.getSiteManager().getDefaultSite().getSiteRoot() + "/") 236 + entry.getPath().substring(1); 237 } else { 238 path = m_jsp.link(entry.getPath()); 239 } 240 result.append(path); 241 result.append( 242 "', '_blank', 'width='+screen.availWidth+', height='+ screen.availHeight+', scrollbars=yes, menubar=yes, toolbar=yes')\""); 243 result.append("\">\n"); 244 name = entry.getField(CmsSearchField.FIELD_TITLE); 245 if (name == null) { 246 name = entry.getPath(); 247 } 248 result.append(name); 249 result.append("</a>"); 250 result.append(" (").append(entry.getScore()).append(" %)\n"); 251 252 result.append("<span class=\"searchExcerpt\">\n"); 253 String excerptString = entry.getExcerpt(); 254 if (CmsStringUtil.isEmptyOrWhitespaceOnly(excerptString)) { 255 result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_EXCERPT_UNAVAILABLE_0)); 256 } else { 257 result.append(excerptString).append('\n'); 258 } 259 result.append("</span>\n"); 260 result.append("</div>\n"); 261 } 262 } finally { 263 m_jsp.getRequestContext().setCurrentProject(m_offlineProject); 264 } 265 266 result.append("</p>\n"); 267 268 // search page links below results 269 if ((search.getPreviousUrl() != null) || (search.getNextUrl() != null)) { 270 result.append("<p>"); 271 if (search.getPreviousUrl() != null) { 272 273 result.append("<a class=\"searchlink\" href=\""); 274 result.append( 275 getSearchPageLink( 276 m_jsp.link( 277 new StringBuffer(search.getPreviousUrl()).append('&').append( 278 CmsLocaleManager.PARAMETER_LOCALE).append("=").append( 279 m_jsp.getRequestContext().getLocale()).toString()), 280 search)); 281 result.append("\">"); 282 result.append(messages.key(org.opencms.search.Messages.GUI_HELP_BUTTON_BACK_0)); 283 result.append(" <<</a> \n"); 284 } 285 Map<Integer, String> pageLinks = search.getPageLinks(); 286 Iterator<Integer> i = pageLinks.keySet().iterator(); 287 while (i.hasNext()) { 288 int pageNumber = (i.next()).intValue(); 289 290 result.append(" "); 291 if (pageNumber != search.getSearchPage()) { 292 result.append("<a class=\"searchlink\" href=\"").append( 293 getSearchPageLink( 294 m_jsp.link( 295 new StringBuffer(pageLinks.get(Integer.valueOf(pageNumber))).append('&').append( 296 CmsLocaleManager.PARAMETER_LOCALE).append("=").append( 297 m_jsp.getRequestContext().getLocale()).toString()), 298 search)); 299 result.append("\" target=\"_self\">").append(pageNumber).append("</a>\n"); 300 } else { 301 result.append(pageNumber); 302 } 303 } 304 if (search.getNextUrl() != null) { 305 result.append(" <a class=\"searchlink\" href=\""); 306 result.append( 307 getSearchPageLink( 308 new StringBuffer(m_jsp.link(search.getNextUrl())).append('&').append( 309 CmsLocaleManager.PARAMETER_LOCALE).append("=").append( 310 m_jsp.getRequestContext().getLocale()).toString(), 311 search)); 312 result.append("\">>>"); 313 result.append(messages.key(org.opencms.search.Messages.GUI_HELP_BUTTON_NEXT_0)); 314 result.append("</a>\n"); 315 } 316 result.append("</p>\n"); 317 } 318 319 } 320 321 // include the post forms for the page links: 322 Iterator<HTMLForm> values = m_formCache.values().iterator(); 323 while (values.hasNext()) { 324 result.append(values.next()); 325 } 326 return result.toString(); 327 328 } 329 330 /** 331 * Returns true if the links to search results shall point to exported content, false else. <p> 332 * @return true if the links to search results shall point to exported content, false else 333 */ 334 public boolean isExportLinks() { 335 336 return m_exportLinks; 337 } 338 339 /** 340 * Set wether the links to search results point to exported content or not. <p> 341 * 342 * @param exportLinks The value that decides Set wether the links to search results point to exported content or not. 343 */ 344 public void setExportLinks(boolean exportLinks) { 345 346 m_exportLinks = exportLinks; 347 } 348 349 /** 350 * Set a proprietary resource uri for the search page. <p> 351 * 352 * This is optional but allows to override the standard search result links 353 * (for next or previous pages) that point to 354 * <code>getJsp().getRequestContext().getUri()</code> whenever the search 355 * uri is element of some template and should not be linked directly.<p> 356 * 357 * @param uri the proprietary resource uri for the search page 358 */ 359 public void setSearchRessourceUrl(String uri) { 360 361 m_searchRessourceUrl = uri; 362 } 363 364 /** 365 * Returns the resource uri to the search page with respect to the 366 * optionally configured value <code>{@link #setSearchRessourceUrl(String)}</code> 367 * with the request parameters of the given argument.<p> 368 * 369 * This is a workaround for Tomcat bug 35775 370 * (http://issues.apache.org/bugzilla/show_bug.cgi?id=35775). After it has been 371 * fixed the version 1.1 should be restored (or at least this codepath should be switched back.<p> 372 * 373 * @param link the suggestion of the search result bean ( a previous, next or page number url) 374 * @param search the search bean 375 * 376 * @return the resource uri to the search page with respect to the 377 * optionally configured value <code>{@link #setSearchRessourceUrl(String)}</code> 378 * with the request parameters of the given argument 379 */ 380 private String getSearchPageLink(String link, CmsSearch search) { 381 382 if (m_searchRessourceUrl != null) { 383 // for the form to generate we need params. 384 String pageParams = ""; 385 int paramIndex = link.indexOf('?'); 386 if (paramIndex > 0) { 387 pageParams = link.substring(paramIndex); 388 } 389 StringBuffer formurl = new StringBuffer(m_searchRessourceUrl); 390 if (m_searchRessourceUrl.indexOf('?') != -1) { 391 // the search page url already has a query string, don't start params of search-generated link 392 // with '?' 393 pageParams = new StringBuffer("&").append(pageParams.substring(1)).toString(); 394 } 395 formurl.append(pageParams).toString(); 396 String formname = toPostParameters(formurl.toString(), search); 397 398 link = new StringBuffer("javascript:document.forms['").append(formname).append("'].submit()").toString(); 399 } 400 return link; 401 } 402 403 /** 404 * Generates a html form (named form<n>) with parameters found in 405 * the given GET request string (appended params with "?value=param&value2=param2). 406 * >n< is the number of forms that already have been generated. 407 * This is a content-expensive bugfix for http://issues.apache.org/bugzilla/show_bug.cgi?id=35775 408 * and should be replaced with the 1.1 revision as soon that bug is fixed.<p> 409 * 410 * The forms action will point to the given uri's path info part: All links in the page 411 * that includes this generated html and that are related to the get request should 412 * have "src='#'" and "onclick=documents.forms['<getRequestUri>'].submit()". <p> 413 * 414 * The generated form lands in the internal <code>Map {@link #m_formCache}</code> as mapping 415 * from uris to Strings and has to be appended to the output at a valid position. <p> 416 * 417 * Warning: Does not work with multiple values mapped to one parameter ("key = value1,value2..").<p> 418 * 419 * 420 * 421 * @param getRequestUri a request uri with optional query, will be used as name of the form too 422 * @param search the search bean to get the parameters from 423 * 424 * @return the formname of the the generated form that contains the parameters of the given request uri or 425 * the empty String if there weren't any get parameters in the given request uri. 426 */ 427 private String toPostParameters(String getRequestUri, CmsSearch search) { 428 429 StringBuffer result; 430 String formname = ""; 431 432 if (!m_formCache.containsKey(getRequestUri)) { 433 434 result = new StringBuffer(); 435 int index = getRequestUri.indexOf('?'); 436 String query = ""; 437 String path = ""; 438 if (index > 0) { 439 query = getRequestUri.substring(index + 1); 440 path = getRequestUri.substring(0, index); 441 formname = new StringBuffer("searchform").append(m_formCache.size()).toString(); 442 443 result.append("\n<form method=\"post\" name=\"").append(formname).append("\" action=\""); 444 result.append(path).append("\">\n"); 445 // "key=value" pairs as tokens: 446 StringTokenizer entryTokens = new StringTokenizer(query, "&", false); 447 while (entryTokens.hasMoreTokens()) { 448 StringTokenizer keyValueToken = new StringTokenizer(entryTokens.nextToken(), "=", false); 449 if (keyValueToken.countTokens() != 2) { 450 continue; 451 } 452 // Undo the possible already performed url encoding for the given url 453 String key = CmsEncoder.decode(keyValueToken.nextToken()); 454 String value = CmsEncoder.decode(keyValueToken.nextToken()); 455 if ("action".equals(key)) { 456 // cannot use the "search"-action value in combination with CmsWidgetDialog: prepareCommit would be left out! 457 value = CmsWidgetDialog.DIALOG_SAVE; 458 } 459 result.append(" <input type=\"hidden\" name=\""); 460 result.append(key).append("\" value=\""); 461 result.append(value).append("\" />\n"); 462 } 463 464 // custom search index code for making category widget - compatible 465 // this is needed for transforming e.g. the CmsSearch-generated 466 // "&category=a,b,c" to widget fields categories.0..categories.n. 467 List<String> categories = search.getParameters().getCategories(); 468 Iterator<String> it = categories.iterator(); 469 int count = 0; 470 while (it.hasNext()) { 471 result.append(" <input type=\"hidden\" name=\""); 472 result.append("categories.").append(count).append("\" value=\""); 473 result.append(it.next()).append("\" />\n"); 474 count++; 475 } 476 List<String> roots = search.getParameters().getRoots(); 477 it = roots.iterator(); 478 count = 0; 479 while (it.hasNext()) { 480 result.append(" <input type=\"hidden\" name=\""); 481 result.append("roots.").append(count).append("\" value=\""); 482 result.append(it.next()).append("\" />\n"); 483 count++; 484 } 485 486 result.append(" <input type=\"hidden\" name=\""); 487 result.append("fields").append("\" value=\""); 488 result.append(CmsStringUtil.collectionAsString(search.getParameters().getFields(), ",")); 489 result.append("\" />\n"); 490 491 result.append(" <input type=\"hidden\" name=\""); 492 result.append("sortfields.").append(0).append("\" value=\""); 493 result.append(search.getParameters().getSortName()).append("\" />\n"); 494 495 result.append("</form>\n"); 496 HTMLForm form = new HTMLForm(formname, result.toString()); 497 498 m_formCache.put(getRequestUri, form); 499 return formname; 500 } 501 // empty String for no get parameters 502 return formname; 503 504 } else { 505 HTMLForm form = m_formCache.get(getRequestUri); 506 return form.m_formName; 507 } 508 } 509}