def test_adding(self):
        """
        :return:
        """
        _id = self.book.generateUniqueId(CONTENT_TYPE_BOOK_LOAN)

        intids = getUtility(IIntIds)

        _book = RelationValue(intids.getId(self.book))
        _student = RelationValue(intids.getId(self.student))
        _loan_duration = safe_unicode('2')
        _loan_status = safe_unicode('running')

        self.book.invokeFactory(CONTENT_TYPE_BOOK_LOAN, _id)
        loan = self.book[_id]

        self.assertTrue(IBookLoan.providedBy(loan))

        loan.student = _student
        loan.book = _book
        loan.loan_duration = _loan_duration
        loan.loan_status = _loan_status
        loan.reindexObject()

        # Let's manually triggers
        collective_datatable_book_loan_created(loan, None)

        result = self.portal.portal_catalog.searchResults(id=loan.id)

        self.assertEquals(1, len(result))
        self.assertEqual(self.book, loan.book.to_object)
        self.assertEqual(self.student, loan.student.to_object)
        # Make sure events fired
        self.assertFalse(loan.is_lock)
        self.assertEqual(self.book.number_of_loan_copy, 2)
示例#2
0
    def _createArchiveFolders(self):
        """
        We create an archive object. Into it, we copy the complete ESD hierarchy. 
        We also create two folders "Members" and "Groups", which will hold all the
        documents for the scenario.
        """
        a = self.archive  # Acquire root for archives
        e = self.esd  # Acquire esd root
        now = safe_unicode(self.toLocalizedTime(DateTime(), long_format=1))
        id = ploneId(self, "%s_%s" % (self.getId(), now))
        title = u"%s %s" % (safe_unicode(self.Title()), now)
        # create the archive root
        a.invokeFactory(id=id, type_name="ELANArchive", title=title)
        arc = a._getOb(id)  # get new empty archive
        arc.setDescription(self.Description())
        # create the document folders
        createPloneObjects(arc, ARCHIVESTRUCTURE)
        createPloneObjects(arc.content, TRANSFER_AREA)

        navSettings(arc)

        # copy the ESD folders
        objs = [o.getId for o in e.getFolderContents({'portal_type': ['ELANSection', 'ELANDocCollection']})]
        # print objs
        cb_copy_data = e.manage_copyObjects(objs)  # Copy aus der Quelle
        result = arc.esd.manage_pasteObjects(cb_copy_data)
        arc.esd.setDefaultPage("overview")

        return arc
示例#3
0
def query(
    path=None,
    path_depth=None,
    tags=[],
    portal_types=None,
    facet_by=None,
    sort_by=None,
    searchable_text=None,
    debug=False,
):
    """Helper method for Solr power search:
    - adds request_tag to search phrase
    - sorts on title
    """
    sitesearch = getUtility(ISiteSearch)
    Q = sitesearch.Q

    lucene_query = Q()
    if path:
        lucene_query &= Q(path_parents=path)
    if path_depth:
        if not isinstance(path_depth, (list, tuple)):
            lucene_query &= Q(path_depth=path_depth)
        else:
            subquery = Q()
            for pd in path_depth:
                subquery |= Q(path_depth=pd)
            lucene_query &= subquery
    tags = tags or []
    if isinstance(tags, basestring):
        tags = [tags]
    for tag in tags:
        lucene_query &= Q(tags=safe_unicode(tag))
    if portal_types:
        subquery = Q()
        for pt in portal_types:
            subquery |= Q(portal_type=pt)
        lucene_query &= subquery
    if searchable_text:
        lucene_query &= Q(SearchableText=safe_unicode(searchable_text))
    solr_query = sitesearch._create_query_object(None)
    solr_query = solr_query.filter(lucene_query)
    if facet_by:
        solr_query = solr_query.facet_by(facet_by)
    if sort_by:
        if isinstance(sort_by, basestring):
            sort_by = [sort_by]
        for sb in sort_by:
            solr_query = solr_query.sort_by(sb)
    if debug:
        solr_query = sitesearch._apply_debug(solr_query)

    response = sitesearch.execute(
        solr_query.paginate(rows=99999),
        debug=debug
    )
    return ISearchResponse(response)
    def filter_fields(self):
        fields = ()
        d_vals = getattr(self.view, 'default_values', {})
        p_query = queryparser.parseFormquery(self.context, self.context.query)
        try:
            trans_map = resolve_dottedname(api.portal.get_registry_record(
                'kombinat.behavior.collectionfilter.translation_map'))
        except:
            # fallback
            trans_map = FILTER_TRANSLATION_MAP or {}
        try:
            vocab_map = resolve_dottedname(api.portal.get_registry_record(
                'kombinat.behavior.collectionfilter.vocabulary_map'))
        except:
            # fallback
            vocab_map = FILTER_VOCABULARY_MAP or {}

        for idx in trans_map.keys():
            if idx in (getattr(self.context, 'ignore_fields', []) or []):
                # visibility of filter fields
                continue
            qvals = p_query.get(idx, {}).get('query', [])
            i_sel = safe_unicode(self.request.get(idx) or d_vals.get(idx))
            label_vocab = vocab_map.get(idx,
                lambda x: None)(self.context)

            def option_label(value):
                if label_vocab:
                    try:
                        return label_vocab.getTermByToken(value).title
                    except:
                        pass
                return translate(_pmf(value), context=self.request)

            if idx == 'path':
                vals = []
                for v in qvals:
                    try:
                        loc_title = self.context.restrictedTraverse(
                            v.encode('utf8')).Title()
                    except Exception, msg:
                        logger.info("error: {}".format(msg))
                        continue
                    vals.append(dict(value=v, title=loc_title,
                        selected=i_sel == v and 'selected' or ''))
            else:
                vals = [dict(value=v, title=option_label(v),
                    selected=safe_unicode(i_sel) == v \
                    and 'selected' or '') for v in qvals if v]
            if not vals or len(vals) < 2:
                continue
            fields += (dict(
                name=idx,
                placeholder=translate(trans_map.get(idx, idx),
                    context=self.request),
                options=sorted(vals, key=itemgetter('title')),
            ), )
