/**
  * Delete groups
  *
  * @param array $groupids array of group ids
  * @since Moodle 2.2
  */
 public static function delete_groups($groupids)
 {
     global $CFG, $DB;
     require_once "{$CFG->dirroot}/group/lib.php";
     $params = self::validate_parameters(self::delete_groups_parameters(), array('groupids' => $groupids));
     $transaction = $DB->start_delegated_transaction();
     foreach ($params['groupids'] as $groupid) {
         // validate params
         $groupid = validate_param($groupid, PARAM_INT);
         if (!($group = groups_get_group($groupid, '*', IGNORE_MISSING))) {
             // silently ignore attempts to delete nonexisting groups
             continue;
         }
         // now security checks
         $context = context_course::instance($group->courseid, IGNORE_MISSING);
         try {
             self::validate_context($context);
         } catch (Exception $e) {
             $exceptionparam = new stdClass();
             $exceptionparam->message = $e->getMessage();
             $exceptionparam->courseid = $group->courseid;
             throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
         }
         require_capability('moodle/course:managegroups', $context);
         groups_delete_group($group);
     }
     $transaction->allow_commit();
 }
 public function test_validate_param()
 {
     try {
         $param = validate_param('11a', PARAM_INT);
         $this->fail('invalid_parameter_exception expected');
     } catch (moodle_exception $ex) {
         $this->assertInstanceOf('invalid_parameter_exception', $ex);
     }
     $param = validate_param('11', PARAM_INT);
     $this->assertSame(11, $param);
     try {
         $param = validate_param(null, PARAM_INT, false);
         $this->fail('invalid_parameter_exception expected');
     } catch (moodle_exception $ex) {
         $this->assertInstanceOf('invalid_parameter_exception', $ex);
     }
     $param = validate_param(null, PARAM_INT, true);
     $this->assertSame(null, $param);
     try {
         $param = validate_param(array(), PARAM_INT);
         $this->fail('invalid_parameter_exception expected');
     } catch (moodle_exception $ex) {
         $this->assertInstanceOf('invalid_parameter_exception', $ex);
     }
     try {
         $param = validate_param(new stdClass(), PARAM_INT);
         $this->fail('invalid_parameter_exception expected');
     } catch (moodle_exception $ex) {
         $this->assertInstanceOf('invalid_parameter_exception', $ex);
     }
     $param = validate_param('1.0', PARAM_FLOAT);
     $this->assertSame(1.0, $param);
     // Make sure valid floats do not cause exception.
     validate_param(1.0, PARAM_FLOAT);
     validate_param(10, PARAM_FLOAT);
     validate_param('0', PARAM_FLOAT);
     validate_param('119813454.545464564564546564545646556564465465456465465465645645465645645645', PARAM_FLOAT);
     validate_param('011.1', PARAM_FLOAT);
     validate_param('11', PARAM_FLOAT);
     validate_param('+.1', PARAM_FLOAT);
     validate_param('-.1', PARAM_FLOAT);
     validate_param('1e10', PARAM_FLOAT);
     validate_param('.1e+10', PARAM_FLOAT);
     validate_param('1E-1', PARAM_FLOAT);
     try {
         $param = validate_param('1,2', PARAM_FLOAT);
         $this->fail('invalid_parameter_exception expected');
     } catch (moodle_exception $ex) {
         $this->assertInstanceOf('invalid_parameter_exception', $ex);
     }
     try {
         $param = validate_param('', PARAM_FLOAT);
         $this->fail('invalid_parameter_exception expected');
     } catch (moodle_exception $ex) {
         $this->assertInstanceOf('invalid_parameter_exception', $ex);
     }
     try {
         $param = validate_param('.', PARAM_FLOAT);
         $this->fail('invalid_parameter_exception expected');
     } catch (moodle_exception $ex) {
         $this->assertInstanceOf('invalid_parameter_exception', $ex);
     }
     try {
         $param = validate_param('e10', PARAM_FLOAT);
         $this->fail('invalid_parameter_exception expected');
     } catch (moodle_exception $ex) {
         $this->assertInstanceOf('invalid_parameter_exception', $ex);
     }
     try {
         $param = validate_param('abc', PARAM_FLOAT);
         $this->fail('invalid_parameter_exception expected');
     } catch (moodle_exception $ex) {
         $this->assertInstanceOf('invalid_parameter_exception', $ex);
     }
 }
