Beispiel #1
0
 def choices(self):
     """Get  a list of the possible choices for report activities."""
     result = {
         'name': _('Choose a report activity'),
         'value': '',
         }
     results = [result]
     root = IGradebookRoot(ISchoolToolApplication(None))
     term = self.context
     schoolyear = ISchoolYear(term)
     deployedKey = '%s_%s' % (schoolyear.__name__, term.__name__)
     for key in root.deployed:
         if key.startswith(deployedKey):
             deployedWorksheet = root.deployed[key]
             for activity in deployedWorksheet.values():
                 if ICommentScoreSystem.providedBy(activity.scoresystem):
                     continue
                 name = '%s - %s - %s' % (term.title,
                     deployedWorksheet.title, activity.title)
                 value = '%s|%s|%s' % (term.__name__,
                     deployedWorksheet.__name__, activity.__name__)
                 result = {
                     'name': name,
                     'value': value,
                     }
                 results.append(result)
     return results
Beispiel #2
0
 def createTerms(self, term):
     result = []
     result.append(self.createTerm(
             None,
             z3c.form.widget.SequenceWidget.noValueToken,
             _("Select a source"),
             ))
     root = IGradebookRoot(ISchoolToolApplication(None))
     schoolyear = ISchoolYear(term)
     deployedKey = '%s_%s' % (schoolyear.__name__, term.__name__)
     for key in root.deployed:
         if key.startswith(deployedKey):
             deployedWorksheet = root.deployed[key]
             for activity in deployedWorksheet.values():
                 if ICommentScoreSystem.providedBy(activity.scoresystem):
                     continue
                 title = '%s - %s - %s' % (term.title,
                     deployedWorksheet.title, activity.title)
                 token = '%s-%s-%s' % (term.__name__,
                     deployedWorksheet.__name__, activity.__name__)
                 token=unicode(token).encode('punycode')
                 result.append(self.createTerm(
                     (deployedWorksheet, activity,),
                     token,
                     title,
                     ))
     return result
Beispiel #3
0
    def script(self):
        zc.resourcelibrary.need("ckeditor")
        config = self.config

        app_url = absoluteURL(ISchoolToolApplication(None), self.request)
        config_path = '%s%s' % (app_url, config.path)

        # XXX: using some values that may be not JS safe
        return '''
            <script type="text/javascript" language="JavaScript">
                var %(variable)s = new CKEDITOR.replace("%(id)s",
                    {
                        height: %(height)s,
                        width: %(width)s,
                        customConfig: "%(customConfigPath)s"
                    }
                );
            </script>
            ''' % {
            'id': self.element_id,
            'variable': self.editor_var_name,
            'width': config.width,
            'height': config.height,
            'toolbar': config.toolbar,
            'customConfigPath': config_path,
            }
Beispiel #4
0
    def __call__(self):
        app = ISchoolToolApplication(None)
        person = IPerson(self.request.principal, None)
        if not person:
            raise Unauthorized("Only logged in users can book resources.")
        cal = ISchoolToolCalendar(person)
        if self.request.has_key('event_id'):
            event = cal.find(self.request['event_id'])
        else:
            start_date = self.request.get('start_date')
            start_time = self.request.get('start_time')
            title = self.request.get('title')
            start_datetime = "%s %s" % (start_date, start_time)
            start_datetime = datetime(*strptime(start_datetime,
                                                "%Y-%m-%d %H:%M")[0:6])
            start_datetime = self.timezone.localize(start_datetime)
            start_datetime = start_datetime.astimezone(pytz.UTC)
            duration = timedelta(seconds=int(self.request.get('duration')))
            event = CalendarEvent(dtstart = start_datetime,
                                  duration = duration,
                                  title = title)
            cal.addEvent(event)

        if event:
            resource = app["resources"].get(self.request['resource_id'])
            if resource is not None:
                resource_calendar = ISchoolToolCalendar(resource)
                if not canAccess(resource_calendar, "addEvent"):
                    raise Unauthorized("You don't have the right to"
                                       " book this resource!")
                event.bookResource(resource)
        self.request.response.redirect(self.nextURL(event))
Beispiel #5
0
 def add(self, contact):
     """Add `contact` to the container and assign it to the person."""
     contact_container = IContactContainer(ISchoolToolApplication(None))
     name = INameChooser(contact_container).chooseName('', contact)
     contact_container[name] = contact
     self.added = contact
     return contact
Beispiel #6
0
def getResourceDemographics(resource):
    app = ISchoolToolApplication(None)
    rdc = app[RESOURCE_DEMO_DATA_KEY]
    demographics = rdc.get(resource.__name__, None)
    if demographics is None:
        rdc[resource.__name__] = demographics = ResourceDemographicsData()
    return demographics
