/* (non-Javadoc)
  * @see org.wikipediacleaner.gui.swing.utils.SwingWorker#construct()
  */
 @Override
 public Object construct() {
   try {
     setText(GT._("Retrieving MediaWiki API"));
     API api = APIFactory.getAPI();
     setText(GT._("Retrieving templates"));
     api.retrieveTemplates(getWikipedia(), page1);
     setText(GT._("Retrieving links in templates"));
     api.retrieveLinks(getWikipedia(), page1.getTemplates());
     setText(GT._("Displaying templates found"));
     for (Page p : page1.getTemplates()) {
       boolean found = false;
       for (Page l : p.getLinks()) {
         if (link1.getTitle().equals(l.getTitle())) {
           found = true;
           break;
         }
       }
       if (found) {
         pages.add(p);
       }
     }
   } catch (APIException e) {
     return e;
   }
   return null;
 }
  /**
   * Create a default popup menu for an internal link.
   * 
   * @param textPane Text pane.
   * @param position Position in the text.
   * @param pageAnalysis Page analysis.
   * @param link Internal link.
   * @return Popup menu.
   */
  protected JPopupMenu createDefaultPopupInternalLink(
      MWPane textPane, int position,
      PageAnalysis pageAnalysis,
      PageElementInternalLink link) {
    if (link == null) {
      return null;
    }

    // Initialization
    Page page = DataManager.getPage(wikipedia, link.getLink(), null, null, null);

    // Menu creation
    BasicMenuCreator menu = new BasicMenuCreator();
    JPopupMenu popup = menu.createPopupMenu(GT._(
        "Page: {0}",
        limitTextLength(page.getTitle(), 50)));
    menu.addCurrentChapter(popup, position, pageAnalysis);
    menu.addSeparator(popup);
    menu.addView(wikipedia, popup, page, false);
    menu.addAnalyze(wikipedia, popup, page);
    menu.addDisambiguation(wikipedia, popup, page);
    menu.addSeparator(popup);
    menu.addItemRemoveLink(
        popup, link.getDisplayedText(),
        textPane, link.getBeginIndex(), link.getEndIndex());

    return popup;
  }
  /**
   * Create a default popup menu for a category.
   * 
   * @param textPane Text pane.
   * @param position Position in the text.
   * @param pageAnalysis Page analysis.
   * @param category Category.
   * @return Popup menu.
   */
  protected JPopupMenu createDefaultPopupCategory(
      MWPane textPane, int position,
      PageAnalysis pageAnalysis,
      PageElementCategory category) {
    if (category == null) {
      return null;
    }

    // Initialization
    String fullName = wikipedia.getWikiConfiguration().getPageTitle(
        Namespace.CATEGORY,
        category.getName());
    Page page = DataManager.getPage(wikipedia, fullName, null, null, null);

    // Menu creation
    BasicMenuCreator menu = new BasicMenuCreator();
    JPopupMenu popup = menu.createPopupMenu(GT._(
        "Category: {0}",
        limitTextLength(category.getName(), 50)));
    menu.addCurrentChapter(popup, position, pageAnalysis);
    menu.addSeparator(popup);
    menu.addView(wikipedia, popup, page, false);
    menu.addAnalyze(wikipedia, popup, page);

    return popup;
  }
  /**
   * Create a default popup menu for a template.
   * 
   * @param pageAnalysis Page analysis.
   * @param position Position in the text.
   * @param template Template.
   * @return Popup menu.
   */
  protected JPopupMenu createDefaultPopupTemplate(
      PageAnalysis pageAnalysis, int position,
      PageElementTemplate template) {
    if (template == null) {
      return null;
    }

    // Initialization
    String fullName = wikipedia.getWikiConfiguration().getPageTitle(
        Namespace.TEMPLATE,
        template.getTemplateName());
    Page page = DataManager.getPage(wikipedia, fullName, null, null, null);

    // Menu creation
    BasicMenuCreator menu = new BasicMenuCreator();
    JPopupMenu popup = menu.createPopupMenu(GT._(
        "Template: {0}",
        limitTextLength(template.getTemplateName(), 50)));
    menu.addCurrentChapter(popup, position, pageAnalysis);

    // Search engines
    Map<String, List<SearchEngine>> searchEngines = SearchEngine.getSearchEngines(
        wikipedia, template, null);
    if ((searchEngines != null) && !searchEngines.isEmpty()) {
      menu.addSeparator(popup);
      List<String> parameterNames = new ArrayList<>(searchEngines.keySet());
      Collections.sort(parameterNames);
      for (String parameterName : parameterNames) {
        JMenu submenu = new JMenu(GT._("Search using {0}", parameterName));
        for (SearchEngine searchEngine : searchEngines.get(parameterName)) {
          menu.addItemView(null, submenu, searchEngine.getUrl(), searchEngine.getName());
        }
        menu.addSubmenu(popup, submenu, 0, 0);
      }
    }

    // General items
    menu.addSeparator(popup);
    menu.addCheckTemplate(wikipedia, window.getParentComponent(), popup, template);
    menu.addView(wikipedia, popup, page, false);
    menu.addAnalyze(wikipedia, popup, page);

    return popup;
  }
 /**
  * Return the parameters used to configure the algorithm.
  * 
  * @return Map of parameters (Name -> description).
  */
 @Override
 public Map<String, String> getParameters() {
   Map<String, String> parameters = super.getParameters();
   parameters.put("template", GT._(
       "A template that can be used instead of the link to an other language. " +
       "It must be specified as: " +
         "<template name>|" +
         "<param name for local page name>|" +
         "<param name for code of other language>|" +
         "<param name for page name in other language>|" +
         "<param name for displayed text>").replaceAll("\\<", "&lt;").replaceAll("\\>", "&gt;"));
   return parameters;
 }
  /**
   * Create a default popup menu for a parameter.
   * 
   * @param pageAnalysis Page analysis.
   * @param position Position in the text.
   * @param parameter Parameter.
   * @return Popup menu.
   */
  protected JPopupMenu createDefaultPopupParameter(
      PageAnalysis pageAnalysis, int position,
      PageElementParameter parameter) {
    if (parameter == null) {
      return null;
    }

    // Menu creation
    BasicMenuCreator menu = new BasicMenuCreator();
    JPopupMenu popup = menu.createPopupMenu(GT._(
        "Parameter: {0}",
        limitTextLength(parameter.getParameterName(), 50)));
    menu.addCurrentChapter(popup, position, pageAnalysis);

    return popup;
  }
  /**
   * Create a default popup menu for a function.
   * 
   * @param pageAnalysis Page analysis.
   * @param position Position in the text.
   * @param function Function.
   * @return Popup menu.
   */
  protected JPopupMenu createDefaultPopupFunction(
      PageAnalysis pageAnalysis, int position,
      PageElementFunction function) {
    if (function == null) {
      return null;
    }

    // Menu creation
    BasicMenuCreator menu = new BasicMenuCreator();
    JPopupMenu popup = menu.createPopupMenu(GT._(
        "Function: {0}",
        limitTextLength(function.getFunctionName(), 50)));
    menu.addCurrentChapter(popup, position, pageAnalysis);

    return popup;
  }
  /**
   * Create a default popup menu for an ISSN.
   * 
   * @param pageAnalysis Page analysis.
   * @param position Position in the text.
   * @param issn ISSN.
   * @return Popup menu.
   */
  protected JPopupMenu createDefaultPopupISSN(
      PageAnalysis pageAnalysis, int position,
      PageElementISSN issn) {
    if (issn == null) {
      return null;
    }

    // Menu creation
    BasicMenuCreator menu = new BasicMenuCreator();
    JPopupMenu popup = menu.createPopupMenu(GT._(
        "ISSN: {0}",
        limitTextLength(issn.getISSN(), 50)));
    menu.addCurrentChapter(popup, position, pageAnalysis);

    return popup;
  }
  /**
   * Create a default popup menu for an interwiki link.
   * 
   * @param textPane Text pane.
   * @param position Position in the text.
   * @param pageAnalysis Page analysis.
   * @param link Interwiki link.
   * @return Popup menu.
   */
  protected JPopupMenu createDefaultPopupInterwikiLink(
      MWPane textPane, int position,
      PageAnalysis pageAnalysis,
      PageElementInterwikiLink link) {
    if (link == null) {
      return null;
    }

    // Menu creation
    BasicMenuCreator menu = new BasicMenuCreator();
    JPopupMenu popup = menu.createPopupMenu(GT._(
        "Interwiki: {0}",
        limitTextLength(link.getInterwikiText() + ":" + link.getLink(), 50)));
    menu.addCurrentChapter(popup, position, pageAnalysis);

    return popup;
  }
  /**
   * @return Window components.
   */
  @Override
  protected Component createComponents() {
    JPanel panel = new JPanel(new GridBagLayout());

    // Initialize constraints
    GridBagConstraints constraints = new GridBagConstraints();
    constraints.fill = GridBagConstraints.HORIZONTAL;
    constraints.gridheight = 1;
    constraints.gridwidth = 1;
    constraints.gridx = 0;
    constraints.gridy = 0;
    constraints.insets = new Insets(0, 0, 0, 0);
    constraints.ipadx = 0;
    constraints.ipady = 0;
    constraints.weightx = 1;
    constraints.weighty = 0;

    // Label
    JLabel label = Utilities.createJLabel(GT._(
        "Templates used in {0}, linking to {1}",
        new Object[] { page.getTitle(), link.getTitle() }));
    panel.add(label, constraints);
    constraints.gridy++;

    // Menu
    modelLinks = new PageListModel();
    modelLinks.setShowDisambiguation(true);
    modelLinks.setShowOther(true);

    // Links
    constraints.fill = GridBagConstraints.BOTH;
    constraints.weighty = 1;
    listLinks = new JList<Page>(modelLinks);
    listLinks.setCellRenderer(new PageListCellRenderer());
    listLinks.addMouseListener(new BasicPageListPopupListener(getWikipedia(), null, listLinks, this));
    listLinks.addMouseListener(new PageListAnalyzeListener(getWikipedia(), null));
    JScrollPane scrollLinks = new JScrollPane(listLinks);
    scrollLinks.setMinimumSize(new Dimension(100, 100));
    scrollLinks.setPreferredSize(new Dimension(200, 500));
    scrollLinks.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    panel.add(scrollLinks, constraints);
    constraints.gridy++;

    return panel;
  }
  /**
   * Create a default popup menu for an external link.
   * 
   * @param pageAnalysis Page analysis.
   * @param position Position in the text.
   * @param link External link.
   * @return Popup menu.
   */
  protected JPopupMenu createDefaultPopupExternalLink(
      PageAnalysis pageAnalysis, int position,
      PageElementExternalLink link) {
    if (link == null) {
      return null;
    }

    // Menu creation
    BasicMenuCreator menu = new BasicMenuCreator();
    JPopupMenu popup = menu.createPopupMenu(GT._(
        "External link: {0}",
        limitTextLength(link.getLink(), 50)));
    menu.addCurrentChapter(popup, position, pageAnalysis);
    menu.addSeparator(popup);
    menu.addItemView(null, popup, link.getLink());

    return popup;
  }
  /**
   * Create a default popup menu for an ISBN.
   * 
   * @param pageAnalysis Page analysis.
   * @param position Position in the text.
   * @param isbn ISBN.
   * @return Popup menu.
   */
  protected JPopupMenu createDefaultPopupISBN(
      PageAnalysis pageAnalysis, int position,
      PageElementISBN isbn) {
    if (isbn == null) {
      return null;
    }

    // Menu creation
    BasicMenuCreator menu = new BasicMenuCreator();
    JPopupMenu popup = menu.createPopupMenu(GT._(
        "ISBN: {0}",
        limitTextLength(isbn.getISBN(), 50)));
    ISBNInformation infos = ISBNRange.getInformation(isbn.getISBN());
    if ((infos != null) && (infos.getTexts() != null)) {
      for (String info : infos.getTexts()) {
        menu.addDisabledText(popup, info);
      }
    }
    menu.addCurrentChapter(popup, position, pageAnalysis);

    return popup;
  }