Example #3
0
 function test_validate_param()
 {
     try {
         $param = validate_param('11a', PARAM_INT);
         $this->fail('invalid_parameter_exception expected');
     } catch (invalid_parameter_exception $ex) {
         $this->assertTrue(true);
     }
     try {
         $param = validate_param('11', PARAM_INT);
         $this->assertEqual($param, 11);
     } catch (invalid_parameter_exception $ex) {
         $this->fail('invalid_parameter_exception not expected');
     }
     try {
         $param = validate_param(null, PARAM_INT, false);
         $this->fail('invalid_parameter_exception expected');
     } catch (invalid_parameter_exception $ex) {
         $this->assertTrue(true);
     }
     try {
         $param = validate_param(null, PARAM_INT, true);
         $this->assertTrue($param === null);
     } catch (invalid_parameter_exception $ex) {
         $this->fail('invalid_parameter_exception expected');
     }
     try {
         $param = validate_param(array(), PARAM_INT);
         $this->fail('invalid_parameter_exception expected');
     } catch (invalid_parameter_exception $ex) {
         $this->assertTrue(true);
     }
     try {
         $param = validate_param(new stdClass(), PARAM_INT);
         $this->fail('invalid_parameter_exception expected');
     } catch (invalid_parameter_exception $ex) {
         $this->assertTrue(true);
     }
 }
Example #4
0
 /**
  * Updates a reference to the external resource and all files that use it
  *
  * This function is called after synchronisation of an external file and updates the
  * contenthash, filesize and status of all files that reference this external file
  * as well as time last synchronised.
  *
  * @param int $referencefileid
  * @param int $lastsync
  * @param int $lifetime argument not used any more, liefetime is returned by repository
  * @param string $contenthash
  * @param int $filesize
  * @param int $status 0 if ok or 666 if source is missing
  * @param int $timemodified last time modified of the source, if known
  */
 public function update_references($referencefileid, $lastsync, $lifetime, $contenthash, $filesize, $status, $timemodified = null)
 {
     global $DB;
     $referencefileid = clean_param($referencefileid, PARAM_INT);
     $lastsync = clean_param($lastsync, PARAM_INT);
     validate_param($contenthash, PARAM_TEXT, NULL_NOT_ALLOWED);
     $filesize = clean_param($filesize, PARAM_INT);
     $status = clean_param($status, PARAM_INT);
     $params = array('contenthash' => $contenthash, 'filesize' => $filesize, 'status' => $status, 'referencefileid' => $referencefileid, 'timemodified' => $timemodified);
     $DB->execute('UPDATE {files} SET contenthash = :contenthash, filesize = :filesize,
         status = :status ' . ($timemodified ? ', timemodified = :timemodified' : '') . '
         WHERE referencefileid = :referencefileid', $params);
     $data = array('id' => $referencefileid, 'lastsync' => $lastsync);
     $DB->update_record('files_reference', (object) $data);
 }
Example #5
0
 /**
  * Clean response
  * If a response attribute is unknown from the description, we just ignore the attribute.
  * If a response attribute is incorrect, invalid_response_exception is thrown.
  * Note: this function is similar to validate parameters, however it is distinct because
  * parameters validation must be distinct from cleaning return values.
  *
  * @param external_description $description description of the return values
  * @param mixed $response the actual response
  * @return mixed response with added defaults for optional items, invalid_response_exception thrown if any problem found
  * @author 2010 Jerome Mouneyrac
  * @since Moodle 2.0
  */
 public static function clean_returnvalue(external_description $description, $response)
 {
     if ($description instanceof external_value) {
         if (is_array($response) or is_object($response)) {
             throw new invalid_response_exception('Scalar type expected, array or object received.');
         }
         if ($description->type == PARAM_BOOL) {
             // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
             if (is_bool($response) or $response === 0 or $response === 1 or $response === '0' or $response === '1') {
                 return (bool) $response;
             }
         }
         $debuginfo = 'Invalid external api response: the value is "' . $response . '", the server was expecting "' . $description->type . '" type';
         try {
             return validate_param($response, $description->type, $description->allownull, $debuginfo);
         } catch (invalid_parameter_exception $e) {
             //proper exception name, to be recursively catched to build the path to the faulty attribut
             throw new invalid_response_exception($e->debuginfo);
         }
     } else {
         if ($description instanceof external_single_structure) {
             if (!is_array($response) && !is_object($response)) {
                 throw new invalid_response_exception('Only arrays/objects accepted. The bad value is: \'' . print_r($response, true) . '\'');
             }
             // Cast objects into arrays.
             if (is_object($response)) {
                 $response = (array) $response;
             }
             $result = array();
             foreach ($description->keys as $key => $subdesc) {
                 if (!array_key_exists($key, $response)) {
                     if ($subdesc->required == VALUE_REQUIRED) {
                         throw new invalid_response_exception('Error in response - Missing following required key in a single structure: ' . $key);
                     }
                     if ($subdesc instanceof external_value) {
                         if ($subdesc->required == VALUE_DEFAULT) {
                             try {
                                 $result[$key] = self::clean_returnvalue($subdesc, $subdesc->default);
                             } catch (invalid_response_exception $e) {
                                 //build the path to the faulty attribut
                                 throw new invalid_response_exception($key . " => " . $e->getMessage() . ': ' . $e->debuginfo);
                             }
                         }
                     }
                 } else {
                     try {
                         $result[$key] = self::clean_returnvalue($subdesc, $response[$key]);
                     } catch (invalid_response_exception $e) {
                         //build the path to the faulty attribut
                         throw new invalid_response_exception($key . " => " . $e->getMessage() . ': ' . $e->debuginfo);
                     }
                 }
                 unset($response[$key]);
             }
             return $result;
         } else {
             if ($description instanceof external_multiple_structure) {
                 if (!is_array($response)) {
                     throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' . print_r($response, true) . '\'');
                 }
                 $result = array();
                 foreach ($response as $param) {
                     $result[] = self::clean_returnvalue($description->content, $param);
                 }
                 return $result;
             } else {
                 throw new invalid_response_exception('Invalid external api response description');
             }
         }
     }
 }
