Beispiel #1
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"
    })
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)
Beispiel #3
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("webmail:folder_add"),
           "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)
def autoreply(request, tplname="modoboa_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(mb, request.POST, instance=arm)
        else:
            form = ARmessageForm(mb, request.POST)
        if form.is_valid():
            form.save()
            return render_to_json_response(
                _("Auto reply message updated successfully.")
            )

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

    form = ARmessageForm(mb, instance=arm)
    return render_to_json_response({
        "content": render_to_string(tplname, {"form": form}, request),
        "onload_cb": "autoreply_cb"
    })
Beispiel #5
0
def profile(request, tplname="core/user_profile.html"):
    """Profile detail/update view."""
    update_password = True
    results = signals.allow_password_change.send(
        sender="profile", user=request.user)
    if True in [result[1] for result in results]:
        update_password = False

    if request.method == "POST":
        form = ProfileForm(
            update_password, request.POST, instance=request.user
        )
        if form.is_valid():
            form.save()
            if update_password and form.cleaned_data["confirmation"] != "":
                request.session["password"] = force_text(encrypt(
                    form.cleaned_data["confirmation"]
                ))
            translation.activate(request.user.language)
            request.session[translation.LANGUAGE_SESSION_KEY] = (
                request.user.language)
            return render_to_json_response(_("Profile updated"))
        return render_to_json_response(
            {"form_errors": form.errors}, status=400)

    form = ProfileForm(update_password, instance=request.user)
    return render_to_json_response({
        "content": render_to_string(tplname, {
            "form": form
        }, request)
    })
Beispiel #6
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")
    })
Beispiel #7
0
def graphs(request):
    gset = request.GET.get("gset", None)
    gsets = events.raiseDictEvent("GetGraphSets")
    if gset not 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 "start" not in request.GET or "end" not 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)
Beispiel #8
0
def mark_messages(request, selection, mtype, recipient_db=None):
    """Mark a selection of messages as spam.

    :param str selection: message unique identifier
    :param str mtype: type of marking (spam or ham)
    """
    if not manual_learning_enabled(request.user):
        return render_to_json_response({"status": "ok"})
    if recipient_db is None:
        recipient_db = (
            "user" if request.user.group == "SimpleUsers" else "global"
        )
    selection = check_mail_id(request, selection)
    connector = get_connector()
    saclient = SpamassassinClient(request.user, recipient_db)
    for item in selection:
        rcpt, mail_id = item.split()
        content = connector.get_mail_content(mail_id)
        result = saclient.learn_spam(rcpt, content) if mtype == "spam" \
            else saclient.learn_ham(rcpt, content)
        if not result:
            break
        connector.set_msgrcpt_status(rcpt, mail_id, mtype[0].upper())
    if saclient.error is None:
        saclient.done()
        message = ungettext("%(count)d message processed successfully",
                            "%(count)d messages processed successfully",
                            len(selection)) % {"count": len(selection)}
    else:
        message = saclient.error
    status = 400 if saclient.error else 200
    return render_to_json_response({
        "message": message, "reload": True
    }, status=status)
Beispiel #9
0
def profile(request, tplname='core/user_profile.html'):
    """Profile detail/update view."""
    update_password = True
    if True in events.raiseQueryEvent("PasswordChange", request.user):
        update_password = False

    if request.method == "POST":
        form = ProfileForm(
            update_password, request.POST, instance=request.user
        )
        if form.is_valid():
            form.save()
            if update_password and form.cleaned_data["confirmation"] != "":
                request.session["password"] = encrypt(
                    form.cleaned_data["confirmation"])
            translation.activate(request.user.language)
            request.session[translation.LANGUAGE_SESSION_KEY] = (
                request.user.language)
            return render_to_json_response(_("Profile updated"))
        return render_to_json_response(
            {'form_errors': form.errors}, status=400)

    form = ProfileForm(update_password, instance=request.user)
    return render_to_json_response({
        "content": _render_to_string(request, tplname, {
            "form": form
        })
    })
