示例#1
0
  def _constructFilterForProjectSelection(self, survey, params):
    """Returns the filter needed for the Project selection view.

    Returns a filter for all the valid projects for which the current user
    is a student. Of course only in the survey's scope.

    Args:
      survey: a Survey entity
      params: the params dict for the requesting view

    Returns:
      Dictionary that can be used as a input for a query.
    """

    from soc.modules.gsoc.logic.models.student import logic as \
        student_logic

    survey_logic = params['logic']

    user_entity = user_logic.getCurrentUser()

    # get the student entity for the current user and program
    fields = {'user': user_entity,
              'scope': survey_logic.getScope(survey),
              'status': 'active'}

    student_entity = student_logic.getForFields(fields, unique=True)

    fields = {'student': student_entity,
              'status': 'accepted'}

    return fields
示例#2
0
    def render(self, name, value, attrs=None):
        """Render TinyMCE widget as HTML.
    """

        from soc.logic.models.user import logic as user_logic

        user = user_logic.getCurrentUser()

        if user and user.disable_tinymce:
            return super(FullTinyMCE, self).render(name, value, attrs)

        if value is None:
            value = ""
        value = encoding.smart_unicode(value)
        final_attrs = self.build_attrs(attrs, name=name)

        self.mce_settings["elements"] = "id_%s" % name

        # convert mce_settings from dict to JSON
        mce_json = simplejson.JSONEncoder().encode(self.mce_settings)

        return safestring.mark_safe(
            self.TINY_MCE_HTML_FMT
            % {"attrs": widgets.flatatt(final_attrs), "value": html.escape(value), "settings_json": mce_json}
        )
示例#3
0
    def listProjects(self,
                     request,
                     access_type,
                     page_name=None,
                     params=None,
                     **kwargs):
        """View that lists all of the current user's Student Projects for the
    Program given as Scope.
    """

        from soc.modules.gsoc.views.models import student_project as project_view

        user_entity = user_logic.getCurrentUser()

        # pylint: disable=E1103
        fields = {
            'link_id': user_entity.link_id,
            'scope_path': kwargs['scope_path']
        }

        try:
            student_entity = student_logic.getFromKeyFieldsOr404(fields)
        except out_of_band.Error, error:
            return responses.errorResponse(error,
                                           request,
                                           template=params['error_public'])
示例#4
0
  def _constructFilterForProjectSelection(self, survey, params):
    """Returns the filter needed for the Project selection view.

    Constructs a filter that returns all valid projects for which the current
    user is the mentor. Only for the projects in the program given by the
    survey's scope of course.

    For args see project_survey.View._constructFilterForProjectSelection().
    """

    from soc.modules.gsoc.logic.models.mentor import logic as mentor_logic

    survey_logic = params['logic']

    user_entity = user_logic.getCurrentUser()

    # get the mentor entities for the current user and program
    fields = {'user': user_entity,
              'program': survey_logic.getScope(survey),
              'status': 'active'}

    mentor_entities = mentor_logic.getForFields(fields)

    # TODO: Ensure that this doesn't break when someone is a mentor for
    # a lot of organizations.

    fields = {'mentor': mentor_entities,
              'status': 'accepted'}

    return fields
示例#5
0
  def getRolesListData(self, request, lists_params):
    """Returns the list data for roles.
    """

    user = user_logic.getCurrentUser()

    # only select the roles for the current user
    # pylint: disable=E1103
    fields = {
        'link_id': user.link_id,
        'status': ['active', 'inactive']
        }

    idx = lists.getListIndex(request)

    if not 0 <= idx < len(lists_params):
      return lists.getErrorResponse(request, 'idx not valid')

    list_params = lists_params[idx]

    if list_params is None:
      return lists.getErrorResponse(
          request, 'idx not valid (list not in roles overview)')

    contents = helper.lists.getListData(request, list_params, fields)

    return lists.getResponse(request, contents)
示例#6
0
def sendInviteNotification(entity):
  """Sends out an invite notification to the user the request is for.

  Args:
    entity : A request containing the information needed to create the message
  """

  from soc.logic.models.user import logic as user_logic
  from soc.views.models.role import ROLE_VIEWS

  invitation_url = 'http://%(host)s%(index)s' % {
      'host' : system.getHostname(),
      'index': redirects.getInviteProcessRedirect(entity, None),
      }

  role_params = ROLE_VIEWS[entity.role].getParams()

  message_properties = {
      'role_verbose' : role_params['name'],
      'group': entity.group.name,
      'invitation_url': invitation_url,
      }

  subject = DEF_INVITATION_MSG_FMT % {
      'role_verbose' : role_params['name'],
      'group' : entity.group.name
      }

  template = DEF_GROUP_INVITE_NOTIFICATION_TEMPLATE

  from_user = user_logic.getCurrentUser()

  sendNotification(entity.user, from_user, message_properties, subject, template)
示例#7
0
    def list(self,
             request,
             access_type,
             page_name=None,
             params=None,
             filter=None,
             order=None,
             **kwargs):
        """Lists all notifications that the current logged in user has stored.

    for parameters see base.list()
    """

        if request.method == 'POST':
            return self.listPost(request, params, **kwargs)
        else:  # request.method == 'GET'
            if not order:
                order = ['-created_on']
            user_entity = user_logic.getCurrentUser()
            filter = {'scope': user_entity}
            return super(View, self).list(request,
                                          access_type,
                                          page_name=page_name,
                                          params=params,
                                          filter=filter,
                                          order=order,
                                          **kwargs)
示例#8
0
  def getRequestsListData(self, request, uh_params, ar_params):
    """Returns the list data for getRequestsList.
    """

    idx = lists.getListIndex(request)

    # get the current user
    user_entity = user_logic.getCurrentUser()

    # only select the Invites for this user that haven't been handled yet
    # pylint: disable=E1103
    filter = {'user': user_entity}

    if idx == 0:
      filter['status'] = 'group_accepted'
      params = uh_params
    elif idx == 1:
      filter['status'] = 'new'
      params = ar_params
    else:
      return lists.getErrorResponse(request, "idx not valid")

    contents = helper.lists.getListData(request, params, filter,
                                        visibility='public')

    return lists.getResponse(request, contents)
示例#9
0
  def _getResultsViewRecordFields(self, survey, allowed_to_read):
    """Get the Results View filter for ProjectSurveyRecords.

    For args see survey.View()._getResultsViewRecordFields()

    Returns:
      Returns the dictionary containing the fields to filter on
    """

    from soc.modules.gsoc.logic.models.mentor import logic as mentor_logic
    from soc.modules.gsoc.logic.models.org_admin import logic as \
        org_admin_logic

    if allowed_to_read:
      return super(View, self)._getResultsViewRecordFields(survey,
                                                           allowed_to_read)

    fields = {'survey': survey}

    user_entity = user_logic.getCurrentUser()
    program_entity = survey.scope

    role_fields = {'user': user_entity,
                   'program': program_entity,
                   'status': ['active', 'inactive']}

    org_admins = org_admin_logic.getForFields(role_fields)
    mentors = mentor_logic.getForFields(role_fields)

    organizations = {}

    if org_admins:
      for org_admin in org_admins:
        # for each org admin store the organization
        org_scope = org_admin.scope
        org_key_name = org_scope.key().id_or_name()
        organizations[org_key_name] = org_scope

    if mentors:
      for mentor in mentors:
        # for each mentor store the organization
        # This will allow the user to view the GradingProjectSurvey Records
        # listing for projects which he might have no further access to.
        org_scope = mentor.scope
        org_key_name = org_scope.key().id_or_name()
        organizations[org_key_name] = org_scope

    if organizations:
      # filter on all the found organizations
      fields['org'] = organizations.values()
    else:
      # This user is no org admin or mentor and should only see
      # his/her own records.
      fields['user'] = user_entity

    return fields
