Commits

Hiroshi Funai committed 7068ae5

added madrix

Comments (0)

Files changed (99)

django/madrix/.hgignore

+syntax: glob
+
+local_settings.py
+media/store
+contrib/qrcode_data
+django

django/madrix/__init__.py

Empty file added.

django/madrix/account/__init__.py

Empty file added.

django/madrix/account/admin.py

+from django.contrib import admin
+
+from account.models import UserProfile
+
+class UserProfileAdmin(admin.ModelAdmin):
+    list_display = ('user', 'plan')
+
+admin.site.register(UserProfile, UserProfileAdmin)

django/madrix/account/forms.py

+# vim: fileencoding=utf8
+
+import re
+from datetime import datetime
+
+from django import forms
+from django.contrib.auth.models import User
+
+from account.models import UserProfile, PLAN
+
+nickname_re = re.compile(ur'^[一-龠ーぁ-ヶa-zA-Z0-9]{1,30}$')
+
+class SignupForm(forms.ModelForm):
+    nickname = forms.CharField(label=u'お名前(会社名)')
+    password = forms.CharField(label=u'パスワード', widget=forms.PasswordInput)
+    password2 = forms.CharField(label=u'パスワード確認', widget=forms.PasswordInput)
+    email = forms.EmailField(label=u'メールアドレス')
+    plan = forms.CharField(label=u'プラン', widget=forms.Select(choices=PLAN))
+    agree = forms.CharField(label=u'利用規約に同意する', widget=forms.CheckboxInput)
+
+    def clean_nickname(self):
+        if not nickname_re.search(self.cleaned_data['nickname']):
+            raise forms.ValidationError(u'1文字以上30文字以内で入力してください。')
+        try:
+            profile = UserProfile.objects.get(nickname=self.cleaned_data['nickname'])
+        except:
+            return self.cleaned_data['nickname']
+        raise forms.ValidationError(u'入力されたユーザ名はすでに使用されています。')
+
+    def clean_email(self):
+        try:
+            user = User.objects.get(email=self.cleaned_data['email'])
+        except:
+            return self.cleaned_data['email']
+        raise forms.ValidationError(u'入力されたメールアドレスは無効です。')
+
+    def clean_agree(self):
+        if self.cleaned_data['agree'] == 'False':
+            raise forms.ValidationError(u'規約に同意してください。')
+
+    def clean(self):
+        if self.cleaned_data.has_key('password') and self.cleaned_data.has_key('password2'):
+            if self.cleaned_data['password'] != self.cleaned_data['password2']:
+                raise forms.ValidationError(u'2カ所に異なったパスワードが入力されています。')
+        if self.cleaned_data.has_key('year') and self.cleaned_data.has_key('month') and self.cleaned_data.has_key('day'):
+            try:
+                birthday = datetime(self.cleaned_data['year'],self.cleaned_data['month'],self.cleaned_data['day'])
+            except ValueError, e:
+                raise forms.ValidationError(u'正しい日付を入力してください。')
+            except Exception, e:
+                raise forms.ValidationError(e)
+        return self.cleaned_data
+
+    class Meta:
+        model = UserProfile
+        exclude = ('user', 'plan', 'activation')
+
+
+class LoginForm(forms.Form):
+    username = forms.CharField(label=u'メールアドレス',
+        widget=forms.TextInput(attrs={
+            'class': 'text-box',
+            'maxlength': 75
+        }))
+    password = forms.Field(label=u'パスワード',
+        widget=forms.PasswordInput(attrs={'class': 'text-box'}))

django/madrix/account/models.py

+#vim: fileencoding=utf8
+from django.contrib.auth.models import User
+from django.db import models
+
+
+PLAN = (
+    (0, u'フリー'),
+    (1, u'個人 ビギナー'),
+    (2, u'個人 スタンダード'),
+    (3, u'個人 プロ'),
+    (4, u'法人 ビギナー'),
+    (5, u'法人 スタンダード'),
+    (6, u'法人 プロ'),
+)
+
+DISK_AVAILABLE = (
+    10,
+    100,
+    200,
+    500,
+    500,
+    1000,
+    2000,
+)
+
+PLAN_FEE = (
+    0,
+    3000,
+    5000,
+    10000,
+    30000,
+    50000,
+    100000,
+)
+
+class UserProfile(models.Model):
+    user = models.ForeignKey(User)
+    plan = models.IntegerField(choices=PLAN)
+    activation = models.CharField(max_length=50, blank=True)
+
+    class Meta:
+        verbose_name = verbose_name_plural = u'プロフィール'
+
+    def __unicode__(self):
+        return self.user.username
+
+    def get_nickname(self):
+        return self.user.first_name
+    nickname = property(get_nickname)
+
+    def get_fee(self):
+        return PLAN_FEE[self.plan]
+    fee = property(get_fee)

django/madrix/account/views.py

