<commit_before>import os
import re
import datetime
import pdb

from django import forms
from django.conf import settings
from django.contrib.auth.models import Group,User,Permission
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.core.files import File
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models import Max
from django.db.models import Q
from django.utils.safestring import mark_safe

from ckeditor.fields import RichTextField
from dropbox import client, rest, session
from dropbox.rest import ErrorResponse
from guardian.shortcuts import assign,remove_perm

from dataproviders import FileSystemDataProvider,DropboxDataProvider


def giveFileUploadDestinationPath(uploadmodel,filename):
    """ Where should this file go relative to MEDIA_ROOT? """
    
    #uploadmodel can be either a ComicSiteModel, or a ComicSite
    if hasattr(uploadmodel,'short_name'):
        comicsitename = uploadmodel.short_name  # is a ComicSite
    else:
        comicsitename = uploadmodel.comicsite.short_name # is a ComicSiteModel
         
    path = os.path.join(comicsitename,"uploads",filename)    
    return path


def get_anonymous_user():
    """Anymous user is the default user for non logged in users. I is also the only member of group
      'everyone' for which permissions can be set """
    return User.objects.get(username = "anonymousUser")


class ComicSiteManager(models.Manager):
    """ adds some tabel level functions for getting ComicSites from db. """ 
    
    def non_hidden(self):
        """ like all(), but only return ComicSites for which hidden=false"""
        return self.filter(hidden=False)
    
    def get_query_set(self):
        
        return super(ComicSiteManager, self).get_query_set()
    
    

class ComicSite(models.Model):
    """ A collection of HTML pages using a certain skin. Pages can be browsed and edited."""
    
    short_name = models.CharField(max_length = 50, default="", help_text = "short name used in url, specific css, files etc. No spaces allowed")
    skin = models.CharField(max_length = 225, blank=True, help_text = "additional css to use for this comic site. Not required")    
    description = models.CharField(max_length = 1024, default="", blank=True,help_text = "Short summary of this project, max 1024 characters.")
    logo = models.URLField(help_text = "URL of a 200x200 image to use as logo for this comicsite in overviews",default="http://www.grand-challenge.org/images/a/a7/Grey.png")
    header_image = models.ImageField(default="", blank=True, upload_to=giveFileUploadDestinationPath, help_text = "Header which will appear on top of each project page")
    
    hidden = models.BooleanField(default=False, help_text = "Do not display this Project in any public overview")
    
    objects = ComicSiteManager()
    
    def __unicode__(self):
        """ string representation for this object"""
        return self.short_name
       
    
    def clean(self):
        """ clean method is called automatically for each save in admin"""
        pass
        #TODO check whether short name is really clean and short!        
    
    def upload_dir(self):
        """Where to get and put uploaded files? """
        return os.path.join(settings.MEDIA_ROOT,self.short_name,"uploads")
         
            
    def admin_group_name(self):
        """ returns the name of the admin group which should have all rights to this ComicSite instance"""
        return self.short_name+"_admins"
    
    def participants_group_name(self):
        """ returns the name of the participants group, which should have some rights to this ComicSite instance"""
        return self.short_name+"_participants"
    
    def get_relevant_perm_groups(self):
        """ Return all auth groups which are directly relevant for this ComicSite. 
            This method is used for showin permissions for these groups, even if none
            are defined """
                
        groups = Group.objects.filter(Q(name="everyone") | Q(name=self.admin_group_name()) | Q(name=self.participants_group_name()))
        return groups
  
    def is_admin(self,user):
        """ is user in the admins group for the comicsite to which this object belongs? superuser always passes        
        """
        if user.is_superuser:
            return True
        
        if user.groups.filter(name=self.admin_group_name).count() > 0:
            return True
        else:
            return False
        
    def is_participant(self,user):
        """ is user in the admins group for the comicsite to which this object belongs? superuser always passes        
        """
        if user.is_superuser:
            return True
        
        if user.groups.filter(name=self.participants_group_name).count() > 0:
            return True
        else:
            return False
     
  
              

class ComicSiteModel(models.Model):
    """An object which can be shown or used in the comicsite framework. This base class should handle common functions
     such as authorization.
    """
    #user = models.ManyToManyField()    
    title = models.CharField(max_length=64, blank=True)    
    comicsite = models.ForeignKey(ComicSite, help_text = "To which comicsite does this object belong?")
    
    ALL = 'ALL'
    REGISTERED_ONLY = 'REG'
    ADMIN_ONLY = 'ADM'
    
    PERMISSIONS_CHOICES = (
        (ALL, 'All'),
        (REGISTERED_ONLY, 'Registered users only'),
        (ADMIN_ONLY, 'Administrators only')        
    )
    permission_lvl = models.CharField(max_length=3,
                                      choices=PERMISSIONS_CHOICES,
                                      default=ALL)
    
    # = models.CharField(max_length=64, blank=True)
        
    
    def __unicode__(self):
       """ string representation for this object"""
       return self.title
   
    def can_be_viewed_by(self,user):
        """ boolean, is user allowed to view this? """
        
        # check whether everyone is allowed to view this. Anymous user is the only member of group
        # 'everyone' for which permissions can be set
        anonymousUser = get_anonymous_user()
        
        if anonymousUser.has_perm("view_ComicSiteModel",self):
            return True
        else:
            # if not everyone has access, check whether given user has permissions<commit_msg>fixes #143 : changed page title and comicsite short_name to slugfield to allow only alphanumeric chars<commit_after>import os
import re
import datetime
import pdb

