Commit d113f514 authored by Giuseppe Terrasi's avatar Giuseppe Terrasi

remove all .svn folders

parent 07297561

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

K 25
svn:wc:ra_dav:version-url
V 33
/svnroot/!svn/ver/1272/osqa/trunk
END
settings.py
K 25
svn:wc:ra_dav:version-url
V 45
/svnroot/!svn/ver/1242/osqa/trunk/settings.py
END
rmpyc
K 25
svn:wc:ra_dav:version-url
V 37
/svnroot/!svn/ver/17/osqa/trunk/rmpyc
END
urls.py
K 25
svn:wc:ra_dav:version-url
V 41
/svnroot/!svn/ver/1077/osqa/trunk/urls.py
END
osqa.wsgi.dist
K 25
svn:wc:ra_dav:version-url
V 47
/svnroot/!svn/ver/618/osqa/trunk/osqa.wsgi.dist
END
manage.py
K 25
svn:wc:ra_dav:version-url
V 43
/svnroot/!svn/ver/1077/osqa/trunk/manage.py
END
LICENSE
K 25
svn:wc:ra_dav:version-url
V 39
/svnroot/!svn/ver/79/osqa/trunk/LICENSE
END
osqa.iml
K 25
svn:wc:ra_dav:version-url
V 42
/svnroot/!svn/ver/1261/osqa/trunk/osqa.iml
END
settings_local.py.dist
K 25
svn:wc:ra_dav:version-url
V 56
/svnroot/!svn/ver/1122/osqa/trunk/settings_local.py.dist
END
.project
K 25
svn:wc:ra_dav:version-url
V 41
/svnroot/!svn/ver/186/osqa/trunk/.project
END
__init__.py
K 25
svn:wc:ra_dav:version-url
V 45
/svnroot/!svn/ver/1077/osqa/trunk/__init__.py
END
INSTALL
K 25
svn:wc:ra_dav:version-url
V 40
/svnroot/!svn/ver/361/osqa/trunk/INSTALL
END
K 10
svn:ignore
V 90
.pydevproject
cache
settings_local.py
.settings
.idea
*.iml
osqa.wsgi
jambazov.ipr
K 13
svn:mergeinfo
V 182
/osqa/branches/cacheimp:874-939
/osqa/branches/carpenter:691-725
/osqa/branches/hernani:772-832
/osqa/branches/jambazov:675-831
/osqa/branches/notification-config:809,811-812,825-827
K 19
svnmerge-integrated
V 33
/osqa/branches/experimental:1-105
END
10
dir
1272
http://svn.osqa.net/svnroot/osqa/trunk
http://svn.osqa.net/svnroot
2012-06-15T18:17:36.689322Z
1272
jordan
has-props
0cfe37f9-358a-4d5e-be75-b63607b5c754
.project
file
2012-06-22T20:34:49.077242Z
c88742221eebb0ad28590009c876a103
2010-05-09T16:37:31.070203Z
186
rick
602
__init__.py
file
2012-06-22T20:34:49.077242Z
d41d8cd98f00b204e9800998ecf8427e
2011-06-25T03:50:15.766114Z
1077
jordan
has-props
0
settings.py
file
2012-06-22T20:34:49.081240Z
c27b585afca8fb14dfcd889811b976f5
2012-04-03T23:01:24.940723Z
1242
jordan
has-props
4660
forum
dir
rmpyc
file
2012-06-22T20:34:49.081240Z
ef04cd0870a8a5c4e7b84f7aadf4afcf
2010-04-10T04:19:53.735481Z
17
hernani
26
locale
dir
tmp
dir
cron
dir
settings_local.py.dist
file
2012-06-22T20:34:49.081240Z
7eb057d1a82797568b14d5e6ec98a360
2011-07-17T18:20:29.006551Z
1122
jordan
1342
INSTALL
file
2012-06-22T20:34:49.081240Z
1ebe0341bc13bafab9b49e1fdc16abd0
2010-06-03T01:55:59.867375Z
361
matt
159
urls.py
file
2012-06-22T20:34:49.081240Z
2ab53b48e9974e3f0284d56180af472e
2011-06-25T03:50:15.766114Z
1077
jordan
has-props
417
osqa.wsgi.dist
file
2012-06-22T20:34:49.081240Z
5f6118efa1353e400c19dfbde9646622
2010-11-23T22:39:56.121718Z
618
claycarpenter
495
manage.py
file
2012-06-22T20:34:49.077242Z
18a5768ff203b109efc389760a4eef5a
2011-06-25T03:50:15.766114Z
1077
jordan
has-props
590
forum_modules
dir
log
dir
LICENSE
file
2012-06-22T20:34:49.077242Z
780ed67b633b197f1165ed05b1182609
2010-04-27T21:31:30.438705Z
79
rick
681
osqa.iml
file
2012-06-22T20:34:49.077242Z
bac9c1a592576ad4c6ef59990ffe5009
2012-05-09T20:59:46.733114Z
1261
jordan
1066
K 13
svn:eol-style
V 6
native
END
K 13
svn:eol-style
V 6
native
END
K 13
svn:eol-style
V 6
native
K 13
svn:mergeinfo
V 250
/osqa/branches/cacheimp/settings.py:874-931
/osqa/branches/carpenter/settings.py:691-725
/osqa/branches/hernani/settings.py:772-832
/osqa/branches/jambazov/settings.py:675-831
/osqa/branches/notification-config/settings.py:693-794,809,811-812,825-827
END
K 13
svn:eol-style
V 6
native
END
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>osqa-pydev</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.python.pydev.PyDevBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.python.pydev.pythonNature</nature>
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
<nature>org.python.pydev.django.djangoNature</nature>
</natures>
</projectDescription>
For installation instruction go to:
http://wiki.osqa.net/display/docs/Home
The wiki contains many recipes to help you install on different hosting providers.
\ No newline at end of file
Copyright (c) 2010. OSQA
Some portions Copyright (c) 2009 Chen Gang
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
#!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError, e:
import traceback
traceback.print_exc()
import sys
sys.stderr.write("Error: Can't find the file 'forms.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file forms.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="FacetManager">
<facet type="django" name="Django">
<configuration>
<option name="rootFolder" value="$MODULE_DIR$" />
<option name="settingsModule" value="settings.py" />
<option name="manageScript" value="manage.py" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="Python 2.7.1 (/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TemplatesService">
<option name="templateLanguage" value="Django" />
<option name="TEMPLATE_CONFIGURATION" value="Django" />
<option name="TEMPLATE_FOLDERS">
<list>
<option value="$MODULE_DIR$/templates" />
</list>
</option>
</component>
</module>
import os
import sys
sys.path.append('/path/to_dir_above')
sys.path.append('/path/to_dir_above/osqa')
# The first part of this module name should be identical to the directory name
# of the OSQA source. For instance, if the full path to OSQA is
# /home/osqa/osqa-server, then the DJANGO_SETTINGS_MODULE should have a value
# of 'osqa-server.settings'.
os.environ['DJANGO_SETTINGS_MODULE'] = 'osqa.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
# encoding:utf-8
import os.path
import sys
SITE_ID = 1
ADMIN_MEDIA_PREFIX = '/admin_media/'
SECRET_KEY = '$oo^&_m&qwbib=(_4m_n*zn-d=g#s0he5fx9xonnym#8p6yigm'
CACHE_MAX_KEY_LENGTH = 235
MIDDLEWARE_CLASSES = [
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
'forum.middleware.django_cookies.CookiePreHandlerMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'forum.middleware.extended_user.ExtendedUser',
'forum.middleware.anon_user.ConnectToSessionMessagesMiddleware',
'forum.middleware.request_utils.RequestUtils',
'forum.middleware.cancel.CancelActionMiddleware',
'forum.middleware.admin_messages.AdminMessagesMiddleware',
'forum.middleware.custom_pages.CustomPagesFallbackMiddleware',
'django.middleware.transaction.TransactionMiddleware',
'forum.middleware.django_cookies.CookiePostHandlerMiddleware',
]
TEMPLATE_CONTEXT_PROCESSORS = [
'django.core.context_processors.request',
'forum.context.application_settings',
'forum.user_messages.context_processors.user_messages',
'django.core.context_processors.auth',
]
ROOT_URLCONF = 'urls'
APPEND_SLASH = True
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__),'forum','skins').replace('\\','/'),
)
FILE_UPLOAD_TEMP_DIR = os.path.join(os.path.dirname(__file__), 'tmp').replace('\\','/')
FILE_UPLOAD_HANDLERS = ("django.core.files.uploadhandler.MemoryFileUploadHandler",
"django.core.files.uploadhandler.TemporaryFileUploadHandler",)
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
ALLOW_FILE_TYPES = ('.jpg', '.jpeg', '.gif', '.bmp', '.png', '.tiff')
ALLOW_MAX_FILE_SIZE = 1024 * 1024
# User settings
from settings_local import *
if DEBUG:
TEMPLATE_LOADERS = [
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
'forum.modules.template_loader.module_templates_loader',
'forum.skins.load_template_source',
]
else:
TEMPLATE_LOADERS = [
('django.template.loaders.cached.Loader',(
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
'forum.modules.template_loader.module_templates_loader',
'forum.skins.load_template_source',
)),
]
try:
if len(FORUM_SCRIPT_ALIAS) > 0:
APP_URL = '%s/%s' % (APP_URL, FORUM_SCRIPT_ALIAS[:-1])
except NameError:
pass
app_url_split = APP_URL.split("://")
APP_PROTOCOL = app_url_split[0]
APP_DOMAIN = app_url_split[1].split('/')[0]
APP_BASE_URL = '%s://%s' % (APP_PROTOCOL, APP_DOMAIN)
FORCE_SCRIPT_NAME = ''
for path in app_url_split[1].split('/')[1:]:
FORCE_SCRIPT_NAME = FORCE_SCRIPT_NAME + '/' + path
if FORCE_SCRIPT_NAME.endswith('/'):
FORCE_SCRIPT_NAME = FORCE_SCRIPT_NAME[:-1]
#Module system initialization
MODULES_PACKAGE = 'forum_modules'
MODULES_FOLDER = os.path.join(SITE_SRC_ROOT, MODULES_PACKAGE)
MODULE_LIST = filter(lambda m: getattr(m, 'CAN_USE', True), [
__import__('forum_modules.%s' % f, globals(), locals(), ['forum_modules'])
for f in os.listdir(MODULES_FOLDER)
if os.path.isdir(os.path.join(MODULES_FOLDER, f)) and
os.path.exists(os.path.join(MODULES_FOLDER, "%s/__init__.py" % f)) and
not f in DISABLED_MODULES
])
[MIDDLEWARE_CLASSES.extend(
["%s.%s" % (m.__name__, mc) for mc in getattr(m, 'MIDDLEWARE_CLASSES', [])]
) for m in MODULE_LIST]
[TEMPLATE_LOADERS.extend(
["%s.%s" % (m.__name__, tl) for tl in getattr(m, 'TEMPLATE_LOADERS', [])]
) for m in MODULE_LIST]
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.humanize',
'django.contrib.sitemaps',
'django.contrib.markup',
'forum',
]
if DEBUG:
try:
import debug_toolbar
MIDDLEWARE_CLASSES.append('debug_toolbar.middleware.DebugToolbarMiddleware')
INSTALLED_APPS.append('debug_toolbar')
except:
pass
try:
import south
INSTALLED_APPS.append('south')
except:
pass
# Try loading Gunicorn web server
try:
import gunicorn
INSTALLED_APPS.append('gunicorn')
except ImportError:
pass
if not DEBUG:
try:
import rosetta
INSTALLED_APPS.append('rosetta')
except:
pass
AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend',]
# encoding:utf-8
import os.path
SITE_SRC_ROOT = os.path.dirname(__file__)
LOG_FILENAME = 'django.osqa.log'
#for logging
import logging
logging.basicConfig(
filename=os.path.join(SITE_SRC_ROOT, 'log', LOG_FILENAME),
level=logging.ERROR,
format='%(pathname)s TIME: %(asctime)s MSG: %(filename)s:%(funcName)s:%(lineno)d %(message)s',
)
#ADMINS and MANAGERS
ADMINS = ()
MANAGERS = ADMINS
DEBUG = False
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': True
}
TEMPLATE_DEBUG = DEBUG
INTERNAL_IPS = ('127.0.0.1',)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'osqa',
'USER': 'root',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
CACHE_BACKEND = 'file://%s' % os.path.join(os.path.dirname(__file__),'cache').replace('\\','/')
#CACHE_BACKEND = 'dummy://'
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
# This should be equal to your domain name, plus the web application context.
# This shouldn't be followed by a trailing slash.
# I.e., http://www.yoursite.com or http://www.hostedsite.com/yourhostapp
APP_URL = 'http://'
#LOCALIZATIONS
TIME_ZONE = 'America/New_York'
#OTHER SETTINGS
USE_I18N = True
LANGUAGE_CODE = 'en'
DJANGO_VERSION = 1.1
OSQA_DEFAULT_SKIN = 'default'
DISABLED_MODULES = ['books', 'recaptcha', 'project_badges']
from django.conf.urls.defaults import *
from django.utils.translation import ugettext as _
from django.conf import settings
urlpatterns = patterns('',
(r'', include('forum.urls')),
)
if 'rosetta' in settings.INSTALLED_APPS:
urlpatterns = patterns('',
url(r'^rosetta/', include('rosetta.urls')),
) + urlpatterns
handler404 = 'forum.views.meta.page'
handler500 = 'forum.views.meta.error_handler'
K 25
svn:wc:ra_dav:version-url
V 36
/svnroot/!svn/ver/79/osqa/trunk/cron
END
send_email_alerts_virtualenv
K 25
svn:wc:ra_dav:version-url
V 65
/svnroot/!svn/ver/17/osqa/trunk/cron/send_email_alerts_virtualenv
END
send_email_alerts
K 25
svn:wc:ra_dav:version-url
V 54
/svnroot/!svn/ver/17/osqa/trunk/cron/send_email_alerts
END
README
K 25
svn:wc:ra_dav:version-url
V 43
/svnroot/!svn/ver/17/osqa/trunk/cron/README
END
10
dir
1272
http://svn.osqa.net/svnroot/osqa/trunk/cron
http://svn.osqa.net/svnroot
2010-04-27T21:31:30.438705Z
79
rick
0cfe37f9-358a-4d5e-be75-b63607b5c754
send_email_alerts_virtualenv
file
2012-06-22T20:34:49.069246Z
821ff88879734fcf8208b4144c55bf91
2010-04-10T04:19:53.735481Z
17
hernani
238
send_email_alerts
file
2012-06-22T20:34:49.069246Z
42f0817abe543fd78d58ad9415696bb8
2010-04-10T04:19:53.735481Z
17
hernani
161
README
file
2012-06-22T20:34:49.069246Z
84bab49c86457d38f5b9e450d8ac38cf
2010-04-10T04:19:53.735481Z
17
hernani
184
this directory contains sample commands to be executed
by cron
files with names ending "virtuanenv" should work under Python virtualenv system
other files - with standard unix setup
#!/bin/sh
PYTHONPATH=/path/to/dir_above_osqa_site
export PYTHONPATH
PROJECT_ROOT=$PYTHONPATH/osqa_site
/path/to/python $PROJECT_ROOT/manage.py send_email_alerts
#!/bin/sh
WORKON_HOME=~/envs/osqa
PROJECT_ROOT=~/webapps/osqa_server/projects/osqa/
# activate virtual environment
. $WORKON_HOME/bin/activate
cd $PROJECT_ROOT
python manage.py send_email_alerts >> $PROJECT_ROOT/log/cron_mail.log 2>&1
K 25
svn:wc:ra_dav:version-url
V 39
/svnroot/!svn/ver/1272/osqa/trunk/forum
END
context.py
K 25
svn:wc:ra_dav:version-url
V 50
/svnroot/!svn/ver/1077/osqa/trunk/forum/context.py
END
urls.py
K 25
svn:wc:ra_dav:version-url
V 47
/svnroot/!svn/ver/1212/osqa/trunk/forum/urls.py
END
subscriptions.py
K 25
svn:wc:ra_dav:version-url
V 56
/svnroot/!svn/ver/1246/osqa/trunk/forum/subscriptions.py
END
admin.py
K 25
svn:wc:ra_dav:version-url
V 48
/svnroot/!svn/ver/1077/osqa/trunk/forum/admin.py
END
registry.py
K 25
svn:wc:ra_dav:version-url
V 51
/svnroot/!svn/ver/1212/osqa/trunk/forum/registry.py
END
base.py
K 25
svn:wc:ra_dav:version-url
V 47
/svnroot/!svn/ver/1079/osqa/trunk/forum/base.py
END
__init__.py
K 25
svn:wc:ra_dav:version-url
V 51
/svnroot/!svn/ver/1180/osqa/trunk/forum/__init__.py
END
http_responses.py
K 25
svn:wc:ra_dav:version-url
V 57
/svnroot/!svn/ver/1077/osqa/trunk/forum/http_responses.py
END
startup.py
K 25
svn:wc:ra_dav:version-url
V 50
/svnroot/!svn/ver/1077/osqa/trunk/forum/startup.py
END
sitemap.py
K 25
svn:wc:ra_dav:version-url
V 50
/svnroot/!svn/ver/1081/osqa/trunk/forum/sitemap.py
END
feed.py
K 25
svn:wc:ra_dav:version-url
V 47
/svnroot/!svn/ver/1246/osqa/trunk/forum/feed.py
END
10
dir
1272
http://svn.osqa.net/svnroot/osqa/trunk/forum
http://svn.osqa.net/svnroot
2012-06-15T18:17:36.689322Z
1272
jordan
0cfe37f9-358a-4d5e-be75-b63607b5c754
forms
dir
__init__.py
file
2012-06-22T20:34:47.853852Z
d6e7bd74e79bc205db528cca1af22003
2011-09-30T11:36:17.877893Z
1180
hernani
has-props
114
skins
dir
startup.py
file
2012-06-22T20:34:47.857850Z
68473076745f5155ea5b4ce9d6950673
2011-06-25T03:50:15.766114Z
1077
jordan
has-props
305
sitemap.py
file
2012-06-22T20:34:47.857850Z
1cd8cf88cd769e2ab46caa5ffe80efa1
2011-06-27T16:46:21.599025Z
1081
jordan
has-props
3881
templatetags
dir
feed.py
file
2012-06-22T20:34:47.857850Z
a6679f4865d746da0fa322ae3a077862
2012-04-08T00:25:31.252125Z
1246
jordan
has-props
3824
views
dir
subscriptions.py
file
2012-06-22T20:34:47.857850Z
f53172b394d438579897472a2cafff3c
2012-04-08T00:25:31.252125Z
1246
jordan
has-props
6928
registry.py
file
2012-06-22T20:34:47.861848Z
ba45cfdeeaf1737b6fda7e3e0e3f133e
2011-12-15T19:46:30.210804Z
1212
jordan
has-props
6186
utils
dir
actions
dir
settings
dir
base.py
file
2012-06-22T20:34:47.861848Z
13610efe03dee792bc3db5365823e303
2011-06-25T15:13:15.337221Z
1079
jordan
429
markdownext
dir
user_messages
dir
upfiles
dir
http_responses.py
file
2012-06-22T20:34:47.861848Z
3bcf17e7d1e6949ecda03db964c788cf
2011-06-25T03:50:15.766114Z
1077
jordan
has-props
1567
modules
dir
context.py
file
2012-06-22T20:34:47.861848Z
9e9ea720fd8767041605f0d145e4fca6
2011-06-25T03:50:15.766114Z
1077
jordan
has-props
605
migrations
dir
management
dir
urls.py
file
2012-06-22T20:34:47.865846Z
2dd887b07b3618460af9a4b843e3eb90
2011-12-15T19:46:30.210804Z
1212
jordan
has-props
12521
middleware
dir
authentication
dir
admin.py
file
2012-06-22T20:34:47.853852Z
676bf9d6de1e1a1054583ca167f4a754
2011-06-25T03:50:15.766114Z
1077
jordan
has-props
1746
models
dir
badges
dir
K 13
svn:eol-style
V 6
native
END
K 13
svn:eol-style
V 6
native
END
K 13
svn:eol-style
V 6
native
K 13
svn:mergeinfo
V 285
/osqa/branches/cacheimp/forum/subscriptions.py:874-939
/osqa/branches/carpenter/forum/subscriptions.py:691-725
/osqa/branches/hernani/forum/subscriptions.py:772-832
/osqa/branches/jambazov/forum/subscriptions.py:675-831
/osqa/branches/notification-config/forum/subscriptions.py:693-846
END
K 13
svn:eol-style
V 6
native
K 13
svn:mergeinfo
V 260
/osqa/branches/cacheimp/forum/urls.py:874-939
/osqa/branches/carpenter/forum/urls.py:691-725
/osqa/branches/hernani/forum/urls.py:772-832
/osqa/branches/jambazov/forum/urls.py:675-831
/osqa/branches/notification-config/forum/urls.py:693-793,809,811-812,825-827
END
class RequestHolder(object):
def __init__(self):
self.request = None
REQUEST_HOLDER = RequestHolder()
\ No newline at end of file
# -*- coding: utf-8 -*-
#from django.contrib import admin
#from models import *
#
#class AnonymousQuestionAdmin(admin.ModelAdmin):
# """AnonymousQuestion admin class"""
#
#class NodeAdmin(admin.ModelAdmin):
# """Question admin class"""
#
#class TagAdmin(admin.ModelAdmin):
# """Tag admin class"""
#
#class Answerdmin(admin.ModelAdmin):
# """Answer admin class"""
#
#class CommentAdmin(admin.ModelAdmin):
# """ admin class"""
#
#class VoteAdmin(admin.ModelAdmin):
# """ admin class"""
#
#class FlaggedItemAdmin(admin.ModelAdmin):
# """ admin class"""
#
#class FavoriteQuestionAdmin(admin.ModelAdmin):
# """ admin class"""
#
#class QuestionRevisionAdmin(admin.ModelAdmin):
# """ admin class"""
#
#class AnswerRevisionAdmin(admin.ModelAdmin):
# """ admin class"""
#
#class AwardAdmin(admin.ModelAdmin):
# """ admin class"""
#
#class BadgeAdmin(admin.ModelAdmin):
# """ admin class"""
#
#class ReputeAdmin(admin.ModelAdmin):
# """ admin class"""
#
#class ActionAdmin(admin.ModelAdmin):
# """ admin class"""
#class BookAdmin(admin.ModelAdmin):
# """ admin class"""
#class BookAuthorInfoAdmin(admin.ModelAdmin):
# """ admin class"""
#class BookAuthorRssAdmin(admin.ModelAdmin):
# """ admin class"""
#admin.site.register(Node, NodeAdmin)
#admin.site.register(Tag, TagAdmin)
#admin.site.register(QuestionRevision, QuestionRevisionAdmin)
#admin.site.register(AnswerRevision, AnswerRevisionAdmin)
#admin.site.register(Badge, BadgeAdmin)
#admin.site.register(Award, AwardAdmin)
#admin.site.register(Action, ActionAdmin)
#admin.site.register(Book, BookAdmin)
#admin.site.register(BookAuthorInfo, BookAuthorInfoAdmin)
#admin.site.register(BookAuthorRss, BookAuthorRssAdmin)
from django.conf import settings as django_settings
def get_database_engine():
try:
database_type = django_settings.DATABASE_ENGINE
if len(database_type) == 0:
raise Exception('Empty old style database engine')
except:
try:
database_type = django_settings.DATABASES['default']['ENGINE']
except:
database_type = 'unknown'
return str(database_type)
\ No newline at end of file
from forum import settings
def application_settings(context):
return {'settings': settings}
def auth_processor(request):
if hasattr(request, 'user'):
user = request.user
if user.is_authenticated():
messages = user.message_set.all()
else:
messages = None
else:
from django.contrib.auth.models import AnonymousUser
user = AnonymousUser()
messages = None
from django.core.context_processors import PermWrapper
return {
'user': user,
'messages': messages,
'perms': PermWrapper(user),
}
# -*- coding: utf-8 -*-
try:
from django.contrib.syndication.views import Feed, FeedDoesNotExist, add_domain
old_version = False
except:
from django.contrib.syndication.feeds import Feed, FeedDoesNotExist, add_domain
old_version = True
from django.http import HttpResponse
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
from models import Question
from forum import settings
from forum.modules import decorate
from forum.utils.pagination import generate_uri
@decorate(add_domain, needs_origin=False)
def add_domain(domain, url, *args, **kwargs):
return "%s%s" % (settings.APP_BASE_URL, url)
class BaseNodeFeed(Feed):
if old_version:
title_template = "feeds/rss_title.html"
description_template = "feeds/rss_description.html"
def __init__(self, request, title, description, url):
self._title = u"%s" % smart_unicode(title)
self._description = mark_safe(u"%s" % smart_unicode(description))
self._url = url
if old_version:
super(BaseNodeFeed, self).__init__('', request)
def title(self):
return u"%s" % smart_unicode(self._title)
def link(self):
return self._url
def description(self):
return u"%s" % smart_unicode(self._description)
def item_title(self, item):
return u"%s" % smart_unicode(item.title)
def item_description(self, item):
return u"%s" % smart_unicode(item.html)
def item_link(self, item):
return item.leaf.get_absolute_url()
def item_author_name(self, item):
return u"%s" % smart_unicode(item.author.username)
def item_author_link(self, item):
return item.author.get_profile_url()
def item_pubdate(self, item):
return item.added_at
if old_version:
def __call__(self, request):
feedgen = self.get_feed('')
response = HttpResponse(mimetype=feedgen.mime_type)
feedgen.write(response, 'utf-8')
return response
class RssQuestionFeed(BaseNodeFeed):
def __init__(self, request, question_list, title, description):
url = request.path + "?" + generate_uri(request.GET, (_('page'), _('pagesize'), _('sort')))
super(RssQuestionFeed, self).__init__(request, title, description, url)
self._question_list = question_list
def item_categories(self, item):
return item.tagname_list()
def _items(self):
return self._question_list
def items(self):
return self._items()[:30]
class RssAnswerFeed(BaseNodeFeed):
if old_version:
title_template = "feeds/rss_answer_title.html"
def __init__(self, request, question, include_comments=False):
super(RssAnswerFeed, self).__init__(
request, _("Answers to: %s") % smart_unicode(question.title),
question.html,
question.get_absolute_url()
)
self._question = question
self._include_comments = include_comments
def _items(self):
if self._include_comments:
qs = self._question.all_children
else:
qs = self._question.answers
return qs.filter_state(deleted=False).order_by('-added_at')
def items(self):
return self._items()[:30]
def item_title(self, item):
if item.node_type == "answer":
return _("Answer by %s") % smart_unicode(item.author.username)
else:
return _("Comment by %(cauthor)s on %(pauthor)s's %(qora)s") % dict(
cauthor=smart_unicode(item.author.username),
pauthor=smart_unicode(item.parent.author.username),
qora=(item.parent.node_type == "answer" and _("answer") or _("question"))
)
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.template import RequestContext
from forum import settings
class HttpResponseServiceUnavailable(HttpResponse):
def __init__(self, message):
super(HttpResponseServiceUnavailable, self).__init__(
content=render_to_string('503.html', {
'message': message,
'app_logo': settings.APP_LOGO,
'app_title': settings.APP_TITLE
}), status=503)
class HttpResponseUnauthorized(HttpResponse):
def __init__(self, request):
if request.user.is_authenticated():
super(HttpResponseUnauthorized, self).__init__(
content=render_to_string('403.html', context_instance=RequestContext(request)),
status=403
)
else:
super(HttpResponseUnauthorized, self).__init__(
content=render_to_string('401.html', context_instance=RequestContext(request)),
status=401
)
class HttpResponseNotFound(HttpResponse):
def __init__(self, request):
super(HttpResponseNotFound, self).__init__(
content=render_to_string('404.html', context_instance=RequestContext(request)),
status=404
)
class HttpResponseIntServerError(HttpResponse):
def __init__(self, request):
super(HttpResponseIntServerError, self).__init__(
content=render_to_string('500.html', context_instance=RequestContext(request)),
status=500
)
\ No newline at end of file
from forum.modules import ui, get_modules_script
from django.utils.translation import ugettext as _
from django.utils.encoding import smart_unicode
from django.core.urlresolvers import reverse
from django.template.defaultfilters import slugify
from forum.models import User
from forum.templatetags.extra_tags import get_score_badge
from forum.utils.html import cleanup_urls
from forum import settings
try:
from django.template import get_templatetags_modules
modules_template_tags = get_modules_script('templatetags')
django_template_tags = get_templatetags_modules()
for m in modules_template_tags:
django_template_tags.append(m.__name__)
except:
pass
ui.register(ui.HEADER_LINKS,
ui.Link(_('faq'), ui.Url('faq'), weight=400, name='FAQ'),
ui.Link(_('about'), ui.Url('about'), weight=300, name='ABOUT'),
ui.Link(
text=lambda u, c: u.is_authenticated() and _('logout') or _('login'),
url=lambda u, c: u.is_authenticated() and reverse('logout') or reverse('auth_signin'),
weight=200, name='LOGIN/OUT'),
ui.Link(
visibility=ui.Visibility.AUTHENTICATED,
text=lambda u, c: smart_unicode(u.username),
url=lambda u, c: u.get_profile_url(),
post_code=lambda u, c: get_score_badge(u),
weight=100, name='ACCOUNT'),
ui.Link(
visibility=ui.Visibility.SUPERUSER,
text=_('administration'),
url=lambda u, c: reverse('admin_index'),
weight=0, name='ADMINISTRATION')
)
class SupportLink(ui.Link):
def can_render(self, context):
return bool(settings.SUPPORT_URL)
ui.register(ui.FOOTER_LINKS,
ui.Link(
text=_('contact'),
url=lambda u, c: settings.CONTACT_URL and settings.CONTACT_URL or "%s?next=%s" % (reverse('feedback'), cleanup_urls( c['request'].path)),
weight=400),
SupportLink(_('support'), settings.SUPPORT_URL, attrs={'target': '_blank'}, weight=300),
ui.Link(_('privacy'), ui.Url('privacy'), weight=200),
ui.Link(_('faq'), ui.Url('faq'), weight=100),
ui.Link(_('about'), ui.Url('about'), weight=0),
)
class ModerationMenuGroup(ui.AjaxMenuGroup):
def can_render(self, context):
return context['user'] != context['viewer'] and super(ModerationMenuGroup, self).can_render(context)
class SuperUserSwitchMenuItem(ui.UserMenuItem):
def can_render(self, context):
return context['viewer'].is_siteowner or not context['user'].is_superuser
ui.register(ui.USER_MENU,
ui.UserMenuItem(
label=_("edit profile"),
url=lambda u, c: reverse('edit_user', kwargs={
'id': c['user'].id,
'slug' : slugify(c['user'].username)
}),
span_attrs={'class': 'user-edit'},
weight=0,
name='EDIT_PROFILE'
),
ui.UserMenuItem(
label=_("authentication settings"),
url=lambda u, c: reverse('user_authsettings', kwargs={'id': c['user'].id}),
span_attrs={'class': 'user-auth'},
weight=100,
name='AUTH_SETTINGS'
),
ui.UserMenuItem(
label=_("email notification settings"),
url=lambda u, c: User.objects.get(id=int(c['user'].id)).get_user_subscriptions_url(),
span_attrs={'class': 'user-subscriptions'},
weight=200,
name='EMAIL_SETTINGS'
),
ui.UserMenuItem(
label=_("other preferences"),
url=lambda u, c: reverse('user_preferences', kwargs={'id': c['user'].id, 'slug': slugify(c['user'].username)}),
weight=200,
name='OTHER_PREFS'
),
ModerationMenuGroup(_("Moderation tools"), items=(
ui.UserMenuItem(
label=lambda u, c: c['user'].is_suspended() and _("withdraw suspension") or _("suspend this user"),
url=lambda u, c: reverse('user_suspend', kwargs={'id': c['user'].id}),
a_attrs=lambda u, c: {'class': c['user'].is_suspended() and 'ajax-command confirm' or 'ajax-command withprompt'},
render_to=lambda u: not u.is_superuser,
name='SUSPENSION'
),
ui.UserMenuItem(
label=lambda u, c: _("give/take karma"),
url=lambda u, c: reverse('user_award_points', kwargs={'id': c['user'].id}),
a_attrs=lambda u, c: {'id': 'award-rep-points', 'class': 'ajax-command withprompt'},
span_attrs={'class': 'user-award_rep'},
render_to=lambda u: not u.is_suspended(),
name='KARMA'
),
ui.UserMenuItem(
label=lambda u, c: c['user'].is_staff and _("remove moderator status") or _("grant moderator status"),
url=lambda u, c: reverse('user_powers', kwargs={'id': c['user'].id, 'action':c['user'].is_staff and 'remove' or 'grant', 'status': 'staff'}),
a_attrs=lambda u, c: {'class': 'ajax-command confirm'},
span_attrs={'class': 'user-moderator'},
name='MODERATOR'
),
SuperUserSwitchMenuItem(
label=lambda u, c: c['user'].is_superuser and _("remove super user status") or _("grant super user status"),
url=lambda u, c: reverse('user_powers', kwargs={'id': c['user'].id, 'action':c['user'].is_superuser and 'remove' or 'grant', 'status': 'super'}),
a_attrs=lambda u, c: {'class': 'ajax-command confirm'},
span_attrs={'class': 'user-superuser'},
name='SUPERUSER'
),
), visibility=ui.Visibility.SUPERUSER, weight=500, name='MOD_TOOLS')
)
import re
from django.contrib.sitemaps import Sitemap
from forum.models import Question
from forum.settings import QUESTIONS_SITEMAP_LIMIT, QUESTIONS_SITEMAP_CHANGEFREQ
from django.conf import settings
from django.http import HttpResponse, Http404
from django.template import loader
from django.core import urlresolvers
from django.utils.encoding import smart_str
from django.core.paginator import EmptyPage, PageNotAnInteger
def index(request, sitemaps):
sites = []
for section, site in sitemaps.items():
if callable(site):
pages = site().paginator.num_pages
else:
pages = site.paginator.num_pages
sitemap_url = urlresolvers.reverse('sitemap_section_index', kwargs={'section': section})
# Replace double forward slashes with single ones
final_url = '%s%s' % (settings.APP_URL, sitemap_url)
final_url = re.sub("/+", "/", final_url)
final_url = final_url.replace('http:/', 'http://')
final_url = final_url.replace('https:/', 'https://')
sites.append(final_url)
xml = loader.render_to_string('sitemap_index.xml', {'sitemaps': sites})
return HttpResponse(xml, mimetype='application/xml')
def sitemap_section_index(request, section, sitemaps):
try:
sitemap = sitemaps[section]()
except KeyError:
raise Http404("Sitemap doesn't exist")
paginator = sitemap.paginator
locations = []
for page in paginator.page_range:
location = urlresolvers.reverse('sitemap_section_page', kwargs={ 'page' : page, 'section' : section })
location = '%s%s' % (settings.APP_URL, location)
location = re.sub("/+", "/", location)
location = location.replace('http:/', 'http://')
location = location.replace('https:/', 'https://')
locations.append(location)
xml = loader.render_to_string('sitemap_section_index.xml', { 'locations' : locations, })
return HttpResponse(xml, mimetype='application/xml')
def sitemap(request, sitemaps, section=None, page=1):
maps, urls = [], []
if section is not None:
if section not in sitemaps:
raise Http404("No sitemap available for section: %r" % section)
maps.append(sitemaps[section])
else:
maps = sitemaps.values()
for site in maps:
try:
if callable(site):
urls.extend(site().get_urls(page=page))
else:
urls.extend(site.get_urls(page=page))
except EmptyPage:
raise Http404("Page %s empty" % page)
except PageNotAnInteger:
raise Http404("No page '%s'" % page)
xml = smart_str(loader.render_to_string('sitemap.xml', {'urlset': urls}))
return HttpResponse(xml, mimetype='application/xml')
class OsqaSitemap(Sitemap):
limit = QUESTIONS_SITEMAP_LIMIT
changefreq = QUESTIONS_SITEMAP_CHANGEFREQ
priority = 0.5
def items(self):
return Question.objects.filter_state(deleted=False).order_by('id')
def lastmod(self, obj):
return obj.last_activity_at
def location(self, obj):
return obj.get_absolute_url()
def __get(self, name, obj, default=None):
try:
attr = getattr(self, name)
except AttributeError:
return default
if callable(attr):
return attr(obj)
return attr
def get_urls(self, page=1):
urls = []
for item in self.paginator.page(page).object_list:
loc = "%s%s" % (settings.APP_URL, self.__get('location', item))
url_info = {
'location': loc,
'lastmod': self.__get('lastmod', item, None),
'changefreq': self.__get('changefreq', item, None),
'priority': self.__get('priority', item, None)
}
urls.append(url_info)
return urls
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__),'markdownext'))
from forum.modules import get_modules_script
get_modules_script('settings')
get_modules_script('startup')
import forum.badges
import forum.subscriptions
import forum.registry
get_modules_script('registry')
import os
import re
import datetime
import logging
from forum.models import User, Question, Comment, QuestionSubscription, SubscriptionSettings, Answer
from forum.utils.mail import send_template_email
from django.utils.translation import ugettext as _
from forum.actions import AskAction, AnswerAction, CommentAction, AcceptAnswerAction, UserJoinsAction, QuestionViewAction
from forum import settings
from django.db.models import Q, F
def create_subscription_if_not_exists(question, user):
try:
subscription = QuestionSubscription.objects.get(question=question, user=user)
return subscription
except QuestionSubscription.MultipleObjectsReturned:
pass
except QuestionSubscription.DoesNotExist:
subscription = QuestionSubscription(question=question, user=user)
subscription.save()
return subscription
except Exception, e:
logging.error(e)
return False
def filter_subscribers(subscribers):
subscribers = subscribers.exclude(is_active=False)
if settings.DONT_NOTIFY_UNVALIDATED:
return subscribers.exclude(email_isvalid=False)
else:
return subscribers
def question_posted(action, new):
question = action.node
if not question.is_notifiable:
return
subscribers = User.objects.filter(
Q(subscription_settings__enable_notifications=True, subscription_settings__new_question='i') |
(Q(subscription_settings__new_question_watched_tags='i') &
Q(marked_tags__name__in=question.tagnames.split(' ')) &
Q(tag_selections__reason='good'))
).exclude(id=question.author.id).distinct()
subscribers = filter_subscribers(subscribers)
send_template_email(subscribers, "notifications/newquestion.html", {'question': question})
subscription = QuestionSubscription(question=question, user=question.author)
subscription.save()
new_subscribers = User.objects.filter(
Q(subscription_settings__all_questions=True) |
Q(subscription_settings__all_questions_watched_tags=True,
marked_tags__name__in=question.tagnames.split(' '),
tag_selections__reason='good'))
for user in new_subscribers:
create_subscription_if_not_exists(question, user)
AskAction.hook(question_posted)
def answer_posted(action, new):
answer = action.node
question = answer.question
logging.error("Answer posted: %s" % str(answer.is_notifiable))
if not answer.is_notifiable or not question.is_notifiable:
return
subscribers = question.subscribers.filter(
subscription_settings__enable_notifications=True,
subscription_settings__notify_answers=True,
subscription_settings__subscribed_questions='i'
).exclude(id=answer.author.id).distinct()
subscribers = filter_subscribers(subscribers)
send_template_email(subscribers, "notifications/newanswer.html", {'answer': answer})
create_subscription_if_not_exists(question, answer.author)
AnswerAction.hook(answer_posted)
def comment_posted(action, new):
comment = action.node
post = comment.parent
if not comment.is_notifiable or not post.is_notifiable:
return
if post.__class__ == Question:
question = post
else:
question = post.question
q_filter = Q(subscription_settings__notify_comments=True) | Q(subscription_settings__notify_comments_own_post=True, id=post.author.id)
inreply = re.search('@\w+', comment.comment)
if inreply is not None:
q_filter = q_filter | Q(subscription_settings__notify_reply_to_comments=True,
username__istartswith=inreply.group(0)[1:],
nodes__parent=post, nodes__node_type="comment")
subscribers = question.subscribers.filter(
q_filter, subscription_settings__subscribed_questions='i', subscription_settings__enable_notifications=True
).exclude(id=comment.user.id).distinct()
subscribers = filter_subscribers(subscribers)
send_template_email(subscribers, "notifications/newcomment.html", {'comment': comment})
create_subscription_if_not_exists(question, comment.user)
CommentAction.hook(comment_posted)
def answer_accepted(action, new):
question = action.node.question
if not question.is_notifiable:
return
subscribers = question.subscribers.filter(
subscription_settings__enable_notifications=True,
subscription_settings__subscribed_questions='i'
).exclude(id=action.node.nstate.accepted.by.id).distinct()
subscribers = filter_subscribers(subscribers)
send_template_email(subscribers, "notifications/answeraccepted.html", {'answer': action.node})
AcceptAnswerAction.hook(answer_accepted)
def member_joined(action, new):
subscribers = User.objects.filter(
subscription_settings__enable_notifications=True,
subscription_settings__member_joins='i'
).exclude(id=action.user.id).distinct()
subscribers = filter_subscribers(subscribers)
send_template_email(subscribers, "notifications/newmember.html", {'newmember': action.user})
UserJoinsAction.hook(member_joined)
def question_viewed(action, new):
if not action.viewuser.is_authenticated():
return
try:
subscription = QuestionSubscription.objects.get(question=action.node, user=action.viewuser)
subscription.last_view = datetime.datetime.now()
subscription.save()
except:
if action.viewuser.subscription_settings.questions_viewed:
subscription = QuestionSubscription(question=action.node, user=action.viewuser)
subscription.save()
QuestionViewAction.hook(question_viewed)
#todo: translate this
#record_answer_event_re = re.compile("You have received (a|\d+) .*new response.*")
#def record_answer_event(instance, created, **kwargs):
# if created:
# q_author = instance.question.author
# found_match = False
# #print 'going through %d messages' % q_author.message_set.all().count()
# for m in q_author.message_set.all():
## #print m.message
# # match = record_answer_event_re.search(m.message)
# if match:
# found_match = True
# try:
# cnt = int(match.group(1))
# except:
# cnt = 1
## m.message = u"You have received %d <a href=\"%s?sort=responses\">new responses</a>."\
# # % (cnt+1, q_author.get_profile_url())
#
# m.save()
# break
# if not found_match:
# msg = u"You have received a <a href=\"%s?sort=responses\">new response</a>."\
# % q_author.get_profile_url()
#
# q_author.message_set.create(message=msg)
#
#post_save.connect(record_answer_event, sender=Answer)
This diff is collapsed.
K 25
svn:wc:ra_dav:version-url
V 47
/svnroot/!svn/ver/1263/osqa/trunk/forum/actions
END
page.py
K 25
svn:wc:ra_dav:version-url
V 55
/svnroot/!svn/ver/1077/osqa/trunk/forum/actions/page.py
END
user.py
K 25
svn:wc:ra_dav:version-url
V 55
/svnroot/!svn/ver/1263/osqa/trunk/forum/actions/user.py
END
__init__.py
K 25
svn:wc:ra_dav:version-url
V 59
/svnroot/!svn/ver/1077/osqa/trunk/forum/actions/__init__.py
END
node.py
K 25
svn:wc:ra_dav:version-url
V 55
/svnroot/!svn/ver/1207/osqa/trunk/forum/actions/node.py
END
meta.py
K 25
svn:wc:ra_dav:version-url
V 55
/svnroot/!svn/ver/1077/osqa/trunk/forum/actions/meta.py
END
10
dir
1272
http://svn.osqa.net/svnroot/osqa/trunk/forum/actions
http://svn.osqa.net/svnroot
2012-05-11T00:49:34.640499Z
1263
jordan
0cfe37f9-358a-4d5e-be75-b63607b5c754
meta.py
file
2012-06-22T20:34:43.991779Z
b2adba9e3fdf64490cd5a76096cb0a6f
2011-06-25T03:50:15.766114Z
1077
jordan
has-props
7284
page.py
file
2012-06-22T20:34:43.983783Z
8f546c373588c59f9f61d12f5e972dff
2011-06-25T03:50:15.766114Z
1077
jordan
has-props
1987
user.py
file
2012-06-22T20:34:43.987781Z
c28f062ed4fe535a12867d0040177851
2012-05-11T00:49:34.640499Z
1263
jordan
has-props
8982
__init__.py
file
2012-06-22T20:34:43.987781Z
82e25126764374268741dc45b425e176
2011-06-25T03:50:15.766114Z
1077
jordan
has-props
75
node.py
file
2012-06-22T20:34:43.987781Z
0a1cea5b9183391c9ae23cdc0676a008
2011-12-04T12:29:49.682442Z
1207
jordan
has-props
10187
from meta import *
from node import *
from user import *
from page import *
\ No newline at end of file
from django.utils.translation import ugettext as _
from django.db.models import F
from forum.models.action import ActionProxy, DummyActionProxy
from forum.models import Vote, Flag
from forum import settings
class VoteAction(ActionProxy):
def update_node_score(self, inc):
self.node.score = F('score') + inc
self.node.save()
def process_vote_action(self, value):
self.update_node_score(value)
vote = Vote(node=self.node, user=self.user, action=self, value=value)
vote.save()
def cancel_action(self):
vote = self.vote
self.update_node_score(-vote.value)
vote.delete()
@classmethod
def get_for(cls, user, node):
try:
vote = Vote.objects.get(user=user, node=node)
return vote.value
except:
return None
@classmethod
def get_action_for(cls, user, node):
try:
vote = Vote.objects.get(user=user, node=node)
return vote.action
except:
return None
def describe_vote(self, vote_desc, viewer=None):
return _("%(user)s %(vote_desc)s %(post_desc)s") % {
'user': self.hyperlink(self.user.get_profile_url(), self.friendly_username(viewer, self.user)),
'vote_desc': vote_desc, 'post_desc': self.describe_node(viewer, self.node)
}
class VoteUpAction(VoteAction):
def repute_users(self):
self.repute(self.node.author, int(settings.REP_GAIN_BY_UPVOTED))
def process_action(self):
self.process_vote_action(1)
self.user.reset_vote_up_count_cache()
def cancel_action(self):
super(VoteUpAction, self).cancel_action()
self.user.reset_vote_up_count_cache()
def describe(self, viewer=None):
return self.describe_vote(_("voted up"), viewer)
class VoteDownAction(VoteAction):
def repute_users(self):
self.repute(self.node.author, -int(settings.REP_LOST_BY_DOWNVOTED))
self.repute(self.user, -int(settings.REP_LOST_BY_DOWNVOTING))
def process_action(self):
self.process_vote_action(-1)
self.user.reset_vote_down_count_cache()
def cancel_action(self):
super(VoteDownAction, self).cancel_action()
self.user.reset_vote_down_count_cache()
def describe(self, viewer=None):
return self.describe_vote(_("voted down"), viewer)
class VoteUpCommentAction(VoteUpAction):
def repute_users(self):
pass
def process_action(self):
self.process_vote_action(1)
def cancel_action(self):
super(VoteUpAction, self).cancel_action()
def describe(self, viewer=None):
return self.describe_vote(_("liked"), viewer)
class FlagAction(ActionProxy):
def repute_users(self):
self.repute(self.node.author, -int(settings.REP_LOST_BY_FLAGGED))
def process_action(self):
flag = Flag(user=self.user, node=self.node, action=self, reason=self.extra)
flag.save()
self.node.reset_flag_count_cache()
if self.node.flag_count >= int(settings.FLAG_COUNT_TO_HIDE_POST):
self.repute(self.node.author, -int(settings.REP_LOST_BY_FLAGGED_3_TIMES))
if self.node.flag_count >= int(settings.FLAG_COUNT_TO_DELETE_POST):
self.repute(self.node.author, -int(settings.REP_LOST_BY_FLAGGED_5_TIMES))
if not self.node.nis.deleted:
DeleteAction(node=self.node, user=self.user, extra="BYFLAGGED").save()
def cancel_action(self):
self.flag.delete()
self.node.reset_flag_count_cache()
@classmethod
def get_for(cls, user, node):
try:
flag = Flag.objects.get(user=user, node=node)
return flag.reason or _("No reason given")
except:
return None
def describe(self, viewer=None):
return _("%(user)s flagged %(post_desc)s: %(reason)s") % {
'user': self.hyperlink(self.user.get_profile_url(), self.friendly_username(viewer, self.user)),
'post_desc': self.describe_node(viewer, self.node), 'reason': self.extra
}
class AcceptAnswerAction(ActionProxy):
def repute_users(self):
if (self.user == self.node.parent.author) and (not self.user == self.node.author):
self.repute(self.user, int(settings.REP_GAIN_BY_ACCEPTING))
if self.user != self.node.author:
self.repute(self.node.author, int(settings.REP_GAIN_BY_ACCEPTED))
def process_action(self):
self.node.marked = True
self.node.nstate.accepted = self
self.node.save()
self.node.question.reset_accepted_count_cache()
def cancel_action(self):
self.node.marked = False
self.node.nstate.accepted = None
self.node.save()
self.node.question.reset_accepted_count_cache()
def describe(self, viewer=None):
answer = self.node
question = answer.parent
if self.user == question.author:
asker = (self.user == viewer) and _("your") or _("his")
else:
asker = self.hyperlink(question.author.get_profile_url(), question.author.username)
return _("%(user)s accepted %(answerer)s answer on %(asker)s question %(question)s") % {
'user': self.hyperlink(self.user.get_profile_url(), self.friendly_username(viewer, self.user)),
'answerer': self.hyperlink(answer.author.get_profile_url(), self.friendly_ownername(viewer, answer.author)),
'asker': asker,
'question': self.hyperlink(question.get_absolute_url(), question.title)
}
class FavoriteAction(ActionProxy):
def process_action(self):
self.node.reset_favorite_count_cache()
def cancel_action(self):
self.process_action()
def describe(self, viewer=None):
return _("%(user)s marked %(post_desc)s as favorite") % {
'user': self.hyperlink(self.user.get_profile_url(), self.friendly_username(viewer, self.user)),
'post_desc': self.describe_node(viewer, self.node),
}
class DeleteAction(ActionProxy):
def process_action(self):
self.node.mark_deleted(self)
if self.node.node_type == "answer":
self.node.question.reset_answer_count_cache()
def cancel_action(self):
self.node.mark_deleted(None)
if self.node.node_type == "answer":
self.node.question.reset_answer_count_cache()
def describe(self, viewer=None):
return _("%(user)s deleted %(post_desc)s") % {
'user': self.hyperlink(self.user.get_profile_url(), self.friendly_username(viewer, self.user)),
'post_desc': self.describe_node(viewer, self.node)
}
def reason(self):
if self.extra != "BYFLAGGED":
return self.extra
else:
return _("flagged by multiple users: ") + "; ".join([f.extra for f in FlagAction.objects.filter(node=self.node)])
class UnknownAction(ActionProxy):
pass
class QuestionViewAction(DummyActionProxy):
def __init__(self, node, user, ip=None):
self.viewuser = user
self.node = node
super(QuestionViewAction, self).__init__(ip)
def process_action(self):
self.node.extra_count = F('extra_count') + 1
self.node.save()
This diff is collapsed.
from django.utils.translation import ugettext as _
from forum.models.action import ActionProxy
from forum.models import Page
class NewPageAction(ActionProxy):
verb = _("created")
def process_data(self, **data):
title = data.pop('title')
body = data.pop('content')
page = Page(author=self.user, title=title, body=body, extra=data)
page.save()
self.node = page
def describe(self, viewer=None):
return _("%(user)s created a new page titled %(page)s") % {
'user': self.hyperlink(self.user.get_profile_url(), self.friendly_username(viewer, self.user)),
'page': self.hyperlink(self.node.get_absolute_url(), self.node.title)
}
class EditPageAction(ActionProxy):
verb = _("edited")
def process_data(self, **data):
title = data.pop('title')
body = data.pop('content')
if (title != self.node.title) or (body != self.node.body):
self.node.create_revision(self.user, title=title, body=body)
self.node.extra = data
self.node.save()
def describe(self, viewer=None):
return _("%(user)s edited the page titled %(page)s") % {
'user': self.hyperlink(self.user.get_profile_url(), self.friendly_username(viewer, self.user)),
'page': self.hyperlink(self.node.get_absolute_url(), self.node.title)
}
class PublishAction(ActionProxy):
verb = _("published")
def process_action(self):
self.node.marked = True
self.node.nstate.published = self
self.node.save()
def cancel_action(self):
self.node.marked = False
self.node.nstate.published = None
self.node.save()
def describe(self, viewer=None):
return _("%(user)s published a new page titled %(page)s") % {
'user': self.hyperlink(self.user.get_profile_url(), self.friendly_username(viewer, self.user)),
'page': self.hyperlink(self.node.get_absolute_url(), self.node.title)
}
from django.utils.translation import ungettext, ugettext as _
from django.core.urlresolvers import reverse
from django.db.models import F
from forum.models.action import ActionProxy
from forum.models import Award, Badge, ValidationHash, User
from forum import settings
from forum.settings import APP_SHORT_NAME
from forum.utils.mail import send_template_email
class UserJoinsAction(ActionProxy):
verb = _("joined")
def repute_users(self):
self.repute(self.user, int(settings.INITIAL_REP))
def process_action(self):
hash = ValidationHash.objects.create_new(self.user, 'email', [self.user.email])
send_template_email([self.user], "auth/welcome_email.html", {'validation_code': hash})
def describe(self, viewer=None):
return _("%(user)s %(have_has)s joined the %(app_name)s Q&A community") % {
'user': self.hyperlink(self.user.get_profile_url(), self.friendly_username(viewer, self.user)),
'have_has': self.viewer_or_user_verb(viewer, self.user, _('have'), _('has')),
'app_name': APP_SHORT_NAME,
}
class UserLoginAction(ActionProxy):
verb = _("logged in")
def describe(self, viewer=None):
return _("%(user)s %(have_has)s logged in") % {
'user' : self.hyperlink(self.user.get_profile_url(), self.friendly_username(viewer, self.user)),
'have_has': self.viewer_or_user_verb(viewer, self.user, _('have'), _('has')),
}
class EmailValidationAction(ActionProxy):
verb = _("validated e-mail")
def repute_users(self):
self.repute(self.user, int(settings.REP_GAIN_BY_EMAIL_VALIDATION))
def process_action(self):
self.user.email_isvalid = True
self.user.save()
def describe(self, viewer=None):
return _("%(user)s %(have_has)s validated the e-mail %(email)s") % {
'user': self.hyperlink(self.user.get_profile_url(), self.friendly_username(viewer, self.user)),
'have_has': self.viewer_or_user_verb(viewer, self.user, _('have'), _('has')),
'email' : self.user.email if viewer.is_superuser or viewer.is_staff or viewer == self.user else ""
}
class EditProfileAction(ActionProxy):
verb = _("edited profile")
def describe(self, viewer=None):
return _("%(user)s edited %(hes_or_your)s %(profile_link)s") % {
'user': self.hyperlink(self.user.get_profile_url(), self.friendly_username(viewer, self.user)),
'hes_or_your': self.viewer_or_user_verb(viewer, self.user, _('your'), _('his')),
'profile_link': self.hyperlink(self.user.get_profile_url(), _('profile')),
}
class BonusRepAction(ActionProxy):
verb = _("gave bonus")
def process_data(self, value, affected):
self._value = value
self._affected = affected
def repute_users(self):
self.repute(self._affected, self._value)
if self._value > 0:
self._affected.message_set.create(
message=_("Congratulations, you have been awarded an extra %s reputation points.") % self._value +
'<br />%s' % self.extra.get('message', _('Thank you')))
else:
self._affected.message_set.create(
message=_("You have been penalized in %s reputation points.") % self._value +
'<br />%s' % self.extra.get('message', ''))
def describe(self, viewer=None):
value = self.extra.get('value', _('unknown'))
message = self.extra.get('message', '')
try:
if int(value) > 0:
return _("%(user)s awarded an extra %(value)s reputation points to %(users)s: %(message)s") % {
'user': self.hyperlink(self.user.get_profile_url(), self.friendly_username(viewer, self.user)),
'value': value, 'users':self.affected_links(viewer), 'message': message
}
else:
return _("%(user)s penalised %(users)s in %(value)s reputation points: %(message)s") % {
'user': self.hyperlink(self.user.get_profile_url(), self.friendly_username(viewer, self.user)),
'value': value, 'users':self.affected_links(viewer), 'message': message
}
except Exception, e:
return ''
class AwardPointsAction(ActionProxy):
verb = _("gave reputation points")
def process_data(self, value, affected):
self._value = value
self._affected = affected
def repute_users(self):
self.repute(self._affected, self._value)
self.repute(self.user, -self._value)
self._affected.message_set.create(
message=_("Congratulations, you have been awarded an extra %(points)s reputation %(points_label)s on <a href=\"%(answer_url)s\">this</a> answer.") % {
'points': self._value,
'points_label': ungettext('point', 'points', self._value),
'answer_url': self.node.get_absolute_url()
})
def describe(self, viewer=None):
value = self.extra.get('value', _('unknown'))
try:
if int(value) > 0:
return _("%(user)s awarded an extra %(value)s reputation points to %(users)s") % {
'user': self.hyperlink(self.user.get_profile_url(), self.friendly_username(viewer, self.user)),
'value': value, 'users':self.affected_links(viewer),
}
else:
return _("%(user)s penalised %(users)s in %(value)s reputation points") % {
'user': self.hyperlink(self.user.get_profile_url(), self.friendly_username(viewer, self.user)),
'value': value, 'users':self.affected_links(viewer),
}
except Exception, e:
return ''
class AwardAction(ActionProxy):
verb = _("was awarded")
def process_data(self, badge, trigger):
self.__dict__['_badge'] = badge
self.__dict__['_trigger'] = trigger
def process_action(self):
badge = self.__dict__['_badge']
trigger = self.__dict__['_trigger']
award = Award(user=self.user, badge=badge, trigger=trigger, action=self)
if self.node:
award.node = self.node
award.save()
award.badge.awarded_count = F('awarded_count') + 1
award.badge.save()
if award.badge.type == Badge.GOLD:
self.user.gold += 1
if award.badge.type == Badge.SILVER:
self.user.silver += 1
if award.badge.type == Badge.BRONZE:
self.user.bronze += 1
self.user.save()
self.user.message_set.create(message=_(
"""Congratulations, you have received a badge '%(badge_name)s'. <a href="%(badge_url)s">Find out who has it, too</a>."""
) % dict(
badge_name=award.badge.name,
badge_url=award.badge.get_absolute_url()))
def cancel_action(self):
award = self.award
badge = award.badge
badge.awarded_count = F('awarded_count') - 1
badge.save()
award.delete()
@classmethod
def get_for(cls, user, badge, node=False):
try:
if node is False:
return Award.objects.get(user=user, badge=badge).action
else:
return Award.objects.get(user=user, node=node, badge=badge).action
except:
return None
def describe(self, viewer=None):
return _("%(user)s %(were_was)s awarded the %(badge_name)s badge") % {
'user': self.hyperlink(self.user.get_profile_url(), self.friendly_username(viewer, self.user)),
'were_was': self.viewer_or_user_verb(viewer, self.user, _('were'), _('was')),
'badge_name': self.award.badge.name,
}
class SuspendAction(ActionProxy):
verb = _("suspended")
def process_data(self, **kwargs):
self._suspended = kwargs.pop('suspended')
self.extra = kwargs
def repute_users(self):
self.repute(self._suspended, 0)
def process_action(self):
self._suspended.is_active = False
self._suspended.save()
def cancel_action(self):
for u in User.objects.filter(reputes__action=self).distinct():
u.is_active = True
u._pop_suspension_cache()
u.save()
u.message_set.create(message=_("Your suspension has been removed."))
def describe(self, viewer=None):
if self.extra.get('bantype', 'indefinitely') == 'forxdays' and self.extra.get('forxdays', None):
suspension = _("for %s days") % self.extra['forxdays']
else:
suspension = _("indefinetely")
return _("%(user)s suspended %(users)s %(suspension)s: %(msg)s") % {
'user': self.hyperlink(self.user.get_profile_url(), self.friendly_username(viewer, self.user)),
'users': self.affected_links(viewer), 'suspension': suspension, 'msg': self.extra.get('publicmsg', _('Bad behaviour'))
}
\ No newline at end of file
K 25
svn:wc:ra_dav:version-url
V 54
/svnroot/!svn/ver/1077/osqa/trunk/forum/authentication
END
__init__.py
K 25
svn:wc:ra_dav:version-url
V 66
/svnroot/!svn/ver/1077/osqa/trunk/forum/authentication/__init__.py
END
base.py
K 25
svn:wc:ra_dav:version-url
V 62
/svnroot/!svn/ver/1077/osqa/trunk/forum/authentication/base.py
END
10
dir
1272
http://svn.osqa.net/svnroot/osqa/trunk/forum/authentication
http://svn.osqa.net/svnroot
2011-06-25T03:50:15.766114Z
1077
jordan
0cfe37f9-358a-4d5e-be75-b63607b5c754
__init__.py
file
2012-06-22T20:34:38.590475Z
2654efe93c8c8e8e11649a8144d662a8
2011-06-25T03:50:15.766114Z
1077
jordan
has-props
1062
base.py
file
2012-06-22T20:34:38.586477Z
8ee768023e072b801d13b1c38ff54cd5
2011-06-25T03:50:15.766114Z
1077
jordan
has-props
1154
import re
import django.dispatch
from forum.modules import get_modules_script_classes
from forum.authentication.base import AuthenticationConsumer, ConsumerTemplateContext
class ConsumerAndContext:
def __init__(self, id, consumer, context):
self.id = id
self._consumer = consumer
if context:
context.id = id
self.context = context
@property
def consumer(self):
return self._consumer()
consumers = dict([
(re.sub('AuthConsumer$', '', name).lower(), cls) for name, cls
in get_modules_script_classes('authentication', AuthenticationConsumer).items()
if not re.search('AbstractAuthConsumer$', name)
])
contexts = dict([
(re.sub('AuthContext$', '', name).lower(), cls) for name, cls
in get_modules_script_classes('authentication', ConsumerTemplateContext).items()
])
AUTH_PROVIDERS = dict([
(name, ConsumerAndContext(name, consumers[name], contexts.get(name, None))) for name in consumers.keys()
])
class AuthenticationConsumer(object):
def prepare_authentication_request(self, request, redirect_to):
raise NotImplementedError()
def process_authentication_request(self, response):
raise NotImplementedError()
def get_user_data(self, key):
raise NotImplementedError()
class ConsumerTemplateContext(object):
"""
Class that provides information about a certain authentication provider context in the signin page.
class attributes:
mode - one of BIGICON, SMALLICON, FORM
human_name - the human readable name of the provider
extra_js - some providers require us to load extra javascript on the signin page for them to work,
this is the place to add those files in the form of a list
extra_css - same as extra_js but for css files
"""
mode = ''
weight = 500
human_name = ''
extra_js = []
extra_css = []
show_to_logged_in_user = True
@classmethod
def readable_key(cls, key):
return key.key
class InvalidAuthentication(Exception):
def __init__(self, message):
self.message = message
\ No newline at end of file
K 25
svn:wc:ra_dav:version-url
V 46
/svnroot/!svn/ver/1077/osqa/trunk/forum/badges
END
__init__.py
K 25
svn:wc:ra_dav:version-url
V 58
/svnroot/!svn/ver/1077/osqa/trunk/forum/badges/__init__.py
END
base.py
K 25
svn:wc:ra_dav:version-url
V 54
/svnroot/!svn/ver/1077/osqa/trunk/forum/badges/base.py
END
10
dir
1272
http://svn.osqa.net/svnroot/osqa/trunk/forum/badges
http://svn.osqa.net/svnroot
2011-06-25T03:50:15.766114Z
1077
jordan
0cfe37f9-358a-4d5e-be75-b63607b5c754
base.py
file
2012-06-22T20:34:38.718411Z
655cdcd18cfd09de6e441c37f871dd51
2011-06-25T03:50:15.766114Z
1077
jordan
has-props
2271
__init__.py
file
2012-06-22T20:34:38.718411Z
a029fbc5f30a4428dfd0847d8b9e3d78
2011-06-25T03:50:15.766114Z
1077
jordan
has-props
105
from forum.modules import get_modules_script
get_modules_script('badges')
from base import BadgesMeta
import re
from string import lower
from django.core.exceptions import MultipleObjectsReturned
from django.db.models.signals import post_save
from forum.models import Badge, Node, Action
from forum.actions import AwardAction
import logging
installed = dict([(b.cls, b) for b in Badge.objects.all()])
class BadgesMeta(type):
by_class = {}
by_id = {}
def __new__(mcs, name, bases, dic):
badge = type.__new__(mcs, name, bases, dic)
if not dic.get('abstract', False):
if not name in installed:
ondb = Badge(cls=name, type=dic.get('type', Badge.BRONZE))
ondb.save()
else:
ondb = installed[name]
badge.ondb = ondb.id
inst = badge()
def hook(action, new):
user = inst.award_to(action)
if user:
badge.award(user, action, badge.award_once)
for action in badge.listen_to:
action.hook(hook)
BadgesMeta.by_class[name] = inst
BadgesMeta.by_id[ondb.id] = inst
return badge
class AbstractBadge(object):
__metaclass__ = BadgesMeta
abstract = True
award_once = False
@property
def name(self):
raise NotImplementedError
@property
def description(self):
raise NotImplementedError
@classmethod
def award(cls, user, action, once=False):
db_object = Badge.objects.get(id=cls.ondb)
try:
if once:
node = None
awarded = AwardAction.get_for(user, db_object)
else:
node = action.node
awarded = AwardAction.get_for(user, db_object, node)
trigger = isinstance(action, Action) and action or None
if not awarded:
AwardAction(user=user, node=node).save(data=dict(badge=db_object, trigger=trigger))
except MultipleObjectsReturned:
if node:
logging.error('Found multiple %s badges awarded for user %s (%s)' % (self.name, user.username, user.id))
else:
logging.error('Found multiple %s badges awarded for user %s (%s) and node %s' % (self.name, user.username, user.id, node.id))
\ No newline at end of file
K 25
svn:wc:ra_dav:version-url
V 45
/svnroot/!svn/ver/1259/osqa/trunk/forum/forms
END
auth.py
K 25
svn:wc:ra_dav:version-url
V 53
/svnroot/!svn/ver/1243/osqa/trunk/forum/forms/auth.py
END
qanda.py
K 25
svn:wc:ra_dav:version-url
V 54
/svnroot/!svn/ver/1259/osqa/trunk/forum/forms/qanda.py
END
admin.py
K 25
svn:wc:ra_dav:version-url
V 54
/svnroot/!svn/ver/1077/osqa/trunk/forum/forms/admin.py
END
general.py
K 25
svn:wc:ra_dav:version-url
V 56
/svnroot/!svn/ver/1243/osqa/trunk/forum/forms/general.py
END
__init__.py
K 25
svn:wc:ra_dav:version-url
V 57
/svnroot/!svn/ver/1077/osqa/trunk/forum/forms/__init__.py
END
K 13
svn:mergeinfo
V 98
/osqa/branches/cacheimp/forum/forms:874-939
/osqa/branches/notification-config/forum/forms:693-848
END
10
dir
1272
http://svn.osqa.net/svnroot/osqa/trunk/forum/forms
http://svn.osqa.net/svnroot
2012-04-27T22:19:01.772705Z
1259
jordan
has-props
0cfe37f9-358a-4d5e-be75-b63607b5c754
admin.py
file
2012-06-22T20:34:38.742399Z
a43c1ae22041dc89b6f987dc1a99a73a
2011-06-25T03:50:15.766114Z
1077
jordan
has-props
4232
general.py
file
2012-06-22T20:34:38.742399Z
23bee137a8843249f52781a33fa8896a
2012-04-04T23:10:46.497540Z
1243
jordan
has-props
8563
__init__.py
file
2012-06-22T20:34:38.750395Z
bcdc3b9b78a0ba73dcd40f72539b9aec
2011-06-25T03:50:15.766114Z
1077
jordan
has-props
81
auth.py
file
2012-06-22T20:34:38.750395Z
6142498b2a72083c2014d297d90f941a
2012-04-04T23:10:46.497540Z
1243
jordan
has-props
2040
qanda.py
file
2012-06-22T20:34:38.750395Z
8700e2c58378c204b929c50100af1ecd
2012-04-27T22:19:01.772705Z
1259
jordan
has-props
15431
from qanda import *
from admin import *
from auth import *
from general import *
import socket
from django import forms
from django.utils.translation import ugettext as _
from django.contrib.admin.widgets import FilteredSelectMultiple, AdminDateWidget
from qanda import TitleField, EditorField
from forum import settings
from forum.models.node import NodeMetaClass
from forum.models import User
class IPListField(forms.CharField):
def clean(self, value):
ips = [ip.strip() for ip in value.strip().strip(',').split(',')]
iplist = []
if len(ips) < 1:
raise forms.ValidationError(_('Please input at least one ip address'))
for ip in ips:
try:
socket.inet_aton(ip)
except socket.error:
raise forms.ValidationError(_('Invalid ip address: %s' % ip))
if not len(ip.split('.')) == 4:
raise forms.ValidationError(_('Please use the dotted quad notation for the ip addresses'))
iplist.append(ip)
return iplist
class MaintenanceModeForm(forms.Form):
ips = IPListField(label=_('Allow ips'),
help_text=_('Comma separated list of ips allowed to access the site while in maintenance'),
required=True,
widget=forms.TextInput(attrs={'class': 'longstring'}))
message = forms.CharField(label=_('Message'),
help_text=_('A message to display to your site visitors while in maintainance mode'),
widget=forms.Textarea)
TEMPLATE_CHOICES = (
('default', _('Default')),
('sidebar', _('Default with sidebar')),
('none', _('None')),
)
RENDER_CHOICES = (
('markdown', _('Markdown')),
('html', _('HTML')),
('escape', _('Escaped'))
)
class UrlFieldWidget(forms.TextInput):
def render(self, name, value, attrs=None):
if not value:
value = ''
return """
<input class="url_field" type="text" name="%(name)s" value="%(value)s" />
<a class="url_field_anchor" target="_blank" href="%(app_url)s"></a>
""" % {'name': name, 'value': value, 'app_url': settings.APP_URL}
class PageForm(forms.Form):
def __init__(self, page, *args, **kwargs):
if page:
initial = page.extra
initial.update(dict(title=page.title, content=page.body))
super(PageForm, self).__init__(initial=initial, *args, **kwargs)
else:
super(PageForm, self).__init__(*args, **kwargs)
title = forms.CharField(label=_('Title'), max_length=255, widget=forms.TextInput(attrs={'class': 'longstring'}),
initial='New page')
path = forms.CharField(label=_('Page URL'), widget=UrlFieldWidget, initial='pages/new/')
content = forms.CharField(label=_('Page Content'), widget=forms.Textarea(attrs={'rows': 30}))
mimetype = forms.CharField(label=_('Mime Type'), initial='text/html')
render = forms.ChoiceField(widget=forms.RadioSelect, choices=RENDER_CHOICES, initial='markdown',
label=_('Render Mode'))
template = forms.ChoiceField(widget=forms.RadioSelect, choices=TEMPLATE_CHOICES, initial='default',
label=_('Template'))
sidebar = forms.CharField(label=_('Sidebar Content'), widget=forms.Textarea(attrs={'rows': 20}), required=False)
sidebar_wrap = forms.BooleanField(label=_("Wrap sidebar block"), initial=True, required=False)
sidebar_render = forms.ChoiceField(widget=forms.RadioSelect, choices=RENDER_CHOICES, initial='markdown',
label=_('Sidebar Render Mode'))
comments = forms.BooleanField(label=_("Allow comments"), initial=False, required=False)
from forum.forms.auth import SimpleRegistrationForm
from forum.forms.general import SetPasswordForm
class CreateUserForm(SimpleRegistrationForm, SetPasswordForm):
validate_email = forms.BooleanField(required=False, label=_('send validation email'))
def __init__(self, *args, **kwargs):
super(CreateUserForm, self).__init__(*args, **kwargs)
self.fields.keyOrder = ['username', 'email', 'validate_email', 'password1', 'password2']
self.fields['email'].label = _('email address')
from general import NextUrlField, UserNameField, UserEmailField, UserRealNameField, SetPasswordForm
from forum.models import Question, User
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
from django import forms
import logging
class SimpleRegistrationForm(forms.Form):
next = NextUrlField()
username = UserNameField()
email = UserEmailField()
real_name = UserRealNameField()
class TemporaryLoginRequestForm(forms.Form):
def __init__(self, data=None):
super(TemporaryLoginRequestForm, self).__init__(data)
self.user_cache = None
email = forms.EmailField(
required=True,
label=_("Your account email"),
error_messages={
'required': _("You cannot leave this field blank"),
'invalid': _('please enter a valid email address'),
}
)
def clean_email(self):
users = list(User.objects.filter(email=self.cleaned_data['email']))
if not len(users):
raise forms.ValidationError(_("Sorry, but this email is not on our database."))
self.user_cache = users
return self.cleaned_data['email']
class ChangePasswordForm(SetPasswordForm):
""" change password form """
oldpw = forms.CharField(widget=forms.PasswordInput(attrs={'class':'required'}),
label=mark_safe(_('Current password')))
def __init__(self, data=None, user=None, *args, **kwargs):
if user is None:
raise TypeError("Keyword argument 'user' must be supplied")
super(ChangePasswordForm, self).__init__(data, *args, **kwargs)
self.user = user
def clean_oldpw(self):
""" test old password """
if not self.user.check_password(self.cleaned_data['oldpw']):
raise forms.ValidationError(_("Old password is incorrect. \
Please enter the correct password."))
return self.cleaned_data['oldpw']
from django import forms
import re
from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
from forum import settings
from django.http import str_to_unicode
from forum.models import User
from forum.modules import call_all_handlers
import urllib
import logging
DEFAULT_NEXT = getattr(settings, 'APP_BASE_URL')
def clean_next(next):
if next is None:
return DEFAULT_NEXT
next = str_to_unicode(urllib.unquote(next), 'utf-8')
next = next.strip()
if next.startswith('/'):
return next
return DEFAULT_NEXT
def get_next_url(request):
return clean_next(request.REQUEST.get('next'))
class StrippedNonEmptyCharField(forms.CharField):
def clean(self,value):
value = value.strip()
if self.required and value == '':
raise forms.ValidationError(_('this field is required'))
return value
class NextUrlField(forms.CharField):
def __init__(self):
super(NextUrlField,self).__init__(max_length = 255,widget = forms.HiddenInput(),required = False)
def clean(self,value):
return clean_next(value)
login_form_widget_attrs = { 'class': 'required login' }
username_re = re.compile(r'^[\-\w\s ]+$', re.UNICODE)
class UserNameField(StrippedNonEmptyCharField):
def __init__(self,db_model=User, db_field='username', must_exist=False,skip_clean=False,label=_('choose a username'),**kw):
self.must_exist = must_exist
self.skip_clean = skip_clean
self.db_model = db_model
self.db_field = db_field
error_messages={'required':_('user name is required'),
'taken':_('sorry, this name is taken, please choose another'),
'forbidden':_('sorry, this name is not allowed, please choose another'),
'missing':_('sorry, there is no user with this name'),
'multiple-taken':_('sorry, we have a serious error - user name is taken by several users'),
'invalid':_('user name can only consist of letters, empty space, hyphens and underscore'),
'toshort':_('user name is to short, please use at least %d characters') % settings.MIN_USERNAME_LENGTH
}
if 'error_messages' in kw:
error_messages.update(kw['error_messages'])
del kw['error_messages']
super(UserNameField,self).__init__(max_length=30,
widget=forms.TextInput(attrs=login_form_widget_attrs),
label=label,
error_messages=error_messages,
**kw
)
def clean(self,username):
""" validate username """
if self.skip_clean == True:
return username
if hasattr(self, 'user_instance') and isinstance(self.user_instance, User):
if username == self.user_instance.username:
return username
try:
username = super(UserNameField, self).clean(username)
except forms.ValidationError:
raise forms.ValidationError(self.error_messages['required'])
if len(username) < settings.MIN_USERNAME_LENGTH:
raise forms.ValidationError(self.error_messages['toshort'])
if self.required and not username_re.match(username):
raise forms.ValidationError(self.error_messages['invalid'])
if username in settings.RESERVED_USERNAMES:
raise forms.ValidationError(self.error_messages['forbidden'])
try:
user = self.db_model.objects.get(
**{'%s' % self.db_field : username}
)
if user:
if self.must_exist:
return username
else:
raise forms.ValidationError(self.error_messages['taken'])
except self.db_model.DoesNotExist:
if self.must_exist:
raise forms.ValidationError(self.error_messages['missing'])
else:
return username
except self.db_model.MultipleObjectsReturned:
raise forms.ValidationError(self.error_messages['multiple-taken'])
class UserEmailField(forms.EmailField):
def __init__(self,skip_clean=False,**kw):
self.skip_clean = skip_clean
super(UserEmailField,self).__init__(widget=forms.TextInput(attrs=dict(login_form_widget_attrs,
maxlength=200)), label=mark_safe(_('your email address')),
error_messages={'required':_('email address is required'),
'invalid':_('please enter a valid email address'),
'taken':_('this email is already used by someone else, please choose another'),
},
**kw
)
def clean(self,email):
""" validate if email exist in database
from legacy register
return: raise error if it exist """
email = super(UserEmailField,self).clean(email.strip())
if self.skip_clean:
return email
if settings.EMAIL_UNIQUE == True:
try:
user = User.objects.get(email = email)
raise forms.ValidationError(self.error_messages['taken'])
except User.DoesNotExist:
return email
except User.MultipleObjectsReturned:
raise forms.ValidationError(self.error_messages['taken'])
else:
return email
class UserRealNameField(StrippedNonEmptyCharField):
def __init__(self, db_model=User, db_field='real_name', must_exist=True, skip_clean=False, label=_('Your real name'),**kw):
self.must_exist = must_exist
self.skip_clean = skip_clean
self.db_model = db_model
self.db_field = db_field
error_messages={'required':_('Real name is required')
}
if 'error_messages' in kw:
error_messages.update(kw['error_messages'])
del kw['error_messages']
super(UserRealNameField,self).__init__(max_length=100,
widget=forms.TextInput(attrs=login_form_widget_attrs),
label=label,
error_messages=error_messages,
**kw
)
def clean(self, real_name):
if self.skip_clean == True:
return real_name
try:
return super(UserRealNameField, self).clean(real_name)
except forms.ValidationError:
raise forms.ValidationError(self.error_messages['required'])
class SetPasswordForm(forms.Form):
password1 = forms.CharField(widget=forms.PasswordInput(attrs=login_form_widget_attrs),
label=_('choose password'),
error_messages={'required':_('password is required')},
)
password2 = forms.CharField(widget=forms.PasswordInput(attrs=login_form_widget_attrs),
label=mark_safe(_('retype password')),
error_messages={'required':_('please, retype your password'),
'nomatch':_('sorry, entered passwords did not match, please try again')},
)
def __init__(self, data=None, user=None, *args, **kwargs):
super(SetPasswordForm, self).__init__(data, *args, **kwargs)
def clean_password2(self):
"""
Validates that the two password inputs match.
"""
if 'password1' in self.cleaned_data:
if self.cleaned_data['password1'] == self.cleaned_data['password2']:
self.password = self.cleaned_data['password2']
self.cleaned_data['password'] = self.cleaned_data['password2']
return self.cleaned_data['password2']
else:
del self.cleaned_data['password2']
raise forms.ValidationError(self.fields['password2'].error_messages['nomatch'])
else:
return self.cleaned_data['password2']
class SimpleCaptchaForm(forms.Form):
fields = {}
def __init__(self, *args, **kwargs):
super(SimpleCaptchaForm, self).__init__(*args, **kwargs)
spam_fields = call_all_handlers('create_anti_spam_field')
if spam_fields:
spam_fields = dict(spam_fields)
for name, field in spam_fields.items():
self.fields[name] = field
self._anti_spam_fields = spam_fields.keys()
else:
self._anti_spam_fields = []
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment