Exemple #1
0
def test_setup(test):
    """Create some models needed for the tests."""
    ututi.tests.setUp(test)
    setUpUser()
    uni = LocationTag.get(u'uni')
    dep = LocationTag(u'department', u'dep', u'', uni, member_policy='PUBLIC')
    meta.Session.add(dep)
    meta.Session.commit()

    u = User.get('*****@*****.**', uni)
    meta.set_active_user(u.id)

    g = Group('moderators', u'Moderatoriai', LocationTag.get(u'vu'), date.today(), u'U2ti moderatoriai.')

    role = GroupMembershipType.get('administrator')
    gm = GroupMember()
    gm.user = u
    gm.group = g
    gm.role = role
    meta.Session.add(g)
    meta.Session.add(gm)

    meta.Session.add(Subject(u'subject', u'A Generic subject', uni, u''))
    meta.Session.commit()

    meta.set_active_user(u.id)
def test_setup(test):
    """Create some models needed for the tests."""
    ututi.tests.setUp(test)
    setUpUser()

    u = User.get('*****@*****.**', LocationTag.get(u'uni'))
    meta.set_active_user(u.id)
    meta.Session.add(Subject(u'subject', u'Subject',
                             LocationTag.get(u'uni'),
                             u''))
    meta.Session.commit()
    meta.set_active_user(u.id)
def test_setup(test):
    """Create some models needed for the tests."""
    ututi.tests.setUp(test)
    setUpUser()
    u = User.get('*****@*****.**', LocationTag.get(u'uni'))
    meta.set_active_user(u.id)

    g = Group('moderators', u'Moderatoriai', LocationTag.get(u'vu'), date.today(), u'U2ti moderatoriai.')
    meta.Session.add(g)
    meta.Session.commit()

    meta.set_active_user(u.id)
Exemple #4
0
def setUpModeratorGroup():

    u = User.get('*****@*****.**', LocationTag.get(u'uni'))
    meta.set_active_user(u.id)

    g = Group('moderators', u'Moderatoriai', LocationTag.get(u'uni'), date.today(), u'U2ti moderatoriai.')
    g.moderators = True
    g.add_member(u, True)
    meta.Session.add(g)
    meta.Session.commit()

    meta.set_active_user(u.id)
Exemple #5
0
def _search_query_location_tags(query, settings):
    """Filter the query by location tags."""

    tags = settings.get('tags')
    if tags is not None:
        parsed_tags = [] #storing processed tags here
        for tag_name in tags:
            #let's check each tag and see what we've got: a location tag or a simpletag
            ltag = LocationTag.get_all(tag_name)
            if ltag != []:
                # if it is a location tag, add not only it, but also its children
                location = []
                for ltag_item in ltag:
                    location.extend([lt.id for lt in ltag_item.flatten])
                parsed_tags.append(location)
            else:
                #a tag name that is not in the database was entered. Return empty list.
                return query.filter("false")

        if len(parsed_tags) > 0:
            intersect = None
            for location in parsed_tags:
                if intersect is None:
                    intersect = set(location)
                else:
                    intersect = intersect & set(location)
                query = query.filter(ContentItem.location_id.in_(list(location)))

    return query
Exemple #6
0
    def _page_action(self, id, tags, page_id):
        try:
            page_id = int(page_id)
        except ValueError:
            abort(404)

        location = LocationTag.get(tags)
        if location is None:
            abort(404)

        subject = Subject.get(location, id)
        if subject is None:
            abort(404)
        page = Page.get(page_id)
        if page is None:
            abort(404)

        c.page = page
        c.subject = subject

        c.similar_subjects = find_similar_subjects(location.id, id)
        c.object_location = subject.location
        c.security_context = subject
        c.tabs = subject_menu_items()
        c.theme = location.get_theme()

        return method(self, subject, page)
    def finish(self, registration):
        from ututi.lib.security import sign_in_user
        if not registration.location:
            # if there is a university with same title we will use it.
            existing = LocationTag.get_by_title(registration.university_title)
            if existing is not None:
                registration.location = existing
            else:
                registration.location = registration.create_university()

        user = registration.create_user()
        bind_group_invitations(user)

        # TODO: integrity checks here

        meta.Session.add(user)
        registration.completed = True
        # flush before sending any emails
        meta.Session.flush()

        process_registration_invitations(registration)
        meta.Session.commit()

        if user.is_teacher:
            teacher_registered_email(user)

        sign_in_user(user)
        redirect(url(controller='profile', action='register_welcome'))
