Esempio n. 1
0
 def get_language_from_request(self, request):
     lang = None
     changed = False
     prefix = has_lang_prefix(request.path_info)
     if prefix:
         request.path = "/" + "/".join(request.path.split("/")[2:])
         request.path_info = "/" + "/".join(
             request.path_info.split("/")[2:])
         t = prefix
         if t in SUPPORTED:
             lang = t
             #if hasattr(request, "session"):
             #    request.session["django_language"] = lang
             #else:
             #    request.set_cookie("django_language", lang)
             changed = True
     #else:
     #    lang = translation.get_language_from_request(request)
     #if not changed:
     #if hasattr(request, "session"):
     #    lang = request.session.get("django_language", None)
     #    if lang in SUPPORTED and lang is not None:
     #        return lang
     #elif "django_language" in request.COOKIES.keys():
     #    lang = request.COOKIES.get("django_language", None)
     #    if lang in SUPPORTED and lang is not None:
     #        return lang
     #if not lang:
     #    lang = translation.get_language_from_request(request)
     if not lang:
         lang = get_default_language()
     return lang
Esempio n. 2
0
 def process_response(self, request, response):
     patch_vary_headers(response, ("Accept-Language", ))
     translation.deactivate()
     path = unicode(request.path)
     if not path.startswith(settings.MEDIA_URL) and \
             not path.startswith(settings.STATIC_URL) and \
             response.status_code == 200 and \
             response._headers['content-type'][1].split(';')[0] == "text/html":
         try:
             decoded_response = response.content.decode('utf-8')
         except UnicodeDecodeError:
             decoded_response = response.content
         response.content = SUB.sub(
             r'<a\1href="/%s/\3"\4>' % request.LANGUAGE_CODE,
             decoded_response)
         response.content = SUB2.sub(
             r'<form\1action="/%s/\3"\4>' % request.LANGUAGE_CODE,
             decoded_response)
     if (response.status_code == 301 or response.status_code == 302):
         location = response._headers['location']
         prefix = has_lang_prefix(location[1])
         if not prefix and location[1].startswith("/") and \
             not request.LANGUAGE_CODE == get_default_language() and \
             not location[1].startswith(settings.MEDIA_URL) and \
             not location[1].startswith(settings.STATIC_URL):
             response._headers['location'] = (
                 location[0],
                 "/%s%s" % (request.LANGUAGE_CODE, location[1]))
     return response
Esempio n. 3
0
    def get_queryset(self, request):
        qs = super(SCMSChangeList, self).get_queryset(request)

        page_table_name = self.model._meta.db_table
        slugs_table_name = Slugs._meta.db_table
        language = getattr(settings, 'SCMS_ADMIN_LIST_LANG',
                           get_default_language())

        select = {}

        parent_content_type = scms.site.get_content_type(
            request.scms['page_type'])
        for plugin_field_info in parent_content_type.get_changelist_fields():
            plugin_qs = plugin_field_info['field'].model.objects \
                .filter(
                    language='"%s"' % language,
                    field_name='"%s"' % plugin_field_info['field'].name) \
                .extra(
                    select = {plugin_field_info['db_field']: '`%s`.`%s`' % (plugin_field_info['field'].model._meta.db_table, plugin_field_info['db_field'])},
                    where=['`%s`.`id` = `page_id`' % page_table_name])[plugin_field_info['pos']:plugin_field_info['pos']+1] # Лимит на случай нескольких полей

            plugin_qs.query.default_cols = False
            select[plugin_field_info['list_name']] = str(plugin_qs.query)

        # Добавляем в селект поля модели Slugs и подсчет количества потомков
        select['title'] = '`%s`.`title`' % slugs_table_name
        select['slug'] = '`%s`.`slug`' % slugs_table_name
        select['alias'] = 'IF (`' + page_table_name + '`.`state`=' + str(
            page_state.MAIN
        ) + ', "/", REPLACE(`' + slugs_table_name + '`.`alias`,"*",""))'
        select[
            'nchildren'] = 'SELECT COUNT(*) FROM %s as p WHERE p.parent_id = %s.id' % (
                page_table_name, page_table_name)

        qs = qs \
            .filter(slugs__language='%s' % language) \
            .exclude(state__in=[page_state.EXTRAHIDDEN, page_state.IN_TRASH, page_state.SETTINGS]) \
            .extra(select=select)

        # TODO!!! Проверить корректность следующих строк
        queryset_ext = scms.site.get_content_type(
            request.scms['page_type']
        ).get_queryset  # дополнительный фильтр в зависимости от родительского контента
        if queryset_ext:
            qs = request.queryset_ext(self.model, language, qs)

        # Если не установлен родитель устанавливаем его как корень,
        # если установлен django.admin добавит соответствующий фильтр самостоятельно
        if 'parent__id__exact' not in request.GET:
            qs = qs.filter(parent__id__exact=None)
        return qs