+#vim: fileencoding=utf8
+from email.Header import Header
+from datetime import datetime
+import random
+import string
+
+from django.contrib.auth.models import User
+from django.contrib.auth.decorators import login_required
+from django.contrib.auth import authenticate, login, logout
+from django.core.urlresolvers import reverse
+from django.core.mail import SMTPConnection
+from django.conf import settings
+from django.http import HttpResponse, HttpResponseRedirect
+from django.shortcuts import render_to_response
+from django.template import Context, RequestContext, loader, TemplateDoesNotExist
+from django.template.loader import get_template, render_to_string, get_template_from_string
+
+from util.mail import FixedEmailMessage as EmailMessage
+
+
+def signup(request):
+    """User SignUp Form"""
+
+    dictionary = {}
+    template = 'signup.html'
+
+    if request.method == 'POST':
+        request.logger.debug('SignUp Form posted')
+
+        form = SignUpForm(request.POST)
+        if form.is_valid():
+            if request.POST.has_key('signup'):
+                # SignUp Success
+                request.logger.debug('SignUp Form confirmed')
+
+                # Activation Code
+                chars = string.digits + string.ascii_lowercase
+                activation_code = ''.join([random.choice(chars) for x in range(30)])
+
+                # Create New User
+                try:
+                    new_user = User.objects.create_user(
+                        username = form.cleaned_data['username'],
+                        email = form.cleaned_data['email'],
+                        password = form.cleaned_data['password'],
+                    )
+                except Exception, e:
+                    request.logger.error(e)
+
+                # $BEPO?40N;;~$K%a!<%kAw?.$9$k$?$a$K%Q%9%o!<%I$r%;%C%7%g%s$KJ];}(B
+                request.session['password'] = form.cleaned_data['password']
+
+                new_user.first_name = form.cleaned_data['first_name']
+                new_user.last_name = activation_code
+                new_user.is_active = False
+                new_user.save()
+
+                # Send an email when complete
+                s = render_to_string('email/signup_subject.txt')
+                h = Header(s, 'ISO-2022-JP').encode()
+                subject = ''.join(h.splitlines())
+
+                body_context=Context({
+                    'data': form.cleaned_data,
+                    'activation_code': activation_code,
+                })
+                body = render_to_string('email/signup_body.txt', body_context)
+
+                connection = SMTPConnection()
+                connection.host = settings.SMTP_HOST
+                connection.port = settings.SMTP_PORT
+                email = EmailMessage(
+                    subject=subject,
+                    body=body.encode('iso-2022-jp'),
+                    from_email=settings.SITE_ADMIN_EMAIL,
+                    to=[form.cleaned_data['email']],
+                    bcc=[settings.SITE_ADMIN_EMAIL],
+                    connection=connection,
+                    headers={}
+                )
+                email.encoding = settings.EMAIL_ENCODING
+                email.send()
+                #--------------------------------------------------------------
+                return HttpResponseRedirect(reverse('signup_activation'))
+            elif request.POST.has_key('confirm'):
+                # Confirmation
+                request.logger.debug('SignUp Form Confirmation')
+                template = 'signup_confirm.html'
+                dictionary['form'] = form
+                dictionary['cleaned_data'] = form.cleaned_data
+            else:
+                dictionary['form'] = form
+        else:
+            # Validation Error
+            request.logger.debug('SignUp Form Validation Error')
+            dictionary['form'] = form
+
+    # Request Method `GET` or Edit
+    elif request.method == 'GET':
+        dictionary['form'] = SignUpForm()
+
+    return render_to_response(template,
+                              dictionary,
+                              context_instance=RequestContext(
+                                request,
+                                {'HTTP_USER_AGENT': request.META['HTTP_USER_AGENT']}
+                              ))
+
+def signup_activation(request):
+    """Sign Up Activation"""
+    dictionary = {}
+
+    return render_to_response('signup_activation.html',
+                              dictionary,
+                              context_instance=RequestContext(
+                                request,
+                                {'HTTP_USER_AGENT': request.META['HTTP_USER_AGENT']}
+                              ))
+
+def signup_done(request, activation_code):
+    """Sign Up Completed"""
+    dictionary = {}
+    template = 'signup_done.html'
+    try:
+        user = User.objects.get(last_name=activation_code)
+        user.is_active = True
+        user.last_name = ''
+        user.save()
+        user.backend = "%s.%s" % ('django.contrib.auth.backends', 'ModelBackend')
+        login(request, user)
+
+        # Send an email when complete
+        s = render_to_string('email/signup_complete_subject.txt')
+        h = Header(s, 'ISO-2022-JP').encode()
+        subject = ''.join(h.splitlines())
+
+        body_context=Context({
+            'user': user,
+            'password': request.session['password']
+        })
+        body = render_to_string('email/signup_complete_body.txt', body_context)
+
+        connection = SMTPConnection()
+        connection.host = settings.SMTP_HOST
+        connection.port = settings.SMTP_PORT
+        email = EmailMessage(
+            subject=subject,
+            body=body.encode('iso-2022-jp'),
+            from_email=settings.SITE_ADMIN_EMAIL,
+            to=[user.email],
+            bcc=[settings.SITE_ADMIN_EMAIL],
+            connection=connection,
+            headers={}
+        )
+        email.encoding = settings.EMAIL_ENCODING
+        email.send()
+        #--------------------------------------------------------------
+    except User.DoesNotExist, e:
+        template = 'signup_activation_error.html'
+        request.logger.error(e)
+
+    return render_to_response('%s' % template,
+                              dictionary,
+                              context_instance=RequestContext(
+                                request,
+                                {'HTTP_USER_AGENT': request.META['HTTP_USER_AGENT']}
+                              ))
+
+def password_recovery(request):
+    """Password Recovery Form"""
+
+    dictionary = {}
+
+    if request.method == 'POST':
+        request.logger.debug('Password Recovery Form posted')
+
+        form = PasswordRecoveryForm(request.POST)
+        if form.is_valid():
+            try:
+                user = User.objects.get(email=form.cleaned_data['email'])
+            except Exception, e:
+                request.logger.info('Password Recovery Error: ' + form.cleaned_data['email'] + ' - ' + str(e))
+                return HttpResponseRedirect(reverse('password_recovery_complete'))
+
+            # Make a New Password
+            password = User.objects.make_random_password(length=8)
+            user.set_password(password)
+            user.save()
+
+            # Send an email when complete
+            s = render_to_string('email/password_recovery_subject.txt')
+            h = Header(s, 'ISO-2022-JP').encode()
+            subject = ''.join(h.splitlines())
+
+            body_context=Context({
+                'name': user.first_name,
+                'password': password,
+            })
+            body = render_to_string('email/password_recovery_body.txt', body_context)
+
+            connection = SMTPConnection()
+            connection.host = settings.SMTP_HOST
+            connection.port = settings.SMTP_PORT
+            email = EmailMessage(
+                subject=subject,
+                body=body.encode('iso-2022-jp'),
+                from_email=settings.SITE_ADMIN_EMAIL,
+                to=[user.email],
+                bcc=[],
+                connection=connection,
+                headers={}
+            )
+            email.encoding = settings.EMAIL_ENCODING
+            email.send()
+            #--------------------------------------------------------------
+            return HttpResponseRedirect(reverse('password_recovery_done'))
+        else:
+            # Validation Error
+            request.logger.debug('Password Recovery Form Validation Error')
+            dictionary['form'] = form
+    # Request Method `GET` or Edit
+    elif request.method == 'GET':
+        dictionary['form'] = PasswordRecoveryForm()
+
+    return render_to_response('password_recovery.html',
+                              dictionary,
+                              context_instance=RequestContext(
+                                request,
+                                {'HTTP_USER_AGENT': request.META['HTTP_USER_AGENT']}
+                              ))
+
+def password_recovery_done(request):
+    """Password Recovery Completed"""
+    dictionary = {}
+    return render_to_response('password_recovery_done.html',
+                              dictionary,
+                              context_instance=RequestContext(
+                                request,
+                                {'HTTP_USER_AGENT': request.META['HTTP_USER_AGENT']}
+                              ))
+
+def mylogin(request):
+    """Login Form"""
+
+    dictionary = {}
+
+    if request.method == 'POST':
+        request.logger.debug('Login Form posted')
+
+        form = LoginForm(request.POST)
+        if form.is_valid():
+            user = authenticate(
+                username=form.cleaned_data['username'],
+                password=form.cleaned_data['password']
+            )
+
+            if user is not None:
+                request.logger.debug(user)
+                if user.is_active:
+                    login(request, user)
+                    return HttpResponseRedirect(reverse('index'))
+                ### this user is disabled
+                dictionary['error'] = u'$B%"%+%&%s%H$,L58z$G$9!#(B'
+
+        else:
+            dictionary['error'] = u'$B%a!<%k%"%I%l%9$^$?$O%Q%9%o!<%I$,0c$$$^$9!#(B'
+        dictionary['form'] = form
+
+    elif request.method == 'GET':
+        return HttpResponseRedirect(reverse('index'))
+
+    return render_to_response('index.html',
+                              dictionary,
+                              context_instance=RequestContext(
+                                request,
+                                {'HTTP_USER_AGENT': request.META['HTTP_USER_AGENT']}
+                              ))
+
+def mobile_login(request):
+    """Login Form for Mobile"""
+
+    dictionary = {}
+
+    if request.method == 'POST':
+        request.logger.debug('Mobile Login Form posted')
+
+        ### $B4JC1%m%0%$%s(B
+        if request.POST.get('easy', False):
+            print request.device
+
+        form = LoginForm(request.POST)
+        if form.is_valid():
+            user = authenticate(
+                username=form.cleaned_data['username'],
+                password=form.cleaned_data['password']
+            )
+
+            if user is not None:
+                request.logger.debug(user)
+                if user.is_active:
+                    login(request, user)
+                    return HttpResponseRedirect(reverse('index'))
+                ### this user is disabled
+                dictionary['error'] = u'$B%"%+%&%s%H$,L58z$G$9!#(B'
+
+        request.logger.debug('Mobile Login Error')
+        dictionary['error'] = u'$B%a!<%k%"%I%l%9$^$?$O%Q%9%o!<%I$,0c$$$^$9!#(B'
+        dictionary['form'] = form
+        request.logger.debug(dictionary)
+
+    elif request.method == 'GET':
+        form = LoginForm(request.POST)
+        dictionary['form'] = form
+
+    return render_to_response('login.html',
+                              dictionary,
+                              context_instance=RequestContext(
+                                request,
+                                {'HTTP_USER_AGENT': request.META['HTTP_USER_AGENT']}
+                              ))
+
+@login_required
+def mylogout(request):
+    logout(request)
+    return HttpResponseRedirect(reverse('index'))
+
+@login_required
+def password_edit(request):
+    """Password Edit Form"""
+
+    dictionary = {}
+
+    if request.method == 'POST':
+        request.logger.debug('Password Edit Form posted')
+
+        form = PasswordEditForm(request.POST)
+        if form.is_valid():
+            new_user = authenticate(
+                username=request.user.username,
+                password=form.cleaned_data['password']
+            )
+            if new_user is not None:
+                new_user.set_password(form.cleaned_data['new_password'])
+                new_user.save()
+                return HttpResponseRedirect(reverse('password_edit_complete'))
+            else:
+                dictionary['form'] = form
+                dictionary['error'] = u'$B8=:_$N%Q%9%o!<%I$,4V0c$C$F$$$^$9!#(B';
+        else:
+            # Validation Error
+            request.logger.debug('Password Edit Form Validation Error')
+            dictionary['form'] = form
+    # Request Method `GET` or Edit
+    elif request.method == 'GET':
+        dictionary['form'] = PasswordEditForm()
+
+    return render_to_response('password_edit/index.html',
+                              dictionary,
+                              context_instance=RequestContext(
+                                request,
+                                {'HTTP_USER_AGENT': request.META['HTTP_USER_AGENT']}
+                              ))
+
+@login_required
+def password_edit_complete(request):
+    """Password Edit Completed"""
+    dictionary = {}
+    return render_to_response('password_edit/complete.html',
+                              dictionary,
+                              context_instance=RequestContext(
+                                request,
+                                {'HTTP_USER_AGENT': request.META['HTTP_USER_AGENT']}
+                              ))
+
+@login_required
+def account(request):
+    """User Information"""
+    dictionary = {}
+    return render_to_response('my_user.html',
+                              dictionary,
+                              context_instance=RequestContext(
+                                request,
+                                {'HTTP_USER_AGENT': request.META['HTTP_USER_AGENT']}
+                              ))
+
+@login_required
+def user_edit(request):
+    """User Edit Form"""
+
+    dictionary = {}
+
+    if request.method == 'POST':
+        request.logger.debug('User Edit Form posted')
+
+        form = UserEditForm(request.POST, instance=request.user)
+
+        if form.is_valid():
+            new_user = authenticate(
+                username=request.user.username,
+                password=form.cleaned_data['password']
+            )
+            request.logger.debug(new_user)
+
+            if new_user is not None:
+                new_user.set_password(form.cleaned_data['new_password'])
+                new_user.first_name = form.cleaned_data['first_name']
+                new_user.email = form.cleaned_data['email']
+                new_user.save()
+                return HttpResponseRedirect(reverse('user_edit_done'))
+            else:
+                request.logger.error('User is None')
+        # Validation Error
+        request.logger.debug('User Edit Form Validation Error')
+        dictionary['form'] = form
+    # Request Method `GET` or Edit
+    elif request.method == 'GET':
+        dictionary['form'] = UserEditForm(instance=request.user)
+
+    return render_to_response('my_info.html',
+                              dictionary,
+                              context_instance=RequestContext(
+                                request,
+                                {'HTTP_USER_AGENT': request.META['HTTP_USER_AGENT']}
+                              ))
+
+@login_required
+def user_edit_done(request):
+    """User Edit Completed"""
+    dictionary = {}
+    return render_to_response('my_info_done.html',
+                              dictionary,
+                              context_instance=RequestContext(
+                                request,
+                                {'HTTP_USER_AGENT': request.META['HTTP_USER_AGENT']}
+                              ))
+
+@login_required
+def user_delete(request):
+    """Withdrawal Form"""
+
+    dictionary = {}
+
+    if request.method == 'POST':
+        request.logger.debug('User Delete Form posted')
+
+        form = UserResignCommentForm(request.POST)
+        if form.is_valid():
+            user = request.user
+            user.is_active = False
+            user.save()
+            logout(request)
+
+            # Send an email when complete
+            s = render_to_string('email/resign_subject.txt')
+            h = Header(s, 'ISO-2022-JP').encode()
+            subject = ''.join(h.splitlines())
+
+            body_context=Context({})
+            body = render_to_string('email/resign_body.txt', body_context)
+
+            connection = SMTPConnection()
+            connection.host = settings.SMTP_HOST
+            connection.port = settings.SMTP_PORT
+            email = EmailMessage(
+                subject=subject,
+                body=body.encode('iso-2022-jp'),
+                from_email=settings.SITE_ADMIN_EMAIL,
+                to=[user.email],
+                bcc=[],
+                connection=connection,
+                headers={}
+            )
+            email.encoding = settings.EMAIL_ENCODING
+            email.send()
+            return HttpResponseRedirect(reverse('user_delete_done'))
+        else:
+            # Validation Error
+            request.logger.debug('User Delete Form Validation Error')
+            dictionary['form'] = form
+    # Request Method `GET` or Edit
+    elif request.method == 'GET':
+        dictionary['form'] = UserResignCommentForm()
+
+    return render_to_response('my_resign.html',
+                              dictionary,
+                              context_instance=RequestContext(
+                                request,
+                                {'HTTP_USER_AGENT': request.META['HTTP_USER_AGENT']}
+                              ))
+
+def user_delete_done(request):
+    """Withdrawal Form"""
+    dictionary = {}
+    return render_to_response('my_resign_done.html',
+                              dictionary,
+                              context_instance=RequestContext(
+                                request,
+                                {'HTTP_USER_AGENT': request.META['HTTP_USER_AGENT']}
+                              ))

