]> git.openstreetmap.org Git - osqa.git/blob - forum/views/users.py
Bad url reverse causing 500 on temporary signin.
[osqa.git] / forum / views / users.py
1 from django.contrib.auth.decorators import login_required\r
2 from forum.models import User\r
3 from django.db.models import Q, Count\r
4 from django.core.paginator import Paginator, EmptyPage, InvalidPage\r
5 from django.template.defaultfilters import slugify\r
6 from django.contrib.contenttypes.models import ContentType\r
7 from django.core.urlresolvers import reverse\r
8 from django.shortcuts import render_to_response, get_object_or_404\r
9 from django.template import RequestContext\r
10 from django.http import HttpResponse, HttpResponseForbidden, HttpResponseRedirect, Http404\r
11 from django.utils.translation import ugettext as _\r
12 from django.utils.http import urlquote_plus\r
13 from django.utils.html import strip_tags\r
14 from django.utils import simplejson\r
15 from django.core.urlresolvers import reverse\r
16 from forum.forms import *\r
17 from forum.utils.html import sanitize_html\r
18 from datetime import date\r
19 import decorators\r
20 from forum.actions import EditProfileAction, FavoriteAction, BonusRepAction\r
21 \r
22 import time\r
23 \r
24 USERS_PAGE_SIZE = 35# refactor - move to some constants file\r
25 \r
26 def users(request):\r
27     is_paginated = True\r
28     sortby = request.GET.get('sort', 'reputation')\r
29     suser = request.REQUEST.get('q',  "")\r
30     try:\r
31         page = int(request.GET.get('page', '1'))\r
32     except ValueError:\r
33         page = 1\r
34 \r
35     if suser == "":\r
36         if sortby == "newest":\r
37             objects_list = Paginator(User.objects.all().order_by('-date_joined'), USERS_PAGE_SIZE)\r
38         elif sortby == "last":\r
39             objects_list = Paginator(User.objects.all().order_by('date_joined'), USERS_PAGE_SIZE)\r
40         elif sortby == "user":\r
41             objects_list = Paginator(User.objects.all().order_by('username'), USERS_PAGE_SIZE)\r
42         # default\r
43         else:\r
44             objects_list = Paginator(User.objects.all().order_by('-reputation'), USERS_PAGE_SIZE)\r
45         base_url = reverse('users') + '?sort=%s&' % sortby\r
46     else:\r
47         sortby = "reputation"\r
48         objects_list = Paginator(User.objects.filter(username__icontains=suser).order_by('-reputation'), USERS_PAGE_SIZE)\r
49         base_url = reverse('users') + '?name=%s&sort=%s&' % (suser, sortby)\r
50 \r
51     try:\r
52         users = objects_list.page(page)\r
53     except (EmptyPage, InvalidPage):\r
54         users = objects_list.page(objects_list.num_pages)\r
55 \r
56     return render_to_response('users/users.html', {\r
57                                 "users" : users,\r
58                                 "suser" : suser,\r
59                                 "keywords" : suser,\r
60                                 "tab_id" : sortby,\r
61                                 "context" : {\r
62                                     'is_paginated' : is_paginated,\r
63                                     'pages': objects_list.num_pages,\r
64                                     'page': page,\r
65                                     'has_previous': users.has_previous(),\r
66                                     'has_next': users.has_next(),\r
67                                     'previous': users.previous_page_number(),\r
68                                     'next': users.next_page_number(),\r
69                                     'base_url' : base_url\r
70                                 }\r
71 \r
72                                 }, context_instance=RequestContext(request))\r
73 \r
74 def set_new_email(user, new_email, nomessage=False):\r
75     if new_email != user.email:\r
76         user.email = new_email\r
77         user.email_isvalid = False\r
78         user.save()\r
79         #if settings.EMAIL_VALIDATION == 'on':\r
80         #    send_new_email_key(user,nomessage=nomessage)    \r
81 \r
82 @login_required\r
83 def edit_user(request, id):\r
84     user = get_object_or_404(User, id=id)\r
85     if not (request.user.is_superuser or request.user == user):\r
86         return HttpResponseForbidden()\r
87     if request.method == "POST":\r
88         form = EditUserForm(user, request.POST)\r
89         if form.is_valid():\r
90             new_email = sanitize_html(form.cleaned_data['email'])\r
91 \r
92             set_new_email(user, new_email)\r
93 \r
94             if settings.EDITABLE_SCREEN_NAME:\r
95                 user.username = sanitize_html(form.cleaned_data['username'])\r
96             user.real_name = sanitize_html(form.cleaned_data['realname'])\r
97             user.website = sanitize_html(form.cleaned_data['website'])\r
98             user.location = sanitize_html(form.cleaned_data['city'])\r
99             user.date_of_birth = sanitize_html(form.cleaned_data['birthday'])\r
100             if user.date_of_birth == "None":\r
101                 user.date_of_birth = '1900-01-01'\r
102             user.about = sanitize_html(form.cleaned_data['about'])\r
103 \r
104             user.save()\r
105             EditProfileAction(user=user, ip=request.META['REMOTE_ADDR']).save()\r
106 \r
107             return HttpResponseRedirect(user.get_profile_url())\r
108     else:\r
109         form = EditUserForm(user)\r
110     return render_to_response('users/edit.html', {\r
111                                                 'user': user,\r
112                                                 'form' : form,\r
113                                                 'gravatar_faq_url' : reverse('faq') + '#gravatar',\r
114                                     }, context_instance=RequestContext(request))\r
115 \r
116 \r
117 @login_required\r
118 def user_powers(request, id, action, status):\r
119     if not request.user.is_superuser:\r
120         return HttpResponseForbidden()\r
121 \r
122     user = get_object_or_404(User, id=id)\r
123     new_state = action == 'grant'\r
124 \r
125     if status == 'super':\r
126         user.is_superuser = new_state\r
127     elif status == 'staff':\r
128         user.is_staff = new_state\r
129     else:\r
130         raise Http404()\r
131 \r
132     user.save()    \r
133     return HttpResponseRedirect(user.get_profile_url())\r
134 \r
135 \r
136 @decorators.command\r
137 def award_points(request, id):\r
138     if (not request.POST) and request.POST.get('points', None):\r
139         raise decorators.CommandException(_("Invalid request type"))\r
140 \r
141     if not request.user.is_superuser:\r
142         raise decorators.CommandException(_("Only superusers are allowed to award reputation points"))\r
143 \r
144     user = get_object_or_404(User, id=id)\r
145     points = int(request.POST['points'])\r
146 \r
147     extra = dict(message=request.POST.get('message', ''), awarding_user=request.user.id, value=points)\r
148 \r
149     BonusRepAction(user=user, extra=extra).save(data=dict(value=points))\r
150 \r
151     return dict(reputation=user.reputation)\r
152 \r
153 \r
154 def user_view(template, tab_name, tab_description, page_title, private=False):\r
155     def decorator(fn):\r
156         def decorated(request, id, slug=None):\r
157             user = get_object_or_404(User, id=id)\r
158             if private and not (user == request.user or request.user.is_superuser):\r
159                 return HttpResponseForbidden()\r
160             context = fn(request, user)\r
161 \r
162             rev_page_title = user.username + " - " + page_title\r
163 \r
164             context.update({\r
165                 "tab_name" : tab_name,\r
166                 "tab_description" : tab_description,\r
167                 "page_title" : rev_page_title,\r
168                 "can_view_private": (user == request.user) or request.user.is_superuser\r
169             })\r
170             return render_to_response(template, context, context_instance=RequestContext(request))\r
171         return decorated\r
172     return decorator\r
173 \r
174 \r
175 @user_view('users/stats.html', 'stats', _('user profile'), _('user overview'))\r
176 def user_stats(request, user):\r
177     questions = Question.objects.filter(author=user, deleted=None).order_by('-added_at')\r
178     answers = Answer.objects.filter(author=user, deleted=None).order_by('-added_at')\r
179 \r
180     up_votes = user.vote_up_count\r
181     down_votes = user.vote_down_count\r
182     votes_today = user.get_vote_count_today()\r
183     votes_total = int(settings.MAX_VOTES_PER_DAY)\r
184 \r
185     user_tags = Tag.objects.filter(Q(nodes__author=user) | Q(nodes__children__author=user)) \\r
186         .annotate(user_tag_usage_count=Count('name')).order_by('-user_tag_usage_count')\r
187 \r
188     awards = [(Badge.objects.get(id=b['id']), b['count']) for b in\r
189             Badge.objects.filter(awards__user=user).values('id').annotate(count=Count('cls')).order_by('-count')]\r
190 \r
191     return {\r
192             "view_user" : user,\r
193             "questions" : questions,\r
194             "answers" : answers,\r
195             "up_votes" : up_votes,\r
196             "down_votes" : down_votes,\r
197             "total_votes": up_votes + down_votes,\r
198             "votes_today_left": votes_total-votes_today,\r
199             "votes_total_per_day": votes_total,\r
200             "user_tags" : user_tags[:50],\r
201             "awards": awards,\r
202             "total_awards" : len(awards),\r
203         }\r
204 \r
205 @user_view('users/recent.html', 'recent', _('recent user activity'), _('recent activity'))\r
206 def user_recent(request, user):\r
207     activities = user.actions.exclude(action_type__in=("voteup", "votedown", "voteupcomment", "flag")).order_by('-action_date')[:USERS_PAGE_SIZE]\r
208 \r
209     return {"view_user" : user, "activities" : activities}\r
210 \r
211 \r
212 @user_view('users/votes.html', 'votes', _('user vote record'), _('votes'), True)\r
213 def user_votes(request, user):\r
214     votes = user.votes.filter(node__deleted=None, node__node_type__in=("question", "answer")).order_by('-voted_at')[:USERS_PAGE_SIZE]\r
215 \r
216     return {"view_user" : user, "votes" : votes}\r
217 \r
218 \r
219 @user_view('users/reputation.html', 'reputation', _('user reputation in the community'), _('user reputation'))\r
220 def user_reputation(request, user):\r
221     rep = list(user.reputes.order_by('date'))\r
222     values = [r.value for r in rep]\r
223     redux = lambda x, y: x+y     \r
224 \r
225     graph_data = simplejson.dumps([\r
226             (time.mktime(rep[i].date.timetuple()) * 1000, reduce(redux, values[:i], 0))\r
227             for i in range(len(values))\r
228     ])\r
229 \r
230     rep = user.reputes.filter(action__canceled=False).order_by('-date')[0:20]\r
231     \r
232     return {"view_user": user, "reputation": rep, "graph_data": graph_data}\r
233 \r
234 @user_view('users/questions.html', 'favorites', _('favorite questions'),  _('favorite questions'))\r
235 def user_favorites(request, user):\r
236     favorites = FavoriteAction.objects.filter(user=user)\r
237 \r
238     return {"favorites" : favorites, "view_user" : user}\r
239 \r
240 @user_view('users/subscriptions.html', 'subscriptions', _('subscription settings'), _('subscriptions'), True)\r
241 def user_subscriptions(request, user):\r
242     if request.method == 'POST':\r
243         form = SubscriptionSettingsForm(request.POST)\r
244 \r
245         if 'notswitch' in request.POST:\r
246             user.subscription_settings.enable_notifications = not user.subscription_settings.enable_notifications\r
247             user.subscription_settings.save()\r
248 \r
249             if user.subscription_settings.enable_notifications:\r
250                 request.user.message_set.create(message=_('Notifications are now enabled'))\r
251             else:\r
252                 request.user.message_set.create(message=_('Notifications are now disabled'))\r
253         else:\r
254             form.is_valid()\r
255             for k,v in form.cleaned_data.items():\r
256                 setattr(user.subscription_settings, k, v)\r
257 \r
258             user.subscription_settings.save()\r
259             request.user.message_set.create(message=_('New subscription settings are now saved'))\r
260     else:\r
261         form = SubscriptionSettingsForm(user.subscription_settings.__dict__)\r
262 \r
263     notificatons_on = user.subscription_settings.enable_notifications\r
264 \r
265     return {'view_user':user, 'notificatons_on': notificatons_on, 'form':form}\r
266 \r
267 @login_required\r
268 def account_settings(request):\r
269     logging.debug('')\r
270     msg = request.GET.get('msg', '')\r
271     is_openid = False\r
272 \r
273     return render_to_response('account_settings.html', {\r
274         'msg': msg,\r
275         'is_openid': is_openid\r
276         }, context_instance=RequestContext(request))\r
277 \r