Ejemplo n.º 1
0
 def run(self):
     articles = self.cat.articlesList(recurse = 0)
     if len(articles) == 0:
         pywikibot.output(u'There are no articles in category %s' % self.cat.title())
     else:
         for article in articles:
             if not self.titleRegex or re.search(self.titleRegex,article.title()):
                 catlib.change_category(article, self.cat, None, comment = self.editSummary, inPlace = self.inPlace)
     # Also removes the category tag from subcategories' pages
     subcategories = self.cat.subcategoriesList(recurse = 0)
     if len(subcategories) == 0:
         pywikibot.output(u'There are no subcategories in category %s' % self.cat.title())
     else:
         for subcategory in subcategories:
             catlib.change_category(subcategory, self.cat, None, comment = self.editSummary, inPlace = self.inPlace)
     # Deletes the category page
     if self.cat.exists() and self.cat.isEmptyCategory():
         if self.useSummaryForDeletion and self.editSummary:
             reason = self.editSummary
         else:
             reason = i18n.twtranslate(self.site, 'category-was-disbanded')
         talkPage = self.cat.toggleTalkPage()
         try:
             self.cat.delete(reason, not self.batchMode)
         except pywikibot.NoUsername:
             pywikibot.output(u'You\'re not setup sysop info, category will not delete.' % self.cat.site())
             return
         if (talkPage.exists()):
             talkPage.delete(reason=reason, prompt=not self.batchMode)
Ejemplo n.º 2
0
 def run(self):
     articles = self.cat.articlesList(recurse = 0)
     if len(articles) == 0:
         pywikibot.output(u'There are no articles in category %s' % self.cat.title())
     else:
         for article in articles:
             if not self.titleRegex or re.search(self.titleRegex,article.title()):
                 catlib.change_category(article, self.cat, None, comment = self.editSummary, inPlace = self.inPlace)
     # Also removes the category tag from subcategories' pages
     subcategories = self.cat.subcategoriesList(recurse = 0)
     if len(subcategories) == 0:
         pywikibot.output(u'There are no subcategories in category %s' % self.cat.title())
     else:
         for subcategory in subcategories:
             catlib.change_category(subcategory, self.cat, None, comment = self.editSummary, inPlace = self.inPlace)
     # Deletes the category page
     if self.cat.exists() and self.cat.isEmptyCategory():
         if self.useSummaryForDeletion and self.editSummary:
             reason = self.editSummary
         else:
             reason = pywikibot.translate(self.site, self.deletion_reason_remove)
         talkPage = self.cat.toggleTalkPage()
         try:
             self.cat.delete(reason, not self.batchMode)
         except pywikibot.NoUsername:
             pywikibot.output(u'You\'re not setup sysop info, category will not delete.' % self.cat.site())
             return
         if (talkPage.exists()):
             talkPage.delete(reason=reason, prompt=not self.batchMode)
Ejemplo n.º 3
0
 def run(self):
     articles = self.cat.articlesList(recurse = 0)
     if len(articles) == 0:
         wikipedia.output(u'There are no articles in category %s' % self.cat.title())
     else:
         for article in articles:
             if not self.titleRegex or re.search(self.titleRegex,article.title()):
                 catlib.change_category(article, self.cat, None, comment = self.editSummary, inPlace = self.inPlace)
     # Also removes the category tag from subcategories' pages
     subcategories = self.cat.subcategoriesList(recurse = 0)
     if len(subcategories) == 0:
         wikipedia.output(u'There are no subcategories in category %s' % self.cat.title())
     else:
         for subcategory in subcategories:
             catlib.change_category(subcategory, self.cat, None, comment = self.editSummary, inPlace = self.inPlace)
     # Deletes the category page
     if self.cat.exists() and self.cat.isEmpty():
         if self.useSummaryForDeletion and self.editSummary:
             reason = self.editSummary
         else:
             reason = wikipedia.translate(wikipedia.getSite(), self.deletion_reason_remove)
         talkPage = self.cat.toggleTalkPage()
         self.cat.delete(reason, not self.batchMode)
         if (talkPage.exists()):
             talkPage.delete(reason=reason, prompt=not self.batchMode)
