Пример #1
0
 private String getContextId() {
   if (TestUtil.isRunningTests()) {
     return "test-context";
   }
   Placement placement = ToolManager.getCurrentPlacement();
   String presentSiteId = placement.getContext();
   return presentSiteId;
 }
Пример #2
0
  /**
   * Get the current site id
   *
   * @throws SessionDataException
   * @return Site id (GUID)
   */
  private String getSiteId() throws SessionDataException {
    Placement placement = ToolManager.getCurrentPlacement();

    if (placement == null) {
      throw new SessionDataException("No current tool placement");
    }
    return placement.getContext();
  }
  public void doEdit(RenderRequest request, RenderResponse response)
      throws PortletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = getTitleString(request);
    if (title != null) response.setTitle(title);

    Context context = new VelocityContext();
    context.put("tlang", rb);
    context.put("validator", validator);
    sendAlert(request, context);

    PortletURL url = response.createActionURL();
    context.put("actionUrl", url.toString());
    context.put("doCancel", "sakai.cancel");
    context.put("doUpdate", "sakai.update");

    // get current site
    Placement placement = ToolManager.getCurrentPlacement();
    String siteId = "";

    // find the right LTIContent object for this page
    String source = placement.getPlacementConfig().getProperty(SOURCE);
    Long key = getContentIdFromSource(source);
    if (key == null) {
      out.println(rb.getString("get.info.notconfig"));
      M_log.warn("Cannot find content id placement=" + placement.getId() + " source=" + source);
      return;
    }

    Map<String, Object> content = m_ltiService.getContent(key);
    if (content == null) {
      out.println(rb.getString("get.info.notconfig"));
      M_log.warn("Cannot find content item placement=" + placement.getId() + " key=" + key);
      return;
    }

    // attach the ltiToolId to each model attribute, so that we could have the tool configuration
    // page for multiple tools
    String foundLtiToolId = content.get(m_ltiService.LTI_TOOL_ID).toString();
    Map<String, Object> tool = m_ltiService.getTool(Long.valueOf(foundLtiToolId));
    if (tool == null) {
      out.println(rb.getString("get.info.notconfig"));
      M_log.warn("Cannot find tool placement=" + placement.getId() + " key=" + foundLtiToolId);
      return;
    }

    String[] contentToolModel = m_ltiService.getContentModel(Long.valueOf(foundLtiToolId));
    String formInput = m_ltiService.formInput(content, contentToolModel);
    context.put("formInput", formInput);

    vHelper.doTemplate(vengine, "/vm/edit.vm", context, out);
  }
Пример #4
0
  /**
   * Get the current site id
   *
   * @param state SessionState
   * @throws SessionDataException
   * @return Site id (GUID)
   */
  private String getSiteId(SessionState state) throws SessionDataException {
    // Check if it is state (i.e. we are a helper in site.info)
    String retval = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
    if (retval != null) return retval;

    // If it is not in state, we must be stand alone
    Placement placement = ToolManager.getCurrentPlacement();

    if (placement == null) {
      throw new SessionDataException("No current tool placement");
    }
    return placement.getContext();
  }
Пример #5
0
    public BaseResourceEdit(String id, SyllabusData data) {
      Placement placement = ToolManager.getCurrentPlacement();
      String currentSiteId = placement.getContext();

      m_id = id;

      m_data = data;

      m_reference = Entity.SEPARATOR + currentSiteId + Entity.SEPARATOR + m_id;

      m_properties = new BaseResourcePropertiesEdit();

      m_properties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, data.getTitle());
    }
  public boolean setTemporaryPlacement(Site site) {
    if (site == null) return false;

    Placement ppp = ToolManager.getCurrentPlacement();
    if (ppp != null && site.getId().equals(ppp.getContext())) {
      return true;
    }

    // Create a site-only placement
    Placement placement =
        new org.sakaiproject.util.Placement(
            "portal-temporary", /* toolId */
            null, /* tool */
            null,
            /* config */ null, /* context */
            site.getId(), /* title */
            null);

    ThreadLocalManager.set(CURRENT_PLACEMENT, placement);

    // Debugging
    ppp = ToolManager.getCurrentPlacement();
    if (ppp == null) {
      System.out.println("WARNING portal-temporary placement not set - null");
    } else {
      String cont = ppp.getContext();
      if (site.getId().equals(cont)) {
        return true;
      } else {
        System.out.println(
            "WARNING portal-temporary placement mismatch site="
                + site.getId()
                + " context="
                + cont);
      }
    }
    return false;
  }
  public void processActionEdit(ActionRequest request, ActionResponse response)
      throws PortletException, IOException {
    // TODO: Check Role

    // Stay in EDIT mode unless we are successful
    response.setPortletMode(PortletMode.EDIT);

    Placement placement = ToolManager.getCurrentPlacement();
    // get the site toolConfiguration, if this is part of a site.
    ToolConfiguration toolConfig = SiteService.findTool(placement.getId());
    String id = request.getParameter(LTIService.LTI_ID);
    String toolId = request.getParameter(LTIService.LTI_TOOL_ID);
    Properties reqProps = new Properties();
    Enumeration names = request.getParameterNames();
    while (names.hasMoreElements()) {
      String name = (String) names.nextElement();
      reqProps.setProperty(name, request.getParameter(name));
    }
    Object retval = m_ltiService.updateContent(Long.parseLong(id), reqProps);
    placement.save();

    response.setPortletMode(PortletMode.VIEW);
  }
