Beispiel #1
0
  public void headingAdded(WikiContext context, Heading hd) {
    log.debug("HD: " + hd.m_level + ", " + hd.m_titleText + ", " + hd.m_titleAnchor);

    switch (hd.m_level) {
      case Heading.HEADING_SMALL:
        m_buf.append("<li class=\"toclevel-3\">");
        m_level3Index++;
        break;
      case Heading.HEADING_MEDIUM:
        m_buf.append("<li class=\"toclevel-2\">");
        m_level2Index++;
        break;
      case Heading.HEADING_LARGE:
        m_buf.append("<li class=\"toclevel-1\">");
        m_level1Index++;
        break;
      default:
        throw new InternalWikiException("Unknown depth in toc! (Please submit a bug report.)");
    }

    if (m_level1Index < m_starting) {
      // in case we never had a large heading ...
      m_level1Index++;
    }
    if ((m_lastLevel == Heading.HEADING_SMALL) && (hd.m_level != Heading.HEADING_SMALL)) {
      m_level3Index = 0;
    }
    if (((m_lastLevel == Heading.HEADING_SMALL) || (m_lastLevel == Heading.HEADING_MEDIUM))
        && (hd.m_level == Heading.HEADING_LARGE)) {
      m_level3Index = 0;
      m_level2Index = 0;
    }

    String titleSection = hd.m_titleSection.replace('%', '_');
    String pageName = context.getEngine().encodeName(context.getPage().getName()).replace('%', '_');

    String url = context.getURL(WikiContext.VIEW, context.getPage().getName());
    String sectref = "#section-" + pageName + "-" + titleSection;

    m_buf.append("<a class=\"wikipage\" href=\"" + url + sectref + "\">");
    if (m_usingNumberedList) {
      switch (hd.m_level) {
        case Heading.HEADING_SMALL:
          m_buf.append(m_prefix + m_level1Index + "." + m_level2Index + "." + m_level3Index + " ");
          break;
        case Heading.HEADING_MEDIUM:
          m_buf.append(m_prefix + m_level1Index + "." + m_level2Index + " ");
          break;
        case Heading.HEADING_LARGE:
          m_buf.append(m_prefix + m_level1Index + " ");
          break;
        default:
          throw new InternalWikiException("Unknown depth in toc! (Please submit a bug report.)");
      }
    }
    m_buf.append(TextUtil.replaceEntities(hd.m_titleText) + "</a></li>\n");

    m_lastLevel = hd.m_level;
  }
Beispiel #2
0
  public String preTranslate(WikiContext context, String content) {
    for (int i = 0; i < c_profanities.length; i++) {
      String word = c_profanities[i];
      String replacement = word.charAt(0) + "*" + word.charAt(word.length() - 1);

      content = TextUtil.replaceString(content, word, replacement);
    }

    return content;
  }
  /**
   * Initializes the RenderingManager. Checks for cache size settings, initializes the document
   * cache. Looks for alternative WikiRenderers, initializes one, or the default XHTMLRenderer, for
   * use.
   *
   * @param engine A WikiEngine instance.
   * @param properties A list of properties to get parameters from.
   */
  public void initialize(WikiEngine engine, Properties properties) throws WikiException {
    m_engine = engine;
    int cacheSize = TextUtil.getIntegerProperty(properties, PROP_CACHESIZE, -1);

    if (cacheSize == -1) {
      cacheSize =
          TextUtil.getIntegerProperty(
              properties, CachingProvider.PROP_CACHECAPACITY, DEFAULT_CACHESIZE);
    }

    if (cacheSize > 0) {
      m_documentCache = new Cache(true, false, false, false, OSCACHE_ALGORITHM, cacheSize);
    } else {
      log.info("RenderingManager caching is disabled.");
    }

    String renderImplName = properties.getProperty(PROP_RENDERER);
    if (renderImplName == null) {
      renderImplName = DEFAULT_RENDERER;
    }
    Class[] rendererParams = {WikiContext.class, WikiDocument.class};
    try {
      Class c = Class.forName(renderImplName);
      m_rendererConstructor = c.getConstructor(rendererParams);
    } catch (ClassNotFoundException e) {
      log.error("Unable to find WikiRenderer implementation " + renderImplName);
    } catch (SecurityException e) {
      log.error(
          "Unable to access the WikiRenderer(WikiContext,WikiDocument) constructor for "
              + renderImplName);
    } catch (NoSuchMethodException e) {
      log.error(
          "Unable to locate the WikiRenderer(WikiContext,WikiDocument) constructor for "
              + renderImplName);
    }
    if (m_rendererConstructor == null) {
      throw new WikiException("Failed to get WikiRenderer '" + renderImplName + "'.");
    }
    log.info("Rendering content with " + renderImplName + ".");

    WikiEventUtils.addWikiEventListener(m_engine, WikiPageEvent.POST_SAVE_BEGIN, this);
  }