Beispiel #7
0
def evolve(context):
    root = getRootFolder(context)
    old_site = getSite()

    assert ISchoolToolApplication.providedBy(root)
    setSite(root)

    requireURICache(root)

    connection = context.connection

    link_oids, linkset_oids = collectOIDs(connection)

    evolveLinks(connection, link_oids)
    transaction.savepoint(optimistic=True)

    evolveLinkSets(connection, linkset_oids)
    transaction.savepoint(optimistic=True)

    addLinkCatalog(root)
    transaction.savepoint(optimistic=True)

    evolveGroupRelationships(root)
    evolveCourseRelationships(root)
    evolveResourceRelationships(root)
    evolveAdvisorRelationships(root)
    evolveSectionsRelationships(root)

    transaction.savepoint(optimistic=True)

    evolveContactRelationships(root)

    setSite(old_site)
Beispiel #8
0
    def createAndAdd(self, data, dry_run=True):
        """Create objects and add them to the container."""

        if len(data) < 1:
            self.errors.fields.append(_('Insufficient data provided.'))
            return

        if not data[0]:
            self.errors.fields.append(_('User names must not be empty.'))
            return

        app = ISchoolToolApplication(None)
        person_container = app['persons']
        username = data[0]

        if username not in person_container:
            self.errors.fields.append(
                _('"${username}" is not a valid username.',
                  mapping={'username': username}))
            return

        user = person_container[username]
        if not dry_run:
            removeSecurityProxy(self.container.members).add(
                removeSecurityProxy(user))
Beispiel #9
0
 def getTermByToken(self, token):
     gc = IGroupContainer(ISchoolToolApplication(None))
     if gc is None:
         raise LookupError(token)
     if token not in gc:
         raise LookupError(token)
     return GroupTerm(gc[token])
def getSourceObj(source):
    if source is None:
        return None

    items = source.split('_')
    scid = items[0]
    ws_hash = items[-2]
    act_hash = items[-1]
    sid = '_'.join(items[1:-2])

    app = ISchoolToolApplication(None)
    sectionContainer = app['schooltool.course.section'].get(scid, None)
    if sectionContainer is None:
        return None

    section = sectionContainer.get(sid, None)
    if section is None:
        return None

    for worksheet in interfaces.IActivities(section).values():
        if ws_hash == unicode(hash(IKeyReference(worksheet))):
            break
    else:
        return None

    if act_hash == 'ave':
        return worksheet
    for key, activity in worksheet.items():
        if act_hash == unicode(hash(IKeyReference(activity))):
            return activity
    return None
Beispiel #11
0
 def app_states(self):
     app = ISchoolToolApplication(None)
     container = IRelationshipStateContainer(app)
     states = container.get(self.view.app_states_name, None)
     if states is None:
         return {}
     return states
Beispiel #12
0
    def format_persons(self):
        fields = [('User Name', Text, attrgetter('__name__')),
                  ('Prefix', Text, attrgetter('prefix')),
                  ('First Name', Text, attrgetter('first_name')),
                  ('Middle Name', Text, attrgetter('middle_name')),
                  ('Last Name', Text, attrgetter('last_name')),
                  ('Suffix', Text, attrgetter('suffix')),
                  ('Preferred Name', Text, attrgetter('preferred_name')),
                  ('Birth Date', Date, attrgetter('birth_date')),
                  ('Gender', Text, attrgetter('gender')),
                  ('Password', Text, lambda p: None)]

        def demographics_getter(attribute):
            def getter(person):
                demographics = IDemographics(person)
                return demographics[attribute]

            return getter

        app = ISchoolToolApplication(None)
        demographics_fields = IDemographicsFields(app)
        for field in demographics_fields.values():
            title = field.title
            format = Text
            if isinstance(field, DateFieldDescription):
                format = Date
            getter = demographics_getter(field.name)
            fields.append((title, format, getter))

        items = self.context['persons'].values()
        return self.format_table(fields, items, importer='export_persons')
def setUpCourses(names):
    app = ISchoolToolApplication(None)
    CourseInit(app)()
    SectionInit(app)()
    courses = ICourseContainer(app)
    for name in names:
        courses[name.lower()] = Course(title=name)
Beispiel #14
0
 def done_link(self):
     schoolyear = ISchoolYear(self.context.__parent__)
     url = '%s/%s?schoolyear_id=%s' % (
         absoluteURL(ISchoolToolApplication(None), self.request),
         'courses',
         schoolyear.__name__)
     return url
