/*
========== programs and enrolments ==========
548691
public function GetProgramById(XsInt $programId)
    {
        $url = sprintf("programs/%s", $programId);
        return new ApiProgram($this->execute($url));
    }
929007
function (cb) {

            var opts = {
                meta: {}
            };
            opts = this.populateClasses(opts);
            opts = this.populateModules(opts);

            ['classes', 'modules'].forEach(function (id) {
                opts.meta[id].forEach(function (v, k) {
                    opts.meta[id][k] = v.name;
                    if (v.submodules) {
                        v.submodules.forEach(function (s) {
                            opts.meta[id].push(s.displayName);
                        });
                    }
                });
                opts.meta[id].sort();
            });

            var apijs = 'YUI.add("yuidoc-meta", function(Y) {\n' +
                '   Y.YUIDoc = { meta: ' + JSON.stringify(opts.meta, null, 4) + ' };\n' +
                '});';

            cb(apijs);
        }
294319
public function init() {
        global $CFG, $DB;

        $this->close();

        export_verify_grades($this->course->id);
        $course_item = grade_item::fetch_course_item($this->course->id);
        if ($course_item->needsupdate) {
            // Can not calculate all final grades - sorry.
            return false;
        }

        $coursecontext = context_course::instance($this->course->id);

        list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
        list($gradebookroles_sql, $params) = $DB->get_in_or_equal(explode(',', $CFG->gradebookroles), SQL_PARAMS_NAMED, 'grbr');
        list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, '', 0, $this->onlyactive);

        $params = array_merge($params, $enrolledparams, $relatedctxparams);

        if ($this->groupid) {
            $groupsql = "INNER JOIN {groups_members} gm ON gm.userid = u.id";
            $groupwheresql = "AND gm.groupid = :groupid";
            // $params contents: gradebookroles
            $params['groupid'] = $this->groupid;
        } else {
            $groupsql = "";
            $groupwheresql = "";
        }

        if (empty($this->sortfield1)) {
            // We must do some sorting even if not specified.
            $ofields = ", u.id AS usrt";
            $order   = "usrt ASC";

        } else {
            $ofields = ", u.$this->sortfield1 AS usrt1";
            $order   = "usrt1 $this->sortorder1";
            if (!empty($this->sortfield2)) {
                $ofields .= ", u.$this->sortfield2 AS usrt2";
                $order   .= ", usrt2 $this->sortorder2";
            }
            if ($this->sortfield1 != 'id' and $this->sortfield2 != 'id') {
                // User order MUST be the same in both queries,
                // must include the only unique user->id if not already present.
                $ofields .= ", u.id AS usrt";
                $order   .= ", usrt ASC";
            }
        }

        $userfields = 'u.*';
        $customfieldssql = '';
        if ($this->allowusercustomfields && !empty($CFG->grade_export_customprofilefields)) {
            $customfieldscount = 0;
            $customfieldsarray = grade_helper::get_user_profile_fields($this->course->id, $this->allowusercustomfields);
            foreach ($customfieldsarray as $field) {
                if (!empty($field->customid)) {
                    $customfieldssql .= "
                            LEFT JOIN (SELECT * FROM {user_info_data}
                                WHERE fieldid = :cf$customfieldscount) cf$customfieldscount
                            ON u.id = cf$customfieldscount.userid";
                    $userfields .= ", cf$customfieldscount.data AS customfield_{$field->customid}";
                    $params['cf'.$customfieldscount] = $field->customid;
                    $customfieldscount++;
                }
            }
        }

        $users_sql = "SELECT $userfields $ofields
                        FROM {user} u
                        JOIN ($enrolledsql) je ON je.id = u.id
                             $groupsql $customfieldssql
                        JOIN (
                                  SELECT DISTINCT ra.userid
                                    FROM {role_assignments} ra
                                   WHERE ra.roleid $gradebookroles_sql
                                     AND ra.contextid $relatedctxsql
                             ) rainner ON rainner.userid = u.id
                         WHERE u.deleted = 0
                             $groupwheresql
                    ORDER BY $order";
        $this->users_rs = $DB->get_recordset_sql($users_sql, $params);

        if (!$this->onlyactive) {
            $context = context_course::instance($this->course->id);
            $this->suspendedusers = get_suspended_userids($context);
        } else {
            $this->suspendedusers = array();
        }

        if (!empty($this->grade_items)) {
            $itemids = array_keys($this->grade_items);
            list($itemidsql, $grades_params) = $DB->get_in_or_equal($itemids, SQL_PARAMS_NAMED, 'items');
            $params = array_merge($params, $grades_params);

            $grades_sql = "SELECT g.* $ofields
                             FROM {grade_grades} g
                             JOIN {user} u ON g.userid = u.id
                             JOIN ($enrolledsql) je ON je.id = u.id
                                  $groupsql
                             JOIN (
                                      SELECT DISTINCT ra.userid
                                        FROM {role_assignments} ra
                                       WHERE ra.roleid $gradebookroles_sql
                                         AND ra.contextid $relatedctxsql
                                  ) rainner ON rainner.userid = u.id
                              WHERE u.deleted = 0
                              AND g.itemid $itemidsql
                              $groupwheresql
                         ORDER BY $order, g.itemid ASC";
            $this->grades_rs = $DB->get_recordset_sql($grades_sql, $params);
        } else {
            $this->grades_rs = false;
        }

        return true;
    }
743948
public function getSchoolsByChildCareProgramId($program_id) {
    $data = [];

    $map = $this->getMapSchoolsProgramIds();
    if (isset($map[$program_id])) {
      $data = $map[$program_id];
    }

    return $data;
  }
1344457
public function process(course_enrolment_manager $manager, array $users, stdClass $properties) {
        if (!has_capability("enrol/self:unenrol", $manager->get_context())) {
            return false;
        }

        foreach ($users as $user) {
            foreach ($user->enrolments as $enrolment) {
                $plugin = $enrolment->enrolmentplugin;
                $instance = $enrolment->enrolmentinstance;
                if ($plugin->allow_unenrol_user($instance, $enrolment)) {
                    $plugin->unenrol_user($instance, $user->id);
                }
            }
        }

        return true;
    }
615787
function(preScripture){

      this.stdin.resume();
      this.stdin.setEncoding('utf8');
      this.stdin.on('data', this.checkInput.bind(this));

      var _fillStrBlue = '................................................................................';
      var _lengthOfSprite = _fillStrBlue.length;
      var _fillerStrLengthForConsoleWidth = Math.floor(_lengthOfSprite / 2);

      var _fillerStrForConsolePadding = '';

      for(var oo = 0; oo < _fillerStrLengthForConsoleWidth; oo++){
        _fillerStrForConsolePadding += '.';
      }

      util.puts("Loading PatsyJS...".bold);
      util.print('\n'+
      _fillerStrForConsolePadding.inverse.blue + '................................................................................'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '................................................................................'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '................................................................................'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '................................................................................'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '......................................................'.inverse.blue + ',:::::::,,,,'.inverse.yellow + '..............'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '................................................'.inverse.blue + ',,::'.inverse.yellow + '~~~~~~======'.inverse.white + '+=,'.inverse.yellow + '.............'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '.........................,'.inverse.blue + '$$~I+'.inverse.yellow + '..............'.inverse.blue + ',::'.inverse.yellow + '~~'.inverse.white + '::::::::::::::'.white + '~'.inverse.white + '+=,'.inverse.yellow + '............'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '...................'.inverse.blue + '++Z7$7=~~~+?7ZOZZO?'.inverse.yellow + '.....'.inverse.blue + ',:'.inverse.yellow + '~~'.inverse.white + '::::::::::~~~~::'.white + '::'.inverse.white + '+?:'.inverse.yellow + '............'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '................'.inverse.blue + 'OZ$~?~'.inverse.yellow + ':::,,:,,,,,,'.inverse.white + '::~IZZ8Z:'.inverse.yellow + '~:'.inverse.white + ':::::::::~:~~~~~:'.white + '::'.inverse.white + '~II:,'.inverse.yellow + '...........'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '..............'.inverse.blue + 'ZZZ~'.inverse.yellow + '::,:,,,,,.,.....,,,,'.inverse.white + '::=78~~'.inverse.yellow + '::::::::::::~~~:'.white + '::'.inverse.white + '~IZI:,'.inverse.yellow + '...........'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '...........'.inverse.blue + 'I:IZO~'.inverse.yellow + ':,,,.,,,,,'.inverse.white + '::~:'.white + ',,,,...,,,'.inverse.white + '::78,'.inverse.yellow + ':::::::::::::'.white + ':::'.inverse.white + '=7ZZI:,'.inverse.yellow + '...........'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '...........'.inverse.blue + '=IZO~'.inverse.yellow + ':,,,.,'.inverse.white + '~~~~~~==~=~~~~'.white + ':,,...,'.inverse.white + ':~DO,'.inverse.yellow + ',,'.inverse.white + '::::::'.white + ':::~'.inverse.white + '=IZZZZ?:'.inverse.yellow + '............'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '...........'.inverse.blue + '~Z7$'.inverse.yellow + ':,,,,,'.inverse.white + '=~~=~========~=~~~~'.white + '...,,'.inverse.white + ':IO~'.inverse.yellow + '~~~~~~='.inverse.white + '?I$OOZZZZ$=,'.inverse.yellow + '............'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '..........'.inverse.blue + 'Z$O$O~'.inverse.yellow + ':,,,'.inverse.white + '~=~~~==============~~'.white + ',,,,'.inverse.white + '::$O$ZZZOOOOOOOOZZZZ?:'.inverse.yellow + '.............'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '..........'.inverse.blue + 'ZO$$Z~'.inverse.yellow + ':,,,'.inverse.white + '=~~~~~~==============~'.white + ':,,'.inverse.white + '::~OOZOOZZOOOOOOOOZ$~'.inverse.yellow + ','.inverse.grey + '.............'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '.........'.inverse.blue + '~ZOZOO7'.inverse.yellow + ':,,,'.inverse.white + '=~~~~~~~~=============~'.white + ':,,,'.inverse.white + ':~OZZZOOOOOOOOOOO+'.inverse.yellow + ','.inverse.grey + '..............'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '.........'.inverse.blue + 'O8OOOZZ'.inverse.yellow + '::,,:'.inverse.white + '~~~~~~~~~====~~=======~'.white + ',,,,'.inverse.white + '~IZOOOOOOOOOZOZ?:'.inverse.yellow + ',,'.inverse.grey + '.............'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '.........'.inverse.blue + 'NZ$788ZI'.inverse.yellow + ':,,,'.inverse.white + '~~~~~~~~~~=~~~~~======~'.white + ',.,,'.inverse.white + ':~OIO8888888Z7+'.inverse.yellow + '~~:::,,,,'.inverse.grey + '........'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '........'.inverse.blue + '=Z$Z8OZ$$7'.inverse.yellow + ':,,,'.inverse.white + '~~~~~~~~=~~~~~~~====~~'.white + ',,,,'.inverse.white + '::ZODDDDD8Z7+='.inverse.yellow + '~~~~::::::,,,'.inverse.grey + '.....'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '........'.inverse.blue + ':$8$OZZOZO7'.inverse.yellow + ':,,,,'.inverse.white + '~~~~~~~~~~~~~~===~~~'.white + ',.,,'.inverse.white + ':~ZO?IIIII?+='.inverse.yellow + '~~~::::::,,,,'.inverse.grey + '......'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '.......'.inverse.blue + '+?Z$O$OZZZOOO'.inverse.yellow + ':,,,,:'.inverse.white + '~~~~~~~~~~~~=~~~~'.white + ',.,,,'.inverse.white + ':~ZI'.inverse.yellow + '::::::::::,,,,,,'.inverse.grey + '............'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '.........'.inverse.blue + 'Z78ZO88OZ7$$='.inverse.yellow + ':,,,,'.inverse.white + '~~~~~~~~=~~~~~'.white + '::.,,,,'.inverse.white + ':7Z='.inverse.yellow + ',,,,,,,,,,,,,,,'.inverse.grey + '.............'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '.........'.inverse.blue + ':OZ8ZZ8ZZ$?$$$'.inverse.yellow + ':,,,,.,,,'.inverse.white + ':::=::'.white + '...,..,,'.inverse.white + '::~ZI'.inverse.yellow + ',,,,,,,,,,,,,,,'.inverse.grey + '..............'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '.........'.inverse.blue + '.7ZZO88OZ8ZOOZOO'.inverse.yellow + ':,,,,,.....,,,,,,,,,'.inverse.white + '::=ZI'.inverse.yellow + '......'.inverse.blue + ',.,,,,,'.inverse.grey + '.................'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '...........'.inverse.blue + 'IZ$88OOOOZZ88Z7OZ~'.inverse.yellow + ':,,,,,,,,,,,'.inverse.white + '::::$OZZ:'.inverse.yellow + '..............................'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '............'.inverse.blue + 'ZZZZO$Z$OOOZOO$77OZI77+'.inverse.yellow + ':::ZOOOZZZZ$8'.inverse.yellow + '................................'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '............'.inverse.blue + '+878$$ZZDZZOOZZZOO$ZOOZO7Z7$$Z$OO7?'.inverse.yellow + '.................................'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '.....'.inverse.blue + ',,,,,,,,,'.inverse.grey + 'Z$OZOZ8ZOOO$O$O7Z$OO$$$8OOOOZZZ7'.inverse.yellow + '..................................'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '..'.inverse.blue + ',,,,,,,,,,,,,,'.inverse.grey + 'OOO8Z88OZD8OOO$8Z8$8OZZO7Z7O'.inverse.yellow + '....................................'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '..'.inverse.blue + ',,,,,,,,,,,,:~+?'.inverse.grey + 'OD8D$O888OOOOZ$88OZ$Z8O~~'.inverse.yellow + '~::,,'.inverse.grey + '................................'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '...'.inverse.blue + ',,,,,,,,,~=+++???'.inverse.grey + '8D8DD8NDDDO88NOD8?7==='.inverse.yellow + '~~~:::::,,,'.inverse.grey + '...........................'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '.......'.inverse.blue + ',,,::=++??IZ78O'.inverse.grey + '8NNDDNMNM8MZZ$7I?+'.inverse.yellow + '==~~~::::,,,,,,,,'.inverse.grey + '.......................'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '............'.inverse.blue + ',:=+??I7$$$'.inverse.grey + 'ZZZOOO8OOOZ$7I?+'.inverse.yellow + '=~~::::,,,,,,,,,'.inverse.grey + '.........................'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue +
      _fillerStrForConsolePadding.inverse.blue + '...............'.inverse.blue + ',,:~~==============~~~~:::::,,,,,,'.inverse.grey + '...............................'.inverse.blue + _fillerStrForConsolePadding.inverse.blue + '\n'.inverse.blue);


      if ((Array.isArray(preScripture)) && (preScripture.length > 0)) {
        for (var i = 0; i < preScripture.length; i++) {
          this.scripture.print(preScripture[i]);
        }
      }

      this.scripture.print('[King Arthur]'.magenta + ': Come Patsy, my trusty servant!!');
      this.scripture.print('[Patsy]'.yellow + ': <banging two half coconuts together> ');

      try{
        var patsy = this;
        /**
         * Require project from the library
         *
         * @var     Object
         * @source  patsy
         */
        var project = require('./project')(opts);
        project.check(patsy);
      } catch(e){
        console.log('>> PatsyStartException'.red + ':', e);
      }
    }