示例#10
0
  def listTasks(self, request, access_type, page_name=None, params=None,
                **kwargs):
    """View where all the tasks can be searched from.
    """

    from soc.modules.gci.views.models.task import view as task_view

    logic = params['logic']

    program_entity = logic.getFromKeyFieldsOr404(kwargs)

    page_name = '%s %s' % (page_name, program_entity.name)

    list_params = task_view.getParams().copy()

    user_account = user_logic.getCurrentUser()
    user_fields = {
        'user': user_account,
        'status': 'active'
        }

    host_entity = host_logic.getForFields(user_fields, unique=True)

    tasks_filter = {
        'program': program_entity,
        'status': ['Open', 'Reopened', 'ClaimRequested']
    }

    if host_entity:
      list_params['list_description'] = self.DEF_LIST_VALID_TASKS_MSG_FMT % (
          program_entity.name)
      tasks_filter['status'].extend([
          'Claimed', 'ActionNeeded', 'Closed', 'AwaitingRegistration',
          'NeedsWork', 'NeedsReview','Unapproved', 'Unpublished'])
    else:
      list_params.setdefault('public_field_ignore', []).append('mentors')
      list_params['list_description'] = self.DEF_LIST_PUBLIC_TASKS_MSG_FMT % (
          program_entity.name)

    list_params['public_row_extra'] = lambda entity, *args: {
        'link': redirects.getPublicRedirect(entity, list_params)
        }

    list_params['public_conf_min_num'] = list_params['public_conf_limit'] = 100

    if lists.isDataRequest(request):
        return self.getListTasksData(request, list_params, tasks_filter)

    contents = []
    order = ['-modified_on']

    tasks_list = lists.getListGenerator(request, list_params,
                                        order=order, idx=0)
    contents.append(tasks_list)

    return self._list(request, list_params, contents, page_name)
示例#11
0
 def createCurrentUser(self):
   """Create the current user.
   """
   properties = {
       'account': users.get_current_user(),
       'link_id': 'current_user',
       'name': 'Current User',
       }
   current_user = user_logic.updateOrCreateFromFields(properties)
   entity = user_logic.getCurrentUser()
   return entity
示例#12
0
    def _editPost(self, request, entity, fields):
        """See base.View._editPost().
    """

        # get the current user
        current_user = user_logic.getCurrentUser()

        fields['link_id'] = 't%i' % (int(time.time() * 100))
        fields['scope'] = fields['to_user']
        fields['from_user'] = current_user
        fields['scope_path'] = fields['to_user'].link_id
示例#13
0
  def _editPost(self, request, entity, fields):
    """See base.View._editPost().
    """

    # get the current user
    current_user = user_logic.getCurrentUser()

    fields['link_id'] = 't%i' % (int(time.time()*100))
    fields['scope'] = fields['to_user']
    fields['from_user'] = current_user
    fields['scope_path'] = fields['to_user'].link_id
示例#14
0
 def createCurrentUser(self):
     """Create the current user.
 """
     properties = {
         'account': users.get_current_user(),
         'link_id': 'current_user',
         'name': 'Current User',
     }
     current_user = user_logic.updateOrCreateFromFields(properties)
     entity = user_logic.getCurrentUser()
     return entity
示例#15
0
  def _getResultsViewRecordFields(self, survey, allowed_to_read):
    """Get the Results View filter for ProjectSurveyRecords.

    For args see survey.View()._getResultsViewRecordFields()

    Returns:
      Returns the dictionary containing the fields to filter on
    """

    from soc.modules.gsoc.logic.models.org_admin import logic as \
        org_admin_logic
    from soc.modules.gsoc.logic.models.student import logic as \
        student_logic

    if allowed_to_read:
      return super(View, self)._getResultsViewRecordFields(survey,
                                                           allowed_to_read)

    fields = {'survey': survey}

    program_entity = survey.scope
    user_entity = user_logic.getCurrentUser()

    student_fields = {'scope': program_entity,
                      'user': user_entity,
                      'status': ['active', 'inactive']}
    student_entity = student_logic.getForFields(student_fields, unique=True)

    if student_entity:
      # just get all records for the current user
      fields['user'] = user_entity
      return fields

    org_admin_fields = {'user': user_entity,
                        'program': program_entity,
                        'status': ['active', 'inactive']}

    org_admins = org_admin_logic.getForFields(org_admin_fields)

    if org_admins:
      # filter on all the organizations this user is org admin for
      organizations = []

      for org_admin in org_admins:
        organizations.append(org_admin.scope)

      # TODO: this might blow up if the user is org admin for too many orgs
      fields['org'] = organizations

    if not student_entity and not org_admins:
      # return only the surveys for the current user
      fields['user'] = user_entity

    return fields
示例#16
0
    def listMyTasks(self,
                    request,
                    access_type,
                    page_name=None,
                    params=None,
                    **kwargs):
        """Displays a list of all starred tasks for the current user.

    If the current user is a student it also lists all tasks claimed by them.

    See base.View.list() for more details.
    """
        from soc.modules.gci.views.models import task as gci_task_view
        from soc.modules.gci.views.models import task_subscription as \
            gci_subscription_view

        program = gci_program_logic.logic.getFromKeyFieldsOr404(kwargs)
        user = user_logic.getCurrentUser()

        task_params = gci_task_view.view.getParams().copy()
        task_params['list_description'] = ugettext(
            'Tasks that you have claimed.')

        subscription_params = gci_subscription_view.view.getParams().copy()
        subscription_params['list_description'] = ugettext(
            'Tasks that you have starred.')

        if lists.isDataRequest(request):
            return self.getListMyTasksData(request, task_params,
                                           subscription_params, program, user)

        contents = []

        fields = {
            'user': user,
            'status': ['active', 'inactive'],
        }
        if gci_student_logic.logic.getForFields(fields, unique=True):
            order = ['modified_on']
            tasks_list = lists.getListGenerator(request,
                                                task_params,
                                                order=order,
                                                idx=0)
            contents.append(tasks_list)

        starred_tasks_list = lists.getListGenerator(request,
                                                    subscription_params,
                                                    idx=1)
        contents.append(starred_tasks_list)

        return self._list(request, task_params, contents, page_name)
示例#17
0
    def _editPost(self, request, entity, fields):
        """See base.View._editPost().
    """

        user = user_logic.getCurrentUser()

        if not entity:
            fields['author'] = user
        else:
            fields['author'] = entity.author

        fields['modified_by'] = user

        super(View, self)._editPost(request, entity, fields)
示例#18
0
  def _editPost(self, request, entity, fields):
    """See base.View._editPost().
    """

    user = user_logic.getCurrentUser()

    if not entity:
      fields['author'] = user
    else:
      fields['author'] = entity.author

    fields['modified_by'] = user

    super(View, self)._editPost(request, entity, fields)
示例#19
0
  def _editPost(self, request, entity, fields):
    """See base.View._editPost().

    Processes POST request items to add new dynamic field names,
    question types, and default prompt values to SurveyContent model.
    """

    user = user_logic.getCurrentUser()
    schema = {}
    survey_fields = {}

    if not entity:
      # new Survey
      if 'serialized' in request.POST:
        fields, schema, survey_fields = self.importSerialized(request, fields,
                                                              user)
      fields['author'] = user
    else:
      fields['author'] = entity.author
      schema = self.loadSurveyContent(schema, survey_fields, entity)

    # remove deleted properties from the model
    self.deleteQuestions(schema, survey_fields, request.POST)

    # add new text questions and re-build choice questions
    self.getRequestQuestions(schema, survey_fields, request.POST)

    # get schema options for choice questions
    self.getSchemaOptions(schema, survey_fields, request.POST)

    survey_content = getattr(entity,'survey_content', None)
    # create or update a SurveyContent for this Survey
    survey_content = survey_logic.createSurvey(survey_fields, schema,
                                                survey_content=survey_content)

    # save survey_content for existent survey or pass for creating a new one
    if entity:
      entity.modified_by = user
      entity.survey_content = survey_content
      db.put(entity)
    else:
      fields['survey_content'] = survey_content

    fields['modified_by'] = user

    super(View, self)._editPost(request, entity, fields)
示例#20
0
  def list(self, request, access_type, page_name=None, params=None,
           filter=None, order=None, **kwargs):
    """Lists all notifications that the current logged in user has stored.

    for parameters see base.list()
    """

    if request.method == 'POST':
      return self.listPost(request, params, **kwargs)
    else: # request.method == 'GET'
      if not order:
        order = ['-created_on']
      user_entity = user_logic.getCurrentUser()
      filter = {'scope': user_entity}
      return super(View, self).list(request, access_type, page_name=page_name,
                                    params=params, filter=filter, order=order,
                                    **kwargs)
