Ejemplo n.º 1
0
def view_pw_reset(context, request):
    
    # Second step: User is visiting reset url
    if 'key' in request.params:
        key = request.params['key']
        
        if 'form.submitted' in request.params:
            try:
                # FormEncode validation
                schema = PWResetSchema()
                form_result = schema.to_python(request.params)
            except formencode.validators.Invalid, why:
                form = render_template('templates/password_reset.pt', request=request, api=TemplateAPI(request))
                # FormEncode fills template with error messages
                form = htmlfill.render(form, defaults=request.params, errors=why.error_dict)
                return Response(form)
            else:
                session = DBSession()
                user = session.query(User).filter_by(email=form_result['email']).one()
                if key == user.password_reset_key():
                    user.password = '******' % sha.new(form_result['password'].encode('utf-8')).hexdigest()
                    # Login directly
                    headers = []
                    plugins = request.environ.get('repoze.who.plugins', {})
                    identifier = plugins.get('auth_tkt')
                    if identifier:
                        identity = {'repoze.who.userid': form_result['email']}
                        headers = identifier.remember(request.environ, identity)
                    request.environ['repoze.who.userid'] = form_result['email']
                    return HTTPFound(location = model_url(context, request), headers=headers)
                else:
                    statusmessage.show(request, u"Retrieve request not valid.", u"error")
        
        return render_template_to_response('templates/password_reset.pt', request=request, api=TemplateAPI(request))
Ejemplo n.º 2
0
def retail_view(context, request):

    page_title = context.title
    api = TemplateAPI(context, request, page_title)

    middle_portlet_html = _get_portlet_html(context, request,
                                            context.middle_portlets)
    right_portlet_html = _get_portlet_html(context, request,
                                           context.right_portlets)
    current_intranet = api.current_intranet
    feature = getattr(find_intranets(current_intranet), 'feature', u'')

    # Rendering this separately gives us a chance later to think about
    # some kind of caching.
    body = render_template(
        'templates/intranethome_body.pt',
        current_intranet=current_intranet,
        feature=feature,
        middle_portlet_html=middle_portlet_html,
        right_portlet_html=right_portlet_html,
        )

    return render_template_to_response(
        'templates/intranet_homepage.pt',
        api=api,
        body=body,
        )
Ejemplo n.º 3
0
def request_password_reset(user, profile, request):
    profile.password_reset_key = sha1(
        str(random.random())).hexdigest()
    profile.password_reset_time = datetime.datetime.now()
    context = find_site(profile)
    reset_url = model_url(
        context, request, "reset_confirm.html",
        query=dict(key=profile.password_reset_key))

    # send email
    mail = Message()
    system_name = get_setting(context, 'system_name', 'OpenCore')
    admin_email = get_setting(context, 'admin_email')
    mail["From"] = "%s Administrator <%s>" % (system_name, admin_email)
    mail["To"] = "%s <%s>" % (profile.title, profile.email)
    mail["Subject"] = "%s Password Reset Request" % system_name
    body = render_template(
        "templates/email_reset_password.pt",
        login=user['login'],
        reset_url=reset_url,
        system_name=system_name,
    )

    if isinstance(body, unicode):
        body = body.encode("UTF-8")

    mail.set_payload(body, "UTF-8")
    mail.set_type("text/html")

    recipients = [profile.email]
    mailer = getUtility(IMailDelivery)
    mailer.send(admin_email, recipients, mail)
Ejemplo n.º 4
0
def comments_view(context, request):
    
    journal_entry = context.__parent__
    
    return render_template('templates/comments.pt',
                           api=TemplateAPI(request),
                           journal_entry=journal_entry,
                           number=journal_entry.comments.count(),
                           context=context)
Ejemplo n.º 5
0
def comments_view(context, request):

    journal_entry = context.__parent__

    return render_template('templates/comments.pt',
                           api=TemplateAPI(request),
                           journal_entry=journal_entry,
                           number=journal_entry.comments.count(),
                           context=context)
Ejemplo n.º 6
0
def change_password_view(context, request):
    min_pw_length = get_setting(context, 'min_pw_length')
    form = ChangePasswordForm(min_pw_length=min_pw_length)
    if 'form.cancel' in request.POST:
        return HTTPFound(location=model_url(context, request))

    if 'form.submitted' in request.POST:
        try:
            converted = form.validate(request.POST)
            users = find_users(context)
            userid = context.__name__
            user = users.get_by_id(userid)

            # check the old password
            # XXX: repoze.who.plugins.zodb.interfaces.IUsers
            # really should have a check_password(id, password)
            # method.  We shouldn't have to use get_sha_password
            # directly.
            enc = get_sha_password(converted['old_password'])
            if enc != user['password']:
                raise CustomInvalid({'old_password': '******'})

            users.change_password(userid, converted['password'])

            # send email
            system_name = get_setting(context, 'system_name', 'KARL')
            mail = karl.mail.Message()
            admin_email = get_setting(context, 'admin_email')
            mail["From"] = "%s Administrator <%s>" % (system_name, admin_email)
            mail["To"] = "%s <%s>" % (context.title, context.email)
            mail["Subject"] = "%s Password Change Notification" % system_name
            system_name = get_setting(context, 'system_name', 'KARL')
            body = render_template(
                "templates/email_change_password.pt",
                login=user['login'],
                password=converted['password'],
                system_name=system_name,
            )

            if isinstance(body, unicode):
                body = body.encode("UTF-8")

            mail.set_payload(body, "UTF-8")
            mail.set_type("text/html")

            recipients = [context.email]
            mailer = getUtility(IMailDelivery)
            mailer.send(admin_email, recipients, mail)

            path = model_url(context, request)
            msg = '?status_message=Password%20changed'
            return HTTPFound(location=path+msg)

        except Invalid, e:
            fielderrors = e.error_dict
            fill_values = form.convert(request.POST)