django/madrix/contact/__init__.py

Empty file added.

django/madrix/contact/forms.py

+# vim: fileencoding=utf8
+
+from django import forms
+
+from contrib.widgets import TextareaNoCols
+
+class ContactForm(forms.Form):
+    name = forms.CharField(label=u'お名前',
+        widget=forms.TextInput(attrs={'class': 'text-box'}))
+    email = forms.EmailField(label=u'メールアドレス',
+        widget=forms.TextInput(attrs={'class': 'text-box'}))
+    address = forms.CharField(label=u'住所',
+        widget=forms.TextInput(attrs={'class': 'text-box'}))
+    phone = forms.CharField(label=u'電話番号',
+        widget=forms.TextInput(attrs={'class': 'text-box'}))
+    comment = forms.CharField(label=u'お問い合わせ内容',
+        widget=TextareaNoCols(attrs={'cols': 30, 'id': 'text'}))

django/madrix/contact/models.py

+from django.db import models
+
+# Create your models here.

django/madrix/contact/views.py

+# vim: fileencoding=utf8
+from email.Header import Header
+
+from django.http import HttpResponse, HttpResponseRedirect
+from django.shortcuts import render_to_response
+from django.contrib.auth import authenticate, login, logout
+from django.template import Context, RequestContext
+from django.template.loader import get_template, render_to_string
+from django.core.urlresolvers import reverse
+from django.core.mail import SMTPConnection
+from django.conf import settings
+
+from news.models import News
+from contrib.mail import FixedEmailMessage as EmailMessage
+from contact.forms import ContactForm
+
+def contact(request):
+    """Contact Form"""
+    
+    dictionary = {}
+    template = 'index.html'
+
+    # News 取得
+    dictionary['news_list'] = News.objects.all().order_by('-created_at')[0:3]
+
+    if request.method == 'POST':
+
+        form = ContactForm(request.POST)
+        if form.is_valid():
+            if request.POST.has_key('regist'):
+                # Send an email when complete
+                s = render_to_string('email/contact_subject.txt')
+                h = Header(s, 'ISO-2022-JP').encode()
+                subject = ''.join(h.splitlines())
+
+                body_context=Context({
+                    'data': form.cleaned_data,
+                })
+                body = render_to_string('email/contact_body.txt', body_context)
+
+                connection = SMTPConnection()
+                connection.host = settings.SMTP_HOST
+                connection.port = settings.SMTP_PORT
+                email = EmailMessage(
+                    subject=subject,
+                    body=body.encode('iso-2022-jp'),
+                    from_email=settings.SITE_ADMIN_EMAIL,
+                    to=[form.cleaned_data['email']],
+                    bcc=[settings.SITE_ADMIN_EMAIL],
+                    connection=connection,
+                    headers={}
+                )
+                email.encoding = settings.EMAIL_ENCODING
+                email.send()
+                #--------------------------------------------------------------
+                return HttpResponseRedirect(reverse('contact_complete'))
+            elif request.POST.has_key('confirm'):
+                # Confirmation
+                template = 'confirm.html'
+                dictionary['form'] = form
+                dictionary['cleaned_data'] = form.cleaned_data
+            else:
+                dictionary['form'] = form
+        else:
+            dictionary['form'] = form
+
+    # Request Method `GET` or Edit
+    elif request.method == 'GET':
+        dictionary['form'] = ContactForm()
+
+    return render_to_response('contact/' + template,
+                              dictionary,
+                              context_instance=RequestContext(request))
+
+
+def contact_complete(request):
+    """Contact Completed"""
+
+    dictionary = {}
+
+    return render_to_response('contact/thanks.html',
+                              dictionary,
+                              context_instance=RequestContext(request))

django/madrix/contrib/__init__.py

Empty file added.

django/madrix/contrib/auth.py