Beispiel #4
0
  /** {@inheritDoc} */
  public String execute(WikiContext context, Map params) throws PluginException {
    //
    //  First, determine which kind of name we use to store in
    //  the WikiContext.
    //
    String countername = (String) params.get(PARAM_NAME);

    if (countername == null) {
      countername = DEFAULT_NAME;
    } else {
      countername = DEFAULT_NAME + "-" + countername;
    }

    //
    //  Fetch the old value
    //
    Integer val = (Integer) context.getVariable(countername);

    if (val == null) {
      val = 0;
    }

    //
    //  Check if we need to reset this
    //

    String start = (String) params.get(PARAM_START);

    if (start != null) {
      val = Integer.parseInt(start);
    } else {
      //
      //  Determine how much to increment
      //
      Object incrementObj = params.get(PARAM_INCREMENT);

      int increment = DEFAULT_INCREMENT;

      if (incrementObj != null) {
        increment = (new Integer((String) incrementObj)).intValue();
      }

      val = val + increment;
    }

    context.setVariable(countername, val);

    //
    // check if we want to hide the result (just count, don't show result on the page
    //
    Object showObj = params.get(PARAM_SHOW_RESULT);

    boolean show = DEFAULT_SHOW_RESULT;

    if (showObj != null) {
      show = TextUtil.isPositive((String) showObj);
    }

    if (show) {
      return val.toString();
    }

    return "";
  }
Beispiel #5
0
  public String execute(WikiContext context, Map params) throws PluginException {
    WikiEngine engine = context.getEngine();
    WikiPage page = context.getPage();

    if (context.getVariable(VAR_ALREADY_PROCESSING) != null) return "Table of Contents";

    StringBuffer sb = new StringBuffer();

    sb.append("<div class=\"toc\">\n");
    sb.append("<div class=\"collapsebox\">\n");

    String title = (String) params.get(PARAM_TITLE);
    if (title != null) {
      sb.append("<h4>" + TextUtil.replaceEntities(title) + "</h4>\n");
    } else {
      sb.append("<h4>Table of Contents</h4>\n");
    }

    // should we use an ordered list?
    m_usingNumberedList = false;
    if (params.containsKey(PARAM_NUMBERED)) {
      String numbered = (String) params.get(PARAM_NUMBERED);
      if (numbered.equalsIgnoreCase("true")) {
        m_usingNumberedList = true;
      } else if (numbered.equalsIgnoreCase("yes")) {
        m_usingNumberedList = true;
      }
    }

    // if we are using a numbered list, get the rest of the parameters (if any) ...
    if (m_usingNumberedList) {
      int start = 0;
      String startStr = (String) params.get(PARAM_START);
      if ((startStr != null) && (startStr.matches("^\\d+$"))) {
        start = Integer.parseInt(startStr);
      }
      if (start < 0) start = 0;

      m_starting = start;
      m_level1Index = start - 1;
      if (m_level1Index < 0) m_level1Index = 0;
      m_level2Index = 0;
      m_level3Index = 0;
      m_prefix = (String) params.get(PARAM_PREFIX);
      if (m_prefix == null) m_prefix = "";
      m_lastLevel = Heading.HEADING_LARGE;
    }

    try {
      String wikiText = engine.getPureText(page);

      context.setVariable(VAR_ALREADY_PROCESSING, "x");
      JSPWikiMarkupParser parser = new JSPWikiMarkupParser(context, new StringReader(wikiText));
      parser.addHeadingListener(this);

      parser.parse();

      sb.append("<ul>\n" + m_buf.toString() + "</ul>\n");
    } catch (IOException e) {
      log.error("Could not construct table of contents", e);
      throw new PluginException("Unable to construct table of contents (see logs)");
    }

    sb.append("</div>\n</div>\n");

    return sb.toString();
  }
  // FIXME: The compiled pattern strings should really be cached somehow.
  public void initialize(WikiContext context, Map params) throws PluginException {
    m_dateFormat = Preferences.getDateFormat(context, TimeFormat.DATETIME);
    m_engine = context.getEngine();
    m_maxwidth = TextUtil.parseIntParameter((String) params.get(PARAM_MAXWIDTH), Integer.MAX_VALUE);
    if (m_maxwidth < 0) m_maxwidth = 0;

    String s = (String) params.get(PARAM_SEPARATOR);

    if (s != null) {
      m_separator = s;
      // pre-2.1.145 there was a separator at the end of the list
      // if they set the parameters, we use the new format of
      // before Item1 after separator before Item2 after separator before Item3 after
      m_after = "";
    }

    s = (String) params.get(PARAM_BEFORE);

    if (s != null) {
      m_before = s;
    }

    s = (String) params.get(PARAM_AFTER);

    if (s != null) {
      m_after = s;
    }

    s = (String) params.get(PARAM_EXCLUDE);

    if (s != null) {
      try {
        PatternCompiler pc = new GlobCompiler();

        String[] ptrns = StringUtils.split(s, ",");

        m_exclude = new Pattern[ptrns.length];

        for (int i = 0; i < ptrns.length; i++) {
          m_exclude[i] = pc.compile(ptrns[i]);
        }
      } catch (MalformedPatternException e) {
        throw new PluginException("Exclude-parameter has a malformed pattern: " + e.getMessage());
      }
    }

    // TODO: Cut-n-paste, refactor
    s = (String) params.get(PARAM_INCLUDE);

    if (s != null) {
      try {
        PatternCompiler pc = new GlobCompiler();

        String[] ptrns = StringUtils.split(s, ",");

        m_include = new Pattern[ptrns.length];

        for (int i = 0; i < ptrns.length; i++) {
          m_include[i] = pc.compile(ptrns[i]);
        }
      } catch (MalformedPatternException e) {
        throw new PluginException("Include-parameter has a malformed pattern: " + e.getMessage());
      }
    }

    // log.debug( "Requested maximum width is "+m_maxwidth );
    s = (String) params.get(PARAM_SHOW);

    if (s != null) {
      if (s.equalsIgnoreCase("count")) {
        m_show = "count";
      }
    }

    s = (String) params.get(PARAM_LASTMODIFIED);

    if (s != null) {
      if (s.equalsIgnoreCase("true")) {
        if (m_show.equals("count")) {
          m_lastModified = true;
        } else {
          throw new PluginException(
              "showLastModified=true is only valid if show=count is also specified");
        }
      }
    }

    initSorter(context, params);
  }