224437
function definition () {
        global $USER, $CFG, $COURSE;
        $coursecontext = context_course::instance($COURSE->id);

        $mform =& $this->_form;
        $editoroptions = $this->_customdata['editoroptions'];

        $mform->addElement('header', 'general', get_string('general', 'form'));

        $mform->addElement('text','name', get_string('groupname', 'group'),'maxlength="254" size="50"');
        $mform->addRule('name', get_string('required'), 'required', null, 'client');
        $mform->setType('name', PARAM_TEXT);

        $mform->addElement('text','idnumber', get_string('idnumbergroup'), 'maxlength="100" size="10"');
        $mform->addHelpButton('idnumber', 'idnumbergroup');
        $mform->setType('idnumber', PARAM_RAW);
        if (!has_capability('moodle/course:changeidnumber', $coursecontext)) {
            $mform->hardFreeze('idnumber');
        }

        $mform->addElement('editor', 'description_editor', get_string('groupdescription', 'group'), null, $editoroptions);
        $mform->setType('description_editor', PARAM_RAW);

        $mform->addElement('passwordunmask', 'enrolmentkey', get_string('enrolmentkey', 'group'), 'maxlength="254" size="24"', get_string('enrolmentkey', 'group'));
        $mform->addHelpButton('enrolmentkey', 'enrolmentkey', 'group');
        $mform->setType('enrolmentkey', PARAM_RAW);

        // Group conversation messaging.
        if (\core_message\api::can_create_group_conversation($USER->id, $coursecontext)) {
            $mform->addElement('selectyesno', 'enablemessaging', get_string('enablemessaging', 'group'));
            $mform->addHelpButton('enablemessaging', 'enablemessaging', 'group');
        }

        $mform->addElement('static', 'currentpicture', get_string('currentpicture'));

        $mform->addElement('checkbox', 'deletepicture', get_string('delete'));
        $mform->setDefault('deletepicture', 0);

        $options = array(get_string('no'), get_string('yes'));
        $mform->addElement('select', 'hidepicture', get_string('hidepicture'), $options);

        $mform->addElement('filepicker', 'imagefile', get_string('newpicture', 'group'));
        $mform->addHelpButton('imagefile', 'newpicture', 'group');

        $mform->addElement('hidden','id');
        $mform->setType('id', PARAM_INT);

        $mform->addElement('hidden','courseid');
        $mform->setType('courseid', PARAM_INT);

        $this->add_action_buttons();
    }
