Example #1
0
def remove_site(request):
    u = request.session.get('switched_user', request.user)

    try:
        object_id = request.POST['object_id']
        s = get_object_or_404(UserSite, id=object_id)
        if s.owner != u:
            raise Exception("Forbidden operation")

        s.removed = True
        s.end_date = date.today()
        s.save()

        #Signal
        restart_master(config.mode, u)

        ur = UWSGIRequest(u, u.parms.web_machine)
        ur.stop(s)
        ur.mod_config()

        # calculate!
        u.parms.pay_for_sites(use_cache=False)
        return JsonResponse("OK", {1: ugettext("Site was successfuly removed")})
    except Exception, e:
        return JsonResponse("KO", {1: ugettext("Error deleting site")})
Example #2
0
    def save(self, request, datastream_rev=None, visualization_rev=None):
        if datastream_rev:
            lifecycle = VisualizationLifeCycleManager(user=request.user)
            visualization_rev = lifecycle.create(datastream_rev, language=request.user.language,  **self.cleaned_data)

            return dict(
                status='ok',
                revision_id=visualization_rev.id,
                messages=[ugettext('APP-VISUALIZATION-CREATEDSUCCESSFULLY-TEXT')]
            )
        elif visualization_rev:
            lifecycle = VisualizationLifeCycleManager(
                user=request.user,
                visualization_revision_id=visualization_rev['visualization_revision_id']
            )
            visualization_rev = lifecycle.edit(
                language=request.auth_manager.language,
                changed_fields=self.changed_data,
                **self.cleaned_data
            )
            return dict(
                status='ok',
                revision_id=visualization_rev.id,
                messages=[ugettext('APP-VISUALIZATION-CREATEDSUCCESSFULLY-TEXT')]
            )
Example #3
0
def admin_invite_user(request, **kwargs):
    """
    This view, by default, works inside the Django admin.
    """
    
    form_class = kwargs.pop("form_class", InviteUserForm)
    template_name = kwargs.pop("template_name", "signup_codes/admin_invite_user.html")
    
    group, bridge = group_and_bridge(request)
    if request.method == "POST":
        form = form_class(request.POST, group=group)
        if form.is_valid():
            email = form.cleaned_data["email"]
            form.send_signup_code()
            messages.add_message(request, messages.INFO,
                ugettext("An email has been sent to %(email)s.") % {
                    "email": email
                }
            )
            form = form_class() # reset
    else:
        form = form_class(group=group)
    
    ctx = group_context(group, bridge)
    ctx.update({
        "title": ugettext("Invite user"),
        "form": form,
    })
    
    return render_to_response(template_name, RequestContext(request, ctx))
Example #4
0
def edit(request, id, form_class=BlogForm, template_name="blog/edit.html"):
    post = get_object_or_404(Post, id=id)
    
    if request.method == "POST":
        if post.author != request.user:
            messages.add_message(request, messages.ERROR,
                ugettext("You can't edit posts that aren't yours")
            )
            return HttpResponseRedirect(reverse("blog_list_yours"))
        if request.POST["action"] == "update":
            blog_form = form_class(request.user, request.POST, instance=post)
            if blog_form.is_valid():
                blog = blog_form.save(commit=False)
                blog.save()
                messages.add_message(request, messages.SUCCESS,
                    ugettext("Successfully updated post '%s'") % blog.title
                )
                if notification:
                    if blog.status == 2: # published
                        if friends: # @@@ might be worth having a shortcut for sending to all friends
                            notification.send((x['friend'] for x in Friendship.objects.friends_for_user(blog.author)), "blog_friend_post", {"post": blog})
                
                return HttpResponseRedirect(reverse("blog_list_yours"))
        else:
            blog_form = form_class(instance=post)
    else:
        blog_form = form_class(instance=post)
    
    return render_to_response(template_name, {
        "blog_form": blog_form,
        "post": post,
    }, context_instance=RequestContext(request))
Example #5
0
 def save(self,*args, **kwargs):
   super(User, self).save(*args, **kwargs)
   m=Mail(
     ugettext(u'Bienvenido!'),
     ugettext('Tu cuenta de mail ha sido creada/modificada.'),
     [self.email])
   m.send()
Example #6
0
def delta_filter(delta):
    """Humanizes a timedelta object on template (i.e. "2 months, 2 weeks")."""
    if not delta:
        return ""
    try:
        # ignore microseconds
        since = delta.days * 24 * 60 * 60 + delta.seconds
        if since <= 0:
            # d is in the future compared to now, stop processing.
            return ugettext("0 seconds")
        for i, (seconds, name) in enumerate(TIME_SINCE_CHUNKS):
            count = since // seconds
            if count != 0:
                break
        result = name % count
        if i + 1 < len(TIME_SINCE_CHUNKS):
            # Now get the second item
            seconds2, name2 = TIME_SINCE_CHUNKS[i + 1]
            count2 = (since - (seconds * count)) // seconds2
            if count2 != 0:
                result += ugettext(", ") + name2 % count2
        return result

    except Exception:
        return ""
Example #7
0
def create_categories(request):
    form = forms.CategoryCreateForm(request.POST)
    if form.is_valid():
        auth_manager = request.auth_manager
        category_name = form.cleaned_data['name']
        # check for duplicates in this account
        duplicated = CategoryI18n.objects.filter(name=category_name, category__account__id=auth_manager.account_id)
        if len(duplicated) > 0:
            errors = [ugettext('ERROR-DUPLICATED-CATEGORY')]
            response = {'status': 'error', 'messages': errors}
            return HttpResponse(json.dumps(response), content_type='application/json', status = 400)

        category = Category.objects.create(account_id=auth_manager.account_id)
        categoryi18n = CategoryI18n.objects.create(
            category=category,
            name=category_name,
            description=form.cleaned_data['description'],
            language=auth_manager.language
        )

        is_default = form.cleaned_data['is_default']
        account = auth_manager.get_account()
        if is_default:
            account.set_preference('account.default.category', category.id)

        response = {'status': 'ok', 'messages': [ugettext('APP-CATEGORY-CREATEDSUCCESSFULLY-TEXT')]}
        return HttpResponse(json.dumps(response), content_type='application/json')
    else:
        errors = generate_ajax_form_errors(form)
        response = {'status': 'error', 'messages': errors}
        return HttpResponse(json.dumps(response), content_type='application/json', status = 400)
Example #8
0
  def __init__(self, request, data):
    """Initializes the dashboard.

    Args:
      request: The HTTPRequest object
      data: The RequestData object
    """
    r = data.redirect
    r.program()

    shipment_info = ShipmentInfoDashboard(request, data)

    subpages = [
        {
            'name': 'shipment_infos',
            'description': ugettext('Manage Shipment Information'),
            'title': 'Shipment Information',
            'link': '',
            'subpage_links': shipment_info.getSubpagesLink(),
        },
        {
            'name': 'sync_data',
            'description': ugettext('Sync Data'),
            'title': 'Sync Data',
            'link': r.urlOf('trackings_sync_data'),
        },
    ]

    super(TrackingsDashboard, self).__init__(request, data, subpages)
Example #9
0
  def __init__(self, request, data):
    """Initializes the dashboard.

    Args:
      request: The HTTPRequest object
      data: The RequestData object
    """
    r = data.redirect
    r.program()

    subpages = [
        {
            'name': 'create_shipment_info',
            'description': ugettext('Create shipment information'),
            'title': 'Create',
            'link': r.urlOf('create_shipment_info'),
        },
        {
            'name': 'edit_shipment_infos',
            'description': ugettext('Edit shipment informations'),
            'title': 'Edit',
            'link': r.urlOf('shipment_info_records'),
        },
    ]

    super(ShipmentInfoDashboard, self).__init__(request, data, subpages)
Example #10
0
 def get_unique_error_message(self, unique_check):
     if len(unique_check) == 1:
         return ugettext("Please correct the duplicate data for %(field)s.") % {"field": unique_check[0]}
     else:
         return ugettext("Please correct the duplicate data for %(field)s, " "which must be unique.") % {
             "field": get_text_list(unique_check, unicode(_("and")))
         }
Example #11
0
def filesizeformat(bytes):
    """
    Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
    102 bytes, etc.).
    """
    try:
        bytes = float(bytes)
    except (TypeError, ValueError, UnicodeDecodeError):
        value = ungettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0}
        return avoid_wrapping(value)

    filesize_number_format = lambda value: formats.number_format(round(value, 1), 1)

    KB = 1 << 10
    MB = 1 << 20
    GB = 1 << 30
    TB = 1 << 40
    PB = 1 << 50

    if bytes < KB:
        value = ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes}
    elif bytes < MB:
        value = ugettext("%s KB") % filesize_number_format(bytes / KB)
    elif bytes < GB:
        value = ugettext("%s MB") % filesize_number_format(bytes / MB)
    elif bytes < TB:
        value = ugettext("%s GB") % filesize_number_format(bytes / GB)
    elif bytes < PB:
        value = ugettext("%s TB") % filesize_number_format(bytes / TB)
    else:
        value = ugettext("%s PB") % filesize_number_format(bytes / PB)

    return avoid_wrapping(value)