Ejemplo n.º 7
0
def objectives_pdf_view(context, request):

    project = context.__parent__

    result = render_template('templates/objectives_pdf.pt',
                             api=TemplateAPI(request),
                             project=project)

    response = Response(parseString(result.encode('utf-8')).read())
    response.content_type = "application/pdf"
    return response
Ejemplo n.º 8
0
def objectives_pdf_view(context, request):

    project = context.__parent__     

    result =  render_template('templates/objectives_pdf.pt',
               api=TemplateAPI(request),
               project = project)
     
    response = Response(parseString(result.encode('utf-8')).read())
    response.content_type =  "application/pdf"
    return response
Ejemplo n.º 9
0
    def handle_submit(self, validated):
        
        user = _get_user_by_email(self.context, validated['email'])
        
        # No such user, we're not letting anyone know about it though to protect
        # users from crooks trying to explore the users DB in hope of finding
        # out who has an account here.
        if not user:
            return self._redirect()
        
        request_id = uuid4().hex
        request = PasswordRequestRequest(request_id, user.email)
        
        site = find_site(self.context)
        if user.email in site['reset_password']:
            del site['reset_password'][user.email]
            
        site['reset_password'][user.email] = request

        reset_url = model_url(self.context, self.request, 
                              "reset.html", query=dict(key=request_id))
        
        # send email
        mail = Message()
        system_name = get_setting(self.context, 'system_name', 'OpenCore')
        admin_email = get_setting(self.context, 'admin_email')
        mail["From"] = "%s Administrator <%s>" % (system_name, admin_email)
        mail["To"] = "%s <%s>" % (user.title, user.email)
        mail["Subject"] = "%s Password Reset Request" % system_name
        body = render_template(
            "templates/email_reset_password.pt",
            login=user.__name__,
            reset_url=reset_url,
            system_name=system_name,
            valid_hours=REQUEST_VALIDITY_HOURS,
        )
    
        if isinstance(body, unicode):
            body = body.encode("UTF-8")
    
        mail.set_payload(body, "UTF-8")
        mail.set_type("text/html")
    
        recipients = [user.email]
        mailer = getUtility(IMailDelivery)
        mailer.send(admin_email, recipients, mail)
        
        return self._redirect()
Ejemplo n.º 10
0
def _get_viewall(context, request, api):
    """Get the nested data used by ZPT for showing the refman TOC"""

    # First, be a chicken and sync
    context.ordering.sync(context.keys())

    # Iterate over each section using the ordering for the order of
    # __name__'s
    sections = []
    for section_name in context.ordering.items():
        # Get the data about this section
        section = context.get(section_name)
        section.ordering.sync(section.keys())
        item = {
            'name': section_name,
            'title': section.title,
            'html': '<p>%s</p>' % section.description,
            'items': [],
            }
        # Now append data about each section's items, again using the
        # ordering
        for subitem_name in section.ordering.items():
            subitem = section.get(subitem_name)

            # If this is a page, we generate one chunk of HTML, if
            # File, a different
            if IPage.providedBy(subitem):
                html = subitem.text
            elif ICommunityFile.providedBy(subitem):
                fileinfo = getMultiAdapter((subitem, request), IFileInfo)
                html = render_template(
                    'templates/inline_file.pt',
                    api=api,
                    fileinfo=fileinfo,
                    )
            else:
                html = '<p>Unknown type</p>'
            item['items'].append({
                'name': subitem_name,
                'title': subitem.title,
                'html': html,
                 })

        sections.append(item)

    return sections
Ejemplo n.º 11
0
def view_pw_reset(context, request):

    # Second step: User is visiting reset url
    if 'key' in request.params:
        key = request.params['key']

        if 'form.submitted' in request.params:
            try:
                # FormEncode validation
                schema = PWResetSchema()
                form_result = schema.to_python(request.params)
            except formencode.validators.Invalid, why:
                form = render_template('templates/password_reset.pt',
                                       request=request,
                                       api=TemplateAPI(request))
                # FormEncode fills template with error messages
                form = htmlfill.render(form,
                                       defaults=request.params,
                                       errors=why.error_dict)
                return Response(form)
            else:
                session = DBSession()
                user = session.query(User).filter_by(
                    email=form_result['email']).one()
                if key == user.password_reset_key():
                    user.password = '******' % sha.new(
                        form_result['password'].encode('utf-8')).hexdigest()
                    # Login directly
                    headers = []
                    plugins = request.environ.get('repoze.who.plugins', {})
                    identifier = plugins.get('auth_tkt')
                    if identifier:
                        identity = {'repoze.who.userid': form_result['email']}
                        headers = identifier.remember(request.environ,
                                                      identity)
                    request.environ['repoze.who.userid'] = form_result['email']
                    return HTTPFound(location=model_url(context, request),
                                     headers=headers)
                else:
                    statusmessage.show(request, u"Retrieve request not valid.",
                                       u"error")

        return render_template_to_response('templates/password_reset.pt',
                                           request=request,
                                           api=TemplateAPI(request))