Пример #8
0
  /*
   * public void setRelease(String release) { this.release = release; }
   *
   * public String getRelease() { return release; }
   */
  public ArrayList getGradebooks() {
    if (userId == null) {
      userId = SessionManager.getCurrentSessionUserId();

      if (userId != null) {
        try {
          userEid = UserDirectoryService.getUserEid(userId);
        } catch (UserNotDefinedException e) {
          LOG.error("UserNotDefinedException", e);
        }
      }
    }

    Placement placement = ToolManager.getCurrentPlacement();
    String currentSiteId = placement.getContext();

    siteId = currentSiteId;
    try {
      if (checkAccess()) {
        // logger.info("**** Getting by context!");
        gradebooks =
            new ArrayList(gradebookManager.getGradebooksByContext(siteId, sortBy, ascending));
      } else {
        // logger.info("**** Getting RELEASED by context!");
        gradebooks =
            new ArrayList(
                gradebookManager.getReleasedGradebooksByContext(siteId, sortBy, ascending));
      }
    } catch (Exception e) {
      gradebooks = null;
    }

    if (gradebooks != null && gradebooks.size() > 0) gradebooksExist = true;
    else gradebooksExist = false;

    return gradebooks;
  }
Пример #9
0
  // NOTE: This code is duplicated in SkinnableCharonPortal.java
  // make sure to change code both places
  protected void setupForward(
      HttpServletRequest req, HttpServletResponse res, Placement p, String skin)
      throws ToolException {
    // setup html information that the tool might need (skin, body on load,
    // js includes, etc).
    if (skin == null || skin.length() == 0)
      skin = ServerConfigurationService.getString("skin.default");
    String skinRepo = ServerConfigurationService.getString("skin.repo");
    String headCssToolBase =
        "<link href=\""
            + skinRepo
            + "/tool_base.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />\n";
    String headCssToolSkin =
        "<link href=\""
            + skinRepo
            + "/"
            + skin
            + "/tool.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />\n";
    String headCss = headCssToolBase + headCssToolSkin;
    String headJs =
        "<script type=\"text/javascript\" src=\"/library/js/headscripts.js\"></script>\n";
    String head = headCss + headJs;
    StringBuilder bodyonload = new StringBuilder();
    if (p != null) {
      String element = Web.escapeJavascript("Main" + p.getId());
      bodyonload.append("setMainFrameHeight('" + element + "');");
    }
    bodyonload.append("setFocus(focus_path);");

    req.setAttribute("sakai.html.head", head);
    req.setAttribute("sakai.html.head.css", headCss);
    req.setAttribute("sakai.html.head.css.base", headCssToolBase);
    req.setAttribute("sakai.html.head.css.skin", headCssToolSkin);
    req.setAttribute("sakai.html.head.js", headJs);
    req.setAttribute("sakai.html.body.onload", bodyonload.toString());
  }