Example #12
0
    def __init__(self, *args, **kwargs):
        email_required = kwargs.pop('email_required',
                                    app_settings.EMAIL_REQUIRED)
        self.username_required = kwargs.pop('username_required',
                                            app_settings.USERNAME_REQUIRED)
        super(BaseSignupForm, self).__init__(*args, **kwargs)
        # field order may contain additional fields from our base class,
        # so take proper care when reordering...
        field_order = ['email', 'username']
        merged_field_order = list(self.fields.keys())
        if email_required:
            self.fields["email"].label = ugettext("E-mail")
            self.fields["email"].required = True
        else:
            self.fields["email"].label = ugettext("E-mail (optional)")
            self.fields["email"].required = False
            self.fields["email"].widget.is_required = False
            if self.username_required:
                field_order = ['username', 'email']

        # Merge our email and username fields in if they are not
        # currently in the order.  This is to allow others to
        # re-arrange email and username if they desire.  Go in reverse
        # so that we make sure the inserted items are always
        # prepended.
        for field in reversed(field_order):
            if field not in merged_field_order:
                merged_field_order.insert(0, field)
        set_form_field_order(self, merged_field_order)
        if not self.username_required:
            del self.fields["username"]
Example #13
0
    def resolve(self, new_url):
        if self.resolved:
            raise Exception(ugettext("Attempting to double-resolve import request"))

        if self.expiration < datetime.datetime.now():
            raise Exception(ugettext("Attempting to resolve expired import request"))

        if self.podcast:
            if self.audio_source_url:
                raise Exception(ugettext("Invalid import request"))

            orig_url = self.podcast.cover_image
            self.podcast.cover_image = new_url
            self.podcast.save()

            eps = self.podcast.podcastepisode_set.filter(image_url=orig_url)
            for ep in eps:
                ep.image_url = new_url
                ep.save()

        elif self.episode:
            if self.audio_source_url:
                self.episode.audio_url = new_url
            else:
                self.episode.image_url = new_url

            if settings.S3_BUCKET in self.episode.audio_url and settings.S3_BUCKET in self.episode.image_url:
                self.episode.awaiting_import = False
            self.episode.save()

        else:
            raise Exception(ugettext("Invalid import request for neither podcast nor ep"))

        self.resolved = True
        self.save()
Example #14
0
    def save(self):
        username = self.cleaned_data["username"]
        email = self.cleaned_data["email"]
        password = self.cleaned_data["password1"]
        if self.cleaned_data["confirmation_key"]:
            try:
                join_invitation = JoinInvitation.objects.get(confirmation_key = self.cleaned_data["confirmation_key"])
                confirmed = True
            except JoinInvitation.DoesNotExist:
                confirmed = False
        else:
            confirmed = False

        # @@@ clean up some of the repetition below -- DRY!

        if confirmed:
            if email == join_invitation.contact.email:
                new_user = User.objects.create_user(username, email, password)
                join_invitation.accept(new_user) # should go before creation of EmailAddress below
                new_user.message_set.create(message=ugettext(u"Your email address has already been verified"))
                # already verified so can just create
                EmailAddress(user=new_user, email=email, verified=True, primary=True).save()
            else:
                new_user = User.objects.create_user(username, "", password)
                join_invitation.accept(new_user) # should go before creation of EmailAddress below
                if email:
                    new_user.message_set.create(message=ugettext(u"Confirmation email sent to %(email)s") % {'email': email})
                    EmailAddress.objects.add_email(new_user, email)
            return username, password # required for authenticate()
        else:
            new_user = User.objects.create_user(username, "", password)
            if email:
                new_user.message_set.create(message=ugettext(u"Confirmation email sent to %(email)s") % {'email': email})
                EmailAddress.objects.add_email(new_user, email)
            return username, password # required for authenticate()
Example #15
0
 def add_vevent_to_ical(self, cal, summary_length):
     """
     adds itself as a vevent to @cal.
     cal should be a vobject.iCalendar
     """
     vevent = cal.add('vevent')
     vevent.add('dtstart').value = self.when
     warnings = []
     if not self.when_over:
         # this can happen if you migrated so you have when_over but
         # have not run parse_future_committee_meetings yet.
         self.when_over = self.when + timedelta(hours=2)
         self.when_over_guessed = True
         self.save()
     if self.when_over_guessed:
         warnings.append(ugettext('no end date data - guessed it to be 2 hours after start'))
     # TODO: add `geo` to the Event model
     # FLOAT:FLOAT lon:lat, up to 6 digits, degrees.
     vevent.add('geo').value = '31.777067;35.205495'
     vevent.add('x-pk').value = str(self.pk)
     vevent.add('dtend').value = self.when_over
     vevent.add('summary').value = self.get_summary(summary_length)
     vevent.add('location').value = self.where
     if warnings:
         self.what = '\n'.join((self.what, '', ugettext('oknesset warnings:'), ''))
         self.what += '\n'.join(warnings)
     vevent.add('description').value = self.what
Example #16
0
def sidebar(app):
    """Populates the sidebar with (categories, types)."""
    from olympia.addons.models import Category
    if app is None:
        return [], []

    # Fetch categories...
    qs = Category.objects.filter(application=app.id, weight__gte=0,
                                 type=amo.ADDON_EXTENSION)
    # Now sort them in python according to their name property (which looks up
    # the translated name using gettext + our constants)
    categories = sorted(qs, key=attrgetter('weight', 'name'))

    Type = collections.namedtuple('Type', 'id name url')
    base = urlresolvers.reverse('home')
    types = [Type(99, ugettext('Collections'), base + 'collections/')]

    shown_types = {
        amo.ADDON_PERSONA: urlresolvers.reverse('browse.personas'),
        amo.ADDON_DICT: urlresolvers.reverse('browse.language-tools'),
        amo.ADDON_SEARCH: urlresolvers.reverse('browse.search-tools'),
        amo.ADDON_THEME: urlresolvers.reverse('browse.themes'),
    }
    titles = dict(
        amo.ADDON_TYPES,
        **{amo.ADDON_DICT: ugettext('Dictionaries & Language Packs')})
    for type_, url in shown_types.items():
        if type_ in app.types:
            types.append(Type(type_, titles[type_], url))

    return categories, sorted(types, key=lambda x: x.name)
Example #17
0
def destroy(request, id, **kwargs):

    group, bridge = group_and_bridge(kwargs)

    photos = Image.objects.all()

    if group:
        photos = group.content_objects(photos)
    else:
        photos = photos.filter(object_id=None)

    photo = get_object_or_404(photos, pk=id)
    title = photo.title

    if group:
        redirect_to = bridge.reverse("photos_yours", group)
    else:
        redirect_to = reverse("photos_yours")

    if photo.member != request.user:
        messages.add_message(request, messages.ERROR,
            ugettext("You can't edit photos that aren't yours")
        )
        return HttpResponseRedirect(redirect_to)

    if request.method == "POST" and request.POST["action"] == "delete":
        photo.delete()
        messages.add_message(request, messages.SUCCESS,
            ugettext("Successfully deleted photo '%s'") % title
        )

    return HttpResponseRedirect(redirect_to)
Example #18
0
 def __unicode__(self):
     date_format = u'l, %s' % ugettext("DATE_FORMAT")
     return ugettext('%(title)s: %(start)s-%(end)s') % {
         'title': self.title,
         'start': date(self.start, date_format),
         'end': date(self.end, date_format),
     }
Example #19
0
 def admin_status_text(self, obj):
     if obj.subscribed:
         return ugettext("Subscribed")
     elif obj.unsubscribed:
         return ugettext("Unsubscribed")
     else:
         return ugettext("Unactivated")
Example #20
0
 def format_output(self, rendered_widgets):
     return format_html(
         '<div class="field-box">{0} {1}</div>'
         '<div class="field-box">{2} {3}</div>',
         ugettext('Date:'), rendered_widgets[0],
         ugettext('Time:'), rendered_widgets[1],
     )
Example #21
0
def pie_usage(q, legend):
  log = q.exclude(AnonymousQ)
  unlog = q.filter(AnonymousQ).exclude(RobotQ)
  robot = q.filter(AnonymousQ).filter(RobotQ)
  return pie_chart([log.count(), unlog.count(), robot.count()],
    [ugettext(u'Logged users'), ugettext(u'Anonymous'), ugettext(u'Robots')],
    legend)