Beispiel #15
0
def evolve(context):
    root = getRootFolder(context)
    old_site = getSite()

    assert ISchoolToolApplication.providedBy(root)
    setSite(root)

    requireURICache(root)

    connection = context.connection

    link_oids, linkset_oids = collectOIDs(connection)

    evolveLinks(connection, link_oids)
    transaction.savepoint(optimistic=True)

    evolveLinkSets(connection, linkset_oids)
    transaction.savepoint(optimistic=True)

    addLinkCatalog(root)
    transaction.savepoint(optimistic=True)

    evolveGroupRelationships(root)
    evolveCourseRelationships(root)
    evolveResourceRelationships(root)
    evolveAdvisorRelationships(root)
    evolveSectionsRelationships(root)

    transaction.savepoint(optimistic=True)

    evolveContactRelationships(root)

    setSite(old_site)
def setUpTimetables():
    app = ISchoolToolApplication(None)
    TimetableStartUp(app)()
    syc = ISchoolYearContainer(app)
    sy = syc.getActiveSchoolYear()
    timetables = ITimetableContainer(sy)
    timetables[u'rotating'] = tt_rot = Timetable(sy.first,
                                                 sy.last,
                                                 title=u"Rotating")

    tt_rot.periods = CalendarDayTemplates()
    initTemplates(tt_rot.periods)
    tt_rot.time_slots = CalendarDayTemplates()
    initTemplates(tt_rot.time_slots)
    addTimetableDays(tt_rot, [('1', 'Day 1'), ('2', 'Day 2'), ('3', 'Day 3')],
                     ['A', 'B', 'C'])

    timetables[u'weekly'] = tt_week = Timetable(sy.first,
                                                sy.last,
                                                title=u"Weekly")

    tt_week.periods = WeekDayTemplates()
    initTemplates(tt_week.periods)
    tt_week.time_slots = WeekDayTemplates()
    initTemplates(tt_week.time_slots)

    dows = [
        'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday',
        'Sunday'
    ]
    week_days = [(unicode(n), title) for n, title in enumerate(dows)]

    addTimetableDays(tt_week, week_days, ['A', 'B', 'C'])
Beispiel #17
0
    def setUp(self):
        layeredTestSetup()
        app = ISchoolToolApplication(None)
        self.person = app['persons']['person'] = Person('person')

        # set up schoolyear
        from schooltool.schoolyear.schoolyear import SchoolYear
        from schooltool.schoolyear.interfaces import ISchoolYearContainer
        ISchoolYearContainer(app)['2004'] = SchoolYear("2004",
                                                       date(2004, 9, 1),
                                                       date(2004, 12, 31))

        # set up the timetable schema
        days = ['A', 'B', 'C']
        schema = self.createSchema(days, ['1', '2', '3', '4'],
                                   ['1', '2', '3', '4'], ['1', '2', '3', '4'])
        schema.timezone = 'Europe/London'
        template = SchooldayTemplate()
        template.add(SchooldaySlot(time(8, 0), timedelta(hours=1)))
        template.add(SchooldaySlot(time(10, 15), timedelta(hours=1)))
        template.add(SchooldaySlot(time(11, 30), timedelta(hours=1)))
        template.add(SchooldaySlot(time(12, 30), timedelta(hours=2)))
        schema.model = SequentialDaysTimetableModel(days, {None: template})

        ITimetableSchemaContainer(app)['default'] = schema

        # set up terms
        from schooltool.term.term import Term
        terms = ITermContainer(app)
        terms['term'] = term = Term("Some term", date(2004, 9, 1),
                                    date(2004, 12, 31))
        term.add(date(2004, 11, 5))
Beispiel #18
0
def getPersonDemographics(person):
    app = ISchoolToolApplication(None)
    pdc = app['schooltool.basicperson.demographics_data']
    demographics = pdc.get(person.username, None)
    if demographics is None:
        pdc[person.username] = demographics = PersonDemographicsData()
    return demographics
Beispiel #19
0
 def types(self):
     app = ISchoolToolApplication(None)
     types = set()
     for resource in app['resources'].values():
         if self.interface.providedBy(resource):
             types.add(resource.type)
     return list(types)
Beispiel #20
0
 def __iter__(self):
     gc = IGroupContainer(ISchoolToolApplication(None), None)
     if gc is None:
         return
     persons = gc['teachers'].members
     for person in sorted(persons, key=lambda p: p.__name__):
         yield PersonTerm(person)
Beispiel #21
0
 def contains(self, principal):
     from schooltool.app.browser import same  # XXX
     from schooltool.app.interfaces import ISchoolToolApplication
     from schooltool.person.interfaces import IPerson
     app = ISchoolToolApplication(None)
     persons = app['persons']
     person = IPerson(principal, None)
     return person is not None and same(person, persons.super_user)
Beispiel #22
0
def getCourseContainer(sy):
    int_ids = getUtility(IIntIds)
    sy_id = str(int_ids.getId(sy))
    app = ISchoolToolApplication(None)
    cc = app[COURSE_CONTAINER_KEY].get(sy_id, None)
    if cc is None:
        cc = app[COURSE_CONTAINER_KEY][sy_id] = CourseContainer()
    return cc
