Example #1
0
/**
 * Used by {@link optional_param()} and {@link required_param()} to
 * clean the variables and/or cast to specific types, based on
 * an options field.
 * <code>
 * $course->format = clean_param($course->format, PARAM_ALPHA);
 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_CLEAN);
 * </code>
 *
 * @uses $CFG
 * @uses PARAM_RAW
 * @uses PARAM_CLEAN
 * @uses PARAM_CLEANHTML
 * @uses PARAM_INT
 * @uses PARAM_NUMBER
 * @uses PARAM_ALPHA
 * @uses PARAM_ALPHANUM
 * @uses PARAM_ALPHAEXT
 * @uses PARAM_SEQUENCE
 * @uses PARAM_BOOL
 * @uses PARAM_NOTAGS
 * @uses PARAM_TEXT
 * @uses PARAM_SAFEDIR
 * @uses PARAM_CLEANFILE
 * @uses PARAM_FILE
 * @uses PARAM_PATH
 * @uses PARAM_HOST
 * @uses PARAM_URL
 * @uses PARAM_LOCALURL
 * @uses PARAM_PEM
 * @uses PARAM_BASE64
 * @uses PARAM_TAG
 * @uses PARAM_SEQUENCE
 * @param mixed $param the variable we are cleaning
 * @param int $type expected format of param after cleaning.
 * @return mixed
 */
function clean_param($param, $type)
{
    global $CFG;
    if (is_array($param)) {
        // Let's loop
        $newparam = array();
        foreach ($param as $key => $value) {
            $newparam[$key] = clean_param($value, $type);
        }
        return $newparam;
    }
    switch ($type) {
        case PARAM_RAW:
            // no cleaning at all
            return $param;
        case PARAM_CLEAN:
            // General HTML cleaning, try to use more specific type if possible
            if (is_numeric($param)) {
                return $param;
            }
            $param = stripslashes($param);
            // Needed for kses to work fine
            $param = clean_text($param);
            // Sweep for scripts, etc
            return addslashes($param);
            // Restore original request parameter slashes
        // Restore original request parameter slashes
        case PARAM_CLEANHTML:
            // prepare html fragment for display, do not store it into db!!
            $param = stripslashes($param);
            // Remove any slashes
            $param = clean_text($param);
            // Sweep for scripts, etc
            return trim($param);
        case PARAM_INT:
            return (int) $param;
            // Convert to integer
        // Convert to integer
        case PARAM_NUMBER:
            return (double) $param;
            // Convert to integer
        // Convert to integer
        case PARAM_ALPHA:
            // Remove everything not a-z
            return eregi_replace('[^a-zA-Z]', '', $param);
        case PARAM_ALPHANUM:
            // Remove everything not a-zA-Z0-9
            return eregi_replace('[^A-Za-z0-9]', '', $param);
        case PARAM_ALPHAEXT:
            // Remove everything not a-zA-Z/_-
            return eregi_replace('[^a-zA-Z/_-]', '', $param);
        case PARAM_SEQUENCE:
            // Remove everything not 0-9,
            return eregi_replace('[^0-9,]', '', $param);
        case PARAM_BOOL:
            // Convert to 1 or 0
            $tempstr = strtolower($param);
            if ($tempstr == 'on' or $tempstr == 'yes') {
                $param = 1;
            } else {
                if ($tempstr == 'off' or $tempstr == 'no') {
                    $param = 0;
                } else {
                    $param = empty($param) ? 0 : 1;
                }
            }
            return $param;
        case PARAM_NOTAGS:
            // Strip all tags
            return strip_tags($param);
        case PARAM_TEXT:
            // leave only tags needed for multilang
            return clean_param(strip_tags($param, '<lang><span>'), PARAM_CLEAN);
        case PARAM_SAFEDIR:
            // Remove everything not a-zA-Z0-9_-
            return eregi_replace('[^a-zA-Z0-9_-]', '', $param);
        case PARAM_CLEANFILE:
            // allow only safe characters
            return clean_filename($param);
        case PARAM_FILE:
            // Strip all suspicious characters from filename
            $param = ereg_replace('[[:cntrl:]]|[<>"`\\|\':\\/]', '', $param);
            $param = ereg_replace('\\.\\.+', '', $param);
            if ($param == '.') {
                $param = '';
            }
            return $param;
        case PARAM_PATH:
            // Strip all suspicious characters from file path
            $param = str_replace('\\\'', '\'', $param);
            $param = str_replace('\\"', '"', $param);
            $param = str_replace('\\', '/', $param);
            $param = ereg_replace('[[:cntrl:]]|[<>"`\\|\':]', '', $param);
            $param = ereg_replace('\\.\\.+', '', $param);
            $param = ereg_replace('//+', '/', $param);
            return ereg_replace('/(\\./)+', '/', $param);
        case PARAM_HOST:
            // allow FQDN or IPv4 dotted quad
            $param = preg_replace('/[^\\.\\d\\w-]/', '', $param);
            // only allowed chars
            // match ipv4 dotted quad
            if (preg_match('/(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/', $param, $match)) {
                // confirm values are ok
                if ($match[0] > 255 || $match[1] > 255 || $match[3] > 255 || $match[4] > 255) {
                    // hmmm, what kind of dotted quad is this?
                    $param = '';
                }
            } elseif (preg_match('/^[\\w\\d\\.-]+$/', $param) && !preg_match('/^[\\.-]/', $param) && !preg_match('/[\\.-]$/', $param)) {
                // all is ok - $param is respected
            } else {
                // all is not ok...
                $param = '';
            }
            return $param;
        case PARAM_URL:
            // allow safe ftp, http, mailto urls
            include_once $CFG->dirroot . '/lib/validateurlsyntax.php';
            if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
                // all is ok, param is respected
            } else {
                $param = '';
                // not really ok
            }
            return $param;
        case PARAM_LOCALURL:
            // allow http absolute, root relative and relative URLs within wwwroot
            $param = clean_param($param, PARAM_URL);
            if (!empty($param)) {
                if (preg_match(':^/:', $param)) {
                    // root-relative, ok!
                } elseif (preg_match('/^' . preg_quote($CFG->wwwroot, '/') . '/i', $param)) {
                    // absolute, and matches our wwwroot
                } else {
                    // relative - let's make sure there are no tricks
                    if (validateUrlSyntax($param, 's-u-P-a-p-f+q?r?')) {
                        // looks ok.
                    } else {
                        $param = '';
                    }
                }
            }
            return $param;
        case PARAM_PEM:
            $param = trim($param);
            // PEM formatted strings may contain letters/numbers and the symbols
            // forward slash: /
            // plus sign:     +
            // equal sign:    =
            // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
            if (preg_match('/^-----BEGIN CERTIFICATE-----([\\s\\w\\/\\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
                list($wholething, $body) = $matches;
                unset($wholething, $matches);
                $b64 = clean_param($body, PARAM_BASE64);
                if (!empty($b64)) {
                    return "-----BEGIN CERTIFICATE-----\n{$b64}\n-----END CERTIFICATE-----\n";
                } else {
                    return '';
                }
            }
            return '';
        case PARAM_BASE64:
            if (!empty($param)) {
                // PEM formatted strings may contain letters/numbers and the symbols
                // forward slash: /
                // plus sign:     +
                // equal sign:    =
                if (0 >= preg_match('/^([\\s\\w\\/\\+=]+)$/', trim($param))) {
                    return '';
                }
                $lines = preg_split('/[\\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
                // Each line of base64 encoded data must be 64 characters in
                // length, except for the last line which may be less than (or
                // equal to) 64 characters long.
                for ($i = 0, $j = count($lines); $i < $j; $i++) {
                    if ($i + 1 == $j) {
                        if (64 < strlen($lines[$i])) {
                            return '';
                        }
                        continue;
                    }
                    if (64 != strlen($lines[$i])) {
                        return '';
                    }
                }
                return implode("\n", $lines);
            } else {
                return '';
            }
        case PARAM_TAG:
            //as long as magic_quotes_gpc is used, a backslash will be a
            //problem, so remove *all* backslash.
            $param = str_replace('\\', '', $param);
            //convert many whitespace chars into one
            $param = preg_replace('/\\s+/', ' ', $param);
            $textlib = textlib_get_instance();
            $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH);
            return $param;
        case PARAM_TAGLIST:
            $tags = explode(',', $param);
            $result = array();
            foreach ($tags as $tag) {
                $res = clean_param($tag, PARAM_TAG);
                if ($res != '') {
                    $result[] = $res;
                }
            }
            if ($result) {
                return implode(',', $result);
            } else {
                return '';
            }
        default:
            // throw error, switched parameters in optional_param or another serious problem
            error("Unknown parameter type: {$type}");
    }
}
Example #2
0
/**
 * Used by {@link optional_param()} and {@link required_param()} to
 * clean the variables and/or cast to specific types, based on
 * an options field.
 * <code>
 * $course->format = clean_param($course->format, PARAM_ALPHA);
 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
 * </code>
 *
 * @param mixed $param the variable we are cleaning
 * @param string $type expected format of param after cleaning.
 * @return mixed
 * @throws coding_exception
 */