Esempio n. 4
0
 def parse_destination(self, request, obj=None):
     """
     Анализирует GET['destination'] и формирует путь по которому необходимо перейти
     """
     destination = request.GET.get('destination', '../') 
     if destination == 'alias':
         edit_lang = get_language_from_request(request)
         if obj.state == page_state.MAIN:
             destination = "/"
         else:
             try:
                 destination = self.slug_model.objects.get(page=obj, language=edit_lang).alias.replace('*', '')
             except self.slug_model.DoesNotExist: # на случай если destination == alias, а записи в слугс нет
                 return "/"
         if not edit_lang == get_default_language() and  not edit_lang == get_language(): # для того, чтобы при возврате на 'alias' страница отображалась не на языке по-умолчанию, а на редактируемом
             destination = '/%s%s' % (edit_lang, destination)
     
             
     return destination
Esempio n. 5
0
 def items(self):
     self.default_language = get_default_language()
     # qs = Page.objects.filter(published=1, slugs__language__in=[lang[0] for lang in settings.SCMS_LANGUAGES]).order_by('id','slugs__alias').extra(select={
     #         'alias': 'IF (`scms_page`.`state` = %s, "/", REPLACE(`scms_slugs`.`alias`,"*",""))' % page_state.MAIN,
     #         'language': '`scms_slugs`.`language`',
     #         }).exclude(state__in=[page_state.EXTRAHIDDEN, page_state.IN_TRASH, page_state.SETTINGS]).exclude(slugs__alias=None)
     qs = Slugs.objects.filter(
         page__published=1,
         language__in=[lang[0] for lang in settings.SCMS_LANGUAGES]
     ).order_by('id', 'alias').extra(
         select={
             'alias':
             'IF (`scms_page`.`state` = %s, "/", REPLACE(`scms_slugs`.`alias`,"*",""))'
             % page_state.MAIN,
             'language':
             '`scms_slugs`.`language`',
         }).exclude(page__state__in=[
             page_state.EXTRAHIDDEN, page_state.IN_TRASH,
             page_state.SETTINGS
         ]).exclude(alias=None).values("page__modifed", "language",
                                       "page__date", "id", "alias")
     return qs