def main():
    '''
    Main loop. Loop over all categories of Category:Non-empty_category_redirects and move all content.
    '''

    site = wikipedia.getSite(u'commons', u'commons')
    dirtycat = catlib.Category(site, u'Category:Non-empty category redirects')
    destination = None
    catbot = None

    for old_category in dirtycat.subcategories():
        #We want to wait several days after the last edit before we start moving things around.
        #This it to prevent edit wars and vandals.
        if(readyToEdit(old_category)):
            destination = get_redirect_cat(old_category)
            if destination:
                wikipedia.output(destination.title())
                for page in old_category.articles():
                    try:
                        catlib.change_category(page, old_category, destination, move_message % (old_category.title(), old_category.titleWithoutNamespace(), destination.title(), destination.titleWithoutNamespace()))
                    except wikipedia.IsRedirectPage:
                        wikipedia.output(page.title() + u' is a redirect!')
                for cat in old_category.subcategories():
                    try:
                        catlib.change_category(cat, old_category, destination, move_message % (old_category.title(), old_category.titleWithoutNamespace(), destination.title(), destination.titleWithoutNamespace()))
                    except wikipedia.IsRedirectPage:
                        wikipedia.output(page.title() + u' is a redirect!')
        #Dummy edit to refresh the page, shouldnt show up in any logs.
        try:
            old_category.put(old_category.get())
        except:
            wikipedia.output(u'Dummy edit at ' + old_category.title() + u' failed')
Ejemplo n.º 5
0
def main():
    ''' Main loop. Loop over all categories of
    Category:Non-empty_category_redirects and move all content.

    '''

    site = pywikibot.getSite(u'commons', u'commons')
    dirtycat = catlib.Category(site, u'Category:Non-empty category redirects')
    destination = None
    catbot = None

    for old_category in dirtycat.subcategories():
        # We want to wait several days after the last edit before we start moving
        # things around. This it to prevent edit wars and vandals.
        if (readyToEdit(old_category)):
            destination = get_redirect_cat(old_category)
            if destination:
                pywikibot.output(destination.title())
                for page in old_category.articles():
                    try:
                        catlib.change_category(
                            page, old_category, destination, move_message %
                            (old_category.title(),
                             old_category.title(withNamespace=False),
                             destination.title(),
                             destination.title(withNamespace=False)))
                    except pywikibot.IsRedirectPage:
                        pywikibot.output(u'%s is a redirect!' % page.title())
                for cat in old_category.subcategories():
                    try:
                        catlib.change_category(
                            cat, old_category, destination, move_message %
                            (old_category.title(),
                             old_category.title(withNamespace=False),
                             destination.title(),
                             destination.title(withNamespace=False)))
                    except pywikibot.IsRedirectPage:
                        pywikibot.output(u'%s is a redirect!' % page.title())
        #Dummy edit to refresh the page, shouldnt show up in any logs.
        try:
            old_category.put(old_category.get())
        except:
            pywikibot.output(u'Dummy edit at %s failed' % old_category.title())
Ejemplo n.º 6
0
def include(pl, checklinks=True, realinclude=True, linkterm=None):
    cl = checklinks
    if linkterm:
        actualworkingcat = catlib.Category(mysite,
                                           workingcat.title(),
                                           sortKey=linkterm)
    else:
        actualworkingcat = workingcat
    if realinclude:
        try:
            text = pl.get()
        except pywikibot.NoPage:
            pass
        except pywikibot.IsRedirectPage:
            cl = True
            pass
        else:
            cats = pl.categories()
            if workingcat not in cats:
                cats = pl.categories()
                for c in cats:
                    if c in parentcats:
                        if removeparent:
                            catlib.change_category(pl, c, actualworkingcat)
                            break
                else:
                    pl.put(
                        pywikibot.replaceCategoryLinks(
                            text, cats + [actualworkingcat]))
    if cl:
        if checkforward:
            for page2 in pl.linkedPages():
                if needcheck(page2):
                    tocheck.append(page2)
                    checked[page2] = page2
        if checkbackward:
            for refPage in pl.getReferences():
                if needcheck(refPage):
                    tocheck.append(refPage)
                    checked[refPage] = refPage
Ejemplo n.º 7
0
def include(pl,checklinks=True,realinclude=True,linkterm=None):
    cl = checklinks
    if linkterm:
        actualworkingcat = catlib.Category(mysite,workingcat.title(),
                                           sortKey=linkterm)
    else:
        actualworkingcat = workingcat
    if realinclude:
        try:
            text = pl.get()
        except pywikibot.NoPage:
            pass
        except pywikibot.IsRedirectPage:
            cl = True
            pass
        else:
            cats = pl.categories()
            if not workingcat in cats:
                cats = pl.categories()
                for c in cats:
                    if c in parentcats:
                        if removeparent:
                            catlib.change_category(pl,c,actualworkingcat)
                            break
                else:
                    pl.put(pywikibot.replaceCategoryLinks(
                        text, cats + [actualworkingcat]))
    if cl:
        if checkforward:
            for page2 in pl.linkedPages():
                if needcheck(page2):
                    tocheck.append(page2)
                    checked[page2] = page2
        if checkbackward:
            for refPage in pl.getReferences():
                 if needcheck(refPage):
                    tocheck.append(refPage)
                    checked[refPage] = refPage
Ejemplo n.º 8
0
    def move_to_category(self, article, original_cat, current_cat):
        '''
        Given an article which is in category original_cat, ask the user if
        it should be moved to one of original_cat's subcategories.
        Recursively run through subcategories' subcategories.
        NOTE: current_cat is only used for internal recursion. You should
        always use current_cat = original_cat.
        '''
        pywikibot.output(u'')
        # Show the title of the page where the link was found.
        # Highlight the title in purple.
        pywikibot.output(u'Treating page \03{lightpurple}%s\03{default}, currently in \03{lightpurple}%s\03{default}' % (article.title(), current_cat.title()))

        # Determine a reasonable amount of context to print
        try:
            full_text = article.get(get_redirect = True)
        except pywikibot.NoPage:
            pywikibot.output(u'Page %s not found.' % article.title())
            return
        try:
            contextLength = full_text.index('\n\n')
        except ValueError: # substring not found
            contextLength = 500
        if full_text.startswith(u'[['): # probably an image
            # Add extra paragraph.
            contextLength = full_text.find('\n\n', contextLength+2)
        if contextLength > 1000 or contextLength < 0:
            contextLength = 500
        print
        pywikibot.output(full_text[:contextLength])
        print

        subcatlist = self.catDB.getSubcats(current_cat)
        supercatlist = self.catDB.getSupercats(current_cat)
        alternatives = u'\n'
        if len(subcatlist) == 0:
            alternatives += u'This category has no subcategories.\n\n'
        if len(supercatlist) == 0:
            alternatives += u'This category has no supercategories.\n\n'
        # show subcategories as possible choices (with numbers)
        for i in range(len(supercatlist)):
            # layout: we don't expect a cat to have more than 10 supercats
            alternatives += (u"u%d - Move up to %s\n" % (i, supercatlist[i].title()))
        for i in range(len(subcatlist)):
            # layout: we don't expect a cat to have more than 100 subcats
            alternatives += (u"%2d - Move down to %s\n" % (i, subcatlist[i].title()))
        alternatives += u" j - Jump to another category\n"
        alternatives += u" s - Skip this article\n"
        alternatives += u" r - Remove this category tag\n"
        alternatives += u" l - list these options again\n"
        alternatives += u" m - more context\n"
        alternatives += (u"Enter - Save category as %s\n" % current_cat.title())
        flag = False
        longchoice = True
        while not flag:
            if longchoice:
                longchoice = False
                pywikibot.output(alternatives)
                choice = pywikibot.input(u"Option:")
            else:
                choice = pywikibot.input(u"Option (#, [j]ump, [s]kip, [r]emove, [l]ist, [m]ore context, [RETURN]):")
            if choice in ['s', 'S']:
                flag = True
            elif choice == '':
                pywikibot.output(u'Saving category as %s' % current_cat.title())
                if current_cat == original_cat:
                    print 'No changes necessary.'
                else:
                    newcat = u'[[:%s|%s]]' % (current_cat.title(savetitle=True, decode=True), current_cat.titleWithoutNamespace())
                    editsum = pywikibot.translate(pywikibot.getSite(), msg_replace) % {'oldcat': original_cat.titleWithoutNamespace(), 'newcat': newcat}
                    catlib.change_category(article, original_cat, current_cat, comment = editsum)
                flag = True
            elif choice in ['j', 'J']:
                newCatTitle = pywikibot.input(u'Please enter the category the article should be moved to:')
                newCat = catlib.Category(pywikibot.getSite(), 'Category:' + newCatTitle)
                # recurse into chosen category
                self.move_to_category(article, original_cat, newCat)
                flag = True
            elif choice in ['r', 'R']:
                # remove the category tag
                catlib.change_category(article, original_cat, None, comment = self.editSummary)
                flag = True
            elif choice in ['l', 'L']:
                longchoice = True
            elif choice in ['m', 'M', '?']:
                contextLength += 500
                print
                pywikibot.output(full_text[:contextLength])
                print

                # if categories possibly weren't visible, show them additionally
                # (maybe this should always be shown?)
                if len(full_text) > contextLength:
                    print ''
                    print 'Original categories: '
                    for cat in article.categories():
                        pywikibot.output(u'* %s' % cat.title())
            elif choice[0] == 'u':
                try:
                    choice=int(choice[1:])
                except ValueError:
                    # user pressed an unknown command. Prompt him again.
                    continue
                self.move_to_category(article, original_cat, supercatlist[choice])
                flag = True
            else:
                try:
                    choice=int(choice)
                except ValueError:
                    # user pressed an unknown command. Prompt him again.
                    continue
                # recurse into subcategory
                self.move_to_category(article, original_cat, subcatlist[choice])
                flag = True