示例#5
0
    def get_label(self, with_principal=True):
        name = self.user.getProperty('fullname')
        if not name:
            name = safe_unicode(self.user.getUserName())

        if with_principal:
            return u'{} ({})'.format(safe_unicode(name), safe_unicode(self.identifier))
        else:
            return name
示例#6
0
    def get_label(self, with_principal=True):
        name = self.user.getProperty('fullname')
        if not name:
            name = safe_unicode(self.user.getUserName())

        if with_principal:
            return u'{} ({})'.format(safe_unicode(name),
                                     safe_unicode(self.identifier))
        else:
            return name
示例#7
0
    def setUp(self):
        self.portal = self.layer["portal"]
        setRoles(self.portal, TEST_USER_ID, ["Manager"])

        subjects = [safe_unicode("\xc3\xbcber Keyword"), safe_unicode("Second one")]

        self.content = api.content.create(
            container=api.portal.get(),
            type="Document",
            title="test document",
            subject=subjects,
        )
    def test_adding_by_browser(self):

        """
        :return:
        """
        _resource_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources")
        _id = safe_unicode("test-first-review")
        _title = safe_unicode("Test First Review")
        _description = safe_unicode("<h1>Test Book Review</h1>")
        _reviewer = self.student.UID()
        _attachment = "test-review.pdf"

        _url = self.book.absolute_url() + "/++add++" + CONTENT_TYPE_BOOK_REVIEW
        self.browser.open(_url)

        try:
            form = self.browser.getForm(id="form")

        except LookupError as exc:

            if not self.browser.cookies.get("__ac", None):

                self.browser_login()
                form = self.browser.getForm(id="form")
            else:
                raise LookupError(exc.message)

        # Fill the form
        form.getControl(name="form.widgets.title").value = _title
        form.getControl(name="form.widgets.description").value = _description
        form.getControl(name="form.widgets.reviewer").value = _reviewer

        form.getControl(name="form.widgets.IShortName.id").value = _id
        form.getControl(name="form.widgets.IExcludeFromNavigation.exclude_from_nav:list").value = 1
        form.getControl(name="form.widgets.INextPreviousToggle.nextPreviousEnabled:list").value = 1

        file_control = form.getControl(name="form.widgets.attachment")
        file_control.add_file(open(os.path.join(_resource_path, _attachment), "rb"), "application/pdf", _attachment)

        form.submit(form.getControl(name="form.buttons.save").value)

        self.assertEqual(
            self.book.absolute_url() + "/" + _id + "/view",
            self.browser.url,
            "Current URL should be default view for newly created review",
        )
        review = self.portal.portal_catalog.searchResults(portal_type=CONTENT_TYPE_BOOK_REVIEW, id=_id)
        review = review[0]

        self.assertEqual(review.Title, _title)
        self.assertEqual(review.getObject().reviewer.to_object, self.student)
        self.assertEqual(review.getObject().attachment.filename, _attachment)
    def _book_structure(self):
        """
        :return:
        """
        self.library.invokeFactory(CONTENT_TYPE_BOOK, 'book')
        self.book = self.library['book']
        self.book.setTitle('My Test Book')

        self.book.details = safe_unicode('<h1>Test Book Details</h1>')
        self.book.isbn = safe_unicode('98-999-99-9999')
        self.book.author = safe_unicode('Test Author')
        self.book.publisher = safe_unicode('Test Publisher')
        self.book.number_of_copy = safe_unicode('2')
    def test_invalid_ssn(self):
        """
        :return:
        """
        _id = safe_unicode('test-first-book')
        _title = safe_unicode('Test First Book')
        _description = safe_unicode('The test description')
        _isbn = safe_unicode('ISBN 978-0-3-0-40615-7')
        _number_of_copy = safe_unicode('10')

        _url = self.library.absolute_url() + '/++add++' + CONTENT_TYPE_BOOK
        self.browser.open(_url)

        try:
            form = self.browser.getForm(id='form')

        except LookupError as exc:

            if not self.browser.cookies.get('__ac', None):

                self.browser_login()
                form = self.browser.getForm(id='form')
            else:
                raise LookupError(exc.message)

        # Fill the form
        form.getControl(name='form.widgets.title').value = _title
        form.getControl(name='form.widgets.description').value = _description
        form.getControl(name='form.widgets.isbn').value = _isbn
        form.getControl(name='form.widgets.number_of_copy').value = _number_of_copy

        form.getControl(name='form.widgets.IShortName.id').value = _id

        form.submit(form.getControl(name='form.buttons.save').value)

        self.assertEqual(self.library.absolute_url() + '/++add++' + CONTENT_TYPE_BOOK, self.browser.url,
                         'Current URL should be same as add url `++add++%s`, because of validation error'
                         % CONTENT_TYPE_BOOK)

        html_output = BeautifulSoup(self.browser.contents.strip('\n'), 'lxml')
        isbn_container = html_output.find('div', id='formfield-form-widgets-isbn')

        error = isbn_container.find('div', class_='fieldErrorBox').find('div', class_='error')

        # We make sure error message shown.
        self.assertIsNotNone(error)
        # We make sure `ISBN` related message
        self.assertIn('isbn', error.text.lower())