Пример #10
0
  /** Populate the state with configuration settings */
  protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData rundata) {
    // TODO: we might want to keep this from running for each request - but by letting it we get
    // fresh info each time... -ggolden
    super.initState(state, portlet, rundata);

    Placement placement = ToolManager.getCurrentPlacement();
    Properties config = placement.getConfig();

    // set the pass_pid parameter
    boolean passPid = false;
    String passPidStr = config.getProperty(PASS_PID, "false");
    state.removeAttribute(PASS_PID);
    if ("true".equalsIgnoreCase(passPidStr)) {
      state.setAttribute(PASS_PID, Boolean.TRUE);
      passPid = true;
    }

    // Assume macro expansion (disable on request)
    boolean macroExpansion = true;
    String macroExpansionStr = config.getProperty(MACRO_EXPANSION, "true");

    state.removeAttribute(MACRO_EXPANSION);
    if ("false".equalsIgnoreCase(macroExpansionStr)) {
      state.setAttribute(MACRO_EXPANSION, Boolean.FALSE);
      macroExpansion = false;
    }

    // set the special setting
    String special = config.getProperty(SPECIAL);

    final String sakaiPropertiesUrlKey = config.getProperty(SAKAI_PROPERTIES_URL_KEY);

    final String hideOptions = config.getProperty(HIDE_OPTIONS);

    // check for an older way the ChefWebPagePortlet took parameters, converting to our "special"
    // values
    if (special == null) {
      if ("true".equals(config.getProperty("site"))) {
        special = SPECIAL_SITE;
      } else if ("true".equals(config.getProperty("workspace"))) {
        special = SPECIAL_WORKSPACE;
      } else if ("true".equals(config.getProperty("worksite"))) {
        special = SPECIAL_WORKSITE;
      } else if ("true".equals(config.getProperty("annotatedurl"))) {
        special = SPECIAL_ANNOTATEDURL;
      }
    }

    state.removeAttribute(SPECIAL);
    if ((special != null) && (special.trim().length() > 0)) {
      state.setAttribute(SPECIAL, special);
    }

    state.removeAttribute(HIDE_OPTIONS);
    if ((hideOptions != null) && (hideOptions.trim().length() > 0)) {
      state.setAttribute(HIDE_OPTIONS, hideOptions);
    }

    // set the source url setting
    String source = StringUtils.trimToNull(config.getProperty(SOURCE));

    // check for an older way the ChefWebPagePortlet took parameters, converting to our "source"
    // value
    if (source == null) {
      source = StringUtils.trimToNull(config.getProperty("url"));
    }

    // store the raw as-configured source url
    state.removeAttribute(SOURCE);
    if (source != null) {
      state.setAttribute(SOURCE, source);
    }

    // compute working URL, modified from the configuration URL if special
    String url =
        sourceUrl(
            special,
            source,
            placement.getContext(),
            macroExpansion,
            passPid,
            placement.getId(),
            sakaiPropertiesUrlKey);
    state.setAttribute(URL, url);

    // set the height
    state.setAttribute(HEIGHT, config.getProperty(HEIGHT, "600px"));

    state.setAttribute(ANNOTATED_TEXT, config.getProperty(ANNOTATED_TEXT, ""));

    if (config.getProperty(TARGETPAGE_URL) != null) {
      // set Target page url for Annotated URL Tool
      state.setAttribute(TARGETPAGE_URL, config.getProperty(TARGETPAGE_URL));

      // set Target page name for Annotated URL Tool
      state.setAttribute(TARGETPAGE_NAME, config.getProperty(TARGETPAGE_NAME));
    }

    // set the title
    state.setAttribute(TITLE, placement.getTitle());

    if (state.getAttribute(STATE_PAGE_TITLE) == null) {
      SitePage p = SiteService.findPage(getCurrentSitePageId());
      state.setAttribute(STATE_PAGE_TITLE, p.getTitle());
    }

    // if events found in tool registration file put them in state
    if ((StringUtils.trimToNull(config.getProperty(EVENT_ACCESS_WEB_CONTENT)) != null)) {
      state.setAttribute(EVENT_ACCESS_WEB_CONTENT, config.getProperty(EVENT_ACCESS_WEB_CONTENT));
    }
    if ((StringUtils.trimToNull(config.getProperty(EVENT_REVISE_WEB_CONTENT)) != null)) {
      state.setAttribute(EVENT_REVISE_WEB_CONTENT, config.getProperty(EVENT_REVISE_WEB_CONTENT));
    }

    if (m_eventTrackingService == null) {
      m_eventTrackingService =
          (EventTrackingService)
              ComponentManager.get("org.sakaiproject.event.api.EventTrackingService");
    }
  }
Пример #11
0
 private String getCurrentSiteId() {
   Placement placement = ToolManager.getCurrentPlacement();
   return placement.getContext();
 }
