def move_documents_in_proposal_to_dossier(options):
    """Move documents placed in a proposal to their parent dossier.

    """

    catalog = api.portal.get_tool('portal_catalog')
    brains = catalog.unrestrictedSearchResults(
        portal_type='opengever.meeting.proposal')

    with elevated_privileges():
        for brain in brains:
            proposal = brain.getObject()
            document_brains = catalog.unrestrictedSearchResults(
                path=brain.getPath(),
                portal_type='opengever.document.document')
            for document_brain in document_brains:
                document = document_brain.getObject()
                dossier = proposal.get_containing_dossier()
                logger.info("moving document {} to dossier {}".format(
                    document_brain.getPath(),
                    "/".join(dossier.getPhysicalPath())))
                api.content.move(source=document, target=dossier)

    if not options.dry_run:
        logger.info("committing...")
        transaction.commit()
    logger.info("done.")
def use_canonical_document_id(options):
    """Rename documents that do not use the current naming-schema.

    Also write a short report of the renamed documents to a csv file.

    """
    catalog = api.portal.get_tool('portal_catalog')
    brains = catalog.unrestrictedSearchResults(
        portal_type='opengever.document.document')

    to_rename = []

    for brain in brains:
        name = brain.id
        if name.startswith('template-') or name.startswith('document-'):
            continue

        to_rename.append(brain.getObject())

    if to_rename:
        logger.info(SEPARATOR)

    def build_url(fragment):
        fragment = urllib.quote(fragment)
        if not options.domain:
            return fragment

        # we assume a virtualhost and strip the plone site id
        assert fragment.startswith("/"), "path should start with /"
        visible_fragment = "/".join(fragment.split('/')[2:])
        base = "https://{}/".format(options.domain)
        return urljoin(base, visible_fragment)

    def commit():
        if options.dry_run:
            return

        if options.verbose:
            logger.info("committing...")
        transaction.commit()

    with open(REPORT_PATH, 'w+') as csvfile:
        writer = DictWriter(csvfile, fieldnames=["old_url", "new_url"])
        writer.writeheader()

        # elevated privileges are necessary to be able to modify stuff in
        # closed dossiers.
        with elevated_privileges():
            for index, obj in enumerate(ProgressLogger("renaming", to_rename)):
                parent = aq_parent(aq_inner(obj))
                old_url = '/'.join(obj.getPhysicalPath())
                new_name = INameChooser(parent).chooseName(None, obj)
                api.content.rename(obj=obj, new_id=new_name)
                new_url = '/'.join(obj.getPhysicalPath())
                writer.writerow({
                    "old_url": build_url(old_url),
                    "new_url": build_url(new_url)
                })

                if index and index % 100 == 0:
                    commit()

    commit()
    logger.info("done.")