722934
public function sync_enrolments(progress_trace $trace, $onecourse = null) {
        global $CFG, $DB;

        if (!$this->ldap_connect($trace)) {
            $trace->finished();
            return;
        }

        $ldap_pagedresults = ldap_paged_results_supported($this->get_config('ldap_version'), $this->ldapconnection);

        // we may need a lot of memory here
        core_php_time_limit::raise();
        raise_memory_limit(MEMORY_HUGE);

        $oneidnumber = null;
        if ($onecourse) {
            if (!$course = $DB->get_record('course', array('id'=>$onecourse), 'id,'.$this->enrol_localcoursefield)) {
                // Course does not exist, nothing to do.
                $trace->output("Requested course $onecourse does not exist, no sync performed.");
                $trace->finished();
                return;
            }
            if (empty($course->{$this->enrol_localcoursefield})) {
                $trace->output("Requested course $onecourse does not have {$this->enrol_localcoursefield}, no sync performed.");
                $trace->finished();
                return;
            }
            $oneidnumber = ldap_filter_addslashes(core_text::convert($course->idnumber, 'utf-8', $this->get_config('ldapencoding')));
        }

        // Get enrolments for each type of role.
        $roles = get_all_roles();
        $enrolments = array();
        foreach($roles as $role) {
            // Get all contexts
            $ldap_contexts = explode(';', $this->config->{'contexts_role'.$role->id});

            // Get all the fields we will want for the potential course creation
            // as they are light. Don't get membership -- potentially a lot of data.
            $ldap_fields_wanted = array('dn', $this->config->course_idnumber);
            if (!empty($this->config->course_fullname)) {
                array_push($ldap_fields_wanted, $this->config->course_fullname);
            }
            if (!empty($this->config->course_shortname)) {
                array_push($ldap_fields_wanted, $this->config->course_shortname);
            }
            if (!empty($this->config->course_summary)) {
                array_push($ldap_fields_wanted, $this->config->course_summary);
            }
            array_push($ldap_fields_wanted, $this->config->{'memberattribute_role'.$role->id});

            // Define the search pattern
            $ldap_search_pattern = $this->config->objectclass;

            if ($oneidnumber !== null) {
                $ldap_search_pattern = "(&$ldap_search_pattern({$this->config->course_idnumber}=$oneidnumber))";
            }

            $ldap_cookie = '';
            foreach ($ldap_contexts as $ldap_context) {
                $ldap_context = trim($ldap_context);
                if (empty($ldap_context)) {
                    continue; // Next;
                }

                $flat_records = array();
                do {
                    if ($ldap_pagedresults) {
                        ldap_control_paged_result($this->ldapconnection, $this->config->pagesize, true, $ldap_cookie);
                    }

                    if ($this->config->course_search_sub) {
                        // Use ldap_search to find first user from subtree
                        $ldap_result = @ldap_search($this->ldapconnection,
                                                    $ldap_context,
                                                    $ldap_search_pattern,
                                                    $ldap_fields_wanted);
                    } else {
                        // Search only in this context
                        $ldap_result = @ldap_list($this->ldapconnection,
                                                  $ldap_context,
                                                  $ldap_search_pattern,
                                                  $ldap_fields_wanted);
                    }
                    if (!$ldap_result) {
                        continue; // Next
                    }

                    if ($ldap_pagedresults) {
                        ldap_control_paged_result_response($this->ldapconnection, $ldap_result, $ldap_cookie);
                    }

                    // Check and push results
                    $records = ldap_get_entries($this->ldapconnection, $ldap_result);

                    // LDAP libraries return an odd array, really. fix it:
                    for ($c = 0; $c < $records['count']; $c++) {
                        array_push($flat_records, $records[$c]);
                    }
                    // Free some mem
                    unset($records);
                } while ($ldap_pagedresults && !empty($ldap_cookie));

                // If LDAP paged results were used, the current connection must be completely
                // closed and a new one created, to work without paged results from here on.
                if ($ldap_pagedresults) {
                    $this->ldap_close();
                    $this->ldap_connect($trace);
                }

                if (count($flat_records)) {
                    $ignorehidden = $this->get_config('ignorehiddencourses');
                    foreach($flat_records as $course) {
                        $course = array_change_key_case($course, CASE_LOWER);
                        $idnumber = $course{$this->config->course_idnumber}[0];
                        $trace->output(get_string('synccourserole', 'enrol_ldap', array('idnumber'=>$idnumber, 'role_shortname'=>$role->shortname)));

                        // Does the course exist in moodle already?
                        $course_obj = $DB->get_record('course', array($this->enrol_localcoursefield=>$idnumber));
                        if (empty($course_obj)) { // Course doesn't exist
                            if ($this->get_config('autocreate')) { // Autocreate
                                $trace->output(get_string('createcourseextid', 'enrol_ldap', array('courseextid'=>$idnumber)));
                                if (!$newcourseid = $this->create_course($course, $trace)) {
                                    continue;
                                }
                                $course_obj = $DB->get_record('course', array('id'=>$newcourseid));
                            } else {
                                $trace->output(get_string('createnotcourseextid', 'enrol_ldap', array('courseextid'=>$idnumber)));
                                continue; // Next; skip this one!
                            }
                        } else {  // Check if course needs update & update as needed.
                            $this->update_course($course_obj, $course, $trace);
                        }

                        // Enrol & unenrol

                        // Pull the ldap membership into a nice array
                        // this is an odd array -- mix of hash and array --
                        $ldapmembers = array();

                        if (array_key_exists('memberattribute_role'.$role->id, $this->config)
                            && !empty($this->config->{'memberattribute_role'.$role->id})
                            && !empty($course[$this->config->{'memberattribute_role'.$role->id}])) { // May have no membership!

                            $ldapmembers = $course[$this->config->{'memberattribute_role'.$role->id}];
                            unset($ldapmembers['count']); // Remove oddity ;)

                            // If we have enabled nested groups, we need to expand
                            // the groups to get the real user list. We need to do
                            // this before dealing with 'memberattribute_isdn'.
                            if ($this->config->nested_groups) {
                                $users = array();
                                foreach ($ldapmembers as $ldapmember) {
                                    $grpusers = $this->ldap_explode_group($ldapmember,
                                                                          $this->config->{'memberattribute_role'.$role->id});

                                    $users = array_merge($users, $grpusers);
                                }
                                $ldapmembers = array_unique($users); // There might be duplicates.
                            }

                            // Deal with the case where the member attribute holds distinguished names,
                            // but only if the user attribute is not a distinguished name itself.
                            if ($this->config->memberattribute_isdn
                                && ($this->config->idnumber_attribute !== 'dn')
                                && ($this->config->idnumber_attribute !== 'distinguishedname')) {
                                // We need to retrieve the idnumber for all the users in $ldapmembers,
                                // as the idnumber does not match their dn and we get dn's from membership.
                                $memberidnumbers = array();
                                foreach ($ldapmembers as $ldapmember) {
                                    $result = ldap_read($this->ldapconnection, $ldapmember, $this->userobjectclass,
                                                        array($this->config->idnumber_attribute));
                                    $entry = ldap_first_entry($this->ldapconnection, $result);
                                    $values = ldap_get_values($this->ldapconnection, $entry, $this->config->idnumber_attribute);
                                    array_push($memberidnumbers, $values[0]);
                                }

                                $ldapmembers = $memberidnumbers;
                            }
                        }

                        // Prune old ldap enrolments
                        // hopefully they'll fit in the max buffer size for the RDBMS
                        $sql= "SELECT u.id as userid, u.username, ue.status,
                                      ra.contextid, ra.itemid as instanceid
                                 FROM {user} u
                                 JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.component = 'enrol_ldap' AND ra.roleid = :roleid)
                                 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = ra.itemid)
                                 JOIN {enrol} e ON (e.id = ue.enrolid)
                                WHERE u.deleted = 0 AND e.courseid = :courseid ";
                        $params = array('roleid'=>$role->id, 'courseid'=>$course_obj->id);
                        $context = context_course::instance($course_obj->id);
                        if (!empty($ldapmembers)) {
                            list($ldapml, $params2) = $DB->get_in_or_equal($ldapmembers, SQL_PARAMS_NAMED, 'm', false);
                            $sql .= "AND u.idnumber $ldapml";
                            $params = array_merge($params, $params2);
                            unset($params2);
                        } else {
                            $shortname = format_string($course_obj->shortname, true, array('context' => $context));
                            $trace->output(get_string('emptyenrolment', 'enrol_ldap',
                                         array('role_shortname'=> $role->shortname,
                                               'course_shortname' => $shortname)));
                        }
                        $todelete = $DB->get_records_sql($sql, $params);

                        if (!empty($todelete)) {
                            $transaction = $DB->start_delegated_transaction();
                            foreach ($todelete as $row) {
                                $instance = $DB->get_record('enrol', array('id'=>$row->instanceid));
                                switch ($this->get_config('unenrolaction')) {
                                case ENROL_EXT_REMOVED_UNENROL:
                                    $this->unenrol_user($instance, $row->userid);
                                    $trace->output(get_string('extremovedunenrol', 'enrol_ldap',
                                        array('user_username'=> $row->username,
                                              'course_shortname'=>$course_obj->shortname,
                                              'course_id'=>$course_obj->id)));
                                    break;
                                case ENROL_EXT_REMOVED_KEEP:
                                    // Keep - only adding enrolments
                                    break;
                                case ENROL_EXT_REMOVED_SUSPEND:
                                    if ($row->status != ENROL_USER_SUSPENDED) {
                                        $DB->set_field('user_enrolments', 'status', ENROL_USER_SUSPENDED, array('enrolid'=>$instance->id, 'userid'=>$row->userid));
                                        $trace->output(get_string('extremovedsuspend', 'enrol_ldap',
                                            array('user_username'=> $row->username,
                                                  'course_shortname'=>$course_obj->shortname,
                                                  'course_id'=>$course_obj->id)));
                                    }
                                    break;
                                case ENROL_EXT_REMOVED_SUSPENDNOROLES:
                                    if ($row->status != ENROL_USER_SUSPENDED) {
                                        $DB->set_field('user_enrolments', 'status', ENROL_USER_SUSPENDED, array('enrolid'=>$instance->id, 'userid'=>$row->userid));
                                    }
                                    role_unassign_all(array('contextid'=>$row->contextid, 'userid'=>$row->userid, 'component'=>'enrol_ldap', 'itemid'=>$instance->id));
                                    $trace->output(get_string('extremovedsuspendnoroles', 'enrol_ldap',
                                        array('user_username'=> $row->username,
                                              'course_shortname'=>$course_obj->shortname,
                                              'course_id'=>$course_obj->id)));
                                    break;
                                }
                            }
                            $transaction->allow_commit();
                        }

                        // Insert current enrolments
                        // bad we can't do INSERT IGNORE with postgres...

                        // Add necessary enrol instance if not present yet;
                        $sql = "SELECT c.id, c.visible, e.id as enrolid
                                  FROM {course} c
                                  JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'ldap')
                                 WHERE c.id = :courseid";
                        $params = array('courseid'=>$course_obj->id);
                        if (!($course_instance = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE))) {
                            $course_instance = new stdClass();
                            $course_instance->id = $course_obj->id;
                            $course_instance->visible = $course_obj->visible;
                            $course_instance->enrolid = $this->add_instance($course_instance);
                        }

                        if (!$instance = $DB->get_record('enrol', array('id'=>$course_instance->enrolid))) {
                            continue; // Weird; skip this one.
                        }

                        if ($ignorehidden && !$course_instance->visible) {
                            continue;
                        }

                        $transaction = $DB->start_delegated_transaction();
                        foreach ($ldapmembers as $ldapmember) {
                            $sql = 'SELECT id,username,1 FROM {user} WHERE idnumber = ? AND deleted = 0';
                            $member = $DB->get_record_sql($sql, array($ldapmember));
                            if(empty($member) || empty($member->id)){
                                $trace->output(get_string('couldnotfinduser', 'enrol_ldap', $ldapmember));
                                continue;
                            }

                            $sql= "SELECT ue.status
                                     FROM {user_enrolments} ue
                                     JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'ldap')
                                    WHERE e.courseid = :courseid AND ue.userid = :userid";
                            $params = array('courseid'=>$course_obj->id, 'userid'=>$member->id);
                            $userenrolment = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE);

                            if (empty($userenrolment)) {
                                $this->enrol_user($instance, $member->id, $role->id);
                                // Make sure we set the enrolment status to active. If the user wasn't
                                // previously enrolled to the course, enrol_user() sets it. But if we
                                // configured the plugin to suspend the user enrolments _AND_ remove
                                // the role assignments on external unenrol, then enrol_user() doesn't
                                // set it back to active on external re-enrolment. So set it
                                // unconditionally to cover both cases.
                                $DB->set_field('user_enrolments', 'status', ENROL_USER_ACTIVE, array('enrolid'=>$instance->id, 'userid'=>$member->id));
                                $trace->output(get_string('enroluser', 'enrol_ldap',
                                    array('user_username'=> $member->username,
                                          'course_shortname'=>$course_obj->shortname,
                                          'course_id'=>$course_obj->id)));

                            } else {
                                if (!$DB->record_exists('role_assignments', array('roleid'=>$role->id, 'userid'=>$member->id, 'contextid'=>$context->id, 'component'=>'enrol_ldap', 'itemid'=>$instance->id))) {
                                    // This happens when reviving users or when user has multiple roles in one course.
                                    $context = context_course::instance($course_obj->id);
                                    role_assign($role->id, $member->id, $context->id, 'enrol_ldap', $instance->id);
                                    $trace->output("Assign role to user '$member->username' in course '$course_obj->shortname ($course_obj->id)'");
                                }
                                if ($userenrolment->status == ENROL_USER_SUSPENDED) {
                                    // Reenable enrolment that was previously disabled. Enrolment refreshed
                                    $DB->set_field('user_enrolments', 'status', ENROL_USER_ACTIVE, array('enrolid'=>$instance->id, 'userid'=>$member->id));
                                    $trace->output(get_string('enroluserenable', 'enrol_ldap',
                                        array('user_username'=> $member->username,
                                              'course_shortname'=>$course_obj->shortname,
                                              'course_id'=>$course_obj->id)));
                                }
                            }
                        }
                        $transaction->allow_commit();
                    }
                }
            }
        }
        @$this->ldap_close();
        $trace->finished();
    }