Exemple #8
0
    def _location_action(self, path, obj_type=None):
        location = LocationTag.get(path)
        if location is None:
            abort(404)

        c.security_context = location
        c.object_location = None
        c.location = location

        c.selected_sub_department_id = request.params.get('sub_department_id', None)
        c.selected_sub_department = None
        if c.selected_sub_department_id:
            subdepartment = SubDepartment.get(c.selected_sub_department_id)
            c.selected_sub_department = subdepartment
            c.menu_items = subdepartment_menu_items(subdepartment)

        else:
            c.tabs = location_feed_subtabs(location)
            if c.user:
                c.menu_items = location_menu_items(location)
            else:
                c.menu_items = location_menu_public_items(location)

        c.breadcrumbs = location_breadcrumbs(location)

        c.theme = location.get_theme()
        c.notabs = True


        c.current_menu_item = None
        if obj_type is None:
            return method(self, location)
        else:
            return method(self, location, obj_type)
Exemple #9
0
    def _subdepartmnet_action(self, path, subdept_id, obj_type=None):
        location = LocationTag.get(path)
        if location is None:
            abort(404)

        subdepartment = meta.Session.query(SubDepartment).filter_by(id=subdept_id).one()
        if subdepartment is None:
            abort(404)

        c.security_context = location
        c.object_location = None
        c.location = location
        c.breadcrumbs = subdepartment_breadcrumbs(subdepartment)
        c.subdepartment = subdepartment

        c.theme = location.get_theme()
        c.notabs = True

        c.menu_items = subdepartment_menu_items(subdepartment)

        c.current_menu_item = None
        if obj_type is None:
            return method(self, location, subdepartment)
        else:
            return method(self, location, subdepartment, obj_type)
Exemple #10
0
def test_setup(test):
    """Create some models needed for the tests."""
    ututi.tests.setUp(test)
    setUpUser()

    u = User.get('*****@*****.**', LocationTag.get('uni'))
    meta.set_active_user(u.id)

    g = Group('moderators', u'Moderatoriai', LocationTag.get(u'uni'), date.today(), u'U2ti moderatoriai.')
    role = GroupMembershipType.get('administrator')
    gm = GroupMember()
    gm.user = u
    gm.group = g
    gm.role = role
    meta.Session.add(g)
    meta.Session.add(gm)
    meta.Session.commit()
Exemple #11
0
def test_setup(test):
    setUp(test)
    setUpUser()

    uni = LocationTag.get(u'uni')
    dep = LocationTag(u'D-epartment', u'dep', u'', uni, member_policy='PUBLIC')
    meta.Session.add(dep)
    meta.Session.commit()
Exemple #12
0
def location_teachers(location_id):
    from ututi.model import LocationTag, Teacher, meta
    location = LocationTag.get(int(location_id))
    ids = [t.id for t in location.flatten]
    teachers = meta.Session.query(Teacher)\
            .filter(Teacher.location_id.in_(ids))\
            .order_by(Teacher.fullname).all()
    return [{'name': teacher.fullname,
             'url': teacher.url()} for teacher in teachers]
Exemple #13
0
def test_setup(test):
    """Create some models needed for the tests."""
    ututi.tests.setUp(test)
    setUpUser()
    meta.set_active_user(1)
    g = Group('moderators', u'Moderators', LocationTag.get(u'uni'), date.today(), u'Moderators')
    meta.Session.add(g)
    meta.Session.commit()
    meta.set_active_user(1)