Beispiel #10
0
def forward(request, tplname="admin/forward.html"):
    mb = request.user.mailbox
    al = Alias.objects.filter(address=mb.full_address, internal=False).first()
    if request.method == "POST":
        form = ForwardForm(request.POST)
        if form.is_valid():
            if al is None:
                al = Alias.objects.create(
                    address=mb.full_address, domain=mb.domain,
                    enabled=mb.user.is_active)
            recipients = form.get_recipients()
            if form.cleaned_data["keepcopies"]:
                recipients.append(mb.full_address)
            al.set_recipients(recipients)
            al.post_create(request.user)
            return render_to_json_response(_("Forward updated"))

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

    form = ForwardForm()
    if al is not None and al.recipients:
        form.fields["dest"].initial = al.recipients
        if al.aliasrecipient_set.filter(r_mailbox=mb.pk).exists():
            form.fields["keepcopies"].initial = True
    return render_to_json_response({
        "content": _render_to_string(request, tplname, {
            "form": form
        })
    })
Beispiel #11
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
    )
Beispiel #12
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)
Beispiel #13
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)
Beispiel #14
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())
    )
Beispiel #15
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"))
Beispiel #16
0
def editfolder(request, tplname="modoboa_webmail/folder.html"):
    mbc = IMAPconnector(user=request.user.username,
                        password=request.session["password"])
    ctx = {"title": _("Edit mailbox"),
           "formid": "mboxform",
           "action": reverse("modoboa_webmail:folder_change"),
           "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("modoboa_webmail:folder_change"),
           "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)
Beispiel #17
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 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)
Beispiel #18
0
def _validate_alias(request, form, successmsg, callback=None):
    """Alias validation

    Common function shared between creation and modification actions.
    """
    if form.is_valid():
        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)
Beispiel #19
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)
Beispiel #20
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)
    )
Beispiel #21
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
        })
    })
Beispiel #22
0
def list_quotas(request):
    sort_order, sort_dir = get_sort_order(request.GET, "name")
    domains = Domain.objects.get_for_admin(request.user)
    domains = domains.exclude(quota=0)
    if sort_order in ["name", "quota"]:
        domains = domains.order_by("{}{}".format(sort_dir, sort_order))
    elif sort_order == "allocated_quota":
        domains = (
            domains.annotate(allocated_quota=Sum("mailbox__quota"))
            .order_by("{}{}".format(sort_dir, sort_order))
        )
    page = get_listing_page(domains, request.GET.get("page", 1))
    context = {
        "headers": render_to_string(
            "admin/domains_quota_headers.html", {}, request
        )
    }
    if page is None:
        context["length"] = 0
    else:
        context["rows"] = render_to_string(
            "admin/domains_quotas.html", {"domains": page}, request
        )
        context["pages"] = [page.number]
    return render_to_json_response(context)
Beispiel #23
0
def check_top_notifications(request):
    """AJAX service to check for new top notifications to display."""
    notifications = signals.get_top_notifications.send(
        sender="top_notifications", include_all=True)
    notifications = reduce(
        lambda a, b: a + b, [notif[1] for notif in notifications])
    return render_to_json_response(notifications)
Beispiel #24
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
    })
Beispiel #25
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": request.localconfig.parameters.get_value(
            "handle_mailboxes", raise_exception=False)
    }
    page = get_listing_page(objects, request.GET.get("page", 1))
    if page is None:
        context["length"] = 0
    else:
        context["headers"] = render_to_string(
            "admin/identity_headers.html", {}, request)
        context["rows"] = render_to_string(
            "admin/identities_table.html", {
                "identities": page.object_list
            }, request
        )
        context["pages"] = [page.number]
    return render_to_json_response(context)
Beispiel #26
0
def getfs(request, name):
    sc = SieveClient(user=request.user.username,
                     password=request.session["password"])
    editormode = parameters.get_user(request.user, "EDITOR_MODE")
    error = None
    try:
        content = sc.getscript(name, format=editormode)
    except SieveClientError as e:
        error = str(e)
    else:
        if content is None:
            error = _("Failed to retrieve filters set")

    if error is not None:
        return ajax_response(request, "ko", respmsg=error)

    if editormode == "raw":
        htmlcontent = render_to_string("modoboa_sievefilters/rawfilter.html", dict(
            name=name, scriptcontent=content
        ))
    else:
        htmlcontent = render_to_string("modoboa_sievefilters/guieditor.html", dict(
            fs=content
        ))

    menu = '<ul id="fsetmenu" class="nav nav-sidebar"><li class="nav-header">%s</li>%s</ul>' % \
        (_("Actions"), fset_menu(editormode, name))
    resp = dict(menu=menu, content=htmlcontent)
    return render_to_json_response(resp)
