/** {@inheritDoc} */
  public boolean canReadNoteItem(Assignment a, String context) {
    if (a != null) {
      AssignmentNoteItem note = getNoteItem(a.getId());
      if (note != null) {
        User u = m_userDirectoryService.getCurrentUser();
        String noteCreatorId = note.getCreatorId();
        if (noteCreatorId.equals(u.getId())) {
          return true;
        } else if (m_assignmentService.allowGradeSubmission(a.getReference())) {
          // check whether the instructor type can view the note
          int share = note.getShareWith();
          if (share == AssignmentConstants.NOTE_READ_BY_OTHER
              || share == AssignmentConstants.NOTE_READ_AND_WRITE_BY_OTHER) {
            return true;
          }
        }
      }
    } else {
      if (m_assignmentService.allowAddAssignment(context)) {
        return true;
      }
    }

    return false;
  }
  /** {@inheritDoc} */
  public boolean canEditNoteItem(Assignment a) {
    String userId = "";
    User u = m_userDirectoryService.getCurrentUser();
    if (u != null) {
      userId = u.getId();
    }

    if (a != null) {
      AssignmentNoteItem note = getNoteItem(a.getId());
      if (note != null) {
        if (note.getCreatorId().equals(userId)) {
          // being creator can edit
          return true;
        } else if (note.getShareWith() == AssignmentConstants.NOTE_READ_AND_WRITE_BY_OTHER
            && m_assignmentService.allowGradeSubmission(a.getReference())) {
          return true;
        }
      } else {
        return true;
      }
    } else {
      return true;
    }

    return false;
  }
  /** {@inheritDoc} */
  public void notifyCourseRequestRequester(
      String requestEmail, String supportEmailContent, String termTitle) {
    User currentUser = userDirectoryService.getCurrentUser();
    String currentUserDisplayName = currentUser != null ? currentUser.getDisplayName() : "";
    String currentUserDisplayId = currentUser != null ? currentUser.getDisplayId() : "";
    String currentUserId = currentUser != null ? currentUser.getId() : "";
    String currentUserEmail = currentUser != null ? currentUser.getEmail() : "";

    ResourceLoader rb = new ResourceLoader(currentUserId, "UserNotificationProvider");

    String from = requestEmail;
    String to = currentUserEmail;
    String headerTo = to;
    String replyTo = to;
    // message subject
    String message_subject =
        rb.getString("java.sitereqfrom")
            + " "
            + currentUserDisplayName
            + " "
            + rb.getString("java.for")
            + " "
            + termTitle;

    StringBuffer buf = new StringBuffer();
    buf.append(rb.getString("java.isbeing") + " ");
    buf.append(rb.getString("java.meantime") + "\n\n");
    buf.append(rb.getString("java.copy") + "\n\n");
    buf.append(supportEmailContent);
    buf.append("\n" + rb.getString("java.wish") + " " + requestEmail);
    emailService.send(from, to, message_subject, buf.toString(), headerTo, replyTo, null);
  }
 private User addUserWithEid(String eid) throws Exception {
   User user =
       userDirectoryService.addUser(
           null, eid, FIRST_NAME, eid, eid + "@somewhere.edu", eid + "pwd", "Guest", null);
   log.debug("addUser eid=" + eid + ", id=" + user.getId());
   return user;
 }
Пример #5
0
 // Returns getUser and getUserByEid on the input string
 // @return Either the id of the user, or the same string if not defined
 private String getUserDefined(String usr) {
   // Set the original user id
   String userId = usr;
   User userinfo;
   try {
     userinfo = UserDirectoryService.getUser(usr);
     userId = userinfo.getId();
     if (LOG.isDebugEnabled()) {
       LOG.debug("getUserDefined: username for " + usr + " is " + userId);
     }
     return userId;
   } catch (UserNotDefinedException e) {
     try {
       // try with the user eid
       userinfo = UserDirectoryService.getUserByEid(usr);
       userId = userinfo.getId();
     } catch (UserNotDefinedException ee) {
       // This is mostly expected behavior, don't need to notify about it, the UI can handle it
       if (LOG.isDebugEnabled()) {
         LOG.debug("getUserDefined: User Not Defined" + userId);
       }
     }
   }
   return userId;
 }
 public String getDisplayName(User user) {
   if (!UNADVISED_USER_EID.equals(user.getEid())) {
     return user.getFirstName() + " " + user.getLastName() + DISPLAY_ADVISED_SUFFIX;
   } else {
     return null;
   }
 }
