Advertisement
Guest User

noreferences.py

a guest
Feb 23rd, 2014
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 25.25 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8  -*-
  3.  
  4. """
  5. This script goes over multiple pages, searches for pages where <references />
  6. is missing although a <ref> tag is present, and in that case adds a new
  7. references section.
  8.  
  9. These command line parameters can be used to specify which pages to work on:
  10.  
  11. &params;
  12.  
  13.    -xml          Retrieve information from a local XML dump (pages-articles
  14.                  or pages-meta-current, see http://download.wikimedia.org).
  15.                  Argument can also be given as "-xml:filename".
  16.  
  17.    -namespace:n  Number or name of namespace to process. The parameter can be
  18.                  used multiple times. It works in combination with all other
  19.                  parameters, except for the -start parameter. If you e.g.
  20.                  want to iterate over all categories starting at M, use
  21.                  -start:Category:M.
  22.  
  23.    -always       Don't prompt you for each replacement.
  24.  
  25. All other parameters will be regarded as part of the title of a single page,
  26. and the bot will only work on that single page.
  27.  
  28. If neither a page title nor a page generator is given, it takes all pages from
  29. the default maintenance category.
  30.  
  31. It is strongly recommended not to run this script over the entire article
  32. namespace (using the -start) parameter, as that would consume too much
  33. bandwidth. Instead, use the -xml parameter, or use another way to generate
  34. a list of affected articles
  35. """
  36. #
  37. # (C) Pywikibot team, 2007-2013
  38. #
  39. # Distributed under the terms of the MIT license.
  40. #
  41. __version__ = '$Id: 8e32ea2fb40f3413c6916ba86923f60f98955387 $'
  42. #
  43.  
  44. import re
  45. import pywikibot
  46. from pywikibot import i18n
  47. import pagegenerators
  48. import catlib
  49.  
  50. # This is required for the text that is shown when you run this script
  51. # with the parameter -help.
  52. docuReplacements = {
  53.     '&params;':     pagegenerators.parameterHelp,
  54. }
  55.  
  56. # References sections are usually placed before further reading / external
  57. # link sections. This dictionary defines these sections, sorted by priority.
  58. # For example, on an English wiki, the script would place the "References"
  59. # section in front of the "Further reading" section, if that existed.
  60. # Otherwise, it would try to put it in front of the "External links" section,
  61. # or if that fails, the "See also" section, etc.
  62. placeBeforeSections = {
  63.     'ar': [              # no explicit policy on where to put the references
  64.         u'وصلات خارجية',
  65.         u'انظر أيضا',
  66.         u'ملاحظات'
  67.     ],
  68.     'cs': [
  69.         u'Externí odkazy',
  70.         u'Poznámky',
  71.     ],
  72.     'da': [              # no explicit policy on where to put the references
  73.         u'Eksterne links'
  74.     ],
  75.     'de': [              # no explicit policy on where to put the references
  76.         u'Literatur',
  77.         u'Weblinks',
  78.         u'Siehe auch',
  79.         u'Weblink',      # bad, but common singular form of Weblinks
  80.     ],
  81.     'dsb': [
  82.         u'Nožki',
  83.     ],
  84.     'en': [              # no explicit policy on where to put the references
  85.         u'Further reading',
  86.         u'External links',
  87.         u'See also',
  88.         u'Notes'
  89.     ],
  90.     'ru': [
  91.         u'Ссылки',
  92.         u'Литература',
  93.     ],
  94.     'eo': [
  95.         u'Eksteraj ligiloj',
  96.         u'Ekstera ligilo',
  97.         u'Eksteraj ligoj',
  98.         u'Ekstera ligo',
  99.         u'Rete'
  100.     ],
  101.     'es': [
  102.         u'Enlaces externos',
  103.         u'Véase también',
  104.         u'Notas',
  105.     ],
  106.     'fa': [
  107.         u'پیوند به بیرون',
  108.         u'پانویس',
  109.         u'جستارهای وابسته'
  110.     ],
  111.     'fi': [
  112.         u'Kirjallisuutta',
  113.         u'Aiheesta muualla',
  114.         u'Ulkoiset linkit',
  115.         u'Linkkejä',
  116.     ],
  117.     'fr': [
  118.         u'Liens externes',
  119.         u'Voir aussi',
  120.         u'Notes'
  121.     ],
  122.     'hsb': [
  123.         u'Nóžki',
  124.     ],
  125.     'hu': [
  126.         u'Külső hivatkozások',
  127.         u'Lásd még',
  128.     ],
  129.     'it': [
  130.         u'Bibliografia',
  131.         u'Voci correlate',
  132.         u'Altri progetti',
  133.         u'Collegamenti esterni',
  134.         u'Vedi anche',
  135.     ],
  136.     'ja': [
  137.         u'関連項目',
  138.         u'参考文献',
  139.         u'外部リンク',
  140.     ],
  141.     'ko': [              # no explicit policy on where to put the references
  142.         u'외부 링크',
  143.         u'외부링크',
  144.         u'바깥 고리',
  145.         u'바깥고리',
  146.         u'바깥 링크',
  147.         u'바깥링크'
  148.         u'외부 고리',
  149.         u'외부고리'
  150.     ],
  151.     'lt': [              # no explicit policy on where to put the references
  152.         u'Nuorodos'
  153.     ],
  154.     'nl': [              # no explicit policy on where to put the references
  155.         u'Literatuur',
  156.         u'Zie ook',
  157.         u'Externe verwijzingen',
  158.         u'Externe verwijzing',
  159.     ],
  160.     'pdc': [
  161.         u'Beweisunge',
  162.         u'Quelle unn Literatur',
  163.         u'Gwelle',
  164.         u'Gwuelle',
  165.         u'Auswenniche Gleecher',
  166.         u'Gewebbgleecher',
  167.         u'Guckt mol aa',
  168.         u'Seh aa',
  169.     ],
  170.     'pl': [
  171.         u'Źródła',
  172.         u'Bibliografia',
  173.         u'Zobacz też',
  174.         u'Linki zewnętrzne',
  175.     ],
  176.     'pt': [
  177.         u'Ligações externas',
  178.         u'Veja também',
  179.         u'Ver também',
  180.         u'Notas',
  181.     ],
  182.     'sk': [
  183.         u'Pozri aj',
  184.     ],
  185.     'szl': [
  186.         u'Przipisy',
  187.         u'Připisy',
  188.     ],
  189.     'zh': [
  190.         u'外部链接',
  191.         u'外部連结',
  192.         u'外部連結',
  193.         u'外部连接',
  194.     ],
  195. }
  196.  
  197. # Titles of sections where a reference tag would fit into.
  198. # The first title should be the preferred one: It's the one that
  199. # will be used when a new section has to be created.
  200. referencesSections = {
  201.     'ar': [             # not sure about which ones are preferred.
  202.         u'مراجع',
  203.         u'المراجع',
  204.         u'مصادر',
  205.         u'المصادر',
  206.         u'مراجع ومصادر',
  207.         u'مصادر ومراجع',
  208.         u'المراجع والمصادر',
  209.         u'المصادر والمراجع',
  210.     ],
  211.     'cs': [
  212.         u'Reference',
  213.         u'Poznámky',
  214.     ],
  215.     'da': [
  216.         u'Noter',
  217.     ],
  218.     'de': [             # see [[de:WP:REF]]
  219.         u'Einzelnachweise',
  220.         u'Anmerkungen',
  221.         u'Belege',
  222.         u'Endnoten',
  223.         u'Fußnoten',
  224.         u'Fuß-/Endnoten',
  225.         u'Quellen',
  226.         u'Quellenangaben',
  227.     ],
  228.     'dsb': [
  229.         u'Nožki',
  230.     ],
  231.     'en': [             # not sure about which ones are preferred.
  232.         u'References',
  233.         u'Footnotes',
  234.         u'Notes',
  235.     ],
  236.     'ru': [
  237.         u'Примечания',
  238.         u'Сноски',
  239.         u'Источники',
  240.     ],
  241.     'eo': [
  242.         u'Referencoj',
  243.     ],
  244.     'es': [
  245.         u'Referencias',
  246.         u'Notas',
  247.     ],
  248.     'fa': [
  249.         u'منابع',
  250.         u'منبع'
  251.     ],
  252.     'fi': [
  253.         u'Lähteet',
  254.         u'Viitteet',
  255.     ],
  256.     'fr': [             # [[fr:Aide:Note]]
  257.         u'Notes et références',
  258.         u'Références',
  259.         u'References',
  260.         u'Notes'
  261.     ],
  262.     'he': [
  263.         u'הערות שוליים',
  264.     ],
  265.     'hsb': [
  266.         u'Nóžki',
  267.     ],
  268.     'hu': [
  269.         u'Források és jegyzetek',
  270.         u'Források',
  271.         u'Jegyzetek',
  272.         u'Hivatkozások',
  273.         u'Megjegyzések',
  274.     ],
  275.     'is': [
  276.         u'Heimildir',
  277.         u'Tilvísanir',
  278.     ],
  279.     'it': [
  280.         u'Note',
  281.         u'Riferimenti',
  282.     ],
  283.     'ja': [
  284.         u'脚注',
  285.         u'脚注欄',
  286.         u'脚注・出典',
  287.         u'出典',
  288.         u'注釈',
  289.         u'註',
  290.     ],
  291.     'ko': [
  292.         u'주석',
  293.         u'각주'
  294.         u'주석 및 참고 자료'
  295.         u'주석 및 참고자료',
  296.         u'주석 및 참고 출처'
  297.     ],
  298.     'lt': [             # not sure about which ones are preferred.
  299.         u'Šaltiniai',
  300.         u'Literatūra',
  301.     ],
  302.     'nl': [             # not sure about which ones are preferred.
  303.         u'Voetnoten',
  304.         u'Voetnoot',
  305.         u'Referenties',
  306.         u'Noten',
  307.         u'Bronvermelding',
  308.     ],
  309.     'pdc': [
  310.         u'Aamarrickunge',
  311.     ],
  312.     'pl': [
  313.         u'Przypisy',
  314.         u'Uwagi',
  315.     ],
  316.     'pt': [
  317.         u'Referências',
  318.     ],
  319.     'sk': [
  320.         u'Referencie',
  321.     ],
  322.     'szl': [
  323.         u'Przipisy',
  324.         u'Připisy',
  325.     ],
  326.     'zh': [
  327.         u'參考資料',
  328.         u'参考资料',
  329.         u'參考文獻',
  330.         u'参考文献',
  331.         u'資料來源',
  332.         u'资料来源',
  333.     ],
  334. }
  335.  
  336. # Templates which include a <references /> tag. If there is no such template
  337. # on your wiki, you don't have to enter anything here.
  338. referencesTemplates = {
  339.     'wikipedia': {
  340.         'ar': [u'Reflist', u'مراجع', u'ثبت المراجع', u'ثبت_المراجع', u'بداية المراجع', u'نهاية المراجع'],
  341.         'be': [u'Зноскі', u'Примечания', u'Reflist', u'Спіс заўваг',
  342.                u'Заўвагі'],
  343.         'be-x-old': [u'Зноскі'],
  344.         'da': [u'Reflist'],
  345.         'dsb': [u'Referency'],
  346.         'en': [u'Reflist', u'Refs', u'FootnotesSmall', u'Reference',
  347.                u'Ref-list', u'Reference list', u'References-small', u'Reflink',
  348.                u'Footnotes', u'FootnotesSmall'],
  349.         'eo': [u'Referencoj'],
  350.         'es': ['Listaref', 'Reflist', 'muchasref'],
  351.         'fa': [u'Reflist', u'Refs', u'FootnotesSmall', u'Reference',
  352.                u'پانویس', u'پانویس‌ها ', u'پانویس ۲', u'پانویس۲',
  353.                u'فهرست منابع'],
  354.         'fi': [u'Viitteet', u'Reflist'],
  355.         'fr': [u'Références', u'Notes', u'References', u'Reflist'],
  356.         'hsb': [u'Referency'],
  357.         'hu': [u'reflist', u'források', u'references', u'megjegyzések'],
  358.         'is': [u'reflist'],
  359.         'it': [u'References'],
  360.         'ja': [u'Reflist', u'脚注リスト'],
  361.         'ko': [u'주석', u'Reflist'],
  362.         'lt': [u'Reflist', u'Ref', u'Litref'],
  363.         'nl': [u'Reflist', u'Refs', u'FootnotesSmall', u'Reference',
  364.                u'Ref-list', u'Reference list', u'References-small', u'Reflink',
  365.                u'Referenties', u'Bron', u'Bronnen/noten/referenties', u'Bron2',
  366.                u'Bron3', u'ref', u'references', u'appendix',
  367.                u'Noot', u'FootnotesSmall'],
  368.         'pl': [u'Przypisy', u'Przypisy-lista', u'Uwagi'],
  369.         'pt': [u'Notas', u'ref-section', u'Referências', u'Reflist'],
  370.         'ru': [u'Reflist', u'Ref-list', u'Refs', u'Sources',
  371.                u'Примечания', u'Список примечаний',
  372.                u'Сноска', u'Сноски'],
  373.         'szl': [u'Przipisy', u'Připisy'],
  374.         'zh': [u'Reflist', u'RefFoot', u'NoteFoot'],
  375.     },
  376. }
  377.  
  378. # Text to be added instead of the <references /> tag.
  379. # Define this only if required by your wiki.
  380. referencesSubstitute = {
  381.     'wikipedia': {
  382.         'ar': u'{{مراجع}}',
  383.         'be': u'{{зноскі}}',
  384.         'da': u'{{reflist}}',
  385.         'dsb': u'{{referency}}',
  386.         'fa': u'{{پانویس}}',
  387.         'fi': u'{{viitteet}}',
  388.         'hsb': u'{{referency}}',
  389.         'hu': u'{{Források}}',
  390.         'pl': u'{{Przypisy}}',
  391.         'ru': u'{{примечания}}',
  392.         'szl': u'{{Przipisy}}',
  393.         'zh': u'{{reflist}}',
  394.     },
  395. }
  396.  
  397. # Sites where no title is required for references template
  398. # as it is already included there
  399. # like pl.wiki where {{Przypisy}} generates
  400. # == Przypisy ==
  401. # <references />
  402. noTitleRequired = [u'pl', u'be', u'szl']
  403.  
  404. maintenance_category = {
  405.     'wikipedia': {
  406.         'be-x-old': u'Вікіпэдыя:Старонкі з адсутным сьпісам зносак',
  407.         'cs': u'Údržba:Články s chybějící značkou REFERENCES',
  408.         'de': u'Wikipedia:Seite mit fehlendem References-Tag',
  409.         'en': u'Pages with missing references list',
  410.         'fa': u'صفحه‌های با یادکرد خراب (فقدان پانویس)',
  411.         'ja': u'Refタグがあるのにreferencesタグがないページ',
  412.         'simple': u'Wikipedia pages with broken references',
  413.         'zh': u'参考资料格式错误的页面',
  414.     },
  415. }
  416.  
  417.  
  418. class XmlDumpNoReferencesPageGenerator:
  419.     """
  420.    Generator which will yield Pages that might lack a references tag.
  421.    These pages will be retrieved from a local XML dump file
  422.    (pages-articles or pages-meta-current).
  423.    """
  424.     def __init__(self, xmlFilename):
  425.         """
  426.        Arguments:
  427.            * xmlFilename  - The dump's path, either absolute or relative
  428.        """
  429.         self.xmlFilename = xmlFilename
  430.         self.refR = re.compile('</ref>', re.IGNORECASE)
  431.         # The references tab can contain additional spaces and a group
  432.         # attribute.
  433.         self.referencesR = re.compile('<references.*?/>', re.IGNORECASE)
  434.  
  435.     def __iter__(self):
  436.         import xmlreader
  437.         dump = xmlreader.XmlDump(self.xmlFilename)
  438.         for entry in dump.parse():
  439.             text = pywikibot.removeDisabledParts(entry.text)
  440.             if self.refR.search(text) and not self.referencesR.search(text):
  441.                 yield pywikibot.Page(pywikibot.getSite(), entry.title)
  442.  
  443.  
  444. class NoReferencesBot:
  445.  
  446.     def __init__(self, generator, always=False):
  447.         self.generator = generator
  448.         self.always = always
  449.         self.site = pywikibot.getSite()
  450.         self.comment = i18n.twtranslate(self.site, 'noreferences-add-tag')
  451.  
  452.         self.refR = re.compile('</ref>', re.IGNORECASE)
  453.         self.referencesR = re.compile('<references.*?/>', re.IGNORECASE)
  454.         self.referencesTagR = re.compile('<references>.*?</references>',
  455.                                          re.IGNORECASE | re.DOTALL)
  456.         try:
  457.             self.referencesTemplates = referencesTemplates[
  458.                 pywikibot.getSite().family.name][pywikibot.getSite().lang]
  459.         except KeyError:
  460.             self.referencesTemplates = []
  461.         try:
  462.             self.referencesText = referencesSubstitute[
  463.                 pywikibot.getSite().family.name][pywikibot.getSite().lang]
  464.         except KeyError:
  465.             self.referencesText = u'<references />'
  466.  
  467.     def lacksReferences(self, text, verbose=True):
  468.         """
  469.        Checks whether or not the page is lacking a references tag.
  470.        """
  471.         oldTextCleaned = pywikibot.removeDisabledParts(text)
  472.         if self.referencesR.search(oldTextCleaned) or \
  473.            self.referencesTagR.search(oldTextCleaned):
  474.             if verbose:
  475.                 pywikibot.output(u'No changes necessary: references tag found.')
  476.             return False
  477.         elif self.referencesTemplates:
  478.             templateR = u'{{(' + u'|'.join(self.referencesTemplates) + ')'
  479.             if re.search(templateR, oldTextCleaned, re.IGNORECASE | re.UNICODE):
  480.                 if verbose:
  481.                     pywikibot.output(
  482.                         u'No changes necessary: references template found.')
  483.                 return False
  484.         if not self.refR.search(oldTextCleaned):
  485.             if verbose:
  486.                 pywikibot.output(u'No changes necessary: no ref tags found.')
  487.             return False
  488.         else:
  489.             if verbose:
  490.                 pywikibot.output(u'Found ref without references.')
  491.             return True
  492.  
  493.     def addReferences(self, oldText):
  494.         """
  495.        Tries to add a references tag into an existing section where it fits
  496.        into. If there is no such section, creates a new section containing
  497.        the references tag.
  498.        * Returns : The modified pagetext
  499.  
  500.        """
  501.         # Is there an existing section where we can add the references tag?
  502.         for section in pywikibot.translate(self.site, referencesSections):
  503.             sectionR = re.compile(r'\r?\n=+ *%s *=+ *\r?\n' % section)
  504.             index = 0
  505.             while index < len(oldText):
  506.                 match = sectionR.search(oldText, index)
  507.                 if match:
  508.                     if pywikibot.isDisabled(oldText, match.start()):
  509.                         pywikibot.output(
  510.                             'Existing  %s section is commented out, skipping.'
  511.                             % section)
  512.                         index = match.end()
  513.                     else:
  514.                         pywikibot.output(
  515.                             u'Adding references tag to existing %s section...\n'
  516.                             % section)
  517.                         newText = (
  518.                             oldText[:match.end()] + u'\n' +
  519.                             self.referencesText + u'\n' +
  520.                             oldText[match.end():]
  521.                         )
  522.                         return newText
  523.                 else:
  524.                     break
  525.  
  526.         # Create a new section for the references tag
  527.         for section in pywikibot.translate(self.site, placeBeforeSections):
  528.             # Find out where to place the new section
  529.             sectionR = re.compile(r'\r?\n(?P<ident>=+) *%s *(?P=ident) *\r?\n'
  530.                                   % section)
  531.             index = 0
  532.             while index < len(oldText):
  533.                 match = sectionR.search(oldText, index)
  534.                 if match:
  535.                     if pywikibot.isDisabled(oldText, match.start()):
  536.                         pywikibot.output(
  537.                             'Existing  %s section is commented out, won\'t add '
  538.                             'the references in front of it.' % section)
  539.                         index = match.end()
  540.                     else:
  541.                         pywikibot.output(
  542.                             u'Adding references section before %s section...\n'
  543.                             % section)
  544.                         index = match.start()
  545.                         ident = match.group('ident')
  546.                         return self.createReferenceSection(oldText, index,
  547.                                                            ident)
  548.                 else:
  549.                     break
  550.         # This gets complicated: we want to place the new references
  551.         # section over the interwiki links and categories, but also
  552.         # over all navigation bars, persondata, and other templates
  553.         # that are at the bottom of the page. So we need some advanced
  554.         # regex magic.
  555.         # The strategy is: create a temporary copy of the text. From that,
  556.         # keep removing interwiki links, templates etc. from the bottom.
  557.         # At the end, look at the length of the temp text. That's the position
  558.         # where we'll insert the references section.
  559.         catNamespaces = '|'.join(self.site.category_namespaces())
  560.         categoryPattern = r'\[\[\s*(%s)\s*:[^\n]*\]\]\s*' % catNamespaces
  561.         interwikiPattern = r'\[\[([a-zA-Z\-]+)\s?:([^\[\]\n]*)\]\]\s*'
  562.         # won't work with nested templates
  563.         # the negative lookahead assures that we'll match the last template
  564.         # occurence in the temp text.
  565.         ### fix me:
  566.         ### {{commons}} or {{commonscat}} are part of Weblinks section
  567.         ### * {{template}} is mostly part of a section
  568.         ### so templatePattern must be fixed
  569.         templatePattern = r'\r?\n{{((?!}}).)+?}}\s*'
  570.         commentPattern = r'<!--((?!-->).)*?-->\s*'
  571.         metadataR = re.compile(r'(\r?\n)?(%s|%s|%s|%s)$'
  572.                                % (categoryPattern, interwikiPattern,
  573.                                   templatePattern, commentPattern), re.DOTALL)
  574.         tmpText = oldText
  575.         while True:
  576.             match = metadataR.search(tmpText)
  577.             if match:
  578.                 tmpText = tmpText[:match.start()]
  579.             else:
  580.                 break
  581.         pywikibot.output(
  582.             u'Found no section that can be preceeded by a new references '
  583.             u'section.\nPlacing it before interwiki links, categories, and '
  584.             u'bottom templates.')
  585.         index = len(tmpText)
  586.         return self.createReferenceSection(oldText, index)
  587.  
  588.     def createReferenceSection(self, oldText, index, ident='=='):
  589.         if self.site.language() in noTitleRequired:
  590.             newSection = u'\n%s\n' % (self.referencesText)
  591.         else:
  592.             newSection = u'\n%s %s %s\n%s\n' % (ident,
  593.                                                 pywikibot.translate(
  594.                                                     self.site,
  595.                                                     referencesSections)[0],
  596.                                                 ident, self.referencesText)
  597.         return oldText[:index] + newSection + oldText[index:]
  598.  
  599.     def save(self, page, newText):
  600.         """
  601.        Saves the page to the wiki, if the user accepts the changes made.
  602.        """
  603.         pywikibot.showDiff(page.get(), newText)
  604.         if not self.always:
  605.             choice = pywikibot.inputChoice(
  606.                 u'Do you want to accept these changes?',
  607.                 ['Yes', 'No', 'Always yes'], ['y', 'N', 'a'], 'Y')
  608.             if choice == 'n':
  609.                 return
  610.             elif choice == 'a':
  611.                 self.always = True
  612.  
  613.         if self.always:
  614.             try:
  615.                 page.put(newText, self.comment)
  616.             except pywikibot.EditConflict:
  617.                 pywikibot.output(u'Skipping %s because of edit conflict'
  618.                                  % (page.title(),))
  619.             except pywikibot.SpamfilterError as e:
  620.                 pywikibot.output(
  621.                     u'Cannot change %s because of blacklist entry %s'
  622.                     % (page.title(), e.url))
  623.             except pywikibot.LockedPage:
  624.                 pywikibot.output(u'Skipping %s (locked page)' % (page.title(),))
  625.         else:
  626.             # Save the page in the background. No need to catch exceptions.
  627.             page.put_async(newText, self.comment)
  628.         return
  629.  
  630.     def run(self):
  631.  
  632.         for page in self.generator:
  633.             # Show the title of the page we're working on.
  634.             # Highlight the title in purple.
  635.             pywikibot.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<"
  636.                              % page.title())
  637.             try:
  638.                 text = page.get()
  639.             except pywikibot.NoPage:
  640.                 pywikibot.output(u"Page %s does not exist?!"
  641.                                  % page.title(asLink=True))
  642.                 continue
  643.             except pywikibot.IsRedirectPage:
  644.                 pywikibot.output(u"Page %s is a redirect; skipping."
  645.                                  % page.title(asLink=True))
  646.                 continue
  647.             except pywikibot.LockedPage:
  648.                 pywikibot.output(u"Page %s is locked?!"
  649.                                  % page.title(asLink=True))
  650.                 continue
  651.             if page.isDisambig():
  652.                 pywikibot.output(u"Page %s is a disambig; skipping."
  653.                                  % page.title(asLink=True))
  654.                 continue
  655.             if pywikibot.getSite().sitename() == 'wikipedia:en' and \
  656.                page.isIpEdit():
  657.                 pywikibot.output(
  658.                     u"Page %s is edited by IP. Possible vandalized"
  659.                     % page.title(asLink=True))
  660.                 continue
  661.             if self.lacksReferences(text):
  662.                 newText = self.addReferences(text)
  663.                 self.save(page, newText)
  664.  
  665.  
  666. def main():
  667.     #page generator
  668.     gen = None
  669.     # This temporary array is used to read the page title if one single
  670.     # page to work on is specified by the arguments.
  671.     pageTitle = []
  672.     # Which namespaces should be processed?
  673.     # default to [] which means all namespaces will be processed
  674.     namespaces = []
  675.     # Never ask before changing a page
  676.     always = False
  677.     # This factory is responsible for processing command line arguments
  678.     # that are also used by other scripts and that determine on which pages
  679.     # to work on.
  680.     genFactory = pagegenerators.GeneratorFactory()
  681.  
  682.     for arg in pywikibot.handleArgs():
  683.         if arg.startswith('-xml'):
  684.             if len(arg) == 4:
  685.                 xmlFilename = i18n.input('pywikibot-enter-xml-filename')
  686.             else:
  687.                 xmlFilename = arg[5:]
  688.             gen = XmlDumpNoReferencesPageGenerator(xmlFilename)
  689.         elif arg.startswith('-namespace:'):
  690.             try:
  691.                 namespaces.append(int(arg[11:]))
  692.             except ValueError:
  693.                 namespaces.append(arg[11:])
  694.         elif arg == '-always':
  695.             always = True
  696.         else:
  697.             if not genFactory.handleArg(arg):
  698.                 pageTitle.append(arg)
  699.  
  700.     if pageTitle:
  701.         page = pywikibot.Page(pywikibot.getSite(), ' '.join(pageTitle))
  702.         gen = iter([page])
  703.     if not gen:
  704.         gen = genFactory.getCombinedGenerator()
  705.     if not gen:
  706.         site = pywikibot.getSite()
  707.         try:
  708.             cat = maintenance_category[site.family.name][site.lang]
  709.         except:
  710.             pass
  711.         else:
  712.             if not namespaces:
  713.                 namespaces = [0]
  714.             cat = catlib.Category(site, "%s:%s" % (
  715.                 site.category_namespace(), cat))
  716.             gen = pagegenerators.CategorizedPageGenerator(cat)
  717.     if not gen:
  718.         pywikibot.showHelp('noreferences')
  719.     else:
  720.         if namespaces:
  721.             gen = pagegenerators.NamespaceFilterPageGenerator(gen, namespaces)
  722.         preloadingGen = pagegenerators.PreloadingGenerator(gen)
  723.         bot = NoReferencesBot(preloadingGen, always)
  724.         bot.run()
  725.  
  726. if __name__ == "__main__":
  727.     try:
  728.         main()
  729.     finally:
  730.         pywikibot.stopme()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement