Ejemplo n.º 1
0
    def run(self):
        articles = set(self.cat.articles())
        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)
        if self.pagesonly:
            return

        # Also removes the category tag from subcategories' pages
        subcategories = set(self.cat.subcategories())
        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 = set(self.cat.articles())
        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)
        if self.pagesonly:
            return

        # Also removes the category tag from subcategories' pages
        subcategories = set(self.cat.subcategories())
        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.º 3
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)
        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
            pywikibot.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
            pywikibot.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)'
        pywikibot.output(u'Enter - Save category as %s' % current_cat.title())

        flag = False
        while not flag:
            print ''
            choice = pywikibot.input(u'Choice:')
            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:
                    catlib.change_category(article, original_cat, current_cat, comment=self.editSummary)
                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.Link('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
                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.º 4
0
    def run(self):
        if self.withHistory:
            raise NotImplementedError("History printing is not yet enabled.")
        site = pywikibot.getSite()
        newCat = pywikibot.Category(
            pywikibot.Link('Category:' + self.newCatTitle))
        newcat_contents = set(newCat.members())
        # set edit summary message
        if not self.editSummary:
            self.editSummary = i18n.twtranslate(site, 'category-replacing',
                                                {'oldcat': self.oldCat.title(),
                                                 'newcat': newCat.title()})

        # 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),
                i18n.twtranslate(site, 'category-renamed')
            )
            # Also move the talk page
            if copied:
                reason = i18n.twtranslate(
                    site, 'category-was-moved',
                    {'newcat': self.newCatTitle, 'title': self.newCatTitle}
                )
                oldTalk = self.oldCat.toggleTalkPage()
                if oldTalk.exists():
                    newTalkTitle = newCat.toggleTalkPage().title()
                    try:
                        talkMoved = oldTalk.move(newTalkTitle, reason)
                    except (pywikibot.NoPage, pywikibot.PageNotSaved) as 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()):
                if article in newcat_contents:
                    catlib.change_category(article, self.oldCat, None,
                                           comment=self.editSummary,
                                           inPlace=self.inPlace)
                else:
                    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()):
                if subcategory in newcat_contents:
                    catlib.change_category(subcategory, self.oldCat, None,
                                           comment=self.editSummary,
                                           inPlace=self.inPlace)
                else:
                    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():
                reason = i18n.twtranslate(
                    site, 'category-was-moved',
                    {'newcat': self.newCatTitle, 'title': self.newCatTitle}
                )
                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.º 5
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)
        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
            pywikibot.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
            pywikibot.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)'
        pywikibot.output(u'Enter - Save category as %s' % current_cat.title())

        flag = False
        while not flag:
            print ''
            choice = pywikibot.input(u'Choice:')
            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:
                    catlib.change_category(article,
                                           original_cat,
                                           current_cat,
                                           comment=self.editSummary)
                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.Link('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
                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.º 6
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(pywikibot.Link('Category:' +
                                                     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(pywikibot.Link('Category:' +
                                                self.newCatTitle))
        newcat_contents = set(newCat.members())
        # set edit summary message
        if not self.editSummary:
            self.editSummary = i18n.twtranslate(site, 'category-replacing', {
                'oldcat': self.oldCat.title(),
                'newcat': newCat.title()
            })

        # 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),
                i18n.twtranslate(site, 'category-renamed'))
            # Also move the talk page
            if copied:
                reason = i18n.twtranslate(site, 'category-was-moved', {
                    'newcat': self.newCatTitle,
                    'title': self.newCatTitle
                })
                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()):
                if article in newcat_contents:
                    catlib.change_category(article,
                                           self.oldCat,
                                           None,
                                           comment=self.editSummary,
                                           inPlace=self.inPlace)
                else:
                    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()):
                if subcategory in newcat_contents:
                    catlib.change_category(subcategory,
                                           self.oldCat,
                                           None,
                                           comment=self.editSummary,
                                           inPlace=self.inPlace)
                else:
                    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():
                reason = i18n.twtranslate(site, 'category-was-moved', {
                    'newcat': self.newCatTitle,
                    'title': self.newCatTitle
                })
                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())