Beispiel #27
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)
Beispiel #28
0
    def done(self):
        from modoboa.lib.web_utils 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"))
Beispiel #29
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"))
Beispiel #30
0
def information(request, tplname="core/information.html"):
    status, extensions = check_for_updates(request)
    return render_to_json_response({
        "content": render_to_string(tplname, {
            "update_avail": status,
            "extensions": extensions,
        }),
    })
Beispiel #31
0
def move(request):
    for arg in ["msgset", "to"]:
        if arg not 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)
Beispiel #32
0
def api_access(request):
    """A view to configure API access."""
    if request.method == "POST":
        form = APIAccessForm(request.POST, user=request.user)
        if form.is_valid():
            if form.cleaned_data.get("enable_api_access"):
                Token.objects.get_or_create(user=request.user)
            else:
                Token.objects.filter(user=request.user).delete()
            return render_to_json_response(_("Access updated"))
        return render_to_json_response({
            "form_errors": form.errors
        }, status=400)
    form = APIAccessForm(user=request.user)
    return render_to_json_response({
        "content": _render_to_string(
            request, "core/api_access.html", {"form": form})
    })
Beispiel #33
0
def information(request, tplname="core/information.html"):
    status, extensions = check_for_updates(request)
    return render_to_json_response({
        "content":
        render_to_string(tplname, {
            "update_avail": status,
            "extensions": extensions,
        }),
    })
Beispiel #34
0
 def done(self):
     genform = self.first_step.form
     domain = genform.save(self.request.user)
     domain.post_create(self.request.user)
     for step in self.steps[1:]:
         if not step.check_access(self):
             continue
         step.form.save(user=self.request.user, domain=domain)
     return render_to_json_response(_("Domain created"))
Beispiel #35
0
def preferences(request):
    if request.method == "POST":
        for formdef in parameters.get_user_forms(request.user, request.POST):
            form = formdef["form"]
            if form.is_valid():
                form.save()
                continue
            return render_to_json_response({
                "prefix": form.app, "form_errors": form.errors
            }, status=400)

        return render_to_json_response(_("Preferences saved"))

    return render_to_json_response({
        "content": _render_to_string(request, "core/user_preferences.html", {
            "forms": parameters.get_user_forms(request.user)
        })
    })