Example #6
0
 /**
  * Delete cohorts
  *
  * @param array $cohortids
  * @return null
  * @since Moodle 2.5
  */
 public static function delete_cohorts($cohortids)
 {
     global $CFG, $DB;
     require_once "{$CFG->dirroot}/cohort/lib.php";
     $params = self::validate_parameters(self::delete_cohorts_parameters(), array('cohortids' => $cohortids));
     $transaction = $DB->start_delegated_transaction();
     foreach ($params['cohortids'] as $cohortid) {
         // Validate params.
         $cohortid = validate_param($cohortid, PARAM_INT);
         $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
         // Now security checks.
         $context = context::instance_by_id($cohort->contextid, MUST_EXIST);
         if ($context->contextlevel != CONTEXT_COURSECAT and $context->contextlevel != CONTEXT_SYSTEM) {
             throw new invalid_parameter_exception('Invalid context');
         }
         self::validate_context($context);
         require_capability('moodle/cohort:manage', $context);
         cohort_delete_cohort($cohort);
     }
     $transaction->allow_commit();
     return null;
 }
Example #7
0
 /**
  * Clean response
  * If a response attribute is unknown from the description, we just ignore the attribute.
  * If a response attribute is incorrect, invalid_response_exception is thrown.
  * Note: this function is similar to validate parameters, however it is distinct because
  * parameters validation must be distinct from cleaning return values.
  * @param external_description $description description of the return values
  * @param mixed $response the actual response
  * @return mixed response with added defaults for optional items, invalid_response_exception thrown if any problem found
  */
 public static function clean_returnvalue(external_description $description, $response)
 {
     if ($description instanceof external_value) {
         if (is_array($response) or is_object($response)) {
             throw new invalid_response_exception(get_string('errorscalartype', 'webservice'));
         }
         if ($description->type == PARAM_BOOL) {
             // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
             if (is_bool($response) or $response === 0 or $response === 1 or $response === '0' or $response === '1') {
                 return (bool) $response;
             }
         }
         return validate_param($response, $description->type, $description->allownull, get_string('errorinvalidresponseapi', 'webservice'));
     } else {
         if ($description instanceof external_single_structure) {
             if (!is_array($response)) {
                 throw new invalid_response_exception(get_string('erroronlyarray', 'webservice'));
             }
             $result = array();
             foreach ($description->keys as $key => $subdesc) {
                 if (!array_key_exists($key, $response)) {
                     if ($subdesc->required == VALUE_REQUIRED) {
                         throw new webservice_parameter_exception('errorresponsemissingkey', $key);
                     }
                     if ($subdesc instanceof external_value) {
                         if ($subdesc->required == VALUE_DEFAULT) {
                             try {
                                 $result[$key] = self::clean_returnvalue($subdesc, $subdesc->default);
                             } catch (Exception $e) {
                                 throw new webservice_parameter_exception('invalidextresponse', $key . " (" . $e->debuginfo . ")");
                             }
                         }
                     }
                 } else {
                     try {
                         $result[$key] = self::clean_returnvalue($subdesc, $response[$key]);
                     } catch (Exception $e) {
                         //it's ok to display debug info as here the information is useful for ws client/dev
                         throw new webservice_parameter_exception('invalidextresponse', $key . " (" . $e->debuginfo . ")");
                     }
                 }
                 unset($response[$key]);
             }
             return $result;
         } else {
             if ($description instanceof external_multiple_structure) {
                 if (!is_array($response)) {
                     throw new invalid_response_exception(get_string('erroronlyarray', 'webservice'));
                 }
                 $result = array();
                 foreach ($response as $param) {
                     $result[] = self::clean_returnvalue($description->content, $param);
                 }
                 return $result;
             } else {
                 throw new invalid_response_exception(get_string('errorinvalidresponsedesc', 'webservice'));
             }
         }
     }
 }
    function test_validate_param() {
        try {
            $param = validate_param('11a', PARAM_INT);
            $this->fail('invalid_parameter_exception expected');
        } catch (invalid_parameter_exception $ex) {
            $this->assertTrue(true);
        }
        try {
            $param = validate_param('11', PARAM_INT);
            $this->assertEquals($param, 11);
        } catch (invalid_parameter_exception $ex) {
            $this->fail('invalid_parameter_exception not expected');
        }
        try {
            $param = validate_param(null, PARAM_INT, false);
            $this->fail('invalid_parameter_exception expected');
        } catch (invalid_parameter_exception $ex) {
            $this->assertTrue(true);
        }
        try {
            $param = validate_param(null, PARAM_INT, true);
            $this->assertTrue($param===null);
        } catch (invalid_parameter_exception $ex) {
            $this->fail('invalid_parameter_exception expected');
        }
        try {
            $param = validate_param(array(), PARAM_INT);
            $this->fail('invalid_parameter_exception expected');
        } catch (invalid_parameter_exception $ex) {
            $this->assertTrue(true);
        }
        try {
            $param = validate_param(new stdClass, PARAM_INT);
            $this->fail('invalid_parameter_exception expected');
        } catch (invalid_parameter_exception $ex) {
            $this->assertTrue(true);
        }
        try {
            $param = validate_param('1.0', PARAM_FLOAT);
            $this->assertSame(1.0, $param);

            // Make sure valid floats do not cause exception.
            validate_param(1.0, PARAM_FLOAT);
            validate_param(10, PARAM_FLOAT);
            validate_param('0', PARAM_FLOAT);
            validate_param('119813454.545464564564546564545646556564465465456465465465645645465645645645', PARAM_FLOAT);
            validate_param('011.1', PARAM_FLOAT);
            validate_param('11', PARAM_FLOAT);
            validate_param('+.1', PARAM_FLOAT);
            validate_param('-.1', PARAM_FLOAT);
            validate_param('1e10', PARAM_FLOAT);
            validate_param('.1e+10', PARAM_FLOAT);
            validate_param('1E-1', PARAM_FLOAT);
            $this->assertTrue(true);
        } catch (invalid_parameter_exception $ex) {
            $this->fail('Valid float notation not accepted');
        }
        try {
            $param = validate_param('1,2', PARAM_FLOAT);
            $this->fail('invalid_parameter_exception expected');
        } catch (invalid_parameter_exception $ex) {
            $this->assertTrue(true);
        }
        try {
            $param = validate_param('', PARAM_FLOAT);
            $this->fail('invalid_parameter_exception expected');
        } catch (invalid_parameter_exception $ex) {
            $this->assertTrue(true);
        }
        try {
            $param = validate_param('.', PARAM_FLOAT);
            $this->fail('invalid_parameter_exception expected');
        } catch (invalid_parameter_exception $ex) {
            $this->assertTrue(true);
        }
        try {
            $param = validate_param('e10', PARAM_FLOAT);
            $this->fail('invalid_parameter_exception expected');
        } catch (invalid_parameter_exception $ex) {
            $this->assertTrue(true);
        }
        try {
            $param = validate_param('abc', PARAM_FLOAT);
            $this->fail('invalid_parameter_exception expected');
        } catch (invalid_parameter_exception $ex) {
            $this->assertTrue(true);
        }
    }