示例#11
0
    def send_sector_manager_notifications(self, outdated_tool_paths):
        sector_paths = set()
        for path in outdated_tool_paths:
            sector_path = '/'.join(path.split('/')[:5])
            sector_paths.add(sector_path)
        for sector_path in sector_paths:
            sector = self.context.unrestrictedTraverse(sector_path, False)
            if not sector or sector.portal_type != 'euphorie.sector':
                log.error('Missing sector: {}'.format(sector_path))
                continue
            contact_name = sector.contact_name or ''
            contact_email = sector.contact_email
            if not contact_email:
                log.error('No contact email address: {}'.format(sector_path))
                continue
            sector_tools = filter(
                lambda x: x.startswith(sector_path), outdated_tool_paths)
            intro = u"""
You are receiving this notification since you are the sector manager for
"{0}" """.format(safe_unicode(sector.Title()))
            self.send_notification(
                to_name=contact_name,
                to_address=contact_email,
                tool_paths=sector_tools,
                intro=intro,
            )
示例#12
0
    def send_country_manager_notifications(self, outdated_tool_paths):
        country_paths = set()
        for path in outdated_tool_paths:
            country_path = "/".join(path.split("/")[:4])
            country_paths.add(country_path)
        for country_path in country_paths:
            country_tools = filter(
                lambda x: x.startswith(country_path), outdated_tool_paths
            )
            country = self.context.unrestrictedTraverse(country_path)
            view = country.restrictedTraverse("manage-ldap-users", None)
            managers = (
                [
                    userid
                    for userid in view.local_roles_userids()
                    if view.get_user(userid)
                ]
                if view
                else []
            )
            for manager in managers:
                intro = """
You are receiving this notification since you are the country manager for
"{0}". """.format(
                    safe_unicode(country.Title())
                )

                self.send_notification(
                    to_name="",
                    to_address=manager,
                    tool_paths=country_tools,
                    intro=intro,
                )
示例#13
0
    def send_sector_manager_notifications(self, outdated_tool_paths):
        sector_paths = set()
        for path in outdated_tool_paths:
            sector_path = "/".join(path.split("/")[:5])
            sector_paths.add(sector_path)
        for sector_path in sector_paths:
            sector = self.context.unrestrictedTraverse(sector_path, False)
            if not sector or sector.portal_type != "euphorie.sector":
                log.error("Missing sector: {}".format(sector_path))
                continue
            contact_name = sector.contact_name or ""
            contact_email = sector.contact_email
            if not contact_email:
                log.error("No contact email address: {}".format(sector_path))
                continue
            sector_tools = filter(
                lambda x: x.startswith(sector_path), outdated_tool_paths
            )
            intro = """
You are receiving this notification since you are the sector manager for
"{0}". """.format(
                safe_unicode(sector.Title())
            )
            self.send_notification(
                to_name=contact_name,
                to_address=contact_email,
                tool_paths=sector_tools,
                intro=intro,
            )