Beispiel #13
0
 @Override
 public String toString() {
   return GT._("Template");
 }
  /**
   * Analyze a page to check if errors are present.
   * 
   * @param analysis Page analysis.
   * @param errors Errors found in the page.
   * @param onlyAutomatic True if analysis could be restricted to errors automatically fixed.
   * @return Flag indicating if the error was found.
   */
  @Override
  public boolean analyze(
      PageAnalysis analysis,
      Collection<CheckErrorResult> errors,
      boolean onlyAutomatic) {
    if (analysis == null) {
      return false;
    }

    // Retrieve possible templates to replace the link to other language
    List<String> templatesList = getTemplatesList();

    // Analyzing the text from the beginning
    boolean result = false;
    EnumWikipedia toWiki = analysis.getWikipedia();
    for (PageElementInterwikiLink link : analysis.getInterwikiLinks()) {
      if (isLanguageLink(link, toWiki)) {
        if (errors == null) {
          return true;
        }
        result = true;
        CheckErrorResult errorResult = createCheckErrorResult(
            analysis, link.getBeginIndex(), link.getEndIndex());
        String lgCode = link.getInterwiki().getPrefix();
        EnumWikipedia fromWiki = EnumWikipedia.getWikipedia(lgCode);
        if ((fromWiki != null) && (fromWiki.getSettings().getCode().equals(lgCode))) {
          String pageTitle = link.getLink();
          errorResult.addPossibleAction(
              GT._("Check language links"),
              new CheckLanguageLinkActionProvider(
                  fromWiki, toWiki,
                  pageTitle, link.getText()));
          if ((templatesList != null) && (templatesList.size() > 0)) {
            for (String template : templatesList) {
              String[] templateArgs = template.split("\\|");
              if (templateArgs.length >= 5) {

                // Compute order of parameters
                List<String> order = new ArrayList<>();
                if (templateArgs.length >= 6) {
                  String[] tmpOrder = templateArgs[5].split(",");
                  for (String tmp : tmpOrder) {
                    order.add(tmp);
                  }
                }
                for (int numParam = 1; numParam <= 4; numParam++) {
                  if (!order.contains(templateArgs[numParam])) {
                    order.add(templateArgs[numParam]);
                  }
                }

                StringBuilder prefix = new StringBuilder();
                StringBuilder suffix = new StringBuilder();
                prefix.append("{{");
                prefix.append(templateArgs[0]);
                boolean localTitle = false;
                for (String param : order) {
                  if (param.equals(templateArgs[1])) {
                    prefix.append("|");
                    prefix.append(templateArgs[1]);
                    prefix.append("=");
                    localTitle = true;
                  } else {
                    String value = "";
                    if (param.equals(templateArgs[2])) {
                      value = lgCode;
                    } else if (param.equals(templateArgs[3])) {
                      value = pageTitle;
                    } else if (param.equals(templateArgs[4])) {
                      value = (link.getText() != null) ? link.getText() : pageTitle;
                    }
                    StringBuilder buffer = localTitle ? suffix : prefix;
                    buffer.append("|");
                    buffer.append(param);
                    buffer.append("=");
                    if (value != null) {
                      buffer.append(value);
                    }
                  }
                }
                suffix.append("}}");
                String question = GT._("What is the title of the page on this wiki ?");
                AddTextActionProvider action = null;
                if ((link.getText() != null) && (!link.getText().equals(pageTitle))) {
                  String[] possibleValues = { null, pageTitle, link.getText() };
                  action = new AddTextActionProvider(
                      prefix.toString(), suffix.toString(), null, question,
                      possibleValues, false, null, checker);
                } else {
                  action = new AddTextActionProvider(
                      prefix.toString(), suffix.toString(), null, question,
                      pageTitle, checker);
                }
                errorResult.addPossibleAction(
                    GT._("Replace using template {0}", "{{" + templateArgs[0] + "}}"),
                    action);
              }
            }
          }
          errorResult.addPossibleAction(
              GT._("External Viewer"),
              new BasicActionProvider(
                  new ActionExternalViewer(fromWiki, pageTitle)));
        }
        errors.add(errorResult);
      }
    }

    return result;
  }