Пример #12
0
  /** Setup the velocity context and choose the template for options. */
  public String buildOptionsPanelContext(
      VelocityPortlet portlet, Context context, RunData data, SessionState state) {
    // provide the source, and let the user edit, if not special
    String special = (String) state.getAttribute(SPECIAL);
    String source = "";
    String siteId = "";
    if (special == null) {
      source = (String) state.getAttribute(SOURCE);
      if (source == null) source = "";
      context.put(SOURCE, source);
      context.put("heading", rb.getString("gen.custom"));
    }

    // set the heading based on special
    else {
      if (SPECIAL_SITE.equals(special)) {
        context.put("heading", rb.getString("gen.custom.site"));
      } else if (SPECIAL_WORKSPACE.equals(special)) {
        context.put("heading", rb.getString("gen.custom.workspace"));
      } else if (SPECIAL_WORKSITE.equals(special)) {
        context.put("heading", rb.getString("gen.custom.worksite"));

        // for worksite, also include the Site's infourl and description
        try {
          Site s = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
          siteId = s.getId();

          String infoUrl = StringUtils.trimToNull(s.getInfoUrl());
          if (infoUrl != null) {
            context.put("info_url", infoUrl);
          }

          String description = StringUtils.trimToNull(s.getDescription());
          if (description != null) {
            description = FormattedText.escapeHtmlFormattedTextarea(description);
            context.put("description", description);
          }
        } catch (Throwable e) {
        }
      } else if (SPECIAL_ANNOTATEDURL.equals(special)) {

        context.put("heading", rb.getString("gen.custom.annotatedurl"));

        // for Annotated URL Tool page, also include the description
        try {
          String desp = state.getAttribute(ANNOTATED_TEXT).toString();
          context.put("description", desp);

        } catch (Throwable e) {
        }
      } else {
        context.put("heading", rb.getString("gen.custom"));
      }
    }

    boolean selected = false;
    String height = state.getAttribute(HEIGHT).toString();
    for (int i = 0; i < ourPixels.length; i++) {
      if (height.equals(ourPixels[i])) {
        selected = true;
        continue;
      }
    }
    if (!selected) {
      String[] strings = height.trim().split("px");
      context.put("custom_height", strings[0]);
      height = rb.getString("gen.heisomelse");
    }
    context.put(HEIGHT, height);

    context.put(TITLE, state.getAttribute(TITLE));
    context.put("tlang", rb);

    context.put("doUpdate", BUTTON + "doConfigure_update");
    context.put("doCancel", BUTTON + "doCancel");

    context.put("form_tool_title", FORM_TOOL_TITLE);
    context.put("form_page_title", FORM_PAGE_TITLE);

    // if we are part of a site, and the only tool on the page, offer the popup to edit
    Placement placement = ToolManager.getCurrentPlacement();
    ToolConfiguration toolConfig = SiteService.findTool(placement.getId());
    if ((state.getAttribute(SPECIAL) == null) && (toolConfig != null)) {
      try {
        Site site = SiteService.getSite(toolConfig.getSiteId());
        siteId = site.getId();
        SitePage page = site.getPage(toolConfig.getPageId());

        // if this is the only tool on that page, update the page's title also
        if ((page.getTools() != null) && (page.getTools().size() == 1)) {
          context.put("showPopup", Boolean.TRUE);
          context.put("popup", Boolean.valueOf(page.isPopUp()));

          context.put("pageTitleEditable", Boolean.TRUE);
          context.put("page_title", (String) state.getAttribute(STATE_PAGE_TITLE));
        }
      } catch (Throwable e) {
      }
    }

    // pick the "-customize" template based on the standard template name
    String template = (String) getContext(data).get("template");

    // pick the site customize template if we are in that mode
    if (SPECIAL_WORKSITE.equals(special)) {
      template = template + "-site-customize";
    } else if (SPECIAL_WORKSPACE.equals(special)) {
      template = template + "-customize";
    } else if (SPECIAL_ANNOTATEDURL.equals(special)) {
      template = template + "-annotatedurl-customize";
    } else {
      template = template + "-customize";
    }

    // tracking event
    if (siteId.length() == 0) {
      try {
        Site s = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
        siteId = s.getId();
      } catch (Throwable e) {

      }
    }
    if (special == null) {
      if (state.getAttribute(EVENT_REVISE_WEB_CONTENT) == null) {

        // this is a Web Content tool
        m_eventTrackingService.post(
            m_eventTrackingService.newEvent(
                EVENT_REVISE_WEB_CONTENT, source, siteId, true, NotificationService.NOTI_NONE));
      } else {
        // event in tool registration file will be used
        m_eventTrackingService.post(
            m_eventTrackingService.newEvent(
                (String) state.getAttribute(EVENT_REVISE_WEB_CONTENT),
                source,
                siteId,
                true,
                NotificationService.NOTI_NONE));
      }
    } else {
      if (state.getAttribute(EVENT_REVISE_WEB_CONTENT) != null) {
        // special and event in tool registration file
        m_eventTrackingService.post(
            m_eventTrackingService.newEvent(
                (String) state.getAttribute(EVENT_REVISE_WEB_CONTENT),
                source,
                siteId,
                true,
                NotificationService.NOTI_NONE));
      }
    }

    // output the max limit
    context.put("max_length_title", MAX_TITLE_LENGTH);
    context.put("max_length_info_url", MAX_SITE_INFO_URL_LENGTH);

    return template;
  }