Example #9
0
 /**
  * Validates the data.
  *
  * Developers can implement addition validation by defining a method as follows. Note that
  * the method MUST return a lang_string() when there is an error, and true when the data is valid.
  *
  * protected function validate_propertyname($value) {
  *     if ($value !== 'My expected value') {
  *         return new lang_string('invaliddata', 'error');
  *     }
  *     return true
  * }
  *
  * It is OK to use other properties in your custom validation methods when you need to, however note
  * they might not have been validated yet, so try not to rely on them too much.
  *
  * Note that the validation methods should be protected. Validating just one field is not
  * recommended because of the possible dependencies between one field and another,also the
  * field ID can be used to check whether the object is being updated or created.
  *
  * When validating foreign keys the persistent should only check that the associated model
  * exists. The validation methods should not be used to check for a change in that relationship.
  * The API method setting the attributes on the model should be responsible for that.
  * E.g. On a course model, the method validate_categoryid will check that the category exists.
  * However, if a course can never be moved outside of its category it would be up to the calling
  * code to ensure that the category ID will not be altered.
  *
  * @return array|true Returns true when the validation passed, or an array of properties with errors.
  */
 public final function validate()
 {
     global $CFG;
     // Before validate hook.
     $this->before_validate();
     // If this object has not been validated yet.
     if ($this->validated !== true) {
         $errors = array();
         $properties = static::properties_definition();
         foreach ($properties as $property => $definition) {
             // Get the data, bypassing the potential custom getter which could alter the data.
             $value = $this->get($property);
             // Check if the property is required.
             if ($value === null && static::is_property_required($property)) {
                 $errors[$property] = new lang_string('requiredelement', 'form');
                 continue;
             }
             // Check that type of value is respected.
             try {
                 if ($definition['type'] === PARAM_BOOL && $value === false) {
                     // Validate_param() does not like false with PARAM_BOOL, better to convert it to int.
                     $value = 0;
                 }
                 validate_param($value, $definition['type'], $definition['null']);
             } catch (invalid_parameter_exception $e) {
                 $errors[$property] = static::get_property_error_message($property);
                 continue;
             }
             // Check that the value is part of a list of allowed values.
             if (isset($definition['choices']) && !in_array($value, $definition['choices'])) {
                 $errors[$property] = static::get_property_error_message($property);
                 continue;
             }
             // Call custom validation method.
             $method = 'validate_' . $property;
             if (method_exists($this, $method)) {
                 // Warn the developers when they are doing something wrong.
                 if ($CFG->debugdeveloper) {
                     $reflection = new ReflectionMethod($this, $method);
                     if (!$reflection->isProtected()) {
                         throw new coding_exception('The method ' . get_class($this) . '::' . $method . ' should be protected.');
                     }
                 }
                 $valid = $this->{$method}($value);
                 if ($valid !== true) {
                     if (!$valid instanceof lang_string) {
                         throw new coding_exception('Unexpected error message.');
                     }
                     $errors[$property] = $valid;
                     continue;
                 }
             }
         }
         $this->validated = true;
         $this->errors = $errors;
     }
     return empty($this->errors) ? true : $this->errors;
 }