Exemple #14
0
def setup_university_export():
    uni = LocationTag.get('uni')
    uni.description = u'U-niversity description'

    for i in ('1', '2', '3'):
        f = LocationTag(u'Faculty ' + i, u'f' + i, u'U-niversity faculty ' + i, uni, member_policy='PUBLIC')
        meta.Session.add(f)

    meta.Session.commit()
Exemple #15
0
    def create_university(self):
        from ututi.model import LocationTag, EmailDomain

        # parse short title from url
        title_short = urlparse(self.university_site_url).netloc
        if title_short.startswith('www.'):
            title_short = title_short.replace('www.', '', 1)

        university = LocationTag(self.university_title, title_short, confirmed=False)

        # fill out the rest of information
        university.site_url = self.university_site_url
        university.logo = self.university_logo
        university.country = self.university_country
        university.member_policy = self.university_member_policy
        for domain_name in self.university_allowed_domains.split(','):
            university.email_domains.append(EmailDomain(domain_name))

        return university
Exemple #16
0
 def create(self, id, tags):
     if not hasattr(self, 'form_result'):
         redirect(url.current(action='add'))
     location = LocationTag.get(tags)
     subject = Subject.get(location, id)
     page = Page(self.form_result['page_title'],
                 self.form_result['page_content'])
     subject.pages.append(page)
     meta.Session.add(page)
     meta.Session.commit()
     redirect(url.current(action='index', page_id=page.id))
Exemple #17
0
    def create(self):
        values = self.form_result

        structure = LocationTag(title=values['title'],
                                title_short=values['title_short'],
                                description=values['description'],
                                member_policy='PUBLIC')
        structure.region_id = int(values['region']) or None

        if values.get('logo_upload', None) is not None:
            logo = values['logo_upload']
            structure.logo = logo.file.read()

        meta.Session.add(structure)

        # XXX why zero?
        if int(values['parent']) != 0:
            parent = meta.Session.query(LocationTag).filter_by(id=values['parent']).one()
            parent.children.append(structure)
        meta.Session.commit()
        redirect(url(controller='structure', action='index'))
Exemple #18
0
    def _subject_action(self, id, tags):
        location = LocationTag.get(tags)
        subject = Subject.get(location, id)

        if subject is None:
            abort(404)

        c.security_context = subject
        c.object_location = subject.location
        c.subject = subject
        c.similar_subjects = find_similar_subjects(location.id, id)
        c.tabs = subject_menu_items()
        c.breadcrumbs = [{'link': subject.url(), 'title': subject.title}]
        c.theme = subject.location.get_theme()
        return method(self, subject)
Exemple #19
0
    def add_description(self):
        if 'subject_title' not in session or \
           'subject_location_id' not in session:
            redirect(url(controller='subject', action='add'))

        defaults = dict(title=session['subject_title'])
        if c.user.is_teacher and c.user.teacher_verified:
            defaults['lecturer'] = c.user.fullname
        location = LocationTag.get(session['subject_location_id'])
        tags = dict([('location-%d' % n, tag)
                    for n, tag in enumerate(location.hierarchy())])
        defaults.update(tags)

        return htmlfill.render(self._add_full_form(),
                               defaults=defaults)
Exemple #20
0
    def validate_python(self, form_dict, state):
        old_path = form_dict.get('old_path', None)
        parent = form_dict.get('parent', None)
        title_short = form_dict['title_short']
        path = []
        old_location = None

        if old_path:
            old_location = LocationTag.get(old_path)
            # XXX test for id matching a tag
            path = old_location.path
            if len(path) > 0:         # If it's department
                del(path[-1])         # then delete last element
        if parent:
            parent_location = LocationTag.get_by_id(parent)
            path = parent_location.path

        path.append(title_short)
        location = LocationTag.get(path)

        if location is not None and not location is old_location:
            raise Invalid(self.message('duplicate', state),
                          form_dict, state,
                          error_dict={'title_short' : Invalid(self.message('duplicate', state), form_dict, state)})