Пример #7
0
 private void loginUser(String ipAddress, User user) {
   Session sess = SessionManager.getCurrentSession();
   UsageSessionService.login(
       user.getId(), user.getEid(), ipAddress, null, UsageSessionService.EVENT_LOGIN_WS);
   sess.setUserId(user.getId());
   sess.setUserEid(user.getEid());
 }
  /**
   * Adds attendees to an existing event with a given role Common logic for addAttendeesToEvent and
   * addChairAttendeestoEvent
   *
   * @param vevent the VEvent to add the attendess too
   * @param attendees list of Users that have been invited to the event
   * @param role the role with which to add each user
   * @return the VEvent for the given event or null if there was an error
   */
  protected VEvent addAttendeesToEventWithRole(VEvent vevent, List<User> attendees, Role role) {

    if (!isIcsEnabled()) {
      log.debug(
          "ExternalCalendaringService is disabled. Enable via calendar.ics.generation.enabled=true in sakai.properties");
      return null;
    }

    // add attendees to event with 'required participant' role
    if (attendees != null) {
      for (User u : attendees) {
        Attendee a = new Attendee(createMailURI(u.getEmail()));
        a.getParameters().add(role);
        a.getParameters().add(new Cn(u.getDisplayName()));
        a.getParameters().add(PartStat.ACCEPTED);
        a.getParameters().add(Rsvp.FALSE);

        vevent.getProperties().add(a);
      }
    }

    if (log.isDebugEnabled()) {
      log.debug("VEvent with attendees:" + vevent);
    }

    return vevent;
  }
  /** @see junit.framework.TestCase#setUp() */
  @Before
  public void setUp() throws Exception {
    super.setUp();
    trustedLoginFilter = new TrustedLoginFilter();
    when(componentManager.get(ServerConfigurationService.class))
        .thenReturn(serverConfigurationService);
    when(componentManager.get(SessionManager.class)).thenReturn(sessionManager);
    when(componentManager.get(UserDirectoryService.class)).thenReturn(userDirectoryService);
    when(serverConfigurationService.getBoolean(
            TrustedLoginFilter.ORG_SAKAIPROJECT_UTIL_TRUSTED_LOGIN_FILTER_ENABLED, true))
        .thenReturn(true);
    when(serverConfigurationService.getString(
            TrustedLoginFilter.ORG_SAKAIPROJECT_UTIL_TRUSTED_LOGIN_FILTER_SHARED_SECRET, null))
        .thenReturn("e2KS54H35j6vS5Z38nK40");
    when(serverConfigurationService.getString(
            TrustedLoginFilter.ORG_SAKAIPROJECT_UTIL_TRUSTED_LOGIN_FILTER_SAFE_HOSTS,
            trustedLoginFilter.safeHosts))
        .thenReturn(trustedLoginFilter.safeHosts);
    when(request.getRemoteHost()).thenReturn("localhost");
    when(request.getHeader("x-sakai-token"))
        .thenReturn("sw9TTTqlEbGQkELqQuQPq92ydr4=;username;nonce");
    // default to non-existing session to exercise more code
    when(existingSession.getUserEid()).thenReturn(null);
    when(sessionManager.getCurrentSession()).thenReturn(existingSession);
    when(sessionManager.startSession()).thenReturn(newSession);
    when(user.getEid()).thenReturn("username");
    when(user.getId()).thenReturn("uuid1234567890");
    when(userDirectoryService.getUserByEid("username")).thenReturn(user);

    trustedLoginFilter.setupTestCase(componentManager);
    trustedLoginFilter.init(config);
  }
Пример #10
0
  /** @inheritDoc */
  public List getUnassignedMembersInRole(final String siteContext, final Role role) {
    List siteMembers = getSiteMembersInRole(siteContext, role);

    // Get all userUids of all users in sections
    List<String> sectionedUserUids = new ArrayList<String>();
    List sections = getSections(siteContext);
    for (Iterator sectionIter = sections.iterator(); sectionIter.hasNext(); ) {
      CourseSection section = (CourseSection) sectionIter.next();
      List sectionUsers = securityService.unlockUsers(getLock(role), section.getUuid());
      for (Iterator userIter = sectionUsers.iterator(); userIter.hasNext(); ) {
        org.sakaiproject.user.api.User user = (org.sakaiproject.user.api.User) userIter.next();
        sectionedUserUids.add(user.getId());
      }
    }

    // Now generate the list of unsectioned enrollments by subtracting the two collections
    // Since the APIs return different kinds of objects, we need to iterate
    List<ParticipationRecord> unsectionedMembers = new ArrayList<ParticipationRecord>();
    for (Iterator iter = siteMembers.iterator(); iter.hasNext(); ) {
      ParticipationRecord record = (ParticipationRecord) iter.next();
      if (!sectionedUserUids.contains(record.getUser().getUserUid())) {
        unsectionedMembers.add(record);
      }
    }
    return unsectionedMembers;
  }