847864
function () {
            var $pages = this.$pages,
                index = this.state.currentPage - 1,
                next = index + 1,
                prev = index - 1,
                buffer = 20;

            // @TODO: optimize this a bit
            // add/removeClass is expensive, so try using hasClass
            $pages.removeClass(PRESENTATION_CSS_CLASSES);
            if (this.twoPageMode) {
                next = index + 2;
                prev = index - 2;
                $pages.slice(Math.max(prev, 0), index).addClass(CSS_CLASS_PAGE_PREV);
                $pages.slice(next, next + 2).addClass(CSS_CLASS_PAGE_NEXT);
            } else {
                if (prev >= 0) {
                    $pages.eq(prev).addClass(CSS_CLASS_PAGE_PREV);
                }
                if (next < this.numPages) {
                    $pages.eq(next).addClass(CSS_CLASS_PAGE_NEXT);
                }
            }
            $pages.slice(0, index).addClass(CSS_CLASS_PAGE_BEFORE);
            $pages.slice(Math.max(0, index - buffer), index).addClass(CSS_CLASS_PAGE_BEFORE_BUFFER);
            $pages.slice(next).addClass(CSS_CLASS_PAGE_AFTER);
            $pages.slice(next, Math.min(this.numPages, next + buffer)).addClass(CSS_CLASS_PAGE_AFTER_BUFFER);

            /*
            // OPTIMIZATION CODE NOT YET WORKING PROPERLY
            $pages.slice(0, index).each(function () {
                var $p = $(this),
                    i = $p.index(),
                    toAdd = '',
                    toRm = '';
                if (!$p.hasClass(beforeClass.trim())) toAdd += beforeClass;
                if ($p.hasClass(nextClass.trim())) toRm += nextClass;
                if ($p.hasClass(afterClass.trim())) toRm += afterClass;
                if ($p.hasClass(afterBufferClass.trim())) toRm += afterBufferClass;
                if (i >= index - buffer && !$p.hasClass(beforeBufferClass.trim()))
                    toAdd += beforeBufferClass;
                else if ($p.hasClass(beforeBufferClass.trim()))
                    toRm += beforeBufferClass;
                if (i >= prev && !$p.hasClass(prevClass.trim()))
                    toAdd += prevClass;
                else if ($p.hasClass(prevClass.trim()))
                    toRm += prevClass;
                $p.addClass(toAdd).removeClass(toRm);
//                console.log('before', $p.index(), toRm, toAdd);
            });
            $pages.slice(next).each(function () {
                var $p = $(this),
                    i = $p.index(),
                    toAdd = '',
                    toRm = '';
                if (!$p.hasClass(afterClass.trim())) toAdd += afterClass;
                if ($p.hasClass(prevClass.trim())) toRm += prevClass;
                if ($p.hasClass(beforeClass.trim())) toRm += beforeClass;
                if ($p.hasClass(beforeBufferClass.trim())) toRm += beforeBufferClass;
                if (i <= index + buffer && !$p.hasClass(afterBufferClass.trim()))
                    toAdd += afterBufferClass;
                else if ($p.hasClass(afterBufferClass.trim()))
                    toRm += afterBufferClass;
                if (i <= next + 1 && !$p.hasClass(nextClass.trim()))
                    toAdd += nextClass;
                else if ($p.hasClass(nextClass.trim()))
                    toRm += nextClass;
                $p.addClass(toAdd).removeClass(toRm);
//                console.log('after', $p.index(), toRm, toAdd);
            });*/
        }
1112697
function () {
			var N = this.N;

			var cg = this.costGrad(this.Y); // evaluate gradient
			var cost = cg.cost;
			var grad = cg.grad;

			var e = 1e-5;
			for (var i = 0; i < N; i++) {
				for (var d = 0; d < this.dim; d++) {
					var yold = this.Y[i][d];

					this.Y[i][d] = yold + e;
					var cg0 = this.costGrad(this.Y);

					this.Y[i][d] = yold - e;
					var cg1 = this.costGrad(this.Y);

					var analytic = grad[i][d];
					var numerical = (cg0.cost - cg1.cost) / ( 2 * e );
					console.log(i + ',' + d + ': gradcheck analytic: ' + analytic + ' vs. numerical: ' + numerical);

					this.Y[i][d] = yold;
				}
			}
		}
924222
function main(program) {
  program || (program = { args: [] });
  if(program.args.length === 0) {
    program.outputHelp();
    return process.exit(1);
  }

  return Promise
    .map(program.args, _.partial(exports.downloadPosting, program))
    .map(function(html) {
      return cheerio.load(html);
    })
    .map(exports.extractInfo)
    .then(_.partial(exports.outputInfo, program));
}
619347
protected function load_courses_enrolled() {
        global $CFG;

        $limit = (int) $CFG->navcourselimit;

        $courses = enrol_get_my_courses('*');
        $flatnavcourses = [];

        // Go through the courses and see which ones we want to display in the flatnav.
        foreach ($courses as $course) {
            $classify = course_classify_for_timeline($course);

            if ($classify == COURSE_TIMELINE_INPROGRESS) {
                $flatnavcourses[$course->id] = $course;
            }
        }

        // Get the number of courses that can be displayed in the nav block and in the flatnav.
        $numtotalcourses = count($courses);
        $numtotalflatnavcourses = count($flatnavcourses);

        // Reduce the size of the arrays to abide by the 'navcourselimit' setting.
        $courses = array_slice($courses, 0, $limit, true);
        $flatnavcourses = array_slice($flatnavcourses, 0, $limit, true);

        // Get the number of courses we are going to show for each.
        $numshowncourses = count($courses);
        $numshownflatnavcourses = count($flatnavcourses);
        if ($numshowncourses && $this->show_my_categories()) {
            // Generate an array containing unique values of all the courses' categories.
            $categoryids = array();
            foreach ($courses as $course) {
                if (in_array($course->category, $categoryids)) {
                    continue;
                }
                $categoryids[] = $course->category;
            }

            // Array of category IDs that include the categories of the user's courses and the related course categories.
            $fullpathcategoryids = [];
            // Get the course categories for the enrolled courses' category IDs.
            $mycoursecategories = core_course_category::get_many($categoryids);
            // Loop over each of these categories and build the category tree using each category's path.
            foreach ($mycoursecategories as $mycoursecat) {
                $pathcategoryids = explode('/', $mycoursecat->path);
                // First element of the exploded path is empty since paths begin with '/'.
                array_shift($pathcategoryids);
                // Merge the exploded category IDs into the full list of category IDs that we will fetch.
                $fullpathcategoryids = array_merge($fullpathcategoryids, $pathcategoryids);
            }

            // Fetch all of the categories related to the user's courses.
            $pathcategories = core_course_category::get_many($fullpathcategoryids);
            // Loop over each of these categories and build the category tree.
            foreach ($pathcategories as $coursecat) {
                // No need to process categories that have already been added.
                if (isset($this->addedcategories[$coursecat->id])) {
                    continue;
                }
                // Skip categories that are not visible.
                if (!$coursecat->is_uservisible()) {
                    continue;
                }

                // Get this course category's parent node.
                $parent = null;
                if ($coursecat->parent && isset($this->addedcategories[$coursecat->parent])) {
                    $parent = $this->addedcategories[$coursecat->parent];
                }
                if (!$parent) {
                    // If it has no parent, then it should be right under the My courses node.
                    $parent = $this->rootnodes['mycourses'];
                }

                // Build the category object based from the coursecat object.
                $mycategory = new stdClass();
                $mycategory->id = $coursecat->id;
                $mycategory->name = $coursecat->name;
                $mycategory->visible = $coursecat->visible;

                // Add this category to the nav tree.
                $this->add_category($mycategory, $parent, self::TYPE_MY_CATEGORY);
            }
        }

        // Go through each course now and add it to the nav block, and the flatnav if applicable.
        foreach ($courses as $course) {
            $node = $this->add_course($course, false, self::COURSE_MY);
            if ($node) {
                $node->showinflatnavigation = false;
                // Check if we should also add this to the flat nav as well.
                if (isset($flatnavcourses[$course->id])) {
                    $node->showinflatnavigation = true;
                }
            }
        }

        // Go through each course in the flatnav now.
        foreach ($flatnavcourses as $course) {
            // Check if we haven't already added it.
            if (!isset($courses[$course->id])) {
                // Ok, add it to the flatnav only.
                $node = $this->add_course($course, false, self::COURSE_MY);
                $node->display = false;
                $node->showinflatnavigation = true;
            }
        }

        $showmorelinkinnav = $numtotalcourses > $numshowncourses;
        $showmorelinkinflatnav = $numtotalflatnavcourses > $numshownflatnavcourses;
        // Show a link to the course page if there are more courses the user is enrolled in.
        if ($showmorelinkinnav || $showmorelinkinflatnav) {
            // Adding hash to URL so the link is not highlighted in the navigation when clicked.
            $url = new moodle_url('/my/');
            $parent = $this->rootnodes['mycourses'];
            $coursenode = $parent->add(get_string('morenavigationlinks'), $url, self::TYPE_CUSTOM, null, self::COURSE_INDEX_PAGE);

            if ($showmorelinkinnav) {
                $coursenode->display = true;
            }

            if ($showmorelinkinflatnav) {
                $coursenode->showinflatnavigation = true;
            }
        }
    }