/**
 * Algorithm for analyzing error 68 of check wikipedia project.
 * Error 68: Link to other language
 */
public class CheckErrorAlgorithm068 extends CheckErrorAlgorithmBase {

  /**
   * String checker for text inputed by user.
   */
  private final StringChecker checker;

  /**
   * Possible global fixes.
   */
  private final static String[] globalFixes = new String[] {
    GT._("Check all links to other language"),
  };

  public CheckErrorAlgorithm068() {
    super("Link to other language");
    checker = new StringCheckerUnauthorizedCharacters("[]\"");
  }

  /**
   * @return Possible templates to replace the link to an other language.
   */
  private List<String> getTemplatesList() {
    String templatesParam = getSpecificProperty(
        "template", true, false, false);
    List<String> templatesList = null;
    if (templatesParam != null) {
      templatesList = WPCConfiguration.convertPropertyToStringList(templatesParam);
    }
    return templatesList;
  }

  /**
   * @param link Interwiki link.
   * @param wiki Current wiki.
   * @return True if the interwiki link is a link to an other language.
   */
  private boolean isLanguageLink(PageElementInterwikiLink link, EnumWikipedia wiki) {
    if ((link != null) &&
        (link.getInterwiki() != null) &&
        (link.getInterwiki().getLanguage() != null) &&
        (!link.getInterwikiText().equals(wiki.getSettings().getCode()))) {
      return true;
    }
    return false;
  }

