An admin user requests a change to an enrolment
499592
def change(self, event):
        """"""

        uuid = event.data['uuid']
        status = event.data['status']

        if status not in ['Open', 'Pending', 'Accepted', 'Denied', 'Resend']:
            self.log('Erroneous status for enrollment requested!', lvl=warn)
            return

        self.log('Changing status of an enrollment', uuid, 'to', status)

        enrollment = objectmodels['enrollment'].find_one({'uuid': uuid})
        if enrollment is not None:
            self.log('Enrollment found', lvl=debug)
        else:
            return

        if status == 'Resend':
            enrollment.timestamp = std_now()
            enrollment.save()
            self._send_invitation(enrollment, event)
            reply = {True: 'Resent'}
        else:
            enrollment.status = status
            enrollment.save()
            reply = {True: enrollment.serializablefields()}

        if status == 'Accepted' and enrollment.method == 'Enrolled':
            self._create_user(enrollment.name, enrollment.password, enrollment.email, 'Invited', event.client.uuid)
            self._send_acceptance(enrollment, None, event)

        packet = {
            'component': 'hfos.enrol.enrolmanager',
            'action': 'change',
            'data': reply
        }
        self.log('packet:', packet, lvl=verbose)
        self.fireEvent(send(event.client.uuid, packet))
        self.log('Enrollment changed', lvl=debug)
473167
@POST
  @Path("me/email")
  @RolesAllowed({"ROLE_ADMIN", "ROLE_USER"})
  public Response changeEmail(@Context HttpServletRequest request, EmailRequest emailRequest) {
    Long userId = (Long) request.getAttribute(OAuth2Filter.NAME_USER_ID);
    return changeEmail(userId, emailRequest);
  }
561071
def update_course_settings(self, course_id, allow_student_discussion_editing=None, allow_student_discussion_topics=None, allow_student_forum_attachments=None, allow_student_organized_groups=None, hide_distribution_graphs=None, hide_final_grades=None, home_page_announcement_limit=None, lock_all_announcements=None, restrict_student_future_view=None, restrict_student_past_view=None, show_announcements_on_home_page=None):
        
        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - course_id
        """ID"""
        path["course_id"] = course_id

        # OPTIONAL - allow_student_discussion_topics
        """Let students create discussion topics"""
        if allow_student_discussion_topics is not None:
            data["allow_student_discussion_topics"] = allow_student_discussion_topics

        # OPTIONAL - allow_student_forum_attachments
        """Let students attach files to discussions"""
        if allow_student_forum_attachments is not None:
            data["allow_student_forum_attachments"] = allow_student_forum_attachments

        # OPTIONAL - allow_student_discussion_editing
        """Let students edit or delete their own discussion posts"""
        if allow_student_discussion_editing is not None:
            data["allow_student_discussion_editing"] = allow_student_discussion_editing

        # OPTIONAL - allow_student_organized_groups
        """Let students organize their own groups"""
        if allow_student_organized_groups is not None:
            data["allow_student_organized_groups"] = allow_student_organized_groups

        # OPTIONAL - hide_final_grades
        """Hide totals in student grades summary"""
        if hide_final_grades is not None:
            data["hide_final_grades"] = hide_final_grades

        # OPTIONAL - hide_distribution_graphs
        """Hide grade distribution graphs from students"""
        if hide_distribution_graphs is not None:
            data["hide_distribution_graphs"] = hide_distribution_graphs

        # OPTIONAL - lock_all_announcements
        """Disable comments on announcements"""
        if lock_all_announcements is not None:
            data["lock_all_announcements"] = lock_all_announcements

        # OPTIONAL - restrict_student_past_view
        """Restrict students from viewing courses after end date"""
        if restrict_student_past_view is not None:
            data["restrict_student_past_view"] = restrict_student_past_view

        # OPTIONAL - restrict_student_future_view
        """Restrict students from viewing courses before start date"""
        if restrict_student_future_view is not None:
            data["restrict_student_future_view"] = restrict_student_future_view

        # OPTIONAL - show_announcements_on_home_page
        """Show the most recent announcements on the Course home page (if a Wiki, defaults to five announcements, configurable via home_page_announcement_limit)"""
        if show_announcements_on_home_page is not None:
            data["show_announcements_on_home_page"] = show_announcements_on_home_page

        # OPTIONAL - home_page_announcement_limit
        """Limit the number of announcements on the home page if enabled via show_announcements_on_home_page"""
        if home_page_announcement_limit is not None:
            data["home_page_announcement_limit"] = home_page_announcement_limit

        self.logger.debug("PUT /api/v1/courses/{course_id}/settings with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("PUT", "/api/v1/courses/{course_id}/settings".format(**path), data=data, params=params, no_data=True)
124002
def can_edit(self, user):
        """"""
        return self.class_.can_edit(user) and self.status != u'locked'
140314
def edit_instance_view(request, semester, pk, profile=None):
    
    instance = get_object_or_404(WorkshiftInstance, pk=pk)

    if instance.weekly_workshift and instance.weekly_workshift.is_manager_shift:
        president = Manager.objects.filter(
            incumbent__user=request.user,
            president=True
        ).count() > 0
        can_edit = request.user.is_superuser or president
        message = MESSAGES["PRESIDENTS_ONLY"]
    else:
        can_edit = utils.can_manage(
            request.user, semester=semester, pool=instance.pool,
        )
        message = MESSAGES["ADMINS_ONLY"]

    if not can_edit:
        messages.add_message(request, messages.ERROR, message)
        return HttpResponseRedirect(semester.get_view_url())

    page_name = "Edit " + instance.title

    edit_form = WorkshiftInstanceForm(
        data=request.POST if "edit" in request.POST else None,
        instance=instance,
        semester=semester,
        edit_hours=False,
    )

    if "delete" in request.POST:
        instance.delete()
        return HttpResponseRedirect(wurl(
            "workshift:manage",
            sem_url=semester.sem_url,
        ))
    elif edit_form.is_valid():
        instance = edit_form.save()
        return HttpResponseRedirect(instance.get_view_url())

    return render_to_response("edit_instance.html", {
        "page_name": page_name,
        "instance": instance,
        "edit_form": edit_form,
    }, context_instance=RequestContext(request))
1292944
public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
        global $DB;

        if ($this->get_config('unenrolaction') == ENROL_EXT_REMOVED_UNENROL) {
            // Enrolments were already synchronised in restore_instance(), we do not want any suspended leftovers.
            return;
        }
        if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
            $this->enrol_user($instance, $userid, null, 0, 0, ENROL_USER_SUSPENDED);
        }
    }