Ejemplo n.º 9
0
    def move_to_category(self, article, original_cat, current_cat):
        '''
        Given an article which is in category original_cat, ask the user if
        it should be moved to one of original_cat's subcategories.
        Recursively run through subcategories' subcategories.
        NOTE: current_cat is only used for internal recursion. You should
        always use current_cat = original_cat.
        '''
        wikipedia.output(u'')
        # Show the title of the page where the link was found.
        # Highlight the title in purple.
        wikipedia.output(u'Treating page \03{lightpurple}%s\03{default}, currently in \03{lightpurple}%s\03{default}' % (article.title(), current_cat.title()))

        # Determine a reasonable amount of context to print
        try:
            full_text = article.get(get_redirect = True)
        except wikipedia.NoPage:
            wikipedia.output(u'Page %s not found.' % article.title())
            return
        try:
            contextLength = full_text.index('\n\n')
        except ValueError: # substring not found
            contextLength = 500
        if full_text.startswith(u'[['): # probably an image
            # Add extra paragraph.
            contextLength = full_text.find('\n\n', contextLength+2)
        if contextLength > 1000 or contextLength < 0:
            contextLength = 500
        print
        wikipedia.output(full_text[:contextLength])
        print

        subcatlist = self.catDB.getSubcats(current_cat)
        supercatlist = self.catDB.getSupercats(current_cat)
        print
        if len(subcatlist) == 0:
            print 'This category has no subcategories.'
            print
        if len(supercatlist) == 0:
            print 'This category has no supercategories.'
            print
        # show subcategories as possible choices (with numbers)
        for i in range(len(supercatlist)):
            # layout: we don't expect a cat to have more than 10 supercats
            wikipedia.output(u'u%d - Move up to %s' % (i, supercatlist[i].title()))
        for i in range(len(subcatlist)):
            # layout: we don't expect a cat to have more than 100 subcats
            wikipedia.output(u'%2d - Move down to %s' % (i, subcatlist[i].title()))
        print ' j - Jump to another category'
        print ' s - Skip this article'
        print ' r - Remove this category tag'
        print ' ? - Print first part of the page (longer and longer)'
        wikipedia.output(u'Enter - Save category as %s' % current_cat.title())

        flag = False
        while not flag:
            print ''
            choice=wikipedia.input(u'Choice:')
            if choice in ['s', 'S']:
                flag = True
            elif choice == '':
                wikipedia.output(u'Saving category as %s' % current_cat.title())
                if current_cat == original_cat:
                    print 'No changes necessary.'
                else:
                    catlib.change_category(article, original_cat, current_cat, comment = self.editSummary)
                flag = True
            elif choice in ['j', 'J']:
                newCatTitle = wikipedia.input(u'Please enter the category the article should be moved to:')
                newCat = catlib.Category(wikipedia.getSite(), 'Category:' + newCatTitle)
                # recurse into chosen category
                self.move_to_category(article, original_cat, newCat)
                flag = True
            elif choice in ['r', 'R']:
                # remove the category tag
                catlib.change_category(article, original_cat, None, comment = self.editSummary)
                flag = True
            elif choice == '?':
                contextLength += 500
                print
                wikipedia.output(full_text[:contextLength])
                print

                # if categories possibly weren't visible, show them additionally
                # (maybe this should always be shown?)
                if len(full_text) > contextLength:
                    print ''
                    print 'Original categories: '
                    for cat in article.categories():
                        wikipedia.output(u'* %s' % cat.title())
            elif choice[0] == 'u':
                try:
                    choice=int(choice[1:])
                except ValueError:
                    # user pressed an unknown command. Prompt him again.
                    continue
                self.move_to_category(article, original_cat, supercatlist[choice])
                flag = True
            else:
                try:
                    choice=int(choice)
                except ValueError:
                    # user pressed an unknown command. Prompt him again.
                    continue
                # recurse into subcategory
                self.move_to_category(article, original_cat, subcatlist[choice])
                flag = True