Example #22
0
def change_password(request):
    user = request.user
    data = request.POST
    error = ugettext('Password was changed')
    if request.method != "POST":
        return render(request, 'blog/changepassword.html',
                      {'user': user, })
    if request.method == "POST":

        if user.check_password(data.get("old_pass")):

            if data.get("pass1") == data.get("pass2"):

                if data.get("pass2") != "":
                    user.set_password(data.get("pass1"))
                    user.save()
                else:
                    error = ugettext("Passwords must not be null")
            else:
                error = ugettext('passwords are not matching')
        else:
            error = ugettext('wrong password ')

    return render(request, 'blog/changepassword.html',
                  {'user': user, 'error': error},)
Example #23
0
    def get(self, request, *args, **kwargs):
        if not hasattr(request, 'event'):
            return self._get_event_list(request, **kwargs)

        if not request.event.live:
            return self.response({
                'error': ugettext('This ticket shop is currently disabled.')
            })

        self.subevent = None
        if request.event.has_subevents:
            if 'subevent' in kwargs:
                self.subevent = request.event.subevents.filter(pk=kwargs['subevent'], active=True).first()
                if not self.subevent:
                    return self.response({
                        'error': ugettext('The selected date does not exist in this event series.')
                    })
            else:
                return self._get_event_list(request, **kwargs)
        else:
            if 'subevent' in kwargs:
                return self.response({
                    'error': ugettext('This is not an event series.')
                })
        return self._get_event_view(request, **kwargs)
    def create(self, request, post_id=None, comment_id=None):
        user = request.user
        groups = get_accessible_group_ids(user)

        model = request.POST.get('model', '')
        if model:
            comment = StreamPostCommentValidationForm(json.loads(model))
        else:
            comment = StreamPostCommentValidationForm(request.POST)

        #Find a post that matches the given post_id and belongs to one of the request
        #user's groups
        if post_id:
            try:
                post = StreamPost.objects.get(id__exact=int(post_id), groups__id__in=groups)
                if comment.is_valid():
                    comment = StreamPostComment.objects.create(poster=request.user,
                                                           stream_post=post,
                                                           content=comment.cleaned_data['content'])
                    return comment
                else:
                    resp = rc.BAD_REQUEST
                    resp.write(ugettext('Invalid content'))
                    return resp
            except StreamPost.DoesNotExist:
                resp = rc.BAD_REQUEST
                resp.write(ugettext('No post has the specified ID, or the user has no permission to access it'))
                return resp

        else:
            resp = rc.BAD_REQUEST
            resp.write(ugettext('No Post ID was supplied!'))
            return resp
    def update(self, request, post_id=None, comment_id=None):
        user = request.user
        if not (post_id and comment_id):
            resp = rc.BAD_REQUEST
            resp.write(ugettext('Both Post and Comment IDs must be supplied!'))
            return resp

        model = request.POST.get('model', '')
        if model:
            comment_update = StreamPostCommentValidationForm(json.loads(model))
        else:
            comment_update = StreamPostCommentValidationForm(request.POST)
        
        try:
            comment = StreamPostComment.objects.get(stream_post__id__exact=int(post_id),
                                                    id__exact=int(comment_id))
            if user != comment.poster:
                resp = rc.FORBIDDEN
                resp.write(ugettext('Only the original commenter can update the comment!'))
                return resp
            
            if comment_update.is_valid():
                comment.content = comment_update.cleaned_data['content']
                comment.save()
                return comment
            else:
                resp = rc.BAD_REQUEST
                resp.write(ugettext('Invalid content'))
                return resp
            
        except StreamPostComment.DoesNotExist:
            resp = rc.BAD_REQUEST
            resp.write(ugettext('Invalid Post or Comment ID'))
            return resp
Example #26
0
def cron(request):
    ok = False

    # Shared secret authentication.
    secret = request.POST.get("secret")
    if settings.FILESHACK_CRON_SECRET and \
       settings.FILESHACK_CRON_SECRET == secret:
        ok = True

    # Host-based authentication.
    for host in settings.FILESHACK_CRON_HOSTS:
        try: sockinfos = socket.getaddrinfo(host, None)
        except socket.gaierror: sockinfos = []
        ips = [sockinfo[4][0] for sockinfo in sockinfos]
        if request.META["REMOTE_ADDR"] in ips:
            ok = True
            break

    if not ok: return HttpResponseForbidden(ugettext("Permission denied\n"))

    output = ugettext("Cron started at %s\n" % \
                      timezone.now().strftime("%H:%M %Z, %d %b %Y"))

    error = False

    # digest.
    response = digest(request)
    output += u"digest: %s\n" % response.content
    if response.status_code != 200: error = True

    return HttpResponseServerError(output) if error else HttpResponse(output)
    def read(self, request, post_id=None, comment_id=None):
        user = request.user
        groups = get_accessible_group_ids(user)

        #Find a post that matches the given post_id and belongs to one of the request
        #user's groups
        if post_id:
            try:
                post = StreamPost.objects.get(id__exact=int(post_id), groups__id__in=groups)

                if comment_id:
                    try:
                        return post.comments.get(id=comment_id)
                    except StreamPostComment.DoesNotExist:
                        resp = rc.BAD_REQUEST
                        resp.write(ugettext('No comment has the specified ID, or the user has no permission to access it'))
                        return resp
                else:
                    return post.comments.all()
                
            except StreamPost.DoesNotExist:
                resp = rc.BAD_REQUEST
                resp.write(ugettext('No post has the specified ID, or the user has no permission to access it'))
                return resp
        else:
            resp = rc.BAD_REQUEST
            resp.write(ugettext('No Post ID was supplied!'))
            return resp
Example #28
0
def activate(request, c_code):
    if confirm_comment(c_code):
        msg = ugettext("Your comment is activated")
    else:
        msg = ugettext("Your comment can not be activated")
    return render(request, 'blog/conf.html', {
        'ccode': msg, }, context_instance=RequestContext(request))
Example #29
0
 def description(self, category):
     """Description for the feed as a whole."""
     if category:
         # L10n: %s is a category name.
         return ugettext(u'%s Add-ons') % category.name
     else:
         return ugettext('Extensions')
Example #30
0
def twitter_connect(request, template_name="account/twitter_connect.html", extra_context=None):
    if extra_context is None:
        extra_context = {}
    done = request.GET.get('done', None)
    if done:
        if request.user.twitterprofile_set.all().count() > 0:
            messages.add_message(request, messages.SUCCESS,
                ugettext("You have successfully linked your account with Twitter Account")
            )
        else:
            messages.add_message(request, messages.ERROR,
                ugettext("Failed to linked your account with Twitter Account. Maybe the Twitter Account has already been linked to another account.")
            )
        return HttpResponseRedirect(reverse("acct_external")) 

    if request.POST.get('unlink', None):
        request.user.twitterprofile_set.all().delete()
        messages.add_message(request, messages.SUCCESS,
            ugettext("You have successfully unlinked your account with Twitter Account")
        )
        next = request.POST.get("next", None)
        if next:
            return HttpResponseRedirect(next)

    return render_to_response(template_name, dict({
        'next': '%s?done=1' % request.path,
        'done': done,
    }, **extra_context), context_instance=RequestContext(request))
Example #31
0
 def show_public(self, obj):
     format = '<a href="{0}" style="white-space:nowrap;">%s</a>' % ugettext('View on site')
     return format_html(format, obj.get_absolute_url())
Example #32
0
 def get_form_valid_message(self):
     msg = ugettext('Talk proposal <strong>{title}</strong> updated.')
     return format_html(msg, title=self.object.title)
Example #33
0
 def status(self):
     return [
         f.STATUS_CHOICES.get(f.status,
                              ugettext('[status:%s]') % f.status)
         for f in self.all_files
     ]
Example #34
0
 def get_path(quotation):
     quotation_date = quotation.current_revision.quotation_date or quotation.current_revision.issue_date
     return '{0}/{1}/{2}'.format(ugettext('Quotations'), quotation_date.strftime('%Y/%m'), quotation.filename)
Example #35
0
 def __str__(self):
     return (ugettext('Build command {pk} for build {build}').format(
         pk=self.pk, build=self.build))