Example #10
0
    /**
     * Validates submitted value, comparing it to a description. If anything is incorrect
     * invalid_return_value_exception is thrown. Also casts the values to the type specified in
     * the description.
     *
     * @param external_description $description description of parameters or null if no return value
     * @param mixed $value the actual values
     * @return mixed params with added defaults for optional items
     * @throws invalid_return_value_exception
     */
    public static function validate_and_cast_values($description, $value) {
        if (is_null($description)){
            return;
        }
        if ($description instanceof external_value) {
            if (is_array($value) or is_object($value)) {
                throw new invalid_return_value_exception('Scalar type expected, array or object received.');
            }

            if ($description->type == PARAM_BOOL) {
                // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
                if (is_bool($value) or $value === 0 or $value === 1 or $value === '0' or $value === '1') {
                    return (bool)$value;
                }
            }
            return validate_param($value, $description->type, $description->allownull, 'Invalid external api parameter');

        } else if ($description instanceof external_single_structure) {
            if (!is_array($value)) {
                throw new invalid_return_value_exception('Only arrays accepted.');
            }
            $result = array();
            foreach ($description->keys as $key=>$subdesc) {
                if (!array_key_exists($key, $value)) {
                    if ($subdesc->required == VALUE_REQUIRED) {
                        throw new invalid_return_value_exception('Missing required key in single structure: '.$key);
                    }
                    if ($subdesc instanceof external_value) {
                            if ($subdesc->required == VALUE_DEFAULT) {
                                $result[$key] = self::validate_and_cast_values($subdesc, $subdesc->default);
                            }
                    }
                } else {
                    $result[$key] = self::validate_and_cast_values($subdesc, $value[$key]);
                }
                unset($value[$key]);
            }

            return (object)$result;

        } else if ($description instanceof external_multiple_structure) {
            if (!is_array($value)) {
                throw new invalid_return_value_exception('Only arrays accepted.');
            }
            $result = array();
            foreach ($value as $param) {
                $result[] = self::validate_and_cast_values($description->content, $param);
            }
            return $result;

        } else {
            throw new invalid_return_value_exception('Invalid external api description.');
        }
    }    
