Exemplo n.º 1
0
 /**
  * org.olat.lms.course.run.userview.UserCourseEnvironment,
  * org.olat.lms.course.run.userview.NodeEvaluation)
  */
 @Override
 public Controller createPeekViewRunController(
     final UserRequest ureq,
     final WindowControl wControl,
     final UserCourseEnvironment userCourseEnv,
     final NodeEvaluation ne) {
   if (ne.isAtLeastOneAccessible()) {
     // Create a feed peekview controller that shows the latest two entries
     final RepositoryEntry entry = getReferencedRepositoryEntry();
     final Long courseId = userCourseEnv.getCourseEnvironment().getCourseResourceableId();
     final String nodeId = this.getIdent();
     final boolean isAdmin = ureq.getUserSession().getRoles().isOLATAdmin();
     final boolean isGuest = ureq.getUserSession().getRoles().isGuestOnly();
     final SubscriptionContext subscriptionContext =
         CourseModule.createSubscriptionContext(userCourseEnv.getCourseEnvironment(), this);
     final FeedSecurityCallback callback =
         new FeedNodeSecurityCallback(ne, isAdmin, isGuest, subscriptionContext);
     final FeedUIFactory uiFactory = BlogUIFactory.getInstance(ureq.getLocale());
     final Controller peekViewController =
         new FeedPeekviewController(
             entry.getOlatResource(),
             ureq,
             wControl,
             callback,
             courseId,
             nodeId,
             uiFactory,
             2,
             "o_blog_peekview");
     return peekViewController;
   } else {
     // use standard peekview
     return super.createPeekViewRunController(ureq, wControl, userCourseEnv, ne);
   }
 }
Exemplo n.º 2
0
 /**
  * org.olat.lms.course.run.userview.UserCourseEnvironment,
  * org.olat.lms.course.run.userview.NodeEvaluation, java.lang.String)
  */
 @Override
 public NodeRunConstructionResult createNodeRunConstructionResult(
     final UserRequest ureq,
     final WindowControl wControl,
     final UserCourseEnvironment userCourseEnv,
     final NodeEvaluation ne,
     final String nodecmd) {
   final RepositoryEntry entry = getReferencedRepositoryEntry();
   // create business path courseID:nodeID
   // userCourseEnv.getCourseEnvironment().getCourseResourceableId();
   // getIdent();
   final Long courseId = userCourseEnv.getCourseEnvironment().getCourseResourceableId();
   final String nodeId = this.getIdent();
   final boolean isAdmin = ureq.getUserSession().getRoles().isOLATAdmin();
   final boolean isGuest = ureq.getUserSession().getRoles().isGuestOnly();
   final SubscriptionContext subscriptionContext =
       CourseModule.createSubscriptionContext(userCourseEnv.getCourseEnvironment(), this);
   final FeedSecurityCallback callback =
       new FeedNodeSecurityCallback(ne, isAdmin, isGuest, subscriptionContext);
   ThreadLocalUserActivityLogger.addLoggingResourceInfo(LoggingResourceable.wrap(this));
   final FeedMainController blogCtr =
       BlogUIFactory.getInstance(ureq.getLocale())
           .createMainController(
               entry.getOlatResource(), ureq, wControl, callback, courseId, nodeId);
   blogCtr.activate(ureq, nodecmd);
   final Controller wrapperCtrl =
       TitledWrapperHelper.getWrapper(ureq, wControl, blogCtr, this, "o_blog_icon");
   final NodeRunConstructionResult result = new NodeRunConstructionResult(wrapperCtrl);
   return result;
 }
Exemplo n.º 3
0
 @Override
 public SiteInstance createSite(final UserRequest ureq, final WindowControl wControl) {
   SiteInstance si = null;
   if (ureq.getUserSession().getRoles().isUserManager()) {
     // only open for olat-usermanagers
     si = new UserAdminSite(ureq.getLocale());
   }
   return si;
 }
  /**
   * @param ureq
   * @param subscriptionContext
   * @param publisherData
   */
  public ContextualSubscriptionController(
      UserRequest ureq,
      WindowControl wControl,
      SubscriptionContext subscriptionContext,
      PublisherData publisherData) {
    super(ureq, wControl);
    this.subscriptionContext = subscriptionContext;
    this.publisherData = publisherData;
    isNewNotificationService = useNewNotificationService(publisherData);

    myContent = createVelocityContainer("consubs");

    if (subscriptionContext == null) {
      setInitialComponent(new Panel("empty:nosubscription"));
      return;
    }

    detailsPanel = new Panel("subscription_detail");
    allPanel = new Panel("subscription_all");

    subscribeButton = LinkFactory.createButtonSmall("command.subscribe", myContent, this);
    // subscribeButton.setCustomEnabledLinkCSS("b_noti_subscribe_link");

    this.unsubscribeButton = LinkFactory.createButtonSmall("command.unsubscribe", myContent, this);
    // unsubscribeButton.setCustomEnabledLinkCSS("b_noti_unsubscribe_link");

    if (isNewNotificationService) {
      log.info(
          "Notification-Service: " + publisherData.getType() + " is running with NEW notification");
      newNotificationService = getService(LearnServices.notificationLearnService);
      subscriptionContext.setContextId(
          getRepositoryService()
              .getRepositoryEntryIdFromResourceable(
                  subscriptionContext.getResId(),
                  subscriptionContext.getResName())); // TODO: LD: move this at construction of
      // subscriptionContext
      newSubscriptionContext =
          newNotificationService.createNotificationSubscriptionContext(
              ureq.getIdentity(), subscriptionContext, publisherData);
      isSubscribed = newNotificationService.isSubscribed(newSubscriptionContext);
    } else {
      log.info(
          "Notification-Service: "
              + publisherData.getType()
              + " is running with LEGACY notification");
      notifManager = getNotificationService();
      // if subscribed, offer a unsubscribe button and vica versa.
      isSubscribed = notifManager.isSubscribed(ureq.getIdentity(), subscriptionContext);
    }

    updateUI();
    myContent.put("detailsPanel", detailsPanel);
    allPanel.setContent(myContent);
    putInitialPanel(allPanel);
  }