728371
public final Program program() throws RecognitionException {
		Program program = null;


		QueryProgram s1 =null;
		InsertProgram s2 =null;
		DeleteProgram s3 =null;
		DropProgram s4 =null;

		 program = null; 
		try {
			// druidG.g:45:2: ( (s1= grandQuery ) | (s2= grandInsert ) | (s3= grandDelete ) | (s4= grandDrop ) )
			int alt1=4;
			switch ( input.LA(1) ) {
			case SELECT:
				{
				alt1=1;
				}
				break;
			case INSERT:
			case INSERT_HADOOP:
			case INSERT_REALTIME:
				{
				alt1=2;
				}
				break;
			case DELETE:
				{
				alt1=3;
				}
				break;
			case DROP:
				{
				alt1=4;
				}
				break;
			default:
				NoViableAltException nvae =
					new NoViableAltException("", 1, 0, input);
				throw nvae;
			}
			switch (alt1) {
				case 1 :
					// druidG.g:45:4: (s1= grandQuery )
					{
					// druidG.g:45:4: (s1= grandQuery )
					// druidG.g:45:5: s1= grandQuery
					{
					pushFollow(FOLLOW_grandQuery_in_program49);
					s1=grandQuery();
					state._fsp--;

					}

					 program = s1; 
					}
					break;
				case 2 :
					// druidG.g:46:4: (s2= grandInsert )
					{
					// druidG.g:46:4: (s2= grandInsert )
					// druidG.g:46:5: s2= grandInsert
					{
					pushFollow(FOLLOW_grandInsert_in_program61);
					s2=grandInsert();
					state._fsp--;

					}

					 program = s2; 
					}
					break;
				case 3 :
					// druidG.g:47:4: (s3= grandDelete )
					{
					// druidG.g:47:4: (s3= grandDelete )
					// druidG.g:47:5: s3= grandDelete
					{
					pushFollow(FOLLOW_grandDelete_in_program73);
					s3=grandDelete();
					state._fsp--;

					}

					 program = s3; 
					}
					break;
				case 4 :
					// druidG.g:48:4: (s4= grandDrop )
					{
					// druidG.g:48:4: (s4= grandDrop )
					// druidG.g:48:5: s4= grandDrop
					{
					pushFollow(FOLLOW_grandDrop_in_program85);
					s4=grandDrop();
					state._fsp--;

					}

					 program = s4; 
					}
					break;

			}
		}
		catch (RecognitionException re) {
			reportError(re);
			recover(input,re);
		}
		finally {
			// do for sure before leaving
		}
		return program;
	}
