def __iter__(self):
     checkme = aq_base(self.context)
     if IBibliographicItem.providedBy(checkme):
         biblio = queryAdapter(self.context, IBibliographicReference)
         if biblio is not None:
             yield biblio
     # common collection/topic API
     elif hasattr(checkme, 'queryCatalog'):
         for brain in self.context.queryCatalog():
             obj = brain.getObject()
             biblio = queryAdapter(obj, IBibliographicReference)
             if biblio is not None:
                 yield biblio
     # folderish thingies
     elif hasattr(checkme, 'objectValues'):
         for obj in self.context.objectValues():
             if IBibliographicItem.providedBy(obj):
                 try:
                     biblio = queryAdapter(obj, IBibliographicReference)
                 except AttributeError, e:
                     # this can happen if a bibliographic item does
                     # not have one of the required attributes for the 
                     # adapter.  Log the error
                     msg = "Adaptation of {} to IBibliographicReference "
                     msg += "failed due to a missing attribute: {}"
                     logger.warn(msg.format(obj.id, str(e)))
                     continue
                 if biblio is not None:
                     yield biblio
Exemplo n.º 2
0
Arquivo: view.py Projeto: RBINS/mars
 def get_ref_info(self, obj):
     """."""
     infos = None
     bview = self.get_biblio_view()
     if IBibliographicItem.providedBy(obj):
         infos = bview.infosFor(obj)
     return infos
Exemplo n.º 3
0
 def get_ref_info(self, obj):
     """."""
     infos = None
     bview = self.get_biblio_view()
     if IBibliographicItem.providedBy(obj):
         infos = bview.infosFor(obj)
     return infos
 def available(self):
     if (IBibliographicItem.providedBy(self.context) or
             IBibliographyFolder.providedBy(self.context) or
             ILargeBibliographyFolder.providedBy(self.context) or
             IBibViewMarker.providedBy(self.view)):
         return True
     return False
 def available(self):
     if (IBibliographicItem.providedBy(self.context)
             or IBibliographyFolder.providedBy(self.context)
             or ILargeBibliographyFolder.providedBy(self.context)
             or IBibViewMarker.providedBy(self.view)):
         return True
     return False
Exemplo n.º 6
0
    def render(self, objects,
                     title_force_uppercase=False,
                     output_encoding=None,
                     msdos_eol_style=False,
                     omit_fields_mapping={}):
        """ Export a bunch of bibliographic entries in bibex format"""

        # This implementation here is completely bullshit from the 
        # beginning. Why is there no interface and API for getting hold
        # of the exportable items? The iterator interface here sucks.
        # This method should also work with *single* bibliographic entries.

        #request = getattr(objects[0], 'REQUEST', None)
        #if request is None:
        request = TestRequest()

        # Adapt to IBibliography if necessary/possible
        # If not, it could be ok if `entries' can be iterated over anyway.
        objects = IBibliography(objects, objects)

        found = False
        if HAVE_CMFBIB_AT:
            if IBibliographicItem.providedBy(objects):
                entries = [objects]
                found = True

        if not found:
            try:
                # We want the values from a dictionary-ish/IBibliography object
                entries = objects.itervalues()
            except AttributeError:
                # Otherwise we just iterate over what is presumably something
                # sequence-ish.
                entries = iter(objects)

        rendered = []
        for obj in entries:
            ref = queryAdapter(obj, interface=IBibliographicReference,
                                    name=self.__name__)
            if ref is None:
                # if there is no named adapter, get the default adapter
                # compatibility with older versions
                ref = IBibliographicReference(obj, None)
            if ref is None:
                continue

            # do rendering for entry
            view = getMultiAdapter((ref, request), name=self.view_name)
            omit_fields = omit_fields_mapping.get(ref.publication_type, [])
            bibtex_string = view.render(title_force_uppercase=title_force_uppercase,
                                        omit_fields=omit_fields
                                        )
            rendered.append(bibtex_string)

        rendered = ''.join(rendered)
        if msdos_eol_style:
            rendered = rendered.replace('\n', '\r\n')
        return rendered
Exemplo n.º 7
0
 def getAuthorsList(self, firstfull=False):
     if IBibliographicItem.providedBy(self.context):
         authors = [dict(e) for e in self.context.getAuthors()]
         results = []
         for e in authors:
             result = []
             for k in self.ifs:
                 if k not in e:
                     e[k] = ''
                 result.append(e[k])
             results.append(tuple(result))
         if results:
             return results
Exemplo n.º 8
0
 def getAuthorsList(self, firstfull=False):
     if IBibliographicItem.providedBy(self.context):
         authors = [dict(e) for e in self.context.getAuthors()]
         results = []
         for e in authors:
             result = []
             for k in self.ifs:
                 if k not in e:
                     e[k] = ""
                 result.append(e[k])
             results.append(tuple(result))
         if results:
             return results
    def getFeedEntries(self, max_only=True):
        """ See IFeedSource """

        ps = getToolByName(self.context, "portal_syndication")
        if not ps.isSyndicationAllowed(self.context):
            raise ValueError(
                "Site syndication via RSS feeds is not allowed. "
                "Ask the sites system administrator to go to "
                "portal_syndication > Policies and enable "
                "syndication. Each folder then needs to have "
                "syndication enabled."
            )

        brains = self.context.getFolderContents()
        objs = [brain.getObject() for brain in brains]
        objs = [o for o in objs if IBibliographicItem.providedBy(o)]
        for o in objs:
            o2 = IFeedEntry(o, None)
            if o2:
                yield o2
    def render(
        self, objects, title_force_uppercase=False, output_encoding=None, msdos_eol_style=False, omit_fields_mapping={}
    ):
        """ Export a bunch of bibliographic entries in ref format"""
        request = TestRequest()
        objects = IBibliography(objects, objects)
        found = False
        if IBibliographicItem.providedBy(objects):
            entries = [objects]
            found = True

        if not found:
            try:
                # We want the values from a dictionary-ish/IBibliography object
                entries = objects.itervalues()
            except AttributeError:
                # Otherwise we just iterate over what is presumably something
                # sequence-ish.
                entries = iter(objects)
        rendered = []
        for obj in entries:
            ref = queryAdapter(obj, interface=IBibliographicReference, name=self.__name__)
            if ref is None:
                # if there is no named adapter, get the default adapter
                # compatibility with older versions
                ref = IBibliographicReference(obj, None)
            if ref is None:
                continue

            # do rendering for entry
            view = getMultiAdapter((ref, request), name=self.view_name)
            omit_fields = omit_fields_mapping.get(ref.publication_type, [])
            ref_string = view.render(title_force_uppercase=title_force_uppercase, omit_fields=omit_fields)
            rendered.append(ref_string)

        rendered = "".join(rendered)
        if msdos_eol_style:
            rendered = rendered.replace("\n", "\r\n")
        return rendered