Example #36
0
    def handle_upload(self, request, addon, version_string, guid=None):
        if 'upload' in request.FILES:
            filedata = request.FILES['upload']
        else:
            raise forms.ValidationError(
                ugettext(u'Missing "upload" key in multipart file data.'),
                status.HTTP_400_BAD_REQUEST)

        # Parse the file to get and validate package data with the addon.
        parsed_data = parse_addon(filedata, addon, user=request.user)

        if addon is not None and addon.status == amo.STATUS_DISABLED:
            msg = ugettext(
                'You cannot add versions to an addon that has status: %s.' %
                amo.STATUS_CHOICES_ADDON[amo.STATUS_DISABLED])
            raise forms.ValidationError(msg, status.HTTP_400_BAD_REQUEST)

        version_string = version_string or parsed_data['version']

        if version_string and parsed_data['version'] != version_string:
            raise forms.ValidationError(
                ugettext('Version does not match the manifest file.'),
                status.HTTP_400_BAD_REQUEST)

        if (addon is not None
                and addon.versions.filter(version=version_string).exists()):
            latest_version = addon.find_latest_version(None, exclude=())
            msg = ugettext('Version already exists. Latest version is: %s.' %
                           latest_version.version)
            raise forms.ValidationError(msg, status.HTTP_409_CONFLICT)

        package_guid = parsed_data.get('guid', None)

        dont_allow_no_guid = (not addon and not package_guid and
                              not parsed_data.get('is_webextension', False))

        if dont_allow_no_guid:
            raise forms.ValidationError(
                ugettext('Only WebExtensions are allowed to omit the GUID'),
                status.HTTP_400_BAD_REQUEST)

        if guid is not None and not addon and not package_guid:
            # No guid was present in the package, but one was provided in the
            # URL, so we take it instead of generating one ourselves. But
            # first, validate it properly.
            if len(guid) > 64:
                raise forms.ValidationError(
                    ugettext(
                        'Please specify your Add-on GUID in the manifest if it\'s '
                        'longer than 64 characters.'))

            if not amo.ADDON_GUID_PATTERN.match(guid):
                raise forms.ValidationError(ugettext('Invalid GUID in URL'),
                                            status.HTTP_400_BAD_REQUEST)
            parsed_data['guid'] = guid

        # channel will be ignored for new addons.
        if addon is None:
            channel = amo.RELEASE_CHANNEL_UNLISTED  # New is always unlisted.
            addon = Addon.initialize_addon_from_upload(data=parsed_data,
                                                       upload=filedata,
                                                       channel=channel,
                                                       user=request.user)
            created = True
        else:
            created = False
            channel_param = request.POST.get('channel')
            channel = amo.CHANNEL_CHOICES_LOOKUP.get(channel_param)
            if not channel:
                last_version = (addon.find_latest_version(None, exclude=()))
                if last_version:
                    channel = last_version.channel
                else:
                    channel = amo.RELEASE_CHANNEL_UNLISTED  # Treat as new.

            will_have_listed = channel == amo.RELEASE_CHANNEL_LISTED
            if not addon.has_complete_metadata(
                    has_listed_versions=will_have_listed):
                raise forms.ValidationError(
                    ugettext('You cannot add a listed version to this addon '
                             'via the API due to missing metadata. '
                             'Please submit via the website'),
                    status.HTTP_400_BAD_REQUEST)

        file_upload = devhub_handle_upload(filedata=filedata,
                                           request=request,
                                           addon=addon,
                                           submit=True,
                                           channel=channel)

        return file_upload, created
Example #37
0
 def test_encode_lazy(self):
     self.assertEqual('"{}"'.format(str(ugettext('User'))),
                      json_encode(ugettext_lazy('User')))
Example #38
0
 def __str__(self):
     return ugettext('%(title)s: %(start)s - %(end)s') % {
         'title': self.title,
         'start': date(self.start, django_settings.DATE_FORMAT),
         'end': date(self.end, django_settings.DATE_FORMAT),
     }
Example #39
0
 def admin_link(self):
     return "<a href='%s'>%s</a>" % (self.get_absolute_url(),
                                     ugettext("View on site"))
Example #40
0
 def show_public(self, obj):
     return format_html('<a href="{0}">%s</a>' % ugettext('View on site'), obj.get_absolute_url())
Example #41
0
def cohort_handler(request, course_key_string, cohort_id=None):
    """
    The restful handler for cohort requests. Requires JSON.
    GET
        If a cohort ID is specified, returns a JSON representation of the cohort
            (name, id, user_count, assignment_type, user_partition_id, group_id).
        If no cohort ID is specified, returns the JSON representation of all cohorts.
           This is returned as a dict with the list of cohort information stored under the
           key `cohorts`.
    PUT or POST or PATCH
        If a cohort ID is specified, updates the cohort with the specified ID. Currently the only
        properties that can be updated are `name`, `user_partition_id` and `group_id`.
        Returns the JSON representation of the updated cohort.
        If no cohort ID is specified, creates a new cohort and returns the JSON representation of the updated
        cohort.
    """
    course_key = SlashSeparatedCourseKey.from_deprecated_string(
        course_key_string)
    course = get_course_with_access(request.user, 'staff', course_key)
    if request.method == 'GET':
        if not cohort_id:
            all_cohorts = [
                _get_cohort_representation(c, course)
                for c in cohorts.get_course_cohorts(course)
            ]
            return JsonResponse({'cohorts': all_cohorts})
        else:
            cohort = cohorts.get_cohort_by_id(course_key, cohort_id)
            return JsonResponse(_get_cohort_representation(cohort, course))
    else:
        name = request.json.get('name')
        assignment_type = request.json.get('assignment_type')
        if not name:
            # Note: error message not translated because it is not exposed to the user (UI prevents this state).
            return JsonResponse({"error": "Cohort name must be specified."},
                                400)
        if not assignment_type:
            # Note: error message not translated because it is not exposed to the user (UI prevents this state).
            return JsonResponse(
                {"error": "Assignment type must be specified."}, 400)
        # If cohort_id is specified, update the existing cohort. Otherwise, create a new cohort.
        if cohort_id:
            cohort = cohorts.get_cohort_by_id(course_key, cohort_id)
            if name != cohort.name:
                if cohorts.is_cohort_exists(course_key, name):
                    err_msg = ugettext(
                        "A cohort with the same name already exists.")
                    return JsonResponse({"error": unicode(err_msg)}, 400)
                cohort.name = name
                cohort.save()
            try:
                cohorts.set_assignment_type(cohort, assignment_type)
            except ValueError as err:
                return JsonResponse({"error": unicode(err)}, 400)
        else:
            try:
                cohort = cohorts.add_cohort(course_key, name, assignment_type)
            except ValueError as err:
                return JsonResponse({"error": unicode(err)}, 400)

        group_id = request.json.get('group_id')
        if group_id is not None:
            user_partition_id = request.json.get('user_partition_id')
            if user_partition_id is None:
                # Note: error message not translated because it is not exposed to the user (UI prevents this state).
                return JsonResponse(
                    {
                        "error":
                        "If group_id is specified, user_partition_id must also be specified."
                    }, 400)
            existing_group_id, existing_partition_id = cohorts.get_group_info_for_cohort(
                cohort)
            if group_id != existing_group_id or user_partition_id != existing_partition_id:
                unlink_cohort_partition_group(cohort)
                link_cohort_to_partition_group(cohort, user_partition_id,
                                               group_id)
        else:
            # If group_id was specified as None, unlink the cohort if it previously was associated with a group.
            existing_group_id, _ = cohorts.get_group_info_for_cohort(cohort)
            if existing_group_id is not None:
                unlink_cohort_partition_group(cohort)

        return JsonResponse(_get_cohort_representation(cohort, course))
Example #42
0
 def __str__(self):
     return ugettext("%(start)s to %(end)s") % {
         'start': date(self.start, django_settings.DATE_FORMAT),
         'end': date(self.end, django_settings.DATE_FORMAT)
     }
Example #43
0
 def checkDelete(self, item):
     if item.deployedServices.count() > 0:
         raise RequestError(
             ugettext(
                 'Can\'t delete an OS Manager with services pools associated'
             ))
Example #44
0
 def get_params(self):
     result = {}
     result.update(self.params)
     if 'method' in result:
         result['method'] = ugettext(result['method'])
     return result