Exemplo n.º 5
0
  /**
   * Constructor for a test run controller
   *
   * @param userCourseEnv
   * @param moduleConfiguration
   * @param secCallback
   * @param ureq
   * @param wControl
   * @param testCourseNode
   */
  IQRunController(
      final UserCourseEnvironment userCourseEnv,
      final ModuleConfiguration moduleConfiguration,
      final IQSecurityCallback secCallback,
      final UserRequest ureq,
      final WindowControl wControl,
      final IQTESTCourseNode testCourseNode,
      final AssessmentNotificationsHandler notificationHandler) {
    super(ureq, wControl);

    this.modConfig = moduleConfiguration;
    this.secCallback = secCallback;
    this.userCourseEnv = userCourseEnv;
    this.courseNode = testCourseNode;
    this.type = AssessmentInstance.QMD_ENTRY_TYPE_ASSESS;
    this.singleUserEventCenter = ureq.getUserSession().getSingleUserEventCenter();
    this.assessmentEventOres = OresHelper.createOLATResourceableType(AssessmentEvent.class);
    this.assessmentInstanceOres = OresHelper.createOLATResourceableType(AssessmentInstance.class);
    this.chatEventOres = OresHelper.createOLATResourceableType(InstantMessaging.class);
    this.notificationHandler = notificationHandler;
    this.userSession = ureq.getUserSession();

    addLoggingResourceable(LoggingResourceable.wrap(courseNode));

    myContent = createVelocityContainer("testrun");

    mainPanel = putInitialPanel(myContent);

    if (!modConfig
        .get(IQEditController.CONFIG_KEY_TYPE)
        .equals(AssessmentInstance.QMD_ENTRY_TYPE_ASSESS)) {
      throw new OLATRuntimeException(
          "IQRunController launched with Test constructor but module configuration not configured as test",
          null);
    }
    init(ureq);
    exposeUserTestDataToVC(ureq);

    final StringBuilder qtiChangelog = createChangelogMsg(ureq);
    // decide about changelog in VC
    if (qtiChangelog.length() > 0) {
      // there is some message
      myContent.contextPut("changeLog", qtiChangelog);
    }

    // if show results on test home page configured - show log
    final Boolean showResultOnHomePage =
        (Boolean)
            testCourseNode
                .getModuleConfiguration()
                .get(IQEditController.CONFIG_KEY_RESULT_ON_HOME_PAGE);
    myContent.contextPut("showChangelog", showResultOnHomePage);
  }
Exemplo n.º 6
0
  /**
   * Sent notification mail for signalling that course creation was successful.
   *
   * @param ureq user request
   * @param config course configuration object
   * @return mailer result object
   */
  public static final MailerResult sentNotificationMail(
      final UserRequest ureq, final CourseCreationConfiguration config) {
    final Translator translator =
        PackageUtil.createPackageTranslator(CourseCreationMailHelper.class, ureq.getLocale());
    log.info(
        "Course creation with wizard finished. [User: "******"] [Course name: "
            + config.getCourseTitle()
            + "]");
    final String subject =
        translator.translate("mail.subject", new String[] {config.getCourseTitle()});
    String body = translator.translate("mail.body.0", new String[] {config.getCourseTitle()});
    body += translator.translate("mail.body.1");
    body += translator.translate("mail.body.2", new String[] {config.getExtLink()});
    body += translator.translate("mail.body.3");
    body += translator.translate("mail.body.4");

    int counter = 1;
    if (config.isCreateSinglePage()) {
      body += translator.translate("mail.body.4.2", new String[] {Integer.toString(++counter)});
    }
    if (config.isCreateEnrollment()) {
      body += translator.translate("mail.body.4.3", new String[] {Integer.toString(++counter)});
    }
    if (config.isCreateDownloadFolder()) {
      body += translator.translate("mail.body.4.4", new String[] {Integer.toString(++counter)});
    }
    if (config.isCreateForum()) {
      body += translator.translate("mail.body.4.5", new String[] {Integer.toString(++counter)});
    }
    if (config.isCreateContactForm()) {
      body += translator.translate("mail.body.4.6", new String[] {Integer.toString(++counter)});
    }
    body += translator.translate("mail.body.5");
    body += translator.translate("mail.body.6");
    body += translator.translate("mail.body.greetings");

    final MailTemplate template =
        new MailTemplate(
            subject, body, MailTemplateHelper.getMailFooter(ureq.getIdentity(), null), null) {
          @Override
          @SuppressWarnings("unused")
          public void putVariablesInMailContext(
              final VelocityContext context, final OLATPrincipal identity) {
            // nothing to do
          }
        };
    return MailerWithTemplate.getInstance()
        .sendMail(ureq.getIdentity(), null, null, template, null);
  }
