Example #1
0
def people_list(request):
    """
	Lists all users of the site - public view
	"""

    # get init values
    try:
        page = int(request.GET.get("page", "1"))
    except ValueError:
        page = 1

        # note: users with private only fragments here are listed @todo better query
    qset = (
        User.objects.exclude(created_fragment=None)
        .exclude(userprofile__defaultPrivate=True)
        .distinct()
        .order_by("-date_joined")
    )

    # qset = [u for u in qset if u.profile.get_fragments(onlypublic=True, count=True)]

    # present data
    paginator = Paginator(qset, 30)
    try:
        page_object = paginator.page(page)
    except (EmptyPage, InvalidPage):  # If page request is out of range, deliver last page of results.
        page_object = paginator.page(paginator.num_pages)
    page_object.extrastuff = paginator_helper(page, paginator.num_pages)
    page_object.totcount = paginator.count

    template_name = BOOTSTRAP + "pages/people_list.html"

    # finally...
    context = {"page_object": page_object}
    return render_to_response(template_name, context, context_instance=RequestContext(request))
Example #2
0
def search_quotes(request, username, favorites=False, clipboard=False):
	"""
	February 24, 2015: 
		removed collection and added group_var
	View that performs a search based on the query string, or returns the whole list of snippets.

	searchdict =  main list of AND constraints

	July 31, 2014: first version
	April 8, 2015: updated and removed <url_encode>
	
	"""
	
	PAGINATION_SET = 50
	
	# get init values
	searchdict = {}
	qset = Fragment.objects.filter()

	quickEditForm = None

	searchval = request.GET.get('q', "") 
	exactmatch = request.GET.get('exact', "") 
	group_var = request.GET.get('g', "") 
	sourcefacet_var = request.GET.get('d', "") 
	# tag = request.GET.get('tag', None) 
	subject = request.GET.get('subject', None) 
	view_var = request.GET.get('v', 'list')	 # March 28, 2014: not used
	sort_var = request.GET.get('sort', 'created')
	if sort_var not in ['alpha', 'modified', 'created']: sort_var = 'created'	 # default sort value
	sorting = {'alpha' : ["text", "-updated_at"], 
				'modified': ["-updated_at", "text"], 
				'created': ["-created_at", "text"]} [sort_var]
	if group_var not in ['all', 'last-week', 'last-month', 'no-collection', 'no-title']: group_var = 'all'
	
	try:
		page = int(request.GET.get('page', '1'))
	except ValueError:
		page = 1

	person = get_object_or_404(User, username=username)
	
	context = {'person' : person} # initialize context
	
	if request.user and request.user.is_authenticated() and person.username == request.user.username:
		context['mykoncepts'] = True
		searchdict['created_by'] = request.user
		usertags = [s.name for s in Subject.subjectsListPerUser(request.user)]
		if usertags:
			context['usertags'] = usertags
		if favorites:
			searchdict['favorite'] = True
			context.update({'page_flag' : "favorites" })
			# context['page_flag'] = "favorites",  # x dynamic top menu
		elif clipboard:
			searchdict['clipboard'] = True
			context.update({'page_flag' : "clipboard" })	
		else:
			context.update({'page_flag' : "searchquotes" })
		
	else:
		context['mykoncepts'] = False
		raise Http404


	try:
		sourcefacet_var = int(sourcefacet_var)
		source = Document.objects.get(pk=sourcefacet_var, created_by=request.user)
		quickEditForm = _prePopulateEditDocumentForm(source)
	except:
		sourcefacet_var, source = None, None

	# printdebug(tag)		


	if subject:
		try:
			subject = Subject.objects.get(pk=int(subject), created_by=person)
			subjects_tree = subject.get_descendants(include_self=True)
			if len(subjects_tree) > 1:
				context.update({
				'tree_inheritance' : True,
				})

		except:
			subjects_tree = None
			subject = None

	if subject:
		# GENERATE A BIG OR QUERY FOR THE SUBJECT TREE
		# searchdict['subjects__id'] = subject.id  # previusly..
		searchval = ""
		# Turn list of values into one big Q objects
		query = reduce(lambda q,value: q|Q(subjects__id=value.id), subjects_tree, Q())
		qset = qset.filter(query)


	if searchval:
		if exactmatch:
			_searchval = ' ' + searchval + ' '
			qset = qset.filter(text__icontains=_searchval)
			print "searchval is", searchval	
		else:  # fuzzy
			multi_search_val = [x.strip() for x in searchval.split(" ") if x]
			for x in multi_search_val:
				qset = qset.filter(text__icontains=x)


	if sourcefacet_var:
		searchdict['source__id'] = sourcefacet_var # already casted to a number

	else:
		# COLLECTIONS
		if group_var == 'all':
			pass # no need for other filters
		elif group_var == 'last-week':
			today = datetime.today()
			searchdict['created_at__gte'] = today - timedelta(days=7)
		elif group_var == 'last-month':
			today = datetime.today()
			searchdict['created_at__gte'] = today - timedelta(days=30)
		elif group_var == 'no-title':
			searchdict['title'] = None
		elif group_var == 'no-collection':
			searchdict['intfrag'] = None

	
	# qset = Fragment.objects.filter(**searchdict).distinct().order_by(*sorting)
	data = qset.filter(**searchdict).distinct().order_by(*sorting)
				

	# 2015-03-29: sources facet only if keyword is passed
	if searchval:
		# if a facet filter is available, remove it before recalc the facets
		if sourcefacet_var: # note: this was previously added
			searchdict.pop("source__id")
		# sourcesfacet = Fragment.objects.filter(**searchdict).order_by('source__title').values_list('source__title', 'source').distinct()
		sourcesfacet = qset.filter(**searchdict).order_by('source__title').values_list('source__title', 'source').distinct()
		
		# transform sourcefacet_var from id to a tuple
		for x in sourcesfacet:
			if x[1] == sourcefacet_var:
				sourcefacet_var = x
				break
		
	else:
		sourcesfacet = []
	
	
	
	# set up pagination and prepare for specific viz
	
	paginator = Paginator(data, PAGINATION_SET)
	try:
		page_object = paginator.page(page)
	except (EmptyPage, InvalidPage):  # If page request is out of range, deliver last page of results.
		page_object = paginator.page(paginator.num_pages)
	page_object.extrastuff = paginator_helper(page, paginator.num_pages)
	page_object.totcount = paginator.count

	if view_var == "list":
		template_name = BOOTSTRAP + 'pages/search_quotes.html'
	else:
		template_name = BOOTSTRAP + 'pages/search_quotes_viewbysource.html'

	# finally...
	context.update({	  
				'page_object' : page_object,
				'searchval' : searchval, 
				'exactmatch' : exactmatch, 
				'sort_var' : sort_var,
				'view_var' : view_var,
				'subject' : subject,
				'active_group' : group_var,
				'sourcesfacet' : sourcesfacet,
				'active_sourcefacet' : sourcefacet_var,
				'active_source' : source,
				'form' : quickEditForm , # for document
				})
	return render_to_response(template_name, 
							context,
							context_instance=RequestContext(request))