Ejemplo n.º 12
0
def student_application_pdf_view(context, request):

    data = gained_competences(context)

    show_projects = request.GET.get('show_projects', False)
    show_journal = request.GET.get('show_journal', False)
    show_indcators = request.GET.get('show_indcators', False)

    result = render_template('templates/student_application_pdf.pt',
                             api=TemplateAPI(request),
                             student=context,
                             show_projects=show_projects,
                             show_journal=show_journal,
                             show_indcators=show_indcators,
                             data=data)
    response = Response(parseString(result.encode('utf-8')).read())
    response.content_type = "application/pdf"
    return response
Ejemplo n.º 13
0
def student_application_pdf_view(context, request):
    
    data = gained_competences(context)
    
    show_projects = request.GET.get('show_projects', False)
    show_journal = request.GET.get('show_journal', False)
    show_indcators = request.GET.get('show_indcators', False)
    
    result = render_template('templates/student_application_pdf.pt',
                             api=TemplateAPI(request),
                             student = context,
                             show_projects = show_projects,
                             show_journal = show_journal,
                             show_indcators = show_indcators,
                             data=data)
    response = Response(parseString(result.encode('utf-8')).read())
    response.content_type =  "application/pdf"
    return response
Ejemplo n.º 14
0
def drawer_dialog_view(context, request,
                       batch_images=batch_images): # unittest
    """This view returns a json reply that is a dictionary containing:

        dialog_snippet: the html of the dialog

        images_info: the first batch of the image listing

        error: ... explicitely raise an error
    """
    # Render the dialog template
    dialog_snippet = render_template('templates/imagedrawer_dialog_snippet.pt',
        )

    return dict(
        dialog_snippet=dialog_snippet,
        images_info=batch_images(context, request),
    )
Ejemplo n.º 15
0
def view_invoice_pdf(request):
    session = DBSession()
    company = session.query(Company).first()
    
    invoice_id = request.matchdict['invoice']
    invoice = session.query(Invoice).filter_by(id=invoice_id).first()
    if not invoice:
        return Response(status=404)
    
    rml_template = 'templates/rml/' + company.invoice_template
        
    # Only jpeg without PIL
    logo_path = os.path.join(os.path.dirname(__file__), 'templates', 'static', 'uploads', 'logo.jpg')
        
    result = render_template(rml_template, invoice=invoice, logo_path=logo_path,
                             formatThousands=formatThousands)
    response = Response(parseString(result.encode('utf-8')).read())
    response.content_type =  "application/pdf"
    return response
Ejemplo n.º 16
0
 def __call__(self, api):
     counts = {}  # {(year, month): count}
     for entry in self.context.values():
         if not IBlogEntry.providedBy(entry):
             continue
         if not has_permission('view', entry, self.request):
             continue
         year = entry.created.year
         month = entry.created.month
         counts[(year, month)] = counts.get((year, month), 0) + 1
     counts = counts.items()
     counts.sort()
     counts.reverse()
     activity_list = [MonthlyActivity(year, month, count)
         for ((year, month), count) in counts]
     blog_url = model_url(self.context, self.request)
     return render_template(
         'templates/blog_sidebar.pt',
         api=api,
         activity_list=activity_list,
         blog_url=blog_url,
         )
Ejemplo n.º 17
0
def view_invoice_pdf(request):
    session = DBSession()
    company = session.query(Company).first()

    invoice_id = request.matchdict['invoice']
    invoice = session.query(Invoice).filter_by(id=invoice_id).first()
    if not invoice:
        return Response(status=404)

    rml_template = 'templates/rml/' + company.invoice_template

    # Only jpeg without PIL
    logo_path = os.path.join(os.path.dirname(__file__), 'templates', 'static',
                             'uploads', 'logo.jpg')

    result = render_template(rml_template,
                             invoice=invoice,
                             logo_path=logo_path,
                             formatThousands=formatThousands)
    response = Response(parseString(result.encode('utf-8')).read())
    response.content_type = "application/pdf"
    return response
Ejemplo n.º 18
0
    def bounce_message_throttled(self, message):
        mailer = getUtility(IMailDelivery)
        from_email = get_setting(self.root, 'postoffice.bounce_from_email')
        if from_email is None:
            from_email = get_setting(self.root, 'admin_email')

        bounce_message = Message()
        bounce_message['From'] = from_email
        bounce_message['To'] = message['From']
        bounce_message['Subject'] = 'Your submission to Karl has bounced.'
        bounce_message.set_type('text/html')
        bounce_message.set_payload(render_template(
            'templates/bounce_email_throttled.pt',
            subject=message.get('Subject'),
            system_name=get_setting(self.root, 'system_name', 'KARL'),
            admin_email=get_setting(self.root, 'admin_email'),
        ).encode('UTF-8'), 'UTF-8')

        self.queue.bounce(
            message, wrap_send(mailer.send), from_email,
            bounce_message=bounce_message
        )