Ejemplo n.º 10
0
    def move_to_category(self, article, original_cat, current_cat):
        '''
        Given an article which is in category original_cat, ask the user if
        it should be moved to one of original_cat's subcategories.
        Recursively run through subcategories' subcategories.
        NOTE: current_cat is only used for internal recursion. You should
        always use current_cat = original_cat.
        '''
        pywikibot.output(u'')
        # Show the title of the page where the link was found.
        # Highlight the title in purple.
        pywikibot.output(
            u'Treating page \03{lightpurple}%s\03{default}, currently in \03{lightpurple}%s\03{default}'
            % (article.title(), current_cat.title()))

        # Determine a reasonable amount of context to print
        try:
            full_text = article.get(get_redirect=True)
        except pywikibot.NoPage:
            pywikibot.output(u'Page %s not found.' % article.title())
            return
        try:
            contextLength = full_text.index('\n\n')
        except ValueError:  # substring not found
            contextLength = 500
        if full_text.startswith(u'[['):  # probably an image
            # Add extra paragraph.
            contextLength = full_text.find('\n\n', contextLength + 2)
        if contextLength > 1000 or contextLength < 0:
            contextLength = 500
        print
        pywikibot.output(full_text[:contextLength])
        print

        subcatlist = self.catDB.getSubcats(current_cat)
        supercatlist = self.catDB.getSupercats(current_cat)
        alternatives = u'\n'
        if len(subcatlist) == 0:
            alternatives += u'This category has no subcategories.\n\n'
        if len(supercatlist) == 0:
            alternatives += u'This category has no supercategories.\n\n'
        # show subcategories as possible choices (with numbers)
        for i in range(len(supercatlist)):
            # layout: we don't expect a cat to have more than 10 supercats
            alternatives += (u"u%d - Move up to %s\n" %
                             (i, supercatlist[i].title()))
        for i in range(len(subcatlist)):
            # layout: we don't expect a cat to have more than 100 subcats
            alternatives += (u"%2d - Move down to %s\n" %
                             (i, subcatlist[i].title()))
        alternatives += u" j - Jump to another category\n"
        alternatives += u" s - Skip this article\n"
        alternatives += u" r - Remove this category tag\n"
        alternatives += u" l - list these options again\n"
        alternatives += u" m - more context\n"
        alternatives += (u"Enter - Save category as %s\n" %
                         current_cat.title())
        flag = False
        longchoice = True
        while not flag:
            if longchoice:
                longchoice = False
                pywikibot.output(alternatives)
                choice = pywikibot.input(u"Option:")
            else:
                choice = pywikibot.input(
                    u"Option (#, [j]ump, [s]kip, [r]emove, [l]ist, [m]ore context, [RETURN]):"
                )
            if choice in ['s', 'S']:
                flag = True
            elif choice == '':
                pywikibot.output(u'Saving category as %s' %
                                 current_cat.title())
                if current_cat == original_cat:
                    print 'No changes necessary.'
                else:
                    newcat = u'[[:%s|%s]]' % (current_cat.title(
                        savetitle=True,
                        decode=True), current_cat.titleWithoutNamespace())
                    editsum = i18n.twtranslate(
                        pywikibot.getSite(), 'category-replacing', {
                            'oldcat': original_cat.titleWithoutNamespace(),
                            'newcat': newcat
                        })
                    catlib.change_category(article,
                                           original_cat,
                                           current_cat,
                                           comment=editsum)
                flag = True
            elif choice in ['j', 'J']:
                newCatTitle = pywikibot.input(
                    u'Please enter the category the article should be moved to:'
                )
                newCat = catlib.Category(pywikibot.getSite(),
                                         'Category:' + newCatTitle)
                # recurse into chosen category
                self.move_to_category(article, original_cat, newCat)
                flag = True
            elif choice in ['r', 'R']:
                # remove the category tag
                catlib.change_category(article,
                                       original_cat,
                                       None,
                                       comment=self.editSummary)
                flag = True
            elif choice in ['l', 'L']:
                longchoice = True
            elif choice in ['m', 'M', '?']:
                contextLength += 500
                print
                pywikibot.output(full_text[:contextLength])
                print

                # if categories possibly weren't visible, show them additionally
                # (maybe this should always be shown?)
                if len(full_text) > contextLength:
                    print ''
                    print 'Original categories: '
                    for cat in article.categories():
                        pywikibot.output(u'* %s' % cat.title())
            elif choice[0] == 'u':
                try:
                    choice = int(choice[1:])
                except ValueError:
                    # user pressed an unknown command. Prompt him again.
                    continue
                self.move_to_category(article, original_cat,
                                      supercatlist[choice])
                flag = True
            else:
                try:
                    choice = int(choice)
                except ValueError:
                    # user pressed an unknown command. Prompt him again.
                    continue
                # recurse into subcategory
                self.move_to_category(article, original_cat,
                                      subcatlist[choice])
                flag = True
Ejemplo n.º 11
0
class CategoryMoveRobot:
    """Robot to move pages from one category to another."""
    def __init__(self,
                 oldCatTitle,
                 newCatTitle,
                 batchMode=False,
                 editSummary='',
                 inPlace=False,
                 moveCatPage=True,
                 deleteEmptySourceCat=True,
                 titleRegex=None,
                 useSummaryForDeletion=True):
        site = pywikibot.getSite()
        self.editSummary = editSummary
        self.oldCat = catlib.Category(site, oldCatTitle)
        self.newCatTitle = newCatTitle
        self.inPlace = inPlace
        self.moveCatPage = moveCatPage
        self.batchMode = batchMode
        self.deleteEmptySourceCat = deleteEmptySourceCat
        self.titleRegex = titleRegex
        self.useSummaryForDeletion = useSummaryForDeletion

    def run(self):
        site = pywikibot.getSite()
        newCat = catlib.Category(site, self.newCatTitle)
        # set edit summary message
        if not self.editSummary:
            self.editSummary = i18n.twtranslate(site, 'category-changing') \
                               % {'oldcat':self.oldCat.title(),
                                  'newcat':newCat.title()}

        if self.useSummaryForDeletion and self.editSummary:
            reason = self.editSummary
        else:
            reason = i18n.twtranslate(site, deletion_reason_move) \
                     % {'newcat': self.newCatTitle, 'title': self.newCatTitle}

        # Copy the category contents to the new category page
        copied = False
        oldMovedTalk = None
        if self.oldCat.exists() and self.moveCatPage:
            copied = self.oldCat.copyAndKeep(
                self.newCatTitle, pywikibot.translate(site, cfd_templates))
            # Also move the talk page
            if copied:
                oldTalk = self.oldCat.toggleTalkPage()
                if oldTalk.exists():
                    newTalkTitle = newCat.toggleTalkPage().title()
                    try:
                        talkMoved = oldTalk.move(newTalkTitle, reason)
                    except (pywikibot.NoPage, pywikibot.PageNotSaved), e:
                        #in order :
                        #Source talk does not exist, or
                        #Target talk already exists
                        pywikibot.output(e.message)
                    else:
                        if talkMoved:
                            oldMovedTalk = oldTalk

        # Move articles
        gen = pagegenerators.CategorizedPageGenerator(self.oldCat,
                                                      recurse=False)
        preloadingGen = pagegenerators.PreloadingGenerator(gen)
        for article in preloadingGen:
            if not self.titleRegex or re.search(self.titleRegex,
                                                article.title()):
                catlib.change_category(article,
                                       self.oldCat,
                                       newCat,
                                       comment=self.editSummary,
                                       inPlace=self.inPlace)

        # Move subcategories
        gen = pagegenerators.SubCategoriesPageGenerator(self.oldCat,
                                                        recurse=False)
        preloadingGen = pagegenerators.PreloadingGenerator(gen)
        for subcategory in preloadingGen:
            if not self.titleRegex or re.search(self.titleRegex,
                                                subcategory.title()):
                catlib.change_category(subcategory,
                                       self.oldCat,
                                       newCat,
                                       comment=self.editSummary,
                                       inPlace=self.inPlace)

        # Delete the old category and its moved talk page
        if copied and self.deleteEmptySourceCat == True:
            if self.oldCat.isEmptyCategory():
                confirm = not self.batchMode
                self.oldCat.delete(reason, confirm, mark=True)
                if oldMovedTalk is not None:
                    oldMovedTalk.delete(reason, confirm, mark=True)
            else:
                pywikibot.output('Couldn\'t delete %s - not empty.' %
                                 self.oldCat.title())