Beispiel #36
0
def list_quotas(request):
    from modoboa.lib.db_utils 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"]:
        mboxes = mboxes.order_by("%s%s" % (sort_dir, sort_order))
    elif sort_order == "quota_value__bytes":
        where = "admin_mailbox.address||'@'||admin_domain.name"
        mboxes = mboxes.extra(
            select={"quota_value__bytes": "admin_quota.bytes"},
            where=["admin_quota.username=%s" % where],
            tables=["admin_quota", "admin_domain"],
            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 = {
        "headers": _render_to_string(
            request, "admin/quota_headers.html", {}
        )
    }
    if page is None:
        context["length"] = 0
    else:
        context["rows"] = _render_to_string(
            request, "admin/quotas.html", {
                "mboxes": page
            }
        )
        context["pages"] = [page.number]
    return render_to_json_response(context)
Beispiel #37
0
def delete_selfservice(request, mail_id):
    rcpt = request.GET.get("rcpt", None)
    if rcpt is None:
        raise BadRequest(_("Invalid request"))
    try:
        get_connector().set_msgrcpt_status(rcpt, mail_id, 'D')
    except Msgrcpt.DoesNotExist:
        raise BadRequest(_("Invalid request"))
    return render_to_json_response(_("Message deleted"))
Beispiel #38
0
def delalias(request):
    selection = request.GET["selection"].split(",")
    for alid in selection:
        alias = Alias.objects.get(pk=alid)
        if not request.user.can_access(alias):
            raise PermDeniedException
        alias.delete()
    msg = ungettext("Alias deleted", "Aliases deleted", len(selection))
    return render_to_json_response(msg)
Beispiel #39
0
def mark_as_junk(request):
    """Mark a message as SPAM."""
    count = _move_selection_to_folder(
        request, request.user.parameters.get_value("junk_folder"))
    message = ungettext("%(count)d message marked",
                        "%(count)d messages marked", count) % {
                            "count": count
                        }
    return render_to_json_response(message)
Beispiel #40
0
def empty_quarantine():
    """Shortcut to use when no content can be displayed."""
    content = loader.render_to_string(
        "modoboa_amavis/empty_quarantine.html", {
            "message_types": constants.MESSAGE_TYPES
        }
    )
    ctx = getctx("ok", level=2, listing=content)
    return render_to_json_response(ctx)
Beispiel #41
0
def empty(request):
    """Empty the trash folder."""
    name = request.GET.get("name", None)
    if name != request.user.parameters.get_value("trash_folder"):
        raise BadRequest(_("Invalid request"))
    get_imapconnector(request).empty(name)
    content = u"<div class='alert alert-info'>%s</div>" % _("Empty folder")
    return render_to_json_response({
        'listing': content, 'mailbox': name, 'pages': [1]
    })
Beispiel #42
0
def check_unseen_messages(request):
    mboxes = request.GET.get("mboxes", None)
    if not mboxes:
        raise BadRequest(_("Invalid request"))
    mboxes = mboxes.split(",")
    counters = {}
    imapc = get_imapconnector(request)
    for mb in mboxes:
        counters[mb] = imapc.unseen_messages(mb)
    return render_to_json_response(counters)
Beispiel #43
0
def remove_filters_set(request, name):
    sc = SieveClient(user=request.user.username,
                     password=request.session["password"])
    sc.deletescript(name)
    acs, scripts = sc.listscripts()
    ctx = {
        "respmsg": _("Filters set deleted"),
        "newfs": acs,
    }
    return render_to_json_response(ctx)
Beispiel #44
0
def get_domain_list(request):
    """Get the list of domains (and relay domains) the user can see."""
    doms = [dom.name for dom in Domain.objects.get_for_admin(request.user)]
    if exts_pool.is_extension_enabled("postfix_relay_domains"):
        from modoboa.extensions.postfix_relay_domains.models import RelayDomain
        doms += [
            rdom.name
            for rdom in RelayDomain.objects.get_for_admin(request.user)
        ]
    return render_to_json_response(doms)
Beispiel #45
0
def new_shared_calendar(request):
    """Shared calendar creation view."""
    if request.method == "POST":
        form = SharedCalendarForm(request.user, request.POST)
        if form.is_valid():
            form.save()
            return render_to_json_response(_("Calendar created"))
        return render_to_json_response({"form_errors": form.errors},
                                       status=400)
    form = SharedCalendarForm(request.user)
    return render(
        request, "common/generic_modal_form.html", {
            "form": form,
            "formid": "sharedcal_form",
            "title": _("New shared calendar"),
            "action": reverse("modoboa_radicale:shared_calendar_add"),
            "action_classes": "submit",
            "action_label": _("Submit")
        })
Beispiel #46
0
def viewextensions(request, tplname='core/extensions.html'):
    """List available extensions."""
    from modoboa.core.extensions import exts_pool

    exts = exts_pool.list_all()
    return render_to_json_response({
        "callback":
        "extensions",
        "content":
        _render_to_string(request, tplname, {"extensions": exts})
    })
Beispiel #47
0
 def validate_step(self):
     stepid = self.request.POST.get("stepid", None)
     if stepid is None:
         raise BadRequest(_("Invalid request"))
     stepid = int(stepid.replace("step", ""))
     if stepid < 0 or stepid > len(self.steps):
         raise BadRequest(_("Invalid request"))
     self.create_forms(self.request.POST)
     statuses = []
     for cpt in xrange(0, stepid):
         statuses.append(self.steps[cpt].form.is_valid())
     if False in statuses:
         return render_to_json_response({
             'stepid': stepid, 'form_errors': self.errors
         }, status=400)
     if stepid == len(self.steps):
         return self.done()
     return render_to_json_response(
         {'title': self.steps[stepid].title, 'stepid': stepid}
     )
Beispiel #48
0
 def done(self):
     genform = self.first_step.form
     domain = genform.save(self.request.user)
     domain.post_create(self.request.user)
     try:
         self.steps[1].form.save(self.request.user, domain)
     except ModoboaException:
         from django.db import transaction
         transaction.rollback()
         raise
     return render_to_json_response(_("Domain created"))
Beispiel #49
0
def logs_page(request, tplname="core/logs_page.html"):
    """Return a page containing logs."""
    page = get_logs_page(request)
    if page is None:
        context = {"length": 0}
    else:
        context = {
            "rows": render_to_string(tplname, {"logs": page.object_list}),
            "pages": [page.number]
        }
    return render_to_json_response(context)
Beispiel #50
0
def create(request, tplname="postfix_relay_domains/new_relaydomain_form.html"):
    events.raiseEvent("CanCreate", request.user, "relay_domains")
    if request.method == 'POST':
        form = RelayDomainFormGeneral(request.POST)
        if form.is_valid():
            rdom = form.save(request.user)
            rdom.post_create(request.user)
            return render_to_json_response(_("Relay domain created"))
        return render_to_json_response({'form_errors': form.errors},
                                       status=400)

    ctx = {
        "title": _("New relay domain"),
        "action_label": _("Create"),
        "action_classes": "submit",
        "action": reverse("postfix_relay_domains:relaydomain_add"),
        "formid": "rdomform",
        "form": RelayDomainFormGeneral()
    }
    return render(request, tplname, ctx)
Beispiel #51
0
def _domains(request):
    sort_order, sort_dir = get_sort_order(request.GET, "name")
    extra_filters = signals.extra_domain_filters.send(sender="_domains")
    if extra_filters:
        extra_filters = reduce(lambda a, b: a + b,
                               [result[1] for result in extra_filters])
    filters = {
        flt: request.GET.get(flt, None)
        for flt in ["domfilter", "searchquery"] + extra_filters
    }
    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]["name"],
                            reverse=sort_dir == "-")
    context = {
        "handle_mailboxes":
        request.localconfig.parameters.get_value("handle_mailboxes",
                                                 raise_exception=False),
        "auto_account_removal":
        request.localconfig.parameters.get_value("auto_account_removal"),
    }
    page = get_listing_page(domainlist, request.GET.get("page", 1))
    parameters = request.localconfig.parameters
    dns_checks = {
        "enable_mx_checks":
        parameters.get_value("enable_mx_checks"),
        "enable_spf_checks":
        parameters.get_value("enable_spf_checks"),
        "enable_dkim_checks":
        parameters.get_value("enable_dkim_checks"),
        "enable_dmarc_checks":
        parameters.get_value("enable_dmarc_checks"),
        "enable_autoconfig_checks":
        (parameters.get_value("enable_autoconfig_checks")),
        "enable_dnsbl_checks":
        parameters.get_value("enable_dnsbl_checks")
    }
    context["headers"] = render_to_string("admin/domain_headers.html",
                                          dns_checks, request)
    if page is None:
        context["length"] = 0
    else:
        tpl_context = {"domains": page.object_list}
        tpl_context.update(dns_checks)
        context["rows"] = render_to_string("admin/domains_table.html",
                                           tpl_context, request)
        context["pages"] = [page.number]
    return render_to_json_response(context)