Example #11
0
 /**
  * Validate user data.
  *
  * This method just validates each user field and return an array of errors. It doesn't clean the data,
  * the methods clean() and clean_field() should be used for this purpose.
  *
  * @param stdClass|array $data user data object or array to be validated.
  * @return array|true $errors array of errors found on the user object, true if the validation passed.
  */
 public static function validate($data)
 {
     // Get all user profile fields definition.
     self::fill_properties_cache();
     foreach ($data as $property => $value) {
         try {
             if (isset(self::$propertiescache[$property])) {
                 validate_param($value, self::$propertiescache[$property]['type'], self::$propertiescache[$property]['null']);
             }
             // Check that the value is part of a list of allowed values.
             if (!empty(self::$propertiescache[$property]['choices']) && !isset(self::$propertiescache[$property]['choices'][$value])) {
                 throw new invalid_parameter_exception($value);
             }
         } catch (invalid_parameter_exception $e) {
             $errors[$property] = $e->getMessage();
         }
     }
     return empty($errors) ? true : $errors;
 }
Example #12
0
 /**
  * Get the signup required settings and profile fields.
  *
  * @param  string $username               username
  * @param  string $password               plain text password
  * @param  string $firstname              the first name(s) of the user
  * @param  string $lastname               the family name of the user
  * @param  string $email                  a valid and unique email address
  * @param  string $city                   home city of the user
  * @param  string $country                home country code
  * @param  string $recaptchachallengehash recaptcha challenge hash
  * @param  string $recaptcharesponse      recaptcha response
  * @param  array  $customprofilefields    user custom fields (also known as user profile fields)
  * @param  string $redirect               Site url to redirect the user after confirmation
  * @return array settings and possible warnings
  * @since Moodle 3.2
  * @throws moodle_exception
  * @throws invalid_parameter_exception
  */
 public static function signup_user($username, $password, $firstname, $lastname, $email, $city = '', $country = '', $recaptchachallengehash = '', $recaptcharesponse = '', $customprofilefields = array(), $redirect = '')
 {
     global $CFG, $PAGE;
     $warnings = array();
     $params = self::validate_parameters(self::signup_user_parameters(), array('username' => $username, 'password' => $password, 'firstname' => $firstname, 'lastname' => $lastname, 'email' => $email, 'city' => $city, 'country' => $country, 'recaptchachallengehash' => $recaptchachallengehash, 'recaptcharesponse' => $recaptcharesponse, 'customprofilefields' => $customprofilefields, 'redirect' => $redirect));
     // We need this to make work the format text functions.
     $context = context_system::instance();
     $PAGE->set_context($context);
     self::check_signup_enabled();
     // Validate profile fields param types.
     $allowedfields = profile_get_signup_fields();
     $fieldproperties = array();
     $fieldsrequired = array();
     foreach ($allowedfields as $field) {
         $fieldproperties[$field->object->inputname] = $field->object->get_field_properties();
         if ($field->object->is_required()) {
             $fieldsrequired[$field->object->inputname] = true;
         }
     }
     foreach ($params['customprofilefields'] as $profilefield) {
         if (!array_key_exists($profilefield['name'], $fieldproperties)) {
             throw new invalid_parameter_exception('Invalid field' . $profilefield['name']);
         }
         list($type, $allownull) = $fieldproperties[$profilefield['name']];
         validate_param($profilefield['value'], $type, $allownull);
         // Remove from the potential required list.
         if (isset($fieldsrequired[$profilefield['name']])) {
             unset($fieldsrequired[$profilefield['name']]);
         }
     }
     if (!empty($fieldsrequired)) {
         throw new invalid_parameter_exception('Missing required parameters: ' . implode(',', array_keys($fieldsrequired)));
     }
     // Validate the data sent.
     $data = $params;
     $data['email2'] = $data['email'];
     unset($data['recaptcharesponse']);
     unset($data['customprofilefields']);
     // Add profile fields data.
     foreach ($params['customprofilefields'] as $profilefield) {
         // First, check if the value is a json (some profile fields like text area uses an array for sending data).
         $datadecoded = json_decode($profilefield['value'], true);
         if (is_array($datadecoded) && json_last_error() == JSON_ERROR_NONE) {
             $data[$profilefield['name']] = $datadecoded;
         } else {
             $data[$profilefield['name']] = $profilefield['value'];
         }
     }
     $errors = signup_validate_data($data, array());
     // Validate recaptcha.
     if (signup_captcha_enabled()) {
         require_once $CFG->libdir . '/recaptchalib.php';
         $response = recaptcha_check_answer($CFG->recaptchaprivatekey, getremoteaddr(), $params['recaptchachallengehash'], $params['recaptcharesponse'], true);
         if (!$response->is_valid) {
             $errors['recaptcharesponse'] = $response->error;
         }
     }
     if (!empty($errors)) {
         foreach ($errors as $itemname => $message) {
             $warnings[] = array('item' => $itemname, 'itemid' => 0, 'warningcode' => 'fielderror', 'message' => s($message));
         }
         $result = array('success' => false, 'warnings' => $warnings);
     } else {
         // Save the user.
         $user = signup_setup_new_user((object) $data);
         $authplugin = get_auth_plugin('email');
         // Check if we should redirect the user once the user is confirmed.
         $confirmationurl = null;
         if (!empty($params['redirect'])) {
             // Pass via moodle_url to fix thinks like admin links.
             $redirect = new moodle_url($params['redirect']);
             $confirmationurl = new moodle_url('/login/confirm.php', array('redirect' => $redirect->out()));
         }
         $authplugin->user_signup_with_confirmation($user, false, $confirmationurl);
         $result = array('success' => true, 'warnings' => array());
     }
     return $result;
 }