Exemplo n.º 7
0
 /**
  * @param ureq
  * @return
  */
 private StringBuilder createChangelogMsg(final UserRequest ureq) {
   /*
    * TODO:pb:is ImsRepositoryResolver the right place for getting the change log?
    */
   final RepositoryEntry re = courseNode.getReferencedRepositoryEntry();
   // re could be null, but if we are here it should not be null!
   final Roles userRoles = ureq.getUserSession().getRoles();
   boolean showAll = false;
   showAll = userRoles.isAuthor() || userRoles.isOLATAdmin();
   // get changelog
   final Formatter formatter = Formatter.getInstance(ureq.getLocale());
   final ImsRepositoryResolver resolver = new ImsRepositoryResolver(re.getKey());
   final QTIChangeLogMessage[] qtiChangeLog = resolver.getDocumentChangeLog();
   final StringBuilder qtiChangelog = new StringBuilder();
   Date msgDate = null;
   if (qtiChangeLog.length > 0) {
     // there are resource changes
     Arrays.sort(qtiChangeLog);
     for (int i = qtiChangeLog.length - 1; i >= 0; i--) {
       // show latest change first
       if (!showAll && qtiChangeLog[i].isPublic()) {
         // logged in person is a normal user, hence public messages only
         msgDate = new Date(qtiChangeLog[i].getTimestmp());
         qtiChangelog
             .append("\nChange date: ")
             .append(formatter.formatDateAndTime(msgDate))
             .append("\n");
         qtiChangelog.append(qtiChangeLog[i].getLogMessage());
         qtiChangelog.append("\n********************************\n");
       } else if (showAll) {
         // logged in person is an author, olat admin, owner, show all messages
         msgDate = new Date(qtiChangeLog[i].getTimestmp());
         qtiChangelog
             .append("\nChange date: ")
             .append(formatter.formatDateAndTime(msgDate))
             .append("\n");
         qtiChangelog.append(qtiChangeLog[i].getLogMessage());
         qtiChangelog.append("\n********************************\n");
       } // else non public messages are not shown to normal user
     }
   }
   return qtiChangelog;
 }
Exemplo n.º 8
0
 private void checkChats(final UserRequest ureq) {
   if (ureq != null) {
     allChats = (List) ureq.getUserSession().getEntry("chats");
   }
   if (allChats == null || allChats.size() == 0) {
     startButton.setEnabled(true);
     myContent.contextPut("hasChatWindowOpen", false);
   } else {
     startButton.setEnabled(false);
     myContent.contextPut("hasChatWindowOpen", true);
   }
 }
Exemplo n.º 9
0
 /**
  * Provides the show results button if results available or a message with the visibility period.
  *
  * @param ureq
  */
 private void exposeResults(final UserRequest ureq) {
   // migration: check if old tests have no summary configured
   final String configuredSummary = (String) modConfig.get(IQEditController.CONFIG_KEY_SUMMARY);
   final boolean noSummary =
       configuredSummary == null
           || (configuredSummary != null
               && configuredSummary.equals(AssessmentInstance.QMD_ENTRY_SUMMARY_NONE));
   if (!noSummary) {
     final Boolean showResultsObj =
         (Boolean) modConfig.get(IQEditController.CONFIG_KEY_RESULT_ON_HOME_PAGE);
     final boolean showResultsOnHomePage =
         (showResultsObj != null && showResultsObj.booleanValue());
     myContent.contextPut("showResultsOnHomePage", new Boolean(showResultsOnHomePage));
     final boolean dateRelatedVisibility = AssessmentHelper.isResultVisible(modConfig);
     if (showResultsOnHomePage && dateRelatedVisibility) {
       myContent.contextPut("showResultsVisible", Boolean.TRUE);
       showResultsButton = LinkFactory.createButton("command.showResults", myContent, this);
       hideResultsButton = LinkFactory.createButton("command.hideResults", myContent, this);
     } else if (showResultsOnHomePage) {
       final Date startDate = (Date) modConfig.get(IQEditController.CONFIG_KEY_RESULTS_START_DATE);
       final Date endDate = (Date) modConfig.get(IQEditController.CONFIG_KEY_RESULTS_END_DATE);
       final String visibilityStartDate =
           DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, ureq.getLocale())
               .format(startDate);
       String visibilityEndDate = "-";
       if (endDate != null) {
         visibilityEndDate =
             DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, ureq.getLocale())
                 .format(endDate);
       }
       final String visibilityPeriod =
           getTranslator()
               .translate(
                   "showResults.visibility",
                   new String[] {visibilityStartDate, visibilityEndDate});
       myContent.contextPut("visibilityPeriod", visibilityPeriod);
       myContent.contextPut("showResultsVisible", Boolean.FALSE);
     }
   }
 }