Пример #13
0
  /** Handle the configure context's update button */
  public void doConfigure_update(RunData data, Context context) {
    // TODO: if we do limit the initState() calls, we need to make sure we get a new one after this
    // call -ggolden

    String peid = ((JetspeedRunData) data).getJs_peid();
    SessionState state = ((JetspeedRunData) data).getPortletSessionState(peid);

    Placement placement = ToolManager.getCurrentPlacement();

    // get the site toolConfiguration, if this is part of a site.
    ToolConfiguration toolConfig = SiteService.findTool(placement.getId());

    // height
    String height = data.getParameters().getString(HEIGHT);
    if (height.equals(rb.getString("gen.heisomelse"))) {
      String customHeight = data.getParameters().getString(CUSTOM_HEIGHT);
      if ((customHeight != null) && (!customHeight.equals(""))) {
        if (!checkDigits(customHeight)) {
          addAlert(state, rb.getString("java.alert.pleentval"));
          return;
        }
        state.setAttribute(HEIGHT, customHeight);
        height = customHeight + "px";
        state.setAttribute(HEIGHT, height);
        placement.getPlacementConfig().setProperty(HEIGHT, height);
      } else {
        addAlert(state, rb.getString("java.alert.pleentval"));
        return;
      }
    } else if (SPECIAL_ANNOTATEDURL.equals(state.getAttribute(SPECIAL))) {
      // update the site info
      try {
        String desp = data.getParameters().getString("description");
        state.setAttribute(ANNOTATED_TEXT, desp);
        placement.getPlacementConfig().setProperty(ANNOTATED_TEXT, desp);

      } catch (Throwable e) {
      }
    } else {
      state.setAttribute(HEIGHT, height);
      placement.getPlacementConfig().setProperty(HEIGHT, height);
    }

    // title
    String title = data.getParameters().getString(TITLE);
    if (StringUtils.isBlank(title)) {
      addAlert(state, rb.getString("gen.tootit.empty"));
      return;
      // SAK-19515 check for LENGTH of tool title
    } else if (title.length() > MAX_TITLE_LENGTH) {
      addAlert(state, rb.getString("gen.tootit.toolong"));
      return;
    }
    placement.setTitle(title);

    // site info url
    String infoUrl = StringUtils.trimToNull(data.getParameters().getString("infourl"));
    if (infoUrl != null && infoUrl.length() > MAX_SITE_INFO_URL_LENGTH) {
      addAlert(state, rb.getString("gen.info.url.toolong"));
      return;
    }

    try {
      Site site = SiteService.getSite(toolConfig.getSiteId());
      SitePage page = site.getPage(toolConfig.getPageId());
      page.setTitleCustom(true);

      // for web content tool, if it is a site page tool, and the only tool on the page, update the
      // page title / popup.
      if ((state.getAttribute(SPECIAL) == null) && (toolConfig != null)) {
        // if this is the only tool on that page, update the page's title also
        if ((page.getTools() != null) && (page.getTools().size() == 1)) {
          String newPageTitle = data.getParameters().getString(FORM_PAGE_TITLE);

          if (StringUtils.isBlank(newPageTitle)) {
            addAlert(state, rb.getString("gen.pagtit.empty"));
            return;
          } else if (newPageTitle.length() > MAX_TITLE_LENGTH) {
            addAlert(state, rb.getString("gen.pagtit.toolong"));
            return;
          }
          page.setTitle(newPageTitle);
          state.setAttribute(STATE_PAGE_TITLE, newPageTitle);

          // popup
          boolean popup = data.getParameters().getBoolean("popup");
          page.setPopup(popup);
        }
      }

      SiteService.save(site);
    } catch (Exception ignore) {
      M_log.warn("doConfigure_update: " + ignore);
    }

    // read source if we are not special
    if (state.getAttribute(SPECIAL) == null) {
      String source = StringUtils.trimToEmpty(data.getParameters().getString(SOURCE));

      // User entered nothing in the source box; give the user an alert
      if (StringUtils.isBlank(source)) {
        addAlert(state, rb.getString("gen.url.empty"));
        return;
      }

      if ((!source.startsWith("/")) && (source.indexOf("://") == -1)) {
        source = "http://" + source;
      }

      // Validate the url
      UrlValidator urlValidator = new UrlValidator();
      if (!urlValidator.isValid(source)) {
        addAlert(state, rb.getString("gen.url.invalid"));
        return;
      }

      // update state
      placement.getPlacementConfig().setProperty(SOURCE, source);
    } else if (SPECIAL_WORKSITE.equals(state.getAttribute(SPECIAL))) {
      if ((infoUrl != null)
          && (infoUrl.length() > 0)
          && (!infoUrl.startsWith("/"))
          && (infoUrl.indexOf("://") == -1)) {
        infoUrl = "http://" + infoUrl;
      }
      String description = StringUtils.trimToNull(data.getParameters().getString("description"));
      description = FormattedText.processEscapedHtml(description);

      // update the site info
      try {
        SiteService.saveSiteInfo(
            ToolManager.getCurrentPlacement().getContext(), description, infoUrl);
      } catch (Throwable e) {
        M_log.warn("doConfigure_update: " + e);
      }
    }

    // save
    // TODO: we might have just saved the entire site, so this would not be needed -ggolden
    placement.save();

    // we are done with customization... back to the main mode
    state.removeAttribute(STATE_MODE);

    // refresh the whole page, since popup and title may have changed
    scheduleTopRefresh();
  }
