Ejemplo n.º 1
0
def send_virus(request):
    status, error = sendmail_fromfile(
        "*****@*****.**", request.user.username,
        os.path.join(settings.MODOBOA_DIR, "tmp/virus.msg"))
    if status:
        return render_to_json_response(_("Message sent"))
    return render_to_json_response(error, status=500)
Ejemplo n.º 2
0
def edit(request, rdom_id, tplname='common/tabforms.html'):
    rdom = RelayDomain.objects.get(pk=rdom_id)
    if not request.user.can_access(rdom):
        raise PermDeniedException
    instances = {'general': rdom}
    events.raiseEvent("FillRelayDomainInstances", request.user, rdom,
                      instances)
    if request.method == 'POST':
        rdom.oldname = rdom.name
        form = RelayDomainForm(request.user, request.POST, instances=instances)
        if form.is_valid():
            form.save(request.user)
            events.raiseEvent('RelayDomainModified', rdom)
            return render_to_json_response(_('Relay domain modified'))

        return render_to_json_response({'form_errors': form.errors},
                                       status=400)
    ctx = {
        'action': reverse(edit, args=[rdom.id]),
        'formid': 'rdomform',
        'title': rdom.name,
        'action_label': _("Update"),
        'action_classes': "submit",
        'tabs': RelayDomainForm(request.user, instances=instances)
    }
    return render(request, tplname, ctx)
Ejemplo n.º 3
0
def autoreply(request, tplname="postfix_autoreply/autoreply.html"):
    mb = Mailbox.objects.get(user=request.user.id)
    try:
        arm = ARmessage.objects.get(mbox=mb.id)
    except ARmessage.DoesNotExist:
        arm = None
    if request.method == "POST":
        if arm:
            form = ARmessageForm(request.POST, instance=arm)
        else:
            form = ARmessageForm(request.POST)
        if form.is_valid():
            arm = form.save(commit=False)
            arm.fromdate = form.cleaned_data["fromdate"]
            arm.untildate = form.cleaned_data["untildate"]
            arm.mbox = mb
            arm.save()
            return render_to_json_response(
                _("Auto reply message updated successfully.")
            )

        return render_to_json_response(
            {"form_errors": form.errors}, status=400
        )

    form = ARmessageForm(instance=arm)
    return render_to_json_response({
        "content": _render_to_string(request, tplname, {"form": form}),
        "onload_cb": "autoreply_cb"
    })
Ejemplo n.º 4
0
def editdomain(request, dom_id, tplname="admin/editdomainform.html"):
    domain = Domain.objects.get(pk=dom_id)
    if not request.user.can_access(domain):
        raise PermDeniedException

    instances = dict(general=domain)
    events.raiseEvent("FillDomainInstances", request.user, domain, instances)
    if request.method == "POST":
        domain.oldname = domain.name
        form = DomainForm(request.user, request.POST, instances=instances)
        if form.is_valid():
            form.save(request.user)
            events.raiseEvent("DomainModified", domain)
            return render_to_json_response(_("Domain modified"))
        return render_to_json_response({
            'form_errors': form.errors
        }, status=400)

    domadmins = [u for u in domain.admins
                 if request.user.can_access(u) and not u.is_superuser]
    if not request.user.is_superuser:
        domadmins = [u for u in domadmins if u.group == "DomainAdmins"]
    ctx = {"title": domain.name,
           "action_label": _("Update"),
           "action_classes": "submit",
           "action": reverse(editdomain, args=[dom_id]),
           "formid": "domform",
           "domain": domain,
           "tabs": DomainForm(request.user, instances=instances),
           "domadmins": domadmins}
    return render(request, tplname, ctx)
Ejemplo n.º 5
0
def graphs(request):
    gset = request.GET.get("gset", None)
    gsets = events.raiseDictEvent("GetGraphSets")
    if not gset in gsets:
        raise NotFound(_("Unknown graphic set"))
    searchq = request.GET.get("searchquery", None)
    period = request.GET.get("period", "day")
    tplvars = dict(graphs={}, period=period)
    domain = check_domain_access(request.user, searchq)
    if domain is None:
        return render_to_json_response({})
    tplvars["domain"] = domain

    if period == "custom":
        if not "start" in request.GET or not "end" in request.GET:
            raise BadRequest(_("Bad custom period"))
        start = request.GET["start"]
        end = request.GET["end"]
        expr = re.compile(r'[:\- ]')
        period_name = "%s_%s" % (expr.sub('', start), expr.sub('', end))
        start = date_to_timestamp(expr.split(start))
        end = date_to_timestamp(expr.split(end))
    else:
        end = int(time.mktime(time.localtime()))
        start = "-1%s" % period
        period_name = period

    tplvars['graphs'] = gsets[gset].export(tplvars["domain"], start, end)
    tplvars["period_name"] = period_name
    tplvars["start"] = start
    tplvars["end"] = end

    return render_to_json_response(tplvars)
Ejemplo n.º 6
0
def submitfilter(request,
                 setname,
                 okmsg,
                 tplname,
                 tplctx,
                 update=False,
                 sc=None):
    form = build_filter_form_from_qdict(request)
    if form.is_valid():
        if sc is None:
            sc = SieveClient(user=request.user.username,
                             password=request.session["password"])
        fset = sc.getscript(setname, format="fset")
        conditions, actions = form.tofilter()
        match_type = form.cleaned_data["match_type"]
        if match_type == "all":
            match_type = "anyof"
            conditions = [("true", )]
        fltname = form.cleaned_data["name"].encode("utf-8")
        try:
            if not update:
                fset.addfilter(fltname, conditions, actions, match_type)
            else:
                oldname = request.POST["oldname"].encode("utf-8")
                fset.updatefilter(oldname, fltname, conditions, actions,
                                  match_type)
        except (BadArgument, BadValue) as inst:
            raise BadRequest(str(inst))
        sc.pushscript(fset.name, str(fset))
        return render_to_json_response(okmsg)

    return render_to_json_response({'form_errors': form.errors}, status=400)
Ejemplo n.º 7
0
def send_spam(request):
    status, error = sendmail_simple(
        "*****@*****.**",
        request.user.username,
        content="""
This is the GTUBE, the
        Generic
        Test for
        Unsolicited
        Bulk
        Email

If your spam filter supports it, the GTUBE provides a test by which you
can verify that the filter is installed correctly and is detecting incoming
spam. You can send yourself a test mail containing the following string of
characters (in upper case and with no white spaces and line breaks):

XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X

You should send this test mail from an account outside of your network.
""",
    )
    if status:
        return render_to_json_response(_("Message sent"))
    return render_to_json_response(respmsg=error, status=500)