  /**
   * Analyze a page to check if errors are present.
   * 
   * @param analysis Page analysis.
   * @param errors Errors found in the page.
   * @param onlyAutomatic True if analysis could be restricted to errors automatically fixed.
   * @return Flag indicating if the error was found.
   */
  @Override
  public boolean analyze(
      PageAnalysis analysis,
      Collection<CheckErrorResult> errors,
      boolean onlyAutomatic) {
    if (analysis == null) {
      return false;
    }

    // Retrieve possible templates to replace the link to other language
    List<String> templatesList = getTemplatesList();

    // Analyzing the text from the beginning
    boolean result = false;
    EnumWikipedia toWiki = analysis.getWikipedia();
    for (PageElementInterwikiLink link : analysis.getInterwikiLinks()) {
      if (isLanguageLink(link, toWiki)) {
        if (errors == null) {
          return true;
        }
        result = true;
        CheckErrorResult errorResult = createCheckErrorResult(
            analysis, link.getBeginIndex(), link.getEndIndex());
        String lgCode = link.getInterwiki().getPrefix();
        EnumWikipedia fromWiki = EnumWikipedia.getWikipedia(lgCode);
        if ((fromWiki != null) && (fromWiki.getSettings().getCode().equals(lgCode))) {
          String pageTitle = link.getLink();
          errorResult.addPossibleAction(
              GT._("Check language links"),
              new CheckLanguageLinkActionProvider(
                  fromWiki, toWiki,
                  pageTitle, link.getText()));
          if ((templatesList != null) && (templatesList.size() > 0)) {
            for (String template : templatesList) {
              String[] templateArgs = template.split("\\|");
              if (templateArgs.length >= 5) {

                // Compute order of parameters
                List<String> order = new ArrayList<>();
                if (templateArgs.length >= 6) {
                  String[] tmpOrder = templateArgs[5].split(",");
                  for (String tmp : tmpOrder) {
                    order.add(tmp);
                  }
                }
                for (int numParam = 1; numParam <= 4; numParam++) {
                  if (!order.contains(templateArgs[numParam])) {
                    order.add(templateArgs[numParam]);
                  }
                }

                StringBuilder prefix = new StringBuilder();
                StringBuilder suffix = new StringBuilder();
                prefix.append("{{");
                prefix.append(templateArgs[0]);
                boolean localTitle = false;
                for (String param : order) {
                  if (param.equals(templateArgs[1])) {
                    prefix.append("|");
                    prefix.append(templateArgs[1]);
                    prefix.append("=");
                    localTitle = true;
                  } else {
                    String value = "";
                    if (param.equals(templateArgs[2])) {
                      value = lgCode;
                    } else if (param.equals(templateArgs[3])) {
                      value = pageTitle;
                    } else if (param.equals(templateArgs[4])) {
                      value = (link.getText() != null) ? link.getText() : pageTitle;
                    }
                    StringBuilder buffer = localTitle ? suffix : prefix;
                    buffer.append("|");
                    buffer.append(param);
                    buffer.append("=");
                    if (value != null) {
                      buffer.append(value);
                    }
                  }
                }
                suffix.append("}}");
                String question = GT._("What is the title of the page on this wiki ?");
                AddTextActionProvider action = null;
                if ((link.getText() != null) && (!link.getText().equals(pageTitle))) {
                  String[] possibleValues = { null, pageTitle, link.getText() };
                  action = new AddTextActionProvider(
                      prefix.toString(), suffix.toString(), null, question,
                      possibleValues, false, null, checker);
                } else {
                  action = new AddTextActionProvider(
                      prefix.toString(), suffix.toString(), null, question,
                      pageTitle, checker);
                }
                errorResult.addPossibleAction(
                    GT._("Replace using template {0}", "{{" + templateArgs[0] + "}}"),
                    action);
              }
            }
          }
          errorResult.addPossibleAction(
              GT._("External Viewer"),
              new BasicActionProvider(
                  new ActionExternalViewer(fromWiki, pageTitle)));
        }
        errors.add(errorResult);
      }
    }

    return result;
  }