Пример #11
0
 protected String getUserId(User u) {
   User user = getUser(u);
   if (user == null) return "";
   String id = user.getId();
   if (id == null) return "";
   return id;
 }
Пример #12
0
 public String getUserNameForDisplay(User user) {
   if (isSortUsersByDisplayName()) {
     return user.getDisplayName();
   } else {
     return user.getSortName();
   }
 }
  /** {@inheritDoc} */
  public boolean canViewAllPurposeItem(Assignment a) {
    boolean rv = false;

    if (a != null) {
      AssignmentAllPurposeItem aItem = getAllPurposeItem(a.getId());
      if (aItem != null) {
        if (!aItem.getHide()) {
          Time now = TimeService.newTime();
          Date releaseDate = aItem.getReleaseDate();
          Date retractDate = aItem.getRetractDate();

          if (releaseDate == null && retractDate == null) {
            // no time limitation on showing the item
            rv = true;
          } else if (releaseDate != null && retractDate == null) {
            // has relase date but not retract date
            rv = now.getTime() > releaseDate.getTime();
          } else if (releaseDate == null && retractDate != null) {
            // has retract date but not release date
            rv = now.getTime() < retractDate.getTime();
          } else if (now != null) {
            // both releaseDate and retract date are not null
            // has both release and retract dates
            rv = now.getTime() > releaseDate.getTime() && now.getTime() < retractDate.getTime();
          }
        } else {
          rv = false;
        }
      }

      if (rv) {
        // reset rv
        rv = false;

        // need to check role/user permission only if the above time test returns true
        List<String> access = getAccessListForAllPurposeItem(aItem);
        User u = m_userDirectoryService.getCurrentUser();
        if (u != null) {
          if (access.contains(u.getId())) rv = true;
          else {
            try {
              String role =
                  m_authzGroupService.getUserRole(
                      u.getId(), m_siteService.siteReference(a.getContext()));
              if (access.contains(role)) rv = true;
            } catch (Exception e) {
              Log.warn(
                  this
                      + ".callViewAllPurposeItem() Hibernate cannot access user role for user id= "
                      + u.getId());
              return rv;
            }
          }
        }
      }
    }

    return rv;
  }
 public String getUserDisplayName(User user, String contextReference) {
   if (contextualSiteUid.equals(contextReference)) {
     if (!NOT_IN_SITE_USER_EID.equals(user.getEid())) {
       return user.getFirstName() + " " + user.getLastName() + CONTEXTUAL_SITE_NAME;
     }
   }
   return null;
 }
 private String getCurrentUserEmailAddress() {
   User currentUser = userDirectoryService.getCurrentUser();
   String email = currentUser != null ? currentUser.getEmail() : null;
   if (email == null || email.length() == 0) {
     email = getSetupRequestEmailAddress();
   }
   return email;
 }