Exemplo n.º 10
0
  /**
   * @param ureq
   * @param te
   */
  public void switchToPage(final UserRequest ureq, final TreeEvent te) {
    // all treeevents receiced here are event clicked only
    // if (!te.getCommand().equals(TreeEvent.COMMAND_TREENODE_CLICKED)) throw
    // new AssertException("error");

    // switch to the new page
    final String nodeId = te.getNodeId();
    final TreeNode tn = ctm.getNodeById(nodeId);
    final String identifierRes = (String) tn.getUserObject();

    // security check
    if (identifierRes.indexOf("../") != -1) {
      throw new AssertException(
          "a non-normalized url encountered in a manifest item:" + identifierRes);
    }

    // Check if path ends with .html, .htm or .xhtml. We do this by searching for "htm"
    // and accept positions of this string at length-3 or length-4
    // Check also for XML resources that use XSLT for rendering
    if (identifierRes.toLowerCase().lastIndexOf(FILE_SUFFIX_HTM) >= (identifierRes.length() - 4)
        || identifierRes.toLowerCase().endsWith(FILE_SUFFIX_XML)) {
      // display html files inline or in an iframe
      if (cpContentCtr != null) {
        cpContentCtr.setCurrentURI(identifierRes);
      }
      if (cpComponent != null) {
        cpComponent.setCurrentURI(identifierRes);
      }

    } else {
      // Also display pdf and other files in the iframe if it has been
      // initialized. Delegates displaying to the browser (and its plugins).
      if (cpContentCtr != null) {
        cpContentCtr.setCurrentURI(identifierRes);
      } else {
        // if an entry in a manifest points e.g. to a pdf file and the iframe
        // controller has not been initialized display it non-inline
        final VFSItem currentItem = rootContainer.resolve(identifierRes);
        MediaResource mr;
        if (currentItem == null || !(currentItem instanceof VFSLeaf)) {
          mr = new NotFoundMediaResource(identifierRes);
        } else {
          mr = new VFSMediaResource((VFSLeaf) currentItem);
        }
        ureq.getDispatchResult().setResultingMediaResource(mr);
        // Prevent 'don't reload' warning
        cpTree.setDirty(false);
      }
    }
    ThreadLocalUserActivityLogger.log(
        CourseLoggingAction.CP_GET_FILE, getClass(), LoggingResourceable.wrapCpNode(identifierRes));
  }
 @Override
 protected void event(UserRequest ureq, Component source, Event event) {
   if (source == subscribeButton) {
     if (isNewNotificationService) {
       subscribeToNewNotificationService();
     } else {
       notifManager.subscribe(ureq.getIdentity(), subscriptionContext, publisherData);
     }
     isSubscribed = true;
     updateUI();
     fireEvent(ureq, event);
   } else if (source == unsubscribeButton) {
     if (isNewNotificationService) {
       unsubscribeFromNewNotificationService();
     } else {
       notifManager.unsubscribe(ureq.getIdentity(), subscriptionContext);
     }
     isSubscribed = false;
     updateUI();
     fireEvent(ureq, event);
   }
 }
  /**
   * Constructor
   *
   * @param ureq
   * @param wControl
   */
  protected CalendarPortletRunController(final UserRequest ureq, final WindowControl wControl) {
    super(ureq, wControl);

    calendarVC = createVelocityContainer("calendarPortlet");
    showAllLink = LinkFactory.createLink("calendar.showAll", calendarVC, this);
    ComponentUtil.registerForValidateEvents(calendarVC, this);

    final Date date = new Date();
    final String today =
        DateFormat.getTimeInstance(DateFormat.MEDIUM, ureq.getLocale()).format(date);
    calendarVC.contextPut("today", today);

    final TableGuiConfiguration tableConfig = new TableGuiConfiguration();
    tableConfig.setTableEmptyMessage(translate("calendar.noEvents"));
    tableConfig.setDisplayTableHeader(false);
    tableConfig.setCustomCssClass("b_portlet_table");
    tableConfig.setDisplayRowCount(false);
    tableConfig.setPageingEnabled(false);
    tableConfig.setDownloadOffered(false);
    tableController = new TableController(tableConfig, ureq, getWindowControl(), getTranslator());
    // dummy header key, won't be used since setDisplayTableHeader is set to
    // false
    tableController.addColumnDescriptor(
        new PortletDateColumnDescriptor("calendar.date", 0, getTranslator()));
    tableController.addColumnDescriptor(
        new DefaultColumnDescriptor(
            "calendar.subject", 1, CMD_LAUNCH, ureq.getLocale(), ColumnDescriptor.ALIGNMENT_LEFT));

    final List events = getMatchingEvents(ureq, wControl);
    tableController.setTableDataModel(new EventsModel(events));
    listenTo(tableController);

    calendarVC.put("table", tableController.getInitialComponent());

    putInitialPanel(this.calendarVC);
  }
 /**
  * Constructor fot the business group multiple copy wizard
  *
  * @param ureq
  * @param wControl
  * @param originalGroup original business group: master that should be copied
  * @param flags
  */
 public BGMultipleCopyWizardController(
     final UserRequest ureq,
     final WindowControl wControl,
     final BusinessGroup originalGroup,
     final BGConfigFlags flags) {
   super(ureq, wControl, 2);
   this.trans =
       BGTranslatorFactory.createBGPackageTranslator(
           PACKAGE, originalGroup.getType(), ureq.getLocale());
   this.flags = flags;
   this.originalGroup = originalGroup;
   // init wizard step 1
   this.copyForm = new BGCopyWizardCopyForm(ureq, wControl);
   this.copyForm.addControllerListener(this);
   // init wizard title and set step 1
   setWizardTitle(trans.translate("bgcopywizard.multiple.title"));
   setNextWizardStep(
       trans.translate("bgcopywizard.copyform.title"), this.copyForm.getInitialComponent());
 }