Example #45
0
File: views.py Project: eteks/Adjod
def user_login(request):
    if request.method == 'POST':
        error = {}
        username = request.POST['email_id']
        password = request.POST['password']
        if 'search' in request.POST['next']:
            next_url = request.POST['next'].split('&')[0]
        else:
            next_url = request.POST['next'].split('?')[0]
        print "next_url", next_url
        try:

            if '@' in username:
                if not User.objects.filter(email=username).exists():
                    error['email_exists'] = ugettext('Email Doesnot exists')
                    print "error['email_exists']", error['email_exists']
                    raise ValidationError(error['email_exists'], 1)
            else:
                if not User.objects.filter(username=username).exists():
                    error['username_exists'] = ugettext(
                        'Username Does not exists')
                    print "error['username_exists']", error['username_exists']
                    raise ValidationError(error['username_exists'], 2)
        except ValidationError as e:
            messages.add_message(request, messages.ERROR, e.messages[-1])
            if next_url == '/':
                redirect_path = "/login/"
            else:
                redirect_path = next_url
            query_string = 'si=%d' % e.code
            redirect_url = format_redirect_url(redirect_path, query_string)
            return HttpResponseRedirect(redirect_url)
        if not error:
            if not '@' in username:
                user = User.objects.get(username=username)
            else:
                user = User.objects.get(email=username)
            user.backend = 'django.contrib.auth.backends.ModelBackend'
            if user.is_superuser:
                return HttpResponseRedirect("/")
            try:
                if user.check_password(password):
                    print user
                else:
                    error['password'] = ugettext('Wrong password')
                    raise ValidationError(error['password'], 3)
            except ValidationError as e:
                messages.add_message(request, messages.ERROR, e.messages[-1])
                if next_url == '/':
                    redirect_path = "/login/"
                else:
                    redirect_path = next_url
                query_string = 'si=%d' % e.code
                redirect_url = format_redirect_url(redirect_path, query_string)
                return HttpResponseRedirect(redirect_url)
            if user:
                # Is the account active? It could have been disabled.
                if user.is_active:
                    # If the account is valid and active, we can log the user in.
                    # We'll send the user back to the homepage.
                    login(request, user)
                    print user.id
                    user_id = user.id
                    # starturl=reverse('start',kwargs={ 'user_id': user.id })
                    if next_url == '/':
                        response = HttpResponseRedirect('/start/?user_id=' +
                                                        str(user.id))
                    else:
                        response = HttpResponseRedirect(next_url)
                    response.set_cookie("chat_email", user.email)
                    response.set_cookie("chat_user", user.username)
                    response.set_cookie("chat_userid", user_id)
                    return response
                else:
                    # An inactive account was used - no logging in!
                    try:
                        # error['inactive'] = ugettext('Your Account is already inactive due to non-maintanence')
                        error['inactive'] = ugettext('Inactive Account')
                        raise ValidationError(error['inactive'], 4)
                    except ValidationError as e:
                        messages.add_message(request, messages.ERROR,
                                             e.messages[-1])
                        if next_url == '/':
                            redirect_path = "/login/"
                        else:
                            redirect_path = next_url
                        query_string = 'si=%d' % e.code
                        redirect_url = format_redirect_url(
                            redirect_path, query_string)
                        return HttpResponseRedirect(redirect_url)
    else:
        return render_to_response('adjod/userpage.html',
                                  context_instance=RequestContext(request))
Example #46
0
 def __unicode__(self):
     return ugettext("%(start)s to %(end)s") % {
         'start': self.start,
         'end': self.end,
     }
Example #47
0
    def _charge_source(self, request, source, payment):
        try:
            params = {}
            if not source.startswith('src_'):
                params['statement_descriptor'] = ugettext('{event}-{code}').format(
                    event=self.event.slug.upper(),
                    code=payment.order.code
                )[:22]
            params.update(self.api_kwargs)
            charge = stripe.Charge.create(
                amount=self._get_amount(payment),
                currency=self.event.currency.lower(),
                source=source,
                description='{event}-{code}'.format(
                    event=self.event.slug.upper(),
                    code=payment.order.code
                ),
                metadata={
                    'order': str(payment.order.id),
                    'event': self.event.id,
                    'code': payment.order.code
                },
                # TODO: Is this sufficient?
                idempotency_key=str(self.event.id) + payment.order.code + source,
                **params
            )
        except stripe.error.CardError as e:
            if e.json_body:
                err = e.json_body['error']
                logger.exception('Stripe error: %s' % str(err))
            else:
                err = {'message': str(e)}
                logger.exception('Stripe error: %s' % str(e))
            logger.info('Stripe card error: %s' % str(err))
            payment.info_data = {
                'error': True,
                'message': err['message'],
            }
            payment.state = OrderPayment.PAYMENT_STATE_FAILED
            payment.save()
            payment.order.log_action('pretix.event.order.payment.failed', {
                'local_id': payment.local_id,
                'provider': payment.provider,
                'message': err['message']
            })
            raise PaymentException(_('Stripe reported an error with your card: %s') % err['message'])

        except stripe.error.StripeError as e:
            if e.json_body and 'error' in e.json_body:
                err = e.json_body['error']
                logger.exception('Stripe error: %s' % str(err))
            else:
                err = {'message': str(e)}
                logger.exception('Stripe error: %s' % str(e))
            payment.info_data = {
                'error': True,
                'message': err['message'],
            }
            payment.state = OrderPayment.PAYMENT_STATE_FAILED
            payment.save()
            payment.order.log_action('pretix.event.order.payment.failed', {
                'local_id': payment.local_id,
                'provider': payment.provider,
                'message': err['message']
            })
            raise PaymentException(_('We had trouble communicating with Stripe. Please try again and get in touch '
                                     'with us if this problem persists.'))
        else:
            ReferencedStripeObject.objects.get_or_create(
                reference=charge.id,
                defaults={'order': payment.order, 'payment': payment}
            )
            if charge.status == 'succeeded' and charge.paid:
                try:
                    payment.info = str(charge)
                    payment.confirm()
                except Quota.QuotaExceededException as e:
                    raise PaymentException(str(e))

                except SendMailException:
                    raise PaymentException(_('There was an error sending the confirmation mail.'))
            elif charge.status == 'pending':
                if request:
                    messages.warning(request, _('Your payment is pending completion. We will inform you as soon as the '
                                                'payment completed.'))
                payment.info = str(charge)
                payment.state = OrderPayment.PAYMENT_STATE_PENDING
                payment.save()
                return
            else:
                logger.info('Charge failed: %s' % str(charge))
                payment.info = str(charge)
                payment.state = OrderPayment.PAYMENT_STATE_FAILED
                payment.save()
                payment.order.log_action('pretix.event.order.payment.failed', {
                    'local_id': payment.local_id,
                    'provider': payment.provider,
                    'info': str(charge)
                })
                raise PaymentException(_('Stripe reported an error: %s') % charge.failure_message)
Example #48
0
File: views.py Project: eteks/Adjod
def update_success(request, pk):
    updated_product = Product.objects.get(id=pk)
    print 'update_success', updated_product
    if request.method == 'POST':
        try:
            error = {}
            updated_product.category = Category.objects.get(
                id=request.POST['category_name'])
            updated_product.subcategory = SubCategory.objects.get(
                id=request.POST['subcategory_name'])
            if request.POST['brand_name']:
                updated_product.ad_brand = Dropdown.objects.get(
                    id=request.POST['brand_name'])
            else:
                updated_product.ad_brand = None
            updated_product.adtype = "sell"
            updated_product.title = request.POST.get('ad_title')
            updated_product.price = request.POST.get('your_price')
            updated_product.ad_year = request.POST.get('your_year')
            updated_product.description = request.POST.get('description')
            updated_product.you_are = request.POST.get('you_are_radio')
            updated_product.you_name = request.POST.get('your_name')
            updated_product.you_email = request.POST.get('your_email')
            updated_product.you_phone = request.POST.get('your_mobile_no')
            updated_product.city = City.objects.get(
                id=int(request.POST['your_city']))
            updated_product.locality = Locality.objects.get(
                id=request.POST['your_locality'])
            print 'updated_product.locality', updated_product.locality
            updated_product.country_code = request.COOKIES.get("country_code")
            # product.photos=request.FILES['photos']
            # if 'photos[]' in request.FILES:
            # 	photos =request.FILES.getlist('photos[]')
            # 	print 'photos>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', photos
            # 	updated_product.photos, updated_product.imagecount, updated_product.thumbnail = create_path_for_photos_thumbanails(photos, updated_product)
            # 	print 'image_receive', updated_product.photos
            # hidden_image_src = request.POST.get('hidden_image_src')
            # product_photos = ''
            # if request.FILES.getlist('photos[]'):
            photos_list = ''
            edit_hidden_photos = request.POST.get('edit_hidden_photos')
            edit_remove_photos = request.POST.get('edit_remove_photos')
            edit_hidden_photos_array = [
                n for n in str(edit_hidden_photos).split(',')
            ]
            edit_remove_photos_array = [
                n for n in str(edit_remove_photos).split(',')
            ]
            exists_photo_array = list(
                set(edit_hidden_photos_array) - set(edit_remove_photos_array))
            for e in exists_photo_array:
                if photos_list == '':
                    photos_list = photos_list + e
                else:
                    photos_list = photos_list + "," + e
            photos = request.FILES.getlist('photos[]')
            print 'photos>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', photos
            # updated_product.photos, updated_product.imagecount, updated_product.thumbnail = create_path_for_photos_thumbanails(photos, updated_product)
            updated_product.photos, updated_product.imagecount, updated_product.thumbnail = create_path_for_photos_thumbanails(
                photos, updated_product)
            if updated_product.photos and photos_list != '':
                updated_product.photos = photos_list + "," + str(
                    updated_product.photos)
            else:
                updated_product.photos = updated_product.photos
            updated_product.imagecount = len(
                [n for n in str(updated_product.photos).split(',')])
            # print 'image_receive', product_photos
            # if hidden_image_src != '' and product_photos != '':
            # 	updated_product.photos = str(hidden_image_src)+','+str(product_photos)
            # elif hidden_image_src !='' and product_photos == '':
            # 	updated_product.photos = str(hidden_image_src)
            # else:
            # 	updated_product.photos = product_photos

            updated_product.video = request.POST.get('video_url')
            updated_product.created_date = datetime.datetime.now()
            updated_product.modified_date = datetime.datetime.now()
            updated_product.expired_date = datetime.datetime.now(
            ) + datetime.timedelta(days=30)
            updated_product.status_isactive = True
            updated_product.post_terms = request.POST.get('terms_of_use')
            updated_product.save()
            # if request.user.is_authenticated():
            if request.POST.get('premium_plan'):
                plan_price = request.POST["premium_plan"]
                updated_product.premium_plan = PremiumPriceInfo.objects.get(
                    premium_price=plan_price)
                updated_product.ispremium = True
                updated_product_dict = {
                    'userprofile': updated_product.userprofile.id,
                    'category': updated_product.category,
                    'subcategory': updated_product.subcategory,
                    'adtype': updated_product.adtype,
                    'title': updated_product.title,
                    'photos': updated_product.photos,
                    'thumbnail': updated_product.thumbnail,
                    'imagecount': updated_product.imagecount,
                    'video': updated_product.video,
                    'condition': updated_product.condition,
                    'price': updated_product.price,
                    'ad_year': updated_product.ad_year,
                    'city': updated_product.city,
                    'locality': updated_product.locality,
                    'country_code': updated_product.country_code,
                    'description': updated_product.description,
                    'you_are': updated_product.you_are,
                    'you_name': updated_product.you_name,
                    'you_email': updated_product.you_email,
                    'you_phone': updated_product.you_phone,
                    'isregistered_user': updated_product.isregistered_user,
                    'ispremium': updated_product.ispremium,
                    'premium_plan': updated_product.premium_plan,
                    'expired_date': updated_product.expired_date,
                    'status_isactive': updated_product.status_isactive,
                    'post_term_status': updated_product.post_term_status,
                    "premium_plan": updated_product.premium_plan.id
                }
                response = paypal_transaction(request, updated_product_dict)
                return response

            # else:
            # 	response = None
            # 	print 'else paypal'
            # 	error['success'] = ugettext('Ad Successfully updated')
            # 	raise ValidationError(error['success'], 7)
            else:
                response = None
                print 'response in else view', response
                error['success'] = ugettext('Ad Successfully updated')
                raise ValidationError(error['success'], 7)
            updated_product.save()
            current_site = Site.objects.get_current()
            send_templated_mail(
                template_name='post_ad',
                from_email='*****@*****.**',
                recipient_list=[updated_product.you_email],
                context={
                    'subject': 'Alert Products',
                    'content': updated_product.title,
                    'user': updated_product.you_name,
                    'current_site': current_site,
                },
            )
            return response

        except ValidationError as e:
            messages.add_message(request, messages.ERROR, e.messages[-1])
            redirect_path = "/user_manage/"
            query_string = 'pt=%d' % e.code
            redirect_url = format_redirect_url(redirect_path, query_string)
            return HttpResponseRedirect(redirect_url)

    else:
        return HttpResponseRedirect("/user_manage/")