示例#14
0
    def send_country_manager_notifications(self, outdated_tool_paths):
        country_paths = set()
        for path in outdated_tool_paths:
            country_path = '/'.join(path.split('/')[:4])
            country_paths.add(country_path)
        for country_path in country_paths:
            country_tools = filter(
                lambda x: x.startswith(country_path), outdated_tool_paths)
            country = self.context.unrestrictedTraverse(country_path)
            managers = [
                i for i in country.values() if ICountryManager.providedBy(i)]
            for manager in managers:
                contact_name = manager.Title() or ''
                contact_email = manager.contact_email
                if not contact_email:
                    continue
                intro = u"""
You are receiving this notification since you are the country manager for
"{0}". """.format(safe_unicode(country.Title()))

                self.send_notification(
                    to_name=contact_name,
                    to_address=contact_email,
                    tool_paths=country_tools,
                    intro=intro,
                )
示例#15
0
 def __init__(self, request, props):
     self.is_user_logged_in = False
     self.properties = props
     self.userid = safe_unicode(self.properties.get('userid'))
     self.request = request
     self.first_login = False
     self.mtool = api.portal.get_tool('portal_membership')
示例#16
0
    def send_country_manager_notifications(self, outdated_tool_paths):
        country_paths = set()
        for path in outdated_tool_paths:
            country_path = '/'.join(path.split('/')[:4])
            country_paths.add(country_path)
        for country_path in country_paths:
            country_tools = filter(
                lambda x: x.startswith(country_path), outdated_tool_paths)
            country = self.context.unrestrictedTraverse(country_path)
            managers = [
                i for i in country.values() if ICountryManager.providedBy(i)]
            for manager in managers:
                contact_name = manager.Title() or ''
                contact_email = manager.contact_email
                if not contact_email:
                    continue
                intro = u"""
You are receiving this notification since you are the country manager for
"{0}" """.format(safe_unicode(country.Title()))

                self.send_notification(
                    to_name=contact_name,
                    to_address=contact_email,
                    tool_paths=country_tools,
                    intro=intro,
                )
示例#17
0
 def get_title(self, contact):
     if self.in_fields("title"):
         return u'<a href="{0}" target="_blank"><h4>{1}</h4></a>'.format(
             contact.absolute_url(), safe_unicode(contact.title)
         )
     else:
         return False
 def __call__(self):
     req_file = self.request.get('file')
     c_type = req_file.headers.get('content-type', '')
     file_data = req_file.read()
     file_name = safe_unicode(req_file.filename)
     media_container = self.get_media_container()
     behavior = IRelatedMedia(self.context)
     if c_type.startswith("image/"):
         blob = NamedBlobImage(data=file_data, filename=file_name)
         img = createContentInContainer(
             media_container, "Image", image=blob)
         # safe image as leadImage if none exists
         if ILeadImage.providedBy(self.context) and \
            ILeadImage(self.context).image is None:
             ILeadImage(self.context).image = blob
         else:
             to_id = self.intids.getId(img)
             imgs = behavior.related_images and \
                 list(behavior.related_images) or []
             imgs.append(RelationValue(to_id))
             behavior.related_images = imgs
     else:
         blob = NamedBlobFile(data=file_data, filename=file_name)
         att = createContentInContainer(media_container, "File", file=blob)
         to_id = self.intids.getId(att)
         atts = behavior.related_attachments and \
             list(behavior.related_attachments) or []
         atts.append(RelationValue(to_id))
         behavior.related_attachments = atts
     return json.dumps(dict(
         status=u"done",
     ))
示例#19
0
    def query(self, path=None, tag=None, portal_types=None):
        """Helper method for Solr power search:
        - adds self.request_tag to search phrase
        - sorts on title
        """
        Q = self.sitesearch.Q
        _query = self.sitesearch.connection.query()
        lucene_query = Q()
        if path:
            lucene_query &= Q(path_parents=path)
        if tag:
            lucene_query &= Q(tags=safe_unicode(tag))
        if self.request_tag:
            lucene_query &= Q(tags=self.request_tag)
        if portal_types:
            subquery = Q()
            for pt in portal_types:
                subquery |= Q(portal_type=pt)
            lucene_query &= subquery

        _query = _query.filter(lucene_query)
        _query = _query.facet_by('tags')
        _query = _query.sort_by('Title')
        response = self.sitesearch.execute(_query)
        return ISearchResponse(response)
示例#20
0
 def image(self):
     """
     """
     # We need to acquire Manager rights here, since we are called in traversal code,
     # which unfortunately comes as Anoymous
     data, filename = execute_under_special_role(self, "Manager", self.getMyImage, False)
     return namedfile.NamedImage(data, filename=safe_unicode(filename))
示例#21
0
 def _tags_facet(self, searchresponse):
     """
     ZCatalog returns <str> Solr returns <unicode>.
     We force everything into unicode and sort abc.
     """
     return sorted(
         [safe_unicode(t) for t in searchresponse.facets.get('tags', [])])
示例#22
0
 def _tags_facet(self, searchresponse):
     """
     ZCatalog returns <str> Solr returns <unicode>.
     We force everything into unicode.
     """
     return [safe_unicode(t)
             for t in searchresponse.facets.get('tags', [])]