+try:
+    set
+except NameError:
+    from sets import Set as set # Python 2.3 fallback
+
+from django.db import connection
+from django.contrib.auth.models import User
+from django.contrib.auth.backends import ModelBackend
+from django.utils.html import simple_email_re
+
+
+class EmailBackend(ModelBackend):
+    def authenticate(self, username=None, password=None):
+        #If username is an email address, then try to pull it up
+        if simple_email_re.search(username):
+            try:
+                user = User.objects.get(email=username)
+            except User.DoesNotExist:
+                return None
+        else:
+            #We have a non-email address username we should try username
+            try:
+                user = User.objects.get(username=username)
+            except User.DoesNotExist:
+                return None
+        if user.check_password(password):
+            return user
+
+    def get_user(self, user_id):
+        try:
+            return User.objects.get(pk=user_id)
+        except User.DoesNotExist:
+            return None

django/madrix/contrib/debugging_smtp_server.py

+import asyncore
+import smtpd
+
+"""
+local_settings.py
+
+SMTP_HOST = 'localhost'
+SMTP_PORT = 20025
+"""
+
+smtpd.DebuggingServer(('localhost', 20025), ('localhost', 25))
+asyncore.loop()

django/madrix/contrib/fields.py

+import os
+import random
+import string
+
+import Image
+
+from django.db.models import ImageField, FileField, signals
+
+class ExtImageField(ImageField):
+
+    def db_type(self):
+        return 'varchar(100)'
+
+    def get_filename(self, filename):
+        root, ext = os.path.splitext(os.path.basename(filename))
+        new_root = ''.join([random.choice(string.letters+string.digits) for x in xrange(10)])
+        return os.path.join(self.get_directory_name(), new_root + ext)
+
+    def contribute_to_class(self, cls, name):
+        super(ExtImageField, self).contribute_to_class(cls, name)
+        signals.post_init.connect(self._post_init, sender=cls)
+
+    def _post_init(self, instance=None, **kargs):
+        if hasattr(instance, 'get_upload_to'):
+            self.upload_to = instance.get_upload_to(self.attname)
+
+    def create_thumbnail(cls, path, width, height, type, crop=True):
+        im = Image.open(path)
+        im_base = Image.new('RGB', (width, height), '#FFFFFF')
+        if im.mode != 'RGB':
+            im = im.convert('RGB')
+
+        im.thumbnail((width, height), Image.ANTIALIAS)
+        x, y = im.size
+        x = (width - x) / 2
+        im_base.paste(im, (x, 0))
+
+        root, ext = os.path.splitext(os.path.basename(path))
+        dirname = os.path.dirname(path)
+        outfile = os.path.join(dirname, root + '_' + type + ext)
+        im_base.save(outfile, 'JPEG', quality=100)
+        #os.chmod(outfile, 0666)
+        #os.chmod(os.path.dirname(outfile), 0777)
+    create_thumbnail=classmethod(create_thumbnail)
+
+    def delete_thumbnail(cls, path):
+        os.remove(path)
+    delete_thumbnail=classmethod(delete_thumbnail)
+
+class ExtFileField(FileField):
+
+    def db_type(self):
+        return 'varchar(100)'
+
+    def get_filename(self, filename):
+        root, ext = os.path.splitext(os.path.basename(filename))
+        new_root = ''.join([random.choice(string.letters+string.digits) for x in xrange(10)])
+        return os.path.join(self.get_directory_name(), new_root + ext)
+
+    def contribute_to_class(self, cls, name):
+        super(ExtFileField, self).contribute_to_class(cls, name)
+        signals.post_init.connect(self._post_init, sender=cls)
+
+    def _post_init(self, instance=None, **kargs):
+        if hasattr(instance, 'get_upload_to'):
+            self.upload_to = instance.get_upload_to(self.attname)

django/madrix/contrib/jp_prefectures.py

+from django.utils.translation import ugettext_lazy
+
+JP_PREFECTURES = (
+    (ugettext_lazy('Hokkaido'), ugettext_lazy('Hokkaido'),),
+    (ugettext_lazy('Aomori'), ugettext_lazy('Aomori'),),
+    (ugettext_lazy('Iwate'), ugettext_lazy('Iwate'),),
+    (ugettext_lazy('Miyagi'), ugettext_lazy('Miyagi'),),
+    (ugettext_lazy('Akita'), ugettext_lazy('Akita'),),
+    (ugettext_lazy('Yamagata'), ugettext_lazy('Yamagata'),),
+    (ugettext_lazy('Fukushima'), ugettext_lazy('Fukushima'),),
+    (ugettext_lazy('Ibaraki'), ugettext_lazy('Ibaraki'),),
+    (ugettext_lazy('Tochigi'), ugettext_lazy('Tochigi'),),
+    (ugettext_lazy('Gunma'), ugettext_lazy('Gunma'),),
+    (ugettext_lazy('Saitama'), ugettext_lazy('Saitama'),),
+    (ugettext_lazy('Chiba'), ugettext_lazy('Chiba'),),
+    (ugettext_lazy('Tokyo'), ugettext_lazy('Tokyo'),),
+    (ugettext_lazy('Kanagawa'), ugettext_lazy('Kanagawa'),),
+    (ugettext_lazy('Yamanashi'), ugettext_lazy('Yamanashi'),),
+    (ugettext_lazy('Nagano'), ugettext_lazy('Nagano'),),
+    (ugettext_lazy('Niigata'), ugettext_lazy('Niigata'),),
+    (ugettext_lazy('Toyama'), ugettext_lazy('Toyama'),),
+    (ugettext_lazy('Ishikawa'), ugettext_lazy('Ishikawa'),),
+    (ugettext_lazy('Fukui'), ugettext_lazy('Fukui'),),
+    (ugettext_lazy('Gifu'), ugettext_lazy('Gifu'),),
+    (ugettext_lazy('Shizuoka'), ugettext_lazy('Shizuoka'),),
+    (ugettext_lazy('Aichi'), ugettext_lazy('Aichi'),),
+    (ugettext_lazy('Mie'), ugettext_lazy('Mie'),),
+    (ugettext_lazy('Shiga'), ugettext_lazy('Shiga'),),
+    (ugettext_lazy('Kyoto'), ugettext_lazy('Kyoto'),),
+    (ugettext_lazy('Osaka'), ugettext_lazy('Osaka'),),
+    (ugettext_lazy('Hyogo'), ugettext_lazy('Hyogo'),),
+    (ugettext_lazy('Nara'), ugettext_lazy('Nara'),),
+    (ugettext_lazy('Wakayama'), ugettext_lazy('Wakayama'),),
+    (ugettext_lazy('Tottori'), ugettext_lazy('Tottori'),),
+    (ugettext_lazy('Shimane'), ugettext_lazy('Shimane'),),
+    (ugettext_lazy('Okayama'), ugettext_lazy('Okayama'),),
+    (ugettext_lazy('Hiroshima'), ugettext_lazy('Hiroshima'),),
+    (ugettext_lazy('Yamaguchi'), ugettext_lazy('Yamaguchi'),),
+    (ugettext_lazy('Tokushima'), ugettext_lazy('Tokushima'),),
+    (ugettext_lazy('Kagawa'), ugettext_lazy('Kagawa'),),
+    (ugettext_lazy('Ehime'), ugettext_lazy('Ehime'),),
+    (ugettext_lazy('Kochi'), ugettext_lazy('Kochi'),),
+    (ugettext_lazy('Fukuoka'), ugettext_lazy('Fukuoka'),),
+    (ugettext_lazy('Saga'), ugettext_lazy('Saga'),),
+    (ugettext_lazy('Nagasaki'), ugettext_lazy('Nagasaki'),),
+    (ugettext_lazy('Kumamoto'), ugettext_lazy('Kumamoto'),),
+    (ugettext_lazy('Oita'), ugettext_lazy('Oita'),),
+    (ugettext_lazy('Miyazaki'), ugettext_lazy('Miyazaki'),),
+    (ugettext_lazy('Kagoshima'), ugettext_lazy('Kagoshima'),),
+    (ugettext_lazy('Okinawa'), ugettext_lazy('Okinawa'),),
+)

django/madrix/contrib/loggingmw.py