Example #49
0
def ParseAlert(xml_string, feed_type, alert_uuid):
    """Parses select fields from the CAP XML file at file_name.

  Primary use is intended for populating a feed <entry>.

  Note:
  - This code assumes the input alert XML has only one <info>.
  - The parsed XML does not contain all fields in the CAP specification.
  - The code accepts both complete and partial CAP messages.

  Args:
    xml_string: (string) Alert XML string.
    feed_type: (string) Alert feed representation (XML or HTML).
    alert_uuid: (string) Alert UUID.

  Returns:
    Dictionary.
    Keys/values corresponding to alert XML attributes or empty dictionary.
  """
    def GetFirstText(xml_element):
        """Returns the first text item from an XML element."""
        if xml_element and len(xml_element):
            return xml_element[0].text
        return ""

    def GetAllText(xml_element):
        """Returns an array of text items from multiple elements."""
        if xml_element and len(xml_element):
            return [item.text for item in xml_element]
        return []

    def GetNameValuePairs(xml_elements):
        """Returns a list of dictionaries for paired elements."""
        pair_list = []
        for xml_element in xml_elements:
            name_element, value_element = xml_element.getchildren()
            pair_list.append({
                "name": name_element.text,
                "value": value_element.text
            })
        return pair_list

    def GetCapElement(element_name, xml_tree):
        """Extracts elements from CAP XML tree."""
        element = "//p:" + element_name
        finder = lxml.etree.XPath(element, namespaces={"p": settings.CAP_NS})
        return finder(xml_tree)

    alert_dict = {}
    try:
        xml_tree = lxml.etree.fromstring(xml_string)
        expires_str = GetFirstText(GetCapElement("expires", xml_tree))

        # Extract the other needed values from the CAP XML.
        sender = GetFirstText(GetCapElement("sender", xml_tree))
        sender_name = GetFirstText(GetCapElement("senderName", xml_tree))
        name = sender
        if sender_name:
            name = name + ": " + sender_name

        title = GetFirstText(GetCapElement("headline", xml_tree))
        if not title:
            title = ugettext("Alert Message")  # Force a default.

        link = "%s%s" % (settings.SITE_URL,
                         reverse("alert", args=[alert_uuid, feed_type]))
        expires = parser.parse(expires_str) if expires_str else None
        sent_str = GetFirstText(GetCapElement("sent", xml_tree))
        sent = parser.parse(sent_str) if sent_str else None

        alert_dict = {
            "title": title,
            "event": GetFirstText(GetCapElement("event", xml_tree)),
            "link": link,
            "web": GetFirstText(GetCapElement("web", xml_tree)),
            "name": name,
            "sender": sender,
            "sender_name": sender_name,
            "expires": expires,
            "msg_type": GetFirstText(GetCapElement("msgType", xml_tree)),
            "references": GetFirstText(GetCapElement("references", xml_tree)),
            "alert_id": GetFirstText(GetCapElement("identifier", xml_tree)),
            "category": GetFirstText(GetCapElement("category", xml_tree)),
            "response_type":
            GetFirstText(GetCapElement("responseType", xml_tree)),
            "sent": sent,
            "description": GetFirstText(GetCapElement("description",
                                                      xml_tree)),
            "instruction": GetFirstText(GetCapElement("instruction",
                                                      xml_tree)),
            "urgency": GetFirstText(GetCapElement("urgency", xml_tree)),
            "severity": GetFirstText(GetCapElement("severity", xml_tree)),
            "certainty": GetFirstText(GetCapElement("certainty", xml_tree)),
            "language": GetFirstText(GetCapElement("language", xml_tree)),
            "parameters":
            GetNameValuePairs(GetCapElement("parameter", xml_tree)),
            "event_codes":
            GetNameValuePairs(GetCapElement("eventCode", xml_tree)),
            "area_desc": GetFirstText(GetCapElement("areaDesc", xml_tree)),
            "geocodes": GetNameValuePairs(GetCapElement("geocode", xml_tree)),
            "circles": GetAllText(GetCapElement("circle", xml_tree)),
            "polys": GetAllText(GetCapElement("polygon", xml_tree)),
        }
        # Non-CAP-compliant fields used for message templates.
        expiresDurationMinutes = GetFirstText(
            GetCapElement("expiresDurationMinutes", xml_tree))
        if expiresDurationMinutes:
            alert_dict["expiresDurationMinutes"] = expiresDurationMinutes
    # We don't expect any invalid XML alerts.
    except lxml.etree.XMLSyntaxError as e:
        logging.exception(e)
    return alert_dict