function clean_param($param, $type)
{
    global $CFG;
    if (is_array($param)) {
        throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
    } else {
        if (is_object($param)) {
            if (method_exists($param, '__toString')) {
                $param = $param->__toString();
            } else {
                throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
            }
        }
    }
    switch ($type) {
        case PARAM_RAW:
            // No cleaning at all.
            $param = fix_utf8($param);
            return $param;
        case PARAM_RAW_TRIMMED:
            // No cleaning, but strip leading and trailing whitespace.
            $param = fix_utf8($param);
            return trim($param);
        case PARAM_CLEAN:
            // General HTML cleaning, try to use more specific type if possible this is deprecated!
            // Please use more specific type instead.
            if (is_numeric($param)) {
                return $param;
            }
            $param = fix_utf8($param);
            // Sweep for scripts, etc.
            return clean_text($param);
        case PARAM_CLEANHTML:
            // Clean html fragment.
            $param = fix_utf8($param);
            // Sweep for scripts, etc.
            $param = clean_text($param, FORMAT_HTML);
            return trim($param);
        case PARAM_INT:
            // Convert to integer.
            return (int) $param;
        case PARAM_FLOAT:
            // Convert to float.
            return (double) $param;
        case PARAM_ALPHA:
            // Remove everything not `a-z`.
            return preg_replace('/[^a-zA-Z]/i', '', $param);
        case PARAM_ALPHAEXT:
            // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
            return preg_replace('/[^a-zA-Z_-]/i', '', $param);
        case PARAM_ALPHANUM:
            // Remove everything not `a-zA-Z0-9`.
            return preg_replace('/[^A-Za-z0-9]/i', '', $param);
        case PARAM_ALPHANUMEXT:
            // Remove everything not `a-zA-Z0-9_-`.
            return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
        case PARAM_SEQUENCE:
            // Remove everything not `0-9,`.
            return preg_replace('/[^0-9,]/i', '', $param);
        case PARAM_BOOL:
            // Convert to 1 or 0.
            $tempstr = strtolower($param);
            if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
                $param = 1;
            } else {
                if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
                    $param = 0;
                } else {
                    $param = empty($param) ? 0 : 1;
                }
            }
            return $param;
        case PARAM_NOTAGS:
            // Strip all tags.
            $param = fix_utf8($param);
            return strip_tags($param);
        case PARAM_TEXT:
            // Leave only tags needed for multilang.
            $param = fix_utf8($param);
            // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
            // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
            do {
                if (strpos($param, '</lang>') !== false) {
                    // Old and future mutilang syntax.
                    $param = strip_tags($param, '<lang>');
                    if (!preg_match_all('/<.*>/suU', $param, $matches)) {
                        break;
                    }
                    $open = false;
                    foreach ($matches[0] as $match) {
                        if ($match === '</lang>') {
                            if ($open) {
                                $open = false;
                                continue;
                            } else {
                                break 2;
                            }
                        }
                        if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\\s*>$/u', $match)) {
                            break 2;
                        } else {
                            $open = true;
                        }
                    }
                    if ($open) {
                        break;
                    }
                    return $param;
                } else {
                    if (strpos($param, '</span>') !== false) {
                        // Current problematic multilang syntax.
                        $param = strip_tags($param, '<span>');
                        if (!preg_match_all('/<.*>/suU', $param, $matches)) {
                            break;
                        }
                        $open = false;
                        foreach ($matches[0] as $match) {
                            if ($match === '</span>') {
                                if ($open) {
                                    $open = false;
                                    continue;
                                } else {
                                    break 2;
                                }
                            }
                            if (!preg_match('/^<span(\\s+lang="[a-zA-Z0-9_-]+"|\\s+class="multilang"){2}\\s*>$/u', $match)) {
                                break 2;
                            } else {
                                $open = true;
                            }
                        }
                        if ($open) {
                            break;
                        }
                        return $param;
                    }
                }
            } while (false);
            // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
            return strip_tags($param);
        case PARAM_COMPONENT:
            // We do not want any guessing here, either the name is correct or not
            // please note only normalised component names are accepted.
            if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
                return '';
            }
            if (strpos($param, '__') !== false) {
                return '';
            }
            if (strpos($param, 'mod_') === 0) {
                // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
                if (substr_count($param, '_') != 1) {
                    return '';
                }
            }
            return $param;
        case PARAM_PLUGIN:
        case PARAM_AREA:
            // We do not want any guessing here, either the name is correct or not.
            if (!is_valid_plugin_name($param)) {
                return '';
            }
            return $param;
        case PARAM_SAFEDIR:
            // Remove everything not a-zA-Z0-9_- .
            return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
        case PARAM_SAFEPATH:
            // Remove everything not a-zA-Z0-9/_- .
            return preg_replace('/[^a-zA-Z0-9\\/_-]/i', '', $param);
        case PARAM_FILE:
            // Strip all suspicious characters from filename.
            $param = fix_utf8($param);
            $param = preg_replace('~[[:cntrl:]]|[&<>"`\\|\':\\\\/]~u', '', $param);
            if ($param === '.' || $param === '..') {
                $param = '';
            }
            return $param;
        case PARAM_PATH:
            // Strip all suspicious characters from file path.
            $param = fix_utf8($param);
            $param = str_replace('\\', '/', $param);
            // Explode the path and clean each element using the PARAM_FILE rules.
            $breadcrumb = explode('/', $param);
            foreach ($breadcrumb as $key => $crumb) {
                if ($crumb === '.' && $key === 0) {
                    // Special condition to allow for relative current path such as ./currentdirfile.txt.
                } else {
                    $crumb = clean_param($crumb, PARAM_FILE);
                }
                $breadcrumb[$key] = $crumb;
            }
            $param = implode('/', $breadcrumb);
            // Remove multiple current path (./././) and multiple slashes (///).
            $param = preg_replace('~//+~', '/', $param);
            $param = preg_replace('~/(\\./)+~', '/', $param);
            return $param;
        case PARAM_HOST:
            // Allow FQDN or IPv4 dotted quad.
            $param = preg_replace('/[^\\.\\d\\w-]/', '', $param);
            // Match ipv4 dotted quad.
            if (preg_match('/(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/', $param, $match)) {
                // Confirm values are ok.
                if ($match[0] > 255 || $match[1] > 255 || $match[3] > 255 || $match[4] > 255) {
                    // Hmmm, what kind of dotted quad is this?
                    $param = '';
                }
            } else {
                if (preg_match('/^[\\w\\d\\.-]+$/', $param) && !preg_match('/^[\\.-]/', $param) && !preg_match('/[\\.-]$/', $param)) {
                    // All is ok - $param is respected.
                } else {
                    // All is not ok...
                    $param = '';
                }
            }
            return $param;
        case PARAM_URL:
            // Allow safe ftp, http, mailto urls.
            $param = fix_utf8($param);
            include_once $CFG->dirroot . '/lib/validateurlsyntax.php';
            if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
                // All is ok, param is respected.
            } else {
                // Not really ok.
                $param = '';
            }
            return $param;
        case PARAM_LOCALURL:
            // Allow http absolute, root relative and relative URLs within wwwroot.
            $param = clean_param($param, PARAM_URL);
            if (!empty($param)) {
                // Simulate the HTTPS version of the site.
                $httpswwwroot = str_replace('http://', 'https://', $CFG->wwwroot);
                if ($param === $CFG->wwwroot) {
                    // Exact match;
                } else {
                    if (!empty($CFG->loginhttps) && $param === $httpswwwroot) {
                        // Exact match;
                    } else {
                        if (preg_match(':^/:', $param)) {
                            // Root-relative, ok!
                        } else {
                            if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
                                // Absolute, and matches our wwwroot.
                            } else {
                                if (!empty($CFG->loginhttps) && preg_match('/^' . preg_quote($httpswwwroot . '/', '/') . '/i', $param)) {
                                    // Absolute, and matches our httpswwwroot.
                                } else {
                                    // Relative - let's make sure there are no tricks.
                                    if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
                                        // Looks ok.
                                    } else {
                                        $param = '';
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return $param;
        case PARAM_PEM:
            $param = trim($param);
            // PEM formatted strings may contain letters/numbers and the symbols:
            //   forward slash: /
            //   plus sign:     +
            //   equal sign:    =
            //   , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
            if (preg_match('/^-----BEGIN CERTIFICATE-----([\\s\\w\\/\\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
                list($wholething, $body) = $matches;
                unset($wholething, $matches);
                $b64 = clean_param($body, PARAM_BASE64);
                if (!empty($b64)) {
                    return "-----BEGIN CERTIFICATE-----\n{$b64}\n-----END CERTIFICATE-----\n";
                } else {
                    return '';
                }
            }
            return '';
        case PARAM_BASE64:
            if (!empty($param)) {
                // PEM formatted strings may contain letters/numbers and the symbols
                //   forward slash: /
                //   plus sign:     +
                //   equal sign:    =.
                if (0 >= preg_match('/^([\\s\\w\\/\\+=]+)$/', trim($param))) {
                    return '';
                }
                $lines = preg_split('/[\\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
                // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
                // than (or equal to) 64 characters long.
                for ($i = 0, $j = count($lines); $i < $j; $i++) {
                    if ($i + 1 == $j) {
                        if (64 < strlen($lines[$i])) {
                            return '';
                        }
                        continue;
                    }
                    if (64 != strlen($lines[$i])) {
                        return '';
                    }
                }
                return implode("\n", $lines);
            } else {
                return '';
            }
        case PARAM_TAG:
            $param = fix_utf8($param);
            // Please note it is not safe to use the tag name directly anywhere,
            // it must be processed with s(), urlencode() before embedding anywhere.
            // Remove some nasties.
            $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
            // Convert many whitespace chars into one.
            $param = preg_replace('/\\s+/u', ' ', $param);
            $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
            return $param;
        case PARAM_TAGLIST:
            $param = fix_utf8($param);
            $tags = explode(',', $param);
            $result = array();
            foreach ($tags as $tag) {
                $res = clean_param($tag, PARAM_TAG);
                if ($res !== '') {
                    $result[] = $res;
                }
            }
            if ($result) {
                return implode(',', $result);
            } else {
                return '';
            }
        case PARAM_CAPABILITY:
            if (get_capability_info($param)) {
                return $param;
            } else {
                return '';
            }
        case PARAM_PERMISSION:
            $param = (int) $param;
            if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
                return $param;
            } else {
                return CAP_INHERIT;
            }
        case PARAM_AUTH:
            $param = clean_param($param, PARAM_PLUGIN);
            if (empty($param)) {
                return '';
            } else {
                if (exists_auth_plugin($param)) {
                    return $param;
                } else {
                    return '';
                }
            }
        case PARAM_LANG:
            $param = clean_param($param, PARAM_SAFEDIR);
            if (get_string_manager()->translation_exists($param)) {
                return $param;
            } else {
                // Specified language is not installed or param malformed.
                return '';
            }
        case PARAM_THEME:
            $param = clean_param($param, PARAM_PLUGIN);
            if (empty($param)) {
                return '';
            } else {
                if (file_exists("{$CFG->dirroot}/theme/{$param}/config.php")) {
                    return $param;
                } else {
                    if (!empty($CFG->themedir) and file_exists("{$CFG->themedir}/{$param}/config.php")) {
                        return $param;
                    } else {
                        // Specified theme is not installed.
                        return '';
                    }
                }
            }
        case PARAM_USERNAME:
            $param = fix_utf8($param);
            $param = trim($param);
            // Convert uppercase to lowercase MDL-16919.
            $param = core_text::strtolower($param);
            if (empty($CFG->extendedusernamechars)) {
                $param = str_replace(" ", "", $param);
                // Regular expression, eliminate all chars EXCEPT:
                // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
                $param = preg_replace('/[^-\\.@_a-z0-9]/', '', $param);
            }
            return $param;
        case PARAM_EMAIL:
            $param = fix_utf8($param);
            if (validate_email($param)) {
                return $param;
            } else {
                return '';
            }
        case PARAM_STRINGID:
            if (preg_match('|^[a-zA-Z][a-zA-Z0-9\\.:/_-]*$|', $param)) {
                return $param;
            } else {
                return '';
            }
        case PARAM_TIMEZONE:
            // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
            $param = fix_utf8($param);
            $timezonepattern = '/^(([+-]?(0?[0-9](\\.[5|0])?|1[0-3](\\.0)?|1[0-2]\\.5))|(99)|[[:alnum:]]+(\\/?[[:alpha:]_-])+)$/';
            if (preg_match($timezonepattern, $param)) {
                return $param;
            } else {
                return '';
            }
        default:
            // Doh! throw error, switched parameters in optional_param or another serious problem.
            print_error("unknownparamtype", '', '', $type);
    }
}
 public function validation($data, $files)
 {
     global $CFG;
     $errors = array();
     // Submit is redirected if error occurs, so we store errordata in session.
     $sessionerrordata = array();
     $cache = cache::make('format_socialwall', 'postformerrors');
     $cache->delete($data['id']);
     // ... do validation of externalurl.
     if (!empty($data['externalurl'])) {
         include_once $CFG->libdir . '/validateurlsyntax.php';
         if (!validateUrlSyntax($data['externalurl'])) {
             $errors['externalurl'] = get_string('invalidurl', 'url');
             $sessionerrordata['externalurl'] = array('message' => $errors['externalurl'], 'value' => $data['externalurl']);
         }
     }
     // ... check if post is all empty.
     if (isset($data['submitbutton'])) {
         $empty = empty($data['posttext']) && empty($data['cmsequence']) && empty($data['externalurl']) && empty($files);
         if ($empty) {
             $errors['posttext'] = get_string('attachmentorpostrequired', 'format_socialwall');
             $sessionerrordata['posttext'] = array('message' => $errors['posttext'], 'value' => $data['posttext']);
         }
     }
     // ... store or clean.
     if (!empty($sessionerrordata)) {
         $cache->set($data['id'], $sessionerrordata);
     }
     return $errors;
 }
Example #4
0
/**
 * Used by {@link optional_param()} and {@link required_param()} to
 * clean the variables and/or cast to specific types, based on
 * an options field.
 * <code>
 * $course->format = clean_param($course->format, PARAM_ALPHA);
 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT);
 * </code>
 *
 * @param mixed $param the variable we are cleaning
 * @param int $type expected format of param after cleaning.
 * @return mixed
 */
function clean_param($param, $type)
{
    global $CFG;
    if (is_array($param)) {
        // Let's loop
        $newparam = array();
        foreach ($param as $key => $value) {
            $newparam[$key] = clean_param($value, $type);
        }
        return $newparam;
    }
    switch ($type) {
        case PARAM_RAW:
            // no cleaning at all
            return $param;
        case PARAM_RAW_TRIMMED:
            // no cleaning, but strip leading and trailing whitespace.
            return trim($param);
        case PARAM_CLEAN:
            // General HTML cleaning, try to use more specific type if possible
            // this is deprecated!, please use more specific type instead
            if (is_numeric($param)) {
                return $param;
            }
            return clean_text($param);
            // Sweep for scripts, etc
        // Sweep for scripts, etc
        case PARAM_CLEANHTML:
            // clean html fragment
            $param = clean_text($param, FORMAT_HTML);
            // Sweep for scripts, etc
            return trim($param);
        case PARAM_INT:
            return (int) $param;
            // Convert to integer
        // Convert to integer
        case PARAM_FLOAT:
        case PARAM_NUMBER:
            return (double) $param;
            // Convert to float
        // Convert to float
        case PARAM_ALPHA:
            // Remove everything not a-z
            return preg_replace('/[^a-zA-Z]/i', '', $param);
        case PARAM_ALPHAEXT:
            // Remove everything not a-zA-Z_- (originally allowed "/" too)
            return preg_replace('/[^a-zA-Z_-]/i', '', $param);
        case PARAM_ALPHANUM:
            // Remove everything not a-zA-Z0-9
            return preg_replace('/[^A-Za-z0-9]/i', '', $param);
        case PARAM_ALPHANUMEXT:
            // Remove everything not a-zA-Z0-9_-
            return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
        case PARAM_SEQUENCE:
            // Remove everything not 0-9,
            return preg_replace('/[^0-9,]/i', '', $param);
        case PARAM_BOOL:
            // Convert to 1 or 0
            $tempstr = strtolower($param);
            if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
                $param = 1;
            } else {
                if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
                    $param = 0;
                } else {
                    $param = empty($param) ? 0 : 1;
                }
            }
            return $param;
        case PARAM_NOTAGS:
            // Strip all tags
            return strip_tags($param);
        case PARAM_TEXT:
            // leave only tags needed for multilang
            // if the multilang syntax is not correct we strip all tags
            // because it would break xhtml strict which is required for accessibility standards
            // please note this cleaning does not strip unbalanced '>' for BC compatibility reasons
            do {
                if (strpos($param, '</lang>') !== false) {
                    // old and future mutilang syntax
                    $param = strip_tags($param, '<lang>');
                    if (!preg_match_all('/<.*>/suU', $param, $matches)) {
                        break;
                    }
                    $open = false;
                    foreach ($matches[0] as $match) {
                        if ($match === '</lang>') {
                            if ($open) {
                                $open = false;
                                continue;
                            } else {
                                break 2;
                            }
                        }
                        if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\\s*>$/u', $match)) {
                            break 2;
                        } else {
                            $open = true;
                        }
                    }
                    if ($open) {
                        break;
                    }
                    return $param;
                } else {
                    if (strpos($param, '</span>') !== false) {
                        // current problematic multilang syntax
                        $param = strip_tags($param, '<span>');
                        if (!preg_match_all('/<.*>/suU', $param, $matches)) {
                            break;
                        }
                        $open = false;
                        foreach ($matches[0] as $match) {
                            if ($match === '</span>') {
                                if ($open) {
                                    $open = false;
                                    continue;
                                } else {
                                    break 2;
                                }
                            }
                            if (!preg_match('/^<span(\\s+lang="[a-zA-Z0-9_-]+"|\\s+class="multilang"){2}\\s*>$/u', $match)) {
                                break 2;
                            } else {
                                $open = true;
                            }
                        }
                        if ($open) {
                            break;
                        }
                        return $param;
                    }
                }
            } while (false);
            // easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string()
            return strip_tags($param);
        case PARAM_SAFEDIR:
            // Remove everything not a-zA-Z0-9_-
            return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
        case PARAM_SAFEPATH:
            // Remove everything not a-zA-Z0-9/_-
            return preg_replace('/[^a-zA-Z0-9\\/_-]/i', '', $param);
        case PARAM_FILE:
            // Strip all suspicious characters from filename
            $param = preg_replace('~[[:cntrl:]]|[&<>"`\\|\':\\\\/]~u', '', $param);
            $param = preg_replace('~\\.\\.+~', '', $param);
            if ($param === '.') {
                $param = '';
            }
            return $param;
        case PARAM_PATH:
            // Strip all suspicious characters from file path
            $param = str_replace('\\', '/', $param);
            $param = preg_replace('~[[:cntrl:]]|[&<>"`\\|\':]~u', '', $param);
            $param = preg_replace('~\\.\\.+~', '', $param);
            $param = preg_replace('~//+~', '/', $param);
            return preg_replace('~/(\\./)+~', '/', $param);
        case PARAM_HOST:
            // allow FQDN or IPv4 dotted quad
            $param = preg_replace('/[^\\.\\d\\w-]/', '', $param);
            // only allowed chars
            // match ipv4 dotted quad
            if (preg_match('/(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/', $param, $match)) {
                // confirm values are ok
                if ($match[0] > 255 || $match[1] > 255 || $match[3] > 255 || $match[4] > 255) {
                    // hmmm, what kind of dotted quad is this?
                    $param = '';
                }
            } elseif (preg_match('/^[\\w\\d\\.-]+$/', $param) && !preg_match('/^[\\.-]/', $param) && !preg_match('/[\\.-]$/', $param)) {
                // all is ok - $param is respected
            } else {
                // all is not ok...
                $param = '';
            }
            return $param;
        case PARAM_URL:
            // allow safe ftp, http, mailto urls
            include_once $CFG->dirroot . '/lib/validateurlsyntax.php';
            if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
                // all is ok, param is respected
            } else {
                $param = '';
                // not really ok
            }
            return $param;
        case PARAM_LOCALURL:
            // allow http absolute, root relative and relative URLs within wwwroot
            $param = clean_param($param, PARAM_URL);
            if (!empty($param)) {
                if (preg_match(':^/:', $param)) {
                    // root-relative, ok!
                } elseif (preg_match('/^' . preg_quote($CFG->wwwroot, '/') . '/i', $param)) {
                    // absolute, and matches our wwwroot
                } else {
                    // relative - let's make sure there are no tricks
                    if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
                        // looks ok.
                    } else {
                        $param = '';
                    }
                }
            }
            return $param;
        case PARAM_PEM:
            $param = trim($param);
            // PEM formatted strings may contain letters/numbers and the symbols
            // forward slash: /
            // plus sign:     +
            // equal sign:    =
            // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
            if (preg_match('/^-----BEGIN CERTIFICATE-----([\\s\\w\\/\\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
                list($wholething, $body) = $matches;
                unset($wholething, $matches);
                $b64 = clean_param($body, PARAM_BASE64);
                if (!empty($b64)) {
                    return "-----BEGIN CERTIFICATE-----\n{$b64}\n-----END CERTIFICATE-----\n";
                } else {
                    return '';
                }
            }
            return '';
        case PARAM_BASE64:
            if (!empty($param)) {
                // PEM formatted strings may contain letters/numbers and the symbols
                // forward slash: /
                // plus sign:     +
                // equal sign:    =
                if (0 >= preg_match('/^([\\s\\w\\/\\+=]+)$/', trim($param))) {
                    return '';
                }
                $lines = preg_split('/[\\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
                // Each line of base64 encoded data must be 64 characters in
                // length, except for the last line which may be less than (or
                // equal to) 64 characters long.
                for ($i = 0, $j = count($lines); $i < $j; $i++) {
                    if ($i + 1 == $j) {
                        if (64 < strlen($lines[$i])) {
                            return '';
                        }
                        continue;
                    }
                    if (64 != strlen($lines[$i])) {
                        return '';
                    }
                }
                return implode("\n", $lines);
            } else {
                return '';
            }
        case PARAM_TAG:
            // Please note it is not safe to use the tag name directly anywhere,
            // it must be processed with s(), urlencode() before embedding anywhere.
            // remove some nasties
            $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
            //convert many whitespace chars into one
            $param = preg_replace('/\\s+/', ' ', $param);
            $textlib = textlib_get_instance();
            $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH);
            return $param;
        case PARAM_TAGLIST:
            $tags = explode(',', $param);
            $result = array();
            foreach ($tags as $tag) {
                $res = clean_param($tag, PARAM_TAG);
                if ($res !== '') {
                    $result[] = $res;
                }
            }
            if ($result) {
                return implode(',', $result);
            } else {
                return '';
            }
        case PARAM_CAPABILITY:
            if (get_capability_info($param)) {
                return $param;
            } else {
                return '';
            }
        case PARAM_PERMISSION:
            $param = (int) $param;
            if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
                return $param;
            } else {
                return CAP_INHERIT;
            }
        case PARAM_AUTH:
            $param = clean_param($param, PARAM_SAFEDIR);
            if (exists_auth_plugin($param)) {
                return $param;
            } else {
                return '';
            }
        case PARAM_LANG:
            $param = clean_param($param, PARAM_SAFEDIR);
            if (get_string_manager()->translation_exists($param)) {
                return $param;
            } else {
                return '';
                // Specified language is not installed or param malformed
            }
        case PARAM_THEME:
            $param = clean_param($param, PARAM_SAFEDIR);
            if (file_exists("{$CFG->dirroot}/theme/{$param}/config.php")) {
                return $param;
            } else {
                if (!empty($CFG->themedir) and file_exists("{$CFG->themedir}/{$param}/config.php")) {
                    return $param;
                } else {
                    return '';
                    // Specified theme is not installed
                }
            }
        case PARAM_USERNAME:
            $param = str_replace(" ", "", $param);
            $param = moodle_strtolower($param);
            // Convert uppercase to lowercase MDL-16919
            if (empty($CFG->extendedusernamechars)) {
                // regular expression, eliminate all chars EXCEPT:
                // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
                $param = preg_replace('/[^-\\.@_a-z0-9]/', '', $param);
            }
            return $param;
        case PARAM_EMAIL:
            if (validate_email($param)) {
                return $param;
            } else {
                return '';
            }
        case PARAM_STRINGID:
            if (preg_match('|^[a-zA-Z][a-zA-Z0-9\\.:/_-]*$|', $param)) {
                return $param;
            } else {
                return '';
            }
        default:
            // throw error, switched parameters in optional_param or another serious problem
            print_error("unknownparamtype", '', '', $type);
    }
}
Example #5
0
function validateFtpSyntax($ftpaddr, $options = "")
{
    // Check Options Parameter
    if (!ereg('^([sHSEFuPaIpfqr][+?-])*$', $options)) {
        trigger_error("Options attribute malformed", E_USER_ERROR);
    }
    // Set Options Array, set defaults if options are not specified
    // Scheme
    if (strpos($options, 's') === false) {
        $aOptions['s'] = '?';
    } else {
        $aOptions['s'] = substr($options, strpos($options, 's') + 1, 1);
    }
    // http://
    if (strpos($options, 'H') === false) {
        $aOptions['H'] = '-';
    } else {
        $aOptions['H'] = substr($options, strpos($options, 'H') + 1, 1);
    }
    // https:// (SSL)
    if (strpos($options, 'S') === false) {
        $aOptions['S'] = '-';
    } else {
        $aOptions['S'] = substr($options, strpos($options, 'S') + 1, 1);
    }
    // mailto: (email)
    if (strpos($options, 'E') === false) {
        $aOptions['E'] = '-';
    } else {
        $aOptions['E'] = substr($options, strpos($options, 'E') + 1, 1);
    }
    // ftp://
    if (strpos($options, 'F') === false) {
        $aOptions['F'] = '+';
    } else {
        $aOptions['F'] = substr($options, strpos($options, 'F') + 1, 1);
    }
    // User section
    if (strpos($options, 'u') === false) {
        $aOptions['u'] = '?';
    } else {
        $aOptions['u'] = substr($options, strpos($options, 'u') + 1, 1);
    }
    // Password in user section
    if (strpos($options, 'P') === false) {
        $aOptions['P'] = '?';
    } else {
        $aOptions['P'] = substr($options, strpos($options, 'P') + 1, 1);
    }
    // Address Section
    if (strpos($options, 'a') === false) {
        $aOptions['a'] = '+';
    } else {
        $aOptions['a'] = substr($options, strpos($options, 'a') + 1, 1);
    }
    // IP Address in address section
    if (strpos($options, 'I') === false) {
        $aOptions['I'] = '?';
    } else {
        $aOptions['I'] = substr($options, strpos($options, 'I') + 1, 1);
    }
    // Port number
    if (strpos($options, 'p') === false) {
        $aOptions['p'] = '?';
    } else {
        $aOptions['p'] = substr($options, strpos($options, 'p') + 1, 1);
    }
    // File Path
    if (strpos($options, 'f') === false) {
        $aOptions['f'] = '?';
    } else {
        $aOptions['f'] = substr($options, strpos($options, 'f') + 1, 1);
    }
    // Query Section
    if (strpos($options, 'q') === false) {
        $aOptions['q'] = '-';
    } else {
        $aOptions['q'] = substr($options, strpos($options, 'q') + 1, 1);
    }
    // Fragment (Anchor)
    if (strpos($options, 'r') === false) {
        $aOptions['r'] = '-';
    } else {
        $aOptions['r'] = substr($options, strpos($options, 'r') + 1, 1);
    }
    // Generate options
    $newoptions = '';
    foreach ($aOptions as $key => $value) {
        $newoptions .= $key . $value;
    }
    // DEBUGGING - Uncomment line below to display generated options
    // echo '<pre>' . $newoptions . '</pre>';
    // Send to validateUrlSyntax() and return result
    return validateUrlSyntax($ftpaddr, $newoptions);
}
Example #6
0
// figure out what the returnto URL should be
$wantsurl = param_variable("wantsurl", false);
if (!$wantsurl) {
    if (isset($_SESSION['wantsurl'])) {
        $wantsurl = $_SESSION['wantsurl'];
    } else {
        if (!$saml_session->getIdP()) {
            $wantsurl = array_key_exists('HTTP_REFERER', $_SERVER) ? $_SERVER['HTTP_REFERER'] : $CFG->wwwroot;
        } else {
            $wantsurl = $CFG->wwwroot;
        }
    }
}
// taken from Moodle clean_param - make sure the wantsurl is correctly formed
include_once 'validateurlsyntax.php';
if (!validateUrlSyntax($wantsurl, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
    $wantsurl = $CFG->wwwroot;
}
// trim off any reference to login and stash
$_SESSION['wantsurl'] = preg_replace('/\\&login$/', '', $wantsurl);
// now - are we logged in?
$as->requireAuth();
// ensure that $_SESSION is cleared for simplesamlphp
if (isset($_SESSION['wantsurl'])) {
    unset($_SESSION['wantsurl']);
}
$saml_attributes = $as->getAttributes();
@session_write_close();
// now - let's continue with the session handling that would normally be done
// by Maharas init.php
// the main thin is that it sets the session cookie name back to what it should be
Example #7
0
<link href="popcss.css" rel="stylesheet" type="text/css" />
</head>

<body>
<h3>Feeds importieren</h3>

<?php 
include './libs/URL.php';
ob_end_flush();
$_ok = TRUE;
if (isset($_FILES['probe']) || !empty($_POST['url'])) {
    require_once 'magpie/rss_fetch.inc';
    require_once 'magpie/rss_parse.inc';
    #require_once('magpie/rss_utils.inc');
    if (!empty($_POST['url'])) {
        if (validateUrlSyntax($_POST['url'], 's+a+')) {
            if (!($snoopy = _fetch_remote_file($_POST['url']))) {
                echo "Ich kann " . $_POST['url'] . " nicht ?en...<br />";
                $_ok = FALSE;
            }
            $simple = $snoopy->results;
            unset($snoopy);
        } else {
            echo "Also, " . $_POST['url'] . " ist aber keine richtige URL...<br />";
            $_ok = FALSE;
        }
    } elseif (isset($_FILES['probe'])) {
        $name = "temp/" . time() . ".opml";
        $_ok = move_uploaded_file($_FILES['probe']['tmp_name'], $name);
        $simple = implode("", file($name));
    }
Example #8
0
/**
 * Used by {@link optional_param()} and {@link required_param()} to
 * clean the variables and/or cast to specific types, based on
 * an options field.
 * <code>
 * $course->format = clean_param($course->format, PARAM_ALPHA);
 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_CLEAN);
 * </code>
 *
 * @uses $CFG
 * @uses PARAM_CLEAN
 * @uses PARAM_INT
 * @uses PARAM_INTEGER
 * @uses PARAM_ALPHA
 * @uses PARAM_ALPHANUM
 * @uses PARAM_NOTAGS
 * @uses PARAM_ALPHATEXT
 * @uses PARAM_BOOL
 * @uses PARAM_SAFEDIR
 * @uses PARAM_CLEANFILE
 * @uses PARAM_FILE
 * @uses PARAM_PATH
 * @uses PARAM_HOST
 * @uses PARAM_URL
 * @uses PARAM_LOCALURL
 * @uses PARAM_CLEANHTML
 * @param mixed $param the variable we are cleaning
 * @param int $options a bit field that specifies the cleaning needed. This field is specified by combining PARAM_* definitions together with a logical or.
 * @return mixed
 */
function clean_param($param, $options)
{
    global $CFG;
    if (is_array($param)) {
        // Let's loop
        $newparam = array();
        foreach ($param as $key => $value) {
            $newparam[$key] = clean_param($value, $options);
        }
        return $newparam;
    }
    if (!$options) {
        return $param;
        // Return raw value
    }
    //this corrupts data - Sven
    //if ((string)$param == (string)(int)$param) {  // It's just an integer
    //    return (int)$param;
    //}
    if ($options & PARAM_CLEAN) {
        // this breaks backslashes in user input
        //        $param = stripslashes($param);   // Needed by kses to work fine
        $param = clean_text($param);
        // Sweep for scripts, etc
        // and this unnecessarily escapes quotes, etc in user input
        //        $param = addslashes($param);     // Restore original request parameter slashes
    }
    if ($options & PARAM_INT) {
        $param = (int) $param;
        // Convert to integer
    }
    if ($options & PARAM_ALPHA) {
        // Remove everything not a-z
        $param = eregi_replace('[^a-zA-Z]', '', $param);
    }
    if ($options & PARAM_ALPHANUM) {
        // Remove everything not a-zA-Z0-9
        $param = eregi_replace('[^A-Za-z0-9]', '', $param);
    }
    if ($options & PARAM_ALPHAEXT) {
        // Remove everything not a-zA-Z/_-
        $param = eregi_replace('[^a-zA-Z/_-]', '', $param);
    }
    if ($options & PARAM_BOOL) {
        // Convert to 1 or 0
        $tempstr = strtolower($param);
        if ($tempstr == 'on') {
            $param = 1;
        } else {
            if ($tempstr == 'off') {
                $param = 0;
            } else {
                $param = empty($param) ? 0 : 1;
            }
        }
    }
    if ($options & PARAM_NOTAGS) {
        // Strip all tags completely
        $param = strip_tags($param);
    }
    if ($options & PARAM_SAFEDIR) {
        // Remove everything not a-zA-Z0-9_-
        $param = eregi_replace('[^a-zA-Z0-9_-]', '', $param);
    }
    if ($options & PARAM_CLEANFILE) {
        // allow only safe characters
        $param = clean_filename($param);
    }
    if ($options & PARAM_FILE) {
        // Strip all suspicious characters from filename
        $param = ereg_replace('[[:cntrl:]]|[<>"`\\|\':\\/]', '', $param);
        $param = ereg_replace('\\.\\.+', '', $param);
        if ($param == '.') {
            $param = '';
        }
    }
    if ($options & PARAM_PATH) {
        // Strip all suspicious characters from file path
        $param = str_replace('\\\'', '\'', $param);
        $param = str_replace('\\"', '"', $param);
        $param = str_replace('\\', '/', $param);
        $param = ereg_replace('[[:cntrl:]]|[<>"`\\|\':]', '', $param);
        $param = ereg_replace('\\.\\.+', '', $param);
        $param = ereg_replace('//+', '/', $param);
        $param = ereg_replace('/(\\./)+', '/', $param);
    }
    if ($options & PARAM_HOST) {
        // allow FQDN or IPv4 dotted quad
        preg_replace('/[^\\.\\d\\w-]/', '', $param);
        // only allowed chars
        // match ipv4 dotted quad
        if (preg_match('/(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/', $param, $match)) {
            // confirm values are ok
            if ($match[0] > 255 || $match[1] > 255 || $match[3] > 255 || $match[4] > 255) {
                // hmmm, what kind of dotted quad is this?
                $param = '';
            }
        } elseif (preg_match('/^[\\w\\d\\.-]+$/', $param) && !preg_match('/^[\\.-]/', $param) && !preg_match('/[\\.-]$/', $param)) {
            // all is ok - $param is respected
        } else {
            // all is not ok...
            $param = '';
        }
    }
    if ($options & PARAM_URL) {
        // allow safe ftp, http, mailto urls
        include_once $CFG->dirroot . 'lib/validateurlsyntax.php';
        //
        // Parameters to validateurlsyntax()
        //
        // s? scheme is optional
        //   H? http optional
        //   S? https optional
        //   F? ftp   optional
        //   E? mailto optional
        // u- user section not allowed
        //   P- password not allowed
        // a? address optional
        //   I? Numeric IP address optional (can use IP or domain)
        //   p-  port not allowed -- restrict to default port
        // f? "file" path section optional
        //   q? query section optional
        //   r? fragment (anchor) optional
        //
        if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p-f?q?r?')) {
            // all is ok, param is respected
        } else {
            $param = '';
            // not really ok
        }
        $options ^= PARAM_URL;
        // Turn off the URL bit so that simple PARAM_URLs don't test true for PARAM_LOCALURL
    }
    if ($options & PARAM_LOCALURL) {
        // assume we passed the PARAM_URL test...
        // allow http absolute, root relative and relative URLs within wwwroot
        if (!empty($param)) {
            if (preg_match(':^/:', $param)) {
                // root-relative, ok!
            } elseif (preg_match('/^' . preg_quote($CFG->wwwroot, '/') . '/i', $param)) {
                // absolute, and matches our wwwroot
            } else {
                // relative - let's make sure there are no tricks
                if (validateUrlSyntax($param, 's-u-P-a-p-f+q?r?')) {
                    // looks ok.
                } else {
                    $param = '';
                }
            }
        }
    }
    if ($options & PARAM_CLEANHTML) {
        //        $param = stripslashes($param);         // Remove any slashes
        $param = clean_text($param);
        // Sweep for scripts, etc
        //        $param = trim($param);                 // Sweep for scripts, etc
    }
    return $param;
}
Example #9
0
 private function create_node_course_modules_mod_resource($sheet_mod_resource, $instance)
 {
     global $CFG;
     require_once $CFG->libdir . '/validateurlsyntax.php';
     $link = '';
     $mod_alltext = '';
     $mod_summary = '';
     $xpath = cc2moodle::newx_path(cc2moodle::$manifest, cc2moodle::$namespaces);
     if ($instance['common_cartriedge_type'] == cc2moodle::CC_TYPE_WEBCONTENT || $instance['common_cartriedge_type'] == cc2moodle::CC_TYPE_ASSOCIATED_CONTENT) {
         $resource = $xpath->query('/imscc:manifest/imscc:resources/imscc:resource[@identifier="' . $instance['resource_indentifier'] . '"]/@href');
         $resource = !empty($resource->item(0)->nodeValue) ? $resource->item(0)->nodeValue : '';
         if (empty($resource)) {
             unset($resource);
             $resource = $xpath->query('/imscc:manifest/imscc:resources/imscc:resource[@identifier="' . $instance['resource_indentifier'] . '"]/imscc:file/@href');
             $resource = !empty($resource->item(0)->nodeValue) ? $resource->item(0)->nodeValue : '';
         }
         if (!empty($resource)) {
             $link = $resource;
         }
     }
     if ($instance['common_cartriedge_type'] == cc2moodle::CC_TYPE_WEBLINK) {
         $external_resource = $xpath->query('/imscc:manifest/imscc:resources/imscc:resource[@identifier="' . $instance['resource_indentifier'] . '"]/imscc:file/@href')->item(0)->nodeValue;
         if ($external_resource) {
             $resource = $this->load_xml_resource(cc2moodle::$path_to_manifest_folder . DIRECTORY_SEPARATOR . $external_resource);
             if (!empty($resource)) {
                 $xpath = cc2moodle::newx_path($resource, cc2moodle::getresourcens());
                 $resource = $xpath->query('//url/@href');
                 if ($resource->length > 0) {
                     $rawlink = $resource->item(0)->nodeValue;
                     if (!validateUrlSyntax($rawlink, 's+')) {
                         $changed = rawurldecode($rawlink);
                         if (validateUrlSyntax($changed, 's+')) {
                             $link = $changed;
                         } else {
                             $link = 'http://invalidurldetected/';
                         }
                     } else {
                         $link = $rawlink;
                     }
                 }
             }
         }
     }
     $find_tags = array('[#mod_instance#]', '[#mod_name#]', '[#mod_type#]', '[#mod_reference#]', '[#mod_summary#]', '[#mod_alltext#]', '[#mod_options#]', '[#date_now#]');
     $mod_type = 'file';
     $mod_options = 'objectframe';
     $mod_reference = $link;
     //detected if we are dealing with html file
     if (!empty($link) && $instance['common_cartriedge_type'] == cc2moodle::CC_TYPE_WEBCONTENT) {
         $ext = strtolower(pathinfo($link, PATHINFO_EXTENSION));
         if (in_array($ext, array('html', 'htm', 'xhtml'))) {
             $mod_type = 'html';
             //extract the content of the file
             $rootpath = realpath(cc112moodle::$path_to_manifest_folder);
             $htmlpath = realpath($rootpath . DIRECTORY_SEPARATOR . $link);
             $dirpath = dirname($htmlpath);
             if (file_exists($htmlpath)) {
                 $fcontent = file_get_contents($htmlpath);
                 $mod_alltext = clean_param($this->prepare_content($fcontent), PARAM_CLEANHTML);
                 $mod_reference = '';
                 $mod_options = '';
                 //TODO: try to handle embedded resources
                 /**
                  * images, linked static resources, applets, videos
                  */
                 $doc = new DOMDocument();
                 $cdir = getcwd();
                 chdir($dirpath);
                 try {
                     if (!empty($mod_alltext) && $doc->loadHTML($mod_alltext)) {
                         $xpath = new DOMXPath($doc);
                         $attributes = array('href', 'src', 'background', 'archive', 'code');
                         $qtemplate = "//*[@##][not(contains(@##,'://'))]/@##";
                         $query = '';
                         foreach ($attributes as $attrname) {
                             if (!empty($query)) {
                                 $query .= " | ";
                             }
                             $query .= str_replace('##', $attrname, $qtemplate);
                         }
                         $list = $xpath->query($query);
                         $searches = array();
                         $replaces = array();
                         foreach ($list as $resrc) {
                             $rpath = $resrc->nodeValue;
                             $rtp = realpath($rpath);
                             if ($rtp !== false && is_file($rtp)) {
                                 //file is there - we are in business
                                 $strip = str_replace("\\", "/", str_ireplace($rootpath, '', $rtp));
                                 $encoded_file = '$@FILEPHP@$' . str_replace('/', '$@SLASH@$', $strip);
                                 $searches[] = $resrc->nodeValue;
                                 $replaces[] = $encoded_file;
                             }
                         }
                         $mod_alltext = str_replace($searches, $replaces, $mod_alltext);
                     }
                 } catch (Exception $e) {
                     //silence the complaints
                 }
                 chdir($cdir);
                 $mod_alltext = self::safexml($mod_alltext);
             }
         }
     }
     $replace_values = array($instance['instance'], self::safexml($instance['title']), $mod_type, $mod_reference, '', $mod_alltext, $mod_options, time());
     return str_replace($find_tags, $replace_values, $sheet_mod_resource);
 }
    echo '<p>' . get_string('nodatareturned', 'report_customsql') . '</p>';
} else {
    list($csvfilename, $cvstimestamp) = report_customsql_csv_filename($report, $cvstimestamp);
    if (!is_readable($csvfilename)) {
        echo '<p>' . get_string('notrunyet', 'report_customsql') . '</p>';
    } else {
        $handle = fopen($csvfilename, 'r');
        if ($report->runable != 'manual' && !$report->singlerow) {
            print_heading(get_string('reportfor', 'report_customsql', userdate($cvstimestamp, get_string('strftimedate'))), '', 3);
        }
        $table = new stdClass();
        $table->head = fgetcsv($handle);
        while ($row = fgetcsv($handle)) {
            $rowdata = array();
            foreach ($row as $value) {
                if (validateUrlSyntax($value, 's+H?S?F?E?u-P-a?I?p?f?q?r?')) {
                    $rowdata[] = '<a href="' . $value . '">' . $value . '</a>';
                } else {
                    $rowdata[] = $value;
                }
            }
            $table->data[] = $rowdata;
            $count += 1;
        }
        fclose($handle);
        print_table($table);
        echo "<br/>" . get_string('recordcount', 'report_customsql') . " = {$count}<br/>";
        if ($count >= REPORT_CUSTOMSQL_MAX_RECORDS) {
            echo '<p class="admin_note">' . get_string('recordlimitreached', 'report_customsql', REPORT_CUSTOMSQL_MAX_RECORDS) . '</p>';
        }
        echo report_customsql_time_note($report, 'p');
Example #11
0
File: f.php Project: e-rasvet/mcm
function clean_param($param, $type = PARAM_CLEAN)
{
    global $CFG;
    if (is_array($param)) {
        // Let's loop
        $newparam = array();
        foreach ($param as $key => $value) {
            $newparam[$key] = clean_param($value, $type);
        }
        return $newparam;
    }
    switch ($type) {
        case PARAM_RAW:
            // no cleaning at all
            return $param;
        case PARAM_CLEAN:
            // General HTML cleaning, try to use more specific type if possible
            if (is_numeric($param)) {
                return $param;
            }
            $param = stripslashes($param);
            // Needed for kses to work fine
            $param = clean_text($param);
            // Sweep for scripts, etc
            return addslashes($param);
            // Restore original request parameter slashes
        // Restore original request parameter slashes
        case PARAM_CLEANHTML:
            // prepare html fragment for display, do not store it into db!!
            $param = stripslashes($param);
            // Remove any slashes
            $param = clean_text($param);
            // Sweep for scripts, etc
            return trim($param);
        case PARAM_INT:
            return (int) $param;
            // Convert to integer
        // Convert to integer
        case PARAM_NUMBER:
            return (double) $param;
            // Convert to integer
        // Convert to integer
        case PARAM_BOOL:
            // Convert to 1 or 0
            $tempstr = strtolower($param);
            if ($tempstr == 'on' or $tempstr == 'yes') {
                $param = 1;
            } else {
                if ($tempstr == 'off' or $tempstr == 'no') {
                    $param = 0;
                } else {
                    $param = empty($param) ? 0 : 1;
                }
            }
            return $param;
        case PARAM_NOTAGS:
            // Strip all tags
            return strip_tags($param);
        case PARAM_TEXT:
            // leave only tags needed for multilang
            return clean_param(strip_tags($param, '<lang><span>'), PARAM_CLEAN);
        case PARAM_SAFEDIR:
            // Remove everything not a-zA-Z0-9_-
            return eregi_replace('[^a-zA-Z0-9_-]', '', $param);
        case PARAM_CLEANFILE:
            // allow only safe characters
            return clean_filename($param);
        case PARAM_FILE:
            // Strip all suspicious characters from filename
            $param = ereg_replace('[[:cntrl:]]|[<>"`\\|\':\\/]', '', $param);
            $param = ereg_replace('\\.\\.+', '', $param);
            if ($param == '.') {
                $param = '';
            }
            return $param;
        case PARAM_PATH:
            // Strip all suspicious characters from file path
            $param = str_replace('\\\'', '\'', $param);
            $param = str_replace('\\"', '"', $param);
            $param = str_replace('\\', '/', $param);
            $param = ereg_replace('[[:cntrl:]]|[<>"`\\|\':]', '', $param);
            $param = ereg_replace('\\.\\.+', '', $param);
            $param = ereg_replace('//+', '/', $param);
            return ereg_replace('/(\\./)+', '/', $param);
        case PARAM_HOST:
            // allow FQDN or IPv4 dotted quad
            $param = preg_replace('/[^\\.\\d\\w-]/', '', $param);
            // only allowed chars
            // match ipv4 dotted quad
            if (preg_match('/(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/', $param, $match)) {
                // confirm values are ok
                if ($match[0] > 255 || $match[1] > 255 || $match[3] > 255 || $match[4] > 255) {
                    // hmmm, what kind of dotted quad is this?
                    $param = '';
                }
            } elseif (preg_match('/^[\\w\\d\\.-]+$/', $param) && !preg_match('/^[\\.-]/', $param) && !preg_match('/[\\.-]$/', $param)) {
                // all is ok - $param is respected
            } else {
                // all is not ok...
                $param = '';
            }
            return $param;
        case PARAM_URL:
            // allow safe ftp, http, mailto urls
            include_once $CFG['dirroot'] . '/inc/validateurlsyntax.php';
            if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
                // all is ok, param is respected
            } else {
                $param = '';
                // not really ok
            }
            return $param;
    }
}