+from datetime import datetime
+import logging
+
+logger = None
+
+class LoggingMiddleware(object):
+    """
+    Basic logging middleware. If settings.LOG_ENABLED is set, adds a logger
+    instance as request.logger
+
+    Logging can be used as request.logger.[debug, info, warning, error and critical]
+
+    Ex: request.logger.info("This is an info message")
+
+    Requires LOG_ENABLED settings value.
+
+    If settings.LOG_ENABLED is True, requires LOG_FILE value.
+
+    LOG_NAME is optional, and will specify a name for this logger
+    instance (not shown in default format string)
+    """
+
+    def process_request(self, request):
+        from django.conf import settings
+        enabled = getattr(settings, 'LOG_ENABLED', False)
+        logfile = getattr(settings, 'LOG_FILE', None)
+        if not enabled or not logfile:
+            return
+
+        global logger
+        if logger is None:
+            logging.basicConfig(
+                # I don't want to `eval` here
+                level=eval('logging.' + settings.LOG_LEVEL),
+                format='%(asctime)s - %(levelname)s - %(message)s',
+                datefmt='%Y-%m-%d %X',
+                filename=settings.LOG_FILE,
+                filemode='a'
+            )
+            logger = logging.getLogger(getattr(settings, 'LOG_NAME', 'django'))
+            #logger.setLevel(logging.DEBUG)
+
+        request.logger = logger
+
+

django/madrix/contrib/mail.py

+from django.core.mail import EmailMessage
+
+class FixedEmailMessage(EmailMessage):
+    def __init__(self, subject='', body='', from_email=None, to=None, cc=None,
+                 bcc=None, connection=None, attachments=None, headers=None):
+        """
+        Initialize a single email message (which can be sent to multiple
+        recipients).
+
+        All strings used to create the message can be Unicode strings (or UTF-8
+        bytestrings). The SafeMIMEText class will handle any necessary encoding
+        conversions.
+        """
+        to_cc_bcc_types = (type(None), list, tuple)
+        # test for typical error: people put strings in to, cc and bcc fields
+        # see documentation at http://www.djangoproject.com/documentation/email/
+        assert isinstance(to, to_cc_bcc_types)
+        assert isinstance(cc, to_cc_bcc_types)
+        assert isinstance(bcc, to_cc_bcc_types)
+        super(FixedEmailMessage, self).__init__(subject, body, from_email, to, 
+                                           bcc, connection, attachments, headers)
+        if cc:
+            self.cc = list(cc)
+        else:
+            self.cc = []
+
+    def recipients(self):
+        """
+        Returns a list of all recipients of the email (includes direct
+        addressees as well as Bcc entries).
+        """
+        return self.to + self.cc + self.bcc
+
+    def message(self):
+        msg = super(FixedEmailMessage, self).message()
+        del msg['Bcc'] # who was that clever guy that added bccs to headers?!
+        if self.cc:
+            msg['Cc'] = ', '.join(self.cc)
+        return msg
+

django/madrix/contrib/middleware.py

+from uamobile import detect, exceptions
+
+class UserAgentMobileMiddleware(object):
+    def process_request(self, request):
+        try:
+            request.device = detect(request.META)
+        except exceptions.NoMatchingError, e:
+            pass

django/madrix/contrib/monthdays.py

+MONTH = (
+    ('01',1),
+    ('02',2),
+    ('03',3),
+    ('04',4),
+    ('05',5),
+    ('06',6),
+    ('07',7),
+    ('08',8),
+    ('09',9),
+    ('10',10),
+    ('11',11),
+    ('12',12),
+)
+
+DAY = (
+    ('01',1),
+    ('02',2),
+    ('03',3),
+    ('04',4),
+    ('05',5),
+    ('06',6),
+    ('07',7),
+    ('08',8),
+    ('09',9),
+    ('10',10),
+    ('11',11),
+    ('12',12),
+    ('13',13),
+    ('14',14),
+    ('15',15),
+    ('16',16),
+    ('17',17),
+    ('18',18),
+    ('19',19),
+    ('20',20),
+    ('21',21),
+    ('22',22),
+    ('23',23),
+    ('24',24),
+    ('25',25),
+    ('26',26),
+    ('27',27),
+    ('28',28),
+    ('29',29),
+    ('30',30),
+    ('31',31),
+)

django/madrix/contrib/pyqrcode.py