Пример #16
0
 /** @inheritDoc */
 public String getUserDisplayId() {
   try {
     User user = this.usageSessionServiceAdaptor.userDirectoryService().getUser(m_user);
     return user.getDisplayId();
   } catch (UserNotDefinedException e) {
     return m_user;
   }
 }
  /**
   * Format the announcement notification from address.
   *
   * @param event The event that matched criteria to cause the notification.
   * @return the announcement notification from address.
   */
  protected String getFromAddress(Event event) {
    Reference ref = EntityManager.newReference(event.getResource());

    // SAK-14831, yorkadam, make site title reflected in 'From:' name instead of default
    // ServerConfigurationService.getString("ui.service", "Sakai");
    String siteId = (getSite() != null) ? getSite() : ref.getContext();
    String title = "";
    try {
      Site site = SiteService.getSite(siteId);
      title = site.getTitle();
    } catch (Exception ignore) {
    }

    String userEmail = "no-reply@" + ServerConfigurationService.getServerName();
    String userDisplay = ServerConfigurationService.getString("ui.service", "Sakai");
    // String no_reply = "From: \"" + userDisplay + "\" <" + userEmail + ">";
    // String no_reply_withTitle = "From: \"" + title + "\" <" + userEmail + ">";
    String from = "From: Sakai"; // fallback value
    if (title != null && !title.equals("")) {
      from = "From: \"" + title + "\" <" + userEmail + ">";
    } else {
      String fromVal = getFrom(event); // should not return null but better safe than sorry
      if (fromVal != null) {
        from = fromVal;
      }
    }

    // get the message
    AnnouncementMessage msg = (AnnouncementMessage) ref.getEntity();
    String userId = msg.getAnnouncementHeader().getFrom().getDisplayId();

    // checks if "from" email id has to be included? and whether the notification is a delayed
    // notification?. SAK-13512
    // SAK-20988 - emailFromReplyable@org.sakaiproject.event.api.NotificationService is deprecated
    boolean notificationEmailFromReplyable =
        ServerConfigurationService.getBoolean("notify.email.from.replyable", false);
    if (notificationEmailFromReplyable && from.contains("no-reply@") && userId != null) {
      try {
        User u = UserDirectoryService.getUser(userId);
        userDisplay = u.getDisplayName();
        userEmail = u.getEmail();
        if ((userEmail != null) && (userEmail.trim().length()) == 0) userEmail = null;

      } catch (UserNotDefinedException e) {
      }

      // some fallback positions
      if (userEmail == null) userEmail = "no-reply@" + ServerConfigurationService.getServerName();
      if (userDisplay == null)
        userDisplay = ServerConfigurationService.getString("ui.service", "Sakai");
      from = "From: \"" + userDisplay + "\" <" + userEmail + ">";
    }

    return from;
  }
Пример #18
0
 /** @return return the current user */
 public EmailUser getCurrentUser() {
   EmailUser euser = null;
   User curU = null;
   try {
     curU = m_userDirectoryService.getCurrentUser();
     euser = new EmailUser(curU.getId(), curU.getDisplayName(), curU.getEmail());
   } catch (Exception e) {
     log.debug("Exception: Mailtool.getCurrentUser(), " + e.getMessage());
   }
   return euser;
 }
 private void checkExplicitContextualService(User user) {
   Assert.assertEquals(null, contextualUserDisplayService.getUserDisplayId(user, standardSiteUid));
   Assert.assertEquals(
       null, contextualUserDisplayService.getUserDisplayName(user, standardSiteUid));
   Assert.assertEquals(
       user.getEid() + CONTEXTUAL_SITE_NAME,
       contextualUserDisplayService.getUserDisplayId(user, contextualSiteUid));
   Assert.assertEquals(
       user.getFirstName() + " " + user.getLastName() + CONTEXTUAL_SITE_NAME,
       contextualUserDisplayService.getUserDisplayName(user, contextualSiteUid));
 }
Пример #20
0
  /**
   * Refine the recipients list to only users that are actually members of the given site.
   *
   * @param users The list of users to refine
   * @param site The site whose membership the users will be refined to
   */
  protected void refineToSiteMembers(List<User> users, Site site) {
    Set<Member> members = site.getMembers();
    Set<String> memberUserIds = getUserIds(members);

    for (Iterator<User> i = users.listIterator(); i.hasNext(); ) {
      User user = i.next();

      if (!memberUserIds.contains(user.getId())) {
        i.remove();
      }
    }
  }