示例#23
0
 def publishReport(self, justDoIt=False, duplicate=False):
     """
     """
     request = self.REQUEST
     alsoProvides(request, IDisableCSRFProtection)
     new_version = self
     if duplicate:
         new_version = content.copy(source=self, id=self.getId(), safe_id=True)
     # copy modules into the report?
     # We would lose all the reference information, which is important for the situation overview
     #mods = self.myModules()
     #for mod in mods:
     #    content.copy(source=mod, target=new_version, safe_id=True)
     # create PDF, upload it
     data = self.restrictedTraverse("@@pdfprint")._generatePDF(raw=True)
     nice_filename = 'report_%s_%s.pdf' % (self.getId(), datetime.now().strftime('%Y%m%d'))
     nice_filename = safe_unicode(nice_filename)
     field = NamedBlobFile(data=data, filename=nice_filename)
     fid = new_version.invokeFactory(id=nice_filename, type_name="File", title=self.Title(), description="")
     f = new_version._getOb(fid)
     f.file = field
     f.reindexObject()
     
     content.transition(new_version, transition="publish")
     if not justDoIt:
         portalMessage(self, _("The report has been published."), "info")
         return self.restrictedTraverse("@@view")()
示例#24
0
 def __call__(self):
     self.pworkflow = getToolByName(self.context, 'portal_workflow')
     self.putils = getToolByName(self.context, 'plone_utils')
     self.transition_id = self.request.form.get('transition', None)
     self.comments = self.request.form.get('comments', '')
     self.recurse = self.request.form.get('recurse', 'no') == 'yes'
     if self.request.form.get('render') == 'yes':
         # asking for render information
         selection = self.get_selection()
         catalog = getToolByName(self.context, 'portal_catalog')
         brains = catalog(UID=selection, show_inactive=True)
         transitions = []
         for brain in brains:
             obj = brain.getObject()
             for transition in self.pworkflow.getTransitionsFor(obj):
                 tdata = {
                     'id':
                     transition['id'],
                     'title':
                     self.context.translate(safe_unicode(
                         transition['name']))
                 }
                 if tdata not in transitions:
                     transitions.append(tdata)
         return self.json({'transitions': transitions})
     else:
         return super().__call__()
    def test_adding_by_browser(self):

        """
        :return:
        """
        _resource_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'resources')
        _id = safe_unicode('test-first-name')
        _first_name = safe_unicode('Test First Name')
        _last_name = safe_unicode('Last')
        _gender = safe_unicode('male')
        _roll_number = safe_unicode('1001')
        _grade = safe_unicode('g4')
        _contact_number = safe_unicode('980000000')
        _profile_photo = 'student.jpg'

        _url = self.school.absolute_url() + '/++add++' + CONTENT_TYPE_STUDENT
        self.browser.open(_url)

        try:
            form = self.browser.getForm(id='form')

        except LookupError as exc:

            if not self.browser.cookies.get('__ac', None):

                self.browser_login()
                form = self.browser.getForm(id='form')
            else:
                raise LookupError(exc.message)

        # Fill the form
        form.getControl(name='form.widgets.first_name').value = _first_name
        form.getControl(name='form.widgets.last_name').value = _last_name
        form.getControl(name='form.widgets.gender:list').value = (_gender, )
        form.getControl(name='form.widgets.roll_number').value = _roll_number
        form.getControl(name='form.widgets.grade:list').value = (_grade, )
        form.getControl(name='form.widgets.contact_number').value = _contact_number

        form.getControl(name='form.widgets.IShortName.id').value = "test-first-name"
        form.getControl(name='form.widgets.IExcludeFromNavigation.exclude_from_nav:list').value = 1
        form.getControl(name='form.widgets.INextPreviousToggle.nextPreviousEnabled:list').value = 1

        image_control = form.getControl(name='form.widgets.profile_photo')
        image_control.add_file(open(os.path.join(_resource_path, _profile_photo), 'rb'), 'image/jpeg', _profile_photo)

        form.submit(form.getControl(name='form.buttons.save').value)

        self.assertEqual(self.school.absolute_url() + '/' + _id + '/view', self.browser.url,
                         'Current URL should be default view for newly created student')
        student = self.portal.portal_catalog.searchResults(portal_type=CONTENT_TYPE_STUDENT, id=_id)
        student = student[0]

        self.assertEqual(student.getObject().first_name, _first_name)
        self.assertEqual(student.getObject().gender, _gender)
        self.assertEqual(student.grade, _grade)
        self.assertEqual(student.roll_number, int(_roll_number))
        self.assertEqual(_first_name + ' ' + _last_name, student.Title)