57057
def changepassword(self, event):
        """"""

        old = event.data['old']
        new = event.data['new']
        uuid = event.user.uuid

        # TODO: Write email to notify user of password change

        user = objectmodels['user'].find_one({'uuid': uuid})
        if std_hash(old, self.salt) == user.passhash:
            user.passhash = std_hash(new, self.salt)
            user.save()

            packet = {
                'component': 'hfos.enrol.enrolmanager',
                'action': 'changepassword',
                'data': True
            }
            self.fireEvent(send(event.client.uuid, packet))
            self.log('Successfully changed password for user', uuid)
        else:
            packet = {
                'component': 'hfos.enrol.enrolmanager',
                'action': 'changepassword',
                'data': False
            }
            self.fireEvent(send(event.client.uuid, packet))
            self.log('User tried to change password without supplying old one', lvl=warn)
1137281
public function enrol_self(stdClass $instance, $data = null) {
        global $DB, $USER, $CFG;

        // Don't enrol user if password is not passed when required.
        if ($instance->password && !isset($data->enrolpassword)) {
            return;
        }

        $timestart = time();
        if ($instance->enrolperiod) {
            $timeend = $timestart + $instance->enrolperiod;
        } else {
            $timeend = 0;
        }

        $this->enrol_user($instance, $USER->id, $instance->roleid, $timestart, $timeend);

        if ($instance->password and $instance->customint1 and $data->enrolpassword !== $instance->password) {
            // It must be a group enrolment, let's assign group too.
            $groups = $DB->get_records('groups', array('courseid'=>$instance->courseid), 'id', 'id, enrolmentkey');
            foreach ($groups as $group) {
                if (empty($group->enrolmentkey)) {
                    continue;
                }
                if ($group->enrolmentkey === $data->enrolpassword) {
                    // Add user to group.
                    require_once($CFG->dirroot.'/group/lib.php');
                    groups_add_member($group->id, $USER->id);
                    break;
                }
            }
        }
        // Send welcome message.
        if ($instance->customint4 != ENROL_DO_NOT_SEND_EMAIL) {
            $this->email_welcome_message($instance, $USER);
        }
    }