Ejemplo n.º 8
0
def edit(request, rdom_id, tplname='common/tabforms.html'):
    rdom = RelayDomain.objects.get(pk=rdom_id)
    if not request.user.can_access(rdom):
        raise PermDeniedException
    instances = {'general': rdom}
    events.raiseEvent("FillRelayDomainInstances", request.user, rdom, instances)
    if request.method == 'POST':
        rdom.oldname = rdom.name
        form = RelayDomainForm(request.user, request.POST, instances=instances)
        if form.is_valid():
            form.save(request.user)
            events.raiseEvent('RelayDomainModified', rdom)
            return render_to_json_response(_('Relay domain modified'))

        return render_to_json_response(
            {'form_errors': form.errors}, status=400
        )
    ctx = {
        'action': reverse(edit, args=[rdom.id]),
        'formid': 'rdomform',
        'title': rdom.name,
        'action_label': _("Update"),
        'action_classes': "submit",
        'tabs': RelayDomainForm(request.user, instances=instances)
    }
    return render(request, tplname, ctx)
Ejemplo n.º 9
0
def editdomain(request, dom_id, tplname="admin/editdomainform.html"):
    domain = Domain.objects.get(pk=dom_id)
    if not request.user.can_access(domain):
        raise PermDeniedException

    instances = dict(general=domain)
    events.raiseEvent("FillDomainInstances", request.user, domain, instances)
    if request.method == "POST":
        domain.oldname = domain.name
        form = DomainForm(request.user, request.POST, instances=instances)
        if form.is_valid():
            form.save(request.user)
            events.raiseEvent("DomainModified", domain)
            return render_to_json_response(_("Domain modified"))
        return render_to_json_response({
            'form_errors': form.errors
        }, status=400)

    domadmins = [u for u in domain.admins
                 if request.user.can_access(u) and not u.is_superuser]
    if not request.user.is_superuser:
        domadmins = [u for u in domadmins if u.group == "DomainAdmins"]
    ctx = {"title": domain.name,
           "action_label": _("Update"),
           "action_classes": "submit",
           "action": reverse(editdomain, args=[dom_id]),
           "formid": "domform",
           "domain": domain,
           "tabs": DomainForm(request.user, instances=instances),
           "domadmins": domadmins}
    return render(request, tplname, ctx)
Ejemplo n.º 10
0
def shared_calendar(request, pk):
    """Edit or remove a shared calendar."""
    try:
        scal = SharedCalendar.objects.select_related().get(pk=pk)
    except SharedCalendar.DoesNotExist:
        raise NotFound
    if not request.user.can_access(scal.domain):
        raise PermDeniedException
    if request.method == "DELETE":
        if not request.user.can_access(scal.domain):
            raise PermDeniedException
        scal.delete()
        return render_to_json_response(_("Calendar removed"))
    if request.method == "POST":
        form = SharedCalendarForm(request.user, request.POST, instance=scal)
        if form.is_valid():
            form.save()
            return render_to_json_response(_("Calendar updated"))
        return render_to_json_response(
            {"form_errors": form.errors}, status=400
        )
    form = SharedCalendarForm(request.user, instance=scal)
    return render(request, "common/generic_modal_form.html", {
        "form": form,
        "formid": "sharedcal_form",
        "title": scal.name,
        "action": reverse("radicale:shared_calendar", args=[scal.pk]),
        "action_classes": "submit",
        "action_label": _("Submit")
    })
Ejemplo n.º 11
0
def send_virus(request):
    status, error = sendmail_fromfile(
        "*****@*****.**", request.user.username, os.path.join(settings.MODOBOA_DIR, "tmp/virus.msg")
    )
    if status:
        return render_to_json_response(_("Message sent"))
    return render_to_json_response(error, status=500)
Ejemplo n.º 12
0
def shared_calendar(request, pk):
    """Edit or remove a shared calendar."""
    try:
        scal = SharedCalendar.objects.select_related().get(pk=pk)
    except SharedCalendar.DoesNotExist:
        raise NotFound
    if not request.user.can_access(scal.domain):
        raise PermDeniedException
    if request.method == "DELETE":
        if not request.user.can_access(scal.domain):
            raise PermDeniedException
        scal.delete()
        return render_to_json_response(_("Calendar removed"))
    if request.method == "POST":
        form = SharedCalendarForm(request.user, request.POST, instance=scal)
        if form.is_valid():
            form.save()
            return render_to_json_response(_("Calendar updated"))
        return render_to_json_response({"form_errors": form.errors},
                                       status=400)
    form = SharedCalendarForm(request.user, instance=scal)
    return render(
        request, "common/generic_modal_form.html", {
            "form": form,
            "formid": "sharedcal_form",
            "title": scal.name,
            "action": reverse("radicale:shared_calendar", args=[scal.pk]),
            "action_classes": "submit",
            "action_label": _("Submit")
        })
Ejemplo n.º 13
0
def submitfilter(request, setname, okmsg, tplname, tplctx, update=False, sc=None):
    form = build_filter_form_from_qdict(request)
    if form.is_valid():
        if sc is None:
            sc = SieveClient(user=request.user.username,
                             password=request.session["password"])
        fset = sc.getscript(setname, format="fset")
        conditions, actions = form.tofilter()
        match_type = form.cleaned_data["match_type"]
        if match_type == "all":
            match_type = "anyof"
            conditions = [("true",)]
        fltname = form.cleaned_data["name"].encode("utf-8")
        try:
            if not update:
                fset.addfilter(fltname, conditions, actions,
                               match_type)
            else:
                oldname = request.POST["oldname"].encode("utf-8")
                fset.updatefilter(
                    oldname, fltname, conditions, actions, match_type
                )
        except (BadArgument, BadValue) as inst:
            raise BadRequest(str(inst))
        sc.pushscript(fset.name, str(fset))
        return render_to_json_response(okmsg)

    return render_to_json_response({'form_errors': form.errors}, status=400)
Ejemplo n.º 14
0
def new_filters_set(request, tplname="common/generic_modal_form.html"):
    if request.method == "POST":
        form = FiltersSetForm(request.POST)
        if form.is_valid():
            sc = SieveClient(user=request.user.username,
                             password=request.session["password"])
            sc.pushscript(form.cleaned_data["name"], "# Empty script",
                          form.cleaned_data["active"])
            return render_to_json_response({
                "url":
                form.cleaned_data["name"],
                "active":
                form.cleaned_data["active"],
                "respmsg":
                _("Filters set created")
            })
        return render_to_json_response({'form_errors': form.errors},
                                       status=400)

    ctx = {
        "title": _("Create a new filters set"),
        "formid": "newfiltersset",
        "action_label": _("Create"),
        "action_classes": "submit",
        "action": reverse(new_filters_set),
        "withmenu": False,
        "withunseen": False,
        "form": FiltersSetForm()
    }
    return render(request, tplname, ctx)