Ejemplo n.º 19
0
def student_competence_cloud_view(context, request):
    session = DBSession()
    query = session.query(Competence.title, func.count(Competence.id))
    query = query.filter(Student.id == context.id)
    query = query.join(Student.journal_entries)
    query = query.join(JournalEntry.indicators)
    query = query.join(Indicator.indicator_set)
    query = query.join(IndicatorSet.competence)
    query = query.group_by(Competence.id, Competence.title)
    
    tags = query.all()
    if tags is not None:
        cloud = [{'name': x[0], 'count': x[1]} for x in tags]
        limited = list(reversed(sorted(cloud, key=lambda x: x['count'])))[:100]
        entries = sorted(_calculateTagWeights(limited), key=lambda x: x['name'])
    else:
        entries = ()

    return render_template(
        'templates/competence_cloud.pt',
        api=TemplateAPI(request),
        entries=entries,
        )
Ejemplo n.º 20
0
def student_competence_cloud_view(context, request):
    session = DBSession()
    query = session.query(Competence.title, func.count(Competence.id))
    query = query.filter(Student.id == context.id)
    query = query.join(Student.journal_entries)
    query = query.join(JournalEntry.indicators)
    query = query.join(Indicator.indicator_set)
    query = query.join(IndicatorSet.competence)
    query = query.group_by(Competence.id, Competence.title)

    tags = query.all()
    if tags is not None:
        cloud = [{'name': x[0], 'count': x[1]} for x in tags]
        limited = list(reversed(sorted(cloud, key=lambda x: x['count'])))[:100]
        entries = sorted(_calculateTagWeights(limited),
                         key=lambda x: x['name'])
    else:
        entries = ()

    return render_template(
        'templates/competence_cloud.pt',
        api=TemplateAPI(request),
        entries=entries,
    )
Ejemplo n.º 21
0
            return HTTPFound(location = model_url(context, request))
    elif 'form.cancel' in request.POST:
        return HTTPFound(location = model_url(context, request))
        
    else:
        if not add_form:
            for field_name in project_schema.fields.keys():
                defaults[field_name] = getattr(project, field_name)
                
            if defaults['start_date']:
                defaults['start_date'] = defaults['start_date'].strftime('%d.%m.%Y')
            if defaults['end_date']:
                defaults['end_date'] = defaults['end_date'].strftime('%d.%m.%Y')
    
    form = render_template('templates/project_edit.pt',
                           project=project,
                           add_form=add_form, 
                           api=TemplateAPI(request))
    # FormEncode fills template with default values
    form = htmlfill.render(form, defaults=defaults, errors=errors)
    return Response(form)