示例#26
0
 def subjects(self):
     base_url = self.app().absolute_url()
     _tags = [
         safe_unicode(t) for t in ICategorization(self.context).subjects
     ]
     return [
         dict(title=_tag,
              absolute_url="%s/tag/%s" %
              (base_url, urllib.quote(_tag.encode('utf8'))))
         for _tag in _tags
     ]
    def test_adding(self):
        """
        :return:
        """
        _id = safe_unicode("test-first-review")
        _title = safe_unicode("Test First Review")

        self.book.invokeFactory(CONTENT_TYPE_BOOK_REVIEW, _id)
        review = self.book[_id]

        self.assertTrue(IBookReview.providedBy(review))

        review.setTitle(_title)
        review.reviewer = self.student.UID()

        review.reindexObject()

        result = self.portal.portal_catalog.searchResults(id=review.id)

        self.assertEquals(1, len(result))
        self.assertEqual(_title, result[0].Title)
示例#28
0
 def escapeVal(self, val):
     if not isinstance(val, six.text_type):
         try:
             val = six.text_type(val)
         except UnicodeDecodeError:
             val = safe_unicode(val)
     if six.PY2:
         val = val.encode("utf-8")
     escaped_val = escape(val.translate(translation_map))
     if isinstance(escaped_val, six.binary_type):
         escaped_val = escaped_val.decode("utf-8")
     return escaped_val
def init_fixture(self, commit=False):

    """
    :param self:
    :param commit:
    :return:
    """
    self.portal.invokeFactory(CONTENT_TYPE_SCHOOL, 'school')
    self.school = self.portal['school']
    self.school.setTitle('My Test School')

    self.school.invokeFactory(CONTENT_TYPE_STUDENT, 'student')
    self.student = self.school['student']

    self.student.first_name = safe_unicode('Test First Name')
    self.student.last_name = safe_unicode('Last')
    self.student.gender = safe_unicode('male')
    self.student.roll_number = safe_unicode('1001')
    self.student.grade = safe_unicode('g4')
    self.student.contact_number = safe_unicode('980000000')

    self.school.invokeFactory(CONTENT_TYPE_LIBRARY, 'library')
    self.library = self.school['library']
    self.library.setTitle('My Test Library')

    self.school.reindexObject()

    if commit:
        transaction.commit()
    def _book_structure(self):
        """
        :return:
        """
        _resource_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'resources')
        _id = safe_unicode('book')
        _title = safe_unicode('Test First Book')
        _description = safe_unicode('The test description')
        _details = safe_unicode('<h1>Test Book Details</h1>')
        _isbn = safe_unicode('ISBN 978-0-306-40615-7')
        _author = safe_unicode('Test Author')
        _publisher = safe_unicode('Test Publisher')
        _number_of_copy = safe_unicode('2')
        _cover_photo = 'book.jpg'

        _url = self.library.absolute_url() + '/++add++' + CONTENT_TYPE_BOOK
        self.browser.open(_url)

        try:
            form = self.browser.getForm(id='form')

        except LookupError as exc:

            if not self.browser.cookies.get('__ac', None):

                self.browser_login()
                form = self.browser.getForm(id='form')
            else:
                raise LookupError(exc.message)

        # Fill the form
        form.getControl(name='form.widgets.title').value = _title
        form.getControl(name='form.widgets.description').value = _description
        form.getControl(name='form.widgets.isbn').value = _isbn
        form.getControl(name='form.widgets.details').value = _details
        form.getControl(name='form.widgets.publisher').value = _publisher
        form.getControl(name='form.widgets.author').value = _author
        form.getControl(name='form.widgets.number_of_copy').value = _number_of_copy

        form.getControl(name='form.widgets.IShortName.id').value = _id
        form.getControl(name='form.widgets.IExcludeFromNavigation.exclude_from_nav:list').value = 1
        form.getControl(name='form.widgets.INextPreviousToggle.nextPreviousEnabled:list').value = 1

        image_control = form.getControl(name='form.widgets.cover_photo')
        image_control.add_file(open(os.path.join(_resource_path, _cover_photo), 'rb'), 'image/jpeg', _cover_photo)

        form.submit(form.getControl(name='form.buttons.save').value)

        book = self.portal.portal_catalog.searchResults(portal_type=CONTENT_TYPE_BOOK, id=_id)[0]
        self.book = book.getObject()