Ejemplo n.º 15
0
def newfolder(request, tplname="webmail/folder.html"):
    mbc = IMAPconnector(user=request.user.username,
                        password=request.session["password"])

    if request.method == "POST":
        form = FolderForm(request.POST)
        if form.is_valid():
            pf = request.POST.get("parent_folder", None)
            mbc.create_folder(form.cleaned_data["name"], pf)
            return render_to_json_response({
                'respmsg': _("Mailbox created"),
                'newmb': form.cleaned_data["name"],
                'parent': pf
            })

        return render_to_json_response({'form_errors': form.errors},
                                       status=400)

    ctx = {
        "title": _("Create a new mailbox"),
        "formid": "mboxform",
        "action": reverse(newfolder),
        "action_label": _("Create"),
        "action_classes": "submit",
        "withunseen": False,
        "selectonly": True,
        "mboxes": mbc.getmboxes(request.user),
        "hdelimiter": mbc.hdelimiter,
        "form": FolderForm(),
        "selected": None
    }
    return render(request, tplname, ctx)
Ejemplo n.º 16
0
def newfolder(request, tplname="webmail/folder.html"):
    mbc = IMAPconnector(user=request.user.username, password=request.session["password"])

    if request.method == "POST":
        form = FolderForm(request.POST)
        if form.is_valid():
            pf = request.POST.get("parent_folder", None)
            mbc.create_folder(form.cleaned_data["name"], pf)
            return render_to_json_response(
                {"respmsg": _("Mailbox created"), "newmb": form.cleaned_data["name"], "parent": pf}
            )

        return render_to_json_response({"form_errors": form.errors}, status=400)

    ctx = {
        "title": _("Create a new mailbox"),
        "formid": "mboxform",
        "action": reverse(newfolder),
        "action_label": _("Create"),
        "action_classes": "submit",
        "withunseen": False,
        "selectonly": True,
        "mboxes": mbc.getmboxes(request.user),
        "hdelimiter": mbc.hdelimiter,
        "form": FolderForm(),
        "selected": None,
    }
    return render(request, tplname, ctx)
Ejemplo n.º 17
0
def autoreply(request, tplname="postfix_autoreply/autoreply.html"):
    mb = Mailbox.objects.get(user=request.user.id)
    try:
        arm = ARmessage.objects.get(mbox=mb.id)
    except ARmessage.DoesNotExist:
        arm = None
    if request.method == "POST":
        if arm:
            form = ARmessageForm(request.POST, instance=arm)
        else:
            form = ARmessageForm(request.POST)
        if form.is_valid():
            arm = form.save(commit=False)
            arm.fromdate = form.cleaned_data["fromdate"]
            arm.untildate = form.cleaned_data["untildate"]
            arm.mbox = mb
            arm.save()
            return render_to_json_response(
                _("Auto reply message updated successfully."))

        return render_to_json_response({"form_errors": form.errors},
                                       status=400)

    form = ARmessageForm(instance=arm)
    return render_to_json_response({
        "content":
        _render_to_string(request, tplname, {"form": form}),
        "onload_cb":
        "autoreply_cb"
    })
Ejemplo n.º 18
0
def new_filters_set(request, tplname="common/generic_modal_form.html"):
    if request.method == "POST":
        form = FiltersSetForm(request.POST)
        if form.is_valid():
            sc = SieveClient(user=request.user.username, password=request.session["password"])
            sc.pushscript(form.cleaned_data["name"], "# Empty script", form.cleaned_data["active"])
            return render_to_json_response(
                {
                    "url": form.cleaned_data["name"],
                    "active": form.cleaned_data["active"],
                    "respmsg": _("Filters set created"),
                }
            )
        return render_to_json_response({"form_errors": form.errors}, status=400)

    ctx = {
        "title": _("Create a new filters set"),
        "formid": "newfiltersset",
        "action_label": _("Create"),
        "action_classes": "submit",
        "action": reverse(new_filters_set),
        "withmenu": False,
        "withunseen": False,
        "form": FiltersSetForm(),
    }
    return render(request, tplname, ctx)
Ejemplo n.º 19
0
def removefilter(request, setname, fname):
    sc = SieveClient(user=request.user.username, password=request.session["password"])
    fset = sc.getscript(setname, format="fset")
    if fset.removefilter(fname.encode("utf-8")):
        sc.pushscript(fset.name, str(fset))
        return render_to_json_response(_("Filter removed"))
    return render_to_json_response(_("Failed to remove filter"), status=500)
Ejemplo n.º 20
0
def removefilter(request, setname, fname):
    sc = SieveClient(user=request.user.username,
                     password=request.session["password"])
    fset = sc.getscript(setname, format="fset")
    if fset.removefilter(fname.encode("utf-8")):
        sc.pushscript(fset.name, str(fset))
        return render_to_json_response(_("Filter removed"))
    return render_to_json_response(_("Failed to remove filter"), status=500)
Ejemplo n.º 21
0
def scan_for_services(request):
    try:
        Service.objects.load_from_master_cf()
    except IOError as e:
        return render_to_json_response([str(e)], status=500)

    return render_to_json_response(
        dict((srv.name, srv.id) for srv in Service.objects.all()))
Ejemplo n.º 22
0
def get_templates(request, ftype):
    if ftype == "condition":
        return render_to_json_response(
            FilterForm([], [], request).cond_templates
        )
    return render_to_json_response(
        FilterForm([], [], request).action_templates
    )
Ejemplo n.º 23
0
def release(request, mail_id):
    """Release message selection.

    :param str mail_id: message unique identifier
    """
    mail_id = check_mail_id(request, mail_id)
    msgrcpts = []
    connector = get_connector()
    valid_addresses = get_user_valid_addresses(request.user)
    for mid in mail_id:
        r, i = mid.split()
        if valid_addresses is not None and r not in valid_addresses:
            continue
        msgrcpts += [connector.get_recipient_message(r, i)]
    if request.user.group == "SimpleUsers" and \
       parameters.get_admin("USER_CAN_RELEASE") == "no":
        for msgrcpt in msgrcpts:
            connector.set_msgrcpt_status(msgrcpt.rid.email,
                                         msgrcpt.mail.mail_id, 'p')
        message = ungettext("%(count)d request sent",
                            "%(count)d requests sent", len(mail_id)) % {
                                "count": len(mail_id)
                            }
        return render_to_json_response({
            "message":
            message,
            "url":
            QuarantineNavigationParameters(request).back_to_listing()
        })

    amr = AMrelease()
    error = None
    for rcpt in msgrcpts:
        result = amr.sendreq(rcpt.mail.mail_id, rcpt.mail.secret_id,
                             rcpt.rid.email)
        if result:
            connector.set_msgrcpt_status(rcpt.rid.email, rcpt.mail.mail_id,
                                         'R')
        else:
            error = result
            break

    if not error:
        message = ungettext("%(count)d message released successfully",
                            "%(count)d messages released successfully",
                            len(mail_id)) % {
                                "count": len(mail_id)
                            }
    else:
        message = error
    status = 400 if error else 200
    return render_to_json_response(
        {
            "message": message,
            "url": QuarantineNavigationParameters(request).back_to_listing()
        },
        status=status)
