def recent_widget(parent=False, parent_type=False, request=False): return_data = {'recent': [], 'featured': []} if parent_type == 'category' and parent: return_data['recent'] = image.objects.filter( cat__in=parent.get_descendants(include_self=True), published=True).filter(access_query(request)).exclude( rebuild_assets=True, is_new=True, featured=True).order_by('-timestamp_post').select_related( 'cat').prefetch_related('assets')[:12] return_data['featured'] = image.objects.filter( cat__in=parent.get_descendants(include_self=True), published=True, featured=True).filter(access_query(request)).exclude( rebuild_assets=True, is_new=True).order_by('-timestamp_post').select_related( 'cat').prefetch_related('assets')[:6] return return_data elif parent_type == 'tag' and parent: return_data['recent'] = image.objects.filter( tags=parent, published=True).filter(access_query(request)).exclude( rebuild_assets=True, is_new=True, featured=True).order_by('-timestamp_post').select_related( 'cat').prefetch_related('assets')[:12] return_data['featured'] = image.objects.filter( tags=parent, published=True, featured=True).filter(access_query(request)).exclude( rebuild_assets=True, is_new=True).order_by('-timestamp_post').select_related( 'cat').prefetch_related('assets')[:6] return return_data else: return False
def finder(request): import os return_data = (False, '') # Fix the trailing slash if request.path.endswith('/'): basename = os.path.basename(request.path[:-1]) else: basename = os.path.basename(request.path) # Check for special features that were improperly categorized feature_check = special_feature.objects.filter( url__iexact=basename).filter( access_query(request)).select_related().first() if feature_check and feature_check.url_reverse: return_data = (True, reverse(feature_check.url_reverse)) if not return_data[0]: if '.' in basename: # Categories don't have dots in the slug return return_data else: cat_check = category.objects.filter(slug__iexact=basename).filter( access_query(request)).select_related().first() if cat_check: return_data = (True, reverse('category', kwargs={ 'cached_url': cat_check.cached_url, })) return return_data
def get_context_data(self, **kwargs): context=super(book,self).get_context_data(**kwargs) context['pages'] = [] context['timestamp'] = False context['source_url'] = False # Prepping for the source_url if 'www' not in self.request.site.domain: site_domain = 'www.%s' % self.request.site.domain else: site_domain = self.request.site.domain for page in context['toc'].pages.filter(access_query()).order_by('book_order'): canview = page.can_view(self.request) if not canview[0]: continue else: context['pages'].append(page) # source_url should be the url for the first visible page if not context['source_url']: context['source_url'] = 'http://%s%s' % (site_domain, reverse('page_htm', kwargs={'cached_url':page.cat.cached_url,'slug':page.slug,})) # timestamp should be the displayed timestamp of whichever page is newest cur_page_timestamp = page.display_times() if context['timestamp']: if context['timestamp'] < cur_page_timestamp[0]['timestamp']: context['timestamp'] = cur_page_timestamp[0]['timestamp'] else: context['timestamp'] = cur_page_timestamp[0]['timestamp'] if not context['pages']: raise Http404 return context
def social_icons(request): social_links = contact_link.objects.filter(featured=True).filter( access_query(request)).order_by('label') if social_links: return {'header_icons': social_links} else: return {'header_icons': False}
def finder(request): import os return_data = (False,'') basename=os.path.basename(request.path) if '.' in basename: search_slug_list = basename.split('.') search_slug = search_slug_list[0] search_type = search_slug_list[-1].lower() page_check = page.objects.filter(slug__iexact=search_slug).filter(access_query(request)).select_related().prefetch_related('docfiles').first() if page_check: # Yay! We found a match that you're allowed to view! # Now let's figure out what type of URL to send back. # php, htm, and html are definitely a page object # pdf, dvi, ps, and epub are definitely an export_file object # txt, md, and tex could be either one is_page = ['php','htm','html','txt','md','tex'] is_file = ['pdf','dvi','ps','epub','rtf','docx','txt','md','tex'] # Uploaded files take priority if search_type in is_file and not return_data[0]: check_file = page_check.docfiles.filter(filetype=search_type).first() if check_file: return_data = (True, check_file.get_url()) # We didn't find it in the uploaded files, so maybe it's a page? if search_type in is_page and not return_data[0]: if search_type == 'php' or search_type == 'html': search_type = 'htm' return_data = (True,reverse('page_%s' % search_type, kwargs={'cached_url':page_check.cat.cached_url, 'slug':page_check.slug})) return return_data
def get_context_data(self, **kwargs): context = super(sitemap,self).get_context_data(**kwargs) context['tags'] = tag.objects.all().annotate(num_leaves=Count('leaf')) context['cats'] = category.objects.filter(access_query(self.request)).annotate(num_leaves=Count('leaf')) return context
def get_context_data(self, **kwargs): context = super(single_page,self).get_context_data(**kwargs) context['has_reading_mode'] = True if self.alt_view and context.get('embed_mature_form') == True: raise PermissionDenied if context['object']: if context['object'].book_title: context['toc'] = context['object'].book_title.pages.filter(access_query(self.request)).select_related('cat').order_by('book_order') context['alt_version_exclude'] = [] if context['object'].docfiles: context['docfiles'] = [] for item in context['object'].docfiles.all(): context['alt_version_exclude'].append(item.filetype) context['docfiles'].append(item) context['body_text'] = sunset_embed(context['object'].body_html, self.request) if self.request.GET.get('mode', False) == 'read': context['showcase_mode'] = True elif context['object'].showcase_default and self.request.GET.get('mode', False) != 'normal': context['showcase_mode'] = True else: context['showcase_mode'] = False if context['can_edit']: context['edit_url'] = 'admin:deerbooks_page_change' context['extra_classes'] = 'writing_page' return context
def get_leaves(self, parent=False, parent_type=False): leaf_filters = {} leaf_ordering = ["-featured", "-timestamp_post"] leaf_filters["timestamp_post__lte"] = timezone.now() if parent_type == "homepage": leaf_ordering = ["-timestamp_post"] leaf_filters["featured"] = True elif parent_type == "main_feed": leaf_ordering = ["-timestamp_post"] elif parent_type == "category" and parent: leaf_filters["cat"] = parent elif parent_type == "tag" and parent: leaf_filters["tags"] = parent from awi_access.models import access_query leaves = ( leaf.objects.filter(**leaf_filters) .filter(access_query(self.request)) .order_by(*leaf_ordering) .select_related() ) if leaves: return leaves else: if parent_type == "category" and parent: descendants = parent.get_descendants() leaves = ( leaf.objects.filter(featured=True, cat__in=descendants) .filter(access_query(self.request)) .order_by("-timestamp_post") .select_related() ) if leaves: self.highlight_featured = False return leaves else: return False else: return False
def contact_widget(parent=False, parent_type=False, request=False): if parent_type == 'category' and parent: ancestors = parent.get_ancestors(include_self=True) contact_links = contact_link.objects.filter(cat__in=ancestors).filter( access_query(request)).order_by('-timestamp_mod') if contact_links: return contact_links else: return False else: return False
def subcats(parent=False, parent_type=False, request=False): if parent_type == 'category' and parent: child_cats = parent.children.filter(access_query(request)).order_by( '-featured', 'title').select_related('icon') if child_cats: return child_cats else: return False else: return False
def recent_widget(parent=False, parent_type=False, request=False): return_data = {'recent': [], 'featured': []} if parent_type == 'category' and parent: return_data['recent'] = page.objects.filter(cat__in=parent.get_descendants(include_self=True), published=True).filter(access_query(request)).exclude(featured=True).order_by('-timestamp_post').select_related('book_title','cat')[:4] return_data['featured'] = page.objects.filter(cat__in=parent.get_descendants(include_self=True), published=True, featured=True).filter(access_query(request)).order_by('-timestamp_post').select_related('book_title','cat')[:2] return return_data elif parent_type == 'tag' and parent: return_data['recent'] = page.objects.filter(tags=parent, published=True).filter(access_query(request)).exclude(featured=True).order_by('-timestamp_post').select_related('book_title','cat')[:4] return_data['featured'] = page.objects.filter(tags=parent, published=True, featured=True).filter(access_query(request)).order_by('-timestamp_post').select_related('book_title','cat')[:2] return return_data else: return False
def get_context_data(self, **kwargs): context = super(all_cats, self).get_context_data(**kwargs) context['view'] = 'catlist' context['cats'] = category.objects.filter(access_query( self.request)).annotate(num_leaves=Count('leaves')) context['breadcrumbs'] = self.breadcrumbs() if self.request.GET.get('return_to') and self.request.user.has_perm( 'deertrees.change_leaf'): context['return_to'] = self.request.GET.get('return_to') return context
def geojson_image(request, slug, **kwargs): from deertrees.models import category, tag return_data = [] query = image.objects.filter(access_query(request)).exclude( rebuild_assets=True, is_new=True ).exclude(Q(geo_lat__isnull=True) | Q(geo_long__isnull=True)).order_by( '-timestamp_post').select_related('cat').prefetch_related('assets') if slug == 'full_list': pass elif 'filter_cat' in slug: filter = slug.replace('filter_cat_', '') filter_obj = get_object_or_404(category, slug=filter) query = query.filter(cat=filter_obj) elif 'filter_tag' in slug: filter = slug.replace('filter_tag_', '') filter_obj = get_object_or_404(tag, slug=filter) query = query.filter(tag=filter_obj) elif slug == 'filter_featured': query = query.exclude(featured=False) else: request.session['deerfind_norecover'] = True raise Http404 for item in query: if item.featured: marker_color = '#5b4aFF' elif item.mature: marker_color = '#c0283a' else: marker_color = '#5b4a71' #icon = item.assets.filter(type='icon').first() return_data.append({ 'type': 'Feature', 'geometry': { 'type': 'Point', 'coordinates': [item.geo_long, item.geo_lat], }, 'properties': { 'marker-color': marker_color, 'marker-size': 'small', 'title': unicode(item), 'description': unicode(item), }, }) return json_response(request, data=return_data)
def get_context_data(self, **kwargs): context=super(single_page,self).get_context_data(**kwargs) if context['object']: if context['object'].book_title: context['toc'] = context['object'].book_title.pages.filter(access_query(self.request)).select_related('cat').order_by('book_order') context['alt_version_exclude'] = [] if context['object'].docfiles: context['docfiles'] = [] for item in context['object'].docfiles.all(): context['alt_version_exclude'].append(item.filetype) context['docfiles'].append(item) return context
def finder(request): import os return_data = (False, '') basename = os.path.basename(request.path) if '.' in basename: search_slug_list = basename.split('.') search_slug = search_slug_list[0] image_check = image.objects.filter(slug__iexact=search_slug).filter( access_query(request)).select_related().first() if image_check: # Yay! We found a match! And it's authorized for viewing. return_data = (True, reverse('image_single', kwargs={ 'cached_url': image_check.cat.cached_url, 'slug': image_check.slug, })) return return_data
def get_context_data(self, **kwargs): context = super(contact_page, self).get_context_data(**kwargs) if not context.get('breadcrumbs', False): context['breadcrumbs'] = [] context['breadcrumbs'].append({ 'url': reverse('contact'), 'title': 'Contact' }) if self.request.session.get('deerconnect_success_msg', False): context['form'] = '' context['error'] = 'mailform_success' self.request.session['deerconnect_success_msg'] = False elif self.request.session.get('deerconnect_mailsent', False): last_message = dateparse.parse_datetime( self.request.session.get('deerconnect_mailsent', False)) expiration = datetime.timedelta(days=1) if last_message > timezone.now() - expiration: context['form'] = '' context['error'] = 'mailform_toosoon' contactinfo = contact_link.objects.filter(access_query( self.request)).order_by('-im', '-timestamp_mod') if contactinfo: for link in contactinfo: if link.im: if not context.get('links_im', False): context['links_im'] = [] context['links_im'].append(link) else: if not context.get('links', False): context['links'] = [] context['links'].append(link) return context
def get_context_data(self, **kwargs): context=super(book,self).get_context_data(**kwargs) context['pages'] = [] context['timestamp'] = False context['source_url'] = False # Prepping for the source_url if 'www' not in self.request.site.domain: site_domain = 'www.%s' % self.request.site.domain else: site_domain = self.request.site.domain for page in context['toc'].pages.filter(access_query()).order_by('book_order'): canview = page.can_view(self.request) if not canview[0]: continue else: page.body = sunset_embed(page.body_html, self.request) context['pages'].append(page) # source_url should be the url for the first visible page if not context['source_url']: context['source_url'] = 'http://%s%s' % (site_domain, reverse('page_htm', kwargs={'cached_url':page.cat.cached_url,'slug':page.slug,})) # timestamp should be the displayed timestamp of whichever page is newest cur_page_timestamp = page.display_times() if context['timestamp']: if context['timestamp'] < cur_page_timestamp[0]['timestamp']: context['timestamp'] = cur_page_timestamp[0]['timestamp'] else: context['timestamp'] = cur_page_timestamp[0]['timestamp'] if not context['pages']: self.request.session['deerfind_norecover'] = True raise Http404 return context
def get_context_data(self, **kwargs): context = super(contact_page, self).get_context_data(**kwargs) if self.request.session.get('deerconnect_mailsent',False): last_message = dateparse.parse_datetime(self.request.session.get('deerconnect_mailsent',False)) expiration = datetime.timedelta(days=1) if last_message > timezone.now() - expiration: context['form'] = '' context['error'] = 'mailform_toosoon' contactinfo = contact_link.objects.filter(access_query(self.request)).order_by('-im','-timestamp_mod') if contactinfo: for link in contactinfo: if link.im: if not context.get('links_im',False): context['links_im'] = [] context['links_im'].append(link) else: if not context.get('links',False): context['links'] = [] context['links'].append(link) return context
def assemble_blocks(self, parent=False, parent_type=False): # BLOCK STRUCTURE # In order of assignment # # main_full_1 - Primary content area, full-width. Omitted if content_priority is desc # sidebar - List; add two, then go to main_full_2 if needed. # main_full_2 - Secondary content area, full_width. # sidebar - List; do one, then go to a main_half block, and alternate as-needed. # main_half - List; there can be as many of these as needed. Alternate as-needed with sidebar. blocks_map = settings.DEERTREES_BLOCKS blocks = {} blocks_count = {} assigned_to_blocks = [] returned_data = [False,{}] # Build the list of blocks to assign if parent_type == 'homepage': blocks_to_assign = ['main_half','sidebar','main_half','sidebar'] else: blocks_to_assign = ['sidebar','sidebar','main_full_2'] if parent and parent.content_priority != 'desc': blocks_to_assign.insert(0,'main_full_1') # Loop the known-existing content types, to get a list. We'll deal with priority later. for type, settings_dict in blocks_map.iteritems(): blocks[type] = [] blocks_count[type] = 0 # Content time! # First, check for subcategories and contact links if parent_type == 'category' and parent: child_cats = parent.children.filter(access_query(self.request)).order_by('title') if child_cats: blocks['category'] = child_cats ancestors = parent.get_ancestors(include_self=True) contact_links = contact_link.objects.filter(cat__in=ancestors).filter(access_query(self.request)).order_by('-timestamp_mod') if contact_links: blocks['contact_link'] = contact_links # Now get items in this category leaves = self.get_leaves(parent,parent_type) if leaves: # 1. Loop all of our leaves # 2. For each leaf, loop blocks_map to find its type # 3. Once that check is successful, put it in the correct block dictionary for leaf_item in leaves: for type, blocksettings in blocks_map.iteritems(): if blocksettings['is_leaf']: if blocks_count[type] <= 50: leaf_content = getattr(leaf_item,type,None) if leaf_content: blocks[type].append(leaf_content) blocks_count[type] += 1 # Clean up empty elements empty_keys = [k for k,v in blocks.iteritems() if not v] for k in empty_keys: del blocks[k] # Moment of truth! Did we actually get anything out of this category? if blocks: returned_data[0] = True # Ok, we how have all of our leaves neatly arranged by type and ready to display. # Now it's time to assign blocks for display # Assignment time! # Start with the special case if blocks_to_assign[0] == 'main_full_1' and blocks.get(parent.content_priority,False): returned_data[1]['main_full_1'] = {'type':parent.content_priority,'title':blocks_map[parent.content_priority]['title'],'data':blocks[parent.content_priority],'template':blocks_map[parent.content_priority]['template']} blocks_to_assign.pop(0) blocks.pop(parent.content_priority) # Make sure we didn't just pop off the last/only one. if blocks: order_main = {} order_sidebar = {} blockorder_main = False blockorder_sidebar = False # Now, let's build a priority list per region for type, content in blocks.iteritems(): if blocks_map[type].get('main',False): order_main[str(blocks_map[type]['main'])] = {'type':type,'title':blocks_map[type]['title'],'data':content,'template':blocks_map[type]['template']} if blocks_map[type].get('sidebar',False): order_sidebar[str(blocks_map[type]['sidebar'])] = {'type':type,'title':blocks_map[type]['title'],'data':content,'template':blocks_map[type]['template']} # And now put them in order if order_main: blockorder_main = [] for key,value in sorted(order_main.iteritems()): blockorder_main.append(value) if order_sidebar: blockorder_sidebar = [] for key,value in sorted(order_sidebar.iteritems()): blockorder_sidebar.append(value) # Assign the main blocks first for blockname in blocks_to_assign: if 'main' in blockname and blockorder_main: for blockdata in blockorder_main: if blockdata['type'] not in assigned_to_blocks: if not returned_data[1].get('main_half',False): returned_data[1]['main_half'] = [] if blockname == 'main_half': returned_data[1]['main_half'].append(blockdata) else: returned_data[1][blockname] = blockdata assigned_to_blocks.append(blockdata['type']) break elif 'sidebar' in blockname and blockorder_sidebar: for blockdata in blockorder_sidebar: if blockdata['type'] not in assigned_to_blocks: if not returned_data[1].get('sidebar',False): returned_data[1]['sidebar'] = [] returned_data[1]['sidebar'].append(blockdata) assigned_to_blocks.append(blockdata['type']) break # Quick bit of cleanup for content_type in assigned_to_blocks: blocks.pop(content_type,None) # Is there anything left? if blocks: # Seriously? Ok then, we'll just go through whatever's left. # Sidebar takes priority. for sidebar_data in blockorder_sidebar: if sidebar_data['type'] not in assigned_to_blocks: returned_data[1]['sidebar'].append(sidebar_data) assigned_to_blocks.append(sidebar_data['type']) for main_data in blockorder_main: if main_data['type'] not in assigned_to_blocks: if not returned_data[1]['main_half']: returned_data[1]['main_half'] = [] returned_data[1]['main_half'].append(main_data) assigned_to_blocks.append(main_data['type']) return returned_data
def get_leaves(self, parent=False, parent_type=False): leaf_filters = {} blocks_map = settings.DEERTREES_BLOCKS leaf_list = [] prefetch_list = [] for type, settings_dict in blocks_map.iteritems(): if settings_dict.get('is_leaf',False): leaf_list.append(type) leaf_list.append('%s__cat' % type) if settings_dict.get('prefetch',False): for pf_field in settings_dict['prefetch']: prefetch_list.append('%s__%s' % (type, pf_field)) if settings_dict.get('related',False): for sr_field in settings_dict['related']: leaf_list.append('%s__%s' % (type, sr_field)) leaf_ordering = ['-featured','-timestamp_post'] leaf_filters['timestamp_post__lte'] = timezone.now() if parent_type == 'homepage': leaf_ordering = ['-timestamp_post',] leaf_filters['featured'] = True elif parent_type == 'main_feed': leaf_ordering = ['-timestamp_post',] elif parent_type == 'category' and parent: leaf_filters['cat'] = parent elif parent_type == 'tag' and parent: leaf_filters['tags'] = parent leaves = leaf.objects.select_related(*leaf_list).prefetch_related(*prefetch_list).filter(**leaf_filters).filter(access_query(self.request)).order_by(*leaf_ordering) if leaves: return leaves else: if parent_type == 'category' and parent: descendants = parent.get_descendants() leaves = leaf.objects.select_related(*leaf_list).prefetch_related(*prefetch_list).filter(featured=True, cat__in=descendants).filter(access_query(self.request)).order_by('-timestamp_post') if leaves: self.highlight_featured = False return leaves else: return False else: return False
def items(self): return special_feature.objects.filter(access_query()).select_related('cat')
def items(self): return category.objects.filter(access_query()).filter(sitemap_include=True)
def items(self): return page.objects.filter(access_query()).select_related('cat')
def get_leaves(self, parent=False, parent_type=False, is_feed=False): blocks_main = settings.DEERTREES_BLOCKS leaf_filters = {} related_list = [] prefetch_list = [] for type, settings_dict in blocks_main.iteritems(): if settings_dict.get('is_leaf', False): related_list.append(type) related_list.append('%s__cat' % type) related_list.append('%s__access_code' % type) if settings_dict.get('prefetch', False): for pf_field in settings_dict['prefetch']: prefetch_list.append('%s__%s' % (type, pf_field)) if settings_dict.get('related', False): for sr_field in settings_dict['related']: related_list.append('%s__%s' % (type, sr_field)) leaf_ordering = ['-featured', '-timestamp_post'] leaf_filters['timestamp_post__lte'] = timezone.now() # Special cases # Site home if parent_type == 'homepage': leaf_ordering = [ '-timestamp_post', ] leaf_filters['featured'] = True # RSS feed (Home) elif parent_type == 'main_feed': leaf_ordering = [ '-timestamp_post', ] # elif parent_type == 'category' and parent: leaf_filters['cat'] = parent elif parent_type == 'tag' and parent: leaf_filters['tags'] = parent elif parent_type == 'root' and parent: descendants = parent.get_descendants() self.highlight_featured = False leaf_ordering = [ '-timestamp_post', ] leaf_filters['featured'] = True leaf_filters['cat__in'] = descendants if is_feed: leaf_ordering = [ '-timestamp_post', ] leaves = leaf.objects.select_related(*related_list).prefetch_related( *prefetch_list).filter(**leaf_filters).filter( access_query(getattr(self, 'request', False))).order_by(*leaf_ordering) if leaves or is_feed: return leaves else: return False
def items(self): return category.objects.filter( access_query()).filter(sitemap_include=True)
def social_icons(request): social_links = contact_link.objects.filter(featured=True).filter(access_query(request)).order_by('label') if social_links: return {'header_icons':social_links} else: return {'header_icons':False}
def items(self): return special_feature.objects.filter( access_query()).select_related('cat')
def sunset_embed(body, request=False): # Moved the import down here to avoid a circular import from sunset.models import image self_closing = [ 'sunset', ] if body and "<sunset" in body: body_raw = BeautifulSoup(body, selfClosingTags=self_closing) imglist = body_raw.findAll('sunset') for imgtag in imglist: err = 'Unknown error parsing Sunset embed tag' new_tag = '' img_pk = imgtag.get('id', False) cur_type = imgtag.get('type', 'icon') if img_pk: img_check = image.objects.filter(pk=int(img_pk)).filter( access_query(request)).select_related('cat') if img_check: cur_img = img_check.first() asset_check = cur_img.assets.filter(type=cur_type) if asset_check: cur_asset = asset_check.first() new_tag = BeautifulSoup(selfClosingTags=self_closing) new_a = Tag(new_tag, 'a') new_img = Tag(new_tag, 'img') new_a['class'] = 'sunset_embed sunset_%s' % cur_type new_a['href'] = cur_img.get_absolute_url() new_a['title'] = cur_img new_img['alt'] = cur_img new_img['title'] = cur_img new_img['src'] = cur_asset.get_url() new_tag.insert(0, new_a) new_a.insert(0, new_img) err = False else: err = 'Sunset image asset type specified in embed tag was not found' else: err = 'Sunset image specified in embed tag was not found' else: err = 'Invalid or missing image ID in Sunset embed tag' if err: imgtag.replaceWith( Comment('%s. Original was: %s' % (err, imgtag))) else: imgtag.replaceWith(new_tag) return unicode(body_raw) else: # Nothing to do. return body