  /**
   * Return the parameters used to configure the algorithm.
   * 
   * @return Map of parameters (Name -> description).
   */
  @Override
  public Map<String, String> getParameters() {
    Map<String, String> parameters = super.getParameters();
    parameters.put("template", GT._(
        "A template that can be used instead of the link to an other language. " +
        "It must be specified as: " +
          "<template name>|" +
          "<param name for local page name>|" +
          "<param name for code of other language>|" +
          "<param name for page name in other language>|" +
          "<param name for displayed text>").replaceAll("\\<", "&lt;").replaceAll("\\>", "&gt;"));
    return parameters;
  }

  /**
   * @return List of possible global fixes.
   */
  @Override
  public String[] getGlobalFixes() {
    return globalFixes;
  }

  /**
   * Fix all the errors in the page.
   * 
   * @param fixName Fix name (extracted from getGlobalFixes()).
   * @param analysis Page analysis.
   * @param textPane Text pane.
   * @return Page contents after fix.
   */
  @Override
  public String fix(String fixName, PageAnalysis analysis, MWPane textPane) {

    // Initialize
    API api = APIFactory.getAPI();
    StringBuilder tmpContents = new StringBuilder();
    int currentIndex = 0;

    // Manage templates that can be used to replace a link to an other language
    List<String> templatesList = getTemplatesList();
    String[] templateArgs = null;
    if ((templatesList != null) && (templatesList.size() > 0)) {
      String[] tmp = templatesList.get(0).split("\\|");
      if (tmp.length >= 5) {
        templateArgs = tmp;
      }
    }

    // Check all internal links
    Object highlight = null;
    String contents = analysis.getContents();
    try {
      EnumWikipedia toWiki = analysis.getWikipedia();
      for (PageElementInterwikiLink link : analysis.getInterwikiLinks()) {
        if (isLanguageLink(link, toWiki)) {
          String lgCode = link.getInterwiki().getPrefix();
          EnumWikipedia fromWiki = EnumWikipedia.getWikipedia(lgCode);
          if ((fromWiki != null) && (fromWiki.getSettings().getCode().equals(lgCode))) {
            String pageTitle = link.getLink();
            int beginIndex = link.getBeginIndex();
            int endIndex = link.getEndIndex();
            String replacement = null;

            // Display selection
            highlight = addHighlight(textPane, beginIndex, endIndex);
            textPane.select(beginIndex, endIndex);

            // Check for language link
            String toTitle = api.getLanguageLink(fromWiki, toWiki, pageTitle);
            if (toTitle != null) {

              // List possible replacements
              List<String> possibleValues = new ArrayList<String>();
              String possible = null;
              possible = PageElementInternalLink.createInternalLink(toTitle, link.getText());
              if (!possibleValues.contains(possible)) {
                possibleValues.add(possible);
              }
              possible = PageElementInternalLink.createInternalLink(toTitle, link.getFullLink());
              if (!possibleValues.contains(possible)) {
                possibleValues.add(possible);
              }
              possible = PageElementInternalLink.createInternalLink(toTitle, null);
              if (!possibleValues.contains(possible)) {
                possibleValues.add(possible);
              }
              possibleValues.add(GT._("Do not replace"));
              possibleValues.add(GT._("Cancel"));

              // Ask user what replacement to use
              String message = GT._(
                  "The page \"{0}\" in \"{1}\" has a language link to \"{2}\": {3}.\n" +
                  "With what text do you want to replace the link ?",
                  new Object[] { pageTitle, fromWiki, toWiki, toTitle } );
              int answer = Utilities.displayQuestion(
                  textPane.getParent(), message,
                  possibleValues.toArray());
              if ((answer < 0) || (answer >= possibleValues.size() - 1)) {
                break;
              } else if (answer < possibleValues.size() - 2) {
                replacement = possibleValues.get(answer);
              }
            } else if (templateArgs != null) {
              String message =
                  GT._("The page \"{0}\" in \"{1}\" doesn''t have a language link to \"{2}\".",
                       new Object[] { pageTitle, fromWiki, toWiki }) +"\n" +
                  GT._("You can replace the link using template {0}.",
                       "{{" + templateArgs[0] + "}}") + "\n" +
                  GT._("What is the title of the page on this wiki ?");
              if ((link.getText() != null) && (!link.getText().equals(pageTitle))) {
                toTitle = Utilities.askForValue(
                    textPane.getParent(), message, link.getText(), checker);
              } else {
                toTitle = Utilities.askForValue(
                    textPane.getParent(), message, pageTitle, checker);
              }
              if (toTitle != null) {
                replacement =
                    "{{" + templateArgs[0] +
                    "|" + templateArgs[1] + "=" + toTitle +
                    "|" + templateArgs[2] + "=" + lgCode +
                    "|" + templateArgs[3] + "=" + pageTitle +
                    "|" + templateArgs[4] + "=" + ((link.getText() != null) ? link.getText() : pageTitle) +
                    "}}";
              }
            }

            // Do the replacement
            if (replacement != null) {
              if (currentIndex < link.getBeginIndex()) {
                tmpContents.append(contents.substring(currentIndex, link.getBeginIndex()));
              }
              tmpContents.append(replacement);
              currentIndex = link.getEndIndex();
            }
            removeHighlight(textPane, highlight);
            highlight = null;
          }
        }
      }
    } catch (APIException e) {
      //
    }
    removeHighlight(textPane, highlight);
    highlight = null;

    // Return result
    if (currentIndex == 0) {
      return contents;
    }
    if (currentIndex < contents.length()) {
      tmpContents.append(contents.substring(currentIndex));
    }
    return tmpContents.toString();
  }
}
Beispiel #16
0
 @Override
 public String toString() {
   return GT._("Namespace");
 }
 /* (non-Javadoc)
  * @see org.wikipediacleaner.gui.swing.basic.BasicWindow#getTitle()
  */
 @Override
 public String getTitle() {
   return GT._("Templates in {0}", link.getTitle());
 }