Esempio n. 6
0
File: views.py Progetto: m4x4n0/scms
def scms_mongo_render(request, alias=''):
    # Формирование страницы
    db = get_mongo()
    if not db: 
        return scms_render(request, alias)
    import pymongo

    request.scms = {}
    
    lang = get_language_from_request(request)
    if alias:
        query = {'language':lang, '$or': [{'alias': '*/%s' % alias}, {'alias': '/%s' % alias}]}
        slug = MongoManager(query)
        is_front = False
        # import debug
        # Чтобы главная страница не дублировалась с двумя адресами
        if slug.state == page_state.MAIN:
            return HttpResponseRedirect('/')
    else:
        # slug = Slugs.objects.filter(page__state=page_state.MAIN, language=lang)[0] # Сделать выдачу исключения , что нет главной страницы
        slug = MongoManager({'state':1, 'language':lang})

        is_front = True
    # import debug
    if not slug.pk:
        raise Http404()
    elif slug.count() > 1:
        raise Http404('Exception: Slugs.MultipleObjectsReturned')

    if not slug.published and alias != 'search':
        raise Http404()

    # try:
    #     cp = Page(id=slug.page_id).full_load(request=request, only_cached=False) # объект текущей страницы
    # except Page.DoesNotExist:
    #     raise Http404()
    cp = slug

    is_inner = cp.parent_id and True or False
    pp = is_inner and MongoManager({'id':cp.parent_id}) or False
    
    
    request.scms['cp'] = cp

    lang_prefix = not lang == get_default_language() and ('/%s' % lang) or ''

    # Подготавливаем сервисные ссылки для быстрого доступа к админке
    scms_links = []

    if  request.user.id: # Чтобы лишние запросы к БД не создовались
        from scms.admin.pageadmin import PageAdmin
        pageadmin = PageAdmin(scms.models.pagemodel.Page, False)
        
        if pageadmin.has_change_permission(request, cp):
            getlang = not lang == get_default_language() and '&language=%s' % lang or ''
    
            scms_links.append({
                'name': _('Edit'), 
                'href': '/admin/scms/page/%s/?destination=alias%s' % (cp.pk, getlang)
            }) 
        
        if pageadmin.has_delete_permission(request, cp):
            link = pp and pp.link or '/'
            scms_links.append({
                'name': _('Delete'), 
                'href': '/admin/scms/page/%s/delete/?destination=%s' % (cp.pk, link ) 
            })
        # parent_content_type = scms.site.get_content_type(cp.type)
        # for children_name in parent_content_type.children:
        #     next_content_type = scms.site.get_content_type(children_name)
        #     if not pageadmin.has_add_permission(request, parent_page=cp, type=children_name):
        #         continue
        #     scms_links.append({
        #         'name': _('Create %s') % force_text(next_content_type.name),
        #         'href': '/admin/scms/page/add/?type=%s&parent=%s&destination=%s' % (next_content_type.id, cp.pk, get_destination(request) )                               
        #     })
        # if request.user.is_staff:
        #     scms_links.append({
        #         'name': _('Go to CMS'), 
        #         'href': '/admin/',
        #     }) 
    
    request.scms_page = cp # сохраняем в request текущую просматриваемую страницу, чтобы можно было ее использовать например в plugins.contact_form Чтобы знать с какой страницы отправлено сообщение

    context = {  'title': slug.title, 
                 'link': cp.link,
                 'page_id': cp.id, 
                 'parent_id': cp.parent_id,
                 'lang_prefix': lang_prefix,
                 'lang': lang,
                 'is_inner': is_inner, # т.е. если страница не в корне
                 'is_front': is_front,
                 'scms_links': scms_links,
                 'request': request,
                 'cp': cp,
                 'pp': pp,
                 'now': datetime.datetime.now().strftime("%Y-%m-%d %H:%M") ,
                 'breadcrumbs': cp.get_parents()
              }

    # context.update(csrf(request))
    # context.update(request)

    # Формируем обращаемся к страницам
    for source in ['%s-%s' % (cp.type, cp.id), cp.type, 'common']:
        try:
            mod = import_module('pages.' + source)
        except SyntaxError as err:
            raise SyntaxError(err)
        except ImportError:
            continue    
            
        prepare_func = getattr(mod, 'prepare')
        
        if prepare_func:
            result = prepare_func(request, context, alias)
            if result:
                return result
        
            
    subtype = request.GET.get('subtype', '')
    templates = ['page-%s-%s-%s-%s.html' % (cp.type, cp.id, lang, subtype),
                                   'page-%s-%s-%s.html' % (cp.type, cp.id, lang),
                                   'page-%s-%s-%s.html' % (cp.type, cp.id, subtype),
                                   'page-%s-%s.html' % (cp.type, cp.id),
                                   'page-%s-%s-%s.html' % (cp.type, lang, subtype), 
                                   'page-%s-%s.html' % (cp.type, lang), 
                                   'page-%s-%s.html' % (cp.type, subtype),
                                   'page-%s.html' % cp.type,
                                   'page-common-%s.html' % lang,
                                   'page-common.html',]
    response = render(request, templates, context)
    
    
    #smart_cache.go(html_cache_fpathname, 0, depended_types=self.depended_types, adition_dependies=self.adition_dependies, delete_callback=None)
    # Сохранение сформированной страницы в кеш
    #try:
    #    dirname = os.path.dirname(html_cache_fpathname)
    #    if not os.path.exists(dirname):
    #        os.makedirs(dirname)
    #    html_cache_fhandle = open(html_cache_fpathname, 'w+')
    #    html_cache_fobj = File(html_cache_fhandle)
    #    html_cache_fobj.write(response.content)
    #    html_cache_fobj.close()
    #except OSError:
    #    pass    
    return response