示例#21
0
    def _editPost(self, request, entity, fields):
        """See base.View._editPost().

    Processes POST request items to add new dynamic field names,
    question types, and default prompt values to SurveyContent model.
    """

        user = user_logic.getCurrentUser()
        schema = {}
        survey_fields = {}

        if not entity:
            # new Survey
            if 'serialized' in request.POST:
                fields, schema, survey_fields = self.importSerialized(
                    request, fields, user)
            fields['author'] = user
        else:
            fields['author'] = entity.author
            schema = self.loadSurveyContent(schema, survey_fields, entity)

        # remove deleted properties from the model
        self.deleteQuestions(schema, survey_fields, request.POST)

        # add new text questions and re-build choice questions
        self.getRequestQuestions(schema, survey_fields, request.POST)

        # get schema options for choice questions
        self.getSchemaOptions(schema, survey_fields, request.POST)

        survey_content = getattr(entity, 'survey_content', None)
        # create or update a SurveyContent for this Survey
        survey_content = survey_logic.createSurvey(
            survey_fields, schema, survey_content=survey_content)

        # save survey_content for existent survey or pass for creating a new one
        if entity:
            entity.modified_by = user
            entity.survey_content = survey_content
            db.put(entity)
        else:
            fields['survey_content'] = survey_content

        fields['modified_by'] = user

        super(View, self)._editPost(request, entity, fields)
示例#22
0
    def listPost(self, request, params, **kwargs):
        """Handles the POST request for the list of notifications.
    """

        import logging

        from django.utils import simplejson

        post_dict = request.POST

        data = simplejson.loads(post_dict.get('data', '[]'))
        button_id = post_dict.get('button_id', '')

        user_entity = user_logic.getCurrentUser()

        notifications = []
        for selection in data:
            notification = notification_logic.getFromKeyName(selection['key'])

            if not notification:
                logging.error('No notification found for %(key)s' % selection)
                continue

            if notification.scope.key() == user_entity.key():
                notifications.append(notification)

        if button_id == 'delete':
            for notification in notifications:
                notification_logic.delete(notification)
        elif button_id == 'mark_read' or button_id == 'mark_unread':
            if button_id == 'mark_read':
                # mark all the Notifications selected as read
                fields = {'unread': False}
            elif button_id == 'mark_unread':
                # mark all the Notifications selected as unread
                fields = {'unread': True}

            for notification in notifications:
                notification_logic.updateEntityProperties(notification,
                                                          fields,
                                                          store=False)
            db.put(notifications)

        # return a 200 response to signal that all is okay
        return http.HttpResponseRedirect('')
示例#23
0
  def editProfile(self, request, access_type,
           page_name=None, params=None, **kwargs):
    """Displays User profile edit page for the current user.

    Args:
      request: the standard Django HTTP request object
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: The Key Fields for the specified entity
    """

    # set the link_id to the current user's link_id
    user_entity = user_logic.getCurrentUser()
    # pylint: disable=E1103
    link_id = user_entity.link_id

    return self.edit(request, access_type, page_name=page_name,
        params=params, link_id=link_id, **kwargs)
示例#24
0
  def _editPost(self, request, entity, fields):
    """See base.View._editPost().
    """

    user = user_logic.getCurrentUser()
    scope_path = fields['scope_path']

    if not entity:
      fields['author'] = user
      fields['link_id'] = 't%i' % (int(time.time()*100))
    else:
      fields['author'] = entity.author
      fields['link_id'] = entity.link_id
      fields['modified_by'] = user

    fields['commented'] = self._getWorkByKeyName(scope_path).key()

    super(View, self)._editPost(request, entity, fields)
示例#25
0
    def _editPost(self, request, entity, fields):
        """See base.View._editPost().
    """

        user = user_logic.getCurrentUser()
        scope_path = fields['scope_path']

        if not entity:
            fields['author'] = user
            fields['link_id'] = 't%i' % (int(time.time() * 100))
        else:
            fields['author'] = entity.author
            fields['link_id'] = entity.link_id
            fields['modified_by'] = user

        fields['commented'] = self._getWorkByKeyName(scope_path).key()

        super(View, self)._editPost(request, entity, fields)
示例#26
0
    def takePost(self, request, template, context, params, survey_form, entity,
                 record, **kwargs):
        """Handles the POST request for the Survey's take page.

    Args:
        template: the template used for this view
        survey_form: instance of SurveyTakeForm
        entity: the Survey entity
        record: a SurveyRecord entity
        rest: see base.View.public()
    """

        survey_logic = params['logic']
        record_logic = survey_logic.getRecordLogic()

        if not survey_form.is_valid():
            # show the form errors
            return self._constructResponse(request,
                                           entity=entity,
                                           context=context,
                                           form=survey_form,
                                           params=params,
                                           template=template)

        # retrieve the data from the form
        _, properties = forms_helper.collectCleanedFields(survey_form)

        # add the required SurveyRecord properties
        properties['user'] = user_logic.getCurrentUser()
        properties['survey'] = entity
        properties['modified'] = db.DateTimeProperty.now()

        # call the hook method before updating the SurveyRecord
        self._takePost(request, params, entity, record, properties)

        # update the record entity if any and clear all dynamic properties
        record = record_logic.updateOrCreateFromFields(record,
                                                       properties,
                                                       clear_dynamic=True)

        # get the path to redirect the user to
        path = self._getRedirectOnSuccessfulTake(request, params, entity,
                                                 record)
        return http.HttpResponseRedirect(path)
示例#27
0
  def listPost(self, request, params, **kwargs):
    """Handles the POST request for the list of notifications.
    """

    import logging

    from django.utils import simplejson

    post_dict = request.POST

    data = simplejson.loads(post_dict.get('data', '[]'))
    button_id = post_dict.get('button_id', '')

    user_entity = user_logic.getCurrentUser()

    notifications = []
    for selection in data:
      notification = notification_logic.getFromKeyName(selection['key'])

      if not notification:
        logging.error('No notification found for %(key)s' %selection)
        continue

      if notification.scope.key() == user_entity.key():
        notifications.append(notification)

    if button_id == 'delete':
      for notification in notifications:
        notification_logic.delete(notification)
    elif button_id == 'mark_read' or button_id == 'mark_unread':
      if button_id == 'mark_read':
        # mark all the Notifications selected as read
        fields = {'unread': False}
      elif button_id == 'mark_unread':
        # mark all the Notifications selected as unread
        fields = {'unread': True}

      for notification in notifications:
        notification_logic.updateEntityProperties(notification, fields,
                                                  store=False)
      db.put(notifications)

    # return a 200 response to signal that all is okay
    return http.HttpResponseRedirect('')
示例#28
0
    def _takePost(self, request, params, entity, record, properties):
        """Hook into the view for the take's page POST request.

    For params see survey.View._takePost().
    """

        from soc.logic.models.user import logic as user_logic

        if not record:
            # creating a new record
            user_entity = user_logic.getCurrentUser()
            properties['main_admin'] = user_entity

            if properties['agreed_to_tos']:
                properties['agreed_to_admin_agreement'] = True

        # remove fields we don't need to store in the SurveyRecord
        properties.pop('tos')
        properties.pop('agreed_to_tos')
示例#29
0
  def listMyTasks(self, request, access_type, page_name=None,
                       params=None, **kwargs):
    """Displays a list of all starred tasks for the current user.

    If the current user is a student it also lists all tasks claimed by them.

    See base.View.list() for more details.
    """
    from soc.modules.gci.views.models import task as gci_task_view
    from soc.modules.gci.views.models import task_subscription as \
        gci_subscription_view

    program = gci_program_logic.logic.getFromKeyFieldsOr404(kwargs)
    user = user_logic.getCurrentUser()

    task_params = gci_task_view.view.getParams().copy()
    task_params['list_description'] = ugettext(
        'Tasks that you have claimed.')

    subscription_params = gci_subscription_view.view.getParams().copy()
    subscription_params['list_description'] = ugettext(
        'Tasks that you have starred.')

    if lists.isDataRequest(request):
        return self.getListMyTasksData(request, task_params,
                                       subscription_params, program, user)

    contents = []

    fields = {'user': user,
              'status': ['active', 'inactive'],
              }
    if gci_student_logic.logic.getForFields(fields, unique=True):
      order = ['modified_on']
      tasks_list = lists.getListGenerator(request, task_params,
                                          order=order, idx=0)
      contents.append(tasks_list)

    starred_tasks_list = lists.getListGenerator(request, subscription_params,
                                                idx=1)
    contents.append(starred_tasks_list)

    return self._list(request, task_params, contents, page_name)
示例#30
0
  def _takePost(self, request, params, entity, record, properties):
    """Hook into the view for the take's page POST request.

    For params see survey.View._takePost().
    """

    from soc.logic.models.user import logic as user_logic

    if not record:
      # creating a new record
      user_entity = user_logic.getCurrentUser()
      properties['main_admin'] = user_entity

      if properties['agreed_to_tos']:
        properties['agreed_to_admin_agreement'] = True

    # remove fields we don't need to store in the SurveyRecord
    properties.pop('tos')
    properties.pop('agreed_to_tos')