Example #3
0
def search_document(request, username):
	"""
	
	View that performs a search based on the query string, or returns the whole list of Documents.

	searchdict =  main list of AND constraints
	
	April 2, 2014: currenlty you can search only for your own documents
	
	February 24, 2015: added groups and reactivated view
	
	"""
	
	PAGINATION_SET = 50
	
	# get init values
	searchdict = {}
	qset = Document.objects.filter()
	
	searchval = request.GET.get('q', None) 
	group_var = request.GET.get('g', "") 	
	# view_var = request.GET.get('v', 'list') 
	sort_var = request.GET.get('sort', 'created')
	
	if sort_var not in ['alpha', 'modified', 'created']: sort_var = 'created'	
	if group_var not in ['all', 'last-week', 'last-month']: group_var = 'all'

	sorting = {'alpha' : ["title", "-updated_at"], 
				'modified': ["-updated_at", "title"], 
				'created': ["-created_at", "title"]} [sort_var]
						
	try:
		page = int(request.GET.get('page', '1'))
	except ValueError:
		page = 1

	person = get_object_or_404(User, username=username)
	
	context = {'person' : person} # initialize context
	
	if request.user and request.user.is_authenticated() and person.username == request.user.username:
		context['mykoncepts'] = True
		searchdict['created_by'] = request.user		
	else:
		context['mykoncepts'] = False
		raise Http404
	
	
	if searchval:
		multi_search_val = [x.strip() for x in searchval.split(" ") if x]
		for x in multi_search_val:
			qset = qset.filter(searchindex__icontains=x)
			# searchdict['searchindex__icontains'] = url_encode_search(x)
	else:	
		# GROUPS
		if group_var == 'all':
			pass # no need for other filters
		elif group_var == 'last-week':
			today = datetime.today()
			searchdict['created_at__gte'] = today - timedelta(days=7)	 
		elif group_var == 'last-month':
			today = datetime.today()
			searchdict['created_at__gte'] = today - timedelta(days=30)

	# print searchdict
	qset = qset.filter(**searchdict).distinct().order_by(*sorting)
					
	
	# set up pagination and prepare for specific viz
	
	paginator = Paginator(qset, PAGINATION_SET)
	try:
		page_object = paginator.page(page)
	except (EmptyPage, InvalidPage):  # If page request is out of range, deliver last page of results.
		page_object = paginator.page(paginator.num_pages)
	page_object.extrastuff = paginator_helper(page, paginator.num_pages)
	page_object.totcount = paginator.count

	template_name = BOOTSTRAP + 'pages/search_documents.html'

	# finally...
	context.update({	  
				'page_object' : page_object,
				'searchval' : searchval, 
				'sort_var' : sort_var,
				'active_group' : group_var,
				'page_flag' : "searchdocs",  # x dynamic top menu
				})
	return render_to_response(template_name, 
							context,
							context_instance=RequestContext(request))