Exemplo n.º 14
0
  @Override
  protected void event(final UserRequest urequest, final Controller source, final Event event) {
    if (source == displayController) {
      if (event instanceof IQSubmittedEvent) {
        final IQSubmittedEvent se = (IQSubmittedEvent) event;
        final AssessmentManager am = userCourseEnv.getCourseEnvironment().getAssessmentManager();

        // Save results in case of test
        if (type.equals(AssessmentInstance.QMD_ENTRY_TYPE_ASSESS)) {
          // update scoring overview for the user in the current course
          final Float score = new Float(se.getScore());
          final Boolean passed = new Boolean(se.isPassed());
          final ScoreEvaluation sceval =
              new ScoreEvaluation(score, passed, new Long(se.getAssessmentID()));
          final AssessableCourseNode acn =
              (AssessableCourseNode) courseNode; // assessment nodes are assesable
          final boolean incrementUserAttempts = true;
          acn.updateUserScoreEvaluation(
              sceval, userCourseEnv, urequest.getIdentity(), incrementUserAttempts);
          // userCourseEnv.getScoreAccounting().scoreInfoChanged(acn, sceval);
          exposeUserTestDataToVC(urequest);

          // Mark publisher for notifications
          final Long courseId = userCourseEnv.getCourseEnvironment().getCourseResourceableId();
          notificationHandler.markPublisherNews(urequest.getIdentity(), courseId);
          if (!assessmentStopped) {
            assessmentStopped = true;
            final AssessmentEvent assessmentStoppedEvent =
                new AssessmentEvent(AssessmentEvent.TYPE.STOPPED, userSession);
            singleUserEventCenter.deregisterFor(this, assessmentInstanceOres);
            singleUserEventCenter.fireEventToListenersOf(
                assessmentStoppedEvent, assessmentEventOres);
          }
        }
        // Save results in case of questionnaire
        else if (type.equals(AssessmentInstance.QMD_ENTRY_TYPE_SURVEY)) {
          // save number of attempts
          // although this is not an assessable node we still use the assessment
          // manager since this one uses caching
          am.incrementNodeAttempts(courseNode, urequest.getIdentity(), userCourseEnv);
          exposeUserQuestionnaireDataToVC();
          getWindowControl().pop();
        }
        // Don't save results in case of self-test
        // but do safe attempts !
        else if (type.equals(AssessmentInstance.QMD_ENTRY_TYPE_SELF)) {
          am.incrementNodeAttempts(courseNode, urequest.getIdentity(), userCourseEnv);
        }
      } else if (event.equals(Event.DONE_EVENT)) {
        getWindowControl().pop();
        if (type.equals(AssessmentInstance.QMD_ENTRY_TYPE_ASSESS) && !assessmentStopped) {
          assessmentStopped = true;
          final AssessmentEvent assessmentStoppedEvent =
              new AssessmentEvent(AssessmentEvent.TYPE.STOPPED, userSession);
          singleUserEventCenter.deregisterFor(this, assessmentInstanceOres);
          singleUserEventCenter.fireEventToListenersOf(assessmentStoppedEvent, assessmentEventOres);
        }
        fireEvent(urequest, Event.DONE_EVENT);
      }
    }
  }
Exemplo n.º 15
0
  @Override
  protected void event(final UserRequest ureq, final Component source, final Event event) {
    if (source == startButton && startButton.isEnabled()) {
      final long callingResId =
          userCourseEnv.getCourseEnvironment().getCourseResourceableId().longValue();
      final String callingResDetail = courseNode.getIdent();
      removeAsListenerAndDispose(displayController);
      final Controller returnController =
          IQManager.getInstance()
              .createIQDisplayController(
                  modConfig, secCallback, ureq, getWindowControl(), callingResId, callingResDetail);
      /*
       * either returnController is a MessageController or it is a IQDisplayController this should not serve as pattern to be copy&pasted. FIXME:2008-11-21:pb
       * INTRODUCED because of read/write QTI Lock solution for scalability II, 6.1.x Release
       */
      if (returnController instanceof IQDisplayController) {
        displayController = (IQDisplayController) returnController;
        listenTo(displayController);
        if (displayController.isReady()) {
          // in case displayController was unable to initialize, a message was set by
          // displayController
          // this is the case if no more attempts or security check was unsuccessfull
          final LayoutMain3ColsController layoutCtr =
              new LayoutMain3ColsController(
                  ureq,
                  getWindowControl(),
                  null,
                  null,
                  displayController.getInitialComponent(),
                  null);
          listenTo(layoutCtr); // autodispose

          // need to wrap a course restart controller again, because IQDisplay
          // runs on top of GUIStack
          final ICourse course = CourseFactory.loadCourse(callingResId);
          final RepositoryEntry courseRepositoryEntry =
              RepositoryServiceImpl.getInstance().lookupRepositoryEntry(course, true);
          final Panel empty = new Panel("empty"); // empty panel set as "menu" and "tool"
          final Controller courseCloser =
              CourseFactory.createDisposedCourseRestartController(
                  ureq, getWindowControl(), courseRepositoryEntry.getResourceableId());
          final Controller disposedRestartController =
              new LayoutMain3ColsController(
                  ureq,
                  getWindowControl(),
                  empty,
                  empty,
                  courseCloser.getInitialComponent(),
                  "disposed course whily in iqRun" + callingResId);
          layoutCtr.setDisposedMessageController(disposedRestartController);

          getWindowControl().pushToMainArea(layoutCtr.getInitialComponent());
          if (modConfig
              .get(IQEditController.CONFIG_KEY_TYPE)
              .equals(AssessmentInstance.QMD_ENTRY_TYPE_ASSESS)) {
            assessmentStopped = false;
            singleUserEventCenter.registerFor(this, getIdentity(), assessmentInstanceOres);
            singleUserEventCenter.fireEventToListenersOf(
                new AssessmentEvent(AssessmentEvent.TYPE.STARTED, ureq.getUserSession()),
                assessmentEventOres);
          }
        } // endif isReady
      } else {
        // -> qti file was locked -> show info message
        // user must click again on course node to activate
        mainPanel.pushContent(returnController.getInitialComponent());
      }
    } else if (source == showResultsButton) {
      final AssessmentManager am = userCourseEnv.getCourseEnvironment().getAssessmentManager();
      Long assessmentID = am.getAssessmentID(courseNode, ureq.getIdentity());
      if (assessmentID == null) {
        // fallback solution: if the assessmentID is not available via AssessmentManager than try to
        // get it via IQManager
        final long callingResId =
            userCourseEnv.getCourseEnvironment().getCourseResourceableId().longValue();
        final String callingResDetail = courseNode.getIdent();
        assessmentID =
            IQManager.getInstance()
                .getLastAssessmentID(ureq.getIdentity(), callingResId, callingResDetail);
      }
      if (assessmentID != null && !assessmentID.equals("")) {
        final Document doc =
            IQManager.getInstance()
                .getResultsReportingFromFile(ureq.getIdentity(), type, assessmentID);
        // StringBuilder resultsHTML =
        // LocalizedXSLTransformer.getInstance(ureq.getLocale()).renderResults(doc);
        final String summaryConfig = (String) modConfig.get(IQEditController.CONFIG_KEY_SUMMARY);
        final int summaryType = AssessmentInstance.getSummaryType(summaryConfig);
        final String resultsHTML =
            IQManager.getInstance().transformResultsReporting(doc, ureq.getLocale(), summaryType);
        myContent.contextPut("displayreporting", resultsHTML);
        myContent.contextPut("resreporting", resultsHTML);
        myContent.contextPut("showResults", Boolean.TRUE);
      }
    } else if (source == hideResultsButton) {
      myContent.contextPut("showResults", Boolean.FALSE);
    }
  }