示例#31
0
  def _getResultsViewRecordFields(self, survey, allowed_to_read):
    """Retrieves the Results View filter for SurveyRecords.

    Args:
      survey: Survey instance for which the Records need to be shown
      allowed_to_read: specifies if the current User has read access

    Returns:
      Returns the dictionary containing the fields to filter on
    """

    # only show records for the retrieved survey
    fields = {'survey': survey}

    if not allowed_to_read:
      # this user is not allowed to view all the Records so only show their own
      fields['user'] = user_logic.getCurrentUser()

    return fields
示例#32
0
    def _getResultsViewRecordFields(self, survey, allowed_to_read):
        """Retrieves the Results View filter for SurveyRecords.

    Args:
      survey: Survey instance for which the Records need to be shown
      allowed_to_read: specifies if the current User has read access

    Returns:
      Returns the dictionary containing the fields to filter on
    """

        # only show records for the retrieved survey
        fields = {'survey': survey}

        if not allowed_to_read:
            # this user is not allowed to view all the Records so only show their own
            fields['user'] = user_logic.getCurrentUser()

        return fields
示例#33
0
    def _getSurveyRecordFor(self, survey, request, params):
        """Returns the SurveyRecord for the given Survey and request.

    Args:
        survey: a Survey entity
        request: a Django HTTPRequest object
        params: params for the requesting view

    Returns:
        An existing SurveyRecord iff any exists for the given Survey, request
        and any other conditions that must apply.
    """

        survey_logic = params['logic']
        record_logic = survey_logic.getRecordLogic()

        user_entity = user_logic.getCurrentUser()

        filter = {'survey': survey, 'user': user_entity}

        return record_logic.getForFields(filter, unique=True)
示例#34
0
  def listProjects(self, request, access_type,
                   page_name=None, params=None, **kwargs):
    """View that lists all of the current user's Student Projects for the
    Program given as Scope.
    """

    from soc.modules.gsoc.views.models import student_project as project_view

    user_entity = user_logic.getCurrentUser()

    # pylint: disable=E1103
    fields = {
        'link_id': user_entity.link_id,
        'scope_path': kwargs['scope_path']
        }

    try:
      student_entity = student_logic.getFromKeyFieldsOr404(fields)
    except out_of_band.Error, error:
      return responses.errorResponse(
          error, request, template=params['error_public'])
示例#35
0
  def takePost(self, request, template, context, params, survey_form, entity,
               record, **kwargs):
    """Handles the POST request for the Survey's take page.

    Args:
        template: the template used for this view
        survey_form: instance of SurveyTakeForm
        entity: the Survey entity
        record: a SurveyRecord entity
        rest: see base.View.public()
    """

    survey_logic = params['logic']
    record_logic = survey_logic.getRecordLogic()

    if not survey_form.is_valid():
      # show the form errors
      return self._constructResponse(request, entity=entity, context=context,
                                     form=survey_form, params=params,
                                     template=template)

    # retrieve the data from the form
    _, properties = forms_helper.collectCleanedFields(survey_form)

    # add the required SurveyRecord properties
    properties['user'] = user_logic.getCurrentUser()
    properties['survey'] = entity
    properties['modified'] = db.DateTimeProperty.now()

    # call the hook method before updating the SurveyRecord
    self._takePost(request, params, entity, record, properties)

    # update the record entity if any and clear all dynamic properties
    record = record_logic.updateOrCreateFromFields(record, properties,
                                                   clear_dynamic=True)

    # get the path to redirect the user to
    path = self._getRedirectOnSuccessfulTake(request, params, entity,
                                                 record)
    return http.HttpResponseRedirect(path)
示例#36
0
  def populate(self, redirect, request, args, kwargs):
    """Populates the fields in the RequestData object.

    Args:
      request: Django HTTPRequest object.
      args & kwargs: The args and kwargs django sends along.
    """
    self.redirect = redirect
    self.request = request
    self.args = args
    self.kwargs = kwargs
    self.GET = request.GET
    self.POST = request.POST
    self.path = request.path.encode('utf-8')
    self.full_path = request.get_full_path().encode('utf-8')
    self.site = site_logic.getSingleton()
    self.user = user_logic.getCurrentUser()
    if users.is_current_user_admin():
      self.is_developer = True
    if self.user and self.user.is_developer:
      self.is_developer = True
    self.gae_user = users.get_current_user()
示例#37
0
    def populate(self, redirect, request, args, kwargs):
        """Populates the fields in the RequestData object.

    Args:
      request: Django HTTPRequest object.
      args & kwargs: The args and kwargs django sends along.
    """
        self.redirect = redirect
        self.request = request
        self.args = args
        self.kwargs = kwargs
        self.GET = request.GET
        self.POST = request.POST
        self.path = request.path.encode('utf-8')
        self.full_path = request.get_full_path().encode('utf-8')
        self.site = site_logic.getSingleton()
        self.user = user_logic.getCurrentUser()
        if users.is_current_user_admin():
            self.is_developer = True
        if self.user and self.user.is_developer:
            self.is_developer = True
        self.gae_user = users.get_current_user()
示例#38
0
  def _getSurveyRecordFor(self, survey, request, params):
    """Returns the SurveyRecord for the given Survey and request.

    Args:
        survey: a Survey entity
        request: a Django HTTPRequest object
        params: params for the requesting view

    Returns:
        An existing SurveyRecord iff any exists for the given Survey, request
        and any other conditions that must apply.
    """

    survey_logic = params['logic']
    record_logic = survey_logic.getRecordLogic()

    user_entity = user_logic.getCurrentUser()

    filter = {'survey': survey,
              'user': user_entity}

    return record_logic.getForFields(filter, unique=True)
示例#39
0
  def _getListSelfData(self, request, entity, ma_params, ba_params):
    """Returns the listSelf data.
    """
    from soc.logic.models.user import logic as user_logic

    user_entity = user_logic.getCurrentUser()

    idx = lists.getListIndex(request)

    if idx == 0:
      fields = {'survey': entity,
                'main_admin': user_entity}
      params = ma_params
    elif idx == 1:
      fields = {'survey': entity,
                'backup_admin': user_entity}
      params = ba_params
    else:
        return lists.getErrorResponse(request, "idx not valid")

    contents = lists.getListData(request, params, fields, visibility='self')

    return lists.getResponse(request, contents)
示例#40
0
  def _public(self, request, entity, context):
    """Marks the Notification as read if that hasn't happened yet.

    for parameters see base._public()
    """

    # if the user viewing is the user for which this notification is meant
    # and the notification has not been read yet
    if entity.unread:
      # get the current user
      user = user_logic.getCurrentUser()

      # if the message is meant for the user that is reading it
      # pylint: disable=E1103
      if entity.scope.key() == user.key():
        # mark the entity as read
        self._logic.updateEntityProperties(entity, {'unread' : False} )

    context['entity_type_url'] = self._params['url_name']
    context['entity_suffix'] = entity.key().id_or_name() if entity else None
    context['page_name'] = 'Notification - %s' % (entity.subject)

    return True
示例#41
0
    def _public(self, request, entity, context):
        """Marks the Notification as read if that hasn't happened yet.

    for parameters see base._public()
    """

        # if the user viewing is the user for which this notification is meant
        # and the notification has not been read yet
        if entity.unread:
            # get the current user
            user = user_logic.getCurrentUser()

            # if the message is meant for the user that is reading it
            # pylint: disable=E1103
            if entity.scope.key() == user.key():
                # mark the entity as read
                self._logic.updateEntityProperties(entity, {'unread': False})

        context['entity_type_url'] = self._params['url_name']
        context['entity_suffix'] = entity.key().id_or_name(
        ) if entity else None
        context['page_name'] = 'Notification - %s' % (entity.subject)

        return True
示例#42
0
  def render(self, name, value, attrs=None):
    """Render TinyMCE widget as HTML.
    """

    from soc.logic.models.user import logic as user_logic
    user = user_logic.getCurrentUser()

    if user and user.disable_tinymce:
      return super(FullTinyMCE, self).render(name, value, attrs)

    if value is None:
      value = ''
    value = encoding.smart_unicode(value)
    final_attrs = self.build_attrs(attrs, name=name)
    
    self.mce_settings['elements'] = "id_%s" % name
      
    # convert mce_settings from dict to JSON
    mce_json = simplejson.JSONEncoder().encode(self.mce_settings)

    return safestring.mark_safe(self.TINY_MCE_HTML_FMT % 
        {'attrs': widgets.flatatt(final_attrs),
         'value': html.escape(value), 
         'settings_json':  mce_json})