def test_setup(test):
    """Create some models needed for the tests."""
    ututi.tests.setUp(test)
    setUpUser()

    uni = LocationTag.get(u'uni')
    u = User.get('*****@*****.**', uni)
    meta.set_active_user(u.id)
    dept1 = LocationTag(title=u'dept1',
                        title_short=u'dept1',
                        parent=uni,
                        member_policy='PUBLIC')
    dept2 = LocationTag(title=u'dept2',
                        title_short=u'dept2',
                        parent=uni,
                        member_policy='PUBLIC')
    other_uni = LocationTag(title=u'other_uni',
                            title_short=u'other_uni',
                            parent=None,
                            member_policy='PUBLIC')
    meta.Session.add_all([dept1, dept2, other_uni])
    meta.Session.commit()

    meta.set_active_user(u.id)

    subj1 = Subject(u'subject1', u'Subject1', dept1, u'')
    subj2 = Subject(u'subject2', u'Subject2', dept2, u'')
    meta.Session.add_all([subj1, subj2])

    u = User.get('*****@*****.**', uni)
    u.location = LocationTag.get(u'uni/dept2')
    meta.Session.add(u)
    meta.Session.commit()

    meta.Session.commit()
    meta.set_active_user(u.id)
Exemple #22
0
    def _profile_action(self, path, id):
        location = LocationTag.get(path)
        user = find_user(id)

        if user is None or not user.is_teacher or user.location != location:
            abort(404)

        if not user.profile_is_public and not c.user:
            deny(_('This user profile is not public'), 401)

        c.teacher = user
        c.location = user.location
        c.tabs = external_teacher_tabs(user)
        c.theme = None

        return method(self, user)
Exemple #23
0
def find_similar_subjects(location_id, id, n=5):
    """Find 5 similar subjects to the one given."""
    location = LocationTag.get(location_id)
    subject = Subject.get(location, id)

    def filter_out(query):
        return query.filter(SearchItem.content_item_id != subject.id)

    results = search(text=subject.title, obj_type='subject', disjunctive=False, limit=n, extra=filter_out, language=location.language)
    if not results:
        results = search(text=subject.title,
                obj_type='subject',
                tags=subject.location.hierarchy(),
                disjunctive=True,
                limit=5,
                extra=filter_out,
                rank_cutoff=0.1,
                language=location.language)
    return [item.object.info_dict() for item in results]
Exemple #24
0
    def get(cls, username, location):
        if isinstance(location, (long, int)):
            from ututi.model import LocationTag
            location = LocationTag.get(location)

        if location is None:
            return None

        loc_ids = [loc.id for loc in location.flatten]
        q = meta.Session.query(cls).filter(cls.location_id.in_(loc_ids))

        if isinstance(username, (long, int)):
            q = q.filter_by(id=username)
        else:
            q = q.filter_by(username=username.strip().lower())

        try:
            return q.one()
        except NoResultFound:
            return None
Exemple #25
0
    def _subject_action(self, id, tags, file_id):
        location = LocationTag.get(tags)
        subject = Subject.get(location, id)

        if subject is None:
            abort(404)

        file = File.get(file_id)
        if file is None:
            abort(404)

        if (file not in subject.files
            and not file.can_write()):
            abort(404)

        c.object_location = subject.location
        c.security_context = file
        c.subject = subject
        c.theme = subject.location.get_theme()
        return method(self, subject, file)