Example #13
0
require_once $CFG->libdir . '/adminlib.php';
$help = "Search and replace text throughout the whole database.\n\nOptions:\n--search=STRING       String to search for.\n--replace=STRING      String to replace with.\n--shorten             Shorten result if necessary.\n--non-interactive     Perform the replacement without confirming.\n-h, --help            Print out this help.\n\nExample:\n\$ sudo -u www-data /usr/bin/php admin/tool/replace/cli/replace.php --search=//oldsitehost --replace=//newsitehost\n";
list($options, $unrecognized) = cli_get_params(array('search' => null, 'replace' => null, 'shorten' => false, 'non-interactive' => false, 'help' => false), array('h' => 'help'));
if ($options['help'] || $options['search'] === null || $options['replace'] === null) {
    echo $help;
    exit(0);
}
if (!$DB->replace_all_text_supported()) {
    cli_error(get_string('notimplemented', 'tool_replace'));
}
if (empty($options['shorten']) && core_text::strlen($options['search']) < core_text::strlen($options['replace'])) {
    cli_error(get_string('cannotfit', 'tool_replace'));
}
try {
    $search = validate_param($options['search'], PARAM_RAW);
    $replace = validate_param($options['replace'], PARAM_RAW);
} catch (invalid_parameter_exception $e) {
    cli_error(get_string('invalidcharacter', 'tool_replace'));
}
if (!$options['non-interactive']) {
    echo get_string('excludedtables', 'tool_replace') . "\n\n";
    echo get_string('notsupported', 'tool_replace') . "\n\n";
    $prompt = get_string('cliyesnoprompt', 'admin');
    $input = cli_input($prompt, '', array(get_string('clianswerno', 'admin'), get_string('cliansweryes', 'admin')));
    if ($input == get_string('clianswerno', 'admin')) {
        exit(1);
    }
}
if (!db_replace($search, $replace)) {
    cli_heading(get_string('error'));
    exit(1);
 /**
  * Cleans the grades data and maps the userid to the internal id.
  *
  * @param array $grades An array user grade details.
  * @throws invalid_parameter_exception if $param is not of given type
  * @return array|null
  */
 protected static function validate_grades($grades)
 {
     global $DB;
     if (!$grades or $grades == "null") {
         return null;
     }
     // The following are the variables that can be passed via grades.
     // We ignore any other variables.
     $allowed = array('userid' => PARAM_TEXT, 'rawgrade' => PARAM_FLOAT, 'identity_type' => PARAM_ALPHA);
     $details = array();
     // Check type of each parameter.
     foreach ($allowed as $var => $type) {
         if (isset($grades[$var]) and $grades[$var] !== '') {
             $details[$var] = validate_param($grades[$var], $type);
         }
     }
     // Map userID to numerical userID if required.
     $idtype = !empty($details['identity_type']) ? $details['identity_type'] : null;
     if (!$idtype or $idtype != 'lti') {
         $userid = $DB->get_field('user', 'id', array('username' => $details['userid']));
         if ($userid !== false) {
             $details['userid'] = $userid;
         }
     }
     return $details;
 }
Example #15
0
 /**
  * Validate the rule config.
  *
  * @param string $value The value to validate.
  * @return bool
  */
 public function validate_config($value)
 {
     $compids = array();
     $config = json_decode($value);
     if ($config === null || !isset($config->base) || !isset($config->competencies)) {
         return false;
     }
     if (!isset($config->base->points)) {
         return false;
     }
     try {
         $requiredpoints = validate_param($config->base->points, PARAM_INT);
     } catch (\invalid_parameter_exception $e) {
         return false;
     }
     if ($requiredpoints < 1) {
         return false;
     }
     $totalpoints = 0;
     // Validate the competency info.
     foreach ($config->competencies as $competency) {
         // Cannot include self.
         if ($competency->id == $this->competency->get_id()) {
             return false;
         }
         // Check for duplicates.
         if (in_array($competency->id, $compids)) {
             return false;
         }
         // Check for required fields.
         if (!isset($competency->id) || !isset($competency->points) || !isset($competency->required)) {
             return false;
         }
         // Validate the parameters.
         try {
             validate_param($competency->id, PARAM_INT);
             $points = validate_param($competency->points, PARAM_INT);
             validate_param($competency->required, PARAM_BOOL);
         } catch (\invalid_parameter_exception $e) {
             return false;
         }
         $totalpoints += $points;
         if ($points < 0) {
             return false;
         }
         $compids[] = $competency->id;
     }
     // No competencies, that's strange.
     if (empty($compids)) {
         return false;
     }
     // Impossible to reach the points required.
     if ($requiredpoints > $totalpoints) {
         return false;
     }
     // Check that all the competencies are children of the competency.
     // We may want to relax this check at a later stage if we want to allow competencies
     // to be linked throughout the whole framework.
     return $this->competency->is_parent_of($compids);
 }