class FlatPage(models.Model): url = models.CharField(_('URL'), max_length=100, db_index=True) title = models.CharField(_('title'), max_length=200) content = models.TextField(_('content'), blank=True) enable_comments = models.BooleanField(_('enable comments')) template_name = models.CharField( _('template name'), max_length=70, blank=True, help_text= _("Example: 'flatpages/contact_page.html'. If this isn't provided, the system will use 'flatpages/default.html'." )) registration_required = models.BooleanField( _('registration required'), help_text= _("If this is checked, only logged-in users will be able to view the page." )) sites = models.ManyToManyField(Site) class Meta: db_table = 'django_flatpage' verbose_name = _('flat page') verbose_name_plural = _('flat pages') ordering = ('url', ) def __unicode__(self): return u"%s -- %s" % (self.url, self.title) def get_absolute_url(self): return self.url
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 Forum(models.Model): slug = models.SlugField(unique=True) name = models.CharField(max_length=255) group = models.CharField(max_length=255, blank=True) ordering = models.IntegerField(default=0) # -- is_forum = models.BooleanField(default=True) class Meta: ordering = ['ordering', 'group'] def __unicode__(self): return self.name @models.permalink def get_absolute_url(self): return 'cicero.views.forum', [self.slug]
class Comment(BaseCommentAbstractModel): """ A user comment about some object. """ # Who posted this comment? If ``user`` is set then it was an authenticated # user; otherwise at least user_name should have been set and the comment # was posted by a non-authenticated user. user = models.ForeignKey(User, verbose_name=_('user'), blank=True, null=True, related_name="%(class)s_comments") user_name = models.CharField(_("user's name"), max_length=50, blank=True) user_email = models.EmailField(_("user's email address"), blank=True) user_url = models.URLField(_("user's URL"), blank=True) comment = models.TextField(_('comment'), max_length=COMMENT_MAX_LENGTH) # Metadata about the comment submit_date = models.DateTimeField(_('date/time submitted'), default=None) ip_address = models.IPAddressField(_('IP address'), blank=True, null=True) is_public = models.BooleanField(_('is public'), default=True, help_text=_('Uncheck this box to make the comment effectively ' \ 'disappear from the site.')) is_removed = models.BooleanField(_('is removed'), default=False, help_text=_('Check this box if the comment is inappropriate. ' \ 'A "This comment has been removed" message will ' \ 'be displayed instead.')) # Manager objects = CommentManager() class Meta: db_table = "django_comments" ordering = ('submit_date', ) permissions = [("can_moderate", "Can moderate comments")] verbose_name = _('comment') verbose_name_plural = _('comments') def __unicode__(self): return "%s: %s..." % (self.name, self.comment[:50]) def save(self, *args, **kwargs): if self.submit_date is None: self.submit_date = timezone.now() super(Comment, self).save(*args, **kwargs) def _get_userinfo(self): """ Get a dictionary that pulls together information about the poster safely for both authenticated and non-authenticated comments. This dict will have ``name``, ``email``, and ``url`` fields. """ if not hasattr(self, "_userinfo"): self._userinfo = { "name": self.user_name, "email": self.user_email, "url": self.user_url } if self.user_id: u = self.user if u.email: self._userinfo["email"] = u.email # If the user has a full name, use that for the user name. # However, a given user_name overrides the raw user.username, # so only use that if this comment has no associated name. if u.get_full_name(): self._userinfo["name"] = self.user.get_full_name() elif not self.user_name: self._userinfo["name"] = u.username return self._userinfo userinfo = property(_get_userinfo, doc=_get_userinfo.__doc__) def _get_name(self): return self.userinfo["name"] def _set_name(self, val): if self.user_id: raise AttributeError(_("This comment was posted by an authenticated "\ "user and thus the name is read-only.")) self.user_name = val name = property(_get_name, _set_name, doc="The name of the user who posted this comment") def _get_email(self): return self.userinfo["email"] def _set_email(self, val): if self.user_id: raise AttributeError(_("This comment was posted by an authenticated "\ "user and thus the email is read-only.")) self.user_email = val email = property(_get_email, _set_email, doc="The email of the user who posted this comment") def _get_url(self): return self.userinfo["url"] def _set_url(self, val): self.user_url = val url = property(_get_url, _set_url, doc="The URL given by the user who posted this comment") def get_absolute_url(self, anchor_pattern="#c%(id)s"): return self.get_content_object_url() + (anchor_pattern % self.__dict__) def get_as_text(self): """ Return this comment as plain text. Useful for emails. """ d = { 'user': self.user or self.name, 'date': self.submit_date, 'comment': self.comment, 'domain': self.site.domain, 'url': self.get_absolute_url() } return _( 'Posted by %(user)s at %(date)s\n\n%(comment)s\n\nhttp://%(domain)s%(url)s' ) % d
class HgRepository(models.Model): """A version controlled source code repository""" name = models.SlugField(_("Name"), unique=True) summary = models.CharField(_('Summary'), max_length=255, blank=True, null=True) description = models.TextField(_('Description'), blank=True, null=True) anonymous_access = models.BooleanField(_("Allow Anonymous Viewing"), default=True) repo_path = models.CharField(editable=False, max_length=255) repo_url = models.CharField(editable=False, max_length=255) members = models.ManyToManyField(User, through='RepositoryUser', verbose_name="list of members") cmds = [ 'between', 'branches', 'branchmap', 'capabilities', 'changegroupsubset', 'heads', 'unbundle', 'changegroup' ] class Meta: verbose_name = _("Repository") verbose_name_plural = _("Repositories") def __unicode__(self): return self.name objects = HgRepositoryManager() @models.permalink def get_absolute_url(self): """ The path to the project page """ return ("hg-repo", {}, {'name': self.name}) def owners(self): """ Get the project owners """ return self.repositoryuser_set.filter( permission=7).order_by('user__username').select_related() def contributors(self): """ Get the write users """ return self.repositoryuser_set.filter(permission__gte=3).order_by( '-permission', 'user__username').select_related() def members(self): """ Get all users involved in a project """ return self.repositoryuser_set.filter(permission__gte=1).order_by( '-permission', 'user__username').select_related() def user_is_owner(self, userobj): """ Is this user an owner of the project """ try: repousr = self.repositoryuser_set.get(user=userobj) except: return False return repousr.permission > 4 def user_can_write(self, userobj): """ Does this user have write access to this repository """ try: repousr = self.repositoryuser_set.get(user=userobj) except: return False return repousr.permission > 2 def user_can_read(self, userobj): """ Does the user have read access to this repository? """ if self.anonymous_access: return True try: repousr = self.repositoryuser_set.get(user=userobj) except: return False return True # If we have a user, it must have at least read/write def move_to_public(self): """ Move a repository from private to public """ import os #os.umask(0) dest = os.path.abspath( os.path.join(global_settings.DJANGO_HG_REPOSITORIES_DIR['public'], self.name)) source = self.repo_path shutil.move(source, dest) def move_to_private(self): """ Move a repository from public to private """ import os #os.umask(0) source = self.repo_path dest = os.path.abspath( os.path.join(global_settings.DJANGO_HG_REPOSITORIES_DIR['private'], self.name)) shutil.move(source, dest) def get_size(self, directory=None): #The following is the code snippet to get the size of a directory in python: if directory is None: directory = self.repo_path dir_size = 0 for (path, dirs, files) in os.walk(directory): for file in files: try: filename = os.path.join(path, file) dir_size += os.path.getsize(filename) except: pass return dir_size def get_version_controller(self): if not controller: return return getattr(controller, VC_TYPE_CHOICES[self.vc_system - 1][1])(self.repo_path) def create_repository(self): """ Create a source code repository """ import os #os.umask(0) u = ui.ui() if self.anonymous_access: hg.repository( u, os.path.join( global_settings.DJANGO_HG_REPOSITORIES_DIR['public'], self.repo_path), True) else: hg.repository( u, os.path.join( global_settings.DJANGO_HG_REPOSITORIES_DIR['public'], self.repo_path), True) def save(self, force_insert=False, force_update=False): """ Do a little maintenence before doing the final save """ new = self.id is None if self.anonymous_access: repo_path = os.path.abspath( os.path.join( global_settings.DJANGO_HG_REPOSITORIES_DIR['public'], self.name)) repo_url = "%s%s/" % ( global_settings.DJANGO_HG_REPOSITORIES_DIR['public'], self.name) if not new and repo_path != self.repo_path: self.move_to_public() else: repo_path = os.path.abspath( os.path.join( global_settings.DJANGO_HG_REPOSITORIES_DIR['private'], self.name)) repo_url = "%s%s/" % ( global_settings.DJANGO_HG_REPOSITORIES_DIR['private'], self.name) if not new and repo_path != self.repo_path: self.move_to_private() self.repo_path = repo_path self.repo_url = repo_url super(HgRepository, self).save(force_insert, force_update) # create the source repository here, if new if not os.path.isdir(self.repo_path): #new: self.create_repository() def get_hash(self): return self.get_context().ctx def get_context(self): return self.context def set_context(self, ctx): self.context = ctx def delete(self): # Delete the source repository here shutil.rmtree(self.repo_path) super(HgRepository, self).delete()
class Profile(models.Model): # latitude = models.CharField(max_length=25, blank=True, null=True) user = fields.AutoOneToOneField(User, related_name='cicero_profile', primary_key=True) filter = models.CharField(u'Фильтр', max_length=50, choices=[(k, k) for k in filters.keys()], default='agd') read_articles = fields.RangesField(editable=False) moderator = models.BooleanField(default=False) # -- is_banned = models.BooleanField(default=False) # -- last_post = models.DateField(auto_now=False, blank=True, null=True) last_edit = models.DateField(auto_now=False, blank=True, null=True) # -- max_posts = models.IntegerField() today_posts = models.IntegerField() # -- max_topics = models.IntegerField() today_topics = models.IntegerField() # -- max_edits = models.IntegerField() today_edits = models.IntegerField() # -- total_posts = models.IntegerField() carma = models.IntegerField() today_change_carmas = models.IntegerField() max_change_carmas = models.IntegerField() # -- last_ip = models.IPAddressField(default='127.0.0.1') user_agent = models.CharField(max_length=255, default='') # -- registered_ip = models.IPAddressField(default='127.0.0.1') registered_date = models.DateField(auto_now=False) # -- max_repos = models.IntegerField() used_repos = models.IntegerField() #def __unicode__(self): # try: # #return unicode(self.user.scipio_profile) # return unicode(self.user.scipio_profile) # except ScipioProfile.DoesNotExist: # pass # return unicode(self.user) #def save(self, **kwargs): #self.user = self.username #if not self.mutant: # self.generate_mutant() # super(Profile, self).save(**kwargs) #def get_absolute_url(self): # return reverse('profile', args=[self.user_id]) #def generate_mutant(self): # ''' # Создает, если возможно, картинку мутанта из OpenID. # ''' # if self.mutant and os.path.exists(self.mutant.path): # os.remove(self.mutant.path) # if not settings.CICERO_OPENID_MUTANT_PARTS: # return # try: # content = StringIO() # mutant(self.user.scipio_profile.openid).save(content, 'PNG') # self.mutant.save('%s.png' % self._get_pk_val(), ContentFile(content.getvalue())) # except ScipioProfile.DoesNotExist: # pass # scipio.signals.created.connect(lambda sender, profile, **kwargs: profile.user.cicero_profile.generate_mutant()) def unread_topics(self): ''' Непрочитанные топики пользователя во всех форумах ''' query = Q() for range in self.read_articles: query = query | Q(article__id__range=range) return Topic.objects.exclude(query).distinct() def set_news(self, objects): ''' Проставляет признаки наличия новых статей переданным топикам или форумам ''' if len(objects) == 0: return ids = [str(o.id) for o in objects] tables = 'cicero_article a, cicero_topic t' condition = 'topic_id = t.id' \ ' and a.deleted is null and a.spam_status = \'clean\'' \ ' and t.deleted is null and t.spam_status = \'clean\'' \ ' and t.created >= %s' if isinstance(objects[0], Forum): field_name = 'forum_id' condition += ' and forum_id in (%s)' % ','.join(ids) else: field_name = 'topic_id' condition += ' and topic_id in (%s)' % ','.join(ids) ranges = ' or '.join( ['a.id between %s and %s' % range for range in self.read_articles]) condition += ' and not (%s)' % ranges query = 'select %s, count(1) as c from %s where %s group by 1' % ( field_name, tables, condition) old_topic_age = datetime.now().date() - timedelta( settings.CICERO_OLD_TOPIC_AGE) cursor = connection.cursor() cursor.execute(query, [old_topic_age]) counts = dict(cursor.fetchall()) for obj in objects: obj.new = counts.get(obj.id, 0) def add_read_articles(self, articles): ''' Добавляет новые статьи к списку прочитанных. Статьи передаются в виде queryset. ''' return # Нужно еще раз считать read_articles с "for update", чтобы параллельные транзакции # не затирали друг друга cursor = connection.cursor() sql = 'select read_articles from %s where %s = %%s for update' % ( self._meta.db_table, self._meta.pk.attname) cursor.execute('begin') cursor.execute(sql, [self._get_pk_val()]) self.read_articles = cursor.fetchone()[0] query = Q() for range in self.read_articles: query = query | Q(id__range=range) ids = [a['id'] for a in articles.exclude(query).values('id')] merged = self.read_articles for range in ranges.compile_ranges(ids): merged = ranges.merge_range(range, merged) try: article = Article.objects.filter( created__lt=date.today() - timedelta(settings.CICERO_UNREAD_TRACKING_PERIOD)).order_by( '-created')[0] merged = ranges.merge_range((0, article.id), merged) except IndexError: pass if self.read_articles != merged: self.read_articles = merged return True else: return False def can_change_article(self, article): return self.moderator or self.user.is_superuser or ( not article.from_guest() and article.author_id == self.user_id) def can_change_topic(self, topic): return self.can_change_article(topic.article_set.all()[0]) def topics(self): return Topic.objects.filter( article__author=self).distinct().select_related('forum')
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