Beispiel #7
0
    /**
     * Count a page hit, present a pages' counter or output a list of pagecounts.
     *
     * @param context
     * @param params
     * @throws com.ecyrd.jspwiki.plugin.PluginException
     * @return String Wiki page snippet
     * @throws PluginException Malformed pattern parameter.
     * @concurrency concurrent
     */
    public String execute(WikiContext context, Map params) throws PluginException {
      WikiEngine engine = context.getEngine();
      WikiPage page = context.getPage();
      String result = STR_EMPTY;

      if (null != page) {
        // get parameters
        String pagename = page.getName();
        String count = (String) params.get(PARAM_COUNT);
        String show = (String) params.get(PARAM_SHOW);
        int entries =
            TextUtil.parseIntParameter((String) params.get(PARAM_MAX_ENTRIES), Integer.MAX_VALUE);
        final int max =
            TextUtil.parseIntParameter((String) params.get(PARAM_MAX_COUNT), Integer.MAX_VALUE);
        final int min =
            TextUtil.parseIntParameter((String) params.get(PARAM_MIN_COUNT), Integer.MIN_VALUE);
        String sort = (String) params.get(PARAM_SORT);
        String body = (String) params.get(PluginManager.PARAM_BODY);
        Pattern[] exclude = compileGlobs(PARAM_EXCLUDE, (String) params.get(PARAM_EXCLUDE));
        Pattern[] include = compileGlobs(PARAM_INCLUDE, (String) params.get(PARAM_INCLUDE));
        Pattern[] refer = compileGlobs(PARAM_REFER, (String) params.get(PARAM_REFER));
        PatternMatcher matcher =
            (null != exclude || null != include || null != refer) ? new Perl5Matcher() : null;
        boolean increment = false;

        // increment counter?
        if (STR_YES.equals(count)) {
          increment = true;
        } else {
          count = null;
        }

        // default increment counter?
        if ((null == show || STR_NONE.equals(show)) && null == count) {
          increment = true;
        }

        // filter on referring pages?
        Collection referrers = null;

        if (null != refer) {
          ReferenceManager refManager = engine.getReferenceManager();

          Iterator iter = refManager.findCreated().iterator();

          while (null != iter && iter.hasNext()) {

            String name = (String) iter.next();
            boolean use = false;

            for (int n = 0; !use && n < refer.length; n++) {
              use = matcher.matches(name, refer[n]);
            }

            if (use) {
              Collection refs = engine.getReferenceManager().findReferrers(name);

              if (null != refs && !refs.isEmpty()) {
                if (null == referrers) {
                  referrers = new HashSet();
                }
                referrers.addAll(refs);
              }
            }
          }
        }

        synchronized (this) {
          Counter counter = (Counter) counters.get(pagename);

          // only count in view mode, keep storage values in sync
          if (increment && WikiContext.VIEW.equalsIgnoreCase(context.getRequestContext())) {
            if (null == counter) {
              counter = new Counter();
              counters.put(pagename, counter);
            }
            counter.increment();
            storage.setProperty(pagename, counter.toString());
            dirty = true;
          }

          if (null == show || STR_NONE.equals(show)) {
            // nothing to show

          } else if (PARAM_COUNT.equals(show)) {
            // show page count
            result = counter.toString();

          } else if (null != body && 0 < body.length() && STR_LIST.equals(show)) {
            // show list of counts
            String header = STR_EMPTY;
            String line = body;
            String footer = STR_EMPTY;
            int start = body.indexOf(STR_SEPARATOR);

            // split body into header, line, footer on ----
            // separator
            if (0 < start) {
              header = body.substring(0, start);

              start = skipWhitespace(start + STR_SEPARATOR.length(), body);

              int end = body.indexOf(STR_SEPARATOR, start);

              if (start >= end) {
                line = body.substring(start);

              } else {
                line = body.substring(start, end);

                end = skipWhitespace(end + STR_SEPARATOR.length(), body);

                footer = body.substring(end);
              }
            }

            // sort on name or count?
            Map sorted = counters;

            if (null != sort && PARAM_COUNT.equals(sort)) {
              sorted = new TreeMap(compareCountDescending);

              sorted.putAll(counters);
            }

            // build a messagebuffer with the list in wiki markup
            StringBuffer buf = new StringBuffer(header);
            MessageFormat fmt = new MessageFormat(line);
            Object[] args = new Object[] {pagename, STR_EMPTY, STR_EMPTY};
            Iterator iter = sorted.entrySet().iterator();

            while (null != iter && 0 < entries && iter.hasNext()) {

              Entry entry = (Entry) iter.next();
              String name = (String) entry.getKey();

              // check minimum count
              final int value = ((Counter) entry.getValue()).getValue();
              boolean use = min <= value && value <= max;

              // did we specify a refer-to page?
              if (use && null != referrers) {

                use = referrers.contains(name);
              }

              // did we specify what pages to include?
              if (use && null != include) {
                use = false;

                for (int n = 0; !use && n < include.length; n++) {

                  use = matcher.matches(name, include[n]);
                }
              }

              // did we specify what pages to exclude?
              if (use && null != exclude) {
                for (int n = 0; use && n < exclude.length; n++) {

                  use &= !matcher.matches(name, exclude[n]);
                }
              }

              if (use) {
                args[1] = engine.beautifyTitle(name);
                args[2] = entry.getValue();

                fmt.format(args, buf, null);

                entries--;
              }
            }
            buf.append(footer);

            // let the engine render the list
            result = engine.textToHTML(context, buf.toString());
          }
        }
      }
      return result;
    }