Пример #21
0
  protected Map<String, String> getCurrentUserFields() {
    Map<String, String> rv = new HashMap<String, String>();
    String userRef = developerHelperService.getCurrentUserReference();
    if (userRef != null) {
      User user = (User) developerHelperService.fetchEntity(userRef);
      try {
        String email = user.getEmail();
        if (email == null) email = "";
        String first = user.getFirstName();
        if (first == null) first = "";
        String last = user.getLastName();
        if (last == null) last = "";

        rv.put(CURRENT_USER_EMAIL, email);
        rv.put(CURRENT_USER_FIRST_NAME, first);
        rv.put(CURRENT_USER_LAST_NAME, last);
        rv.put(CURRENT_USER_DISPLAY_NAME, user.getDisplayName());
        rv.put(CURRENT_USER_DISPLAY_ID, user.getDisplayId());
        rv.put("currentUserDispalyId", user.getDisplayId());

      } catch (Exception e) {
        log.warn("Failed to get current user replacements: " + userRef, e);
      }
    }
    /*NoN user fields */
    rv.put(LOCAL_SAKAI_NAME, serverConfigurationService.getString("ui.service", "Sakai"));
    rv.put(
        LOCAL_SAKAI_SUPPORT_MAIL,
        serverConfigurationService.getString(
            "support.email", "help@" + serverConfigurationService.getServerUrl()));
    rv.put(LOCAL_SAKAI_URL, serverConfigurationService.getServerUrl());

    return rv;
  }
  /**
   * Add the AuthzGroup for this user id, or for the user's type template, or for the general
   * template.
   *
   * @param rv The list.
   * @param id The user id.
   */
  public void addUserTemplateAuthzGroup(Collection rv, String id) {
    if (id == null) {
      id = "";
    }

    // user type template
    String template = "!user.template";
    try {
      User user = userDirectoryService.getUser(id);
      String type = user.getType();
      if (type != null) {
        rv.add(template + "." + type);
      }
    } catch (Exception ignore) {
    }

    // general user template
    rv.add("!user.template");
  }
  public void notifyNewUserEmail(User user, String newUserPassword, String siteTitle) {

    String from = getSetupRequestEmailAddress();
    String productionSiteName = serverConfigurationService.getString("ui.service", "");
    String newUserEmail = user.getEmail();
    String to = newUserEmail;
    String headerTo = newUserEmail;
    String replyTo = newUserEmail;

    String content = "";

    if (from != null && newUserEmail != null) {
      /*
       * $userName
       * $localSakaiName
       * $currentUserName
       * $localSakaiUrl
       */
      Map<String, String> replacementValues = new HashMap<String, String>();
      replacementValues.put("userName", user.getDisplayName());
      replacementValues.put(
          "localSakaiName", serverConfigurationService.getString("ui.service", ""));
      replacementValues.put(
          "currentUserName", userDirectoryService.getCurrentUser().getDisplayName());
      replacementValues.put("userEid", user.getEid());
      replacementValues.put("localSakaiUrl", serverConfigurationService.getPortalUrl());
      replacementValues.put("newPassword", newUserPassword);
      replacementValues.put("siteName", siteTitle);
      replacementValues.put("productionSiteName", productionSiteName);
      RenderedTemplate template =
          emailTemplateService.getRenderedTemplateForUser(
              NOTIFY_NEW_USER, user.getReference(), replacementValues);
      if (template == null) return;
      content = template.getRenderedMessage();

      String message_subject = template.getRenderedSubject();
      List<String> headers = new ArrayList<String>();
      headers.add("Precedence: bulk");
      emailService.send(from, to, message_subject, content, headerTo, replyTo, headers);
    }
  }
  /** {@inheritDoc} */
  public void notifyNewUserEmail(User user, String newUserPassword, Site site) {
    ResourceLoader rb = new ResourceLoader("UserNotificationProvider");
    // set the locale to individual receipient's setting
    rb.setContextLocale(rb.getLocale(user.getId()));

    String from = getSetupRequestEmailAddress();
    String productionSiteName = serverConfigurationService.getString("ui.service", "");
    String productionSiteUrl = serverConfigurationService.getPortalUrl();

    String newUserEmail = user.getEmail();
    String to = newUserEmail;
    String headerTo = newUserEmail;
    // UVa: change Reply-To to be the From (collab support) address
    String replyTo = from;
    String message_subject = productionSiteName + " " + rb.getString("java.newusernoti");
    String content = "";

    if (from != null && newUserEmail != null) {
      StringBuilder buf = new StringBuilder();
      buf.setLength(0);

      // email body
      buf.append(user.getDisplayName() + ":\n\n");

      buf.append(
          rb.getString("java.addedto")
              + " "
              + productionSiteName
              + " ("
              + productionSiteUrl
              + ") ");
      buf.append(rb.getString("java.simpleby") + " ");
      buf.append(userDirectoryService.getCurrentUser().getDisplayName() + ". \n\n");
      buf.append(rb.getString("java.passwordis1") + "\n" + newUserPassword + "\n\n");
      buf.append(rb.getString("java.passwordis2") + "\n\n");

      content = buf.toString();
      emailService.send(from, to, message_subject, content, headerTo, replyTo, null);
    }
  }