Example #50
0
    def _handle_payment_intent(self, request, payment, intent=None):
        self._init_api()

        try:
            if self.payment_is_valid_session(request):
                intent = stripe.PaymentIntent.create(
                    amount=self._get_amount(payment),
                    currency=self.event.currency.lower(),
                    payment_method=request.session['payment_stripe_payment_method_id'],
                    confirmation_method='manual',
                    confirm=True,
                    description='{event}-{code}'.format(
                        event=self.event.slug.upper(),
                        code=payment.order.code
                    ),
                    statement_descriptor=ugettext('{event}-{code}').format(
                        event=self.event.slug.upper(),
                        code=payment.order.code
                    )[:22],
                    metadata={
                        'order': str(payment.order.id),
                        'event': self.event.id,
                        'code': payment.order.code
                    },
                    # TODO: Is this sufficient?
                    idempotency_key=str(self.event.id) + payment.order.code + request.session['payment_stripe_payment_method_id'],
                    return_url=build_absolute_uri(self.event, 'plugins:stripe:sca.return', kwargs={
                        'order': payment.order.code,
                        'payment': payment.pk,
                        'hash': hashlib.sha1(payment.order.secret.lower().encode()).hexdigest(),
                    }),
                    **self.api_kwargs
                )
            else:
                payment_info = json.loads(payment.info)

                if 'id' in payment_info:
                    if not intent:
                        intent = stripe.PaymentIntent.retrieve(
                            payment_info['id'],
                            **self.api_kwargs
                        )
                else:
                    return

        except stripe.error.CardError as e:
            if e.json_body:
                err = e.json_body['error']
                logger.exception('Stripe error: %s' % str(err))
            else:
                err = {'message': str(e)}
                logger.exception('Stripe error: %s' % str(e))
            logger.info('Stripe card error: %s' % str(err))
            payment.info_data = {
                'error': True,
                'message': err['message'],
            }
            payment.state = OrderPayment.PAYMENT_STATE_FAILED
            payment.save()
            payment.order.log_action('pretix.event.order.payment.failed', {
                'local_id': payment.local_id,
                'provider': payment.provider,
                'message': err['message']
            })
            raise PaymentException(_('Stripe reported an error with your card: %s') % err['message'])

        except stripe.error.StripeError as e:
            if e.json_body and 'error' in e.json_body:
                err = e.json_body['error']
                logger.exception('Stripe error: %s' % str(err))
            else:
                err = {'message': str(e)}
                logger.exception('Stripe error: %s' % str(e))
            payment.info_data = {
                'error': True,
                'message': err['message'],
            }
            payment.state = OrderPayment.PAYMENT_STATE_FAILED
            payment.save()
            payment.order.log_action('pretix.event.order.payment.failed', {
                'local_id': payment.local_id,
                'provider': payment.provider,
                'message': err['message']
            })
            raise PaymentException(_('We had trouble communicating with Stripe. Please try again and get in touch '
                                     'with us if this problem persists.'))
        else:
            ReferencedStripeObject.objects.get_or_create(
                reference=intent.id,
                defaults={'order': payment.order, 'payment': payment}
            )
            if intent.status == 'requires_action':
                payment.info = str(intent)
                payment.state = OrderPayment.PAYMENT_STATE_CREATED
                payment.save()
                return build_absolute_uri(self.event, 'plugins:stripe:sca', kwargs={
                    'order': payment.order.code,
                    'payment': payment.pk,
                    'hash': hashlib.sha1(payment.order.secret.lower().encode()).hexdigest(),
                })

            if intent.status == 'requires_confirmation':
                payment.info = str(intent)
                payment.state = OrderPayment.PAYMENT_STATE_CREATED
                payment.save()
                self._confirm_payment_intent(request, payment)

            elif intent.status == 'succeeded' and intent.charges.data[-1].paid:
                try:
                    payment.info = str(intent)
                    payment.confirm()
                except Quota.QuotaExceededException as e:
                    raise PaymentException(str(e))

                except SendMailException:
                    raise PaymentException(_('There was an error sending the confirmation mail.'))
            elif intent.status == 'processing':
                if request:
                    messages.warning(request, _('Your payment is pending completion. We will inform you as soon as the '
                                                'payment completed.'))
                payment.info = str(intent)
                payment.state = OrderPayment.PAYMENT_STATE_PENDING
                payment.save()
                return
            elif intent.status == 'requires_payment_method':
                if request:
                    messages.warning(request, _('Your payment failed. Please try again.'))
                payment.info = str(intent)
                payment.state = OrderPayment.PAYMENT_STATE_FAILED
                payment.save()
                return
            else:
                logger.info('Charge failed: %s' % str(intent))
                payment.info = str(intent)
                payment.state = OrderPayment.PAYMENT_STATE_FAILED
                payment.save()
                payment.order.log_action('pretix.event.order.payment.failed', {
                    'local_id': payment.local_id,
                    'provider': payment.provider,
                    'info': str(intent)
                })
                raise PaymentException(_('Stripe reported an error: %s') % intent.last_payment_error.message)
Example #51
0
def parse_csv(myfile, newsletter, ignore_errors=False):
    import csv

    myreader = csv.reader(myfile)
    firstrow = myreader.next()

    # Find name column
    colnum = 0
    namecol = None
    for column in firstrow:
        if "name" in column.lower() or ugettext("name") in column.lower():
            namecol = colnum

            if "display" in column.lower() or ugettext(
                    "display") in column.lower():
                break

        colnum += 1

    if namecol is None:
        raise forms.ValidationError(
            _("Name column not found. The name of this column should be either 'name' or '%s'."
              ) % ugettext("name"))

    logger.debug("Name column found: '%s'" % firstrow[namecol])

    # Find email column
    colnum = 0
    mailcol = None
    for column in firstrow:
        if 'email' in column.lower() or 'e-mail' in column.lower() or ugettext(
                "e-mail") in column.lower():
            mailcol = colnum

            break

        colnum += 1

    if mailcol is None:
        raise forms.ValidationError(
            _("E-mail column not found. The name of this column should be either 'email', 'e-mail' or '%s'."
              ) % ugettext("e-mail"))

    logger.debug("E-mail column found: '%s'" % firstrow[mailcol])

    #assert namecol != mailcol, 'Name and e-mail column should not be the same.'
    if namecol == mailcol:
        raise forms.ValidationError(
            _("Could not properly determine the proper columns in the CSV-file. There should be a field called 'name' or '%(name)s' and one called 'e-mail' or '%(e-mail)s'."
              ) % {
                  "name": _("name"),
                  "e-mail": _("e-mail")
              })

    logger.debug('Extracting data.')

    addresses = {}
    for row in myreader:
        name = check_name(row[namecol], ignore_errors)
        email = check_email(row[mailcol], ignore_errors)

        logger.debug("Going to add %s <%s>" % (name, email))

        if email_re.search(email):
            addr = make_subscription(newsletter, email, name)
        elif not ignore_errors:
            raise forms.ValidationError(
                _("Entry '%s' does not contain a valid e-mail address.") %
                name)

        if addr:
            if addresses.has_key(email) and not ignore_errors:
                raise forms.ValidationError(
                    _("The address file contains duplicate entries for '%s'.")
                    % email)

            addresses.update({email: addr})
        elif not ignore_errors:
            raise forms.ValidationError(
                _("Some entries are already subscribed to."))

    return addresses
    def delete_on_cancel(self, request, plugin_id):
        # This view is responsible for deleting a plugin
        # bypassing the delete permissions.
        # We check for add permissions because this view is meant
        # only for plugins created through the ckeditor
        # and the ckeditor plugin itself.
        if not request.user.is_active and request.user.is_staff:
            message = ugettext("Unable to process your request. "
                               "You don't have the required permissions.")
            return HttpResponseForbidden(message)

        plugin_type = self.__class__.__name__
        plugins = (
            CMSPlugin
            .objects
            .select_related('placeholder', 'parent')
            .filter(plugin_type=plugin_type)
        )

        field = self.model._meta.pk

        try:
            object_id = field.to_python(unquote(plugin_id))
        except (ValidationError, ValueError):
            raise Http404('Invalid plugin id')

        text_plugin = get_object_or_404(plugins, pk=object_id)

        # This form validates the the given plugin is a child
        # of the text plugin or is a text plugin.
        # If the plugin is a child then we validate that this child
        # is not present in the text plugin (because then it's not a cancel).
        # If the plugin is a text plugin then we validate that the text
        # plugin does NOT have a real instance attached.
        form = DeleteOnCancelForm(
            request.POST,
            text_plugin=text_plugin,
        )

        if not form.is_valid():
            message = ugettext("Unable to process your request.")
            return HttpResponseBadRequest(message)

        text_plugin_class = text_plugin.get_plugin_class_instance()
        # The following is needed for permission checking
        text_plugin_class.opts = text_plugin_class.model._meta

        has_add_permission = text_plugin_class.has_add_permission(request)

        placeholder = text_plugin.placeholder

        if not (has_add_permission and
                placeholder.has_add_permission(request)):
            message = ugettext("Unable to process your request. "
                               "You don't have the required permissions.")
            return HttpResponseForbidden(message)
        elif form.is_valid_token(request.session.session_key):
            # Token is validated after checking permissions
            # to avoid non-auth users from triggering validation mechanism.
            form.delete()
            # 204 -> request was successful but no response returned.
            return HttpResponse(status=204)
        else:
            message = ugettext("Unable to process your request. Invalid token.")
            return HttpResponseBadRequest(message)