Beispiel #52
0
def preferences(request):
    if request.method == "POST":
        forms = param_tools.registry.get_forms(
            "user", request.POST, user=request.user)
        for formdef in forms:
            form = formdef["form"]
            if form.is_valid():
                form.save()
                continue
            return render_to_json_response({
                "prefix": form.app, "form_errors": form.errors
            }, status=400)
        request.user.save()
        return render_to_json_response(_("Preferences saved"))

    return render_to_json_response({
        "content": _render_to_string(request, "core/user_preferences.html", {
            "forms": param_tools.registry.get_forms(
                "user", user=request.user, first_app="general")
        })
    })
Beispiel #53
0
def profile(request, tplname='core/user_profile.html'):
    update_password = True
    if True in events.raiseQueryEvent("PasswordChange", request.user):
        update_password = False

    if request.method == "POST":
        form = ProfileForm(update_password,
                           request.POST,
                           instance=request.user)
        if form.is_valid():
            form.save()
            if update_password and form.cleaned_data["confirmation"] != "":
                request.session["password"] = encrypt(
                    form.cleaned_data["confirmation"])
            return render_to_json_response(_("Profile updated"))
        return render_to_json_response({'form_errors': form.errors},
                                       status=400)

    form = ProfileForm(update_password, instance=request.user)
    return render_to_json_response(
        {"content": _render_to_string(request, tplname, {"form": form})})