Esempio n. 7
0
File: views.py Progetto: m4x4n0/scms
def scms_render(request, alias=''):
    
    # Подготовка имени файла для механизма кеширования целых страниц
    #html_cache_fname = alias and alias or 'index'
    #if request.environ['QUERY_STRING']:
    #    html_cache_fname = html_cache_fname + '&&&' + request.environ['QUERY_STRING']
    #html_cache_fpathname = settings.SITE_ROOT + settings.TMP_DIR + 'html_cache/' + html_cache_fname + '.html'
    
    # Попытка загрузки кеша из файла
    #try:
    #    html_cache_fhandle = open(html_cache_fpathname, 'r')
    #    html_cache_fobj = File(html_cache_fhandle)
    #    content = html_cache_fobj.read()
    #    html_cache_fobj.close()
    #    return HttpResponse(content)
    #except IOError:
    #    pass
    
    
    
    # Формирование страницы
    request.scms = {}
    
    lang = get_language_from_request(request)
    
    try:
        if alias:
            #slug = Slugs.objects.get(alias__regex=r'^[\*]?/%s$' % alias, language=lang)
            slug = Slugs.objects.get(Q(alias='*/%s' % alias) | Q(alias='/%s' % alias), language=lang) #, page__published=True)
            is_front = False
            
            # Чтобы главная страница не дублировалась с двумя адресами
            if slug.page.state == page_state.MAIN:
                return HttpResponseRedirect('/')
        else:
            slug = Slugs.objects.filter(page__state=page_state.MAIN, language=lang)[0] # Сделать выдачу исключения , что нет главной страницы
            is_front = True
    except Slugs.DoesNotExist:
        raise Http404()
    except Slugs.MultipleObjectsReturned:
        raise Http404('Exception: Slugs.MultipleObjectsReturned')

    if not slug.page.published and alias != 'search':
        raise Http404()

    try:
        cp = Page(id=slug.page_id).full_load(request=request, only_cached=False) # объект текущей страницы
    except Page.DoesNotExist:
        raise Http404()

    is_inner = cp.parent_id and True or False
    pp = is_inner and Page(id=cp.parent_id).full_load(request=request) or False
    
    
    request.scms['cp'] = cp

    lang_prefix = not lang == get_default_language() and ('/%s' % lang) or ''

    # Подготавливаем сервисные ссылки для быстрого доступа к админке
    scms_links = []
    if request.user.id: # Чтобы лишние запросы к БД не создовались
        from scms.admin.pageadmin import PageAdmin
        pageadmin = PageAdmin(scms.models.pagemodel.Page, False)
        
        if pageadmin.has_change_permission(request, cp):
            getlang = not lang == get_default_language() and '&language=%s' % lang or ''
    
            scms_links.append({
                'name': _('Edit'), 
                'href': '/admin/scms/page/%s/?destination=alias%s' % (cp.pk, getlang)
            }) 
    
        if pageadmin.has_delete_permission(request, cp):
            link = pp and pp.link or '/'
            scms_links.append({
                'name': _('Delete'), 
                'href': '/admin/scms/page/%s/delete/?destination=%s' % (cp.pk, link ) 
            })
        parent_content_type = scms.site.get_content_type(cp.type)
        for children_name in parent_content_type.children:
            next_content_type = scms.site.get_content_type(children_name)
            if not pageadmin.has_add_permission(request, parent_page=cp, type=children_name):
                continue
            scms_links.append({
                'name': _('Create %s') % force_text(next_content_type.name),
                'href': '/admin/scms/page/add/?type=%s&parent=%s&destination=%s' % (next_content_type.id, cp.pk, get_destination(request) )                               
            })
        if request.user.is_staff:
            scms_links.append({
                'name': _('Go to CMS'), 
                'href': '/admin/',
            }) 
    
    request.scms_page = cp # сохраняем в request текущую просматриваемую страницу, чтобы можно было ее использовать например в plugins.contact_form Чтобы знать с какой страницы отправлено сообщение

    context = {  'title': slug.title, 
                 'link': cp.link,
                 'page_id': slug.page_id, 
                 'parent_id': cp.parent_id,
                 'lang_prefix': lang_prefix,
                 'lang': lang,
                 'is_inner': is_inner, # т.е. если страница не в корне
                 'is_front': is_front,
                 'scms_links': scms_links,
                 'request': request,
                 'cp': cp,
                 'pp': pp,
                 'now': datetime.datetime.now().strftime("%Y-%m-%d %H:%M") ,
                 'breadcrumbs': cp.parents,
              }
    # import debug
    # context.update(csrf(request))
    # context.update(dict(request))

    # Формируем обращаемся к страницам
    for source in ['%s-%s'%(cp.type, cp.id), cp.type, 'common']:
        try:
            mod = import_module('pages.' + source)
        except SyntaxError as err:
            raise SyntaxError(err)
        except ImportError:
            continue    
            
        prepare_func = getattr(mod, 'prepare')
        
        if prepare_func:
            result = prepare_func(request, context, alias)
            if result:
                return result
        
            
    subtype = request.GET.get('subtype', '')
    
    
    response = render(request, ['page-%s-%s-%s-%s.html' % (cp.type, cp.id, lang, subtype),
                                   'page-%s-%s-%s.html' % (cp.type, cp.id, lang),
                                   'page-%s-%s-%s.html' % (cp.type, cp.id, subtype),
                                   'page-%s-%s.html' % (cp.type, cp.id),
                                   'page-%s-%s-%s.html' % (cp.type, lang, subtype), 
                                   'page-%s-%s.html' % (cp.type, lang), 
                                   'page-%s-%s.html' % (cp.type, subtype),
                                   'page-%s.html' % cp.type,
                                   'page-common-%s.html' % lang,
                                   'page-common.html',], context)
    
    
    #smart_cache.go(html_cache_fpathname, 0, depended_types=self.depended_types, adition_dependies=self.adition_dependies, delete_callback=None)
    # Сохранение сформированной страницы в кеш
    #try:
    #    dirname = os.path.dirname(html_cache_fpathname)
    #    if not os.path.exists(dirname):
    #        os.makedirs(dirname)
    #    html_cache_fhandle = open(html_cache_fpathname, 'w+')
    #    html_cache_fobj = File(html_cache_fhandle)
    #    html_cache_fobj.write(response.content)
    #    html_cache_fobj.close()
    #except OSError:
    #    pass    
    return response
Esempio n. 8
0
 def save(self, commit=True):
     obj = super(ChangelistModelForm, self).save(commit)
     for plugin_field_info in self.plugin_fields:
         if plugin_field_info['list_name'] in self.changed_data:
             record = {}
             record['page'] = obj
             record['language'] = plugin_field_info['field'].lang_depended and get_default_language() or ''
             record['field_name'] = plugin_field_info['field'].name
             
             # Получаем объект редактируемого параметра
             field_obj = plugin_field_info['field'].model.objects.filter(**record)[plugin_field_info['pos']:plugin_field_info['pos']+1]
             
             if field_obj:
                 field_obj = field_obj[0]
             else:
                 field_obj = plugin_field_info['field'].model(**record)
             # Записываем новое значение этого параметра
             setattr(field_obj, plugin_field_info['db_field'], self.cleaned_data[plugin_field_info['list_name']])
             if commit:
                 field_obj.save()
             
     return obj