from django import forms
from django.conf import settings
from django.contrib.auth.models import Group,User,Permission
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.core.files import File
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models import Max
from django.db.models import Q
from django.utils.safestring import mark_safe

from ckeditor.fields import RichTextField
from dropbox import client, rest, session
from dropbox.rest import ErrorResponse
from guardian.shortcuts import assign,remove_perm

from dataproviders import FileSystemDataProvider,DropboxDataProvider


def giveFileUploadDestinationPath(uploadmodel,filename):
    """ Where should this file go relative to MEDIA_ROOT? """
    
    #uploadmodel can be either a ComicSiteModel, or a ComicSite
    if hasattr(uploadmodel,'short_name'):
        comicsitename = uploadmodel.short_name  # is a ComicSite
    else:
        comicsitename = uploadmodel.comicsite.short_name # is a ComicSiteModel
         
    path = os.path.join(comicsitename,"uploads",filename)    
    return path


def get_anonymous_user():
    """Anymous user is the default user for non logged in users. I is also the only member of group
      'everyone' for which permissions can be set """
    return User.objects.get(username = "anonymousUser")


class ComicSiteManager(models.Manager):
    """ adds some tabel level functions for getting ComicSites from db. """ 
    
    def non_hidden(self):
        """ like all(), but only return ComicSites for which hidden=false"""
        return self.filter(hidden=False)
    
    def get_query_set(self):
        
        return super(ComicSiteManager, self).get_query_set()
    
    

class ComicSite(models.Model):
    """ A collection of HTML pages using a certain skin. Pages can be browsed and edited."""
    
    short_name = models.SlugField(max_length = 50, default="", help_text = "short name used in url, specific css, files etc. No spaces allowed")
    skin = models.CharField(max_length = 225, blank=True, help_text = "additional css to use for this comic site. Not required")    
    description = models.CharField(max_length = 1024, default="", blank=True,help_text = "Short summary of this project, max 1024 characters.")
    logo = models.URLField(help_text = "URL of a 200x200 image to use as logo for this comicsite in overviews",default="http://www.grand-challenge.org/images/a/a7/Grey.png")
    header_image = models.ImageField(default="", blank=True, upload_to=giveFileUploadDestinationPath, help_text = "Header which will appear on top of each project page")
    
    hidden = models.BooleanField(default=False, help_text = "Do not display this Project in any public overview")
    
    objects = ComicSiteManager()
    
    def __unicode__(self):
        """ string representation for this object"""
        return self.short_name
       
    
    def clean(self):
        """ clean method is called automatically for each save in admin"""
        pass
        #TODO check whether short name is really clean and short!        
    
    def upload_dir(self):
        """Where to get and put uploaded files? """
        return os.path.join(settings.MEDIA_ROOT,self.short_name,"uploads")
         
            
    def admin_group_name(self):
        """ returns the name of the admin group which should have all rights to this ComicSite instance"""
        return self.short_name+"_admins"
    
    def participants_group_name(self):
        """ returns the name of the participants group, which should have some rights to this ComicSite instance"""
        return self.short_name+"_participants"
    
    def get_relevant_perm_groups(self):
        """ Return all auth groups which are directly relevant for this ComicSite. 
            This method is used for showin permissions for these groups, even if none
            are defined """
                
        groups = Group.objects.filter(Q(name="everyone") | Q(name=self.admin_group_name()) | Q(name=self.participants_group_name()))
        return groups
  
    def is_admin(self,user):
        """ is user in the admins group for the comicsite to which this object belongs? superuser always passes        
        """
        if user.is_superuser:
            return True
        
        if user.groups.filter(name=self.admin_group_name).count() > 0:
            return True
        else:
            return False
        
    def is_participant(self,user):
        """ is user in the admins group for the comicsite to which this object belongs? superuser always passes        
        """
        if user.is_superuser:
            return True
        
        if user.groups.filter(name=self.participants_group_name).count() > 0:
            return True
        else:
            return False
     
  
              

class ComicSiteModel(models.Model):
    """An object which can be shown or used in the comicsite framework. This base class should handle common functions
     such as authorization.
    """
    #user = models.ManyToManyField()    
    title = models.SlugField(max_length=64, blank=True)    
    comicsite = models.ForeignKey(ComicSite, help_text = "To which comicsite does this object belong?")
    
    ALL = 'ALL'
    REGISTERED_ONLY = 'REG'
    ADMIN_ONLY = 'ADM'
    
    PERMISSIONS_CHOICES = (
        (ALL, 'All'),
        (REGISTERED_ONLY, 'Registered users only'),
        (ADMIN_ONLY, 'Administrators only')        
    )
    permission_lvl = models.CharField(max_length=3,
                                      choices=PERMISSIONS_CHOICES,
                                      default=ALL)
    
    # = models.CharField(max_length=64, blank=True)
        
    
    
    
    def __unicode__(self):
       """ string representation for this object"""
       return self.title
   
    def can_be_viewed_by(self,user):
        """ boolean, is user allowed to view this? """
        
        # check whether everyone is allowed to view this. Anymous user is the only member of group
        # 'everyone' for which permissions can be set
        anonymousUser = get_anonymous_user()
        
        if anonymousUser.has_perm("view_ComicSiteModel",self):
            return True
        else:
            # if not everyone has access, check whether given user has permissions
{'fraction_non_alphanumeric': 0.07733026467203682, 'fraction_numerical': 0.004372842347525892, 'mean_word_length': 2.758938869665513, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5188927', 'n_tokens_mistral': 3585, 'n_tokens_neox': 3440, 'n_words': 1169}