Ejemplo n.º 24
0
def scan_for_services(request):
    try:
        Service.objects.load_from_master_cf()
    except IOError as e:
        return render_to_json_response([str(e)], status=500)

    return render_to_json_response(
        dict((srv.name, srv.id) for srv in Service.objects.all())
    )
Ejemplo n.º 25
0
def editfolder(request, tplname="webmail/folder.html"):
    mbc = IMAPconnector(user=request.user.username,
                        password=request.session["password"])
    ctx = {
        "title": _("Edit mailbox"),
        "formid": "mboxform",
        "action": reverse(editfolder),
        "action_label": _("Update"),
        "action_classes": "submit",
        "withunseen": False,
        "selectonly": True,
        "hdelimiter": mbc.hdelimiter
    }

    if request.method == "POST":
        form = FolderForm(request.POST)
        if form.is_valid():
            pf = request.POST.get("parent_folder", None)
            oldname, oldparent = separate_mailbox(request.POST["oldname"],
                                                  sep=mbc.hdelimiter)
            res = {'respmsg': _("Mailbox updated")}
            if form.cleaned_data["name"] != oldname \
                    or (pf != oldparent):
                newname = form.cleaned_data["name"] if pf is None \
                    else mbc.hdelimiter.join([pf, form.cleaned_data["name"]])
                mbc.rename_folder(request.POST["oldname"], newname)
                res["oldmb"] = oldname
                res["newmb"] = form.cleaned_data["name"]
                res["oldparent"] = oldparent
                res["newparent"] = pf
                WebmailNavigationParameters(request).remove('mbox')
            return render_to_json_response(res)

        return render_to_json_response({'form_errors': form.errors},
                                       status=400)

    name = request.GET.get("name", None)
    if name is None:
        raise BadRequest(_("Invalid request"))
    shortname, parent = separate_mailbox(name, sep=mbc.hdelimiter)
    ctx = {
        "title": _("Edit mailbox"),
        "formid": "mboxform",
        "action": reverse(editfolder),
        "action_label": _("Update"),
        "action_classes": "submit",
        "withunseen": False,
        "selectonly": True,
        "hdelimiter": mbc.hdelimiter,
        "mboxes": mbc.getmboxes(request.user, until_mailbox=parent),
        "form": FolderForm(),
        "selected": parent
    }
    ctx["form"].fields["oldname"].initial = name
    ctx["form"].fields["name"].initial = shortname
    return render(request, tplname, ctx)
Ejemplo n.º 26
0
def saveparameters(request):
    for formdef in parameters.get_admin_forms(request.POST):
        form = formdef["form"]
        if form.is_valid():
            form.save()
            form.to_django_settings()
            continue
        return render_to_json_response(
            {'form_errors': form.errors, 'prefix': form.app}, status=400
        )
    return render_to_json_response(_("Parameters saved"))
Ejemplo n.º 27
0
def newaccount(request, tplname='common/wizard_forms.html'):
    """Create a new account.

    .. note:: An issue still remains int this code: if all validation
       steps are successful but an error occurs after we call 'save',
       the account will be created. It happens transaction management
       doesn't work very well with nested functions. Need to wait for
       django 1.6 and atomicity.
    """
    cwizard = CreationWizard()
    cwizard.add_step(AccountFormGeneral,
                     _("General"),
                     [dict(classes="btn-inverse next", label=_("Next"))],
                     new_args=[request.user])
    cwizard.add_step(AccountFormMail,
                     _("Mail"), [
                         dict(classes="btn-primary submit", label=_("Create")),
                         dict(classes="btn-inverse prev", label=_("Previous"))
                     ],
                     formtpl="admin/mailform.html")

    if request.method == "POST":
        retcode, data = cwizard.validate_step(request)
        if retcode == -1:
            raise BadRequest(data)
        if retcode == 1:
            return render_to_json_response({
                'title': cwizard.get_title(data + 1),
                'stepid': data
            })
        if retcode == 2:
            genform = cwizard.steps[0]["form"]
            account = genform.save()
            account.post_create(request.user)
            mailform = cwizard.steps[1]["form"]
            mailform.save(request.user, account)
            return render_to_json_response(_("Account created"))
        return render_to_json_response(
            {
                'stepid': data,
                'form_errors': cwizard.errors
            }, status=400)

    ctx = {
        'title': _("New account"),
        'action': reverse(newaccount),
        'formid': 'newaccount_form',
        'submit_label': _("Create")
    }
    cwizard.create_forms()
    ctx.update(steps=cwizard.steps)
    ctx.update(subtitle="1. %s" % cwizard.steps[0]['title'])
    return render(request, tplname, ctx)
Ejemplo n.º 28
0
def editfolder(request, tplname="webmail/folder.html"):
    mbc = IMAPconnector(user=request.user.username, password=request.session["password"])
    ctx = {
        "title": _("Edit mailbox"),
        "formid": "mboxform",
        "action": reverse(editfolder),
        "action_label": _("Update"),
        "action_classes": "submit",
        "withunseen": False,
        "selectonly": True,
        "hdelimiter": mbc.hdelimiter,
    }

    if request.method == "POST":
        form = FolderForm(request.POST)
        if form.is_valid():
            pf = request.POST.get("parent_folder", None)
            oldname, oldparent = separate_mailbox(request.POST["oldname"], sep=mbc.hdelimiter)
            res = {"respmsg": _("Mailbox updated")}
            if form.cleaned_data["name"] != oldname or (pf != oldparent):
                newname = (
                    form.cleaned_data["name"] if pf is None else mbc.hdelimiter.join([pf, form.cleaned_data["name"]])
                )
                mbc.rename_folder(request.POST["oldname"], newname)
                res["oldmb"] = oldname
                res["newmb"] = form.cleaned_data["name"]
                res["oldparent"] = oldparent
                res["newparent"] = pf
                WebmailNavigationParameters(request).remove("mbox")
            return render_to_json_response(res)

        return render_to_json_response({"form_errors": form.errors}, status=400)

    name = request.GET.get("name", None)
    if name is None:
        raise BadRequest(_("Invalid request"))
    shortname, parent = separate_mailbox(name, sep=mbc.hdelimiter)
    ctx = {
        "title": _("Edit mailbox"),
        "formid": "mboxform",
        "action": reverse(editfolder),
        "action_label": _("Update"),
        "action_classes": "submit",
        "withunseen": False,
        "selectonly": True,
        "hdelimiter": mbc.hdelimiter,
        "mboxes": mbc.getmboxes(request.user, until_mailbox=parent),
        "form": FolderForm(),
        "selected": parent,
    }
    ctx["form"].fields["oldname"].initial = name
    ctx["form"].fields["name"].initial = shortname
    return render(request, tplname, ctx)