Beispiel #18
0
 @Override
 public String toString() {
   return GT._("Title");
 }
Beispiel #19
0
 @Override
 public String toString() {
   return GT._("Revision Id");
 }
Beispiel #20
0
 @Override
 public String toString() {
   return GT._("Page Id");
 }
  /**
   * Fix all the errors in the page.
   * 
   * @param fixName Fix name (extracted from getGlobalFixes()).
   * @param analysis Page analysis.
   * @param textPane Text pane.
   * @return Page contents after fix.
   */
  @Override
  public String fix(String fixName, PageAnalysis analysis, MWPane textPane) {

    // Initialize
    API api = APIFactory.getAPI();
    StringBuilder tmpContents = new StringBuilder();
    int currentIndex = 0;

    // Manage templates that can be used to replace a link to an other language
    List<String> templatesList = getTemplatesList();
    String[] templateArgs = null;
    if ((templatesList != null) && (templatesList.size() > 0)) {
      String[] tmp = templatesList.get(0).split("\\|");
      if (tmp.length >= 5) {
        templateArgs = tmp;
      }
    }

    // Check all internal links
    Object highlight = null;
    String contents = analysis.getContents();
    try {
      EnumWikipedia toWiki = analysis.getWikipedia();
      for (PageElementInterwikiLink link : analysis.getInterwikiLinks()) {
        if (isLanguageLink(link, toWiki)) {
          String lgCode = link.getInterwiki().getPrefix();
          EnumWikipedia fromWiki = EnumWikipedia.getWikipedia(lgCode);
          if ((fromWiki != null) && (fromWiki.getSettings().getCode().equals(lgCode))) {
            String pageTitle = link.getLink();
            int beginIndex = link.getBeginIndex();
            int endIndex = link.getEndIndex();
            String replacement = null;

            // Display selection
            highlight = addHighlight(textPane, beginIndex, endIndex);
            textPane.select(beginIndex, endIndex);

            // Check for language link
            String toTitle = api.getLanguageLink(fromWiki, toWiki, pageTitle);
            if (toTitle != null) {

              // List possible replacements
              List<String> possibleValues = new ArrayList<String>();
              String possible = null;
              possible = PageElementInternalLink.createInternalLink(toTitle, link.getText());
              if (!possibleValues.contains(possible)) {
                possibleValues.add(possible);
              }
              possible = PageElementInternalLink.createInternalLink(toTitle, link.getFullLink());
              if (!possibleValues.contains(possible)) {
                possibleValues.add(possible);
              }
              possible = PageElementInternalLink.createInternalLink(toTitle, null);
              if (!possibleValues.contains(possible)) {
                possibleValues.add(possible);
              }
              possibleValues.add(GT._("Do not replace"));
              possibleValues.add(GT._("Cancel"));

              // Ask user what replacement to use
              String message = GT._(
                  "The page \"{0}\" in \"{1}\" has a language link to \"{2}\": {3}.\n" +
                  "With what text do you want to replace the link ?",
                  new Object[] { pageTitle, fromWiki, toWiki, toTitle } );
              int answer = Utilities.displayQuestion(
                  textPane.getParent(), message,
                  possibleValues.toArray());
              if ((answer < 0) || (answer >= possibleValues.size() - 1)) {
                break;
              } else if (answer < possibleValues.size() - 2) {
                replacement = possibleValues.get(answer);
              }
            } else if (templateArgs != null) {
              String message =
                  GT._("The page \"{0}\" in \"{1}\" doesn''t have a language link to \"{2}\".",
                       new Object[] { pageTitle, fromWiki, toWiki }) +"\n" +
                  GT._("You can replace the link using template {0}.",
                       "{{" + templateArgs[0] + "}}") + "\n" +
                  GT._("What is the title of the page on this wiki ?");
              if ((link.getText() != null) && (!link.getText().equals(pageTitle))) {
                toTitle = Utilities.askForValue(
                    textPane.getParent(), message, link.getText(), checker);
              } else {
                toTitle = Utilities.askForValue(
                    textPane.getParent(), message, pageTitle, checker);
              }
              if (toTitle != null) {
                replacement =
                    "{{" + templateArgs[0] +
                    "|" + templateArgs[1] + "=" + toTitle +
                    "|" + templateArgs[2] + "=" + lgCode +
                    "|" + templateArgs[3] + "=" + pageTitle +
                    "|" + templateArgs[4] + "=" + ((link.getText() != null) ? link.getText() : pageTitle) +
                    "}}";
              }
            }

            // Do the replacement
            if (replacement != null) {
              if (currentIndex < link.getBeginIndex()) {
                tmpContents.append(contents.substring(currentIndex, link.getBeginIndex()));
              }
              tmpContents.append(replacement);
              currentIndex = link.getEndIndex();
            }
            removeHighlight(textPane, highlight);
            highlight = null;
          }
        }
      }
    } catch (APIException e) {
      //
    }
    removeHighlight(textPane, highlight);
    highlight = null;

    // Return result
    if (currentIndex == 0) {
      return contents;
    }
    if (currentIndex < contents.length()) {
      tmpContents.append(contents.substring(currentIndex));
    }
    return tmpContents.toString();
  }
 /**
  * @return Map of parameters (Name -> description).
  * @see org.wikipediacleaner.api.check.algorithm.CheckErrorAlgorithmBase#getParameters()
  */
 @Override
 public Map<String, String> getParameters() {
   Map<String, String> parameters = super.getParameters();
   parameters.put("category", GT._("A category containing the list of pages in error"));
   return parameters;
 }