def init_fixture(self, commit=False):

    """
    :param self:
    :param commit:
    :return:
    """
    self.portal.invokeFactory(CONTENT_TYPE_SCHOOL, "school")
    self.school = self.portal["school"]
    self.school.setTitle("My Test School")

    self.school.invokeFactory(CONTENT_TYPE_STUDENT, "student")
    self.student = self.school["student"]

    self.student.first_name = safe_unicode("Test First Name")
    self.student.last_name = safe_unicode("Last")
    self.student.gender = safe_unicode("male")
    self.student.roll_number = safe_unicode("1001")
    self.student.grade = safe_unicode("g4")
    self.student.contact_number = safe_unicode("980000000")

    self.school.invokeFactory(CONTENT_TYPE_LIBRARY, "library")
    self.library = self.school["library"]
    self.library.setTitle("My Test Library")

    self.library.invokeFactory(CONTENT_TYPE_BOOK, "book")
    self.book = self.library["book"]
    self.book.setTitle("My Test Book")

    self.book.details = safe_unicode("<h1>Test Book Details</h1>")
    self.book.isbn = safe_unicode("98-999-99-9999")
    self.book.author = safe_unicode("Test Author")
    self.book.publisher = safe_unicode("Test Publisher")
    self.book.number_of_copy = 10

    self.school.reindexObject()

    if commit:
        transaction.commit()
    def test_adding(self):
        """
        :return:
        """
        _id = safe_unicode('test-first-name')
        _first_name = safe_unicode('Test First Name')
        _last_name = safe_unicode('Last')

        self.school.invokeFactory(CONTENT_TYPE_STUDENT, _id)
        student = self.school[_id]

        self.assertTrue(IStudent.providedBy(student))

        student.first_name = _first_name
        student.last_name = _last_name

        student.reindexObject()

        result = self.portal.portal_catalog.searchResults(id=student.id)

        self.assertEquals(1, len(result))
        self.assertEqual(_first_name + ' ' + _last_name, result[0].Title)
        self.assertEquals(result[0].getObject().first_name, _first_name)
    def test_adding(self):
        """
        :return:
        """
        _id = safe_unicode('test-first-book')
        _title = safe_unicode('Test First Book')
        _isbn = safe_unicode('ISBN-01-90')

        self.library.invokeFactory(CONTENT_TYPE_BOOK, _id)
        book = self.library[_id]

        self.assertTrue(IBook.providedBy(book))

        book.setTitle(_title)
        book.isbn = _isbn

        book.reindexObject()

        result = self.portal.portal_catalog.searchResults(id=book.id)

        self.assertEquals(1, len(result))
        self.assertEqual(_title, result[0].Title)
        self.assertEquals(result[0].getObject().isbn, _isbn)
示例#34
0
 def _set_subjects(self, value):
     value = tuple([safe_unicode(x) for x in value])
     self.context.subject = value
     graph = getUtility(INetworkTool)
     user = api.user.get_current()
     try:
         uuid = IUUID(self.context)
     except TypeError:
         # new factory document, not registered yet
         # we'll come back to this with an event listener
         return
     if value:
         graph.tag("content", uuid, user.id, *value)
     # else value==() -> cleaned up below
     try:
         current_tags = graph.get_tags("content", uuid, user.id)
     except KeyError:
         # no tags set yet
         return
     else:
         stale = [tag for tag in current_tags if tag not in value]
         if stale:
             graph.untag("content", uuid, user.id, *stale)
示例#35
0
 def _set_subjects(self, value):
     value = tuple([safe_unicode(x) for x in value])
     self.context.subject = value
     graph = getUtility(INetworkTool)
     user = api.user.get_current()
     try:
         uuid = IUUID(self.context)
     except TypeError:
         # new factory document, not registered yet
         # we'll come back to this with an event listener
         return
     if value:
         graph.tag('content', uuid, user.id, *value)
     # else value==() -> cleaned up below
     try:
         current_tags = graph.get_tags('content', uuid, user.id)
     except KeyError:
         # no tags set yet
         return
     else:
         stale = [tag for tag in current_tags if tag not in value]
         if stale:
             graph.untag('content', uuid, user.id, *stale)
示例#36
0
def addLogEntry(old_changelog, obj):
    print obj.SectorizingNetworks
    mdate, userInfo = obj.modInfo()
    text = """
    <tr>
    <td>%s<br/>(%s)</td>
    <td>%s</td>
    <td>%s</td>
    <td>%s</td>
    <td>%s</td>
    <td>%s</td>
    </tr>
    <tr class="last"></tr>
    """ % (
        obj.toLocalizedTime(mdate, long_format=1),
        userInfo,
        obj.Status,
        obj.OperationMode,
        obj.phaseInfo(),
        ", ".join (obj.SectorizingSampleTypes if obj.SectorizingSampleTypes != None else ' '),
        ", ".join((n.to_object.Title() for n in obj.SectorizingNetworks) if obj.SectorizingNetworks != None else ' ')
    )
    new_changelog = old_changelog.replace("""<tr class="last"></tr>""", safe_unicode(text))
    obj.changelog = RichTextValue(new_changelog, 'text/html', 'text/html')
示例#37
0
 def _get__name__(self):
     if six.PY2:
         return safe_unicode(self.id)
     return self.id
示例#38
0
def creatorsDefault(data):
    user = getSecurityManager().getUser()
    # NB: CMF users are UTF-8 encoded bytes, decode them before inserting
    return user and (safe_unicode(user.getId()), )
示例#39
0
def user_mail():
    if not api.user.is_anonymous():
        email = api.user.get_current().getProperty('email')
        return safe_unicode(email) or u''
    return u''