Пример #25
0
  /**
   * Creates a searchBean
   *
   * @param request The HTTP request
   * @param searchService The search service to use
   * @param siteService the site service
   * @param portalService the portal service
   * @throws IdUnusedException if there is no current worksite
   */
  public SearchBeanImpl(
      HttpServletRequest request,
      SearchService searchService,
      SiteService siteService,
      ToolManager toolManager,
      UserDirectoryService userDirectoryService,
      SecurityService securityService,
      ServerConfigurationService serverConfigurationService)
      throws IdUnusedException {
    this.search = request.getParameter(SEARCH_PARAM);
    this.searchService = searchService;
    this.siteService = siteService;
    this.toolManager = toolManager;
    this.placementId = this.toolManager.getCurrentPlacement().getId();
    this.toolId = this.toolManager.getCurrentTool().getId();
    this.siteId = this.toolManager.getCurrentPlacement().getContext();
    this.serverConfigurationService = serverConfigurationService;
    this.securityService = securityService;
    try {
      this.requestPage = Integer.parseInt(request.getParameter(SEARCH_PAGE));
    } catch (Exception ex) {
      log.debug(ex);
    }
    currentSite = this.siteService.getSite(this.siteId);
    try {
      this.scope = Scope.valueOf(request.getParameter(SEARCH_SCOPE));
    } catch (NullPointerException npe) {
    } catch (IllegalArgumentException iae) {
      log.debug(iae);
      log.warn("Invalid Scope Supplied: " + request.getParameter(SEARCH_SCOPE));
    }

    User user = userDirectoryService.getCurrentUser();
    if (user != null) currentUser = user.getId();

    requestURL = request.getRequestURL().toString();

    // normal or pda portal?
    checkPdaPortal(request);
  }
  /**
   * @see org.sakaiproject.api.common.edu.person.SakaiPersonManager#create(java.lang.String,
   *     java.lang.String, org.sakaiproject.api.common.type.Type)
   */
  public SakaiPerson create(String userId, Type recordType) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("create(String " + userId + ",  Type " + recordType + ")");
    }
    if (userId == null || userId.length() < 1)
      throw new IllegalArgumentException("Illegal agentUuid argument passed!");
    ; // a null uid is valid
    if (!isSupportedType(recordType))
      throw new IllegalArgumentException("Illegal recordType argument passed!");

    SakaiPersonImpl spi = new SakaiPersonImpl();
    persistableHelper.createPersistableFields(spi);
    spi.setUuid(IdManager.createUuid());
    spi.setAgentUuid(userId);
    spi.setUid(userId);
    spi.setTypeUuid(recordType.getUuid());
    spi.setLocked(Boolean.valueOf(false));
    this.getHibernateTemplate().save(spi);

    // log the event
    String ref = getReference(spi);
    eventTrackingService.post(eventTrackingService.newEvent("profile.new", ref, true));

    // do not do this for system profiles
    if (serverConfigurationService.getBoolean("profile.updateUser", false)) {
      try {
        User u = userDirectoryService.getUser(userId);
        spi.setGivenName(u.getFirstName());
        spi.setSurname(u.getLastName());
        spi.setMail(u.getEmail());
      } catch (UserNotDefinedException uue) {
        LOG.error("User " + userId + "doesn't exist");
      }
    }

    LOG.debug("return spi;");
    return spi;
  }
  /** {@inheritDoc} */
  public void notifyTemplateUse(Site templateSite, User currentUser, Site site) {
    // send an email to track who are using the template
    String from = getSetupRequestEmailAddress();
    // send it to the email archive of the template site
    // TODO: need a better way to get the email archive address
    // String domain = from.substring(from.indexOf('@'));
    String templateEmailArchive =
        templateSite.getId() + "@" + serverConfigurationService.getServerName();
    String to = templateEmailArchive;
    String headerTo = templateEmailArchive;
    String replyTo = templateEmailArchive;
    String message_subject = templateSite.getId() + ": copied by " + currentUser.getDisplayId();

    if (from != null && templateEmailArchive != null) {
      StringBuffer buf = new StringBuffer();
      buf.setLength(0);

      // email body
      buf.append("Dear template maintainer,\n\n");
      buf.append("Congratulations!\n\n");
      buf.append("The following user just created a new site based on your template.\n\n");
      buf.append("Template name: " + templateSite.getTitle() + "\n");
      buf.append(
          "User         : "******" ("
              + currentUser.getDisplayId()
              + ")\n");
      buf.append("Date         : " + new java.util.Date() + "\n");
      buf.append("New site Id  : " + site.getId() + "\n");
      buf.append("New site name: " + site.getTitle() + "\n\n");
      buf.append("Cheers,\n");
      buf.append("Alliance Team\n");
      String content = buf.toString();

      emailService.send(from, to, message_subject, content, headerTo, replyTo, null);
    }
  }