1233181
public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
        global $DB;

        if ($this->get_config('unenrolaction') != ENROL_EXT_REMOVED_SUSPENDNOROLES) {
            // Enrolments were already synchronised in restore_instance(), we do not want any suspended leftovers.
            return;
        }

        // ENROL_EXT_REMOVED_SUSPENDNOROLES means all previous enrolments are restored
        // but without roles and suspended.

        if (!$DB->record_exists('user_enrolments', array('enrolid' => $instance->id, 'userid' => $userid))) {
            $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, ENROL_USER_SUSPENDED);
            if ($instance->customint2) {
                groups_add_member($instance->customint2, $userid, 'enrol_meta', $instance->id);
            }
        }
    }
234848
public function change()
    {
        $table = $this->table('permissions');
        
        $table->addColumn('owner_model', 'string', [
            'default' => null,
            'null' => false,
            'limit' => 50,
        ]);

        $table->removeColumn('user_id');
        $table->removeColumn('is_active');

        $table->addColumn('owner_foreign_key', 'char', [
            'default' => null,
            'null' => false,
            'limit' => 36 
        ]);

        $table->save();
    }
618912
def changeUserRole( dbid, userid, roleid, newroleid )
      @dbid, @userid, @roleid, @newroleid = dbid, userid, roleid, newroleid
      
      xmlRequestData = toXML( :userid, @userid )
      xmlRequestData << toXML( :roleid, @roleid )
      xmlRequestData << toXML( :newroleid, @newroleid )
      
      sendRequest( :changeUserRole, xmlRequestData )

      return self if @chainAPIcalls
      @requestSucceeded
    end
765690
def edit_section(self, id, course_section_end_at=None, course_section_name=None, course_section_restrict_enrollments_to_section_dates=None, course_section_sis_section_id=None, course_section_start_at=None):
        
        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - id
        """ID"""
        path["id"] = id

        # OPTIONAL - course_section[name]
        """The name of the section"""
        if course_section_name is not None:
            data["course_section[name]"] = course_section_name

        # OPTIONAL - course_section[sis_section_id]
        """The sis ID of the section"""
        if course_section_sis_section_id is not None:
            data["course_section[sis_section_id]"] = course_section_sis_section_id

        # OPTIONAL - course_section[start_at]
        """Section start date in ISO8601 format, e.g. 2011-01-01T01:00Z"""
        if course_section_start_at is not None:
            data["course_section[start_at]"] = course_section_start_at

        # OPTIONAL - course_section[end_at]
        """Section end date in ISO8601 format. e.g. 2011-01-01T01:00Z"""
        if course_section_end_at is not None:
            data["course_section[end_at]"] = course_section_end_at

        # OPTIONAL - course_section[restrict_enrollments_to_section_dates]
        """Set to true to restrict user enrollments to the start and end dates of the section."""
        if course_section_restrict_enrollments_to_section_dates is not None:
            data["course_section[restrict_enrollments_to_section_dates]"] = course_section_restrict_enrollments_to_section_dates

        self.logger.debug("PUT /api/v1/sections/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("PUT", "/api/v1/sections/{id}".format(**path), data=data, params=params, single_item=True)
1305184
def _current_user_override(self):
        """"""
        try:
            # threadlocals is a module, not an actual thread locals object
            request = threadlocals.request()
            if request is None:
                return False
            requesting_user = request.user
            if isinstance(requesting_user, AnonymousUser) or not requesting_user.is_authenticated:
                return False
            can_view_anyway = requesting_user and (requesting_user.is_teacher or requesting_user.is_eighthoffice or requesting_user.is_eighth_admin)
        except (AttributeError, KeyError) as e:
            logger.error("Could not check teacher/eighth override: {}".format(e))
            can_view_anyway = False
        return can_view_anyway
1015246
def update_allowed(self):
        
        return self.update_action.allowed(self.column.table.request,
                                          self.datum,
                                          self)
452319
def can_edit(self, user):
        """"""
        return user.is_admin or not self.is_locked and self in user.admin_for
346186
def can_update(self, user, **kwargs):
        """"""
        if user.is_admin():
            raise Return((True, set([])))

        is_creator = self.created_by == user.id
        if not (user.is_org_admin(self.organisation_id) or is_creator):
            raise Return((False, set([])))

        fields = ({'service_type', 'organisation_id'} & set(kwargs.keys()))
        if fields:
            raise Return((False, fields))
        else:
            raise Return((True, set([])))
1171333
def allowed_to_accept_and_reject?(emendation)
      return unless emendation.amendment.evaluating?

      emendation.amendable.created_by?(current_user) || current_user.admin?
    end