Beispiel #23
0
def getScheduleContainer(obj):
    int_ids = getUtility(IIntIds)
    obj_id = str(int_ids.getId(obj))
    app = ISchoolToolApplication(None)
    container = app[SCHEDULES_KEY].get(obj_id, None)
    if container is None:
        container = app[SCHEDULES_KEY][obj_id] = ScheduleContainer()
    return container
Beispiel #24
0
 def handle_cancel_action(self, action):
     if 'camefrom' in self.request:
         url = self.request['camefrom']
         self.request.response.redirect(url)
         return
     app = ISchoolToolApplication(None)
     url = self.url_with_schoolyear_id(app, view_name='groups')
     self.request.response.redirect(url)
Beispiel #25
0
def ensureEvolved(context):
    root = getRootFolder(context)
    assert ISchoolToolApplication.providedBy(root)
    catalogs = root["schooltool.app.catalog:Catalogs"]
    if LinkCatalog.key() in catalogs:
        return
    evolve(context)
    transaction.commit()
Beispiel #26
0
def getSectionContainer(term):
    int_ids = getUtility(IIntIds)
    term_id = str(int_ids.getId(term))
    app = ISchoolToolApplication(None)
    sc = app[SECTION_CONTAINERS_KEY].get(term_id, None)
    if sc is None:
        sc = app[SECTION_CONTAINERS_KEY][term_id] = SectionContainer()
    return sc
Beispiel #27
0
 def nextURL(self):
     if 'CONFIRM' in self.request:
         schoolyear = ISchoolYear(self.context)
         url = '%s/%s?schoolyear_id=%s' % (absoluteURL(
             ISchoolToolApplication(None),
             self.request), 'groups', schoolyear.__name__)
         return url
     return flourish.containers.ContainerDeleteView.nextURL(self)
Beispiel #28
0
def getTimetableContainer(obj):
    int_ids = getUtility(IIntIds)
    obj_id = str(int_ids.getId(obj))
    app = ISchoolToolApplication(None)
    container = app[TIMETABLES_KEY].get(obj_id, None)
    if container is None:
        container = app[TIMETABLES_KEY][obj_id] = TimetableContainer()
    return container
Beispiel #29
0
 def getActivities(self):
     activities = []
     root = IGradebookRoot(ISchoolToolApplication(None))
     prefix = '%s_%s_' % (self.schoolyear.__name__, self.term.__name__)
     for key, sheet in root.deployed.items():
         if key.startswith(prefix) and key[len(prefix):].isdigit():
             activities.extend(sheet.values())
     return activities
Beispiel #30
0
 def __call__(self):
     app = ISchoolToolApplication(None)
     syc = ISchoolYearContainer(app)
     activeSchoolyear = syc.getActiveSchoolYear()
     if activeSchoolyear is not None:
         self.importDefaultGroups(activeSchoolyear)
     else:
         self.initializeGroupContainer()
Beispiel #31
0
def ensureEvolved(context):
    root = getRootFolder(context)
    assert ISchoolToolApplication.providedBy(root)
    catalogs = root['schooltool.app.catalog:Catalogs']
    if LinkCatalog.key() in catalogs:
        return
    evolve(context)
    transaction.commit()
Beispiel #32
0
 def getApplicationCalendar(self):
     if self.user is None:
         return None
     app = ISchoolToolApplication(None)
     calendar = ISchoolToolCalendar(app)
     if not canAccess(calendar, '__iter__'):
         return None
     return calendar
Beispiel #33
0
def schoolToolTraverseSubscriber(event):
    """A subscriber to BeforeTraverseEvent.

    Adds DevMode layer to the request.
    """
    if (ISchoolToolApplication.providedBy(event.object) and
        IBrowserRequest.providedBy(event.request)):
        directlyProvides(event.request,
                         directlyProvidedBy(event.request) + IDevModeLayer)
Beispiel #34
0
def getSchoolToolApplication(ignore=None):
    """Return the nearest ISchoolToolApplication.

    This function is also registered as an adapter, so you
    can use it like this:

        app = ISchoolToolApplication(None)

    and stub it in unit tests.
    """
    candidate = getSite()
    if ISchoolToolApplication.providedBy(candidate):
        return candidate
    return None
Beispiel #35
0
 def openDB(self, options):
     if self.db is not None:
         return self.db
     db_configuration = options.config.database
     db = db_configuration.open()
     connection = db.open()
     root = connection.root()
     app = root.get(ZopePublication.root_name)
     if app is None or not ISchoolToolApplication.providedBy(app):
         connection.close()
         return None
     connection.close()
     provideUtility(db, IDatabase)
     db.setActivityMonitor(ActivityMonitor())
     self.db = db
     return self.db