def test_setup(test):
    """Create some models for this test."""
    ututi.tests.setUp(test)

    # The following c&p from model tests. Maybe should be put to base set up.

    #a user needs a university
    uni = LocationTag(u'U-niversity', u'uni', u'', member_policy='PUBLIC')
    meta.Session.add(uni)
    meta.Session.commit()

    #the user
    meta.Session.execute("insert into authors (type, fullname) values ('user', 'Administrator of the university')")
    meta.Session.execute("insert into users (id, location_id, username, password)"
                         " (select authors.id, tags.id, '*****@*****.**', 'xnIVufqLhFFcgX+XjkkwGbrY6kBBk0vvwjA7'"
                         " from tags, authors where title_short = 'uni' and fullname = 'Administrator of the university');")
    meta.Session.execute("insert into emails (id, email, confirmed)"
                         " (select users.id, users.username, true from users where username = '******')")
    meta.Session.commit()

    u = User.get('*****@*****.**', uni)
    user = User(u"a new user", "*****@*****.**", uni, "his password")
    meta.Session.add(user)
    user.emails.append(Email("*****@*****.**"))
    user.phone_number = '+37060000000'
    user.phone_confirmed = False
    meta.Session.commit()

    meta.Session.execute("SET LOCAL ututi.active_user TO %d" % u.id)

    g = Group('moderators', u'Moderatoriai', LocationTag.get(u'vu'), date.today(), u'U2ti moderatoriai.')

    role = GroupMembershipType.get('administrator')
    gm = GroupMember()
    gm.user = u
    gm.group = g
    gm.role = role
    meta.Session.add(g)
    meta.Session.add(gm)
    meta.Session.commit()
    meta.set_active_user(u.id)
Exemple #27
0
    def index(self):
        if c.user is not None:
            redirect(url(controller='profile', action='home'))
        else:
            # If default_location is set in configuration.ini, try
            # redirecting to it.
            default_location_path = config.get('default_location', None)
            if default_location_path:
                default_location = LocationTag.get(default_location_path)
                if default_location:
                    return redirect(default_location.url())

            self._get_unis()
            (c.subjects, c.groups, c.universities) = (self._subjects(), self._groups(), self._universities(limit=12))

            c.all_universities = self._universities()

            if request.params.has_key('js'):
                return render_mako_def('/search/browse.mako', 'universities', unis=c.unis, ajax_url=url(controller='home', action='index'))
            c.slideshow = request.params.has_key('slide')
            return htmlfill.render(self._sign_up_form())
Exemple #28
0
    def _profile_action(self, path, id, post_id):
        location = LocationTag.get(path)
        user = find_user(id)

        if user is None or not user.is_teacher or user.location != location:
            abort(404)

        if not user.profile_is_public and not c.user:
            deny(_('This user profile is not public'), 401)

        post = meta.Session.query(TeacherBlogPost).filter_by(id=post_id, created=user).one()
        if not post:
            abort(404)

        c.teacher = user
        c.location = user.location
        c.tabs = external_teacher_tabs(user)
        c.current_tab = 'blog'
        c.theme = None

        return method(self, user, post)
Exemple #29
0
    def _to_python(self, value, state):
        obj = None
        # check if this is a plain numeric id
        try:
            num_id = int(value)
            obj = ContentItem.get(num_id)
        except ValueError:
            pass

        # check if the id is a path to a subject
        if obj is None and value.startswith('subject'):
            path = value.split('/')[1:]
            location = LocationTag.get(path[:-1])
            obj = Subject.get(location, path.pop())

        # check if the object is a group
        if obj is None and value.startswith('group'):
            id = value.split('/')
            obj = Group.get(id.pop())

        return obj
Exemple #30
0
    def email_domains(self):
        if hasattr(self, 'form_result'):
            location_id = self.form_result.get('location_id', 0)
            location = LocationTag.get(location_id)
            # here location_id = 0 -> location = None -> domain is public
            for domain in self.form_result['domains']:
                meta.Session.add(EmailDomain(domain, location))
            meta.Session.commit()

        unis = meta.Session.query(LocationTag)\
            .filter(LocationTag.parent == None)\
            .order_by(LocationTag.title.asc())
        c.uni_options = [(0, 'Public domain')]
        for uni in unis:
            for u in uni.flatten:
                title = u.title
                if u.parent:
                    title = "%s: %s" % (u.parent.title, u.title)
                c.uni_options.append((u.id, title))

        c.public_domains = EmailDomain.all()
        return render('admin/email_domains.mako')