Example #4
0
def get_document(request, username, source_name):
	"""
	View that returns a document with all of its interpretations/koncepts
	
	December 27, 2015: if the document is not owned by the user, it is not shown
	
	August 27, 2014: removed the Intfrags and tried to use only Koncept list
	- no pagination anymore temporarily, nor sorting
	
	December 29, 2014: added mechanism to make this work via IDs only
	eg '617-mind-a-brief-introduction-fundamentals-of-philosophy-searle-john-r'
	 is reduced to 617.
	"""

	d1, quickEditForm, qset, relatedDocuments, koncepts = None, None, None, None, None
	nodes, edges = [], []
	searchdict = {}
	PAGINATION_SET = 50
	MAX_RELATED_ITEMS = 7
	
	# try to extract the number ID
	try:
		pos = source_name.find("-")
		if pos > 0:
			source_id = int(source_name[:pos])
		else:
			source_id = int(source_name)
	except:
		raise Http404
	
	person = get_object_or_404(User, username=username)
	context = {'person' : person} # initialize context
	
	if request.user and request.user.is_authenticated() and person.username == request.user.username:
		context['mykoncepts'] = True
		usertags = [s.name for s in Subject.subjectsListPerUser(request.user)]
		if usertags:
			context['usertags'] = usertags
	else:
		context['mykoncepts'] = False
								
	try:
		page = int(request.GET.get('page', '1'))
	except ValueError:
		page = 1

	sort_snippets = request.GET.get('sort', 'words')
	if sort_snippets not in ['words', 'order',]: sort_snippets = 'words'	 # default 

	# compose search dictionary: 
	
	if context['mykoncepts']:
		searchdict['created_by'] = request.user
		# searchdict['name_url'] = url_encode(source_name)
		searchdict['id'] = source_id
	else:
		searchdict['created_by'] = person
		# searchdict['name_url'] = url_encode(source_name)
		searchdict['id'] = source_id
		
	try:
		d1 = Document.objects.filter(**searchdict).distinct()[0]
	except:		
		# return HttpResponseRedirect('/search/source/%s' % url_encode(source_name))  #always fallback to search
		raise Http404


	# get the objects to be displayed
	
	if context['mykoncepts']:

		quickEditForm = _prePopulateEditDocumentForm(d1)
		#temp: June 23, 2014
		snippets = Fragment.objects.filter(source=d1, created_by=person)
		
		if sort_snippets == "words":
			snippets_overview = sorted(snippets, key=lambda x: len(x.text.split()))
		else:
			snippets_overview = snippets
			
		if False:
			nodes, edges = getSourceQuotesGraph(d1)

	else:

		snippets = Fragment.objects.filter(source=d1, created_by=person, isprivate=False)
		snippets_overview = snippets

				
		# if the document has no public intfrags, then it is hidden
		if not snippets:
			raise Http404

	
	if False:
		# set up pagination == August 27, 2014: Removed
		paginator = Paginator(qset, PAGINATION_SET)			
		try:
			page_object = paginator.page(page)
		except (EmptyPage, InvalidPage):  # If page request is out of range, deliver last page of results.
			page_object = paginator.page(paginator.num_pages)
		page_object.extrastuff = paginator_helper(page, paginator.num_pages)
		page_object.totcount = paginator.count


	# printdebug(context['mykoncepts'])


	# finally...
	context.update({	  
				'd1' : d1,
				'page_flag' : 'document_detail', 
				# 'page_object' : page_object,
				'sort_snippets_var' : sort_snippets,
				'form' : quickEditForm ,
				'person' : person,
				'snippets': snippets,
				'snippets_overview': snippets_overview,
				# 'recentDocuments' : recentDocuments,
				'relatedDocuments' : relatedDocuments,
				'koncepts' :koncepts, 
				# 'nodes': simplejson.dumps(nodes),
				# 'edges': simplejson.dumps(edges),
				})
	
	return render_to_response(BOOTSTRAP + 'pages/document_detail.html', 
							context,
							context_instance=RequestContext(request))