623588
public function define_enrol_plugin_structure() {
        // Get the parent we will be adding these elements to.
        $plugin = $this->get_plugin_element();

        // Define our elements.
        $tool = new backup_nested_element('tool', array('id'), array(
            'enrolid', 'contextid', 'institution', 'lang', 'timezone', 'maxenrolled', 'maildisplay', 'city',
            'country', 'gradesync', 'gradesynccompletion', 'membersync', 'membersyncmode',  'roleinstructor',
            'rolelearner', 'secret', 'timecreated', 'timemodified'));

        $users = new backup_nested_element('users');

        $user = new backup_nested_element('user', array('id'), array(
            'userid', 'toolid', 'serviceurl', 'sourceid', 'consumerkey', 'consumersecret', 'membershipurl',
            'membershipsid'));

        // Build elements hierarchy.
        $plugin->add_child($tool);
        $tool->add_child($users);
        $users->add_child($user);

        // Set sources to populate the data.
        $tool->set_source_table('enrol_lti_tools',
            array('enrolid' => backup::VAR_PARENTID));

        // Users are only added only if users included.
        if ($this->task->get_setting_value('users')) {
            $user->set_source_table('enrol_lti_users', array('toolid' => backup::VAR_PARENTID));
        }
    }
607200
function postprocessProgram(program) {
      var body = program.body;

      if (body.length === 0) {
        return;
      }

      if (usesMorph(body[0])) {
        body.unshift(buildText(''));
      }

      if (usesMorph(body[body.length-1])) {
        body.push(buildText(''));
      }
    }