Exemplo n.º 16
0
 public boolean isSame(UserRequest ureq) {
   return (componentId.equals(ureq.getComponentID())
       && windowTimestamp.equals(ureq.getTimestampID())
       && componentTimestamp.equals(ureq.getComponentTimestamp()));
 }
Exemplo n.º 17
0
  /**
   * Main method called by DispatcherAction. This processess all requests for authenticated users.
   *
   * @param request
   * @param response
   * @param uriPrefix
   */
  @Override
  public void execute(
      final HttpServletRequest request,
      final HttpServletResponse response,
      final String uriPrefix) {
    long startExecute = 0;
    if (log.isDebugEnabled()) {
      startExecute = System.currentTimeMillis();
    }
    final UserSession usess = UserSession.getUserSession(request);
    UserRequest ureq = null;
    try {
      // upon creation URL is checked for
      ureq = new UserRequest(uriPrefix, request, response);
    } catch (final NumberFormatException nfe) {
      // MODE could not be decoded
      // typically if robots with wrong urls hit the system
      // or user have bookmarks
      // or authors copy-pasted links to the content.
      // showing redscreens for non valid URL is wrong instead
      // a 404 message must be shown -> e.g. robots correct their links.
      if (log.isDebugEnabled()) {
        log.debug("Bad Request " + request.getPathInfo());
      }
      DispatcherAction.sendBadRequest(request.getPathInfo(), response);
      return;
    }

    // GUIInterna.setLoadPerformanceMode(ureq);
    // GUIInterna.setUserSession (usess);

    final boolean auth = usess.isAuthenticated();

    if (!auth) {
      if (!ureq.isValidDispatchURI()) {
        // might be a direct jump request -> remember it if not logged in yet
        final String reqUri = request.getRequestURI();
        final String query = request.getQueryString();
        final String allGet = reqUri + QUESTIONMARK + query;
        usess.putEntryInNonClearedStore(AUTHDISPATCHER_ENTRYURL, allGet);
      }
      final String guestAccess = ureq.getParameter(GUEST);
      if (guestAccess == null || !LoginModule.isGuestLoginLinksEnabled()) {
        DispatcherAction.redirectToDefaultDispatcher(response);
        return;
      } else if (guestAccess.equals(TRUE)) {
        // try to log in as anonymous
        // use the language from the lang paramter if available, otherwhise use the system default
        // locale
        final String guestLang = ureq.getParameter("lang");
        Locale guestLoc;
        if (guestLang == null) {
          guestLoc = I18nModule.getDefaultLocale();
        } else {
          guestLoc = I18nManager.getInstance().getLocaleOrDefault(guestLang);
        }
        final int loginStatus = AuthHelper.doAnonymousLogin(ureq, guestLoc);
        if (loginStatus != AuthHelper.LOGIN_OK) {
          if (loginStatus == AuthHelper.LOGIN_NOTAVAILABLE) {
            DispatcherAction.redirectToServiceNotAvailable(response);
          }
          DispatcherAction.redirectToDefaultDispatcher(response); // error, redirect to login screen
          return;
        }
        // else now logged in as anonymous user, continue
      }
    }

    // authenticated!
    try {

      // kill session if not secured via SSL
      if (forceSecureAccessOnly && !request.isSecure()) {
        final SessionInfo sessionInfo = usess.getSessionInfo();
        if (sessionInfo != null) {
          final HttpSession session = sessionInfo.getSession();
          if (session != null) {
            try {
              session.invalidate();
            } catch (final IllegalStateException ise) {
              // thrown when session already invalidated. fine. ignore.
            }
          }
        }
        DispatcherAction.redirectToDefaultDispatcher(response);
        return;
      }

      final SessionInfo sessionInfo = usess.getSessionInfo();
      if (sessionInfo == null) {
        DispatcherAction.redirectToDefaultDispatcher(response);
        return;
      }

      if (userBasedLogLevelManager != null) {
        userBasedLogLevelManager.activateUsernameBasedLogLevel(sessionInfo.getLogin());
      }

      sessionInfo.setLastClickTime();
      final String origUrl = (String) usess.removeEntryFromNonClearedStore(AUTHDISPATCHER_ENTRYURL);
      if (origUrl != null) {
        // we had a direct jump request
        // to avoid a endless redirect, remove the guest parameter if any
        // this can happen if a guest has cookies disabled
        final String url = new URIHelper(origUrl).removeParameter(GUEST).toString();
        DispatcherAction.redirectTo(response, url);
        return;
      }
      final String businessPath =
          (String) usess.removeEntryFromNonClearedStore(AUTHDISPATCHER_BUSINESSPATH);
      if (businessPath != null) {
        final BusinessControl bc =
            BusinessControlFactory.getInstance().createFromString(businessPath);
        final ChiefController cc =
            (ChiefController) Windows.getWindows(usess).getAttribute("AUTHCHIEFCONTROLLER");

        if (cc == null) {
          log.error("I-130611-0017 [url=" + request.getRequestURI());
        }
        final WindowControl wControl = cc.getWindowControl();
        final WindowControl bwControl =
            BusinessControlFactory.getInstance().createBusinessWindowControl(bc, wControl);
        NewControllerFactory.getInstance().launch(ureq, bwControl);
        // render the window
        final Window w = cc.getWindow();
        w.dispatchRequest(ureq, true); // renderOnly
        return;
      }

      if (ureq.isValidDispatchURI()) { // valid uri for dispatching (has timestamp, componentid and
        // windowid)
        final Windows ws = Windows.getWindows(ureq);
        final Window window = ws.getWindow(ureq);
        if (window == null) {
          // If no window, this is probably a stale link. send not
          // found
          // note: do not redirect to login since this wastes a new
          // window each time since we are in an authenticated session
          // -> a content packaging with wrong links e.g. /css/my.css
          // wastes all the windows
          DispatcherAction.sendNotFound(request.getRequestURI(), response);
          return;
        }
        long startDispatchRequest = 0;
        if (log.isDebugEnabled()) {
          startDispatchRequest = System.currentTimeMillis();
        }
        window.dispatchRequest(ureq);
        if (log.isDebugEnabled()) {
          final long durationDispatchRequest = System.currentTimeMillis() - startDispatchRequest;
          log.debug("Perf-Test: window=" + window);
          log.debug("Perf-Test: durationDispatchRequest=" + durationDispatchRequest);
        }
      }
    } catch (final Throwable th) {
      // Do not log as Warn or Error here, log as ERROR in MsgFactory => ExceptionWindowController
      // throws an OLATRuntimeException
      log.debug("handleError in AuthenticatedDispatcher throwable=" + th);
      DispatcherAction.handleError();
      final ChiefController msgcc = MsgFactory.createMessageChiefController(ureq, th);
      // the controller's window must be failsafe also
      msgcc.getWindow().dispatchRequest(ureq, true);
      // do not dispatch (render only), since this is a new Window created as
      // a result of another window's click.
    } finally {
      if (userBasedLogLevelManager != null) {
        userBasedLogLevelManager.deactivateUsernameBasedLogLevel();
      }
      if (log.isDebugEnabled()) {
        final long durationExecute = System.currentTimeMillis() - startExecute;
        log.debug("Perf-Test: durationExecute=" + durationExecute);
      }
      // XX:GUIInterna.setLoadPerformanceMode(null);
    }
  }