示例#43
0
    def _getListSelfData(self, request, entity, ma_params, ba_params):
        """Returns the listSelf data.
    """
        from soc.logic.models.user import logic as user_logic

        user_entity = user_logic.getCurrentUser()

        idx = lists.getListIndex(request)

        if idx == 0:
            fields = {'survey': entity, 'main_admin': user_entity}
            params = ma_params
        elif idx == 1:
            fields = {'survey': entity, 'backup_admin': user_entity}
            params = ba_params
        else:
            return lists.getErrorResponse(request, "idx not valid")

        contents = lists.getListData(request,
                                     params,
                                     fields,
                                     visibility='self')

        return lists.getResponse(request, contents)
示例#44
0
 def testGetCurrentUserNonMatching(self):
   """Test that None is returned when the current user is not registered.
   """
   entity = user_logic.getCurrentUser()
   self.failUnlessEqual(entity, None)
示例#45
0
  def showRanking(self, request, access_type,
                  page_name=None, params=None, **kwargs):
    """Shows the ranking for the program specified by **kwargs.

    Args:
      request: the standard Django HTTP request object
      access_type : the name of the access type which should be checked
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    from soc.modules.gci.views.models.student_ranking import view as ranking_view
    from soc.modules.gci.views.models.student import view as student_view

    sparams = student_view.getParams()

    user_account = user_logic.getCurrentUser()
    user_fields = {
        'user': user_account,
        'status': 'active'
        }
    host_entity = host_logic.getForFields(user_fields, unique=True)
    is_host = host_entity or user_logic.isDeveloper(user=user_account)

    logic = params['logic']
    program = logic.getFromKeyFieldsOr404(kwargs)

    list_params = ranking_view.getParams().copy()

    list_params['list_description'] = self.DEF_LIST_RANKING_MSG_FMT % (
        program.name)

    list_params['public_field_keys'] = ["student", "points", "number"]
    list_params['public_field_names'] = ["Student", "Points", "Number of tasks"]
    list_params['public_conf_extra'] = {
        "rowNum": -1,
        "rowList": [],
        }
    list_params['public_field_prefetch'] = ['student']
    def getExtraFields(entity, *args):
      res = {
          'student': entity.student.user.name,
          'number': len(entity.tasks)
      }
      if is_host:
        fields = sparams['admin_field_keys']
        extra = dicts.toDict(entity.student, fields)
        res.update(extra)
        res['group_name'] = entity.student.scope.name
        res['birth_date'] = entity.student.birth_date.isoformat()
        res['account_name'] = accounts.normalizeAccount(entity.student.user.account).email()
        res['forms_submitted'] = "Yes" if (entity.student.consent_form and entity.student.student_id_form) else "No"
      return res

    list_params['public_field_extra'] = getExtraFields
    list_params['public_row_extra'] = lambda entity, *args: {
        'link': gci_redirects.getShowRankingDetails(entity, list_params)
    }

    list_params['public_field_props'] = {
        'points': {
            'sorttype': 'integer',
        },
        'number': {
            'sorttype': 'integer',
        },
    }
    if is_host:
      list_params['public_field_keys'] += ["forms_submitted"]
      list_params['public_field_names'] += ["Forms submitted"]
      list_params['public_field_hidden'] = sparams['admin_field_hidden'] + sparams['admin_field_keys']
      list_params['public_field_keys'].extend(sparams['admin_field_keys'])
      list_params['public_field_names'].extend(sparams['admin_field_names'])

    ranking_filter = {
        'scope': program
        }

    order = ['-points']

    if lists.isDataRequest(request):
      contents = lists.getListData(request, list_params, ranking_filter)
      return lists.getResponse(request, contents)

    contents = [lists.getListGenerator(
        request, list_params, order=order, idx=0)]

    return self._list(request, list_params, contents=contents,
        page_name=page_name)
示例#46
0
    def showRanking(self,
                    request,
                    access_type,
                    page_name=None,
                    params=None,
                    **kwargs):
        """Shows the ranking for the program specified by **kwargs.

    Args:
      request: the standard Django HTTP request object
      access_type : the name of the access type which should be checked
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

        from soc.modules.gci.views.models.student_ranking import view as ranking_view
        from soc.modules.gci.views.models.student import view as student_view

        sparams = student_view.getParams()

        user_account = user_logic.getCurrentUser()
        user_fields = {'user': user_account, 'status': 'active'}
        host_entity = host_logic.getForFields(user_fields, unique=True)
        is_host = host_entity or user_logic.isDeveloper(user=user_account)

        logic = params['logic']
        program = logic.getFromKeyFieldsOr404(kwargs)

        list_params = ranking_view.getParams().copy()

        list_params['list_description'] = self.DEF_LIST_RANKING_MSG_FMT % (
            program.name)

        list_params['public_field_keys'] = ["student", "points", "number"]
        list_params['public_field_names'] = [
            "Student", "Points", "Number of tasks"
        ]
        list_params['public_conf_extra'] = {
            "rowNum": -1,
            "rowList": [],
        }
        list_params['public_field_prefetch'] = ['student']

        def getExtraFields(entity, *args):
            res = {
                'student': entity.student.user.name,
                'number': len(entity.tasks)
            }
            if is_host:
                fields = sparams['admin_field_keys']
                extra = dicts.toDict(entity.student, fields)
                res.update(extra)
                res['group_name'] = entity.student.scope.name
                res['birth_date'] = entity.student.birth_date.isoformat()
                res['account_name'] = accounts.normalizeAccount(
                    entity.student.user.account).email()
                res['forms_submitted'] = "Yes" if (
                    entity.student.consent_form
                    and entity.student.student_id_form) else "No"
            return res

        list_params['public_field_extra'] = getExtraFields
        list_params['public_row_extra'] = lambda entity, *args: {
            'link': gci_redirects.getShowRankingDetails(entity, list_params)
        }

        list_params['public_field_props'] = {
            'points': {
                'sorttype': 'integer',
            },
            'number': {
                'sorttype': 'integer',
            },
        }
        if is_host:
            list_params['public_field_keys'] += ["forms_submitted"]
            list_params['public_field_names'] += ["Forms submitted"]
            list_params['public_field_hidden'] = sparams[
                'admin_field_hidden'] + sparams['admin_field_keys']
            list_params['public_field_keys'].extend(
                sparams['admin_field_keys'])
            list_params['public_field_names'].extend(
                sparams['admin_field_names'])

        ranking_filter = {'scope': program}

        order = ['-points']

        if lists.isDataRequest(request):
            contents = lists.getListData(request, list_params, ranking_filter)
            return lists.getResponse(request, contents)

        contents = [
            lists.getListGenerator(request, list_params, order=order, idx=0)
        ]

        return self._list(request,
                          list_params,
                          contents=contents,
                          page_name=page_name)
示例#47
0
    def listTasks(self,
                  request,
                  access_type,
                  page_name=None,
                  params=None,
                  **kwargs):
        """View where all the tasks can be searched from.
    """

        from soc.modules.gci.views.models.task import view as task_view

        logic = params['logic']

        program_entity = logic.getFromKeyFieldsOr404(kwargs)

        page_name = '%s %s' % (page_name, program_entity.name)

        list_params = task_view.getParams().copy()

        user_account = user_logic.getCurrentUser()
        user_fields = {'user': user_account, 'status': 'active'}

        host_entity = host_logic.getForFields(user_fields, unique=True)

        tasks_filter = {
            'program': program_entity,
            'status': ['Open', 'Reopened', 'ClaimRequested']
        }

        if host_entity:
            list_params[
                'list_description'] = self.DEF_LIST_VALID_TASKS_MSG_FMT % (
                    program_entity.name)
            tasks_filter['status'].extend([
                'Claimed', 'ActionNeeded', 'Closed', 'AwaitingRegistration',
                'NeedsWork', 'NeedsReview', 'Unapproved', 'Unpublished'
            ])
        else:
            list_params.setdefault('public_field_ignore', []).append('mentors')
            list_params[
                'list_description'] = self.DEF_LIST_PUBLIC_TASKS_MSG_FMT % (
                    program_entity.name)

        list_params['public_row_extra'] = lambda entity, *args: {
            'link': redirects.getPublicRedirect(entity, list_params)
        }

        list_params['public_conf_min_num'] = list_params[
            'public_conf_limit'] = 100

        if lists.isDataRequest(request):
            return self.getListTasksData(request, list_params, tasks_filter)

        contents = []
        order = ['-modified_on']

        tasks_list = lists.getListGenerator(request,
                                            list_params,
                                            order=order,
                                            idx=0)
        contents.append(tasks_list)

        return self._list(request, list_params, contents, page_name)