Beispiel #54
0
def logs(request, tplname="core/logs.html"):
    """Return a list of log entries.

    This view is only called the first time the page is displayed.

    """
    page = get_logs_page(request, 1)
    return render_to_json_response({
        "callback": "logs",
        "content": render_to_string(tplname, {"logs": page.object_list}),
        "page": page.number
    })
Beispiel #55
0
def profile(request, tplname="core/user_profile.html"):
    """Profile detail/update view."""
    update_password = True
    results = signals.allow_password_change.send(sender="profile",
                                                 user=request.user)
    if True in [result[1] for result in results]:
        update_password = False
    password_url = request.localconfig.parameters.get_value(
        "update_password_url")
    show_password_url = False
    if not request.user.is_local and password_url:
        show_password_url = True
        update_password = False

    if request.method == "POST":
        form = ProfileForm(update_password,
                           request.POST,
                           instance=request.user)
        if form.is_valid():
            form.save()
            if update_password and form.cleaned_data["confirmation"] != "":
                request.session["password"] = force_text(
                    encrypt(form.cleaned_data["confirmation"]))
            translation.activate(request.user.language)
            request.session[translation.LANGUAGE_SESSION_KEY] = (
                request.user.language)
            return render_to_json_response(_("Profile updated"))
        return render_to_json_response({"form_errors": form.errors},
                                       status=400)

    form = ProfileForm(update_password, instance=request.user)
    return render_to_json_response({
        "content":
        render_to_string(
            tplname, {
                "form": form,
                "show_password_url": show_password_url,
                "password_url": password_url
            }, request)
    })
Beispiel #56
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)
Beispiel #57
0
    def process_exception(self, request, exception):
        if not isinstance(exception, ModoboaException):
            return None

        if request.is_ajax() or "/api/" in request.path:
            if exception.http_code is None:
                return ajax_response(request,
                                     status="ko",
                                     respmsg=unicode(exception),
                                     norefresh=True)
            return render_to_json_response(unicode(exception),
                                           status=exception.http_code)
        return _render_error(request, user_context=dict(error=str(exception)))
Beispiel #58
0
def username_list(request):
    """Get the list of username the current user can see."""
    result = []
    qset = Mailbox.objects.select_related("user")
    if request.user.has_perm("admin.add_mailbox"):
        qset = qset.filter(
            domain__in=Domain.objects.get_for_admin(request.user))
    else:
        user_domain = request.user.mailbox.domain
        qset = qset.filter(domain=user_domain)
    for mbox in qset:
        result.append(mbox.user.username)
    return render_to_json_response(result)
Beispiel #59
0
def forward(request, tplname='admin/forward.html'):
    mb = request.user.mailbox_set.all()[0]
    try:
        al = Alias.objects.get(address=mb.address, domain__name=mb.domain.name)
    except Alias.DoesNotExist:
        al = None
    if request.method == "POST":
        form = ForwardForm(request.POST)
        error = None
        if form.is_valid():
            if al is None:
                al = Alias()
                al.address = mb.address
                al.domain = mb.domain
                al.enabled = mb.user.is_active
            intdests = []
            if form.cleaned_data["keepcopies"]:
                intdests += [mb]
            form.parse_dest()
            al.save(int_rcpts=intdests,
                    ext_rcpts=form.dests,
                    creator=request.user)
            return render_to_json_response(_("Forward updated"))

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

    form = ForwardForm()
    if al is not None:
        form.fields["dest"].initial = al.extmboxes
        try:
            al.mboxes.get(pk=mb.id)
        except Mailbox.DoesNotExist:
            pass
        else:
            form.fields["keepcopies"].initial = True
    return render_to_json_response(
        {"content": _render_to_string(request, tplname, {"form": form})})
Beispiel #60
0
 def done(self):
     genform = self.first_step.form
     domain = genform.save(self.request.user)
     domain.post_create(self.request.user)
     for step in self.steps[1:]:
         if not step.check_access(self):
             continue
         try:
             step.form.save(user=self.request.user, domain=domain)
         except ModoboaException:
             from django.db import transaction
             transaction.rollback()
             raise
     return render_to_json_response(_("Domain created"))