Exemplo n.º 18
0
 /**
  * Get the success info message.
  *
  * @param ureq user request
  * @return info message
  */
 public static final String getSuccessMessageString(final UserRequest ureq) {
   final Translator translator =
       PackageUtil.createPackageTranslator(CourseCreationMailHelper.class, ureq.getLocale());
   return translator.translate("coursecreation.success");
 }
Exemplo n.º 19
0
 public HistoryEntry(UserRequest ureq) {
   this.componentId = ureq.getComponentID();
   this.windowTimestamp = ureq.getTimestampID();
   this.componentTimestamp = ureq.getComponentTimestamp();
 }
Exemplo n.º 20
0
  /**
   * @param ureq
   * @param cpRoot
   * @param showMenu
   * @param activateFirstPage
   */
  CPDisplayController(
      final UserRequest ureq,
      final WindowControl wControl,
      final VFSContainer rootContainer,
      final boolean showMenu,
      final boolean activateFirstPage,
      final String initialUri,
      final OLATResourceable ores) {
    super(ureq, wControl);
    this.rootContainer = rootContainer;

    // wrapper velocity container for page content
    this.myContent = createVelocityContainer("cpDisplay");
    // the cp component, added to the velocity

    if (!ureq.getUserSession().getRoles().isGuestOnly()) {
      final SearchServiceUIFactory searchServiceUIFactory =
          (SearchServiceUIFactory) CoreSpringFactory.getBean(SearchServiceUIFactory.class);
      searchCtrl =
          searchServiceUIFactory.createInputController(ureq, wControl, DisplayOption.BUTTON, null);
      myContent.put("search_input", searchCtrl.getInitialComponent());
    }

    // TODO:gs:a
    // may add an additional config for disabling, enabling IFrame style or not in CP mode
    // but always disable IFrame display when in screenreader mode (no matter whether style gets
    // ugly)
    if (getWindowControl().getWindowBackOffice().getWindowManager().isForScreenReader()) {
      cpComponent = new HtmlStaticPageComponent("", rootContainer);
      cpComponent.addListener(this);
      myContent.put("cpContent", cpComponent);
    } else {
      cpContentCtr =
          new IFrameDisplayController(ureq, getWindowControl(), rootContainer, null, ores);
      cpContentCtr.setAllowDownload(true);
      listenTo(cpContentCtr);
      myContent.put("cpContent", cpContentCtr.getInitialComponent());
    }

    // even if we do not show the menu, we need to build parse the manifest and
    // find the first node to display at startup
    final VFSItem mani = rootContainer.resolve("imsmanifest.xml");
    if (mani == null || !(mani instanceof VFSLeaf)) {
      throw new OLATRuntimeException(
          "error.manifest.missing",
          null,
          this.getClass().getPackage().getName(),
          "CP " + rootContainer + " has no imsmanifest",
          null);
    }
    // initialize tree model in any case
    ctm = new CPManifestTreeModel((VFSLeaf) mani);

    if (showMenu) {
      // the menu is only initialized when needed.
      cpTree = new MenuTree("cpDisplayTree");
      cpTree.setTreeModel(ctm);
      cpTree.addListener(this);
    }

    LoggingResourceable nodeInfo = null;
    if (activateFirstPage) {
      // set content to first accessible child or root node if no children
      // available
      TreeNode node = ctm.getRootNode();
      if (node == null) {
        throw new OLATRuntimeException(
            CPDisplayController.class,
            "root node of content packaging was null, file:" + rootContainer,
            null);
      }
      while (node != null && !node.isAccessible()) {
        if (node.getChildCount() > 0) {
          node = (TreeNode) node.getChildAt(0);
        } else {
          node = null;
        }
      }
      if (node != null) { // node.isAccessible
        final String nodeUri = (String) node.getUserObject();
        if (cpContentCtr != null) {
          cpContentCtr.setCurrentURI(nodeUri);
        }
        if (cpComponent != null) {
          cpComponent.setCurrentURI(nodeUri);
        }
        if (showMenu) {
          cpTree.setSelectedNodeId(node.getIdent());
        }
        // activate the selected node in the menu (skips the root node that is
        // empty anyway and saves one user click)
        selNodeId = node.getIdent();

        nodeInfo = LoggingResourceable.wrapCpNode(nodeUri);
      }
    } else if (initialUri != null) {
      // set page
      if (cpContentCtr != null) {
        cpContentCtr.setCurrentURI(initialUri);
      }
      if (cpComponent != null) {
        cpComponent.setCurrentURI(initialUri);
      }
      // update menu
      final TreeNode newNode = ctm.lookupTreeNodeByHref(initialUri);
      if (newNode != null) { // user clicked on a link which is listed in the
        // toc
        if (cpTree != null) {
          cpTree.setSelectedNodeId(newNode.getIdent());
        } else {
          selNodeId = newNode.getIdent();
        }
      }
      nodeInfo = LoggingResourceable.wrapCpNode(initialUri);
    }
    // Note: the ores has a typename of ICourse - see
    // CPCourseNode.createNodeRunConstructorResult
    // which has the following line:
    // OresHelper.createOLATResourceableInstance(ICourse.class,
    // userCourseEnv.getCourseEnvironment().getCourseResourceableId());
    // therefore we use OresHelper.calculateTypeName(ICourse.class) here
    if (ores != null
        && nodeInfo != null
        && !OresHelper.calculateTypeName(ICourse.class).equals(ores.getResourceableTypeName())) {
      addLoggingResourceable(LoggingResourceable.wrap(ores, OlatResourceableType.cp));
      ThreadLocalUserActivityLogger.log(
          LearningResourceLoggingAction.LEARNING_RESOURCE_OPEN, getClass(), nodeInfo);
    }

    putInitialPanel(myContent);
  }
  /**
   * org.olat.presentation.framework.control.Controller,
   * org.olat.presentation.framework.UserRequest)
   */
  @Override
  @SuppressWarnings("unused")
  // listener is never used because listener == this!
  protected void initForm(
      final FormItemContainer formLayout, final Controller listener, final UserRequest ureq) {
    setFormTitle("guidemo_flexi_form_advanced");
    setFormDescription("advanced_form.description");
    // setFormContextHelp(this.getClass().getPackage().getName(),
    // "advancedFormHelp", "advanced_form.description");
    // Mandatory and read-only text fields

    this.addTextFields(formLayout);

    // More form items: Date, link and file selector
    this.addDateLinkAndFileItems(formLayout);

    // Separator with line
    uifactory.addSpacerElement("spacer", formLayout, false);

    // Single and multible selections (radio buttons and checkboxes)
    this.addSelections(formLayout);

    // Separator without line
    uifactory.addSpacerElement("spacernoline", formLayout, true);

    // Sublayout (shown if no is selected)
    this.addSublayout(formLayout);

    // Here's a text area
    uifactory.addTextAreaElement("guidemo.form.textarea", 0, 2, null, formLayout);

    // Add some rich text elements
    richTextElement =
        uifactory.addRichTextElementForStringData(
            "guidemo.form.richtext.simple",
            "guidemo.form.richtext.simple",
            "click <i>to</i> <b>edit</b>. This one has an event listener and an <b>external menu with auto hide</b>",
            -1,
            -1,
            true,
            false,
            null,
            null,
            formLayout,
            ureq.getUserSession(),
            getWindowControl());
    // richTextElement.addActionListener(this, FormEvent.ONCHANGE);

    richTextElement2 =
        uifactory.addRichTextElementForStringData(
            "guidemo.form.richtext.simple2",
            null,
            "one <i>with</i> <b>height</b> and <span style='color:red'>no</span> event listener and an <b>internal</b> menu",
            10,
            40,
            false,
            true,
            null,
            null,
            formLayout,
            ureq.getUserSession(),
            getWindowControl());

    disabledRichTextElement =
        uifactory.addRichTextElementForStringData(
            "guidemo.form.richtext.simple3",
            "guidemo.form.richtext.simple",
            "this <i>is</i> <b>disabled</b>",
            -1,
            -1,
            true,
            false,
            null,
            null,
            formLayout,
            ureq.getUserSession(),
            getWindowControl());
    disabledRichTextElement.setEnabled(false);

    // Button layout
    final FormLayoutContainer buttonLayout =
        FormLayoutContainer.createButtonLayout("button_layout", getTranslator());
    formLayout.add(buttonLayout);

    // Submit and cancel buttons (without effect)
    uifactory.addFormSubmitButton("advanced_form.submit", buttonLayout);
    uifactory.addFormLink("advanced_form.cancel", buttonLayout, Link.BUTTON);
  }