Beispiel #23
0
  /**
   * @param isbn ISBN.
   * @return Information about ISBN.
   */
  public static ISBNInformation getInformation(String isbn) {
    if (isbn == null) {
      return null;
    }

    // Retrieve information about ISBN
    isbn = PageElementISBN.cleanISBN(isbn);
    boolean isbn10 = false;
    if (isbn.length() == 10) {
      isbn = "978" + isbn;
      isbn10 = true;
    }
    Range eanPrefix = getEANPrefix(isbn);
    Range registrationGroup = getRegistrationGroup(isbn);

    // Build information
    ISBNInformation isbnInfo = new ISBNInformation();
    if ((eanPrefix != null) && !isbn10) {
      isbnInfo.texts.add(eanPrefix.getPrefix() + " - " + eanPrefix.getAgency());
    }
    String prefix = null;
    String cleanPrefix = null;
    if (registrationGroup != null) {
      prefix = registrationGroup.getPrefix();
      cleanPrefix = registrationGroup.getCleanPrefix();
      if (isbn10 && (prefix != null) && (prefix.length() > 4)) {
        // Remove "978-"
        prefix = prefix.substring(4);
      }
      if ((prefix != null) && (prefix.length() > 0)) {
        isbnInfo.texts.add(prefix + "-" + registrationGroup.getAgency());
      }
    }

    // Suggest a formatted ISBN
    if ((registrationGroup != null) && (cleanPrefix != null)) {
      String suffix = isbn.substring(cleanPrefix.length());
      Rule rule = registrationGroup.getRule(suffix);
      if (rule == null) {
        isbnInfo.texts.add(GT._("No range found for ISBN"));
        isbnInfo.unknownRange = true;
      } else {
        int nextLength = rule.getLength();
        if (nextLength > 0) {
          if (suffix.length() > nextLength + 1) {
            String suggestedISBN = prefix + "-" +
                suffix.substring(0, nextLength) + "-" +
                suffix.substring(nextLength, suffix.length() - 1) + "-" +
                suffix.substring(suffix.length() - 1);
            isbnInfo.texts.add(GT._("Suggested format: {0}", suggestedISBN));
          } else {
            isbnInfo.texts.add(GT._("ISBN length incoherent with range found"));
          }
        } else {
          isbnInfo.texts.add(GT._(
              "ISBN is in a reserved range {0}",
              prefix + "-(" + rule.getFrom() + "-" + rule.getTo() + ")"));
          isbnInfo.reservedRange = true;
        }
      }
    } else {
      isbnInfo.texts.add(GT._("No range found for ISBN"));
      isbnInfo.unknownRange = true;
    }

    return isbnInfo;
  }
Beispiel #24
0
 @Override
 public String toString() {
   return GT._("Redirect");
 }