Beispiel #8
0
  /**
   * Renames a page.
   *
   * @param context The current context.
   * @param renameFrom The name from which to rename.
   * @param renameTo The new name.
   * @param changeReferrers If true, also changes all the referrers.
   * @return The final new name (in case it had to be modified)
   * @throws WikiException If the page cannot be renamed.
   */
  public String renamePage(
      WikiContext context, String renameFrom, String renameTo, boolean changeReferrers)
      throws WikiException {
    //
    //  Sanity checks first
    //
    if (renameFrom == null || renameFrom.length() == 0) {
      throw new WikiException("From name may not be null or empty");
    }
    if (renameTo == null || renameTo.length() == 0) {
      throw new WikiException("To name may not be null or empty");
    }

    //
    //  Clean up the "to" -name so that it does not contain anything illegal
    //

    renameTo = MarkupParser.cleanLink(renameTo.trim());

    if (renameTo.equals(renameFrom)) {
      throw new WikiException("You cannot rename the page to itself");
    }

    //
    //  Preconditions: "from" page must exist, and "to" page must not yet exist.
    //
    WikiEngine engine = context.getEngine();
    WikiPage fromPage = engine.getPage(renameFrom);

    if (fromPage == null) {
      throw new WikiException("No such page " + renameFrom);
    }

    WikiPage toPage = engine.getPage(renameTo);

    if (toPage != null) {
      throw new WikiException("Page already exists " + renameTo);
    }

    //
    //  Options
    //

    m_camelCase =
        TextUtil.getBooleanProperty(
            engine.getWikiProperties(), JSPWikiMarkupParser.PROP_CAMELCASELINKS, m_camelCase);

    Set<String> referrers = getReferencesToChange(fromPage, engine);

    //
    //  Do the actual rename by changing from the frompage to the topage, including
    //  all of the attachments
    //

    engine.getPageManager().getProvider().movePage(renameFrom, renameTo);

    if (engine.getAttachmentManager().attachmentsEnabled()) {
      engine
          .getAttachmentManager()
          .getCurrentProvider()
          .moveAttachmentsForPage(renameFrom, renameTo);
    }

    //
    //  Add a comment to the page notifying what changed.  This adds a new revision
    //  to the repo with no actual change.
    //

    toPage = engine.getPage(renameTo);

    if (toPage == null)
      throw new InternalWikiException(
          "Rename seems to have failed for some strange reason - please check logs!");

    toPage.setAttribute(WikiPage.CHANGENOTE, fromPage.getName() + " ==> " + toPage.getName());
    toPage.setAuthor(context.getCurrentUser().getName());

    engine.getPageManager().putPageText(toPage, engine.getPureText(toPage));

    //
    //  Update the references
    //

    engine.getReferenceManager().pageRemoved(fromPage);
    engine.updateReferences(toPage);

    //
    //  Update referrers
    //
    if (changeReferrers) {
      updateReferrers(context, fromPage, toPage, referrers);
    }

    //
    //  re-index the page
    //
    engine.getSearchManager().reindexPage(toPage);

    Collection<Attachment> attachments = engine.getAttachmentManager().listAttachments(toPage);
    for (Attachment att : attachments) {
      engine.getSearchManager().reindexPage(att);
    }

    //
    //  Done, return the new name.
    //
    return renameTo;
  }