Пример #14
0
 protected Properties extractPropertiesFromTool() {
   Placement placement = toolManager.getCurrentPlacement();
   Properties props = placement.getPlacementConfig();
   if (props.isEmpty()) props = placement.getConfig();
   return props;
 }
  // Render the portlet - this is not supposed to change the state of the portlet
  // Render may be called many times so if it changes the state - that is tacky
  // Render will be called when someone presses "refresh" or when another portlet
  // onthe same page is handed an Action.
  public void doView(RenderRequest request, RenderResponse response)
      throws PortletException, IOException {
    response.setContentType("text/html");

    // System.out.println("==== doView called ====");

    // Grab that underlying request to get a GET parameter
    ServletRequest req = (ServletRequest) ThreadLocalManager.get(CURRENT_HTTP_REQUEST);
    String popupDone = req.getParameter("sakai.popup");

    PrintWriter out = response.getWriter();
    Placement placement = ToolManager.getCurrentPlacement();
    response.setTitle(placement.getTitle());
    String source = placement.getPlacementConfig().getProperty(SOURCE);
    if (source == null) source = "";
    String height = placement.getPlacementConfig().getProperty(HEIGHT);
    if (height == null) height = "1200px";
    boolean maximize = "true".equals(placement.getPlacementConfig().getProperty(MAXIMIZE));

    boolean popup = false; // Comes from content item
    boolean oldPopup = "true".equals(placement.getPlacementConfig().getProperty(POPUP));

    // Retrieve the corresponding content item and tool to check the launch
    Map<String, Object> content = null;
    Map<String, Object> tool = null;
    Long key = getContentIdFromSource(source);
    if (key == null) {
      out.println(rb.getString("get.info.notconfig"));
      M_log.warn("Cannot find content id placement=" + placement.getId() + " source=" + source);
      return;
    }
    try {
      content = m_ltiService.getContent(key);
      // If we are supposed to popup (per the content), do so and optionally
      // copy the calue into the placement to communicate with the portal
      popup = getLongNull(content.get("newpage")) == 1;
      if (oldPopup != popup) {
        placement.getPlacementConfig().setProperty(POPUP, popup ? "true" : "false");
        placement.save();
      }
      String launch = (String) content.get("launch");
      Long tool_id = getLongNull(content.get("tool_id"));
      if (launch == null && tool_id != null) {
        tool = m_ltiService.getTool(tool_id);
        launch = (String) tool.get("launch");
      }

      // Force http:// to pop-up if we are https://
      String serverUrl = ServerConfigurationService.getServerUrl();
      if (request.isSecure() || (serverUrl != null && serverUrl.startsWith("https://"))) {
        if (launch != null && launch.startsWith("http://")) popup = true;
      }
    } catch (Exception e) {
      out.println(rb.getString("get.info.notconfig"));
      e.printStackTrace();
      return;
    }

    if (source != null && source.trim().length() > 0) {

      Context context = new VelocityContext();
      context.put("tlang", rb);
      context.put("validator", validator);
      context.put("source", source);
      context.put("height", height);
      sendAlert(request, context);
      context.put("popupdone", Boolean.valueOf(popupDone != null));
      context.put("popup", Boolean.valueOf(popup));
      context.put("maximize", Boolean.valueOf(maximize));

      vHelper.doTemplate(vengine, "/vm/main.vm", context, out);
    } else {
      out.println(rb.getString("get.info.notconfig"));
    }

    // System.out.println("==== doView complete ====");
  }
 // If the property is final, the property wins.  If it is not final,
 // the portlet preferences take precedence.
 public String getTitleString(RenderRequest request) {
   Placement placement = ToolManager.getCurrentPlacement();
   return placement.getTitle();
 }
  public void fillComponents(
      UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
    ViewSubmissionsViewParams params = (ViewSubmissionsViewParams) viewparams;
    // make sure that we have an AssignmentID to work with
    if (params.assignmentId == null) {
      // ERROR SHOULD BE SET, OTHERWISE TAKE BACK TO ASSIGNMENT_LIST
      messages.addMessage(new TargettedMessage("GeneralActionError"));
      return;
    }
    assignmentId = params.assignmentId;
    Assignment2 assignment = assignmentLogic.getAssignmentByIdWithAssociatedData(assignmentId);

    String currUserId = externalLogic.getCurrentUserId();

    boolean contentReviewEnabled =
        assignment.isContentReviewEnabled()
            && contentReviewLogic.isContentReviewAvailable(assignment.getContextId());

    // let's double check that none of the associated groups were deleted from the site
    boolean displayGroupDeletionWarning = false;
    if (assignment.getAssignmentGroupSet() != null
        && !assignment.getAssignmentGroupSet().isEmpty()) {
      Collection<Group> siteGroups = externalLogic.getSiteGroups(assignment.getContextId());
      List<String> groupIds = new ArrayList<String>();
      if (siteGroups != null) {
        for (Group group : siteGroups) {
          groupIds.add(group.getId());
        }
      }

      for (AssignmentGroup assignGroup : assignment.getAssignmentGroupSet()) {
        if (!groupIds.contains(assignGroup.getGroupId())) {
          displayGroupDeletionWarning = true;
          break;
        }
      }
    }

    if (displayGroupDeletionWarning) {
      UIOutput.make(
          tofill,
          "deleted_group",
          messageLocator.getMessage("assignment2.assignment_grade-assignment.group_deleted"));
    }

    // Edit Permission
    boolean userMayEditAssign =
        permissionLogic.isUserAllowedToEditAssignment(currUserId, assignment);
    boolean userMayManageSubmissions =
        permissionLogic.isUserAllowedToManageSubmissionsForAssignment(currUserId, assignment);

    // get parameters
    if (params.sort_by == null) params.sort_by = DEFAULT_SORT_BY;
    if (params.sort_dir == null) params.sort_dir = DEFAULT_SORT_DIR;

    UIVerbatim.make(
        tofill, "defaultSortBy", HTMLUtil.emitJavascriptVar("defaultSortBy", DEFAULT_SORT_BY));

    // we need to retrieve the history for the release/retract feedback logic
    List<AssignmentSubmission> submissions =
        submissionLogic.getViewableSubmissionsWithHistoryForAssignmentId(
            assignmentId, params.groupId);
    List<String> studentIdList = new ArrayList<String>();
    if (submissions != null) {
      for (AssignmentSubmission submission : submissions) {
        studentIdList.add(submission.getUserId());
      }
    }

    // The following is some code to populate the sort order/page size, if
    // it's already been put in session state by the entity provider.
    Long pagesize = null;
    String orderBy = null;
    Boolean ascending = null;
    ToolSession toolSession = sessionManager.getCurrentToolSession();
    if (toolSession.getAttribute(Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR)
        != null) {
      Map attr =
          (Map)
              toolSession.getAttribute(
                  Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR);
      if (attr.containsKey(
          Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_PAGE_SIZE)) {
        pagesize =
            (Long)
                attr.get(Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_PAGE_SIZE);
      }
      if (attr.containsKey(
          Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_ORDER_BY)) {
        orderBy =
            (String)
                attr.get(Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_ORDER_BY);
      }
      if (attr.containsKey(
          Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_ASCENDING)) {
        ascending =
            (Boolean)
                attr.get(Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_ASCENDING);
      }
    }

    // if assign is graded, retrieve the gb details, if appropriate
    GradebookItem gbItem = null;
    boolean gbItemExists = false;
    boolean gradesReleased = false;
    // user may view the associated gradebook item
    boolean userMayViewGbItem = false;
    // user has grading privileges for this gb item
    boolean userMayGrade = false;
    boolean userMayReleaseGrades = false;

    if (assignment.isGraded() && assignment.getGradebookItemId() != null) {
      userMayViewGbItem =
          gradebookLogic.isCurrentUserAbleToViewGradebookItem(
              assignment.getContextId(), assignment.getGradebookItemId());

      if (userMayViewGbItem) {
        // user may grade if there is at least one gradable student among the submissions
        List<String> gradableStudents =
            gradebookLogic.getFilteredStudentsForGradebookItem(
                currUserId,
                assignment.getContextId(),
                assignment.getGradebookItemId(),
                AssignmentConstants.GRADE,
                studentIdList);
        userMayGrade = gradableStudents != null && !gradableStudents.isEmpty();
        userMayReleaseGrades = gradebookLogic.isCurrentUserAbleToEdit(assignment.getContextId());

        try {
          gbItem =
              gradebookLogic.getGradebookItemById(
                  assignment.getContextId(), assignment.getGradebookItemId());
          gbItemExists = true;
          gradesReleased = gbItem.isReleased();
        } catch (GradebookItemNotFoundException ginfe) {
          if (log.isDebugEnabled())
            log.debug("Gb item with id: " + assignment.getGradebookItemId() + " no longer exists!");
          gbItem = null;
        }
      }
    }

    // if user has grading privileges but item no longer exists, display warning
    // to user
    if (assignment.isGraded() && userMayViewGbItem && !gbItemExists) {
      UIOutput.make(
          tofill,
          "no_gb_item",
          messageLocator.getMessage("assignment2.assignment_grade-assignment.gb_item_deleted"));
    }

    // We need to check if it's a non electronic submission.  If it is, we don't want to have
    // the submitted columns appear (Submitted and Submission Status).
    // We pass in the boolean parameter nonElectronicSubmission to viewSubmission.js (specifically
    // snn2subview.init()),
    // where logic is there to use this parameter.
    boolean nonElectronicSubmission = false;

    if (assignment.getSubmissionType() == AssignmentConstants.SUBMIT_NON_ELECTRONIC) {
      nonElectronicSubmission = true;
    }

    UIInitBlock.make(
        tofill,
        "asnn2subview-init",
        "asnn2subview.init",
        new Object[] {
          assignmentId,
          externalLogic.getCurrentContextId(),
          placement.getId(),
          submissions.size(),
          assignment.isGraded(),
          contentReviewEnabled,
          nonElectronicSubmission,
          pagesize,
          orderBy,
          ascending,
          gradesReleased,
          params.pageIndex
        });

    // Breadcrumbs
    UIInternalLink.make(
        tofill,
        "breadcrumb",
        messageLocator.getMessage("assignment2.assignment_list-sortview.heading"),
        new SimpleViewParameters(ListProducer.VIEW_ID));
    UIMessage.make(
        tofill,
        "last_breadcrumb",
        "assignment2.assignment_grade-assignment.heading",
        new Object[] {assignment.getTitle()});

    // ACTION BAR
    boolean displayReleaseGrades = false;
    boolean displayReleaseFB = false;
    boolean displayDownloadAll = false;
    boolean displayUploadAll = false;

    if (userMayEditAssign || userMayManageSubmissions) {
      UIOutput.make(tofill, "navIntraTool");
    }

    // RELEASE GRADES
    // don't display this option if the gb item doesn't exist anymore
    if (userMayReleaseGrades && assignment.isGraded() && gbItemExists) {
      displayReleaseGrades = true;

      // determine if grades have been released yet
      String releaseLinkText =
          messageLocator.getMessage("assignment2.assignment_grade-assignment.grades.release");
      if (gradesReleased) {
        releaseLinkText =
            messageLocator.getMessage("assignment2.assignment_grade-assignment.grades.retract");
      }

      UIForm releaseGradesForm = UIForm.make(tofill, "release_grades_form");
      UICommand releaseGradesButton = UICommand.make(releaseGradesForm, "release_grades");

      UIOutput.make(tofill, "release_grades_li");
      UIInternalLink releaseGradesLink =
          UIInternalLink.make(tofill, "release_grades_link", releaseLinkText, viewparams);
      Map<String, String> idmap = new HashMap<String, String>();
      idmap.put(
          "onclick",
          "asnn2.releaseGradesDialog('"
              + releaseGradesButton.getFullID()
              + "', '"
              + assignment.getContextId()
              + "', '"
              + assignment.getGradebookItemId()
              + "', '"
              + !gradesReleased
              + "'); return false;");
      releaseGradesLink.decorate(new UIFreeAttributeDecorator(idmap));

      makeReleaseGradesDialog(gradesReleased, assignment, tofill);
    }

    // RELEASE FEEDBACK
    if (userMayManageSubmissions) {
      displayReleaseFB = true;
      makeReleaseFeedbackLink(tofill, params, submissions);
    }

    // DOWNLOAD ALL
    if (userMayManageSubmissions) {
      displayDownloadAll = true;

      ZipViewParams zvp = new ZipViewParams("zipSubmissions", assignmentId);
      UIInternalLink.make(
          tofill,
          "downloadall",
          UIMessage.make("assignment2.assignment_grade-assignment.downloadall.button"),
          zvp);
    }

    // UPLOAD GRADES & FEEDBACK
    if (userMayManageSubmissions) {
      displayUploadAll = true;

      AssignmentViewParams avp = new AssignmentViewParams("uploadall", assignmentId);
      if (assignment.isGraded() && gbItemExists && userMayGrade) {
        UIInternalLink.make(
            tofill,
            "uploadall",
            UIMessage.make("assignment2.uploadall.breadcrumb.upload.graded"),
            avp);
      } else {
        UIInternalLink.make(
            tofill,
            "uploadall",
            UIMessage.make("assignment2.uploadall.breadcrumb.upload.ungraded"),
            avp);
      }
    }

    // handle those pesky separators
    if (displayReleaseGrades && (displayReleaseFB || displayUploadAll || displayDownloadAll)) {
      UIOutput.make(tofill, "release_grades_sep");
    }

    if (displayReleaseFB && (displayUploadAll || displayDownloadAll)) {
      UIOutput.make(tofill, "release_feedback_sep");
    }

    if (displayDownloadAll && displayUploadAll) {
      UIOutput.make(tofill, "downloadall_sep");
    }

    UIMessage.make(tofill, "page-title", "assignment2.assignment_grade-assignment.title");

    // now make the "View By Sections/Groups" filter
    makeViewByGroupFilter(tofill, params, assignment);

    /*
     * Form for assigning a grade to all submissions without a grade.
     * Do not allow grading if gbItem is null - it must have been deleted
     */
    if (submissions != null
        && !submissions.isEmpty()
        && userMayGrade
        && assignment.isGraded()
        && gbItemExists) {
      createApplyToUngradedWidget(assignment, tofill, params, "unassigned-apply-form0:");
      createApplyToUngradedWidget(assignment, tofill, params, "unassigned-apply-form1:");
    }

    // Confirmation Dialogs
    // These are only added here for internationalization. They are not part
    // of a real form.
    UICommand.make(
        tofill,
        "release-feedback-confirm",
        UIMessage.make("assignment2.dialogs.release_all_feedback.confirm"));
    UICommand.make(
        tofill,
        "release-feedback-cancel",
        UIMessage.make("assignment2.dialogs.release_all_feedback.cancel"));

    UICommand.make(
        tofill,
        "retract-feedback-confirm",
        UIMessage.make("assignment2.dialogs.retract_all_feedback.confirm"));
    UICommand.make(
        tofill,
        "retract-feedback-cancel",
        UIMessage.make("assignment2.dialogs.retract_all_feedback.cancel"));
  }
Пример #18
0
 public ToolConfigBean(Placement currentPlacement, String defaultHomePageName) {
   m_properties = currentPlacement.getConfig();
   this.defaultHomePageName = defaultHomePageName;
 }