def renderLinkField(request, wikidpageID, linkName, renderFormat=RENDER_HTML, futureLinks=[]) :
  
  debugOutput("linkName %s, futureLinks %s" % (linkName, futureLinks))
  
  nLinkField = wikidbase.core.normaliseTerm(linkName)
  
  wikidpage = pagestore.getWikidpage(wikidpageID)
  stateSource = wikidpage and (wikidpage.context or wikidpage.id) or None

  if wikidpage or futureLinks :
    try :
      links = pagestore.getLinks(wikidpage.id)[nLinkField]
    except :
      links = []
    # XXX: This next line is a bit wasteful.
    linkIDs = [link[0] for link in links]
    queryResults = query.QueryResults(futureLinks or [] + linkIDs)
  else :
    queryResults = None

  if renderFormat == RENDER_HTML :
    # Get a view from the user's state.
    queryResultsView = state.getItem(request, state.STATE_VIEW, stateSource, nLinkField)
    if not queryResultsView or dir(QuerySetView()) != dir(queryResultsView):
      queryResultsView = QuerySetView()
    queryResultsView.update(request)
    if stateSource :
      state.setItem(request, state.STATE_VIEW, stateSource, nLinkField, queryResultsView)
    
    renderedData = queryResultsView.render(queryResults, wikidpage, stateSource=stateSource, nLinkField=nLinkField)

  elif renderFormat == RENDER_CSV :
    renderedData = renderCSV(queryResults)

  return renderedData
def renderCommand(request, source, command, renderFormat = RENDER_HTML) :
  """Renders a wikidpage command: a query or a module function call."""
  debugOutput("Running command %s" % command)

  # See if the source will yield a wikidpage
  wikidpage = pagestore.getWikidpage(source)
  stateSource = wikidpage and (wikidpage.context or wikidpage.id) or source

  if ">>" in command and command.lower().strip().startswith("command") :
    result = wikidbase.core.module.runModuleCallString(request, command.split(">>")[1])
    return str(result)

  # Then try to run this as a query

  # Get a query set.
  wikidbase.core.performance.startTimer("runQuery")
  queryResults = query.runQuery(command)
  wikidbase.core.performance.stopTimer("runQuery")

  if renderFormat == RENDER_HTML :

    # Get a view from the user's state.
    wikidbase.core.performance.startTimer("get view from user state")
    queryResultsView = state.getItem(request, state.STATE_VIEW, stateSource, command)
    if not queryResultsView or dir(QuerySetView()) != dir(queryResultsView):
      queryResultsView = QuerySetView()
    queryResultsView.update(request)
    state.setItem(request, state.STATE_VIEW, stateSource, command, queryResultsView)
    wikidbase.core.performance.stopTimer("get view from user state")

    # Render the view.
    wikidbase.core.performance.startTimer("queryResultsView.render")
    renderedData = queryResultsView.render(queryResults, wikidpage=wikidpage, stateSource=stateSource, command=command)
    wikidbase.core.performance.stopTimer("queryResultsView.render")

  elif renderFormat == RENDER_CSV :
    renderedData = renderCSV(queryResults)

  return renderedData