811317
public function process(course_enrolment_manager $manager, array $users, stdClass $properties) {
        global $DB, $USER;

        if (!has_capability("enrol/manual:manage", $manager->get_context())) {
            return false;
        }

        // Get all of the user enrolment id's.
        $ueids = array();
        $instances = array();
        foreach ($users as $user) {
            foreach ($user->enrolments as $enrolment) {
                $ueids[] = $enrolment->id;
                if (!array_key_exists($enrolment->id, $instances)) {
                    $instances[$enrolment->id] = $enrolment;
                }
            }
        }

        // Check that each instance is manageable by the current user.
        foreach ($instances as $instance) {
            if (!$this->plugin->allow_manage($instance)) {
                return false;
            }
        }

        // Collect the known properties.
        $status = $properties->status;
        $timestart = $properties->timestart;
        $timeend = $properties->timeend;

        list($ueidsql, $params) = $DB->get_in_or_equal($ueids, SQL_PARAMS_NAMED);

        $updatesql = array();
        if ($status == ENROL_USER_ACTIVE || $status == ENROL_USER_SUSPENDED) {
            $updatesql[] = 'status = :status';
            $params['status'] = (int)$status;
        }
        if (!empty($timestart)) {
            $updatesql[] = 'timestart = :timestart';
            $params['timestart'] = (int)$timestart;
        }
        if (!empty($timeend)) {
            $updatesql[] = 'timeend = :timeend';
            $params['timeend'] = (int)$timeend;
        }
        if (empty($updatesql)) {
            return true;
        }

        // Update the modifierid.
        $updatesql[] = 'modifierid = :modifierid';
        $params['modifierid'] = (int)$USER->id;

        // Update the time modified.
        $updatesql[] = 'timemodified = :timemodified';
        $params['timemodified'] = time();

        // Build the SQL statement.
        $updatesql = join(', ', $updatesql);
        $sql = "UPDATE {user_enrolments}
                   SET $updatesql
                 WHERE id $ueidsql";

        if ($DB->execute($sql, $params)) {
            foreach ($users as $user) {
                foreach ($user->enrolments as $enrolment) {
                    $enrolment->courseid  = $enrolment->enrolmentinstance->courseid;
                    $enrolment->enrol     = 'manual';
                    // Trigger event.
                    $event = \core\event\user_enrolment_updated::create(
                            array(
                                'objectid' => $enrolment->id,
                                'courseid' => $enrolment->courseid,
                                'context' => context_course::instance($enrolment->courseid),
                                'relateduserid' => $user->id,
                                'other' => array('enrol' => 'manual')
                                )
                            );
                    $event->trigger();
                }
            }
            // Delete cached course contacts for this course because they may be affected.
            cache::make('core', 'coursecontacts')->delete($manager->get_context()->instanceid);
            return true;
        }

        return false;
    }
1136967
public function init()
    {
        $this->setName('emails')
             ->setLabel(/* @translate */ 'E-Mail Notifications');
        
        $this->add(
            array('type' => Checkbox::class,
                'name' => 'mailAccess',
                'label' => 'foo',
                'options' => array('label' => /* @translate */ 'receive E-Mail alert',
                                   'long_label' => /* @translate */ 'if checked, you\'ll be informed by mail about new applications.'),
                )
        );
        $this->add(
            array('type' => 'Zend\Form\Element\Textarea',
                'name' => 'mailAccessText',
                'options' => array('label' => /* @translate */ 'Mailtext',
                                            'description' => /* @translate */ 'default text of the notification mail about new applications. The following variables can be used:<ul><li>##name## = your name</li><li>##title## = title of the job</li><li>##link## = Url of the application detail page</li></ul>'))
        );
        
        $this->add(
            array('type' => 'Zend\Form\Element\Checkbox',
                'name' => 'autoConfirmMail',
                'options' => array('label' => /* @translate */ 'confirm application immidiatly after submit',
                                   'long_label' => /* @translate */ 'if checked, an application is immediatly confirmed. If unchecked confirmation is the duty of the recruiter.'),
                )
        );
        $this->add(
            array('type' => 'Zend\Form\Element\Textarea',
                        'name' => 'mailConfirmationText',
                         'options' => array('label' => /* @translate */ 'Confirmation mail text',
                                            'description' => /* @translate */ 'default text of the acknowledgment of receipt mail to the applicant. The following variables can be used:<br><ul><li>##anrede_formell## = salutation. Includes gender, firstname and lastname.<li>##anrede_informell## = salutation. Includes fistname and lastname.</li><li>##job_title## = title of the jobs</li><li>##name## = name of the applicant.</li><li>##date## = date of recipt of the application.</li><li>##link## = Link to the application details</li></ul>' ))
        );
        
        $this->add(
            array('type' => 'Zend\Form\Element\Textarea',
                'name' => 'mailInvitationText',
                'options' => array('label' => /* @translate */ 'Invitation mail text',
                                    'description'=> /* @translate */ 'default text of the invitation mail to the applicant. You can use all variables of the acknowledgment of receipt mail. '
                                    ))
        );

        $this->add(
            [
                'type' => 'Zend\Form\Element\Textarea',
                'name' => 'mailAcceptedText',
                'options' => [
                    'label' => /* @translate */ 'Accept mail text',
                    'description'=> /* @translate */ 'default text, when accepting an applicant. This mail is send to by a domain admin to the recruiter, who is responsible for the job posting.'
                ]
            ]
        );
        
        $this->add(
            [
                'type' => 'Zend\Form\Element\Textarea',
                'name' => 'mailRejectionText',
                'options' => [
                    'label' => /* @translate */ 'Rejection mail text',
                    'description' => /* @translate */ 'default text of the refusal of an application to the applicant. You can use all variables of the acknowledgment of receipt mail.'
                ]
            ]
        );
        
        $this->add(
            [
                'type' => 'Zend\Form\Element\Checkbox',
                'name' => 'mailBCC',
                'options' => [
                    'label' => /* @translate */ 'get blind carbon copy of all own mails',
                    'long_label' => /* @translate */ 'if checked, you\'ll get a copy of all mails you send.',
                    'value_options' => [0, 1, true, false]
                ]
            ]
        );

        $this->add(
            array(
                'type' => 'Settings/DisableElementsCapableFormSettingsFieldset',
                'name' => 'applyFormSettings',
                'options' => array(
    
                )
            )
        );
    }