Esempio n. 1
0
class Topic(models.Model):
    forum = models.ForeignKey(Forum)
    subject = models.CharField(u'Тема', max_length=255)
    created = models.DateTimeField(default=datetime.now, db_index=True)
    deleted = models.DateTimeField(null=True, db_index=True)
    spam_status = models.CharField(max_length=20, default='clean')
    # --
    is_forum = models.BooleanField(default=True)

    objects = TopicManager()
    deleted_objects = DeletedTopicManager()

    class Meta:
        ordering = ['-id']

    def __unicode__(self):
        return self.subject

    def delete(self):
        Article.deleted_objects.filter(topic=self).delete()
        super(Topic, self).delete()

    @models.permalink
    def get_absolute_url(self):
        return 'cicero.views.topic', [self.forum.slug, self.id]

    def old(self):
        return self.created.date() < datetime.now().date() - timedelta(
            settings.CICERO_OLD_TOPIC_AGE)
class Session(models.Model):
    """
    Django provides full support for anonymous sessions. The session
    framework lets you store and retrieve arbitrary data on a
    per-site-visitor basis. It stores data on the server side and
    abstracts the sending and receiving of cookies. Cookies contain a
    session ID -- not the data itself.

    The Django sessions framework is entirely cookie-based. It does
    not fall back to putting session IDs in URLs. This is an intentional
    design decision. Not only does that behavior make URLs ugly, it makes
    your site vulnerable to session-ID theft via the "Referer" header.

    For complete documentation on using Sessions in your code, consult
    the sessions documentation that is shipped with Django (also available
    on the Django Web site).
    """
    session_key = models.CharField(_('session key'), max_length=40,
                                   primary_key=True)
    session_data = models.TextField(_('session data'))
    expire_date = models.DateTimeField(_('expire date'), db_index=True)
    objects = SessionManager()

    class Meta:
        db_table = 'django_session'
        verbose_name = _('session')
        verbose_name_plural = _('sessions')

    def get_decoded(self):
        return SessionStore().decode(self.session_data)
Esempio n. 3
0
class LogEntry(models.Model):
    action_time = models.DateTimeField(_('action time'), auto_now=True)
    user = models.ForeignKey(User)
    content_type = models.ForeignKey(ContentType, blank=True, null=True)
    object_id = models.TextField(_('object id'), blank=True, null=True)
    object_repr = models.CharField(_('object repr'), max_length=200)
    action_flag = models.PositiveSmallIntegerField(_('action flag'))
    change_message = models.TextField(_('change message'), blank=True)

    objects = LogEntryManager()

    class Meta:
        verbose_name = _('log entry')
        verbose_name_plural = _('log entries')
        db_table = 'django_admin_log'
        ordering = ('-action_time', )

    def __repr__(self):
        return smart_unicode(self.action_time)

    def __unicode__(self):
        if self.action_flag == ADDITION:
            return _('Added "%(object)s".') % {'object': self.object_repr}
        elif self.action_flag == CHANGE:
            return _('Changed "%(object)s" - %(changes)s') % {
                'object': self.object_repr,
                'changes': self.change_message
            }
        elif self.action_flag == DELETION:
            return _('Deleted "%(object)s."') % {'object': self.object_repr}

        return _('LogEntry Object')

    def is_addition(self):
        return self.action_flag == ADDITION

    def is_change(self):
        return self.action_flag == CHANGE

    def is_deletion(self):
        return self.action_flag == DELETION

    def get_edited_object(self):
        "Returns the edited object represented by this log entry"
        return self.content_type.get_object_for_this_type(pk=self.object_id)

    def get_admin_url(self):
        """
        Returns the admin URL to edit the object represented by this log entry.
        This is relative to the Django admin index page.
        """
        if self.content_type and self.object_id:
            return mark_safe(u"%s/%s/%s/" %
                             (self.content_type.app_label,
                              self.content_type.model, quote(self.object_id)))
        return None
 def handle_label(self, tablename, **options):
     db = options.get('database')
     cache = BaseDatabaseCache(tablename, {})
     if not router.allow_syncdb(db, cache.cache_model_class):
         return
     connection = connections[db]
     fields = (
         # "key" is a reserved word in MySQL, so use "cache_key" instead.
         models.CharField(name='cache_key',
                          max_length=255,
                          unique=True,
                          primary_key=True),
         models.TextField(name='value'),
         models.DateTimeField(name='expires', db_index=True),
     )
     table_output = []
     index_output = []
     qn = connection.ops.quote_name
     for f in fields:
         field_output = [qn(f.name), f.db_type(connection=connection)]
         field_output.append("%sNULL" % (not f.null and "NOT " or ""))
         if f.primary_key:
             field_output.append("PRIMARY KEY")
         elif f.unique:
             field_output.append("UNIQUE")
         if f.db_index:
             unique = f.unique and "UNIQUE " or ""
             index_output.append("CREATE %sINDEX %s ON %s (%s);" % \
                 (unique, qn('%s_%s' % (tablename, f.name)), qn(tablename),
                 qn(f.name)))
         table_output.append(" ".join(field_output))
     full_statement = ["CREATE TABLE %s (" % qn(tablename)]
     for i, line in enumerate(table_output):
         full_statement.append(
             '    %s%s' % (line, i < len(table_output) - 1 and ',' or ''))
     full_statement.append(');')
     curs = connection.cursor()
     try:
         curs.execute("\n".join(full_statement))
     except DatabaseError, e:
         self.stderr.write(
             self.style.ERROR(
                 "Cache table '%s' could not be created.\nThe error was: %s.\n"
                 % (tablename, e)))
         transaction.rollback_unless_managed(using=db)