+# !/usr/bin/env python
+# based on t.swetake(http://www.swetake.com/')'s qr class library
+# for ruby 0.50beta
+
+class myarray(list):
+    def __setitem__(self, key, value):
+        try:
+            list.__setitem__(self,key,value)
+        except:
+            self += [None for i in range(key - len(self)+1)]
+            list.__setitem__(self,key,value)
+
+    def __getitem__(self, key):
+        try:
+            return list.__getitem__(self,key)
+        except:
+            return None
+
+#endclass    
+
+class Qrcode:
+    def __init__(self):
+        self.path = "/var/www-root/madrix.jp/madrix/contrib/qrcode_data"
+        self.qrcode_error_correct="M"
+        self.qrcode_version=0
+
+        self.qrcode_structureappend_n=0
+        self.qrcode_structureappend_m=0
+        self.qrcode_structureappend_parity=""
+        self.qrcode_structureappend_originaldata=""
+
+        return
+    
+    def string_bit_cal(self, s1, s2, ind):
+        if len(s1) > len(s2): s1,s2 = s2,s1
+        i = 0
+        res = ""
+        left_length = len(s2) - len(s1)
+
+        if ind == "xor":
+            for s in s1:
+                b = ord(s)
+
+                res += chr(b ^ ord(s2[i]))
+                i += 1
+
+            res += s2[len(s1):len(s1)+left_length]
+        elif ind == "or":
+            for s in s1:
+                b = ord(s)                
+                res += chr(b | ord(s2[i]))
+                i += 1
+            res += s2[len(s1):len(s1)+left_length]
+
+        elif ind == "and":
+            for s in s1:
+                b = ord(s)
+                res += chr(b & ord(s2[i]))
+                i += 1
+            res += chr(0) * left_length
+
+        return res
+    
+    def string_bit_not(self, s1):
+        res = ""
+        for s in s1:
+            b = ord(s)
+            res += chr(256 + ~b)
+        return res
+
+    def set_qrcode_version(self, z):
+        if z>= 0 and z<=40:
+            self.qrcode_version = z
+        return
+
+    def set_qrcode_error_correct(self, z):
+        self.qrcode_error_correct = z
+        return
+
+    def get_qrcode_version(self, z):
+        return self.qrcode_version
+
+    def set_structureappend(self, m, n, p):
+        if n>1 and n<=16 and m>0 and m<=16 and p>=0 and p<=255 :
+            self.qrcode_structureappend_m = m
+            self.qrcode_structureappend_n = n
+            self.qrcode_structureappend_parity = p
+
+        return
+    
+    def cal_structureappend_parity(self, originaldata):
+        if len(originaldata) > 1:
+            structureappend_parity=0
+            for s in originaldata:
+                b = ord(s)
+                structureappend_parity ^= b
+        return
+    
+    def make_qrcode(self, qrcode_data_string):
+        data_length = len(qrcode_data_string)
+        data_counter=0
+        data_value= myarray()
+        data_bits= myarray()
+
+        data_bits[data_counter]=4
+
+
+        ##### mode #####
+        import re
+        if( qrcode_data_string.isdigit()):
+            mode ="num"
+        elif(re.match("^[0-9A-Z\ \$\*\%\+\-\./\:]+$",qrcode_data_string)):
+            mode = "alnum"
+        else:
+            mode = "8bit"
+
+        # ------ 8bit byte mode --------
+        if(mode == "8bit"):
+            codeword_num_plus=[0,0,0,0,0,0,0,0,0,0,
+                               8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+                               8,8,8,8,8,8,8,8,8,8,8,8,8,8]
+            data_value[data_counter]=4
+            data_counter+=1
+            data_value[data_counter]=data_length
+            data_bits[data_counter]=8
+            
+            codeword_num_counter_value=data_counter
+            
+            data_counter+=1
+            i=0
+            while i<data_length:
+                data_value[data_counter]=ord(qrcode_data_string[i])
+                data_bits[data_counter]=8
+                data_counter+=1
+                i+=1
+            #endwhile
+
+        ##### mode-end #####
+
+        # ---- alphanumeric mode
+        if(mode == "alnum"):
+            codeword_num_plus=[0,0,0,0,0,0,0,0,0,0,
+                               2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
+                               4,4,4,4,4,4,4,4,4,4,4,4,4,4]
+    
+            data_value[data_counter]=2
+    
+            data_counter+=1
+            data_value[data_counter]=data_length
+            data_bits[data_counter]=9
+    
+            codeword_num_counter_value=data_counter
+    
+            alphanumeric_character_hash={"0":0,"1":1,"2":2,"3":3,
+                                         "4":4,"5":5,"6":6,"7":7,
+                                         "8":8,"9":9,"A":10,"B":11,
+                                         "C":12,"D":13,"E":14,"F":15,
+                                         "G":16,"H":17,"I":18,"J":19,
+                                         "K":20,"L":21,"M":22,"N":23,
+                                         "O":24,"P":25,"Q":26,"R":27,
+                                         "S":28,"T":29,"U":30,"V":31,
+                                         "W":32,"X":33,"Y":34,"Z":35,
+                                         " ":36,"$":37,"%":38,"*":39,
+                                         "+":40,"-":41,".":42,"/":43,
+                                         ":":44}
+
+            i=0
+            data_counter+=1
+    
+            while i<data_length:
+                if (i % 2) == 0 :
+                    data_value[data_counter]=alphanumeric_character_hash[qrcode_data_string[i]]
+                    data_bits[data_counter]=6
+                else:
+                    data_value[data_counter]=data_value[data_counter]*45+alphanumeric_character_hash[qrcode_data_string[i]]
+                    data_bits[data_counter]=11
+                    data_counter+=1
+                #end
+                i+=1
+            #end
+            
+        # ---- end of alphanumeric mode
+    
+        # ---- numeric mode
+        if(mode=="num"):
+            codeword_num_plus=[0,0,0,0,0,0,0,0,0,0,
+                               2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
+                               4,4,4,4,4,4,4,4,4,4,4,4,4,4]
+
+            data_value[data_counter]=1
+            data_counter+=1
+            data_value[data_counter]=data_length
+            data_bits[data_counter]=10
+            codeword_num_counter_value=data_counter        
+
+
+            i=0
+            data_counter+=1
+            while i < data_length:
+                if ((i % 3)==0):
+                    data_value[data_counter]=int(qrcode_data_string[i])
+                    data_bits[data_counter]=4
+                else:
+                    data_value[data_counter]=data_value[data_counter]*10+int(qrcode_data_string[i])
+                    if ((i % 3)==1):
+                        data_bits[data_counter]=7
+                    else:
+                        data_bits[data_counter]=10
+                        data_counter+=1
+                    #end
+                #end
+                i+=1
+            #end
+    
+            if data_bits[data_counter] is None:
+                pass
+            elif data_bits[data_counter]>0:
+                data_counter+=1
+            #end
+        # --- end of numeric mode
+
+        i=0
+        total_data_bits=0
+
+        while i<data_counter:
+            total_data_bits+=data_bits[i]
+            i+=1
+        #end
+
+        ecc_character_hash = {"L":1,"l":1,
+                              "M":0,"m":0,
+                              "Q":3,"q":3,
+                              "H":2,"h":2}
+        ec=ecc_character_hash[self.qrcode_error_correct]
+        max_data_bits_array=[0,128,224,352,512,688,864,992,1232,1456,1728,
+                             2032,2320,2672,2920,3320,3624,4056,4504,5016,5352,
+                             5712,6256,6880,7312,8000,8496,9024,9544,10136,10984,
+                             11640,12328,13048,13800,14496,15312,15936,16816,17728,18672,
+                             
+                             152,272,440,640,864,1088,1248,1552,1856,2192,
+                             2592,2960,3424,3688,4184,4712,5176,5768,6360,6888,
+                             7456,8048,8752,9392,10208,10960,11744,12248,13048,13880,
+                             14744,15640,16568,17528,18448,19472,20528,21616,22496,23648,
+
+                             72,128,208,288,368,480,528,688,800,976,
+                             1120,1264,1440,1576,1784,2024,2264,2504,2728,3080,
+                             3248,3536,3712,4112,4304,4768,5024,5288,5608,5960,
+                             6344,6760,7208,7688,7888,8432,8768,9136,9776,10208,
+
+                             104,176,272,384,496,608,704,880,1056,1232,
+                             1440,1648,1952,2088,2360,2600,2936,3176,3560,3880,
+                             4096,4544,4912,5312,5744,6032,6464,6968,7288,7880,
+                             8264,8920,9368,9848,10288,10832,11408,12016,12656,13328
+                             ]
+        if self.qrcode_version == 0:
+            i=1+40*ec
+            j=i+39
+            self.qrcode_version=1
+            while i<=j:
+                if ((max_data_bits_array[i])>=total_data_bits+codeword_num_plus[self.qrcode_version]):
+                    max_data_bits=max_data_bits_array[i]
+                    break
+                #end
+                i+=1
+                self.qrcode_version+=1
+            #end
+            else:
+                max_data_bits=max_data_bits_array[self.qrcode_version+40*ec]
+            #end
+            total_data_bits+=codeword_num_plus[self.qrcode_version]
+            data_bits[codeword_num_counter_value]+=codeword_num_plus[self.qrcode_version]
+            max_codewords_array = [ 0,26,44,70,100,134,172,196,242,
+                                    292,346,404,466,532,581,655,733,815,901,991,1085,1156,
+                                    1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,
+                                    2611,2761,2876,3034,3196,3362,3532,3706]
+            max_codewords = max_codewords_array[self.qrcode_version]
+            max_modules_1side=17+(self.qrcode_version << 2)
+            matrix_remain_bit=[0,0,7,7,7,7,7,0,0,0,0,0,0,0,3,3,3,3,3,3,3,
+                               4,4,4,4,4,4,4,3,3,3,3,3,3,3,0,0,0,0,0,0]
+    
+            #/* ---- read version ECC data file */
+            byte_num=matrix_remain_bit[self.qrcode_version]+(max_codewords << 3)
+
+            filename=self.path+"/qrv"+str(self.qrcode_version)+"_"+str(ec)+".dat"
+            fp = open(filename ,"rb")
+            matx=fp.read(byte_num)
+            maty=fp.read(byte_num)
+            masks=fp.read(byte_num)
+            fi_x=fp.read(15)
+            fi_y=fp.read(15)
+            rs_ecc_codewords=ord(fp.read(1))
+            rso=fp.read(128)
+            fp.close()
+
+            unpack = lambda y: map(lambda x:ord(x),y)
+            matrix_x_array = unpack(matx)
+            matrix_y_array = unpack(maty)
+            mask_array = unpack(masks)
+            rs_block_order = unpack(rso)
+            format_information_x2 = unpack(fi_x)
+            format_information_y2 = unpack(fi_y)
+            format_information_x1=[0,1,2,3,4,5,7,8,8,8,8,8,8,8,8]
+            format_information_y1=[8,8,8,8,8,8,8,8,7,5,4,3,2,1,0]
+            
+            max_data_codewords=(max_data_bits >>3)
+
+            filename = self.path+"/rsc"+str(rs_ecc_codewords)+".dat"
+
+            fp =open(filename, "rb")
+
+            i=0
+            rs_cal_table_array=myarray()
+
+            while i<256:
+                rs_cal_table_array[i]=fp.read(rs_ecc_codewords)
+                i+=1
+
+            #end
+            fp.close()
+
+            #/* -- read frame data  -- */
+            filename = self.path+"/qrvfr"+str(self.qrcode_version)+".dat"
+            fp = open(filename, "rb")
+            frame_data = fp.read(65535)
+            fp.close()
+
+            #/*  --- set terminator */
+            if (total_data_bits<=max_data_bits-4):
+                data_value[data_counter]=0
+                data_bits[data_counter]=4
+            elif  (total_data_bits<max_data_bits):
+                data_value[data_counter]=0
+                data_bits[data_counter]=max_data_bits-total_data_bits
+            elif (total_data_bits>max_data_bits) :
+                raise OverflowError, "Overflow error"
+	        return 0
+
+            #/* ----divide data by 8bit */
+            i=0
+            codewords_counter=0
+            codewords=myarray()
+            codewords[0]=0
+            remaining_bits=8
+
+            while (i <= data_counter):
+                buf =data_value[i]
+                buffer_bits=data_bits[i]
+                flag=1
+                while flag!=0 :
+
+                    if remaining_bits>buffer_bits :
+                        if codewords[codewords_counter] ==None : codewords[codewords_counter]=0 
+
+                        codewords[codewords_counter]=((codewords[codewords_counter]<<buffer_bits) | buf)
+                        remaining_bits-=buffer_bits
+                        flag=0
+                    else:
+                        buffer_bits-=remaining_bits
+                        """
+                        print "buf",buf
+                        print "buffer_bits",buffer_bits
+                        print "remaining_bits",remaining_bits
+                        print "codewords",codewords[codewords_counter]
+                        """
+                        codewords[codewords_counter]=((codewords[codewords_counter] << remaining_bits) | (buf >> buffer_bits))
+                        if (buffer_bits==0):
+                            flag=0
+                        else:
+                            buf= (buf & ((1 << buffer_bits)-1) )
+                            flag=1
+
+                        #end
+
+                        codewords_counter+=1
+                        if (codewords_counter<max_data_codewords-1):
+                            codewords[codewords_counter]=0
+                        #end
+                        remaining_bits=8
+                    #end
+
+                #end
+                i+=1
+            #end
+
+            if (remaining_bits!=8):
+                codewords[codewords_counter]=codewords[codewords_counter] << remaining_bits
+            else:
+                codewords_counter-=1
+            #end
+
+            #/* ----  set padding character */            
+            if (codewords_counter<max_data_codewords-1):
+                flag=1
+                while codewords_counter<max_data_codewords-1:
+                    codewords_counter+=1
+                    if (flag==1):
+                        codewords[codewords_counter]=236
+                    else:
+                        codewords[codewords_counter]=17
+                    #end
+                    flag=flag*(-1)
+                #end
+            #end
+
+            #/* ---- RS-ECC prepare */
+
+            i=0
+            j=0
+            rs_block_number=0
+            rs_temp=myarray()
+            rs_temp[0]=""
+
+            while i<max_data_codewords:
+
+                rs_temp[rs_block_number] += chr(codewords[i])
+
+                j+=1
+                if j>=rs_block_order[rs_block_number]-rs_ecc_codewords:
+                    j=0
+                    rs_block_number+=1
+                    rs_temp[rs_block_number]=""
+                #end
+                i+=1
+            #end
+
+            #/*
+            #
+            # RS-ECC main
+            #
+            #*/
+
+            rs_block_number=0
+            rs_block_order_num = len(rs_block_order)
+
+            while rs_block_number<rs_block_order_num:
+                rs_codewords=rs_block_order[rs_block_number]
+                rs_data_codewords=rs_codewords-rs_ecc_codewords
+
+                rstemp=rs_temp[rs_block_number]
+                j=rs_data_codewords
+                while j>0:
+                    first=ord(rstemp[0])
+                    if first!=0:
+                        left_chr=rstemp[1:]
+                        cal=rs_cal_table_array[first]
+                        rstemp=self.string_bit_cal(left_chr,cal,"xor")
+
+                    else:
+                        rstemp=rstemp[1:]
+                        pass
+                    #end
+                    j-=1
+
+                #end
+                pass
+                codewords += unpack(rstemp)
+                rs_block_number+=1
+            #end
+
+            #---- 
+            #/* ---- flash matrix */
+            matrix_content = [[0 for i in range(max_modules_1side)] for j in range(max_modules_1side )]
+
+            #/* --- attach data */
+            i=0
+            while i<max_codewords:
+                codeword_i=codewords[i]
+                j=7
+                while j>=0:
+                    codeword_bits_number=(i << 3) +  j
+
+                    matrix_content[ matrix_x_array[codeword_bits_number] ][ matrix_y_array[codeword_bits_number] ]=((255*(codeword_i & 1)) ^ mask_array[codeword_bits_number] )
+                    codeword_i= codeword_i >> 1
+                    j-=1
+                #end
+                i+=1
+            #end
+             
+            matrix_remain=matrix_remain_bit[self.qrcode_version]
+            while matrix_remain>0:
+                remain_bit_temp = matrix_remain + ( max_codewords << 3)-1
+                matrix_content[ matrix_x_array[remain_bit_temp] ][ matrix_y_array[remain_bit_temp] ]  =  ( 255 ^ mask_array[remain_bit_temp] )
+
+                matrix_remain-=1
+            #end
+
+            #--- mask select
+            min_demerit_score=0
+            hor_master=""
+            ver_master=""
+            k=0
+            while k<max_modules_1side:
+                l=0
+                while l<max_modules_1side:
+                    hor_master += chr(matrix_content[l][k])
+                    ver_master += chr(matrix_content[k][l])
+                    l+=1
+                #end
+                k+=1
+            #end
+            i=0
+            all_matrix=max_modules_1side*max_modules_1side
+
+            while i<8:
+                demerit_n1=0
+                ptn_temp=myarray()
+                bit= 1<< i
+                bit_r=(~bit) & 255
+                bit_mask=chr(bit) * all_matrix
+                hor = self.string_bit_cal(hor_master,bit_mask,"and")
+                ver = self.string_bit_cal(ver_master,bit_mask,"and")
+                ver_and= self.string_bit_cal( ((chr(170) * max_modules_1side) + ver), (ver + (chr(170) * max_modules_1side)),"and")
+                ver_or=  self.string_bit_cal( ((chr(170) * max_modules_1side) + ver), (ver + (chr(170) * max_modules_1side)),"or")
+                hor= self.string_bit_not(hor)
+                ver= self.string_bit_not(ver)
+
+
+                ver_and = self.string_bit_not(ver_and)
+                ver_or  = self.string_bit_not(ver_or)
+
+                strsubst= lambda x,a,c: x[:a]+c+x[a:]
+                ver_and = strsubst(ver_and, all_matrix, chr(170))
+                ver_or = strsubst(ver_or, all_matrix, chr(170))
+
+                k = max_modules_1side - 1
+
+                while k>=0:
+                    hor = strsubst(hor, k*max_modules_1side,chr(170))
+
+                    ver = strsubst(ver, k*max_modules_1side,chr(170))
+                    ver_and = strsubst(ver_and, k*max_modules_1side,chr(170))
+                    ver_or = strsubst(ver_or, k*max_modules_1side,chr(170))                    
+                    k-=1
+
+                #end
+                hor=hor + chr(170) + ver
+                n1_search=(chr(255) * 5)+"+|"+(chr(bit_r) * 5) + "+"
+                n2_search1=chr(bit_r) + chr(bit_r) + "+"
+                n2_search2=chr(255) + chr(255) + "+"
+                n3_search=chr(bit_r) + chr(255) + chr(bit_r) + chr(bit_r) + chr(bit_r) + chr(255)+ chr(bit_r)
+                n4_search=chr(bit_r)
+                hor_temp=hor
+
+
+                import re
+                demerit_n3 = len(re.findall(n3_search,hor_temp))*40 
+                demerit_n4 = abs(int(( ( ( (ver.count(n4_search)*len(n4_search)*100) / byte_num) -50)/5))) * 10
+                
+                demerit_n2=0
+                ptn_temp=re.findall(n2_search1, ver_and)
+                for te in ptn_temp:
+                    demerit_n2 += len(te)-1
+                    
+                ptn_temp=re.findall(n2_search2, ver_or)
+                for te in ptn_temp:
+                    demerit_n2 += len(te)-1
+
+                demerit_n2*=3
+                ptn_temp=re.findall(n1_search, hor)
+                for te in ptn_temp:
+                    demerit_n1 += len(te)-2
+                    
+                demerit_score=demerit_n1+demerit_n2+demerit_n3+demerit_n4
+                if (demerit_score<=min_demerit_score or i==0):
+                    mask_number=i
+                    min_demerit_score=demerit_score
+                #end
+
+                i+=1
+            #end
+
+            mask_content=1 << mask_number
+            
+            # --- format information
+
+            format_information_value=((ec << 3) | mask_number)
+            format_information_array=["101010000010010","101000100100101",
+                                      "101111001111100","101101101001011","100010111111001","100000011001110",
+                                      "100111110010111","100101010100000","111011111000100","111001011110011",
+                                      "111110110101010","111100010011101","110011000101111","110001100011000",
+                                      "110110001000001","110100101110110","001011010001001","001001110111110",
+                                      "001110011100111","001100111010000","000011101100010","000001001010101",
+                                      "000110100001100","000100000111011","011010101011111","011000001101000",
+                                      "011111100110001","011101000000110","010010010110100","010000110000011",
+                                      "010111011011010","010101111101101"]
+
+            for i in range(15):
+                content=int(format_information_array[format_information_value][i])
+                matrix_content[format_information_x1[i]][format_information_y1[i]]=content * 255
+                matrix_content[format_information_x2[i]][format_information_y2[i]]=content * 255
+            #end
+
+            out=""
+            mxe=max_modules_1side
+
+            for i in range(mxe):
+                for j in range(mxe):
+                    if (int(matrix_content[j][i]) & mask_content)!=0:
+                        out+="1"
+                    else:
+                        out+="0"
+                    #end
+                #end
+                out+="\n"
+            #end
+
+            out=self.string_bit_cal(out,frame_data ,"or")
+            return out
+
+
+#endclass
+

