/**
  * Checks if the given user can create/update/delete options
  *
  * @param userRef
  * @param option
  */
 @Deprecated
 private void checkOptionPermission(String userRef, Option option) {
   if (option.getPollId() == null) {
     throw new IllegalArgumentException(
         "Poll Id must be set in the option to check permissions: " + option);
   }
   Long pollId = option.getPollId();
   // validate poll exists
   Poll poll = pollListManager.getPollById(pollId, false);
   if (poll == null) {
     throw new IllegalArgumentException(
         "Invalid poll id (" + pollId + "), could not find poll from option: " + option);
   }
   // check permissions
   String siteRef = "/site/" + poll.getSiteId();
   if (!developerHelperService.isUserAllowedInEntityReference(
       userRef, PollListManager.PERMISSION_ADD, siteRef)) {
     throw new SecurityException(
         "User ("
             + userRef
             + ") is not allowed to create/update/delete options in this poll ("
             + pollId
             + ")");
   }
 }
 /** Note that details is the only optional field */
 public String createEntity(EntityReference ref, Object entity, Map<String, Object> params) {
   Poll poll = (Poll) entity;
   poll.setCreationDate(new Date());
   if (poll.getId() == null) {
     poll.setId(UUID.randomUUID().toString());
   }
   if (poll.getOwner() == null) {
     poll.setOwner(developerHelperService.getCurrentUserId());
   }
   String siteId = developerHelperService.getCurrentLocationId();
   if (poll.getSiteId() == null) {
     poll.setSiteId(siteId);
   } else {
     siteId = poll.getSiteId();
   }
   String userReference = developerHelperService.getCurrentUserReference();
   String location = "/site/" + siteId;
   boolean allowed =
       developerHelperService.isUserAllowedInEntityReference(
           userReference, PollListManager.PERMISSION_ADD, location);
   if (!allowed) {
     throw new SecurityException(
         "Current user ("
             + userReference
             + ") cannot create polls in location ("
             + location
             + ")");
   }
   pollListManager.savePoll(poll);
   return poll.getPollId() + "";
 }
 @Deprecated
 public List<?> getEntities(EntityReference ref, Search search) {
   // get the pollId
   Restriction pollRes = search.getRestrictionByProperty("pollId");
   if (pollRes == null || pollRes.getSingleValue() == null) {
     throw new IllegalArgumentException(
         "Must include a non-null pollId in order to retreive a list of votes");
   }
   Long pollId = null;
   try {
     pollId = developerHelperService.convert(pollRes.getSingleValue(), Long.class);
   } catch (UnsupportedOperationException e) {
     throw new IllegalArgumentException(
         "Invalid: pollId must be a long number: " + e.getMessage(), e);
   }
   // get the poll
   Poll poll = pollListManager.getPollById(pollId);
   if (poll == null) {
     throw new IllegalArgumentException(
         "pollId (" + pollId + ") is invalid and does not match any known polls");
   } else {
     boolean allowedPublic = pollListManager.isPollPublic(poll);
     if (!allowedPublic) {
       String userReference = developerHelperService.getCurrentUserReference();
       if (userReference == null) {
         throw new EntityException(
             "User must be logged in in order to access poll data",
             ref.getId(),
             HttpServletResponse.SC_UNAUTHORIZED);
       } else {
         boolean allowedManage = false;
         boolean allowedVote = false;
         allowedManage =
             developerHelperService.isUserAllowedInEntityReference(
                 userReference, PollListManager.PERMISSION_ADD, "/site/" + poll.getSiteId());
         allowedVote =
             developerHelperService.isUserAllowedInEntityReference(
                 userReference, PollListManager.PERMISSION_VOTE, "/site/" + poll.getSiteId());
         if (!(allowedManage || allowedVote)) {
           throw new SecurityException(
               "User (" + userReference + ") not allowed to access poll data: " + ref);
         }
       }
     }
   }
   // get the options
   List<Option> options = pollListManager.getOptionsForPoll(pollId);
   return options;
 }
  public void interceptActionResult(
      ARIResult result, ViewParameters incoming, Object actionReturn) {
    // OptionViewParameters outgoing = (OptionViewParameters) result.resultingView;
    // SAK-14726 : Start BugFix
    if (LOG.isDebugEnabled() && actionReturn != null) {
      LOG.debug("actionReturn is of type " + actionReturn.getClass());
    }

    if (actionReturn == null) {
      return;
    }

    Poll poll = null;

    if (actionReturn instanceof org.sakaiproject.poll.model.Poll) {
      poll = (Poll) actionReturn;
    } else {

      PollViewParameters ecvp = (PollViewParameters) incoming;

      if (null == ecvp || null == ecvp.id || "New 0".equals(ecvp.id)) {
        return;

      } else {

        poll = pollListManager.getPollById(Long.valueOf(ecvp.id));
      }
    }
    // SAK-14726 : End BugFix

    if (poll == null) {
      return;
    }

    LOG.debug("Action result got poll: " + poll.getPollId());
    LOG.debug("resulting view is: " + result.resultingView);

    if (poll.getPollOptions() == null || poll.getPollOptions().size() == 0) {
      result.resultingView =
          new OptionViewParameters(PollOptionProducer.VIEW_ID, null, poll.getPollId().toString());
    } else {
      result.resultingView = new SimpleViewParameters(PollToolProducer.VIEW_ID);
    }

    // if (poll != null && outgoing.id == null) {
    //  outgoing.id = poll.getId().toString();
    // }
  }
 public void updateEntity(EntityReference ref, Object entity, Map<String, Object> params) {
   String id = ref.getId();
   if (id == null) {
     throw new IllegalArgumentException(
         "The reference must include an id for updates (id is currently null)");
   }
   String userReference = developerHelperService.getCurrentUserReference();
   if (userReference == null) {
     throw new SecurityException("anonymous user cannot update poll: " + ref);
   }
   Poll current = getPollById(id);
   if (current == null) {
     throw new IllegalArgumentException("No poll found to update for the given reference: " + ref);
   }
   Poll poll = (Poll) entity;
   String siteId = developerHelperService.getCurrentLocationId();
   if (poll.getSiteId() == null) {
     poll.setSiteId(siteId);
   } else {
     siteId = poll.getSiteId();
   }
   String location = "/site/" + siteId;
   // should this check a different permission?
   boolean allowed =
       developerHelperService.isUserAllowedInEntityReference(
           userReference, PollListManager.PERMISSION_ADD, location);
   if (!allowed) {
     throw new SecurityException(
         "Current user ("
             + userReference
             + ") cannot update polls in location ("
             + location
             + ")");
   }
   developerHelperService.copyBean(
       poll,
       current,
       0,
       new String[] {
         "id", "pollId", "owner", "siteId", "creationDate", "reference", "url", "properties"
       },
       true);
   pollListManager.savePoll(current);
 }
  public void fillComponents(
      UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {

    String currentuserid = externalLogic.getCurrentUserId();

    PollViewParameters ecvp = (PollViewParameters) viewparams;
    Poll poll = null;
    boolean isNew = true;

    UIForm newPoll = UIForm.make(tofill, "add-poll-form");
    LOG.debug("Poll of id: " + ecvp.id);
    if (ecvp.id == null || "New 0".equals(ecvp.id)) {
      UIMessage.make(tofill, "new_poll_title", "new_poll_title");
      // build an empty poll
      LOG.debug("this is a new poll");
      poll = new Poll();
    } else {
      UIMessage.make(tofill, "new_poll_title", "new_poll_title_edit");

      String strId = ecvp.id;
      LOG.debug("got id of " + strId);
      poll = pollListManager.getPollById(Long.valueOf(strId));
      voteBean.setPoll(poll);
      newPoll.parameters.add(new UIELBinding("#{poll.pollId}", poll.getPollId()));

      isNew = false;
    }

    if (!externalLogic.isUserAdmin()
        && !externalLogic.isAllowedInLocation(
            PollListManager.PERMISSION_ADD,
            externalLogic.getCurrentLocationReference(),
            externalLogic.getCurrentuserReference())) {
      tml.addMessage(new TargettedMessage("new_poll_noperms"));
      return;
    }

    // only display for exisiting polls
    if (!isNew) {
      // fill the options list
      UIBranchContainer actionBlock = UIBranchContainer.make(newPoll, "option-headers:");
      UIMessage.make(actionBlock, "options-title", "new_poll_option_title");
      UIInternalLink.make(
          actionBlock,
          "option-add",
          UIMessage.make("new_poll_option_add"),
          new OptionViewParameters(PollOptionProducer.VIEW_ID, null, poll.getPollId().toString()));

      List<Vote> votes = pollVoteManager.getAllVotesForPoll(poll);
      if (votes != null && votes.size() > 0) {
        LOG.debug("Poll has " + votes.size() + " votes");
        UIBranchContainer errorRow = UIBranchContainer.make(tofill, "error-row:", "0");
        UIMessage.make(errorRow, "error", "warn_poll_has_votes");
      }

      List<Option> options = pollListManager.getVisibleOptionsForPoll(poll.getPollId());
      for (int i = 0; i < options.size(); i++) {
        Option o = (Option) options.get(i);
        UIBranchContainer oRow =
            UIBranchContainer.make(actionBlock, "options-row:", o.getOptionId().toString());
        UIVerbatim.make(oRow, "options-name", o.getOptionText());

        UIInternalLink editOption =
            UIInternalLink.make(
                oRow,
                "option-edit",
                UIMessage.make("new_poll_option_edit"),
                new OptionViewParameters(PollOptionProducer.VIEW_ID, o.getOptionId().toString()));

        editOption.decorators =
            new DecoratorList(
                new UITooltipDecorator(
                    messageLocator.getMessage("new_poll_option_edit")
                        + ":"
                        + FormattedText.convertFormattedTextToPlaintext(o.getOptionText())));

        UIInternalLink deleteOption =
            UIInternalLink.make(
                oRow,
                "option-delete",
                UIMessage.make("new_poll_option_delete"),
                new OptionViewParameters(
                    PollOptionDeleteProducer.VIEW_ID, o.getOptionId().toString()));

        deleteOption.decorators =
            new DecoratorList(
                new UITooltipDecorator(
                    messageLocator.getMessage("new_poll_option_delete")
                        + ":"
                        + FormattedText.convertFormattedTextToPlaintext(o.getOptionText())));
      }
    }

    UIMessage.make(tofill, "new-poll-descr", "new_poll_title");
    UIMessage.make(tofill, "new-poll-question-label", "new_poll_question_label");
    UIMessage pollDescr = UIMessage.make(tofill, "new-poll-descr-label", "new_poll_descr_label");
    UIMessage.make(tofill, "new-poll-descr-label2", "new_poll_descr_label2");

    // UIMessage.make(tofill, "new-poll-open-label", "new_poll_open_label");
    // UIMessage.make(tofill, "new-poll-close-label", "new_poll_close_label");

    UIMessage.make(tofill, "new-poll-limits", "new_poll_limits");
    // UIMessage pollMin = UIMessage.make(tofill, "new-poll-min-limits", "new_poll_min_limits");
    // UIMessage pollMax =  UIMessage.make(tofill, "new-poll-max-limits", "new_poll_max_limits");

    // the form fields
    UIInput.make(newPoll, "new-poll-text", "#{poll.text}", poll.getText());

    if (!externalLogic.isMobileBrowser()) {
      // show WYSIWYG editor
      UIInput itemDescr =
          UIInput.make(
              newPoll,
              "newpolldescr:",
              "#{poll.details}",
              poll.getDetails()); // $NON-NLS-1$ //$NON-NLS-2$
      richTextEvolver.evolveTextInput(itemDescr);
      UILabelTargetDecorator.targetLabel(pollDescr, itemDescr);
    } else {
      // do not show WYSIWYG editor in the mobile view
      UIInput itemDescr =
          UIInput.make(
              newPoll,
              "newpolldescr_mobile",
              "#{poll.details}",
              poll.getDetails()); // $NON-NLS-1$ //$NON-NLS-2$
      UILabelTargetDecorator.targetLabel(pollDescr, itemDescr);
    }

    UIInput voteOpen =
        UIInput.make(newPoll, "openDate-iso8601", "poll.voteOpenStr", poll.getVoteOpenStr());
    UIInput voteClose =
        UIInput.make(newPoll, "closeDate-iso8601", "poll.voteCloseStr", poll.getVoteCloseStr());
    // UILabelTargetDecorator.targetLabel(pollOpen, voteOpen);
    // UILabelTargetDecorator.targetLabel(pollClose, voteClose);

    /*
     * access options
     */
    UIMessage pollAccessLabel =
        UIMessage.make(newPoll, "poll_access_label", "new_poll_access_label");
    UIBoundBoolean accessPublic =
        UIBoundBoolean.make(newPoll, "access-public", "poll.isPublic", poll.getIsPublic());
    UIMessage newPollAccessPublicLabel =
        UIMessage.make(newPoll, "new_poll_access_public_label", "new_poll_access_public");

    // SAK-25399: Do not display the public access by default
    if (!externalLogic.isShowPublicAccess()) {
      newPoll.remove(pollAccessLabel);
      newPoll.remove(accessPublic);
      newPoll.remove(newPollAccessPublicLabel);
    }

    String[] minVotes =
        new String[] {
          "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"
        };
    String[] maxVotes =
        new String[] {
          "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"
        };
    UISelect min =
        UISelect.make(
            newPoll,
            "min-votes",
            minVotes,
            "#{poll.minOptions}",
            Integer.toString(poll.getMinOptions()));
    UISelect max =
        UISelect.make(
            newPoll,
            "max-votes",
            maxVotes,
            "#{poll.maxOptions}",
            Integer.toString(poll.getMaxOptions()));

    /*
     * 	open - can be viewd at any time
     * 	never - not diplayed
     * 	afterVoting - after user has voted
     * 	afterClosing
     *
     */

    String[] values = new String[] {"open", "afterVoting", "afterClosing", "never"};
    String[] labels =
        new String[] {
          messageLocator.getMessage("new_poll_open"),
          messageLocator.getMessage("new_poll_aftervoting"),
          messageLocator.getMessage("new_poll_afterClosing"),
          messageLocator.getMessage("new_poll_never")
        };

    UISelect radioselect =
        UISelect.make(
            newPoll, "release-select", values, "#{poll.displayResult}", poll.getDisplayResult());

    radioselect.optionnames = UIOutputMany.make(labels);

    String selectID = radioselect.getFullID();
    // StringList optList = new StringList();
    UIMessage.make(newPoll, "add_results_label", "new_poll_results_label");
    for (int i = 0; i < values.length; ++i) {

      UIBranchContainer radiobranch =
          UIBranchContainer.make(newPoll, "releaserow:", Integer.toString(i));
      UISelectChoice choice = UISelectChoice.make(radiobranch, "release", selectID, i);
      UISelectLabel lb = UISelectLabel.make(radiobranch, "releaseLabel", selectID, i);
      UILabelTargetDecorator.targetLabel(lb, choice);
    }

    LOG.debug("About to close the form");
    newPoll.parameters.add(new UIELBinding("#{poll.owner}", currentuserid));
    String siteId = externalLogic.getCurrentLocationId();
    newPoll.parameters.add(new UIELBinding("#{poll.siteId}", siteId));

    if (isNew || poll.getPollOptions() == null || poll.getPollOptions().size() == 0) {
      UICommand.make(
          newPoll,
          "submit-new-poll",
          UIMessage.make("new_poll_saveoption"),
          "#{pollToolBean.processActionAdd}");
    } else {
      UICommand.make(
          newPoll,
          "submit-new-poll",
          UIMessage.make("new_poll_submit"),
          "#{pollToolBean.processActionAdd}");
    }

    UICommand cancel =
        UICommand.make(
            newPoll, "cancel", UIMessage.make("new_poll_cancel"), "#{pollToolBean.cancel}");
    cancel.parameters.add(new UIELBinding("#{voteCollection.submissionStatus}", "cancel"));
    LOG.debug("Finished generating view");
  }
 public List<?> getEntities(EntityReference ref, Search search) {
   System.out.println("get entities");
   // get the setting which indicates if we are getting polls we can admin or polls we can take
   boolean adminControl = false;
   Restriction adminRes = search.getRestrictionByProperty("admin");
   if (adminRes != null) {
     adminControl = developerHelperService.convert(adminRes.getSingleValue(), boolean.class);
   }
   // get the location (if set)
   Restriction locRes =
       search.getRestrictionByProperty(
           CollectionResolvable
               .SEARCH_LOCATION_REFERENCE); // requestStorage.getStoredValueAsType(String.class,
   // "siteId");
   String[] siteIds = null;
   if (locRes != null) {
     String siteId = developerHelperService.getLocationIdFromRef(locRes.getStringValue());
     siteIds = new String[] {siteId};
   }
   // get the user (if set)
   Restriction userRes =
       search.getRestrictionByProperty(CollectionResolvable.SEARCH_USER_REFERENCE);
   String userId = null;
   if (userRes != null) {
     String currentUser = developerHelperService.getCurrentUserReference();
     String userReference = userRes.getStringValue();
     if (userReference == null) {
       throw new IllegalArgumentException(
           "Invalid request: Cannot limit polls by user when the value is null");
     }
     if (userReference.equals(currentUser) || developerHelperService.isUserAdmin(currentUser)) {
       userId =
           developerHelperService.getUserIdFromRef(
               userReference); // requestStorage.getStoredValueAsType(String.class, "userId");
     } else {
       throw new SecurityException(
           "Only the admin can get polls for other users, you requested polls for: "
               + userReference);
     }
   } else {
     userId = developerHelperService.getCurrentUserId();
     if (userId == null) {
       throw new EntityException(
           "No user is currently logged in so no polls data can be retrieved",
           ref.getId(),
           HttpServletResponse.SC_UNAUTHORIZED);
     }
   }
   String perm = PollListManager.PERMISSION_VOTE;
   if (adminControl) {
     perm = PollListManager.PERMISSION_ADD;
   }
   List<Poll> polls =
       pollListManager.findAllPollsForUserAndSitesAndPermission(userId, siteIds, perm);
   if (adminControl) {
     // add in options
     for (Poll p : polls) {
       List<Option> options = pollListManager.getOptionsForPoll(p.getPollId());
       p.setOptions(options);
     }
   } else {
     // add in the indicators that this user has replied
     Long[] pollIds = new Long[polls.size()];
     for (int i = 0; i < polls.size(); i++) {
       pollIds[i] = polls.get(i).getPollId();
     }
     Map<Long, List<Vote>> voteMap = pollVoteManager.getVotesForUser(userId, pollIds);
     for (Poll poll : polls) {
       Long pollId = poll.getPollId();
       List<Vote> l = voteMap.get(pollId);
       if (l != null) {
         poll.setCurrentUserVoted(true);
         poll.setCurrentUserVotes(l);
       } else {
         poll.setCurrentUserVoted(false);
       }
     }
   }
   return polls;
 }
  public Object getEntity(EntityReference ref) {
    String id = ref.getId();
    if (id == null) {
      return new Poll();
    }
    Poll poll = getPollById(id);
    if (poll == null) {
      throw new IllegalArgumentException("No poll found for the given reference: " + ref);
    }
    Long pollId = poll.getPollId();
    String currentUserId = developerHelperService.getCurrentUserId();

    boolean allowedManage = false;
    if (!developerHelperService.isEntityRequestInternal(ref + "")) {
      if (!pollListManager.isPollPublic(poll)) {
        // this is not a public poll? (ie .anon role has poll.vote)
        String userReference = developerHelperService.getCurrentUserReference();
        if (userReference == null) {
          throw new EntityException(
              "User must be logged in in order to access poll data",
              ref.getId(),
              HttpServletResponse.SC_UNAUTHORIZED);
        }
        allowedManage =
            developerHelperService.isUserAllowedInEntityReference(
                userReference, PollListManager.PERMISSION_ADD, "/site/" + poll.getSiteId());
        boolean allowedVote =
            developerHelperService.isUserAllowedInEntityReference(
                userReference, PollListManager.PERMISSION_VOTE, "/site/" + poll.getSiteId());
        if (!allowedManage && !allowedVote) {
          throw new SecurityException(
              "User (" + userReference + ") not allowed to access poll data: " + ref);
        }
      }
    }

    Boolean includeVotes = requestStorage.getStoredValueAsType(Boolean.class, "includeVotes");
    if (includeVotes == null) {
      includeVotes = false;
    }
    if (includeVotes) {
      List<Vote> votes = pollVoteManager.getAllVotesForPoll(poll);
      poll.setVotes(votes);
    }
    Boolean includeOptions = requestStorage.getStoredValueAsType(Boolean.class, "includeOptions");
    if (includeOptions == null) {
      includeOptions = false;
    }
    if (includeOptions) {
      List<Option> options = pollListManager.getOptionsForPoll(poll);
      poll.setOptions(options);
    }
    // add in the indicator that this user has replied
    if (currentUserId != null) {
      Map<Long, List<Vote>> voteMap =
          pollVoteManager.getVotesForUser(currentUserId, new Long[] {pollId});
      List<Vote> l = voteMap.get(pollId);
      if (l != null) {
        poll.setCurrentUserVoted(true);
        poll.setCurrentUserVotes(l);
      } else {
        poll.setCurrentUserVoted(false);
      }
    }
    return poll;
  }