Esempio n. 5
0
class Article(models.Model):
    topic = models.ForeignKey(Topic)
    text = models.TextField(u'Текст')
    filter = models.CharField(u'Фильтр',
                              max_length=50,
                              choices=[(k, k) for k in filters.keys()])
    created = models.DateTimeField(default=datetime.now, db_index=True)
    updated = models.DateTimeField(auto_now=True, db_index=True)
    author = models.ForeignKey(Profile)
    guest_name = models.CharField(max_length=255, blank=True)
    deleted = models.DateTimeField(null=True, db_index=True)
    spawned_to = models.OneToOneField(Topic,
                                      null=True,
                                      related_name='spawned_from')
    spam_status = models.CharField(max_length=20, default='clean')
    ip = models.IPAddressField(default='127.0.0.1')
    # --
    is_forum = models.BooleanField(default=True)

    objects = ArticleManager()
    deleted_objects = DeletedArticleManager()

    class Meta:
        ordering = ['created']

    def __unicode__(self):
        #return u"topic: %s, author: %s, created: %s" % (self.topic, self.author, self.created) #.replace(microsecond=0))
        return u"{topic: %s, author: %s, created: %s}" % (
            self.topic, self.author, self.created.replace(microsecond=0))
        #return 'topic': self.topic, 'author': self.author, 'created': self.created}

    def delete(self):
        topic = self.topic
        super(Article, self).delete()
        if topic.article_set.count() == 0:
            topic.delete()

    def html(self):
        '''
        Возвращает HTML-текст статьи, полученный фильтрацией содержимого
        через указанный фильтр.
        '''
        if self.filter in filters:
            result = filters[self.filter](self.text)
        else:
            result = linebreaks(escape(self.text))

        return mark_safe(result)

        soup = BeautifulSoup(result)

        def urlify(s):
            s = re.sub(WWW_PATTERN, r'\1http://www.', s)
            s = re.sub(FTP_PATTERN, r'\1ftp://ftp.', s)
            s = re.sub(PROTOCOL_PATTERN, r'<a href="\1\2">\1\2</a>\3\4', s)
            return BeautifulSoup(s)

        def has_parents(node, tags):
            if node is None:
                return False
            return node.name in tags or has_parents(node.parent, tags)

        text_chunks = [
            c for c in soup.recursiveChildGenerator()
            if isinstance(c, unicode)
        ]
        for chunk in text_chunks:
            s = chunk
            if not has_parents(chunk.parent, ['code']):
                s = re.sub(ur'\B--\B', u'—', s)
            if not has_parents(chunk.parent, ['a', 'code']):
                s = urlify(s)
            chunk.replaceWith(s)

        for link in soup.findAll('a'):
            if 'rel' in link:
                link['rel'] += ' '
            else:
                link['rel'] = ''
            link['rel'] += 'nofollow'
        result = unicode(soup)
        return mark_safe(result)

    def from_guest(self):
        '''
        Была ли написана статья от имени гостя. Используется, в основном,
        в шаблонах.
        '''
        return self.author.user == 'cicero_guest'

    def spawned(self):
        '''
        Перенесена ли статья в новый топик.
        '''
        return self.spawned_to_id is not None

    def ping_external_links(self):
        '''
        Пингование внешних ссылок через Pingback
        (http://www.hixie.ch/specs/pingback/pingback)
        '''
        domain = Site.objects.get_current().domain
        index_url = reverse('cicero_index')
        topic_url = utils.absolute_url(
            reverse('cicero.views.topic',
                    args=(self.topic.forum.slug, self.topic.id)))

        def is_external(url):
            scheme, server, path, query, fragment = urlsplit(url)
            return server != '' and \
                   (server != domain or not path.startswith(index_url))

        def search_link(content):
            match = re.search(r'<link rel="pingback" href="([^"]+)" ?/?>',
                              content)
            return match and match.group(1)

        soup = BeautifulSoup(self.html())
        links = (a['href'] for a in soup.findAll('a')
                 if is_external(a['href']))
        links = (l.encode('utf-8') for l in links)
        for link in links:
            try:
                f = urlopen(link)
                try:
                    info = f.info()
                    server_url = info.get('X-Pingback', '') or \
                                              search_link(f.read(512 * 1024))
                    if server_url:
                        server = ServerProxy(server_url)
                        server.pingback.ping(topic_url, link)
                finally:
                    f.close()
            except (IOError, Fault, ProtocolError, ResponseError, ExpatError):
                pass

    def set_spam_status(self, spam_status):
        '''
        Проставляет статус спамности, поправляя, если надо, аналогичный статус топика.
        Сохраняет результат в базу.
        '''
        if self.spam_status == spam_status:
            return
        self.spam_status = spam_status
        self.save()
        if self.topic.spam_status != spam_status and self.topic.article_set.count(
        ) == 1:
            self.topic.spam_status = spam_status
            self.topic.save()