django/madrix/contrib/widgets.py

+from django.forms.widgets import Widget
+from django.forms.util import flatatt
+from django.utils.encoding import StrAndUnicode, force_unicode
+from django.utils.html import escape, conditional_escape
+from django.utils.safestring import mark_safe
+
+class TextareaNoCols(Widget):
+    def __init__(self, attrs=None):
+        # The 'rows' and 'cols' attributes are required for HTML correctness.
+        self.attrs = {'rows': '10'}
+        if attrs:
+            self.attrs.update(attrs)
+
+    def render(self, name, value, attrs=None):
+        if value is None: value = ''
+        value = force_unicode(value)
+        final_attrs = self.build_attrs(attrs, name=name)
+        return mark_safe(u'<textarea%s>%s</textarea>' % (flatatt(final_attrs),
+                conditional_escape(force_unicode(value))))

django/madrix/core/__init__.py

Empty file added.

django/madrix/core/models.py

+from django.db import models
+
+# Create your models here.

django/madrix/core/views.py

+# vim: fileencoding=utf8
+import os
+import sys
+from email.Header import Header
+from cStringIO import StringIO
+import random
+import sha
+import string
+import re
+
+from django.http import HttpResponse, HttpResponseRedirect, Http404
+from django.contrib.auth import login, authenticate
+from django.shortcuts import render_to_response
+from django.template import Context, RequestContext, loader
+from django.template.loader import get_template, render_to_string
+from django.contrib.auth.decorators import login_required
+from django.core.urlresolvers import reverse
+from django.core.mail import SMTPConnection
+from django.conf import settings
+
+from contrib.mail import FixedEmailMessage as EmailMessage
+from news.models import News
+from movie.models import Movie
+from account.models import DISK_AVAILABLE, PLAN_FEE
+from account.forms import *
+from movie.forms import *
+
+def index(request):
+    dictionary = {}    
+
+    if request.user.is_authenticated():
+        return HttpResponseRedirect(reverse('mypage'))
+
+    # News 取得
+    dictionary['news_list'] = News.objects.all().order_by('-created_at')[0:3]
+
+    return render_to_response('index.html',
+                              dictionary,
+                              context_instance=RequestContext(request))
+
+def mylogin(request):
+    """Login Form"""
+
+    dictionary = {}
+    next = request.GET.get('next', '')
+
+    if request.method == 'POST':
+        form = LoginForm(request.POST)
+        if form.is_valid():
+            user = authenticate(
+                username=form.cleaned_data['username'],
+                password=form.cleaned_data['password']
+            )
+
+            ### Login Success
+            if user is not None:
+                if user.is_active:
+                    login(request, user)
+                    if next:
+                        return HttpResponseRedirect(next)
+                    return HttpResponseRedirect(reverse('index'))
+                ### this user is disabled
+                dictionary['error'] = u'現在アカウントが無効です。'
+            else:
+                dictionary['error'] = u'メールアドレスまたはパスワードが違います。'
+        else:
+            dictionary['error'] = u'メールアドレスまたはパスワードが違います。'
+        dictionary['form'] = form
+
+    elif request.method == 'GET':
+        dictionary['form'] = LoginForm()
+
+    return render_to_response('login.html',
+                              dictionary,
+                              context_instance=RequestContext(request))
+
+@login_required
+def mypage(request):
+    dictionary = {}    
+
+    if not request.user.is_active:
+        return HttpResponseRedirect(reverse('error_disabled'))
+
+    disk_use = dictionary['disk_use'] = float(getsize(settings.MEDIA_ROOT+'store/'+request.user.username))
+    disk_available = dictionary['disk_available'] = float(DISK_AVAILABLE[request.user.get_profile().plan])
+
+    if disk_use >= disk_available:
+        dictionary['over_quota'] = True
+
+    # 動画一覧 取得
+    dictionary['movie_list'] = Movie.objects.filter(user=request.user).order_by('-id')
+
+    return render_to_response('mypage/index.html',
+                              dictionary,
+                              context_instance=RequestContext(request))
+
+@login_required
+def mypage_upload(request):
+    dictionary = {}    
+
+    if not request.user.is_active:
+        return HttpResponseRedirect(reverse('error_disabled'))
+
+    disk_use = dictionary['disk_use'] = float(getsize(settings.MEDIA_ROOT+'store/'+request.user.username))
+    disk_available = dictionary['disk_available'] = float(DISK_AVAILABLE[request.user.get_profile().plan])
+
+    if disk_use >= disk_available:
+        dictionary['over_quota'] = True
+
+    if request.method == 'POST':
+        form = MovieForm(request.POST, request.FILES)
+        if form.is_valid():
+            new_obj = form.save(commit=False)
+            new_obj.user = request.user
+            new_obj.save()
+            return HttpResponseRedirect(reverse('mypage'))
+        else:
+            dictionary['form'] = form
+
+    # Request Method `GET` or Edit
+    elif request.method == 'GET':
+        dictionary['form'] = MovieForm({'user': request.user.id})
+
+    return render_to_response('mypage/upload.html',
+                              dictionary,
+                              context_instance=RequestContext(request))
+
+@login_required
+def movie_delete(request, movie_id):
+    obj = Movie.objects.get(pk=movie_id)
+    try:
+        obj.delete()
+    except:
+        pass
+    return HttpResponseRedirect(reverse('mypage'))
+
+@login_required
+def movie_edit(request, movie_id):
+    dictionary = {}    
+    if not request.user.is_active:
+        return HttpResponseRedirect(reverse('error_disabled'))
+
+    disk_use = dictionary['disk_use'] = float(getsize(settings.MEDIA_ROOT+'store/'+request.user.username))
+    disk_available = dictionary['disk_available'] = float(DISK_AVAILABLE[request.user.get_profile().plan])
+
+    if disk_use >= disk_available:
+        dictionary['over_quota'] = True
+
+    try:
+        movie = Movie.objects.get(pk=movie_id)
+    except Movie.DoesNotExist, e:
+        raise Http404
+
+    if request.method == 'POST':
+        form = MovieForm(request.POST, request.FILES, instance=movie)
+        if form.is_valid():
+            new_obj = form.save(commit=False)
+            new_obj.user = request.user
+            new_obj.save()
+            return HttpResponseRedirect(reverse('mypage'))
+        else:
+            dictionary['form'] = form
+
+    # Request Method `GET` or Edit
+    elif request.method == 'GET':
+        dictionary['form'] = MovieForm(instance=movie)
+    obj = Movie.objects.get(pk=movie_id)
+    return render_to_response('mypage/movie_edit.html',
+                              dictionary,
+                              context_instance=RequestContext(request))
+
+
+def play(request, movie_id):
+    dictionary = {}    
+
+    dev = request.device
+    try:
+        movie = Movie.objects.get(pk=movie_id)
+    except Movie.DoesNotExist, e:
+        raise Http404
+    if dev.is_ezweb():
+        movie.filename = movie.get_3g2
+    else:
+        movie.filename = movie.get_3gp
+    dictionary['movie'] = movie
+    dictionary['device'] = dev
+
+    return render_to_response('play.html',
+                              dictionary,
+                              context_instance=RequestContext(request))
+
+def qrcode(request, movie_id):
+    dictionary = {}    
+
+    buffer = StringIO()
+
+    movie = Movie.objects.get(pk=movie_id)
+    img = create_qrcode('http://madrix.jp/play/' + str(movie.id) + '/')
+    img.save(buffer, 'PNG')