示例#48
0
 def testGetCurrentUserNonMatching(self):
     """Test that None is returned when the current user is not registered.
 """
     entity = user_logic.getCurrentUser()
     self.failUnlessEqual(entity, None)
示例#49
0
class View(organization.View):
    """View methods for the Organization model.
  """
    def __init__(self, params=None):
        """Defines the fields and methods required for the base View class
    to provide the user with list, public, create, edit and delete views.

    Params:
      params: a dict with params for this View
    """

        rights = access.GSoCChecker(params)
        rights['any_access'] = ['allow']
        rights['show'] = ['allow']
        rights['create'] = ['checkIsDeveloper']
        rights['edit'] = [('checkHasRoleForKeyFieldsAsScope', org_admin_logic),
                          ('checkGroupIsActiveForLinkId', org_logic)]
        rights['delete'] = ['checkIsDeveloper']
        rights['home'] = ['allow']
        rights['public_list'] = ['allow']
        rights['applicant'] = [('checkIsOrgAppAccepted', org_app_logic)]
        rights['apply_mentor'] = ['checkIsUser']
        rights['list_requests'] = [('checkHasRoleForKeyFieldsAsScope',
                                    org_admin_logic)]
        rights['list_roles'] = [('checkHasRoleForKeyFieldsAsScope',
                                 org_admin_logic)]
        rights['list_proposals'] = [
            ('checkHasAny', [[('checkHasRoleForKeyFieldsAsScope',
                               [org_admin_logic, ['active', 'inactive']]),
                              ('checkHasRoleForKeyFieldsAsScope',
                               [mentor_logic, ['active', 'inactive']])]])
        ]

        new_params = {}
        new_params['logic'] = org_logic
        new_params['rights'] = rights

        new_params['scope_view'] = program_view

        new_params['name'] = "GSoC Organization"
        new_params['module_name'] = "organization"
        new_params['sidebar_grouping'] = 'Organizations'

        new_params['module_package'] = 'soc.modules.gsoc.views.models'
        new_params['url_name'] = 'gsoc/org'
        new_params['document_prefix'] = 'gsoc_org'

        new_params['mentor_role_name'] = 'gsoc_mentor'
        new_params['mentor_url_name'] = 'gsoc/mentor'
        new_params['org_admin_role_name'] = 'gsoc_org_admin'

        patterns = []

        patterns += [
            (r'^org_tags/(?P<access_type>pick)$',
             '%(module_package)s.%(module_name)s.pick_suggested_tags',
             "Pick a list of suggested tags."),
        ]

        new_params['extra_django_patterns'] = patterns

        new_params['extra_dynaexclude'] = [
            'slots', 'slots_calculated', 'nr_applications', 'nr_mentors'
        ]

        new_params['create_extra_dynaproperties'] = {
            'tags':
            widgets.ReferenceField(
                required=False,
                reference_url='org_tags',
                label=ugettext('Tags'),
                help_text=ugettext("A list of comma seperated tags"),
                example_text="e.g. python, django, appengine",
                filter=['scope_path'],
                group="1. Public Info"),
            'clean_tags':
            gsoc_cleaning.cleanTagsList('tags', gsoc_cleaning.COMMA_SEPARATOR),
            'contrib_template':
            forms.fields.CharField(widget=helper.widgets.FullTinyMCE(
                attrs={
                    'rows': 25,
                    'cols': 100
                })),
            'clean_contrib_template':
            cleaning.clean_html_content('contrib_template'),
            'clean_facebook':
            cleaning.clean_url('facebook'),
            'clean_twitter':
            cleaning.clean_url('twitter'),
            'clean_blog':
            cleaning.clean_url('blog'),
        }

        new_params['org_app_logic'] = org_app_logic

        params = dicts.merge(params, new_params, sub_merge=True)

        super(View, self).__init__(params)

        self._params['public_field_keys'].append('tags')
        self._params['public_field_names'].append("Tags")
        self._params['public_field_extra'] = lambda entity: {
            'ideas': lists.urlize(entity.ideas, 'Click Here'),
            'tags': entity.tags_string(entity.org_tag),
        }
        self._params['select_field_extra'] = self._params['public_field_extra']

    def _editGet(self, request, entity, form):
        """See base.View._editGet().
    """

        if entity.org_tag:
            form.fields['tags'].initial = entity.tags_string(entity.org_tag)

        return super(View, self)._editGet(request, entity, form)

    def _editPost(self, request, entity, fields):
        """See base.View._editPost().
    """

        super(View, self)._editPost(request, entity, fields)

        fields['org_tag'] = {
            'tags': fields['tags'],
            'scope': entity.scope if entity else fields['scope']
        }

    @decorators.check_access
    def pickSuggestedTags(self,
                          request,
                          access_type,
                          page_name=None,
                          params=None,
                          **kwargs):
        """Returns a JSON representation of a list of organization tags
     that are suggested for a given GSoCProgram in scope.
    """

        if 'scope_path' not in request.GET:
            data = []
        else:
            program = program_logic.getFromKeyName(
                request.GET.get('scope_path'))
            if not program:
                data = []
            else:
                fun = soc.cache.logic.cache(OrgTag.get_for_custom_query)
                suggested_tags = fun(OrgTag,
                                     filter={'scope': program},
                                     order=None)
                # TODO: this should be refactored after the issue with autocompletion
                #       is resolved
                data = simplejson.dumps({
                    'data':
                    [{
                        'link_id': item['tag']
                    } for item in
                     [dicts.toDict(tag, ['tag']) for tag in suggested_tags]],
                    'autocomplete_options': {
                        'multiple': True,
                        'selectFirst': False
                    }
                })

        return self.json(request, data, False)

    # TODO (dhans): merge common items with the GCI module in a single function
    def _getExtraMenuItems(self, role_description, params=None):
        """Used to create the specific Organization menu entries.

    For args see group.View._getExtraMenuItems().
    """
        submenus = []

        group_entity = role_description['group']
        program_entity = group_entity.scope
        roles = role_description['roles']

        mentor_entity = roles.get('gsoc_mentor')
        admin_entity = roles.get('gsoc_org_admin')

        is_active_mentor = mentor_entity and mentor_entity.status == 'active'
        is_active_admin = admin_entity and admin_entity.status == 'active'

        if admin_entity or mentor_entity:
            # add a link to view all the student proposals
            submenu = (redirects.getListProposalsRedirect(
                group_entity,
                params), "Manage Student Proposals", 'any_access')
            submenus.append(submenu)

            # add a link to manage student projects after they have been announced
            if timeline_helper.isAfterEvent(
                    program_entity.timeline,
                    'accepted_students_announced_deadline'):
                submenu = (redirects.getManageOverviewRedirect(
                    group_entity, {'url_name': 'gsoc/student_project'}),
                           "Manage Student Projects", 'any_access')
                submenus.append(submenu)

        if is_active_admin:
            # add a link to the management page
            submenu = (redirects.getListRolesRedirect(group_entity, params),
                       "Manage Admins and Mentors", 'any_access')
            submenus.append(submenu)

            # add a link to invite an org admin
            submenu = (redirects.getInviteRedirectForRole(
                group_entity,
                'gsoc/org_admin'), "Invite an Admin", 'any_access')
            submenus.append(submenu)

            # add a link to invite a member
            submenu = (redirects.getInviteRedirectForRole(
                group_entity, 'gsoc/mentor'), "Invite a Mentor", 'any_access')
            submenus.append(submenu)

            # add a link to the request page
            submenu = (redirects.getListRequestsRedirect(group_entity, params),
                       "List Requests and Invites", 'any_access')
            submenus.append(submenu)

            # add a link to the edit page
            submenu = (redirects.getEditRedirect(group_entity, params),
                       "Edit Organization Profile", 'any_access')
            submenus.append(submenu)

        if is_active_admin or is_active_mentor:
            submenu = (redirects.getCreateDocumentRedirect(
                group_entity, params['document_prefix']),
                       "Create a New Document", 'any_access')
            submenus.append(submenu)

            submenu = (redirects.getListDocumentsRedirect(
                group_entity,
                params['document_prefix']), "List Documents", 'any_access')
            submenus.append(submenu)

        if is_active_admin:
            # add a link to the resign page
            submenu = (redirects.getManageRedirect(
                roles['gsoc_org_admin'], {'url_name': 'gsoc/org_admin'}),
                       "Resign as Admin", 'any_access')
            submenus.append(submenu)

            # add a link to the edit page
            submenu = (redirects.getEditRedirect(
                roles['gsoc_org_admin'], {'url_name': 'gsoc/org_admin'}),
                       "Edit My Admin Profile", 'any_access')
            submenus.append(submenu)

        if is_active_mentor:
            # add a link to the resign page
            submenu = (redirects.getManageRedirect(
                roles['gsoc_mentor'],
                {'url_name': 'gsoc/mentor'}), "Resign as Mentor", 'any_access')
            submenus.append(submenu)

            # add a link to the edit page
            submenu = (redirects.getEditRedirect(roles['gsoc_mentor'],
                                                 {'url_name': 'gsoc/mentor'}),
                       "Edit My Mentor Profile", 'any_access')
            submenus.append(submenu)

        return submenus

    def getListProposalsData(self, request, params_collection, org_entity):
        """Returns the list data for listProposals.

    Args:
      request: HTTPRequest object
      params_collection: List of list Params indexed with the idx of the list
      org_entity: GSoCOrganization entity for which the lists are generated
    """

        from soc.modules.gsoc.logic.models.proposal_duplicates import logic \
            as pd_logic
        from soc.modules.gsoc.logic.models.ranker_root import logic \
            as ranker_root_logic

        idx = lists.getListIndex(request)

        # default list settings
        args = []
        visibility = None

        if idx == 0:
            filter = {'org': org_entity, 'status': 'new'}
        elif idx == 1:
            # retrieve the ranker
            fields = {
                'link_id': student_proposal.DEF_RANKER_NAME,
                'scope': org_entity
            }

            ranker_root = ranker_root_logic.getForFields(fields, unique=True)
            ranker = ranker_root_logic.getRootFromEntity(ranker_root)

            status = {}

            program_entity = org_entity.scope

            # only when the program allows allocations
            # we show that proposals are likely to be
            # accepted or rejected
            if program_entity.allocations_visible:
                proposals = sp_logic.getProposalsToBeAcceptedForOrg(org_entity)

                duplicate_proposals = []

                # get all the duplicate entities if duplicates can be shown
                # to the organizations and make a list of all such proposals.
                if program_entity.duplicates_visible:
                    duplicate_properties = {
                        'orgs': org_entity,
                        'is_duplicate': True
                    }
                    duplicates = pd_logic.getForFields(duplicate_properties)

                    for duplicate in duplicates:
                        duplicate_proposals.extend(duplicate.duplicates)

                for proposal in proposals:
                    proposal_key = proposal.key()
                    if proposal.status == 'pending' and proposal_key in duplicate_proposals:
                        status[proposal_key] = """<strong><font color="red">
                Duplicate</font></strong>"""
                    else:
                        status[proposal_key] = """<strong><font color="green">
                Pending acceptance</font><strong>"""

            filter = {
                'org': org_entity,
                'status': ['accepted', 'pending', 'rejected']
            }

            # some extras for the list
            args = [ranker, status]
            visibility = 'review'
        elif idx == 2:
            # check if the current user is a mentor
            user_entity = user_logic.getCurrentUser()

            fields = {
                'user': user_entity,
                'scope': org_entity,
                'status': ['active', 'inactive']
            }
            mentor_entity = mentor_logic.getForFields(fields, unique=True)

            filter = {
                'org': org_entity,
                'mentor': mentor_entity,
                'status': ['pending', 'accepted', 'rejected']
            }
        elif idx == 3:
            filter = {'org': org_entity, 'status': 'invalid'}
        else:
            return lists.getErrorResponse(request, "idx not valid")

        params = params_collection[idx]
        contents = helper.lists.getListData(request,
                                            params,
                                            filter,
                                            visibility=visibility,
                                            args=args)

        return lists.getResponse(request, contents)

    @decorators.merge_params
    @decorators.check_access
    def listProposals(self,
                      request,
                      access_type,
                      page_name=None,
                      params=None,
                      **kwargs):
        """Lists all proposals for the organization given in kwargs.

    For params see base.View.public().
    """

        from soc.modules.gsoc.logic.models.proposal_duplicates_status import \
            logic as ds_logic

        try:
            org_entity = self._logic.getFromKeyFieldsOr404(kwargs)
        except out_of_band.Error, error:
            return helper.responses.errorResponse(
                error, request, template=params['error_public'])

        program_entity = org_entity.scope
        is_after_deadline = timeline_helper.isAfterEvent(
            program_entity.timeline, 'accepted_students_announced_deadline')
        if is_after_deadline:
            redirect_fun = redirects.getProposalCommentRedirect
        else:
            redirect_fun = redirects.getReviewRedirect

        context = {}
        context['entity'] = org_entity
        # whether or not the amount of slots assigned should be shown
        context['slots_visible'] = org_entity.scope.allocations_visible

        # used to check the status of the duplicate process
        context['duplicate_status'] = ds_logic.getOrCreateForProgram(
            org_entity.scope)

        program_entity = org_entity.scope
        page_name = '%s %s (%s)' % (page_name, org_entity.name,
                                    program_entity.short_name)

        list_params = student_proposal_view.view.getParams().copy()
        list_params['list_template'] = 'soc/student_proposal/list_for_org.html'

        np_params = list_params.copy()  # new proposals
        description = ugettext('List of new %s sent to %s') % (
            np_params['name_plural'], org_entity.name)
        np_params['list_description'] = description
        np_params['public_row_extra'] = lambda entity: {
            'link': redirect_fun(entity, np_params),
        }

        rp_params = list_params.copy()  # ranked proposals
        rp_params['review_field_keys'] = [
            'rank', 'title', 'student', 'mentor', 'score', 'status',
            'last_modified_on', 'abstract', 'content', 'additional_info',
            'created_on'
        ]
        rp_params['review_field_hidden'] = [
            'abstract', 'content', 'additional_info', 'created_on'
        ]
        rp_params['review_field_names'] = [
            'Rank', 'Title', 'Student', 'Mentor', 'Score', 'Status',
            'Last Modified On', 'Abstract', 'Content', 'Additional Info',
            'Created On'
        ]
        rp_params['review_field_no_filter'] = ['status']
        rp_params['review_field_prefetch'] = ['scope', 'mentor', 'program']
        rp_params['review_field_extra'] = lambda entity, ranker, status: {
              'rank': ranker.FindRanks([[entity.score]])[0] + 1,
              'student': entity.scope.name(),
              'mentor': entity.mentor.name() if entity.mentor else
                  '%s Proposed' % len(entity.possible_mentors),
              'status': status.get(entity.key(),
                  '<font color="red">Pending rejection</font>') if (
                  entity.program.allocations_visible \
                  and entity.status == 'pending') else entity.status,
        }
        rp_params['review_row_action'] = {
            "type": "redirect_custom",
            "parameters": dict(new_window=True),
        }
        rp_params['review_row_extra'] = lambda entity, *args: {
            'link': redirect_fun(entity, rp_params)
        }
        rp_params['review_field_props'] = {
            "score": {
                "sorttype": "integer",
            },
            "rank": {
                "sorttype": "integer",
            },
        }
        rp_params['review_conf_min_num'] = 50

        description = ugettext('%s already under review sent to %s') % (
            rp_params['name_plural'], org_entity.name)
        rp_params['list_description'] = description

        mp_params = list_params.copy()  # proposals mentored by current user
        description = ugettext('List of %s sent to %s you are mentoring') % (
            mp_params['name_plural'], org_entity.name)
        mp_params['list_description'] = description
        mp_params['public_row_extra'] = lambda entity: {
            'link': redirect_fun(entity, mp_params)
        }

        ip_params = list_params.copy()  # invalid proposals
        ip_params['list_description'] = ugettext(
            'List of invalid %s sent to %s ') % (ip_params['name_plural'],
                                                 org_entity.name)
        ip_params['public_row_extra'] = lambda entity: {
            'link': redirect_fun(entity, ip_params)
        }

        if lists.isDataRequest(request):
            # retrieving data for a list
            return self.getListProposalsData(
                request, [np_params, rp_params, mp_params, ip_params],
                org_entity)

        # fill contents for all the needed lists
        contents = []

        # check if there are new proposals if so show them in a separate list
        fields = {'org': org_entity, 'status': 'new'}
        new_proposal = sp_logic.getForFields(fields, unique=True)

        if new_proposal:
            # we should add this list because there is a new proposal
            np_list = helper.lists.getListGenerator(request, np_params, idx=0)
            contents.append(np_list)

        order = ['-score']
        # the list of proposals that have been reviewed should always be shown
        rp_list = helper.lists.getListGenerator(request,
                                                rp_params,
                                                order=order,
                                                visibility='review',
                                                idx=1)
        contents.append(rp_list)

        # check whether the current user is a mentor for the organization
        user_entity = user_logic.getCurrentUser()

        fields = {
            'user': user_entity,
            'scope': org_entity,
            'status': ['active', 'inactive']
        }
        mentor_entity = mentor_logic.getForFields(fields, unique=True)

        if mentor_entity:
            # show the list of all proposals that this user is mentoring
            mp_list = helper.lists.getListGenerator(request, mp_params, idx=2)
            contents.append(mp_list)

        # check if there are invalid proposals if so show them in a separate list
        fields = {'org': org_entity, 'status': 'invalid'}
        invalid_proposal = sp_logic.getForFields(fields, unique=True)
        if invalid_proposal:
            ip_list = helper.lists.getListGenerator(request, ip_params, idx=3)
            contents.append(ip_list)

        return self._list(request, list_params, contents, page_name, context)