Beispiel #25
0
  /**
   * Replace text in a list of pages.
   * 
   * @param pages List of pages.
   * @param replacements List of text replacements
   *        Key: Additional comments used for the modification.
   *        Value: Text replacements.
   * @param wiki Wiki.
   * @param comment Comment used for the modification.
   * @param description (Out) description of changes made.
   * @param automaticCW True if automatic Check Wiki fixing should be done also.
   * @param save True if modification should be saved.
   * @return Count of modified pages.
   * @throws APIException
   */
  public int replaceText(
      Page[] pages, Map<String, List<AutomaticFixing>> replacements,
      EnumWikipedia wiki, String comment,
      StringBuilder description,
      boolean automaticCW, boolean save,
      boolean updateDabWarning) throws APIException {
    if ((pages == null) || (replacements == null) || (replacements.size() == 0)) {
      return 0;
    }
    UpdateDabWarningTools dabWarnings = new UpdateDabWarningTools(wiki, null, false, false);
    for (Page page : pages) {
      retrieveContents(wiki, page, false, true, false, true, false); // TODO: withRedirects=false ?
    }
    int count = 0;
    final API api = APIFactory.getAPI();
    StringBuilder details = new StringBuilder();
    Configuration config = Configuration.getConfiguration();
    boolean secured = config.getBoolean(null, ConfigurationValueBoolean.SECURE_URL);
    while (hasRemainingTask() && !shouldStop()) {
      Object result = getNextResult();
      if ((result != null) && (result instanceof Page)) {
        boolean changed = false;
        List<String> replacementsDone = new ArrayList<String>();
        Page page = (Page) result;
        String oldContents = page.getContents();
        if (oldContents != null) {
          String newContents = oldContents;
          details.setLength(0);
          for (Entry<String, List<AutomaticFixing>> replacement : replacements.entrySet()) {
            replacementsDone.clear();
            String tmpContents = AutomaticFixing.apply(replacement.getValue(), newContents, replacementsDone);
            if (!newContents.equals(tmpContents)) {
              newContents = tmpContents;

              // Update description
              if (description != null) {
                if (!changed) {
                  String title =
                    "<a href=\"" + wiki.getSettings().getURL(page.getTitle(), false, secured) + "\">" +
                    page.getTitle() + "</a>";
                  description.append(GT._("Page {0}:", title));
                  description.append("\n");
                  description.append("<ul>\n");
                  changed = true;
                }
                for (String replacementDone : replacementsDone) {
                  description.append("<li>");
                  description.append(replacementDone);
                  description.append("</li>\n");
                }
              }

              // Memorize replacement
              if ((replacement.getKey() != null) && (replacement.getKey().length() > 0)) {
                if (details.length() > 0) {
                  details.append(", ");
                }
                details.append(replacement.getKey());
              }
            }
          }

          // Page contents has been modified
          if (!oldContents.equals(newContents)) {
            // Initialize comment
            StringBuilder fullComment = new StringBuilder();
            fullComment.append(wiki.createUpdatePageComment(comment, details.toString()));

            // Apply automatic Check Wiki fixing
            if (automaticCW) {
              List<CheckErrorAlgorithm> algorithms = CheckErrorAlgorithms.getAlgorithms(wiki);
              List<CheckErrorAlgorithm> usedAlgorithms = new ArrayList<CheckErrorAlgorithm>();
              newContents = AutomaticFormatter.tidyArticle(
                  page, newContents, algorithms, false, usedAlgorithms);
              if (!usedAlgorithms.isEmpty()) {
                fullComment.append(" / ");
                fullComment.append(wiki.getCWConfiguration().getComment(usedAlgorithms));
                if (description != null) {
                  for (CheckErrorAlgorithm algorithm : usedAlgorithms) {
                    description.append("<li>");
                    description.append(algorithm.getShortDescriptionReplaced());
                    description.append("</li>\n");
                  }
                }
              }
            }
            if ((description != null) && (changed)) {
              description.append("</ul>\n");
            }

            // Save page
            setText(GT._("Updating page {0}", page.getTitle()));
            count++;
            if (save) {
              api.updatePage(wiki, page, newContents, fullComment.toString(), false, false);
              if (updateDabWarning) {
                dabWarnings.updateWarning(
                    Collections.singletonList(page), null, null, null);
              }
            }
          }
        }
      }
    }
    block(true);
    return count;
  }
  /**
   * Create a default popup menu.
   * 
   * @param textPane Text pane.
   * @param position Position in the text.
   * @param pageAnalysis Page analysis.
   * @return Popup menu.
   */
  protected JPopupMenu createDefaultPopup(
      MWPane textPane, int position,
      PageAnalysis pageAnalysis) {

    // Basic checks
    if (pageAnalysis == null) {
      return null;
    }

    // Find where the user has clicked
    PageElement element = pageAnalysis.isInElement(position);

    // Comment
    if (element instanceof PageElementComment) {
      return null;
    }

    // Menu for internal link
    if (element instanceof PageElementInternalLink) {
      PageElementInternalLink internalLink = (PageElementInternalLink) element;
      return createDefaultPopupInternalLink(textPane, position, pageAnalysis, internalLink);
    }

    // Menu for image
    if (element instanceof PageElementImage) {
      PageElementImage image = (PageElementImage) element;
      return createDefaultPopupImage(textPane, position, pageAnalysis, image);
    }

    // Menu for external link
    if (element instanceof PageElementExternalLink) {
      PageElementExternalLink externalLink = (PageElementExternalLink) element;
      return createDefaultPopupExternalLink(pageAnalysis, position, externalLink);
    }

    // Menu for template
    if (element instanceof PageElementTemplate) {
      PageElementTemplate template = (PageElementTemplate) element;
      return createDefaultPopupTemplate(pageAnalysis, position, template);
    }

    // Menu for category
    if (element instanceof PageElementCategory) {
      PageElementCategory category = (PageElementCategory) element;
      return createDefaultPopupCategory(textPane, position, pageAnalysis, category);
    }

    // Menu for interwiki
    if (element instanceof PageElementInterwikiLink) {
      PageElementInterwikiLink interwiki = (PageElementInterwikiLink) element;
      return createDefaultPopupInterwikiLink(textPane, position, pageAnalysis, interwiki);
    }

    // Menu for language
    if (element instanceof PageElementLanguageLink) {
      PageElementLanguageLink language = (PageElementLanguageLink) element;
      return createDefaultPopupLanguageLink(textPane, position, pageAnalysis, language);
    }

    // Menu for parameter
    if (element instanceof PageElementParameter) {
      PageElementParameter parameter = (PageElementParameter) element;
      return createDefaultPopupParameter(pageAnalysis, position, parameter);
    }

    // Menu for function
    if (element instanceof PageElementFunction) {
      PageElementFunction function = (PageElementFunction) element;
      return createDefaultPopupFunction(pageAnalysis, position, function);
    }

    // Menu for ISBN
    if (element instanceof PageElementISBN) {
      PageElementISBN isbn = (PageElementISBN) element;
      return createDefaultPopupISBN(pageAnalysis, position, isbn);
    }

    // Menu for ISSN
    if (element instanceof PageElementISSN) {
      PageElementISSN issn = (PageElementISSN) element;
      return createDefaultPopupISSN(pageAnalysis, position, issn);
    }

    // Default menu
    BasicMenuCreator menu = new BasicMenuCreator();
    JPopupMenu popup = menu.createPopupMenu(GT._(
        "Page: {0}",
        limitTextLength(pageAnalysis.getPage().getTitle(), 50)));
    menu.addCurrentChapter(popup, position, pageAnalysis);
    menu.addSeparator(popup);
    menu.addView(wikipedia, popup, pageAnalysis.getPage(), false);
    return popup;
  }