def project_view(context, request):
        
    project = context
    competence_cloud = project_competence_cloud_view(context, request)
    
    return dict(api=TemplateAPI(request),
                project=project,
                request=request,
                comments_view=comments_view,
Ejemplo n.º 22
0
            return HTTPFound(location = model_url(context, request))
        else:
            return HTTPFound(location = model_url(context, request, str(student.id)))
        
    else:
        if not add_form:
            field_names = [ p.key for p in class_mapper(Student).iterate_properties ]
            for field_name in field_names:
                defaults[field_name] = getattr(student, field_name)
            defaults['portrait'] = ''
            if defaults['date_of_birth']:
                defaults['date_of_birth'] = defaults['date_of_birth'].strftime('%d/%m/%Y')
                
    
    form = render_template('templates/student_edit.pt',
                           student=student,
                           add_form=add_form, 
                           api=TemplateAPI(request))
    
    # FormEncode fills template with default values
    form = htmlfill.render(form, defaults=defaults, errors=errors)
    return Response(form)

    
def student_projects_view(context, request):
 
    student = context
    projects = student.projects
    
    return dict(student=context,
               request=request,
               projects=projects,
Ejemplo n.º 23
0
                            indicator_set, field_name):
                        setattr(indicator_set, field_name,
                                form_result[field_name])
                        changed = True
            # Add project if this is the add form
            if add_form:
                session = DBSession()
                indicator_set.competence = competence
                session.add(indicator_set)
            return HTTPFound(
                location=model_url(competence.__parent__, request))
    elif 'form.cancel' in request.POST:
        return HTTPFound(location=model_url(competence.__parent__, request))

    else:
        if not add_form:
            field_names = [
                p.key for p in class_mapper(IndicatorSet).iterate_properties
            ]
            for field_name in field_names:
                defaults[field_name] = getattr(indicator_set, field_name)

    form = render_template('templates/indicator_set_edit.pt',
                           indicator_set=indicator_set,
                           competence=competence,
                           add_form=add_form,
                           api=TemplateAPI(request))
    # FormEncode fills template with default values
    form = htmlfill.render(form, defaults=defaults, errors=errors)
    return Response(form)
Ejemplo n.º 24
0
                        identity = {'repoze.who.userid': form_result['email']}
                        headers = identifier.remember(request.environ, identity)
                    request.environ['repoze.who.userid'] = form_result['email']
                    return HTTPFound(location = model_url(context, request), headers=headers)
                else:
                    statusmessage.show(request, u"Retrieve request not valid.", u"error")
        
        return render_template_to_response('templates/password_reset.pt', request=request, api=TemplateAPI(request))
    
    # First step: Create and send reset url
    if 'form.submitted' in request.params:
        try:
            # FormEncode validation
            schema = PWResetRequestSchema()
            form_result = schema.to_python(request.params)
        except formencode.validators.Invalid, why:
            form = render_template('templates/password_retrieve.pt', request = request, api=TemplateAPI(request),)
            # FormEncode fills template with error messages
            form = htmlfill.render(form, defaults=request.params, errors=why.error_dict)
            return Response(form)
        else:
            session = DBSession()
            user = session.query(User).filter_by(email=form_result['email']).one()
            reset_url = model_url(get_root(request), request, 'retrieve_password.html')
            user.send_password_reset(reset_url)
                       
            statusmessage.show(request, u'Password retrieval e-mail sent.')
            return HTTPFound(location = model_url(context, request))
    
    return render_template_to_response('templates/password_retrieve.pt', request=request, api=TemplateAPI(request))
Ejemplo n.º 25
0
         errors=why.error_dict
     else:
         # Apply schema fields to the project object
         field_names = [ p.key for p in class_mapper(Competence).iterate_properties ]
         changed = False
         for field_name in field_names:
             if field_name in form_result.keys():
                 if form_result[field_name] != getattr(competence, field_name):
                     setattr(competence, field_name, form_result[field_name])
                     changed = True
         # Add project if this is the add form
         if add_form:
             session.add(competence)
         return HTTPFound(location = model_url(context, request))
 elif 'form.cancel' in request.POST:
     return HTTPFound(location = model_url(context, request))
     
 else:
     if not add_form:
         field_names = [ p.key for p in class_mapper(Competence).iterate_properties ]
         for field_name in field_names:
             defaults[field_name] = getattr(competence, field_name)
 
 form = render_template('templates/competence_edit.pt',
                        competence=competence,
                        meta_competences=meta_competences,
                        add_form=add_form, 
                        api=TemplateAPI(request))
 # FormEncode fills template with default values
 form = htmlfill.render(form, defaults=defaults, errors=errors)
 return Response(form)
Ejemplo n.º 26
0
 def __call__(self, api):
     fileinfo = getMultiAdapter((self.context, self.request), IFileInfo)
     return render_template('templates/inline_file.pt',
                            api=api,
                            fileinfo=fileinfo,
                           )
Ejemplo n.º 27
0
 def asHTML(self):
     return render_template(
         'templates/feed.pt',
         feed=self.context,
         )
Ejemplo n.º 28
0
                location=model_url(context, request, str(student.id)))

    else:
        if not add_form:
            field_names = [
                p.key for p in class_mapper(Student).iterate_properties
            ]
            for field_name in field_names:
                defaults[field_name] = getattr(student, field_name)
            defaults['portrait'] = ''
            if defaults['date_of_birth']:
                defaults['date_of_birth'] = defaults['date_of_birth'].strftime(
                    '%d/%m/%Y')

    form = render_template('templates/student_edit.pt',
                           student=student,
                           add_form=add_form,
                           api=TemplateAPI(request))

    # FormEncode fills template with default values
    form = htmlfill.render(form, defaults=defaults, errors=errors)
    return Response(form)


def student_projects_view(context, request):

    student = context
    projects = student.projects

    return dict(student=context,
                request=request,
                projects=projects,
Ejemplo n.º 29
0
                    if form_result[field_name] != getattr(
                            indicator, field_name):
                        setattr(indicator, field_name, form_result[field_name])
                        changed = True
            # Add project if this is the add form
            if add_form:
                session = DBSession()
                indicator.indicator_set = indicator_set
                indicator.index = indicator_set.indicators.count() - 1
                session.add(indicator)
            return HTTPFound(
                location=model_url(competences_container, request))
    elif 'form.cancel' in request.POST:
        return HTTPFound(location=model_url(competences_container, request))

    else:
        if not add_form:
            field_names = [
                p.key for p in class_mapper(Indicator).iterate_properties
            ]
            for field_name in field_names:
                defaults[field_name] = getattr(indicator, field_name)

    form = render_template('templates/indicator_edit.pt',
                           indicator=indicator,
                           add_form=add_form,
                           api=TemplateAPI(request))
    # FormEncode fills template with default values
    form = htmlfill.render(form, defaults=defaults, errors=errors)
    return Response(form)
Ejemplo n.º 30
0
                                       u"error")

        return render_template_to_response('templates/password_reset.pt',
                                           request=request,
                                           api=TemplateAPI(request))

    # First step: Create and send reset url
    if 'form.submitted' in request.params:
        try:
            # FormEncode validation
            schema = PWResetRequestSchema()
            form_result = schema.to_python(request.params)
        except formencode.validators.Invalid, why:
            form = render_template(
                'templates/password_retrieve.pt',
                request=request,
                api=TemplateAPI(request),
            )
            # FormEncode fills template with error messages
            form = htmlfill.render(form,
                                   defaults=request.params,
                                   errors=why.error_dict)
            return Response(form)
        else:
            session = DBSession()
            user = session.query(User).filter_by(
                email=form_result['email']).one()
            reset_url = model_url(get_root(request), request,
                                  'retrieve_password.html')
            user.send_password_reset(reset_url)
