]> git.openstreetmap.org Git - osqa.git/blob - forum/views/users.py
It is now possable for users to add tags like "REP_TO_VOTE_UP" to the faq page and...
[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 forum.authentication import user_updated\r
19 from datetime import date\r
20 import decorators\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 @login_required\r
75 def moderate_user(request, id):\r
76     """ajax handler of user moderation\r
77     """\r
78     if not request.user.is_superuser or request.method != 'POST':\r
79         raise Http404\r
80     if not request.is_ajax():\r
81         return HttpResponseForbidden(mimetype="application/json")\r
82 \r
83     user = get_object_or_404(User, id=id)\r
84     form = ModerateUserForm(request.POST, instance=user)\r
85 \r
86     if form.is_valid():\r
87         form.save()\r
88         logging.debug('data saved')\r
89         response = HttpResponse(simplejson.dumps(''), mimetype="application/json")\r
90     else:\r
91         response = HttpResponseForbidden(mimetype="application/json")\r
92     return response\r
93 \r
94 def set_new_email(user, new_email, nomessage=False):\r
95     if new_email != user.email:\r
96         user.email = new_email\r
97         user.email_isvalid = False\r
98         user.save()\r
99         #if settings.EMAIL_VALIDATION == 'on':\r
100         #    send_new_email_key(user,nomessage=nomessage)    \r
101 \r
102 @login_required\r
103 def edit_user(request, id):\r
104     user = get_object_or_404(User, id=id)\r
105     if request.user != user:\r
106         raise Http404\r
107     if request.method == "POST":\r
108         form = EditUserForm(user, request.POST)\r
109         if form.is_valid():\r
110             new_email = sanitize_html(form.cleaned_data['email'])\r
111 \r
112             set_new_email(user, new_email)\r
113 \r
114             #user.username = sanitize_html(form.cleaned_data['username'])\r
115             user.real_name = sanitize_html(form.cleaned_data['realname'])\r
116             user.website = sanitize_html(form.cleaned_data['website'])\r
117             user.location = sanitize_html(form.cleaned_data['city'])\r
118             user.date_of_birth = sanitize_html(form.cleaned_data['birthday'])\r
119             if user.date_of_birth == "None":\r
120                 user.date_of_birth = '1900-01-01'\r
121             user.about = sanitize_html(form.cleaned_data['about'])\r
122 \r
123             user.save()\r
124             # send user updated signal if full fields have been updated\r
125             if user.email and user.real_name and user.website and user.location and \\r
126                 user.date_of_birth and user.about:\r
127                 user_updated.send(sender=user.__class__, instance=user, updated_by=user)\r
128             return HttpResponseRedirect(user.get_profile_url())\r
129     else:\r
130         form = EditUserForm(user)\r
131     return render_to_response('users/edit.html', {\r
132                                                 'form' : form,\r
133                                                 'gravatar_faq_url' : reverse('faq') + '#gravatar',\r
134                                     }, context_instance=RequestContext(request))\r
135 \r
136 \r
137 \r
138 def user_view(template, tab_name, tab_description, page_title, private=False):\r
139     def decorator(fn):\r
140         def decorated(request, id, slug=None):\r
141             user = get_object_or_404(User, id=id)\r
142             if private and not user == request.user:\r
143                 return HttpResponseForbidden()\r
144             context = fn(request, user)\r
145             context.update({\r
146                 "tab_name" : tab_name,\r
147                 "tab_description" : tab_description,\r
148                 "page_title" : page_title,\r
149             })\r
150             return render_to_response(template, context, context_instance=RequestContext(request))\r
151         return decorated\r
152     return decorator\r
153 \r
154 \r
155 @user_view('users/stats.html', 'stats', _('user profile'), _('user profile overview'))\r
156 def user_stats(request, user):\r
157     questions = Question.objects.filter(author=user, deleted=False).order_by('-added_at')\r
158     answers = Answer.objects.filter(author=user, deleted=False).order_by('-added_at')\r
159 \r
160     up_votes = user.get_up_vote_count()\r
161     down_votes = user.get_down_vote_count()\r
162     votes_today = user.get_vote_count_today()\r
163     votes_total = int(settings.MAX_VOTES_PER_DAY)\r
164 \r
165     user_tags = Tag.objects.filter(Q(nodes__author=user) | Q(nodes__children__author=user)) \\r
166         .annotate(user_tag_usage_count=Count('name')).order_by('-user_tag_usage_count')\r
167 \r
168     awards = Badge.objects.filter(award_badge__user=user).annotate(count=Count('name')).order_by('-count')\r
169 \r
170     if request.user.is_superuser:\r
171         moderate_user_form = ModerateUserForm(instance=user)\r
172     else:\r
173         moderate_user_form = None\r
174 \r
175     return {'moderate_user_form': moderate_user_form,\r
176             "view_user" : user,\r
177             "questions" : questions,\r
178             "answers" : answers,\r
179             "up_votes" : up_votes,\r
180             "down_votes" : down_votes,\r
181             "total_votes": up_votes + down_votes,\r
182             "votes_today_left": votes_total-votes_today,\r
183             "votes_total_per_day": votes_total,\r
184             "user_tags" : user_tags[:50],\r
185             "awards": awards,\r
186             "total_awards" : awards.count(),\r
187         }\r
188 \r
189 @user_view('users/recent.html', 'recent', _('recent user activity'), _('profile - recent activity'))\r
190 def user_recent(request, user):\r
191     activities = Activity.objects.filter(activity_type__in=(TYPE_ACTIVITY_PRIZE,\r
192             TYPE_ACTIVITY_ASK_QUESTION, TYPE_ACTIVITY_ANSWER,\r
193             TYPE_ACTIVITY_COMMENT_QUESTION, TYPE_ACTIVITY_COMMENT_ANSWER,\r
194             TYPE_ACTIVITY_MARK_ANSWER), user=user).order_by('-active_at')[:USERS_PAGE_SIZE]\r
195 \r
196     return {"view_user" : user, "activities" : activities}\r
197 \r
198 \r
199 @user_view('users/votes.html', 'votes', _('user vote record'), _('profile - votes'), True)\r
200 def user_votes(request, user):\r
201     votes = user.votes.exclude(node__deleted=True).order_by('-voted_at')[:USERS_PAGE_SIZE]\r
202 \r
203     return {"view_user" : user, "votes" : votes}\r
204 \r
205 \r
206 @user_view('users/reputation.html', 'reputation', _('user reputation in the community'), _('profile - user reputation'))\r
207 def user_reputation(request, user):\r
208     reputation = user.reputes.order_by('-reputed_at')\r
209 \r
210     graph_data = simplejson.dumps([\r
211             (time.mktime(rep.reputed_at.timetuple()) * 1000, rep.reputation)\r
212             for rep in reputation\r
213     ])\r
214 \r
215     return {"view_user": user, "reputation": reputation, "graph_data": graph_data}\r
216 \r
217 @user_view('users/questions.html', 'favorites', _('favorite questions'),  _('profile - favorite questions'), True)\r
218 def user_favorites(request, user):\r
219     questions = user.favorite_questions.filter(deleted=False)\r
220 \r
221     return {"questions" : questions, "view_user" : user}\r
222 \r
223 @user_view('users/subscriptions.html', 'subscriptions', _('subscription settings'), _('profile - subscriptions'), True)\r
224 def user_subscriptions(request, user):\r
225     if request.method == 'POST':\r
226         form = SubscriptionSettingsForm(request.POST)\r
227 \r
228         if 'notswitch' in request.POST:\r
229             user.subscription_settings.enable_notifications = not user.subscription_settings.enable_notifications\r
230             user.subscription_settings.save()\r
231 \r
232             if user.subscription_settings.enable_notifications:\r
233                 request.user.message_set.create(message=_('Notifications are now enabled'))\r
234             else:\r
235                 request.user.message_set.create(message=_('Notifications are now disabled'))\r
236         else:\r
237             form.is_valid()\r
238             for k,v in form.cleaned_data.items():\r
239                 setattr(user.subscription_settings, k, v)\r
240 \r
241             user.subscription_settings.save()\r
242             request.user.message_set.create(message=_('New subscription settings are now saved'))\r
243     else:\r
244         form = SubscriptionSettingsForm(user.subscription_settings.__dict__)\r
245 \r
246     notificatons_on = user.subscription_settings.enable_notifications\r
247 \r
248     return {'view_user':user, 'notificatons_on': notificatons_on, 'form':form}\r
249 \r
250 @login_required\r
251 def account_settings(request):\r
252     logging.debug('')\r
253     msg = request.GET.get('msg', '')\r
254     is_openid = False\r
255 \r
256     return render_to_response('account_settings.html', {\r
257         'msg': msg,\r
258         'is_openid': is_openid\r
259         }, context_instance=RequestContext(request))\r
260 \r