Ejemplo n.º 12
0
class CategoryMoveRobot(object):
    """Bot to move pages from one category to another."""
    def __init__(self,
                 oldCatTitle,
                 newCatTitle,
                 batchMode=False,
                 editSummary='',
                 inPlace=False,
                 moveCatPage=True,
                 deleteEmptySourceCat=True,
                 titleRegex=None,
                 useSummaryForDeletion=True,
                 withHistory=False):
        site = pywikibot.getSite()
        self.editSummary = editSummary
        self.oldCat = catlib.Category(site, oldCatTitle)
        self.newCatTitle = newCatTitle
        self.inPlace = inPlace
        self.moveCatPage = moveCatPage
        self.batchMode = batchMode
        self.deleteEmptySourceCat = deleteEmptySourceCat
        self.titleRegex = titleRegex
        self.useSummaryForDeletion = useSummaryForDeletion
        self.withHistory = withHistory

    def run(self):
        """The main bot function that does all the work."""
        site = pywikibot.getSite()
        newCat = catlib.Category(site, self.newCatTitle)
        # set edit summary message
        if self.useSummaryForDeletion and self.editSummary:
            reason = self.editSummary
        else:
            reason = i18n.twtranslate(site, 'category-was-moved', {
                'newcat': self.newCatTitle,
                'title': self.newCatTitle
            })
        if not self.editSummary:
            self.editSummary = i18n.twtranslate(site, 'category-changing', {
                'oldcat': self.oldCat.title(),
                'newcat': newCat.title()
            })

        # Copy the category contents to the new category page
        copied = False
        oldMovedTalk = None
        if (site.isAllowed('move-categorypages') and self.oldCat.exists()
                and self.moveCatPage):
            self.oldCat.move(newCat.title(),
                             reason=self.editSummary,
                             movetalkpage=True,
                             leaveRedirect=not self.deleteEmptySourceCat)
            copied = True
        elif self.oldCat.exists() and self.moveCatPage:
            copied = self.oldCat.copyAndKeep(
                newCat.title(), pywikibot.translate(site, cfd_templates))
            # Also move the talk page
            if copied:
                oldTalk = self.oldCat.toggleTalkPage()
                if oldTalk.exists():
                    newTalkTitle = newCat.toggleTalkPage().title()
                    try:
                        talkMoved = oldTalk.move(newTalkTitle, reason)
                    except (pywikibot.NoPage, pywikibot.PageNotSaved), e:
                        #in order :
                        #Source talk does not exist, or
                        #Target talk already exists
                        pywikibot.output(e.message)
                    else:
                        if talkMoved:
                            oldMovedTalk = oldTalk

                if self.withHistory:
                    # Whether or not there was an old talk page, we write
                    # the page history to the new talk page
                    history = self.oldCat.getVersionHistoryTable()
                    # Set the section title for the old cat's history on the new
                    # cat's talk page.
                    sectionTitle = i18n.twtranslate(
                        site, 'category-section-title',
                        {'oldcat': self.oldCat.title()})
                    #Should be OK, we are within if self.oldCat.exists()
                    historySection = u'\n== %s ==\n%s' % (sectionTitle,
                                                          history)
                    try:
                        text = newCat.toggleTalkPage().get() + historySection
                    except pywikibot.NoPage:
                        text = historySection
                    try:
                        newCat.toggleTalkPage().put(
                            text,
                            i18n.twtranslate(site, 'category-version-history')
                            % {'oldcat': self.oldCat.title()})
                    except:
                        pywikibot.output(
                            'History of the category has not been saved to new '
                            'talk page')
                        #TODO: some nicer exception handling (not too important)
                        #      first move the page, than tagg the vh

        # Move articles
        gen = pagegenerators.CategorizedPageGenerator(self.oldCat,
                                                      recurse=False)
        preloadingGen = pagegenerators.PreloadingGenerator(gen)
        for article in preloadingGen:
            if not self.titleRegex or re.search(self.titleRegex,
                                                article.title()):
                catlib.change_category(article,
                                       self.oldCat,
                                       newCat,
                                       comment=self.editSummary,
                                       inPlace=self.inPlace)

        # Move subcategories
        gen = pagegenerators.SubCategoriesPageGenerator(self.oldCat,
                                                        recurse=False)
        preloadingGen = pagegenerators.PreloadingGenerator(gen)
        for subcategory in preloadingGen:
            if not self.titleRegex or re.search(self.titleRegex,
                                                subcategory.title()):
                catlib.change_category(subcategory,
                                       self.oldCat,
                                       newCat,
                                       comment=self.editSummary,
                                       inPlace=self.inPlace)

        # Delete the old category and its moved talk page
        if copied and self.deleteEmptySourceCat:
            if self.oldCat.isEmptyCategory():
                confirm = not self.batchMode
                self.oldCat.delete(reason, confirm, mark=True)
                if oldMovedTalk is not None:
                    oldMovedTalk.delete(reason, confirm, mark=True)
            else:
                pywikibot.output('Couldn\'t delete %s - not empty.' %
                                 self.oldCat.title())