Beispiel #9
0
  private String replaceReferrerString(
      WikiContext context, String sourceText, String from, String to) {
    StringBuilder sb = new StringBuilder(sourceText.length() + 32);

    //
    //  This monstrosity just looks for a JSPWiki link pattern.  But it is pretty
    //  cool for a regexp, isn't it?  If you can understand this in a single reading,
    //  you have way too much time in your hands.
    //
    Pattern linkPattern =
        Pattern.compile("([\\[\\~]?)\\[([^\\|\\]]*)(\\|)?([^\\|\\]]*)(\\|)?([^\\|\\]]*)\\]");

    Matcher matcher = linkPattern.matcher(sourceText);

    int start = 0;

    // System.out.println("====");
    // System.out.println("SRC="+sourceText.trim());
    while (matcher.find(start)) {
      char charBefore = (char) -1;

      if (matcher.start() > 0) charBefore = sourceText.charAt(matcher.start() - 1);

      if (matcher.group(1).length() > 0 || charBefore == '~' || charBefore == '[') {
        //
        //  Found an escape character, so I am escaping.
        //
        sb.append(sourceText.substring(start, matcher.end()));
        start = matcher.end();
        continue;
      }

      String text = matcher.group(2);
      String link = matcher.group(4);
      String attr = matcher.group(6);

      /*
      System.out.println("MATCH="+matcher.group(0));
      System.out.println("   text="+text);
      System.out.println("   link="+link);
      System.out.println("   attr="+attr);
      */
      if (link.length() == 0) {
        text = replaceSingleLink(context, text, from, to);
      } else {
        link = replaceSingleLink(context, link, from, to);

        //
        //  A very simple substitution, but should work for quite a few cases.
        //
        text = TextUtil.replaceString(text, from, to);
      }

      //
      //  Construct the new string
      //
      sb.append(sourceText.substring(start, matcher.start()));
      sb.append("[" + text);
      if (link.length() > 0) sb.append("|" + link);
      if (attr.length() > 0) sb.append("|" + attr);
      sb.append("]");

      start = matcher.end();
    }

    sb.append(sourceText.substring(start));

    return sb.toString();
  }