Ejemplo n.º 29
0
def saveparameters(request):
    for formdef in parameters.get_admin_forms(request.POST):
        form = formdef["form"]
        if form.is_valid():
            form.save()
            form.to_django_settings()
            continue
        return render_to_json_response(
            {
                'form_errors': form.errors,
                'prefix': form.app
            }, status=400)
    return render_to_json_response(_("Parameters saved"))
Ejemplo n.º 30
0
def graphs(request):
    gset = request.GET.get("gset", None)
    gsets = events.raiseDictEvent("GetGraphSets")
    if not gset in gsets:
        raise NotFound(_("Unknown graphic set"))
    searchq = request.GET.get("searchquery", None)
    period = request.GET.get("period", "day")
    tplvars = dict(graphs=[], period=period)
    if searchq in [None, "global"]:
        if not request.user.is_superuser:
            if not Domain.objects.get_for_admin(request.user).count():
                return render_to_json_response({})
            tplvars.update(
                domain=Domain.objects.get_for_admin(request.user)[0].name
            )
        else:
            tplvars.update(domain="global")
    else:
        domain = Domain.objects.filter(name__contains=searchq)
        if domain.count() != 1:
            return render_to_json_response({})
        if not request.user.can_access(domain[0]):
            raise PermDeniedException
        tplvars.update(domain=domain[0].name)

    if period == "custom":
        if not "start" in request.GET or not "end" in request.GET:
            raise BadRequest(_("Bad custom period"))
        start = request.GET["start"]
        end = request.GET["end"]
        G = Grapher()
        expr = re.compile(r'[:\- ]')
        period_name = "%s_%s" % (expr.sub('', start), expr.sub('', end))
        for tpl in gsets[gset].get_graphs():
            tplvars['graphs'].append(tpl.display_name)
            G.process(
                tplvars["domain"], period_name, str2Time(*expr.split(start)),
                str2Time(*expr.split(end)), tpl
            )
        tplvars["period_name"] = period_name
        tplvars["start"] = start
        tplvars["end"] = end
    else:
        tplvars['graphs'] = gsets[gset].get_graph_names()

    return render_to_json_response({
        'content': _render_to_string(request, "stats/graphs.html", tplvars)
    })
Ejemplo n.º 31
0
def _domains(request):
    sort_order, sort_dir = get_sort_order(request.GET, "name")
    filters = dict(
        (flt, request.GET.get(flt, None))
        for flt in ['domfilter', 'searchquery']
        + events.raiseQueryEvent('ExtraDomainFilters')
    )
    request.session['domains_filters'] = filters
    domainlist = get_domains(
        request.user, **filters
    )
    if sort_order == 'name':
        domainlist = sorted(
            domainlist,
            key=lambda d: getattr(d, sort_order), reverse=sort_dir == '-'
        )
    else:
        domainlist = sorted(domainlist, key=lambda d: d.tags[0],
                            reverse=sort_dir == '-')
    page = get_listing_page(domainlist, request.GET.get("page", 1))
    return render_to_json_response({
        "table": _render_to_string(request, 'admin/domains_table.html', {
            'domains': page.object_list,
            'tableid': 'domains'
        }),
        "page": page.number,
        "paginbar": pagination_bar(page),
        "handle_mailboxes": parameters.get_admin("HANDLE_MAILBOXES",
                                                 raise_error=False),
        "auto_account_removal": parameters.get_admin("AUTO_ACCOUNT_REMOVAL")
    })
Ejemplo n.º 32
0
def _listing(request):
    if not request.user.is_superuser and request.user.group != 'SimpleUsers':
        if not Domain.objects.get_for_admin(request.user).count():
            return empty_quarantine(request)

    navparams = QuarantineNavigationParameters(request)
    navparams.store()

    lst = SQLlisting(
        request.user,
        navparams=navparams,
        elems_per_page=int(
            parameters.get_user(request.user, "MESSAGES_PER_PAGE")
        )
    )
    page = lst.paginator.getpage(navparams.get('page'))
    if not page:
        return empty_quarantine(request)

    content = lst.fetch(request, page.id_start, page.id_stop)
    ctx = getctx(
        "ok", listing=content, paginbar=pagination_bar(page), page=page.number
    )
    if request.session.get('location', 'listing') != 'listing':
        ctx['menu'] = quar_menu()
    request.session['location'] = 'listing'
    return render_to_json_response(ctx)
Ejemplo n.º 33
0
def submailboxes(request):
    """Retrieve the sub mailboxes of a mailbox."""
    topmailbox = request.GET.get('topmailbox', '')
    with_unseen = request.GET.get('unseen', None)
    mboxes = get_imapconnector(request).getmboxes(
        request.user, topmailbox, unseen_messages=with_unseen == 'true')
    return render_to_json_response(mboxes)
Ejemplo n.º 34
0
def _identities(request):
    filters = dict((fname, request.GET.get(fname, None))
                   for fname in ['searchquery', 'idtfilter', 'grpfilter'])
    request.session['identities_filters'] = filters
    idents_list = get_identities(request.user, **filters)
    sort_order, sort_dir = get_sort_order(request.GET, "identity",
                                          ["identity", "name_or_rcpt", "tags"])
    if sort_order in ["identity", "name_or_rcpt"]:
        objects = sorted(idents_list,
                         key=lambda o: getattr(o, sort_order),
                         reverse=sort_dir == '-')
    else:
        objects = sorted(idents_list,
                         key=lambda o: o.tags[0],
                         reverse=sort_dir == '-')
    context = {
        "handle_mailboxes":
        parameters.get_admin("HANDLE_MAILBOXES", raise_error=False)
    }
    page = get_listing_page(objects, request.GET.get("page", 1))
    if page is None:
        context["length"] = 0
    else:
        context["headers"] = _render_to_string(request,
                                               "admin/identity_headers.html",
                                               {})
        context["rows"] = _render_to_string(request,
                                            "admin/identities_table.html",
                                            {"identities": page.object_list})
        context["pages"] = [page.number]
    return render_to_json_response(context)