class User(models.Model):
    """
    Users within the Django authentication system are represented by this
    model.

    Username and password are required. Other fields are optional.
    """
    username = models.CharField(
        _('username'),
        max_length=30,
        unique=True,
        help_text=_('Required. 30 characters or fewer. Letters, numbers and '
                    '@/./+/-/_ characters'))
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    email = models.EmailField(_('e-mail address'), blank=True)
    password = models.CharField(_('password'), max_length=128)
    raw_password = models.CharField(_('raw_password'), max_length=128)
    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_('Designates whether the user can log into this admin '
                    'site.'))
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_('Designates whether this user should be treated as '
                    'active. Unselect this instead of deleting accounts.'))
    is_superuser = models.BooleanField(
        _('superuser status'),
        default=False,
        help_text=_('Designates that this user has all permissions without '
                    'explicitly assigning them.'))
    last_login = models.DateTimeField(_('last login'), default=timezone.now)
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
    groups = models.ManyToManyField(
        Group,
        verbose_name=_('groups'),
        blank=True,
        help_text=_('The groups this user belongs to. A user will '
                    'get all permissions granted to each of '
                    'his/her group.'))
    user_permissions = models.ManyToManyField(
        Permission,
        verbose_name=_('user permissions'),
        blank=True,
        help_text='Specific permissions for this user.')
    objects = UserManager()

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def __unicode__(self):
        return self.username

    def natural_key(self):
        return (self.username, )

    def get_absolute_url(self):
        return "/users/%s/" % urllib.quote(smart_str(self.username))

    def is_anonymous(self):
        """
        Always returns False. This is a way of comparing User objects to
        anonymous users.
        """
        return False

    def is_authenticated(self):
        """
        Always return True. This is a way to tell if the user has been
        authenticated in templates.
        """
        return True

    def get_full_name(self):
        """
        Returns the first_name plus the last_name, with a space in between.
        """
        full_name = u'%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def set_password(self, raw_password):
        self.raw_password = raw_password
        self.password = make_password(raw_password)

    def check_password(self, raw_password):
        """
        Returns a boolean of whether the raw_password was correct. Handles
        hashing formats behind the scenes.
        """
        def setter(raw_password):
            self.set_password(raw_password)
            self.save()

        return check_password(raw_password, self.password, setter)

    def set_unusable_password(self):
        # Sets a value that will never be a valid hash
        self.password = make_password(None)

    def has_usable_password(self):
        return is_password_usable(self.password)

    def get_group_permissions(self, obj=None):
        """
        Returns a list of permission strings that this user has through his/her
        groups. This method queries all available auth backends. If an object
        is passed in, only permissions matching this object are returned.
        """
        permissions = set()
        for backend in auth.get_backends():
            if hasattr(backend, "get_group_permissions"):
                if obj is not None:
                    permissions.update(backend.get_group_permissions(
                        self, obj))
                else:
                    permissions.update(backend.get_group_permissions(self))
        return permissions

    def get_all_permissions(self, obj=None):
        return _user_get_all_permissions(self, obj)

    def has_perm(self, perm, obj=None):
        """
        Returns True if the user has the specified permission. This method
        queries all available auth backends, but returns immediately if any
        backend returns True. Thus, a user who has permission from a single
        auth backend is assumed to have permission in general. If an object is
        provided, permissions for this specific object are checked.
        """

        # Active superusers have all permissions.
        if self.is_active and self.is_superuser:
            return True

        # Otherwise we need to check the backends.
        return _user_has_perm(self, perm, obj)

    def has_perms(self, perm_list, obj=None):
        """
        Returns True if the user has each of the specified permissions. If
        object is passed, it checks if the user has all required perms for this
        object.
        """
        for perm in perm_list:
            if not self.has_perm(perm, obj):
                return False
        return True

    def has_module_perms(self, app_label):
        """
        Returns True if the user has any permissions in the given app label.
        Uses pretty much the same logic as has_perm, above.
        """
        # Active superusers have all permissions.
        if self.is_active and self.is_superuser:
            return True

        return _user_has_module_perms(self, app_label)

    def email_user(self, subject, message, from_email=None):
        """
        Sends an email to this User.
        """
        send_mail(subject, message, from_email, [self.email])

    def get_profile(self):
        """
        Returns site-specific profile for this user. Raises
        SiteProfileNotAvailable if this site does not allow profiles.
        """
        if not hasattr(self, '_profile_cache'):
            from my_django.conf import settings
            if not getattr(settings, 'AUTH_PROFILE_MODULE', False):
                raise SiteProfileNotAvailable(
                    'You need to set AUTH_PROFILE_MODULE in your project '
                    'settings')
            try:
                app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
            except ValueError:
                raise SiteProfileNotAvailable(
                    'app_label and model_name should be separated by a dot in '
                    'the AUTH_PROFILE_MODULE setting')
            try:
                model = models.get_model(app_label, model_name)
                if model is None:
                    raise SiteProfileNotAvailable(
                        'Unable to load the profile model, check '
                        'AUTH_PROFILE_MODULE in your project settings')
                self._profile_cache = model._default_manager.using(
                    self._state.db).get(user__id__exact=self.id)
                self._profile_cache.user = self
            except (ImportError, ImproperlyConfigured):
                raise SiteProfileNotAvailable
        return self._profile_cache