示例#50
0
    def getListProposalsData(self, request, params_collection, org_entity):
        """Returns the list data for listProposals.

    Args:
      request: HTTPRequest object
      params_collection: List of list Params indexed with the idx of the list
      org_entity: GSoCOrganization entity for which the lists are generated
    """

        from soc.modules.gsoc.logic.models.proposal_duplicates import logic \
            as pd_logic
        from soc.modules.gsoc.logic.models.ranker_root import logic \
            as ranker_root_logic

        idx = lists.getListIndex(request)

        # default list settings
        args = []
        visibility = None

        if idx == 0:
            filter = {'org': org_entity, 'status': 'new'}
        elif idx == 1:
            # retrieve the ranker
            fields = {
                'link_id': student_proposal.DEF_RANKER_NAME,
                'scope': org_entity
            }

            ranker_root = ranker_root_logic.getForFields(fields, unique=True)
            ranker = ranker_root_logic.getRootFromEntity(ranker_root)

            status = {}

            program_entity = org_entity.scope

            # only when the program allows allocations
            # we show that proposals are likely to be
            # accepted or rejected
            if program_entity.allocations_visible:
                proposals = sp_logic.getProposalsToBeAcceptedForOrg(org_entity)

                duplicate_proposals = []

                # get all the duplicate entities if duplicates can be shown
                # to the organizations and make a list of all such proposals.
                if program_entity.duplicates_visible:
                    duplicate_properties = {
                        'orgs': org_entity,
                        'is_duplicate': True
                    }
                    duplicates = pd_logic.getForFields(duplicate_properties)

                    for duplicate in duplicates:
                        duplicate_proposals.extend(duplicate.duplicates)

                for proposal in proposals:
                    proposal_key = proposal.key()
                    if proposal.status == 'pending' and proposal_key in duplicate_proposals:
                        status[proposal_key] = """<strong><font color="red">
                Duplicate</font></strong>"""
                    else:
                        status[proposal_key] = """<strong><font color="green">
                Pending acceptance</font><strong>"""

            filter = {
                'org': org_entity,
                'status': ['accepted', 'pending', 'rejected']
            }

            # some extras for the list
            args = [ranker, status]
            visibility = 'review'
        elif idx == 2:
            # check if the current user is a mentor
            user_entity = user_logic.getCurrentUser()

            fields = {
                'user': user_entity,
                'scope': org_entity,
                'status': ['active', 'inactive']
            }
            mentor_entity = mentor_logic.getForFields(fields, unique=True)

            filter = {
                'org': org_entity,
                'mentor': mentor_entity,
                'status': ['pending', 'accepted', 'rejected']
            }
        elif idx == 3:
            filter = {'org': org_entity, 'status': 'invalid'}
        else:
            return lists.getErrorResponse(request, "idx not valid")

        params = params_collection[idx]
        contents = helper.lists.getListData(request,
                                            params,
                                            filter,
                                            visibility=visibility,
                                            args=args)

        return lists.getResponse(request, contents)
示例#51
0
        record_logic = survey_logic.getRecordLogic()

        try:
            entity = survey_logic.getFromKeyFieldsOr404(kwargs)
        except out_of_band.Error, error:
            return responses.errorResponse(error,
                                           request,
                                           template=params['error_public'])

        # get the context for this webpage
        context = responses.getUniversalContext(request)
        responses.useJavaScript(context, params['js_uses_all'])
        context['entity'] = entity

        # get the rights checker
        user_entity = user_logic.getCurrentUser()
        rights = self._params['rights']
        rights.setCurrentUser(user_entity.account, user_entity)

        # check if the current user is allowed to visit the read the survey
        allowed_to_read = False

        try:
            rights.checkIsSurveyReadable(
                {
                    'key_name': entity.key().name(),
                    'prefix': entity.prefix,
                    'scope_path': entity.scope_path,
                    'link_id': entity.link_id,
                    'user': user_entity
                }, survey_logic)
示例#52
0
  def getListProposalsData(self, request, params_collection, org_entity):
    """Returns the list data for listProposals.

    Args:
      request: HTTPRequest object
      params_collection: List of list Params indexed with the idx of the list
      org_entity: GSoCOrganization entity for which the lists are generated
    """

    from soc.modules.gsoc.logic.models.proposal_duplicates import logic \
        as pd_logic
    from soc.modules.gsoc.logic.models.ranker_root import logic \
        as ranker_root_logic

    idx = lists.getListIndex(request)

    # default list settings
    args = []
    visibility = None

    if idx == 0:
      filter = {'org': org_entity,
                'status': 'new'}
    elif idx == 1:
      # retrieve the ranker
      fields = {'link_id': student_proposal.DEF_RANKER_NAME,
                'scope': org_entity}

      ranker_root = ranker_root_logic.getForFields(fields, unique=True)
      ranker = ranker_root_logic.getRootFromEntity(ranker_root)

      status = {}

      program_entity = org_entity.scope

      # only when the program allows allocations
      # we show that proposals are likely to be
      # accepted or rejected
      if program_entity.allocations_visible:
        proposals = sp_logic.getProposalsToBeAcceptedForOrg(org_entity)

        duplicate_proposals = []

        # get all the duplicate entities if duplicates can be shown
        # to the organizations and make a list of all such proposals.
        if program_entity.duplicates_visible:
          duplicate_properties = {
              'orgs': org_entity,
              'is_duplicate': True
              }
          duplicates = pd_logic.getForFields(duplicate_properties)

          for duplicate in duplicates:
            duplicate_proposals.extend(duplicate.duplicates)

        for proposal in proposals:
          proposal_key =  proposal.key()
          if proposal.status == 'pending' and proposal_key in duplicate_proposals:
            status[proposal_key] = """<strong><font color="red">
                Duplicate</font></strong>"""
          else:
            status[proposal_key] = """<strong><font color="green">
                Pending acceptance</font><strong>"""

      filter = {'org': org_entity,
                'status': ['accepted','pending','rejected']}

      # some extras for the list
      args = [ranker, status]
      visibility = 'review'
    elif idx == 2:
      # check if the current user is a mentor
      user_entity = user_logic.getCurrentUser()

      fields = {'user': user_entity,
                'scope': org_entity,
                'status': ['active', 'inactive']}
      mentor_entity = mentor_logic.getForFields(fields, unique=True)

      filter = {'org': org_entity,
                'mentor': mentor_entity,
                'status': ['pending', 'accepted', 'rejected']}
    elif idx == 3:
      filter = {'org': org_entity,
                'status': 'invalid'}
    else:
      return lists.getErrorResponse(request, "idx not valid")

    params = params_collection[idx]
    contents = helper.lists.getListData(request, params, filter,
                                        visibility=visibility, args=args)

    return lists.getResponse(request, contents)
示例#53
0
 def testGetCurrentUser(self):
     """Test that entity of the current user can be retrieved through user id.
 """
     current_user = self.createCurrentUser()
     entity = user_logic.getCurrentUser()
     self._compareUsers(current_user, entity)
示例#54
0
 def testGetCurrentUser(self):
   """Test that entity of the current user can be retrieved through user id.
   """
   current_user = self.createCurrentUser()
   entity = user_logic.getCurrentUser()
   self._compareUsers(current_user, entity)