Example #53
0
    def __init__(self, course, editor_mode, *args, **kwargs):
        super(BatchIssueTicketsForm, self).__init__(*args, **kwargs)

        from course.utils import get_codemirror_widget
        cm_widget, cm_help_text = get_codemirror_widget(
            language_mode={
                "name": "markdown",
                "xml": True
            },
            dependencies=("xml", ),
            interaction_mode=editor_mode)

        help_text = (ugettext(
            "Enter <a href=\"http://documen.tician.de/"
            "relate/content.html#relate-markup\">"
            "RELATE markup</a> containing Django template statements to render "
            "your exam tickets. <tt>tickets</tt> contains a list of "
            "data structures "
            "containing ticket information. For each entry <tt>tkt</tt>  "
            "in this list, "
            "use <tt>{{ tkt.participation.user.user_name }}</tt>, "
            "<tt>{{ tkt.code }}</tt>, <tt>{{ tkt.exam.description }}</tt>, "
            "and <tt>{{ checkin_uri }}</tt> as placeholders. "
            "See the example for how to use this."))

        self.fields["exam"] = forms.ModelChoiceField(
            queryset=(Exam.objects.filter(course=course, active=True)),
            required=True,
            label=_("Exam"))

        self.fields["valid_start_time"] = forms.DateTimeField(
            label=_("Start validity"),
            widget=DateTimePicker(options={
                "format": "YYYY-MM-DD HH:mm",
                "sideBySide": True
            }),
            required=False)
        self.fields["valid_end_time"] = forms.DateTimeField(
            label=_("End validity"),
            widget=DateTimePicker(options={
                "format": "YYYY-MM-DD HH:mm",
                "sideBySide": True
            }),
            required=False)
        self.fields["restrict_to_facility"] = forms.CharField(
            label=_("Restrict to facility"),
            help_text=_(
                "If not blank, the exam ticket may only be used in the "
                "given facility"),
            required=False)

        self.fields["revoke_prior"] = forms.BooleanField(
            label=_("Revoke prior exam tickets"),
            required=False,
            initial=False)

        self.fields["format"] = forms.CharField(
            label=_("Ticket Format"),
            help_text=help_text,
            widget=cm_widget,
            initial=INITIAL_EXAM_TICKET_TEMPLATE,
            required=True)

        self.style_codemirror_widget()

        self.helper.add_input(Submit("issue", _("Issue tickets")))
Example #54
0
 def get_form_error(self):
     return ugettext("Please correct the duplicate values below.")
Example #55
0
 def save(self):
     self.account.language = self.cleaned_data["language"]
     self.account.save()
     self.user.message_set.create(
         message=ugettext(u"Language successfully updated."))
Example #56
0
def batch_issue_exam_tickets(pctx):
    if not pctx.has_permission(pperm.batch_issue_exam_ticket):
        raise PermissionDenied(_("may not batch-issue tickets"))

    form_text = ""

    request = pctx.request
    if request.method == "POST":
        form = BatchIssueTicketsForm(pctx.course, request.user.editor_mode,
                                     request.POST)

        if form.is_valid():
            exam = form.cleaned_data["exam"]

            from jinja2 import TemplateSyntaxError
            from course.content import markup_to_html
            try:
                with transaction.atomic():
                    if form.cleaned_data["revoke_prior"]:
                        ExamTicket.objects.filter(
                            exam=exam,
                            state__in=(
                                exam_ticket_states.valid,
                                exam_ticket_states.used,
                            )).update(state=exam_ticket_states.revoked)

                    tickets = []
                    for participation in (Participation.objects.filter(
                            course=pctx.course,
                            status=participation_status.active).order_by(
                                "user__last_name")):
                        ticket = ExamTicket()
                        ticket.exam = exam
                        ticket.participation = participation
                        ticket.creator = request.user
                        ticket.state = exam_ticket_states.valid
                        ticket.code = gen_ticket_code()
                        ticket.valid_start_time = \
                                form.cleaned_data["valid_start_time"]
                        ticket.valid_end_time = form.cleaned_data[
                            "valid_end_time"]
                        ticket.restrict_to_facility = \
                                form.cleaned_data["restrict_to_facility"]
                        ticket.save()

                        tickets.append(ticket)

                    checkin_uri = pctx.request.build_absolute_uri(
                        reverse("relate-check_in_for_exam"))
                    form_text = markup_to_html(pctx.course,
                                               pctx.repo,
                                               pctx.course_commit_sha,
                                               form.cleaned_data["format"],
                                               jinja_env={
                                                   "tickets": tickets,
                                                   "checkin_uri": checkin_uri,
                                               })
            except TemplateSyntaxError as e:
                messages.add_message(
                    request, messages.ERROR,
                    string_concat(_("Template rendering failed"),
                                  ": line %(lineno)d: %(err_str)s") % {
                                      "lineno": e.lineno,
                                      "err_str": e.message.decode("utf-8")
                                  })
            except Exception as e:
                messages.add_message(
                    request, messages.ERROR,
                    string_concat(_("Template rendering failed"),
                                  ": %(err_type)s: %(err_str)s") % {
                                      "err_type": type(e).__name__,
                                      "err_str": str(e)
                                  })
            else:
                messages.add_message(request, messages.SUCCESS,
                                     _("%d tickets issued.") % len(tickets))

    else:
        form = BatchIssueTicketsForm(pctx.course, request.user.editor_mode)

    return render_course_page(
        pctx, "course/batch-exam-tickets-form.html", {
            "form": form,
            "form_text": form_text,
            "form_description": ugettext("Batch-Issue Exam Tickets")
        })
Example #57
0
 def save(self):
     self.user.set_password(self.cleaned_data["password1"])
     self.user.save()
     self.user.message_set.create(
         message=ugettext(u"Password successfully set."))
Example #58
0
    def __get__(self, obj, typ=None):
        """
        Read the localised version of the field this descriptor emulates.
        First try to see if the localised field is really set.
        If not, then use ugettext_lazy to find a tranlation in the current language
        for this field.
        """
        # self must be returned in a getattr context.
        if obj is None:
            return self

        current_language = translation.get_language()
        real_field_name = get_real_fieldname(self.name, current_language)

        vo = GettextVO()

        # first check if the database contains the localized data
        vo.stored_value = getattr(obj, real_field_name)

        # the database does not have our localized data.
        # check if we have a translation, first get the msgid, as a unicode string.
        vo.msgid = get_localized_property(
            obj, self.name,
            getattr(settings, 'MSGID_LANGUAGE', settings.LANGUAGE_CODE))

        # check the translation in the current language
        # but avoid empty string and None
        if valid_for_gettext(vo.msgid):
            vo.msg = self.to_python(
                translation.ugettext(force_unicode(vo.msgid)))
        elif valid_for_gettext(vo.stored_value):
            # we can not use the msgid for gettext but we did find a valid
            # translation in the database. Fine we stop here and return that
            # value. No need for a standin, because we don't have a catalog value.
            return vo.stored_value
        else:
            # we can not use the msgid for gettext lookups, so there is no
            # point in trying. Check for fallback languages in database.
            vo.fallback = get_localized_property(obj, self.name)

            if not valid_for_gettext(vo.fallback):
                # Also if we are sure we don't have any old
                # translations in the catalog or something for the fallback
                # languages in the database, we do not need to return a standin either
                return vo.msgid

        # we got here so we've got a valid messageid. Now collect data from the catalog(s)

        # if there isn't anything new in the catalog belonging to the current language:
        if vo.msg == vo.msgid:
            # maybe we have a translation in any of the fallback languages.
            if hasattr(settings, 'FALLBACK_LANGUAGES'):
                # first check if the database has the localized data in
                # any of the fallback languages.
                vo.fallback = get_localized_property(obj, self.name)

                # if the fallback is the same as the msgid, go and look in the catalog
                if vo.fallback == vo.msgid:
                    # there might be a translation in any
                    # of the fallback languages.
                    for fallback in get_fallback_languages():
                        catalog = translation_catalogs(fallback)
                        msg = catalog.ugettext(force_unicode(vo.msgid))
                        if self.to_python(msg) != vo.msgid:
                            vo.fallback = self.to_python(msg)
                            break
                elif vo.fallback:
                    # if a valid fallback is found, then, since the msg is equal
                    # to the msgid, the fallback is the winner.
                    vo.msg = vo.fallback

        # if we came here we collected data from the catalog and we should return
        # a standin. A standin is the return value, with some extra properties.
        # see GettextVO for the extra properties added.
        if valid_for_gettext(vo.stored_value):
            vo.standin_value_is_from_database = True
            # database always wins
            return standin_for(vo.stored_value, **vo.__dict__)
        elif valid_for_gettext(vo.msg):
            # runner up is the translation in the native language
            return standin_for(vo.msg, **vo.__dict__)
        elif valid_for_gettext(vo.fallback):
            # and last is the translation in a fallback language
            return standin_for(vo.fallback, **vo.__dict__)

        assert (valid_for_gettext(vo.msgid))

        # there is a very very small probability that the translation of
        # a valid msgid evaluates to empty string or None (after to_python).
        # If that happened, we got here. I choose to return None, because i like
        # to be like that
        return None
Example #59
0
 def save(self):
     self.user.message_set.create(
         message=ugettext(u"Confirmation email sent to %(email)s") %
         {'email': self.cleaned_data["email"]})
     return EmailAddress.objects.add_email(self.user,
                                           self.cleaned_data["email"])
Example #60
0
 def save(self):
     self.account.timezone = self.cleaned_data["timezone"]
     self.account.save()
     self.user.message_set.create(
         message=ugettext(u"Timezone successfully updated."))