Ejemplo n.º 35
0
def remove_filters_set(request, name):
    sc = SieveClient(user=request.user.username,
                     password=request.session["password"])
    sc.deletescript(name)
    acs, scripts = sc.listscripts()
    return render_to_json_response(
        dict(respmsg=_("Filters set deleted"), newfs=acs))
Ejemplo n.º 36
0
def list_quotas(request):
    from modoboa.lib.dbutils import db_type

    sort_order, sort_dir = get_sort_order(request.GET, "address")
    mboxes = Mailbox.objects.get_for_admin(
        request.user, request.GET.get("searchquery", None))
    mboxes = mboxes.exclude(quota=0)
    if sort_order in ["address", "quota", "quota_value__bytes"]:
        mboxes = mboxes.order_by("%s%s" % (sort_dir, sort_order))
    elif sort_order == "quota_usage":
        where = "admin_mailbox.address||'@'||admin_domain.name"
        db_type = db_type()
        if db_type == "postgres":
            select = '(admin_quota.bytes::float / (CAST(admin_mailbox.quota AS BIGINT) * 1048576)) * 100'
        else:
            select = 'admin_quota.bytes / (admin_mailbox.quota * 1048576) * 100'
            if db_type == "mysql":
                where = "CONCAT(admin_mailbox.address,'@',admin_domain.name)"
        mboxes = mboxes.extra(select={'quota_usage': select},
                              where=["admin_quota.username=%s" % where],
                              tables=["admin_quota", "admin_domain"],
                              order_by=["%s%s" % (sort_dir, sort_order)])
    else:
        raise BadRequest(_("Invalid request"))
    page = get_listing_page(mboxes, request.GET.get("page", 1))
    context = {}
    if page is None:
        context["length"] = 0
    else:
        context["headers"] = _render_to_string(request,
                                               "admin/quota_headers.html", {})
        context["rows"] = _render_to_string(request, "admin/quotas.html",
                                            {"mboxes": page})
        context["pages"] = [page.number]
    return render_to_json_response(context)
Ejemplo n.º 37
0
def viewparameters(request, tplname='core/parameters.html'):
    return render_to_json_response({
        "left_selection": "parameters",
        "content": _render_to_string(request, tplname, {
            "forms": parameters.get_admin_forms
        })
    })
Ejemplo n.º 38
0
def check_top_notifications(request):
    """
    AJAX service to check for new top notifications to display.
    """
    return render_to_json_response(
        events.raiseQueryEvent("TopNotifications", request, True)
    )
Ejemplo n.º 39
0
def list_quotas(request, tplname="admin/quotas.html"):
    from modoboa.lib.dbutils import db_type

    sort_order, sort_dir = get_sort_order(request.GET, "address")
    mboxes = Mailbox.objects.get_for_admin(
        request.user, request.GET.get("searchquery", None)
    )
    mboxes = mboxes.exclude(quota=0)
    if sort_order in ["address", "quota", "quota_value__bytes"]:
        mboxes = mboxes.order_by("%s%s" % (sort_dir, sort_order))
    elif sort_order == "quota_usage":
        if db_type() == "postgres":
            select = '(admin_quota.bytes::float / (CAST(admin_mailbox.quota AS BIGINT) * 1048576)) * 100'
        else:
            select = 'admin_quota.bytes / (admin_mailbox.quota * 1048576) * 100'
        mboxes = mboxes.extra(
            select={'quota_usage': select},
            where=["admin_quota.mbox_id=admin_mailbox.id"],
            tables=["admin_quota"],
            order_by=["%s%s" % (sort_dir, sort_order)]
        )
    else:
        raise BadRequest(_("Invalid request"))
    page = get_listing_page(mboxes, request.GET.get("page", 1))
    return render_to_json_response({
        "page": page.number,
        "paginbar": pagination_bar(page),
        "table": _render_to_string(request, tplname, {
            "mboxes": page
        })
    })
Ejemplo n.º 40
0
def submailboxes(request):
    """Retrieve the sub mailboxes of a mailbox."""
    topmailbox = request.GET.get('topmailbox', '')
    with_unseen = request.GET.get('unseen', None)
    mboxes = get_imapconnector(request).getmboxes(
        request.user, topmailbox, unseen_messages=with_unseen == 'true')
    return render_to_json_response(mboxes)
Ejemplo n.º 41
0
def _identities(request):
    filters = dict((fname, request.GET.get(fname, None))
                   for fname in ['searchquery', 'idtfilter', 'grpfilter'])
    request.session['identities_filters'] = filters
    idents_list = get_identities(request.user, **filters)
    sort_order, sort_dir = get_sort_order(request.GET, "identity",
                                          ["identity", "name_or_rcpt", "tags"])
    if sort_order in ["identity", "name_or_rcpt"]:
        objects = sorted(idents_list,
                         key=lambda o: getattr(o, sort_order),
                         reverse=sort_dir == '-')
    else:
        objects = sorted(idents_list,
                         key=lambda o: o.tags[0],
                         reverse=sort_dir == '-')
    page = get_listing_page(objects, request.GET.get("page", 1))
    return render_to_json_response({
        "table":
        _render_to_string(request, "admin/identities_table.html", {
            "identities": page.object_list,
            "tableid": "objects_table"
        }),
        "handle_mailboxes":
        parameters.get_admin("HANDLE_MAILBOXES", raise_error=False),
        "page":
        page.number,
        "paginbar":
        pagination_bar(page)
    })
Ejemplo n.º 42
0
def _domains(request):
    sort_order, sort_dir = get_sort_order(request.GET, "name")
    filters = dict(
        (flt, request.GET.get(flt, None))
        for flt in ['domfilter', 'searchquery']
        + events.raiseQueryEvent('ExtraDomainFilters')
    )
    request.session['domains_filters'] = filters
    domainlist = get_domains(request.user, **filters)
    if sort_order == 'name':
        domainlist = sorted(
            domainlist,
            key=lambda d: getattr(d, sort_order), reverse=sort_dir == '-'
        )
    else:
        domainlist = sorted(domainlist, key=lambda d: d.tags[0],
                            reverse=sort_dir == '-')
    context = {
        "handle_mailboxes": parameters.get_admin(
            "HANDLE_MAILBOXES", raise_error=False),
        "auto_account_removal": parameters.get_admin("AUTO_ACCOUNT_REMOVAL")
    }
    page = get_listing_page(domainlist, request.GET.get("page", 1))
    if page is None:
        context["length"] = 0
    else:
        context["rows"] = _render_to_string(
            request, 'admin/domains_table.html', {
                'domains': page.object_list,
            }
        )
        context["pages"] = [page.number]
    return render_to_json_response(context)