Exemplo n.º 11
0
    def infosFor(self, it, firstfull=False, invert=False):
        authors_links = []
        catalog = getToolByName(it, 'portal_catalog')
        if (('brain' not in it.__class__.__name__)
                and IBibliographicItem.providedBy(it)):
            it = catalog.search(
                dict(path={
                    'depth': 0,
                    'query': '/'.join(it.getPhysicalPath())
                }))[0]
        path = it.getPath()
        authors = []
        if it.bAuthorsList:
            for ue in it.bAuthorsList:
                e = {
                    'lastname':
                    ue[0],
                    'firstname':
                    ue[1],
                    'middlename':
                    ue[2],
                    'formatedfname':
                    format_firstname((ue[1] + " " + ue[2]).strip(),
                                     firstfull=firstfull),
                    'homepage':
                    ue[3],
                }
                if invert:
                    author = ('%(formatedfname)s %(lastname)s' % e).strip()
                else:
                    author = ('%(lastname)s %(formatedfname)s' % e).strip()
                if e['homepage']:
                    author = '<a href="%s">%s</a>' % (
                        e['homepage'],
                        author,
                    )
                e['author'] = author
                authors_links.append(author)
                authors.append(e)
        title = it.Title
        related = catalog.uniqueValuesFor('getRawRelatedItems')
        has_relitems = bool(
            len([
                a for a in catalog.search(
                    dict(path={
                        'depth': 0,
                        'query': path
                    },
                         getRawRelatedItems=related))
            ]))

        path = it.getPath()
        if not path:
            path = ''
        else:
            try:
                try:
                    path = path[len(self.root_path) + 1:]
                except Exception:
                    pass
            except Exception:
                path = ''

        data = {
            'has_relitems': has_relitems,
            'title': title,
            'authors': authors,
            'authors_links': authors_links,
            'title': title.strip(),
            'publication_year': it.publication_year,
            'source': it.bSource,
            'path': path,
            'url': it.getURL(),
        }
        return data
Exemplo n.º 12
0
 def getSource(self):
     if IBibliographicItem.providedBy(self.context):
         return self.context.Source()
Exemplo n.º 13
0
 def __call__(self):
     # This check is completely bullshit: it does not take export
     # adapters into account nor does it work with the old-style
     # IBibliographyExport interface as used in base.py
     return IBibliographyExport.providedBy(self.context) or IBibliographicItem.providedBy(self.context)
Exemplo n.º 14
0
    def infosFor(self, it, firstfull=False, invert=False):
        # logging.getLogger('foo').error('info hitted')
        authors_links = []
        catalog = getToolByName(it, "portal_catalog")
        if ("brain" not in it.__class__.__name__) and IBibliographicItem.providedBy(it):
            it = catalog.search(dict(path={"depth": 0, "query": "/".join(it.getPhysicalPath())}))[0]
        path = it.getPath()
        authors = []
        # if 'brain' in it.__class__.__name__:
        #    item = it.getObject()
        if it.bAuthorsList:
            for ue in it.bAuthorsList:
                e = {
                    "lastname": ue[0],
                    "firstname": ue[1],
                    "middlename": ue[2],
                    "formatedfname": format_firstname((ue[1] + " " + ue[2]).strip(), firstfull=firstfull),
                    "homepage": ue[3],
                }
                if invert:
                    author = ("%(formatedfname)s %(lastname)s" % e).strip()
                else:
                    author = ("%(lastname)s %(formatedfname)s" % e).strip()
                if e["homepage"]:
                    author = '<a href="%s">%s</a>' % (e["homepage"], author)
                if author:
                    if "\\x" in repr(author[-2:]):
                        initial = ue[1][0:2]
                        author = author[:-2] + initial + author[-1:]
                e["author"] = author
                authors_links.append(author)
                authors.append(e)
        title = it.Title
        related = catalog.uniqueValuesFor("getRawRelatedItems")
        has_relitems = bool(
            len([a for a in catalog.search(dict(path={"depth": 0, "query": path}, getRawRelatedItems=related))])
        )

        path = it.getPath()
        if not path:
            path = ""
        else:
            try:
                try:
                    path = path[len(self.root_path) + 1 :]
                except Exception:
                    pass
            except Exception:
                path = ""

        data = {
            "has_relitems": has_relitems,
            "title": title,
            "authors": authors,
            "authors_links": authors_links,
            "title": title.strip(),
            "publication_year": it.publication_year,
            "source": it.bSource,
            "path": path,
            "url": it.getURL(),
        }
        return data
Exemplo n.º 15
0
 def getSource(self):
     if IBibliographicItem.providedBy(self.context):
         return self.context.Source()