Пример #28
0
  public RankImage createRankImageAttachmentObject(String attachId, String name) {
    if (!isRanksEnabled()) {
      LOG.warn("createRankImageAttachmentObject invoked, but ranks are disabled");
      return null;
    }
    try {
      RankImage attach = new RankImageImpl();
      attach.setCreated(new Date());
      attach.setModified(new Date());

      ContentResource cr = contentHostingService.getResource(attachId);

      User creator =
          userDirectoryService.getUser(
              cr.getProperties().getProperty(cr.getProperties().getNamePropCreator()));
      attach.setCreatedBy(creator.getDisplayName());
      User modifier =
          userDirectoryService.getUser(
              cr.getProperties().getProperty(cr.getProperties().getNamePropModifiedBy()));
      attach.setModifiedBy(modifier.getDisplayName());

      attach.setAttachmentSize((Long.valueOf(cr.getContentLength())).toString());
      attach.setAttachmentId(attachId);
      attach.setAttachmentName(name);
      attach.setAttachmentType(cr.getContentType());
      String tempString = cr.getUrl();
      attach.setAttachmentUrl(resourceUrlEscaping(tempString));

      getHibernateTemplate().saveOrUpdate(attach);

      return attach;
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
Пример #29
0
  /**
   * Process that archives the sites
   *
   * @param sites list of SparseSite
   * @throws InterruptedException
   */
  private void archiveSites(
      List<SparseSite> sites, String selectedTerm, Session currentSession, User currentUser)
      throws InterruptedException {

    if (isLocked()) {
      throw new IllegalStateException(
          "Cannot run batch archive, an archive job is already in progress");
    }
    batchArchiveStarted = System.currentTimeMillis();
    batchArchiveMessage =
        rb.getFormattedMessage(
            "archive.batch.term.text.statusmessage.start",
            new Object[] {sites.size(), selectedTerm, 0});
    batchArchiveStatus = "RUNNING";

    log.info(
        "Batch archive started for term: "
            + selectedTerm
            + ". Archiving "
            + sites.size()
            + " sites.");

    Session threadSession = sessionManager.getCurrentSession();
    if (threadSession == null) {
      threadSession = sessionManager.startSession();
    }
    threadSession.setUserId(currentUser.getId());
    threadSession.setActive();
    sessionManager.setCurrentSession(threadSession);
    authzGroupService.refreshUser(currentUser.getId());

    // counters so we can run this in batches if we have a number of sites to process
    int archiveCount = 0;

    try {

      for (SparseSite s : sites) {

        log.info("Processing site: " + s.getTitle());

        // archive the site
        archiveService.archive(s.getId());

        // compress it
        // TODO check return value? do we care?
        try {
          archiveService.archiveAndZip(s.getId());
        } catch (IOException e) {
          e.printStackTrace();
        }

        archiveCount++;

        // update message
        if (archiveCount % 1 == 0) {
          int percentComplete = (int) (archiveCount * 100) / sites.size();
          batchArchiveMessage =
              rb.getFormattedMessage(
                  "archive.batch.term.text.statusmessage.update",
                  new Object[] {sites.size(), selectedTerm, archiveCount, percentComplete});
        }

        // sleep if we need to and keep sessions alive
        if (archiveCount > 0 && archiveCount % NUM_SITES_PER_BATCH == 0) {
          log.info("Sleeping for " + PAUSE_TIME_MS + "ms");
          Thread.sleep(PAUSE_TIME_MS);
          threadSession.setActive();
          currentSession.setActive();
        }

        // check timeout
        if (!isLocked()) {
          throw new RuntimeException("Timeout occurred while running batch archive");
        }
      }

      // complete
      batchArchiveMessage =
          rb.getFormattedMessage(
              "archive.batch.term.text.statusmessage.complete",
              new Object[] {sites.size(), selectedTerm});

      log.info("Batch archive complete.");

    } finally {
      // reset
      batchArchiveStatus = STATUS_COMPLETE;
      batchArchiveStarted = 0;
      threadSession.clear();
      threadSession.invalidate();
    }
  }
Пример #30
0
  protected void processRoster(
      HttpServletRequest request,
      HttpServletResponse response,
      String lti_message_type,
      Site site,
      String siteId,
      String placement_id,
      Properties pitch,
      String user_id,
      Map<String, Object> theMap)
      throws java.io.IOException {
    // Check for permission in placement
    String allowRoster = pitch.getProperty(LTIService.LTI_ALLOWROSTER);
    if (!"on".equals(allowRoster)) {
      doError(
          request,
          response,
          theMap,
          "outcomes.invalid",
          "lti_message_type=" + lti_message_type,
          null);
      return;
    }

    String roleMapProp = pitch.getProperty("rolemap");
    String releaseName = pitch.getProperty(LTIService.LTI_SENDNAME);
    String releaseEmail = pitch.getProperty(LTIService.LTI_SENDEMAILADDR);
    String assignment = pitch.getProperty("assignment");
    String allowOutcomes =
        ServerConfigurationService.getString(
            SakaiBLTIUtil.BASICLTI_OUTCOMES_ENABLED,
            SakaiBLTIUtil.BASICLTI_OUTCOMES_ENABLED_DEFAULT);
    if (!"true".equals(allowOutcomes)) allowOutcomes = null;

    String maintainRole = site.getMaintainRole();

    SakaiBLTIUtil.pushAdvisor();
    boolean success = false;
    try {
      List<Map<String, Object>> lm = new ArrayList<Map<String, Object>>();
      Set<Member> members = site.getMembers();
      Map<String, String> roleMap = SakaiBLTIUtil.convertRoleMapPropToMap(roleMapProp);
      for (Member member : members) {
        Map<String, Object> mm = new TreeMap<String, Object>();
        Role role = member.getRole();
        String ims_user_id = member.getUserId();
        mm.put("/user_id", ims_user_id);
        String ims_role = "Learner";

        // If there is a role mapping, it has precedence over site.update
        if (roleMap.containsKey(role.getId())) {
          ims_role = roleMap.get(role.getId());
        } else if (ComponentManager.get(AuthzGroupService.class)
            .isAllowed(ims_user_id, SiteService.SECURE_UPDATE_SITE, "/site/" + siteId)) {
          ims_role = "Instructor";
        }

        // Using "/role" is inconsistent with to
        // http://developers.imsglobal.org/ext_membership.html. It
        // should be roles. If we can determine that nobody is using
        // the role tag, we should remove it.

        mm.put("/role", ims_role);
        mm.put("/roles", ims_role);
        User user = null;
        if ("true".equals(allowOutcomes) && assignment != null) {
          user = UserDirectoryService.getUser(ims_user_id);
          String placement_secret = pitch.getProperty(LTIService.LTI_PLACEMENTSECRET);
          String result_sourcedid =
              SakaiBLTIUtil.getSourceDID(user, placement_id, placement_secret);
          if (result_sourcedid != null) mm.put("/lis_result_sourcedid", result_sourcedid);
        }

        if ("on".equals(releaseName) || "on".equals(releaseEmail)) {
          if (user == null) user = UserDirectoryService.getUser(ims_user_id);
          if ("on".equals(releaseName)) {
            mm.put("/person_name_given", user.getFirstName());
            mm.put("/person_name_family", user.getLastName());
            mm.put("/person_name_full", user.getDisplayName());
          }
          if ("on".equals(releaseEmail)) {
            mm.put("/person_contact_email_primary", user.getEmail());
            mm.put("/person_sourcedid", user.getEid());
          }
        }

        Collection groups = site.getGroupsWithMember(ims_user_id);

        if (groups.size() > 0) {
          List<Map<String, Object>> lgm = new ArrayList<Map<String, Object>>();
          for (Iterator i = groups.iterator(); i.hasNext(); ) {
            Group group = (Group) i.next();
            Map<String, Object> groupMap = new HashMap<String, Object>();
            groupMap.put("/id", group.getId());
            groupMap.put("/title", group.getTitle());
            groupMap.put("/set", new HashMap(groupMap));
            lgm.add(groupMap);
          }
          mm.put("/groups/group", lgm);
        }

        lm.add(mm);
      }
      theMap.put("/message_response/members/member", lm);
      success = true;
    } catch (Exception e) {
      doError(request, response, theMap, "memberships.fail", "", e);
    } finally {
      SakaiBLTIUtil.popAdvisor();
    }

    if (!success) return;

    theMap.put("/message_response/statusinfo/codemajor", "Success");
    theMap.put("/message_response/statusinfo/severity", "Status");
    theMap.put("/message_response/statusinfo/codeminor", "fullsuccess");
    String theXml = XMLMap.getXML(theMap, true);
    PrintWriter out = response.getWriter();
    out.println(theXml);
    M_log.debug(theXml);
  }