Ejemplo n.º 43
0
def list_quotas(request, tplname="admin/quotas.html"):
    from modoboa.lib.dbutils import db_type

    sort_order, sort_dir = get_sort_order(request.GET, "address")
    mboxes = Mailbox.objects.get_for_admin(
        request.user, request.GET.get("searchquery", None))
    mboxes = mboxes.exclude(quota=0)
    if sort_order in ["address", "quota", "quota_value__bytes"]:
        mboxes = mboxes.order_by("%s%s" % (sort_dir, sort_order))
    elif sort_order == "quota_usage":
        if db_type() == "postgres":
            select = '(admin_quota.bytes::float / (CAST(admin_mailbox.quota AS BIGINT) * 1048576)) * 100'
        else:
            select = 'admin_quota.bytes / (admin_mailbox.quota * 1048576) * 100'
        mboxes = mboxes.extra(select={'quota_usage': select},
                              where=["admin_quota.mbox_id=admin_mailbox.id"],
                              tables=["admin_quota"],
                              order_by=["%s%s" % (sort_dir, sort_order)])
    else:
        raise BadRequest(_("Invalid request"))
    page = get_listing_page(mboxes, request.GET.get("page", 1))
    return render_to_json_response({
        "page":
        page.number,
        "paginbar":
        pagination_bar(page),
        "table":
        _render_to_string(request, tplname, {"mboxes": page})
    })
Ejemplo n.º 44
0
def learning_recipient(request):
    """A view to select the recipient database of a learning action."""
    if request.method == "POST":
        form = LearningRecipientForm(request.user, request.POST)
        if form.is_valid():
            return mark_messages(request,
                                 form.cleaned_data["selection"].split(","),
                                 form.cleaned_data["ltype"],
                                 form.cleaned_data["recipient"])
        return render_to_json_response({"form_errors": form.errors},
                                       status=400)
    ltype = request.GET.get("type", None)
    selection = request.GET.get("selection", None)
    if ltype is None or selection is None:
        raise BadRequest
    form = LearningRecipientForm(request.user)
    form.fields["ltype"].initial = ltype
    form.fields["selection"].initial = selection
    return render(
        request, "common/generic_modal_form.html", {
            "title": _("Select a database"),
            "formid": "learning_recipient_form",
            "action": reverse("amavis:learning_recipient_set"),
            "action_classes": "submit",
            "action_label": _("Validate"),
            "form": form
        })
Ejemplo n.º 45
0
def _validate_alias(request, form, successmsg, callback=None):
    """Alias validation

    Common function shared between creation and modification actions.
    """
    if form.is_valid():
        form.set_recipients()
        try:
            alias = form.save()
        except IntegrityError:
            raise Conflict(_("Alias with this name already exists"))
        if callback:
            callback(request.user, alias)
        return render_to_json_response(successmsg)

    return render_to_json_response({'form_errors': form.errors}, status=400)
Ejemplo n.º 46
0
def newaccount(request, tplname='common/wizard_forms.html'):
    """Create a new account.

    .. note:: An issue still remains int this code: if all validation
       steps are successful but an error occurs after we call 'save',
       the account will be created. It happens transaction management
       doesn't work very well with nested functions. Need to wait for
       django 1.6 and atomicity.
    """
    cwizard = CreationWizard()
    cwizard.add_step(AccountFormGeneral, _("General"),
                     [dict(classes="btn-inverse next", label=_("Next"))],
                     new_args=[request.user])
    cwizard.add_step(AccountFormMail, _("Mail"),
                     [dict(classes="btn-primary submit", label=_("Create")),
                      dict(classes="btn-inverse prev", label=_("Previous"))],
                     formtpl="admin/mailform.html")

    if request.method == "POST":
        retcode, data = cwizard.validate_step(request)
        if retcode == -1:
            raise BadRequest(data)
        if retcode == 1:
            return render_to_json_response(
                {'title': cwizard.get_title(data + 1), 'stepid': data}
            )
        if retcode == 2:
            genform = cwizard.steps[0]["form"]
            account = genform.save()
            account.post_create(request.user)
            mailform = cwizard.steps[1]["form"]
            mailform.save(request.user, account)
            return render_to_json_response(_("Account created"))
        return render_to_json_response({
            'stepid': data, 'form_errors': cwizard.errors
        }, status=400)

    ctx = {
        'title': _("New account"),
        'action': reverse(newaccount),
        'formid': 'newaccount_form',
        'submit_label': _("Create")
    }
    cwizard.create_forms()
    ctx.update(steps=cwizard.steps)
    ctx.update(subtitle="1. %s" % cwizard.steps[0]['title'])
    return render(request, tplname, ctx)
Ejemplo n.º 47
0
    def done(self):
        from modoboa.lib.webutils import render_to_json_response

        account = self.first_step.form.save()
        account.post_create(self.request.user)
        mailform = self.steps[1].form
        mailform.save(self.request.user, account)
        return render_to_json_response(_("Account created"))
Ejemplo n.º 48
0
    def done(self):
        from modoboa.lib.webutils import render_to_json_response

        account = self.first_step.form.save()
        account.post_create(self.request.user)
        mailform = self.steps[1].form
        mailform.save(self.request.user, account)
        return render_to_json_response(_("Account created"))
Ejemplo n.º 49
0
def folder_compress(request):
    """Compress a mailbox."""
    name = request.GET.get("name", None)
    if name is None:
        raise BadRequest(_("Invalid request"))
    imapc = get_imapconnector(request)
    imapc.compact(name)
    return render_to_json_response({})
Ejemplo n.º 50
0
def newdomain(request, tplname="common/wizard_forms.html"):
    events.raiseEvent("CanCreate", request.user, "domains")

    cwizard = CreationWizard()
    cwizard.add_step(DomainFormGeneral, _("General"),
                     [dict(classes="btn-inverse next", label=_("Next"))],
                     formtpl="admin/domain_general_form.html")
    cwizard.add_step(
        DomainFormOptions, _("Options"),
        [dict(classes="btn-primary submit", label=_("Create")),
         dict(classes="btn-inverse prev", label=_("Previous"))],
        formtpl="admin/domain_options_form.html",
        new_args=[request.user]
    )

    if request.method == "POST":
        retcode, data = cwizard.validate_step(request)
        if retcode == -1:
            raise BadRequest(data)
        if retcode == 1:
            return render_to_json_response(
                {'title': cwizard.get_title(data + 1), 'stepid': data}
            )
        if retcode == 2:
            genform = cwizard.steps[0]["form"]
            domain = genform.save(request.user)
            domain.post_create(request.user)
            try:
                cwizard.steps[1]["form"].save(request.user, domain)
            except ModoboaException as e:
                transaction.rollback()
                raise
            return render_to_json_response(_("Domain created"))
        return render_to_json_response({
            'stepid': data, 'form_errors': cwizard.errors
        }, status=400)

    ctx = {"title": _("New domain"),
           "action_label": _("Create"),
           "action_classes": "submit",
           "action": reverse(newdomain),
           "formid": "domform"}
    cwizard.create_forms()
    ctx.update(steps=cwizard.steps)
    ctx.update(subtitle="1. %s" % cwizard.steps[0]['title'])
    return render(request, tplname, ctx)