Ejemplo n.º 31
0
        return HTTPFound(location=model_url(context, request))

    else:
        if not add_form:
            for field_name in project_schema.fields.keys():
                defaults[field_name] = getattr(project, field_name)

            if defaults['start_date']:
                defaults['start_date'] = defaults['start_date'].strftime(
                    '%d.%m.%Y')
            if defaults['end_date']:
                defaults['end_date'] = defaults['end_date'].strftime(
                    '%d.%m.%Y')

    form = render_template('templates/project_edit.pt',
                           project=project,
                           add_form=add_form,
                           api=TemplateAPI(request))
    # FormEncode fills template with default values
    form = htmlfill.render(form, defaults=defaults, errors=errors)
    return Response(form)


def project_view(context, request):

    project = context
    competence_cloud = project_competence_cloud_view(context, request)

    return dict(api=TemplateAPI(request),
                project=project,
                request=request,
                comments_view=comments_view,
Ejemplo n.º 32
0
    query = query.filter(Project.id == project.id)
    query = query.join(Project.objectives)
    query = query.join(Objective.competences)
    query = query.join(Competence.indicator_sets)
    indicator_sets = []
    for indicator_set in query.all():
        indicators = []
        for indicator in indicator_set.indicators:
            if indicator not in already_tagged:
                indicators.append({
                    'id': str(indicator.id),
                    'description': indicator.description
                })
        if indicators:
            indicator_sets.append({
                'title': indicator_set.title,
                'indicators': indicators,
                'competence': indicator_set.competence.title
            })

    form = render_template('templates/journal_add.pt',
                           api=TemplateAPI(request),
                           indicator_sets=indicator_sets,
                           project=project,
                           entry=entry,
                           add_form=add_form)

    # FormEncode fills template with default values
    form = htmlfill.render(form, defaults=defaults, errors=errors)
    return Response(form)
Ejemplo n.º 33
0
                    if form_result[field_name] != getattr(teacher, field_name):
                        setattr(teacher, field_name, form_result[field_name])
                        changed = True

            # Add student if this is the add form
            if add_form:
                session = DBSession()
                session.add(teacher)

                if not form_result["password"]:
                    reset_url = model_url(get_root(request), request, "retrieve_password.html")
                    teacher.send_password_reset(reset_url)

            return HTTPFound(location=model_url(context, request))

    elif "form.cancel" in request.POST:
        return HTTPFound(location=model_url(context, request))

    else:
        if not add_form:
            field_names = [p.key for p in class_mapper(Teacher).iterate_properties]
            for field_name in field_names:
                defaults[field_name] = getattr(teacher, field_name)
            defaults["portrait"] = ""

    form = render_template("templates/teacher_edit.pt", teacher=teacher, add_form=add_form, api=TemplateAPI(request))

    # FormEncode fills template with default values
    form = htmlfill.render(form, defaults=defaults, errors=errors)
    return Response(form)
Ejemplo n.º 34
0
                if form_result[field_name] != getattr(objective, field_name):
                    setattr(objective, field_name, form_result[field_name])
                    changed = True
            # Add onjective if this is the add form
            if add_form:
                objective.project = project
                session.add(objective)
            return HTTPFound(location=model_url(context, request))
    elif 'form.cancel' in request.POST:
        return HTTPFound(location=model_url(context, request))

    else:
        if not add_form:
            for field_name in objective_schema.fields.keys():
                value = getattr(objective, field_name)
                if field_name == 'competences':
                    values = []
                    for competence in value:
                        values.append(competence.id)
                    value = values
                defaults[field_name] = value

    form = render_template('templates/objective_edit.pt',
                           objective=objective,
                           competences=competences,
                           add_form=add_form,
                           api=TemplateAPI(request))
    # FormEncode fills template with default values
    form = htmlfill.render(form, defaults=defaults, errors=errors)
    return Response(form)
Ejemplo n.º 35
0
 def __call__(self, api):
     return render_template(
         'templates/community_sidebar.pt',
         api=api)
Ejemplo n.º 36
0
         # Apply schema fields to the project object
         field_names = [ p.key for p in class_mapper(Indicator).iterate_properties ]
         changed = False
         for field_name in field_names:
             if field_name in form_result.keys():
                 if form_result[field_name] != getattr(indicator, field_name):
                     setattr(indicator, field_name, form_result[field_name])
                     changed = True
         # Add project if this is the add form
         if add_form:
             session = DBSession()
             indicator.indicator_set = indicator_set
             indicator.index = indicator_set.indicators.count() - 1
             session.add(indicator)
         return HTTPFound(location = model_url(competences_container, request))
 elif 'form.cancel' in request.POST:
     return HTTPFound(location = model_url(competences_container, request))
     
 else:
     if not add_form:
         field_names = [ p.key for p in class_mapper(Indicator).iterate_properties ]
         for field_name in field_names:
             defaults[field_name] = getattr(indicator, field_name)
 
 form = render_template('templates/indicator_edit.pt',
                        indicator=indicator,
                        add_form=add_form, 
                        api=TemplateAPI(request))
 # FormEncode fills template with default values
 form = htmlfill.render(form, defaults=defaults, errors=errors)
 return Response(form)
Ejemplo n.º 37
0
            for field_name in field_names:
                if field_name in form_result.keys():
                    if form_result[field_name] != getattr(
                            competence, field_name):
                        setattr(competence, field_name,
                                form_result[field_name])
                        changed = True
            # Add project if this is the add form
            if add_form:
                session.add(competence)
            return HTTPFound(location=model_url(context, request))
    elif 'form.cancel' in request.POST:
        return HTTPFound(location=model_url(context, request))

    else:
        if not add_form:
            field_names = [
                p.key for p in class_mapper(Competence).iterate_properties
            ]
            for field_name in field_names:
                defaults[field_name] = getattr(competence, field_name)

    form = render_template('templates/competence_edit.pt',
                           competence=competence,
                           meta_competences=meta_competences,
                           add_form=add_form,
                           api=TemplateAPI(request))
    # FormEncode fills template with default values
    form = htmlfill.render(form, defaults=defaults, errors=errors)
    return Response(form)
Ejemplo n.º 38
0
            
            # Add student if this is the add form
            if add_form:
                session = DBSession()
                session.add(teacher)
                
                if not form_result['password']:
                    reset_url = model_url(get_root(request), request, 'retrieve_password.html')
                    teacher.send_password_reset(reset_url)
                
            return HTTPFound(location = model_url(context, request))
            
    elif 'form.cancel' in request.POST:
        return HTTPFound(location = model_url(context, request))

        
    else:
        if not add_form:
            field_names = [ p.key for p in class_mapper(Teacher).iterate_properties ]
            for field_name in field_names:
                defaults[field_name] = getattr(teacher, field_name)
            defaults['portrait'] = ''
    
    form = render_template('templates/teacher_edit.pt',
                           teacher=teacher,
                           add_form=add_form, 
                           api=TemplateAPI(request))
    
    # FormEncode fills template with default values
    form = htmlfill.render(form, defaults=defaults, errors=errors)
    return Response(form)
Ejemplo n.º 39
0
 def render(self):
     return render_template("templates/local_menu.pt",
                            entries=self.entries)
Ejemplo n.º 40
0
 def __call__(self, api):
     return render_template(
         'templates/footer.pt',
         api=api,
         )
Ejemplo n.º 41
0
def batch_view(context, request):
    kss_next_number = 0
    next_url = ''
    previous_url = ''
    kss_previous_number = 0
   
    batch_start = int(request.params.get('b_start', 0))  

    posts = context.get_recent_file_subpaths()

    batch = Batch(posts, start=batch_start, size=5)
    batch_size = batch.size
    batch_total = batch.total
    if batch.previous:
        previous_url = item_url(context, request, batch.previous.start)
        kss_previous_number = batch.previous.start
    if batch.next:
        next_url = item_url(context, request, batch.next.start)
        if batch.next.start:
            kss_next_number = batch.next.start
    batch_number = batch.number

    count = 0
    previous_batchs = []
    mybatch = batch
    while mybatch.previous:
        count = count + 1
        if count > 2:
            break
        previous_batchs.append(mybatch.previous)
        mybatch = mybatch.previous
    previous_batchs.reverse()
        
    count = 0
    next_batchs = []
    mybatch = batch
    while mybatch.next:
        count = count + 1
        if count > 2:
            break
        next_batchs.append(mybatch.next)
        mybatch = mybatch.next
    
    last_batch = None
    if batch.total-2 > batch.number:
        last_batch = batch.batches[batch.total-1]

    first_batch = None
    if batch.number-2 > 1:
        first_batch = batch.batches[0]

    return render_template('templates/batch.pt',
                            batch = batch,
                            batch_total = batch_total,
                            previous_url = previous_url,
                            kss_previous_number = kss_previous_number,
                            batch_size = batch_size,
                            kss_next_number = kss_next_number,
                            next_url = next_url,
                            first_batch = first_batch,
                            previous_batchs = previous_batchs,
                            next_batchs = next_batchs,
                            last_batch = last_batch,
                            )
Ejemplo n.º 42
0
         for field_name in objective_schema.fields.keys():
             if form_result[field_name] != getattr(objective, field_name):
                 setattr(objective, field_name, form_result[field_name])
                 changed = True
         # Add onjective if this is the add form
         if add_form:
             objective.project = project
             session.add(objective) 
         return HTTPFound(location = model_url(context, request))
 elif 'form.cancel' in request.POST:
     return HTTPFound(location = model_url(context, request))
     
 else:
     if not add_form:
         for field_name in objective_schema.fields.keys():
             value = getattr(objective, field_name)
             if field_name == 'competences':
                 values = []
                 for competence in value:
                     values.append(competence.id)
                 value = values
             defaults[field_name] = value
 
 form = render_template('templates/objective_edit.pt',
                        objective=objective,
                        competences=competences,
                        add_form=add_form,
                        api=TemplateAPI(request))
 # FormEncode fills template with default values
 form = htmlfill.render(form, defaults=defaults, errors=errors)
 return Response(form)
Ejemplo n.º 43
0
 def render(self):
     return render_template("templates/local_menu.pt", entries=self.entries)
Ejemplo n.º 44
0
 query = query.filter(JournalEntry.user == user)
 query = query.filter(JournalEntry.project == project)
 query = query.filter(JournalEntry.id != entry.id)
 query = query.join(Indicator.journal_entries)
 already_tagged = query.all()
 
 query = session.query(IndicatorSet)
 query = query.filter(Project.id == project.id)
 query = query.join(Project.objectives)
 query = query.join(Objective.competences)
 query = query.join(Competence.indicator_sets)
 indicator_sets = []
 for indicator_set in query.all():
     indicators = []
     for indicator in indicator_set.indicators:
         if indicator not in already_tagged:
             indicators.append({'id' : str(indicator.id), 'description' : indicator.description})
     if indicators:
         indicator_sets.append({'title' : indicator_set.title, 'indicators' : indicators, 'competence' : indicator_set.competence.title})
 
 form = render_template(
     'templates/journal_add.pt',
     api=TemplateAPI(request),
     indicator_sets=indicator_sets,
     project=project,
     entry=entry,
     add_form=add_form)
 
 # FormEncode fills template with default values
 form = htmlfill.render(form, defaults=defaults, errors=errors)
 return Response(form)
Ejemplo n.º 45
0
def reset_request_view(context, request):

    form = ResetRequestForm()
    system_name = get_setting(context, 'system_name', 'KARL')

    if 'form.cancel' in request.POST:
        return HTTPFound(location=model_url(context, request))

    if 'form.submitted' in request.POST:
        try:
            converted = form.validate(request.POST)

            address = converted['email']
            if address:
                address = address.lower()

            search = getAdapter(context, ICatalogSearch)
            count, docids, resolver = search(
                interfaces=[IProfile], email=[address])

            users = find_users(context)
            for docid in docids:
                profile = resolver(docid)
                if profile is None:
                    continue
                userid = profile.__name__
                user = users.get_by_id(userid)
                if user is None:
                    continue
                # found the profile and user
                break
            else:
                raise CustomInvalid({"email":
                    "%s has no account with the email address: %s" %
                    (system_name, address)})

            groups = user['groups']
            if groups and 'group.KarlStaff' in groups:
                # because staff accounts are managed centrally, staff
                # must use the forgot_password_url if it is set.
                forgot_password_url = get_setting(
                    context, 'forgot_password_url')
                if forgot_password_url:
                    came_from = model_url(context, request, "login.html")
                    url = '%s?email=%s&came_from=%s' % (
                        forgot_password_url, urllib.quote_plus(address),
                        urllib.quote_plus(came_from))
                    return HTTPFound(location=url)

            profile.password_reset_key = sha1(
                str(random.random())).hexdigest()
            profile.password_reset_time = datetime.datetime.now()
            reset_url = model_url(
                context, request, "reset_confirm.html") + (
                "?key=%s" % profile.password_reset_key)

            # send email
            mail = karl.mail.Message()
            admin_email = get_setting(context, 'admin_email')
            mail["From"] = "%s Administrator <%s>" % (system_name, admin_email)
            mail["To"] = "%s <%s>" % (profile.title, profile.email)
            mail["Subject"] = "%s Password Reset Request" % system_name
            body = render_template(
                "templates/email_reset_password.pt",
                login=user['login'],
                reset_url=reset_url,
                system_name=system_name,
            )

            if isinstance(body, unicode):
                body = body.encode("UTF-8")

            mail.set_payload(body, "UTF-8")
            mail.set_type("text/html")

            recipients = [profile.email]
            mailer = getUtility(IMailDelivery)
            mailer.send(admin_email, recipients, mail)

            url = model_url(context, request, 'reset_sent.html') + (
                '?email=%s' % urllib.quote_plus(address))
            return HTTPFound(location=url)

        except Invalid, e:
            fielderrors = e.error_dict
            fill_values = form.convert(request.POST)
Ejemplo n.º 46
0
 def __call__(self):
     xml = render_template(self._template, view=self)
     response = Response(xml, content_type="application/atom+xml")
     return response
Ejemplo n.º 47
0
         field_names = [ p.key for p in class_mapper(IndicatorSet).iterate_properties ]
         changed = False
         for field_name in field_names:
             if field_name in form_result.keys():
                 if form_result[field_name] != getattr(indicator_set, field_name):
                     setattr(indicator_set, field_name, form_result[field_name])
                     changed = True
         # Add project if this is the add form
         if add_form:
             session = DBSession()
             indicator_set.competence = competence
             session.add(indicator_set)
         return HTTPFound(location = model_url(competence.__parent__, request))
 elif 'form.cancel' in request.POST:
     return HTTPFound(location = model_url(competence.__parent__, request))
     
 else:
     if not add_form:
         field_names = [ p.key for p in class_mapper(IndicatorSet).iterate_properties ]
         for field_name in field_names:
             defaults[field_name] = getattr(indicator_set, field_name)
 
 form = render_template('templates/indicator_set_edit.pt',
                        indicator_set=indicator_set,
                        competence=competence,
                        add_form=add_form, 
                        api=TemplateAPI(request))
 # FormEncode fills template with default values
 form = htmlfill.render(form, defaults=defaults, errors=errors)
 return Response(form)