示例#40
0
    def send_notification(
        self,
        to_name=None,
        to_address=None,
        tool_paths=None,
        intro="",
        empty_message=None,
    ):
        if not tool_paths and not empty_message:
            return
        to_name = safe_unicode(to_name)
        mailhost = getToolByName(self.context, "MailHost")
        if to_name:
            recipient = "{} <{}>".format(to_name, to_address)
        else:
            recipient = to_address
        subject = "OiRA: Notification on outdated tools"
        portal_id = self.context.getId()
        portal_url = self.context.absolute_url()
        if tool_paths:
            paths_by_country = OrderedDict()
            for path in tool_paths:
                country = path.split("/")[3]
                if country in paths_by_country:
                    paths_by_country[country].append(path)
                else:
                    paths_by_country[country] = [path]
            tool_details = ""
            for country in paths_by_country.keys():
                if len(paths_by_country.keys()) > 1:
                    tool_details += "\n" + country + ":\n"
                else:
                    tool_details += "\n"
                tool_urls = [
                    i.replace("/" + portal_id, portal_url)
                    for i in paths_by_country[country]
                ]
                tool_details += "\n".join(tool_urls)
                tool_details += "\n"
        else:
            tool_details = empty_message
        years = self.interval / 365
        if years:
            months = int((self.interval % 365) / 30.4)
            period = "over {0} year(s) and {1} month(s)".format(years, months)
        else:
            period = "over {0} month(s)".format(int(self.interval / 30.4))

        body = """
Dear {name},

{intro}

The following tool(s) have not been updated in {period}:
{tools}

Please check if they are still up to date and republish them.

Best regards,
OiRA
""".format(
            name=to_name or to_address, tools=tool_details, period=period, intro=intro
        )
        mail = CreateEmailTo(
            self.email_from_name, self.email_from_address, recipient, subject, body
        )
        try:
            mailhost.send(mail)
        except Exception as err:
            log.error("Failed to send notification {}".format(err))
示例#41
0
def creatorsDefault(data):
    user = getSecurityManager().getUser()
    # NB: CMF users are UTF-8 encoded bytes, decode them before inserting
    return user and (safe_unicode(user.getId()),)
示例#42
0
 def setCreators(self, creators):
     # Set Dublin Core Creator elements - resource authors.
     if isinstance(creators, six.string_types):
         creators = [creators]
     self.creators = tuple(safe_unicode(c.strip()) for c in creators)
示例#43
0
 def setSubject(self, subject):
     # Set Dublin Core Subject element - resource keywords.
     if isinstance(subject, basestring):
         subject = [subject]
     self.subject = tuple(safe_unicode(s.strip()) for s in subject)
示例#44
0
 def setCreators(self, creators):
     # Set Dublin Core Creator elements - resource authors.
     if isinstance(creators, basestring):
         creators = [creators]
     self.creators = tuple(safe_unicode(c.strip()) for c in creators)
示例#45
0
 def setDescription(self, description):
     # Set Dublin Core Description element - resource summary.
     self.description = safe_unicode(description)
示例#46
0
 def setTitle(self, title):
     # Set Dublin Core Title element - resource name.
     self.title = safe_unicode(title)
示例#47
0
 def publishTraverse(self, request, name):
     '''Extract self.request_tag from URL /tag/foobar'''
     self.request_tag = safe_unicode(urllib.unquote(name))
     return self
示例#48
0
 def setContributors(self, contributors):
     # Set Dublin Core Contributor elements - resource collaborators.
     if isinstance(contributors, six.string_types):
         contributors = contributors.split(';')
     self.contributors = tuple(
         safe_unicode(c.strip()) for c in contributors)
示例#49
0
 def setTitle(self, title):
     # Set Dublin Core Title element - resource name.
     self.title = safe_unicode(title)
示例#50
0
 def setContributors(self, contributors):
     # Set Dublin Core Contributor elements - resource collaborators.
     if isinstance(contributors, basestring):
         contributors = contributors.split(';')
     self.contributors = tuple(
         safe_unicode(c.strip()) for c in contributors)
示例#51
0
 def setDescription(self, description):
     # Set Dublin Core Description element - resource summary.
     self.description = safe_unicode(description)
示例#52
0
 def setRights(self, rights):
     # Set Dublin Core Rights element - resource copyright.
     self.rights = safe_unicode(rights)
示例#53
0
 def setSubject(self, subject):
     # Set Dublin Core Subject element - resource keywords.
     if isinstance(subject, six.string_types):
         subject = [subject]
     self.subject = tuple(safe_unicode(s.strip()) for s in subject)
示例#54
0
 def _get__name__(self):
     if six.PY2:
         return safe_unicode(self.id)
     return self.id
示例#55
0
 def setRights(self, rights):
     # Set Dublin Core Rights element - resource copyright.
     self.rights = safe_unicode(rights)
示例#56
0
 def url(self):
     return "{}/@@tagstream/{}".format(
         self.context.absolute_url(),
         urllib.quote(safe_unicode(self.tag).encode('utf8')))