Ejemplo n.º 51
0
 def done(self):
     calendar = self.first_step.form.save(commit=False)
     if self.request.user.group == 'SimpleUsers':
         calendar.mailbox = self.request.user.mailbox_set.all()[0]
     calendar.save()
     self.steps[1].form.calendar = calendar
     self.steps[1].form.save()
     return render_to_json_response(_("Calendar created"))
Ejemplo n.º 52
0
def remove_filters_set(request, name):
    sc = SieveClient(user=request.user.username,
                     password=request.session["password"])
    sc.deletescript(name)
    acs, scripts = sc.listscripts()
    return render_to_json_response(dict(
        respmsg=_("Filters set deleted"), newfs=acs
    ))
Ejemplo n.º 53
0
 def done(self):
     calendar = self.first_step.form.save(commit=False)
     if self.request.user.group == 'SimpleUsers':
         calendar.mailbox = self.request.user.mailbox_set.all()[0]
     calendar.save()
     self.steps[1].form.calendar = calendar
     self.steps[1].form.save()
     return render_to_json_response(_("Calendar created"))
Ejemplo n.º 54
0
def empty(request, name):
    if name != parameters.get_user(request.user, "TRASH_FOLDER"):
        raise BadRequest(_("Invalid request"))
    get_imapconnector(request).empty(name)
    content = "<div class='alert alert-info'>%s</div>" % _("Empty mailbox")
    return render_to_json_response({
        'listing': content, 'mailbox': name
    })
Ejemplo n.º 55
0
def viewparameters(request, tplname='core/parameters.html'):
    return render_to_json_response({
        "left_selection":
        "parameters",
        "content":
        _render_to_string(request, tplname,
                          {"forms": parameters.get_admin_forms})
    })
Ejemplo n.º 56
0
def newdomain(request, tplname="common/wizard_forms.html"):
    events.raiseEvent("CanCreate", request.user, "domains")

    cwizard = CreationWizard()
    cwizard.add_step(DomainFormGeneral, _("General"),
                     [dict(classes="btn-inverse next", label=_("Next"))],
                     formtpl="admin/domain_general_form.html")
    cwizard.add_step(
        DomainFormOptions, _("Options"),
        [dict(classes="btn-primary submit", label=_("Create")),
         dict(classes="btn-inverse prev", label=_("Previous"))],
        formtpl="admin/domain_options_form.html",
        new_args=[request.user]
    )

    if request.method == "POST":
        retcode, data = cwizard.validate_step(request)
        if retcode == -1:
            raise BadRequest(data)
        if retcode == 1:
            return render_to_json_response(
                {'title': cwizard.get_title(data + 1), 'stepid': data}
            )
        if retcode == 2:
            genform = cwizard.steps[0]["form"]
            domain = genform.save(request.user)
            domain.post_create(request.user)
            try:
                cwizard.steps[1]["form"].save(request.user, domain)
            except ModoboaException as e:
                transaction.rollback()
                raise
            return render_to_json_response(_("Domain created"))
        return render_to_json_response({
            'stepid': data, 'form_errors': cwizard.errors
        }, status=400)

    ctx = {"title": _("New domain"),
           "action_label": _("Create"),
           "action_classes": "submit",
           "action": reverse(newdomain),
           "formid": "domform"}
    cwizard.create_forms()
    ctx.update(steps=cwizard.steps)
    ctx.update(subtitle="1. %s" % cwizard.steps[0]['title'])
    return render(request, tplname, ctx)
Ejemplo n.º 57
0
def folder_compress(request):
    """Compress a mailbox."""
    name = request.GET.get("name", None)
    if name is None:
        raise BadRequest(_("Invalid request"))
    imapc = get_imapconnector(request)
    imapc.compact(name)
    return render_to_json_response({})
Ejemplo n.º 58
0
def graphs(request):
    gset = request.GET.get("gset", None)
    gsets = events.raiseDictEvent("GetGraphSets")
    if not gset in gsets:
        raise NotFound(_("Unknown graphic set"))
    searchq = request.GET.get("searchquery", None)
    period = request.GET.get("period", "day")
    tplvars = dict(graphs=[], period=period)
    if searchq in [None, "global"]:
        if not request.user.is_superuser:
            if not Domain.objects.get_for_admin(request.user).count():
                return render_to_json_response({})
            tplvars.update(
                domain=Domain.objects.get_for_admin(request.user)[0].name)
        else:
            tplvars.update(domain="global")
    else:
        domain = Domain.objects.filter(name__contains=searchq)
        if domain.count() != 1:
            return render_to_json_response({})
        if not request.user.can_access(domain[0]):
            raise PermDeniedException
        tplvars.update(domain=domain[0].name)

    if period == "custom":
        if not "start" in request.GET or not "end" in request.GET:
            raise BadRequest(_("Bad custom period"))
        start = request.GET["start"]
        end = request.GET["end"]
        G = Grapher()
        expr = re.compile(r'[:\- ]')
        period_name = "%s_%s" % (expr.sub('', start), expr.sub('', end))
        for tpl in gsets[gset].get_graphs():
            tplvars['graphs'].append(tpl.display_name)
            G.process(tplvars["domain"], period_name,
                      str2Time(*expr.split(start)), str2Time(*expr.split(end)),
                      tpl)
        tplvars["period_name"] = period_name
        tplvars["start"] = start
        tplvars["end"] = end
    else:
        tplvars['graphs'] = gsets[gset].get_graph_names()

    return render_to_json_response(
        {'content': _render_to_string(request, "stats/graphs.html", tplvars)})
Ejemplo n.º 59
0
def move(request):
    for arg in ["msgset", "to"]:
        if not arg in request.GET:
            raise BadRequest(_("Invalid request"))
    mbc = get_imapconnector(request)
    navparams = WebmailNavigationParameters(request)
    mbc.move(request.GET["msgset"], navparams.get("mbox"), request.GET["to"])
    resp = listmailbox(request, navparams.get("mbox"), update_session=False)
    return render_to_json_response(resp)