示例#1
0
 function generate_from_id($id)
 {
     $sql = "select * from {$this->type} where id = {$id}";
     //echo $sql;
     if (!($result = $this->db->query($sql))) {
         error_report(SQL_ERROR, 'generate', __LINE__, __FILE__, $sql);
     }
     $row = $result->fetchRow(DB_FETCHMODE_ASSOC);
     return $this->generate_from_row($row);
 }
示例#2
0
function error_fatal($type, $message, $file, $line = 0)
{
    switch ($type) {
        case E_USER_ERROR:
            $type_str = 'Error';
            break;
        case E_WARNING:
        case E_USER_WARNING:
            $type_str = 'Warning';
            break;
        case E_NOTICE:
        case E_USER_NOTICE:
            $type_str = 'Notice';
            break;
        case QUICKSILVER_QUERY_ERROR:
            $type_str = 'Query Error';
            break;
        default:
            $type_str = 'Unknown Error';
    }
    if (strstr($file, 'eval()')) {
        $split = preg_split('/[\\(\\)]/', $file);
        $file = $split[0];
        $line = $split[1];
        $message .= ' (in evaluated code)';
    }
    $details = null;
    if ($type != QUICKSILVER_QUERY_ERROR) {
        if (strpos($message, 'mysql_fetch_array(): supplied argument') === false) {
            $lines = null;
            $details2 = null;
            if (function_exists('debug_backtrace')) {
                $backtrace = debug_backtrace();
                if (strpos($message, 'Template not found') !== false) {
                    $file = $backtrace[2]['file'];
                    $line = $backtrace[2]['line'];
                }
            }
            if (file_exists($file)) {
                $lines = file($file);
            }
            if ($lines) {
                $details2 = "\n\t\t\t\t<span class='header'>Code:</span><br />\n\t\t\t\t<span class='code'>" . error_getlines($lines, $line) . '</span>';
            }
        } else {
            $details2 = "\n\t\t\t<span class='header'>MySQL Said:</span><br />" . mysql_error() . '<br />';
        }
        $details .= "\n\t\t<span class='header'>{$type_str} [{$type}]:</span><br />\n\t\tThe error was reported on line <b>{$line}</b> of <b>{$file}</b><br /><br />{$details2}";
    } else {
        $details .= "\n\t\t<span class='header'>{$type_str} [{$line}]:</span><br />\n\t\tThis type of error is reported by MySQL.\n\t\t<br /><br /><span class='header'>Query:</span><br />{$file}<br />";
    }
    $checkbug = error_report($type, $message, $file, $line);
    $temp_querystring = str_replace("&", "&amp;", $_SERVER['QUERY_STRING']);
    return "\n\t<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n\t<html>\n\t<head>\n\t<title>Quicksilver Forums Error</title>\n\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n\n\t<style type='text/css'>\n\tbody {font-size:12px; font-family: verdana, arial, helvetica, sans-serif; color:#000000; background-color:#ffffff}\n\thr {height:1px}\n\t.large  {font-weight:bold; font-size:18px; color:#660000; background-color:transparent}\n\t.header {font-weight:bold; font-size:12px; color:#660000; background-color:transparent}\n\t.error  {font-weight:bold; font-size:12px; color:#ff0000; background-color:transparent}\n\t.small  {font-weight:bold; font-size:10px; color:#000000; background-color:transparent}\n\t.code   {font-weight:normal; font-size:12px; font-family:courier new, fixedsys, serif}\n\t</style>\n\t</head>\n\n\t<body>\n\t<span class='large'>Quicksilver Forums has exited with an error</span><br /><br />\n\n\t<hr>\n\t<span class='error'>{$message}</span>\n\t<hr><br />\n\n\t{$details}\n\n\t<br /><hr><br />\n\t<a href='http://developer.berlios.de/bugs/?group_id=5008' class='small'>Check status of problem (recommended)</a><br />\n\t<a href='{$_SERVER['PHP_SELF']}?{$temp_querystring}&amp;debug=1' class='small'>View debug information (advanced)</a><br />\n\t<a href='{$_SERVER['PHP_SELF']}' class='small'>Return to the board</a>\n\t</body>\n\t</html>";
}
示例#3
0
function autoloader($class)
{
    $name = explode('_', $class);
    try {
        @(include_once './models/' . strtolower($name[0]) . '.php');
        @(include_once './controllers/' . strtolower($name[0]) . '.php');
        @(include_once './views/' . strtolower($name[0]) . '.php');
    } catch (ErrorException $e) {
        error_report($e);
        die;
    }
}
示例#4
0
function http_get_simple($url)
{
    $options = array('http' => array('header' => '', 'method' => 'GET'));
    $context = stream_context_create($options);
    $stream = fopen($url, 'r', false, $context);
    if ($stream === FALSE) {
        error_report("Error opening GET request to URL '{$url}'");
        return FALSE;
    }
    $meta = stream_get_meta_data($stream);
    $result = array('headers' => $meta['wrapper_data'], 'meta' => $meta, 'content' => stream_get_contents($stream));
    return $result;
}
示例#5
0
function auth_activate_by_cookie($cookie)
{
    $result = db_get_auth_request_by_cookie($cookie);
    if ($result === FALSE) {
        error_report("Error: No such cookie is known.");
        return FALSE;
    }
    $success = db_mark_user_as_authenicated($result['username'], $result['cookie'], $result['id']);
    if ($success === FALSE) {
        error_report("Error: Could not mark user as 'authenticated'. Aborting.");
        return FALSE;
    }
    return TRUE;
}
示例#6
0
 function generate_from_content_id($content_id)
 {
     global $db, $config_vars;
     unset($this->meta_data);
     $sql = 'select * from ' . $config_vars['table_prefix'] . "content_meta_data where content_id = {$content_id}";
     if (!($result = $db->sql_query($sql))) {
         error_report(SQL_ERROR, 'generate', __LINE__, __FILE__, $sql);
     }
     while ($row = $db->sql_fetchrow($result)) {
         $this->meta_data[$row['id']] = $row;
     }
     $this->content_id = $content_id;
     return OP_SUCCESSFUL;
 }
示例#7
0
function bgg_login()
{
    global $config;
    if ($config['bgg']['cookie'] !== FALSE) {
        error_report("Already logged in! Not logging in again.");
        return TRUE;
    }
    $url = "https://" . $config['bgg']['domain'] . "/login";
    $params = array('lasturl' => '/', 'username' => $config['bgg']['username'], 'password' => $config['bgg']['password']);
    $result = http_post($url, $params);
    if ($result === FALSE) {
        return FALSE;
    }
    $cookies = bgg_get_cookies_from_headers($result['headers']);
    if (!isset($cookies['bggusername']) || !isset($cookies['bggpassword']) || !isset($cookies['SessionID'])) {
        error_log("Missing cookies after BGG logon. Logon error!");
        return FALSE;
    }
    $bgg_cookies = sprintf("bggusername=%s; bggpassword=%s; SessionID=%s", $cookies['bggusername'], $cookies['bggpassword'], $cookies['SessionID']);
    $config['bgg']['cookie'] = $bgg_cookies;
    return TRUE;
}
function get_content_ordered_by($by, $filter = true, $order = 'DESC', $limit_start = 0, $limit_end = -1)
{
    // returns a assoc array containing 'object' = content objects and 'length' = how long they have been viewed ordered by the length they have been viewed.
    global $db, $config_vars;
    if ($filter) {
        $filter = 'and (view_table.end!=0)';
    }
    $sql = 'SELECT SUM(UNIX_TIMESTAMP(view_table.end) - UNIX_TIMESTAMP(view_table.start)) as length,COUNT(*) as amount,content.* FROM ' . $config_vars['table_prefix'] . 'views AS view_table, ' . $config_vars['table_prefix'] . 'content AS content 
		WHERE (view_table.content_id=content.id) ' . $filter . '
		GROUP BY view_table.content_id 
		ORDER BY ' . $by . " {$order} \n\t\tLIMIT {$limit_start},{$limit_end}";
    if (!($result = $db->sql_query($sql))) {
        error_report(SQL_ERROR, 'get_content_ordered_by', __LINE__, __FILE__, $sql);
    }
    while ($row = $db->sql_fetchrow($result)) {
        $a['object'] = get_content_from_row($row);
        $a['length'] = $row['length'];
        $a['amount'] = $row['amount'];
        $objarray[] = $a;
    }
    return $objarray;
}
示例#9
0
function run_test($php, $file, $env)
{
    global $log_format, $ini_overwrites, $cwd, $PHP_FAILED_TESTS;
    global $pass_options, $DETAILED, $IN_REDIRECT, $test_cnt, $test_idx;
    global $leak_check, $temp_source, $temp_target, $cfg, $environment;
    global $no_clean;
    global $valgrind_version;
    global $SHOW_ONLY_GROUPS;
    global $no_file_cache;
    $temp_filenames = null;
    $org_file = $file;
    if (isset($env['TEST_PHP_CGI_EXECUTABLE'])) {
        $php_cgi = $env['TEST_PHP_CGI_EXECUTABLE'];
    }
    if (isset($env['TEST_PHPDBG_EXECUTABLE'])) {
        $phpdbg = $env['TEST_PHPDBG_EXECUTABLE'];
    }
    if (is_array($file)) {
        $file = $file[0];
    }
    if ($DETAILED) {
        echo "\n=================\nTEST {$file}\n";
    }
    // Load the sections of the test file.
    $section_text = array('TEST' => '');
    $fp = fopen($file, "rb") or error("Cannot open test file: {$file}");
    $borked = false;
    $bork_info = '';
    if (!feof($fp)) {
        $line = fgets($fp);
        if ($line === false) {
            $bork_info = "cannot read test";
            $borked = true;
        }
    } else {
        $bork_info = "empty test [{$file}]";
        $borked = true;
    }
    if (!$borked && strncmp('--TEST--', $line, 8)) {
        $bork_info = "tests must start with --TEST-- [{$file}]";
        $borked = true;
    }
    $section = 'TEST';
    $secfile = false;
    $secdone = false;
    while (!feof($fp)) {
        $line = fgets($fp);
        if ($line === false) {
            break;
        }
        // Match the beginning of a section.
        if (preg_match('/^--([_A-Z]+)--/', $line, $r)) {
            $section = $r[1];
            settype($section, 'string');
            if (isset($section_text[$section])) {
                $bork_info = "duplicated {$section} section";
                $borked = true;
            }
            $section_text[$section] = '';
            $secfile = $section == 'FILE' || $section == 'FILEEOF' || $section == 'FILE_EXTERNAL';
            $secdone = false;
            continue;
        }
        // Add to the section text.
        if (!$secdone) {
            $section_text[$section] .= $line;
        }
        // End of actual test?
        if ($secfile && preg_match('/^===DONE===\\s*$/', $line)) {
            $secdone = true;
        }
    }
    // the redirect section allows a set of tests to be reused outside of
    // a given test dir
    if (!$borked) {
        if (@count($section_text['REDIRECTTEST']) == 1) {
            if ($IN_REDIRECT) {
                $borked = true;
                $bork_info = "Can't redirect a test from within a redirected test";
            } else {
                $borked = false;
            }
        } else {
            if (!isset($section_text['PHPDBG']) && @count($section_text['FILE']) + @count($section_text['FILEEOF']) + @count($section_text['FILE_EXTERNAL']) != 1) {
                $bork_info = "missing section --FILE--";
                $borked = true;
            }
            if (@count($section_text['FILEEOF']) == 1) {
                $section_text['FILE'] = preg_replace("/[\r\n]+\$/", '', $section_text['FILEEOF']);
                unset($section_text['FILEEOF']);
            }
            foreach (array('FILE', 'EXPECT', 'EXPECTF', 'EXPECTREGEX') as $prefix) {
                $key = $prefix . '_EXTERNAL';
                if (@count($section_text[$key]) == 1) {
                    // don't allow tests to retrieve files from anywhere but this subdirectory
                    $section_text[$key] = dirname($file) . '/' . trim(str_replace('..', '', $section_text[$key]));
                    if (file_exists($section_text[$key])) {
                        $section_text[$prefix] = file_get_contents($section_text[$key], FILE_BINARY);
                        unset($section_text[$key]);
                    } else {
                        $bork_info = "could not load --" . $key . "-- " . dirname($file) . '/' . trim($section_text[$key]);
                        $borked = true;
                    }
                }
            }
            if (@count($section_text['EXPECT']) + @count($section_text['EXPECTF']) + @count($section_text['EXPECTREGEX']) != 1) {
                $bork_info = "missing section --EXPECT--, --EXPECTF-- or --EXPECTREGEX--";
                $borked = true;
            }
        }
    }
    fclose($fp);
    $shortname = str_replace($cwd . '/', '', $file);
    $tested_file = $shortname;
    if ($borked) {
        show_result("BORK", $bork_info, $tested_file);
        $PHP_FAILED_TESTS['BORKED'][] = array('name' => $file, 'test_name' => '', 'output' => '', 'diff' => '', 'info' => "{$bork_info} [{$file}]");
        junit_mark_test_as('BORK', $shortname, $tested_file, 0, $bork_info);
        return 'BORKED';
    }
    if (isset($section_text['CAPTURE_STDIO'])) {
        $captureStdIn = stripos($section_text['CAPTURE_STDIO'], 'STDIN') !== false;
        $captureStdOut = stripos($section_text['CAPTURE_STDIO'], 'STDOUT') !== false;
        $captureStdErr = stripos($section_text['CAPTURE_STDIO'], 'STDERR') !== false;
    } else {
        $captureStdIn = true;
        $captureStdOut = true;
        $captureStdErr = true;
    }
    if ($captureStdOut && $captureStdErr) {
        $cmdRedirect = ' 2>&1';
    } else {
        $cmdRedirect = '';
    }
    $tested = trim($section_text['TEST']);
    /* For GET/POST/PUT tests, check if cgi sapi is available and if it is, use it. */
    if (!empty($section_text['GET']) || !empty($section_text['POST']) || !empty($section_text['GZIP_POST']) || !empty($section_text['DEFLATE_POST']) || !empty($section_text['POST_RAW']) || !empty($section_text['PUT']) || !empty($section_text['COOKIE']) || !empty($section_text['EXPECTHEADERS'])) {
        if (isset($php_cgi)) {
            $old_php = $php;
            $php = $php_cgi . ' -C ';
        } else {
            if (!strncasecmp(PHP_OS, "win", 3) && file_exists(dirname($php) . "/php-cgi.exe")) {
                $old_php = $php;
                $php = realpath(dirname($php) . "/php-cgi.exe") . ' -C ';
            } else {
                if (file_exists(dirname($php) . "/../../sapi/cgi/php-cgi")) {
                    $old_php = $php;
                    $php = realpath(dirname($php) . "/../../sapi/cgi/php-cgi") . ' -C ';
                } else {
                    if (file_exists("./sapi/cgi/php-cgi")) {
                        $old_php = $php;
                        $php = realpath("./sapi/cgi/php-cgi") . ' -C ';
                    } else {
                        if (file_exists(dirname($php) . "/php-cgi")) {
                            $old_php = $php;
                            $php = realpath(dirname($php) . "/php-cgi") . ' -C ';
                        } else {
                            show_result('SKIP', $tested, $tested_file, "reason: CGI not available");
                            junit_init_suite(junit_get_suitename_for($shortname));
                            junit_mark_test_as('SKIP', $shortname, $tested, 0, 'CGI not available');
                            return 'SKIPPED';
                        }
                    }
                }
            }
        }
        $uses_cgi = true;
    }
    /* For phpdbg tests, check if phpdbg sapi is available and if it is, use it. */
    if (array_key_exists('PHPDBG', $section_text)) {
        if (!isset($section_text['STDIN'])) {
            $section_text['STDIN'] = $section_text['PHPDBG'] . "\n";
        }
        if (isset($phpdbg)) {
            $old_php = $php;
            $php = $phpdbg . ' -qIb';
        } else {
            show_result('SKIP', $tested, $tested_file, "reason: phpdbg not available");
            junit_init_suite(junit_get_suitename_for($shortname));
            junit_mark_test_as('SKIP', $shortname, $tested, 0, 'phpdbg not available');
            return 'SKIPPED';
        }
    }
    if (!$SHOW_ONLY_GROUPS) {
        show_test($test_idx, $shortname);
    }
    if (is_array($IN_REDIRECT)) {
        $temp_dir = $test_dir = $IN_REDIRECT['dir'];
    } else {
        $temp_dir = $test_dir = realpath(dirname($file));
    }
    if ($temp_source && $temp_target) {
        $temp_dir = str_replace($temp_source, $temp_target, $temp_dir);
    }
    $main_file_name = basename($file, 'phpt');
    $diff_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'diff';
    $log_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'log';
    $exp_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'exp';
    $output_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'out';
    $memcheck_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'mem';
    $sh_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'sh';
    $temp_file = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'php';
    $test_file = $test_dir . DIRECTORY_SEPARATOR . $main_file_name . 'php';
    $temp_skipif = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'skip.php';
    $test_skipif = $test_dir . DIRECTORY_SEPARATOR . $main_file_name . 'skip.php';
    $temp_clean = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'clean.php';
    $test_clean = $test_dir . DIRECTORY_SEPARATOR . $main_file_name . 'clean.php';
    $tmp_post = $temp_dir . DIRECTORY_SEPARATOR . uniqid('/phpt.');
    $tmp_relative_file = str_replace(__DIR__ . DIRECTORY_SEPARATOR, '', $test_file) . 't';
    if ($temp_source && $temp_target) {
        $temp_skipif .= 's';
        $temp_file .= 's';
        $temp_clean .= 's';
        $copy_file = $temp_dir . DIRECTORY_SEPARATOR . basename(is_array($file) ? $file[1] : $file) . '.phps';
        if (!is_dir(dirname($copy_file))) {
            mkdir(dirname($copy_file), 0777, true) or error("Cannot create output directory - " . dirname($copy_file));
        }
        if (isset($section_text['FILE'])) {
            save_text($copy_file, $section_text['FILE']);
        }
        $temp_filenames = array('file' => $copy_file, 'diff' => $diff_filename, 'log' => $log_filename, 'exp' => $exp_filename, 'out' => $output_filename, 'mem' => $memcheck_filename, 'sh' => $sh_filename, 'php' => $temp_file, 'skip' => $temp_skipif, 'clean' => $temp_clean);
    }
    if (is_array($IN_REDIRECT)) {
        $tested = $IN_REDIRECT['prefix'] . ' ' . trim($section_text['TEST']);
        $tested_file = $tmp_relative_file;
    }
    // unlink old test results
    @unlink($diff_filename);
    @unlink($log_filename);
    @unlink($exp_filename);
    @unlink($output_filename);
    @unlink($memcheck_filename);
    @unlink($sh_filename);
    @unlink($temp_file);
    @unlink($test_file);
    @unlink($temp_skipif);
    @unlink($test_skipif);
    @unlink($tmp_post);
    @unlink($temp_clean);
    @unlink($test_clean);
    // Reset environment from any previous test.
    $env['REDIRECT_STATUS'] = '';
    $env['QUERY_STRING'] = '';
    $env['PATH_TRANSLATED'] = '';
    $env['SCRIPT_FILENAME'] = '';
    $env['REQUEST_METHOD'] = '';
    $env['CONTENT_TYPE'] = '';
    $env['CONTENT_LENGTH'] = '';
    $env['TZ'] = '';
    if (!empty($section_text['ENV'])) {
        foreach (explode("\n", trim($section_text['ENV'])) as $e) {
            $e = explode('=', trim($e), 2);
            if (!empty($e[0]) && isset($e[1])) {
                $env[$e[0]] = $e[1];
            }
        }
    }
    // Default ini settings
    $ini_settings = array();
    // Additional required extensions
    if (array_key_exists('EXTENSIONS', $section_text)) {
        $ext_dir = `{$php} -r 'echo ini_get("extension_dir");'`;
        $extensions = preg_split("/[\n\r]+/", trim($section_text['EXTENSIONS']));
        $loaded = explode(",", `{$php} -n -r 'echo implode(",", get_loaded_extensions());'`);
        foreach ($extensions as $req_ext) {
            if (!in_array($req_ext, $loaded)) {
                if ($req_ext == 'opcache') {
                    $ini_settings['zend_extension'][] = $ext_dir . DIRECTORY_SEPARATOR . $req_ext . '.' . PHP_SHLIB_SUFFIX;
                } else {
                    $ini_settings['extension'][] = $ext_dir . DIRECTORY_SEPARATOR . $req_ext . '.' . PHP_SHLIB_SUFFIX;
                }
            }
        }
    }
    // additional ini overwrites
    //$ini_overwrites[] = 'setting=value';
    settings2array($ini_overwrites, $ini_settings);
    // Any special ini settings
    // these may overwrite the test defaults...
    if (array_key_exists('INI', $section_text)) {
        if (strpos($section_text['INI'], '{PWD}') !== false) {
            $section_text['INI'] = str_replace('{PWD}', dirname($file), $section_text['INI']);
        }
        settings2array(preg_split("/[\n\r]+/", $section_text['INI']), $ini_settings);
    }
    settings2params($ini_settings);
    // Check if test should be skipped.
    $info = '';
    $warn = false;
    if (array_key_exists('SKIPIF', $section_text)) {
        if (trim($section_text['SKIPIF'])) {
            show_file_block('skip', $section_text['SKIPIF']);
            save_text($test_skipif, $section_text['SKIPIF'], $temp_skipif);
            $extra = substr(PHP_OS, 0, 3) !== "WIN" ? "unset REQUEST_METHOD; unset QUERY_STRING; unset PATH_TRANSLATED; unset SCRIPT_FILENAME; unset REQUEST_METHOD;" : "";
            if ($leak_check) {
                $env['USE_ZEND_ALLOC'] = '0';
                $env['ZEND_DONT_UNLOAD_MODULES'] = 1;
            } else {
                $env['USE_ZEND_ALLOC'] = '1';
                $env['ZEND_DONT_UNLOAD_MODULES'] = 0;
            }
            junit_start_timer($shortname);
            $output = system_with_timeout("{$extra} {$php} {$pass_options} -q {$ini_settings} {$no_file_cache} -d display_errors=0 \"{$test_skipif}\"", $env);
            junit_finish_timer($shortname);
            if (!$cfg['keep']['skip']) {
                @unlink($test_skipif);
            }
            if (!strncasecmp('skip', ltrim($output), 4)) {
                if (preg_match('/^\\s*skip\\s*(.+)\\s*/i', $output, $m)) {
                    show_result('SKIP', $tested, $tested_file, "reason: {$m['1']}", $temp_filenames);
                } else {
                    show_result('SKIP', $tested, $tested_file, '', $temp_filenames);
                }
                if (!$cfg['keep']['skip']) {
                    @unlink($test_skipif);
                }
                $message = !empty($m[1]) ? $m[1] : '';
                junit_mark_test_as('SKIP', $shortname, $tested, null, $message);
                return 'SKIPPED';
            }
            if (!strncasecmp('info', ltrim($output), 4)) {
                if (preg_match('/^\\s*info\\s*(.+)\\s*/i', $output, $m)) {
                    $info = " (info: {$m['1']})";
                }
            }
            if (!strncasecmp('warn', ltrim($output), 4)) {
                if (preg_match('/^\\s*warn\\s*(.+)\\s*/i', $output, $m)) {
                    $warn = true;
                    /* only if there is a reason */
                    $info = " (warn: {$m['1']})";
                }
            }
        }
    }
    if (!extension_loaded("zlib") && (array_key_exists("GZIP_POST", $section_text) || array_key_exists("DEFLATE_POST", $section_text))) {
        $message = "ext/zlib required";
        show_result('SKIP', $tested, $tested_file, "reason: {$message}", $temp_filenames);
        junit_mark_test_as('SKIP', $shortname, $tested, null, $message);
        return 'SKIPPED';
    }
    if (@count($section_text['REDIRECTTEST']) == 1) {
        $test_files = array();
        $IN_REDIRECT = eval($section_text['REDIRECTTEST']);
        $IN_REDIRECT['via'] = "via [{$shortname}]\n\t";
        $IN_REDIRECT['dir'] = realpath(dirname($file));
        $IN_REDIRECT['prefix'] = trim($section_text['TEST']);
        if (!empty($IN_REDIRECT['TESTS'])) {
            if (is_array($org_file)) {
                $test_files[] = $org_file[1];
            } else {
                $GLOBALS['test_files'] = $test_files;
                find_files($IN_REDIRECT['TESTS']);
                foreach ($GLOBALS['test_files'] as $f) {
                    $test_files[] = array($f, $file);
                }
            }
            $test_cnt += @count($test_files) - 1;
            $test_idx--;
            show_redirect_start($IN_REDIRECT['TESTS'], $tested, $tested_file);
            // set up environment
            $redirenv = array_merge($environment, $IN_REDIRECT['ENV']);
            $redirenv['REDIR_TEST_DIR'] = realpath($IN_REDIRECT['TESTS']) . DIRECTORY_SEPARATOR;
            usort($test_files, "test_sort");
            run_all_tests($test_files, $redirenv, $tested);
            show_redirect_ends($IN_REDIRECT['TESTS'], $tested, $tested_file);
            // a redirected test never fails
            $IN_REDIRECT = false;
            junit_mark_test_as('PASS', $shortname, $tested);
            return 'REDIR';
        } else {
            $bork_info = "Redirect info must contain exactly one TEST string to be used as redirect directory.";
            show_result("BORK", $bork_info, '', $temp_filenames);
            $PHP_FAILED_TESTS['BORKED'][] = array('name' => $file, 'test_name' => '', 'output' => '', 'diff' => '', 'info' => "{$bork_info} [{$file}]");
        }
    }
    if (is_array($org_file) || @count($section_text['REDIRECTTEST']) == 1) {
        if (is_array($org_file)) {
            $file = $org_file[0];
        }
        $bork_info = "Redirected test did not contain redirection info";
        show_result("BORK", $bork_info, '', $temp_filenames);
        $PHP_FAILED_TESTS['BORKED'][] = array('name' => $file, 'test_name' => '', 'output' => '', 'diff' => '', 'info' => "{$bork_info} [{$file}]");
        junit_mark_test_as('BORK', $shortname, $tested, null, $bork_info);
        return 'BORKED';
    }
    // We've satisfied the preconditions - run the test!
    if (isset($section_text['FILE'])) {
        show_file_block('php', $section_text['FILE'], 'TEST');
        save_text($test_file, $section_text['FILE'], $temp_file);
    } else {
        $test_file = $temp_file = "";
    }
    if (array_key_exists('GET', $section_text)) {
        $query_string = trim($section_text['GET']);
    } else {
        $query_string = '';
    }
    $env['REDIRECT_STATUS'] = '1';
    if (empty($env['QUERY_STRING'])) {
        $env['QUERY_STRING'] = $query_string;
    }
    if (empty($env['PATH_TRANSLATED'])) {
        $env['PATH_TRANSLATED'] = $test_file;
    }
    if (empty($env['SCRIPT_FILENAME'])) {
        $env['SCRIPT_FILENAME'] = $test_file;
    }
    if (array_key_exists('COOKIE', $section_text)) {
        $env['HTTP_COOKIE'] = trim($section_text['COOKIE']);
    } else {
        $env['HTTP_COOKIE'] = '';
    }
    $args = isset($section_text['ARGS']) ? ' -- ' . $section_text['ARGS'] : '';
    if (array_key_exists('POST_RAW', $section_text) && !empty($section_text['POST_RAW'])) {
        $post = trim($section_text['POST_RAW']);
        $raw_lines = explode("\n", $post);
        $request = '';
        $started = false;
        foreach ($raw_lines as $line) {
            if (empty($env['CONTENT_TYPE']) && preg_match('/^Content-Type:(.*)/i', $line, $res)) {
                $env['CONTENT_TYPE'] = trim(str_replace("\r", '', $res[1]));
                continue;
            }
            if ($started) {
                $request .= "\n";
            }
            $started = true;
            $request .= $line;
        }
        $env['CONTENT_LENGTH'] = strlen($request);
        $env['REQUEST_METHOD'] = 'POST';
        if (empty($request)) {
            junit_mark_test_as('BORK', $shortname, $tested, null, 'empty $request');
            return 'BORKED';
        }
        save_text($tmp_post, $request);
        $cmd = "{$php} {$pass_options} {$ini_settings} -f \"{$test_file}\"{$cmdRedirect} < \"{$tmp_post}\"";
    } elseif (array_key_exists('PUT', $section_text) && !empty($section_text['PUT'])) {
        $post = trim($section_text['PUT']);
        $raw_lines = explode("\n", $post);
        $request = '';
        $started = false;
        foreach ($raw_lines as $line) {
            if (empty($env['CONTENT_TYPE']) && preg_match('/^Content-Type:(.*)/i', $line, $res)) {
                $env['CONTENT_TYPE'] = trim(str_replace("\r", '', $res[1]));
                continue;
            }
            if ($started) {
                $request .= "\n";
            }
            $started = true;
            $request .= $line;
        }
        $env['CONTENT_LENGTH'] = strlen($request);
        $env['REQUEST_METHOD'] = 'PUT';
        if (empty($request)) {
            junit_mark_test_as('BORK', $shortname, $tested, null, 'empty $request');
            return 'BORKED';
        }
        save_text($tmp_post, $request);
        $cmd = "{$php} {$pass_options} {$ini_settings} -f \"{$test_file}\"{$cmdRedirect} < \"{$tmp_post}\"";
    } else {
        if (array_key_exists('POST', $section_text) && !empty($section_text['POST'])) {
            $post = trim($section_text['POST']);
            $content_length = strlen($post);
            save_text($tmp_post, $post);
            $env['REQUEST_METHOD'] = 'POST';
            if (empty($env['CONTENT_TYPE'])) {
                $env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
            }
            if (empty($env['CONTENT_LENGTH'])) {
                $env['CONTENT_LENGTH'] = $content_length;
            }
            $cmd = "{$php} {$pass_options} {$ini_settings} -f \"{$test_file}\"{$cmdRedirect} < \"{$tmp_post}\"";
        } else {
            if (array_key_exists('GZIP_POST', $section_text) && !empty($section_text['GZIP_POST'])) {
                $post = trim($section_text['GZIP_POST']);
                $post = gzencode($post, 9, FORCE_GZIP);
                $env['HTTP_CONTENT_ENCODING'] = 'gzip';
                save_text($tmp_post, $post);
                $content_length = strlen($post);
                $env['REQUEST_METHOD'] = 'POST';
                $env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
                $env['CONTENT_LENGTH'] = $content_length;
                $cmd = "{$php} {$pass_options} {$ini_settings} -f \"{$test_file}\"{$cmdRedirect} < \"{$tmp_post}\"";
            } else {
                if (array_key_exists('DEFLATE_POST', $section_text) && !empty($section_text['DEFLATE_POST'])) {
                    $post = trim($section_text['DEFLATE_POST']);
                    $post = gzcompress($post, 9);
                    $env['HTTP_CONTENT_ENCODING'] = 'deflate';
                    save_text($tmp_post, $post);
                    $content_length = strlen($post);
                    $env['REQUEST_METHOD'] = 'POST';
                    $env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
                    $env['CONTENT_LENGTH'] = $content_length;
                    $cmd = "{$php} {$pass_options} {$ini_settings} -f \"{$test_file}\"{$cmdRedirect} < \"{$tmp_post}\"";
                } else {
                    $env['REQUEST_METHOD'] = 'GET';
                    $env['CONTENT_TYPE'] = '';
                    $env['CONTENT_LENGTH'] = '';
                    $cmd = "{$php} {$pass_options} {$ini_settings} -f \"{$test_file}\" {$args}{$cmdRedirect}";
                }
            }
        }
    }
    if ($leak_check) {
        $env['USE_ZEND_ALLOC'] = '0';
        $env['ZEND_DONT_UNLOAD_MODULES'] = 1;
        /* --vex-iropt-register-updates=allregs-at-mem-access is necessary for phpdbg watchpoint tests */
        if (version_compare($valgrind_version, '3.8.0', '>=')) {
            /* valgrind 3.3.0+ doesn't have --log-file-exactly option */
            $cmd = "valgrind -q --tool=memcheck --trace-children=yes --vex-iropt-register-updates=allregs-at-mem-access --log-file={$memcheck_filename} {$cmd}";
        } elseif (version_compare($valgrind_version, '3.3.0', '>=')) {
            $cmd = "valgrind -q --tool=memcheck --trace-children=yes --vex-iropt-precise-memory-exns=yes --log-file={$memcheck_filename} {$cmd}";
        } else {
            $cmd = "valgrind -q --tool=memcheck --trace-children=yes --vex-iropt-precise-memory-exns=yes --log-file-exactly={$memcheck_filename} {$cmd}";
        }
    } else {
        $env['USE_ZEND_ALLOC'] = '1';
        $env['ZEND_DONT_UNLOAD_MODULES'] = 0;
    }
    if ($DETAILED) {
        echo "\nCONTENT_LENGTH  = " . $env['CONTENT_LENGTH'] . "\nCONTENT_TYPE    = " . $env['CONTENT_TYPE'] . "\nPATH_TRANSLATED = " . $env['PATH_TRANSLATED'] . "\nQUERY_STRING    = " . $env['QUERY_STRING'] . "\nREDIRECT_STATUS = " . $env['REDIRECT_STATUS'] . "\nREQUEST_METHOD  = " . $env['REQUEST_METHOD'] . "\nSCRIPT_FILENAME = " . $env['SCRIPT_FILENAME'] . "\nHTTP_COOKIE     = " . $env['HTTP_COOKIE'] . "\nCOMMAND {$cmd}\n";
    }
    junit_start_timer($shortname);
    $out = system_with_timeout($cmd, $env, isset($section_text['STDIN']) ? $section_text['STDIN'] : null, $captureStdIn, $captureStdOut, $captureStdErr);
    junit_finish_timer($shortname);
    if (array_key_exists('CLEAN', $section_text) && (!$no_clean || $cfg['keep']['clean'])) {
        if (trim($section_text['CLEAN'])) {
            show_file_block('clean', $section_text['CLEAN']);
            save_text($test_clean, trim($section_text['CLEAN']), $temp_clean);
            if (!$no_clean) {
                $clean_params = array();
                settings2array($ini_overwrites, $clean_params);
                settings2params($clean_params);
                $extra = substr(PHP_OS, 0, 3) !== "WIN" ? "unset REQUEST_METHOD; unset QUERY_STRING; unset PATH_TRANSLATED; unset SCRIPT_FILENAME; unset REQUEST_METHOD;" : "";
                system_with_timeout("{$extra} {$php} {$pass_options} -q {$clean_params} {$no_file_cache} \"{$test_clean}\"", $env);
            }
            if (!$cfg['keep']['clean']) {
                @unlink($test_clean);
            }
        }
    }
    @unlink($tmp_post);
    $leaked = false;
    $passed = false;
    if ($leak_check) {
        // leak check
        $leaked = filesize($memcheck_filename) > 0;
        if (!$leaked) {
            @unlink($memcheck_filename);
        }
    }
    // Does the output match what is expected?
    $output = preg_replace("/\r\n/", "\n", trim($out));
    /* when using CGI, strip the headers from the output */
    $headers = array();
    if (!empty($uses_cgi) && preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $out, $match)) {
        $output = trim($match[2]);
        $rh = preg_split("/[\n\r]+/", $match[1]);
        foreach ($rh as $line) {
            if (strpos($line, ':') !== false) {
                $line = explode(':', $line, 2);
                $headers[trim($line[0])] = trim($line[1]);
            }
        }
    }
    $failed_headers = false;
    if (isset($section_text['EXPECTHEADERS'])) {
        $want = array();
        $wanted_headers = array();
        $lines = preg_split("/[\n\r]+/", $section_text['EXPECTHEADERS']);
        foreach ($lines as $line) {
            if (strpos($line, ':') !== false) {
                $line = explode(':', $line, 2);
                $want[trim($line[0])] = trim($line[1]);
                $wanted_headers[] = trim($line[0]) . ': ' . trim($line[1]);
            }
        }
        $output_headers = array();
        foreach ($want as $k => $v) {
            if (isset($headers[$k])) {
                $output_headers[] = $k . ': ' . $headers[$k];
            }
            if (!isset($headers[$k]) || $headers[$k] != $v) {
                $failed_headers = true;
            }
        }
        ksort($wanted_headers);
        $wanted_headers = implode("\n", $wanted_headers);
        ksort($output_headers);
        $output_headers = implode("\n", $output_headers);
    }
    show_file_block('out', $output);
    if (isset($section_text['EXPECTF']) || isset($section_text['EXPECTREGEX'])) {
        if (isset($section_text['EXPECTF'])) {
            $wanted = trim($section_text['EXPECTF']);
        } else {
            $wanted = trim($section_text['EXPECTREGEX']);
        }
        show_file_block('exp', $wanted);
        $wanted_re = preg_replace('/\\r\\n/', "\n", $wanted);
        if (isset($section_text['EXPECTF'])) {
            // do preg_quote, but miss out any %r delimited sections
            $temp = "";
            $r = "%r";
            $startOffset = 0;
            $length = strlen($wanted_re);
            while ($startOffset < $length) {
                $start = strpos($wanted_re, $r, $startOffset);
                if ($start !== false) {
                    // we have found a start tag
                    $end = strpos($wanted_re, $r, $start + 2);
                    if ($end === false) {
                        // unbalanced tag, ignore it.
                        $end = $start = $length;
                    }
                } else {
                    // no more %r sections
                    $start = $end = $length;
                }
                // quote a non re portion of the string
                $temp = $temp . preg_quote(substr($wanted_re, $startOffset, $start - $startOffset), '/');
                // add the re unquoted.
                if ($end > $start) {
                    $temp = $temp . '(' . substr($wanted_re, $start + 2, $end - $start - 2) . ')';
                }
                $startOffset = $end + 2;
            }
            $wanted_re = $temp;
            $wanted_re = str_replace(array('%binary_string_optional%'), 'string', $wanted_re);
            $wanted_re = str_replace(array('%unicode_string_optional%'), 'string', $wanted_re);
            $wanted_re = str_replace(array('%unicode\\|string%', '%string\\|unicode%'), 'string', $wanted_re);
            $wanted_re = str_replace(array('%u\\|b%', '%b\\|u%'), '', $wanted_re);
            // Stick to basics
            $wanted_re = str_replace('%e', '\\' . DIRECTORY_SEPARATOR, $wanted_re);
            $wanted_re = str_replace('%s', '[^\\r\\n]+', $wanted_re);
            $wanted_re = str_replace('%S', '[^\\r\\n]*', $wanted_re);
            $wanted_re = str_replace('%a', '.+', $wanted_re);
            $wanted_re = str_replace('%A', '.*', $wanted_re);
            $wanted_re = str_replace('%w', '\\s*', $wanted_re);
            $wanted_re = str_replace('%i', '[+-]?\\d+', $wanted_re);
            $wanted_re = str_replace('%d', '\\d+', $wanted_re);
            $wanted_re = str_replace('%x', '[0-9a-fA-F]+', $wanted_re);
            $wanted_re = str_replace('%f', '[+-]?\\.?\\d+\\.?\\d*(?:[Ee][+-]?\\d+)?', $wanted_re);
            $wanted_re = str_replace('%c', '.', $wanted_re);
            // %f allows two points "-.0.0" but that is the best *simple* expression
        }
        /* DEBUG YOUR REGEX HERE
        		var_dump($wanted_re);
        		print(str_repeat('=', 80) . "\n");
        		var_dump($output);
        */
        if (preg_match("/^{$wanted_re}\$/s", $output)) {
            $passed = true;
            if (!$cfg['keep']['php']) {
                @unlink($test_file);
            }
            if (!$leaked && !$failed_headers) {
                if (isset($section_text['XFAIL'])) {
                    $warn = true;
                    $info = " (warn: XFAIL section but test passes)";
                } else {
                    show_result("PASS", $tested, $tested_file, '', $temp_filenames);
                    junit_mark_test_as('PASS', $shortname, $tested);
                    return 'PASSED';
                }
            }
        }
    } else {
        $wanted = trim($section_text['EXPECT']);
        $wanted = preg_replace('/\\r\\n/', "\n", $wanted);
        show_file_block('exp', $wanted);
        // compare and leave on success
        if (!strcmp($output, $wanted)) {
            $passed = true;
            if (!$cfg['keep']['php']) {
                @unlink($test_file);
            }
            if (!$leaked && !$failed_headers) {
                if (isset($section_text['XFAIL'])) {
                    $warn = true;
                    $info = " (warn: XFAIL section but test passes)";
                } else {
                    show_result("PASS", $tested, $tested_file, '', $temp_filenames);
                    junit_mark_test_as('PASS', $shortname, $tested);
                    return 'PASSED';
                }
            }
        }
        $wanted_re = null;
    }
    // Test failed so we need to report details.
    if ($failed_headers) {
        $passed = false;
        $wanted = $wanted_headers . "\n--HEADERS--\n" . $wanted;
        $output = $output_headers . "\n--HEADERS--\n" . $output;
        if (isset($wanted_re)) {
            $wanted_re = preg_quote($wanted_headers . "\n--HEADERS--\n", '/') . $wanted_re;
        }
    }
    if ($leaked) {
        $restype[] = 'LEAK';
    }
    if ($warn) {
        $restype[] = 'WARN';
    }
    if (!$passed) {
        if (isset($section_text['XFAIL'])) {
            $restype[] = 'XFAIL';
            $info = '  XFAIL REASON: ' . rtrim($section_text['XFAIL']);
        } else {
            $restype[] = 'FAIL';
        }
    }
    if (!$passed) {
        // write .exp
        if (strpos($log_format, 'E') !== false && file_put_contents($exp_filename, $wanted, FILE_BINARY) === false) {
            error("Cannot create expected test output - {$exp_filename}");
        }
        // write .out
        if (strpos($log_format, 'O') !== false && file_put_contents($output_filename, $output, FILE_BINARY) === false) {
            error("Cannot create test output - {$output_filename}");
        }
        // write .diff
        $diff = generate_diff($wanted, $wanted_re, $output);
        if (is_array($IN_REDIRECT)) {
            $diff = "# original source file: {$shortname}\n" . $diff;
        }
        show_file_block('diff', $diff);
        if (strpos($log_format, 'D') !== false && file_put_contents($diff_filename, $diff, FILE_BINARY) === false) {
            error("Cannot create test diff - {$diff_filename}");
        }
        // write .sh
        if (strpos($log_format, 'S') !== false && file_put_contents($sh_filename, "#!/bin/sh\n\n{$cmd}\n", FILE_BINARY) === false) {
            error("Cannot create test shell script - {$sh_filename}");
        }
        chmod($sh_filename, 0755);
        // write .log
        if (strpos($log_format, 'L') !== false && file_put_contents($log_filename, "\n---- EXPECTED OUTPUT\n{$wanted}\n---- ACTUAL OUTPUT\n{$output}\n---- FAILED\n", FILE_BINARY) === false) {
            error("Cannot create test log - {$log_filename}");
            error_report($file, $log_filename, $tested);
        }
    }
    show_result(implode('&', $restype), $tested, $tested_file, $info, $temp_filenames);
    foreach ($restype as $type) {
        $PHP_FAILED_TESTS[$type . 'ED'][] = array('name' => $file, 'test_name' => (is_array($IN_REDIRECT) ? $IN_REDIRECT['via'] : '') . $tested . " [{$tested_file}]", 'output' => $output_filename, 'diff' => $diff_filename, 'info' => $info);
    }
    $diff = empty($diff) ? '' : preg_replace('/\\e/', '<esc>', $diff);
    junit_mark_test_as($restype, str_replace($cwd . '/', '', $tested_file), $tested, null, $info, $diff);
    return $restype[0] . 'ED';
}
示例#10
0
function run_test($php, $file, $test_cnt, $test_idx)
{
    global $log_format, $info_params, $ini_overwrites, $cwd, $PHP_FAILED_TESTS, $pass_options, $DETAILED, $IN_REDIRECT;
    if ($DETAILED) {
        echo "\n=================\nTEST {$file}\n";
    }
    // Load the sections of the test file.
    $section_text = array('TEST' => '', 'SKIPIF' => '', 'GET' => '', 'ARGS' => '');
    $fp = @fopen($file, "r") or error("Cannot open test file: {$file}");
    $borked = false;
    $bork_info = '';
    if (!feof($fp)) {
        $line = fgets($fp);
    } else {
        $bork_info = "empty test [{$file}]";
        $borked = true;
    }
    if (!ereg('^--TEST--', $line, $r)) {
        $bork_info = "tests must start with --TEST-- [{$file}]";
        $borked = true;
    }
    $section = 'TEST';
    while (!feof($fp)) {
        $line = fgets($fp);
        // Match the beginning of a section.
        if (ereg('^--([A-Z]+)--', $line, $r)) {
            $section = $r[1];
            $section_text[$section] = '';
            continue;
        }
        // Add to the section text.
        $section_text[$section] .= $line;
    }
    // the redirect section allows a set of tests to be reused outside of
    // a given test dir
    if (@count($section_text['REDIRECTTEST']) == 1) {
        if ($IN_REDIRECT) {
            $borked = true;
            $bork_info = "Can't redirect a test from within a redirected test";
        } else {
            $borked = false;
        }
    } else {
        if (@count($section_text['FILE']) != 1) {
            $bork_info = "missing section --FILE-- [{$file}]";
            $borked = true;
        }
        if (@count($section_text['EXPECT']) + @count($section_text['EXPECTF']) + @count($section_text['EXPECTREGEX']) != 1) {
            $bork_info = "missing section --EXPECT--, --EXPECTF-- or --EXPECTREGEX-- [{$file}]";
            $borked = true;
            print_r($section_text);
        }
    }
    fclose($fp);
    if ($borked) {
        echo "BORK {$bork_info} [{$file}]\n";
        $PHP_FAILED_TESTS['BORKED'][] = array('name' => $file, 'test_name' => '', 'output' => '', 'diff' => '', 'info' => $bork_info);
        return 'BORKED';
    }
    /* For GET/POST tests, check if cgi sapi is available and if it is, use it. */
    if (!empty($section_text['GET']) || !empty($section_text['POST'])) {
        if (file_exists("./sapi/cgi/php")) {
            $old_php = $php;
            $php = realpath("./sapi/cgi/php") . ' -C ';
        }
    }
    $shortname = str_replace($cwd . '/', '', $file);
    $tested = trim($section_text['TEST']) . " [{$shortname}]";
    echo "TEST {$test_idx}/{$test_cnt} [{$shortname}]\r";
    flush();
    if (is_array($IN_REDIRECT)) {
        $tmp = $IN_REDIRECT['dir'];
    } else {
        $tmp = realpath(dirname($file));
    }
    $diff_filename = $tmp . DIRECTORY_SEPARATOR . ereg_replace('\\.phpt$', '.diff', basename($file));
    $log_filename = $tmp . DIRECTORY_SEPARATOR . ereg_replace('\\.phpt$', '.log', basename($file));
    $exp_filename = $tmp . DIRECTORY_SEPARATOR . ereg_replace('\\.phpt$', '.exp', basename($file));
    $output_filename = $tmp . DIRECTORY_SEPARATOR . ereg_replace('\\.phpt$', '.out', basename($file));
    $tmp_skipif = $tmp . DIRECTORY_SEPARATOR . uniqid('/phpt.');
    $tmp_file = $tmp . DIRECTORY_SEPARATOR . ereg_replace('\\.phpt$', '.php', basename($file));
    $tmp_post = $tmp . DIRECTORY_SEPARATOR . uniqid('/phpt.');
    if (is_array($IN_REDIRECT)) {
        $tested = $IN_REDIRECT['prefix'] . ' ' . trim($section_text['TEST']) . " [{$tmp_file}]";
        $section_text['FILE'] = "# original source file: {$shortname}\n" . $section_text['FILE'];
    }
    @unlink($tmp_skipif);
    @unlink($tmp_file);
    @unlink($tmp_post);
    // unlink old test results
    @unlink($diff_filename);
    @unlink($log_filename);
    @unlink($exp_filename);
    @unlink($output_filename);
    // Reset environment from any previous test.
    putenv("REDIRECT_STATUS=");
    putenv("QUERY_STRING=");
    putenv("PATH_TRANSLATED=");
    putenv("SCRIPT_FILENAME=");
    putenv("REQUEST_METHOD=");
    putenv("CONTENT_TYPE=");
    putenv("CONTENT_LENGTH=");
    // Check if test should be skipped.
    $info = '';
    $warn = false;
    if (array_key_exists('SKIPIF', $section_text)) {
        if (trim($section_text['SKIPIF'])) {
            $skipif_params = array();
            settings2array($ini_overwrites, $skipif_params);
            settings2params($skipif_params);
            save_text($tmp_skipif, $section_text['SKIPIF']);
            $extra = substr(PHP_OS, 0, 3) !== "WIN" ? "unset REQUEST_METHOD; unset QUERY_STRING; unset PATH_TRANSLATED; unset SCRIPT_FILENAME; unset REQUEST_METHOD;" : "";
            $output = system_with_timeout("{$extra} {$php} -q {$skipif_params} {$tmp_skipif}");
            @unlink($tmp_skipif);
            if (eregi("^skip", trim($output))) {
                echo "SKIP {$tested}";
                $reason = eregi("^skip[[:space:]]*(.+)\$", trim($output)) ? eregi_replace("^skip[[:space:]]*(.+)\$", "\\1", trim($output)) : FALSE;
                if ($reason) {
                    echo " (reason: {$reason})\n";
                } else {
                    echo "\n";
                }
                if (isset($old_php)) {
                    $php = $old_php;
                }
                return 'SKIPPED';
            }
            if (eregi("^info", trim($output))) {
                $reason = ereg("^info[[:space:]]*(.+)\$", trim($output)) ? ereg_replace("^info[[:space:]]*(.+)\$", "\\1", trim($output)) : FALSE;
                if ($reason) {
                    $info = " (info: {$reason})";
                }
            }
            if (eregi("^warn", trim($output))) {
                $reason = ereg("^warn[[:space:]]*(.+)\$", trim($output)) ? ereg_replace("^warn[[:space:]]*(.+)\$", "\\1", trim($output)) : FALSE;
                if ($reason) {
                    $warn = true;
                    /* only if there is a reason */
                    $info = " (warn: {$reason})";
                }
            }
        }
    }
    if (@count($section_text['REDIRECTTEST']) == 1) {
        global $test_files, $test_results, $failed_tests_file;
        $saved_test_files = $test_files;
        $test_files = array();
        $IN_REDIRECT = eval($section_text['REDIRECTTEST']);
        $IN_REDIRECT['via'] = "via [{$shortname}]\n\t";
        $IN_REDIRECT['dir'] = realpath(dirname($file));
        $IN_REDIRECT['prefix'] = trim($section_text['TEST']);
        find_files($IN_REDIRECT['TESTS']);
        $test_cnt += count($test_files);
        $GLOBALS['test_cnt'] = $test_cnt;
        echo "---> {$IN_REDIRECT['TESTS']} ({$tested})\n";
        // set up environment
        foreach ($IN_REDIRECT['ENV'] as $k => $v) {
            putenv("{$k}={$v}");
        }
        putenv("REDIR_TEST_DIR=" . realpath($IN_REDIRECT['TESTS']) . DIRECTORY_SEPARATOR);
        usort($test_files, "test_sort");
        foreach ($test_files as $name) {
            $result = run_test($php, $name, $test_cnt, ++$test_idx);
            $test_results[$tested . ': ' . $name] = $result;
            if ($failed_tests_file && ($result == 'FAILED' || $result == 'WARNED')) {
                fwrite($failed_tests_file, "{$tested}: {$name}\n");
            }
        }
        echo "---> {$IN_REDIRECT['TESTS']} ({$tested}) done\n";
        $GLOBALS['test_idx'] = $test_idx;
        $test_files = $saved_test_files;
        // clean up environment
        foreach ($IN_REDIRECT['ENV'] as $k => $v) {
            putenv("{$k}=");
        }
        putenv("REDIR_TEST_DIR=");
        // a redirected test never fails
        $IN_REDIRECT = false;
        return 'PASSED';
    }
    // Default ini settings
    $ini_settings = array();
    // additional ini overwrites
    //$ini_overwrites[] = 'setting=value';
    settings2array($ini_overwrites, $ini_settings);
    // Any special ini settings
    // these may overwrite the test defaults...
    if (array_key_exists('INI', $section_text)) {
        settings2array(preg_split("/[\n\r]+/", $section_text['INI']), $ini_settings);
    }
    settings2params($ini_settings);
    // We've satisfied the preconditions - run the test!
    save_text($tmp_file, $section_text['FILE']);
    if (array_key_exists('GET', $section_text)) {
        $query_string = trim($section_text['GET']);
    } else {
        $query_string = '';
    }
    if (!empty($section_text['ENV'])) {
        foreach (explode("\n", $section_text['ENV']) as $env) {
            $env = trim($env) and putenv($env);
        }
    }
    putenv("REDIRECT_STATUS=1");
    putenv("QUERY_STRING={$query_string}");
    putenv("PATH_TRANSLATED={$tmp_file}");
    putenv("SCRIPT_FILENAME={$tmp_file}");
    $args = $section_text['ARGS'] ? ' -- ' . $section_text['ARGS'] : '';
    if (array_key_exists('POST', $section_text) && !empty($section_text['POST'])) {
        $post = trim($section_text['POST']);
        save_text($tmp_post, $post);
        $content_length = strlen($post);
        putenv("REQUEST_METHOD=POST");
        putenv("CONTENT_TYPE=application/x-www-form-urlencoded");
        putenv("CONTENT_LENGTH={$content_length}");
        $cmd = "{$php}{$pass_options}{$ini_settings} -f \"{$tmp_file}\" 2>&1 < {$tmp_post}";
    } else {
        putenv("REQUEST_METHOD=GET");
        putenv("CONTENT_TYPE=");
        putenv("CONTENT_LENGTH=");
        if (empty($section_text['ENV'])) {
            $cmd = "{$php}{$pass_options}{$ini_settings} -f \"{$tmp_file}\" {$args} 2>&1";
        } else {
            $cmd = "{$php}{$pass_options}{$ini_settings} < \"{$tmp_file}\" {$args} 2>&1";
        }
    }
    if ($DETAILED) {
        echo "\nCONTENT_LENGTH  = " . getenv("CONTENT_LENGTH") . "\nCONTENT_TYPE    = " . getenv("CONTENT_TYPE") . "\nPATH_TRANSLATED = " . getenv("PATH_TRANSLATED") . "\nQUERY_STRING    = " . getenv("QUERY_STRING") . "\nREDIRECT_STATUS = " . getenv("REDIRECT_STATUS") . "\nREQUEST_METHOD  = " . getenv("REQUEST_METHOD") . "\nSCRIPT_FILENAME = " . getenv("SCRIPT_FILENAME") . "\nCOMMAND {$cmd}\n";
    }
    //	$out = `$cmd`;
    $out = system_with_timeout($cmd);
    if (!empty($section_text['ENV'])) {
        foreach (explode("\n", $section_text['ENV']) as $env) {
            $env = explode('=', $env);
            putenv($env[0] . '=');
        }
    }
    @unlink($tmp_post);
    // Does the output match what is expected?
    $output = trim($out);
    $output = preg_replace('/\\r\\n/', "\n", $output);
    /* when using CGI, strip the headers from the output */
    if (isset($old_php) && ($pos = strpos($output, "\n\n")) !== FALSE) {
        $output = substr($output, $pos + 2);
    }
    if (isset($section_text['EXPECTF']) || isset($section_text['EXPECTREGEX'])) {
        if (isset($section_text['EXPECTF'])) {
            $wanted = trim($section_text['EXPECTF']);
        } else {
            $wanted = trim($section_text['EXPECTREGEX']);
        }
        $wanted_re = preg_replace('/\\r\\n/', "\n", $wanted);
        if (isset($section_text['EXPECTF'])) {
            $wanted_re = preg_quote($wanted_re, '/');
            // Stick to basics
            $wanted_re = str_replace("%e", '\\' . DIRECTORY_SEPARATOR, $wanted_re);
            $wanted_re = str_replace("%s", ".+?", $wanted_re);
            //not greedy
            $wanted_re = str_replace("%i", "[+\\-]?[0-9]+", $wanted_re);
            $wanted_re = str_replace("%d", "[0-9]+", $wanted_re);
            $wanted_re = str_replace("%x", "[0-9a-fA-F]+", $wanted_re);
            $wanted_re = str_replace("%f", "[+\\-]?\\.?[0-9]+\\.?[0-9]*(E-?[0-9]+)?", $wanted_re);
            $wanted_re = str_replace("%c", ".", $wanted_re);
            // %f allows two points "-.0.0" but that is the best *simple* expression
        }
        /* DEBUG YOUR REGEX HERE
        		var_dump($wanted_re);
        		print(str_repeat('=', 80) . "\n");
        		var_dump($output);
        */
        if (preg_match("/^{$wanted_re}\$/s", $output)) {
            @unlink($tmp_file);
            echo "PASS {$tested}\n";
            if (isset($old_php)) {
                $php = $old_php;
            }
            return 'PASSED';
        }
    } else {
        $wanted = trim($section_text['EXPECT']);
        $wanted = preg_replace('/\\r\\n/', "\n", $wanted);
        // compare and leave on success
        $ok = 0 == strcmp($output, $wanted);
        if ($ok) {
            @unlink($tmp_file);
            echo "PASS {$tested}\n";
            if (isset($old_php)) {
                $php = $old_php;
            }
            return 'PASSED';
        }
        $wanted_re = NULL;
    }
    // Test failed so we need to report details.
    if ($warn) {
        echo "WARN {$tested}{$info}\n";
    } else {
        echo "FAIL {$tested}{$info}\n";
    }
    $PHP_FAILED_TESTS['FAILED'][] = array('name' => $file, 'test_name' => (is_array($IN_REDIRECT) ? $IN_REDIRECT['via'] : '') . $tested, 'output' => $output_filename, 'diff' => $diff_filename, 'info' => $info);
    // write .exp
    if (strpos($log_format, 'E') !== FALSE) {
        $log = fopen($exp_filename, 'w') or error("Cannot create test log - {$exp_filename}");
        fwrite($log, $wanted);
        fclose($log);
    }
    // write .out
    if (strpos($log_format, 'O') !== FALSE) {
        $log = fopen($output_filename, 'w') or error("Cannot create test log - {$output_filename}");
        fwrite($log, $output);
        fclose($log);
    }
    // write .diff
    if (strpos($log_format, 'D') !== FALSE) {
        $log = fopen($diff_filename, 'w') or error("Cannot create test log - {$diff_filename}");
        fwrite($log, generate_diff($wanted, $wanted_re, $output));
        fclose($log);
    }
    // write .log
    if (strpos($log_format, 'L') !== FALSE) {
        $log = fopen($log_filename, 'w') or error("Cannot create test log - {$log_filename}");
        fwrite($log, "\n---- EXPECTED OUTPUT\n{$wanted}\n---- ACTUAL OUTPUT\n{$output}\n---- FAILED\n");
        fclose($log);
        error_report($file, $log_filename, $tested);
    }
    if (isset($old_php)) {
        $php = $old_php;
    }
    return $warn ? 'WARNED' : 'FAILED';
}
示例#11
0
function serverInterface_error_report($a)
{
    if (G()->SET['error_report']['javascript']->v) {
        $a['error source'] = 'js';
        error_report($a);
    }
}
    function calc_child_comments_amount()
    {
        global $db, $config_vars;
        //get the comments from  cat
        $sql = 'SELECT count(cat_comments.id) FROM ' . $config_vars['table_prefix'] . 'cat_comments AS cat_comments WHERE cat_comments.owner_id = ' . $this->id;
        if (!($result = $db->sql_query($sql))) {
            $error = new phreak_error(E_WARNING, SQL_ERROR, __LINE__, __FILE__, 'calc_child_comments_amoount', $this->id, 0, 0, $sql);
            $error->commit();
            error_report(SQL_ERROR, 'commit', __LINE__, __FILE__, $sql);
        }
        $row = $db->sql_fetchrow($result);
        $amount = $row[0];
        //get the comments from content
        $sql = 'SELECT count(content_comments.id) 
				FROM ' . $config_vars['table_prefix'] . 'content_comments AS content_comments, ' . $config_vars['table_prefix'] . 'content_in_cat AS content_in_cat 
				WHERE (content_in_cat.cat_id = ' . $this->id . ') AND (content_in_cat.content_id = content_comments.owner_id)';
        if (!($result = $db->sql_query($sql))) {
            error_report(SQL_ERROR, 'commit', __LINE__, __FILE__, $sql);
        }
        $row = $db->sql_fetchrow($result);
        $amount += $row[0];
        $child_cats = get_cats_of_cat($this->id);
        for ($i = 0; $i < sizeof($child_cats); $i++) {
            if ($child_cats[$i]->id != $config_vars['root_categorie']) {
                $amount += $child_cats[$i]->calc_child_comments_amount();
            }
        }
        return $amount;
    }
示例#13
0
    $entry->commit();
    $HTTP_GET_VARS['sel_group_id'] = $entry->id;
}
if (isset($HTTP_POST_VARS['change'])) {
    // make sure at first var is set
    if ($HTTP_POST_VARS[$entry->processing_vars[0]] == '') {
        error_report(INFORMATION, 'enter_name', __LINE__, __FILE__);
    }
    $entry->generate_from_id($HTTP_GET_VARS['sel_group_id']);
    $entry->set_vars($HTTP_POST_VARS);
    $entry->commit();
}
// get all usergroups
$sql = "SELECT * from " . $config_vars['table_prefix'] . "{$_SESSION[type]}s";
if (!($result = $db->sql_query($sql))) {
    error_report(AUTH_ERROR, 'get_groups', __LINE__, __FILE__, $sql);
}
while ($row = $db->sql_fetchrow($result)) {
    $groups[] = $row;
}
// get data of selected group
foreach ($groups as $value) {
    if ($value['id'] == $HTTP_GET_VARS['sel_group_id']) {
        $sel_group = $value;
        break;
    }
}
$smarty->assign('processing_vars', $entry->processing_vars);
$smarty->assign('groups', $groups);
$smarty->assign('sel_group_id', $HTTP_GET_VARS['sel_group_id']);
$smarty->assign('sel_group', $sel_group);
示例#14
0
function db_mark_user_as_authenicated($bggusername, $cookie, $auth_req_id)
{
    global $dbh;
    $id = FALSE;
    $sth = $dbh->prepare('
		SELECT id
			FROM `users`
	WHERE username=:username
		');
    $sth->bindParam('username', $bggusername, PDO::PARAM_STR);
    $sth->execute();
    $id = FALSE;
    if ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
        $id = $row['id'];
    }
    $sth = NULL;
    $params = array('username' => $bggusername, 'cookie' => $cookie);
    if ($id === FALSE) {
        $sth = $dbh->prepare('INSERT INTO users (username, cookie) VALUES (:username, :cookie)');
    } else {
        $sth = $dbh->prepare('UPDATE users SET username=:username, cookie=:cookie WHERE id=:id');
        $params['id'] = $id;
    }
    $result = $sth->execute($params);
    # Now the user is authenticated, we can delete the auth request
    if ($result) {
        $sth = $dbh->prepare('DELETE FROM authrequests WHERE id=:id');
        $delete_result = $sth->execute(array(':id' => $auth_req_id));
        if ($delete_result === FALSE) {
            $info = $sth->errorInfo();
            error_report("Warning: There was en error deleting auth request ID=" . $auth_req_id . " (" . $info[2] . "). Until it is deleted, that user cannot re-auth.");
        }
    }
    return $result !== FALSE;
}
示例#15
0
function run_test($php, $file, $env)
{
    global $log_format, $info_params, $ini_overwrites, $cwd, $PHP_FAILED_TESTS;
    global $pass_options, $DETAILED, $IN_REDIRECT, $test_cnt, $test_idx;
    global $leak_check, $temp_source, $temp_target, $cfg, $environment;
    global $no_clean;
    global $valgrind_version;
    $temp_filenames = null;
    $org_file = $file;
    if (isset($env['TEST_PHP_CGI_EXECUTABLE'])) {
        $php_cgi = $env['TEST_PHP_CGI_EXECUTABLE'];
    }
    if (is_array($file)) {
        $file = $file[0];
    }
    if ($DETAILED) {
        echo "\n=================\nTEST {$file}\n";
    }
    // Load the sections of the test file.
    $section_text = array('TEST' => '');
    $fp = fopen($file, "rt") or error("Cannot open test file: {$file}");
    $borked = false;
    $bork_info = '';
    if (!feof($fp)) {
        $line = fgets($fp);
        if ($line === false) {
            $bork_info = "cannot read test";
            $borked = true;
        }
    } else {
        $bork_info = "empty test [{$file}]";
        $borked = true;
    }
    if (!$borked && strncmp('--TEST--', $line, 8)) {
        $bork_info = "tests must start with --TEST-- [{$file}]";
        $borked = true;
    }
    $section = 'TEST';
    $secfile = false;
    $secdone = false;
    while (!feof($fp)) {
        $line = fgets($fp);
        // Match the beginning of a section.
        if (preg_match('/^--([_A-Z]+)--/', $line, $r)) {
            $section = $r[1];
            if (isset($section_text[$section])) {
                $bork_info = "duplicated {$section} section";
                $borked = true;
            }
            $section_text[$section] = '';
            $secfile = $section == 'FILE' || $section == 'FILEEOF' || $section == 'FILE_EXTERNAL';
            $secdone = false;
            continue;
        }
        // Add to the section text.
        if (!$secdone) {
            $section_text[$section] .= $line;
        }
        // End of actual test?
        if ($secfile && preg_match('/^===DONE===\\s*$/', $line)) {
            $secdone = true;
        }
    }
    // the redirect section allows a set of tests to be reused outside of
    // a given test dir
    if (!$borked) {
        if (@count($section_text['REDIRECTTEST']) == 1) {
            if ($IN_REDIRECT) {
                $borked = true;
                $bork_info = "Can't redirect a test from within a redirected test";
            } else {
                $borked = false;
            }
        } else {
            if (@count($section_text['FILE']) + @count($section_text['FILEEOF']) + @count($section_text['FILE_EXTERNAL']) != 1) {
                $bork_info = "missing section --FILE--";
                $borked = true;
            }
            if (@count($section_text['FILEEOF']) == 1) {
                $section_text['FILE'] = preg_replace("/[\r\n]+\$/", '', $section_text['FILEEOF']);
                unset($section_text['FILEEOF']);
            }
            if (@count($section_text['FILE_EXTERNAL']) == 1) {
                // don't allow tests to retrieve files from anywhere but this subdirectory
                $section_text['FILE_EXTERNAL'] = dirname($file) . '/' . trim(str_replace('..', '', $section_text['FILE_EXTERNAL']));
                if (file_exists($section_text['FILE_EXTERNAL'])) {
                    $section_text['FILE'] = file_get_contents($section_text['FILE_EXTERNAL']);
                    unset($section_text['FILE_EXTERNAL']);
                } else {
                    $bork_info = "could not load --FILE_EXTERNAL-- " . dirname($file) . '/' . trim($section_text['FILE_EXTERNAL']);
                    $borked = true;
                }
            }
            if (@count($section_text['EXPECT']) + @count($section_text['EXPECTF']) + @count($section_text['EXPECTREGEX']) != 1) {
                $bork_info = "missing section --EXPECT--, --EXPECTF-- or --EXPECTREGEX--";
                $borked = true;
            }
        }
    }
    fclose($fp);
    $shortname = str_replace($cwd . '/', '', $file);
    $tested_file = $shortname;
    if ($borked) {
        show_result("BORK", $bork_info, $tested_file);
        $PHP_FAILED_TESTS['BORKED'][] = array('name' => $file, 'test_name' => '', 'output' => '', 'diff' => '', 'info' => "{$bork_info} [{$file}]");
        return 'BORKED';
    }
    $tested = trim($section_text['TEST']);
    /* For GET/POST tests, check if cgi sapi is available and if it is, use it. */
    if (!empty($section_text['GET']) || !empty($section_text['POST']) || !empty($section_text['POST_RAW']) || !empty($section_text['COOKIE']) || !empty($section_text['EXPECTHEADERS'])) {
        if (isset($php_cgi)) {
            $old_php = $php;
            $php = $php_cgi . ' -C ';
        } else {
            if (!strncasecmp(PHP_OS, "win", 3) && file_exists(dirname($php) . "/php-cgi.exe")) {
                $old_php = $php;
                $php = realpath(dirname($php) . "/php-cgi.exe") . ' -C ';
            } else {
                if (file_exists(dirname($php) . "/../../sapi/cgi/php-cgi")) {
                    $old_php = $php;
                    $php = realpath(dirname($php) . "/../../sapi/cgi/php-cgi") . ' -C ';
                } else {
                    if (file_exists("./sapi/cgi/php-cgi")) {
                        $old_php = $php;
                        $php = realpath("./sapi/cgi/php-cgi") . ' -C ';
                    } else {
                        show_result('SKIP', $tested, $tested_file, "reason: CGI not available");
                        return 'SKIPPED';
                    }
                }
            }
        }
    }
    show_test($test_idx, $shortname);
    if (is_array($IN_REDIRECT)) {
        $temp_dir = $test_dir = $IN_REDIRECT['dir'];
    } else {
        $temp_dir = $test_dir = realpath(dirname($file));
    }
    if ($temp_source && $temp_target) {
        $temp_dir = str_replace($temp_source, $temp_target, $temp_dir);
    }
    $main_file_name = basename($file, 'phpt');
    $diff_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'diff';
    $log_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'log';
    $exp_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'exp';
    $output_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'out';
    $memcheck_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'mem';
    $temp_file = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'php';
    $test_file = $test_dir . DIRECTORY_SEPARATOR . $main_file_name . 'php';
    $temp_skipif = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'skip.php';
    $test_skipif = $test_dir . DIRECTORY_SEPARATOR . $main_file_name . 'skip.php';
    $temp_clean = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'clean.php';
    $test_clean = $test_dir . DIRECTORY_SEPARATOR . $main_file_name . 'clean.php';
    $tmp_post = $temp_dir . DIRECTORY_SEPARATOR . uniqid('/phpt.');
    $tmp_relative_file = str_replace(realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR, '', $test_file) . 't';
    if ($temp_source && $temp_target) {
        $temp_skipif .= 's';
        $temp_file .= 's';
        $temp_clean .= 's';
        $copy_file = $temp_dir . DIRECTORY_SEPARATOR . basename(is_array($file) ? $file[1] : $file) . '.phps';
        if (!is_dir(dirname($copy_file))) {
            mkdir(dirname($copy_file), 0777, true) or error("Cannot create output directory - " . dirname($copy_file));
        }
        if (isset($section_text['FILE'])) {
            save_text($copy_file, $section_text['FILE']);
        }
        $temp_filenames = array('file' => $copy_file, 'diff' => $diff_filename, 'log' => $log_filename, 'exp' => $exp_filename, 'out' => $output_filename, 'mem' => $memcheck_filename, 'php' => $temp_file, 'skip' => $temp_skipif, 'clean' => $temp_clean);
    }
    if (is_array($IN_REDIRECT)) {
        $tested = $IN_REDIRECT['prefix'] . ' ' . trim($section_text['TEST']);
        $tested_file = $tmp_relative_file;
        $section_text['FILE'] = "# original source file: {$shortname}\n" . $section_text['FILE'];
    }
    // unlink old test results
    @unlink($diff_filename);
    @unlink($log_filename);
    @unlink($exp_filename);
    @unlink($output_filename);
    @unlink($memcheck_filename);
    @unlink($temp_file);
    @unlink($test_file);
    @unlink($temp_skipif);
    @unlink($test_skipif);
    @unlink($tmp_post);
    @unlink($temp_clean);
    @unlink($test_clean);
    // Reset environment from any previous test.
    $env['REDIRECT_STATUS'] = '';
    $env['QUERY_STRING'] = '';
    $env['PATH_TRANSLATED'] = '';
    $env['SCRIPT_FILENAME'] = '';
    $env['REQUEST_METHOD'] = '';
    $env['CONTENT_TYPE'] = '';
    $env['CONTENT_LENGTH'] = '';
    if (!empty($section_text['ENV'])) {
        foreach (explode("\n", trim($section_text['ENV'])) as $e) {
            $e = explode('=', trim($e), 2);
            if (!empty($e[0]) && isset($e[1])) {
                $env[$e[0]] = $e[1];
            }
        }
    }
    // Default ini settings
    $ini_settings = array();
    // additional ini overwrites
    //$ini_overwrites[] = 'setting=value';
    settings2array($ini_overwrites, $ini_settings);
    // Any special ini settings
    // these may overwrite the test defaults...
    if (array_key_exists('INI', $section_text)) {
        if (strpos($section_text['INI'], '{PWD}') !== false) {
            $section_text['INI'] = str_replace('{PWD}', dirname($file), $section_text['INI']);
        }
        settings2array(preg_split("/[\n\r]+/", $section_text['INI']), $ini_settings);
    }
    settings2params($ini_settings);
    // Check if test should be skipped.
    $info = '';
    $warn = false;
    if (array_key_exists('SKIPIF', $section_text)) {
        if (trim($section_text['SKIPIF'])) {
            show_file_block('skip', $section_text['SKIPIF']);
            save_text($test_skipif, $section_text['SKIPIF'], $temp_skipif);
            $extra = substr(PHP_OS, 0, 3) !== "WIN" ? "unset REQUEST_METHOD; unset QUERY_STRING; unset PATH_TRANSLATED; unset SCRIPT_FILENAME; unset REQUEST_METHOD;" : "";
            if ($leak_check) {
                $env['USE_ZEND_ALLOC'] = '0';
            } else {
                $env['USE_ZEND_ALLOC'] = '1';
            }
            $output = system_with_timeout("{$extra} {$php} {$pass_options} -q {$ini_settings} {$test_skipif}", $env);
            if (!$cfg['keep']['skip']) {
                @unlink($test_skipif);
            }
            if (!strncasecmp('skip', ltrim($output), 4)) {
                if (preg_match('/^\\s*skip\\s*(.+)\\s*/i', $output, $m)) {
                    show_result('SKIP', $tested, $tested_file, "reason: {$m['1']}", $temp_filenames);
                } else {
                    show_result('SKIP', $tested, $tested_file, '', $temp_filenames);
                }
                if (isset($old_php)) {
                    $php = $old_php;
                }
                if (!$cfg['keep']['skip']) {
                    @unlink($test_skipif);
                }
                return 'SKIPPED';
            }
            if (!strncasecmp('info', ltrim($output), 4)) {
                if (preg_match('/^\\s*info\\s*(.+)\\s*/i', $output, $m)) {
                    $info = " (info: {$m['1']})";
                }
            }
            if (!strncasecmp('warn', ltrim($output), 4)) {
                if (preg_match('/^\\s*warn\\s*(.+)\\s*/i', $output, $m)) {
                    $warn = true;
                    /* only if there is a reason */
                    $info = " (warn: {$m['1']})";
                }
            }
        }
    }
    if (@count($section_text['REDIRECTTEST']) == 1) {
        $test_files = array();
        $IN_REDIRECT = eval($section_text['REDIRECTTEST']);
        $IN_REDIRECT['via'] = "via [{$shortname}]\n\t";
        $IN_REDIRECT['dir'] = realpath(dirname($file));
        $IN_REDIRECT['prefix'] = trim($section_text['TEST']);
        if (count($IN_REDIRECT['TESTS']) == 1) {
            if (is_array($org_file)) {
                $test_files[] = $org_file[1];
            } else {
                $GLOBALS['test_files'] = $test_files;
                find_files($IN_REDIRECT['TESTS']);
                foreach ($GLOBALS['test_files'] as $f) {
                    $test_files[] = array($f, $file);
                }
            }
            $test_cnt += @count($test_files) - 1;
            $test_idx--;
            show_redirect_start($IN_REDIRECT['TESTS'], $tested, $tested_file);
            // set up environment
            $redirenv = array_merge($environment, $IN_REDIRECT['ENV']);
            $redirenv['REDIR_TEST_DIR'] = realpath($IN_REDIRECT['TESTS']) . DIRECTORY_SEPARATOR;
            usort($test_files, "test_sort");
            run_all_tests($test_files, $redirenv, $tested);
            show_redirect_ends($IN_REDIRECT['TESTS'], $tested, $tested_file);
            // a redirected test never fails
            $IN_REDIRECT = false;
            return 'REDIR';
        } else {
            $bork_info = "Redirect info must contain exactly one TEST string to be used as redirect directory.";
            show_result("BORK", $bork_info, '', $temp_filenames);
            $PHP_FAILED_TESTS['BORKED'][] = array('name' => $file, 'test_name' => '', 'output' => '', 'diff' => '', 'info' => "{$bork_info} [{$file}]");
        }
    }
    if (is_array($org_file) || @count($section_text['REDIRECTTEST']) == 1) {
        if (is_array($org_file)) {
            $file = $org_file[0];
        }
        $bork_info = "Redirected test did not contain redirection info";
        show_result("BORK", $bork_info, '', $temp_filenames);
        $PHP_FAILED_TESTS['BORKED'][] = array('name' => $file, 'test_name' => '', 'output' => '', 'diff' => '', 'info' => "{$bork_info} [{$file}]");
        return 'BORKED';
    }
    // We've satisfied the preconditions - run the test!
    show_file_block('php', $section_text['FILE'], 'TEST');
    save_text($test_file, $section_text['FILE'], $temp_file);
    if (array_key_exists('GET', $section_text)) {
        $query_string = trim($section_text['GET']);
    } else {
        $query_string = '';
    }
    $env['REDIRECT_STATUS'] = '1';
    $env['QUERY_STRING'] = $query_string;
    $env['PATH_TRANSLATED'] = $test_file;
    $env['SCRIPT_FILENAME'] = $test_file;
    if (array_key_exists('COOKIE', $section_text)) {
        $env['HTTP_COOKIE'] = trim($section_text['COOKIE']);
    } else {
        $env['HTTP_COOKIE'] = '';
    }
    $args = isset($section_text['ARGS']) ? ' -- ' . $section_text['ARGS'] : '';
    if (array_key_exists('POST_RAW', $section_text) && !empty($section_text['POST_RAW'])) {
        $post = trim($section_text['POST_RAW']);
        $raw_lines = explode("\n", $post);
        $request = '';
        $started = false;
        foreach ($raw_lines as $line) {
            if (empty($env['CONTENT_TYPE']) && preg_match('/^Content-Type:(.*)/i', $line, $res)) {
                $env['CONTENT_TYPE'] = trim(str_replace("\r", '', $res[1]));
                continue;
            }
            if ($started) {
                $request .= "\n";
            }
            $started = true;
            $request .= $line;
        }
        $env['CONTENT_LENGTH'] = strlen($request);
        $env['REQUEST_METHOD'] = 'POST';
        if (empty($request)) {
            return 'BORKED';
        }
        save_text($tmp_post, $request);
        $cmd = "{$php} {$pass_options} {$ini_settings} -f \"{$test_file}\" 2>&1 < {$tmp_post}";
    } else {
        if (array_key_exists('POST', $section_text) && !empty($section_text['POST'])) {
            $post = trim($section_text['POST']);
            if (array_key_exists('GZIP_POST', $section_text) && function_exists('gzencode')) {
                $post = gzencode($post, 9, FORCE_GZIP);
                $env['HTTP_CONTENT_ENCODING'] = 'gzip';
            } else {
                if (array_key_exists('DEFLATE_POST', $section_text) && function_exists('gzcompress')) {
                    $post = gzcompress($post, 9);
                    $env['HTTP_CONTENT_ENCODING'] = 'deflate';
                }
            }
            save_text($tmp_post, $post);
            $content_length = strlen($post);
            $env['REQUEST_METHOD'] = 'POST';
            $env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
            $env['CONTENT_LENGTH'] = $content_length;
            $cmd = "{$php} {$pass_options} {$ini_settings} -f \"{$test_file}\" 2>&1 < {$tmp_post}";
        } else {
            $env['REQUEST_METHOD'] = 'GET';
            $env['CONTENT_TYPE'] = '';
            $env['CONTENT_LENGTH'] = '';
            $cmd = "{$php} {$pass_options} {$ini_settings} -f \"{$test_file}\" {$args} 2>&1";
        }
    }
    if ($leak_check) {
        $env['USE_ZEND_ALLOC'] = '0';
        if ($valgrind_version >= 330) {
            /* valgrind 3.3.0+ doesn't have --log-file-exactly option */
            $cmd = "valgrind -q --tool=memcheck --trace-children=yes --log-file={$memcheck_filename} {$cmd}";
        } else {
            $cmd = "valgrind -q --tool=memcheck --trace-children=yes --log-file-exactly={$memcheck_filename} {$cmd}";
        }
    } else {
        $env['USE_ZEND_ALLOC'] = '1';
    }
    if ($DETAILED) {
        echo "\nCONTENT_LENGTH  = " . $env['CONTENT_LENGTH'] . "\nCONTENT_TYPE    = " . $env['CONTENT_TYPE'] . "\nPATH_TRANSLATED = " . $env['PATH_TRANSLATED'] . "\nQUERY_STRING    = " . $env['QUERY_STRING'] . "\nREDIRECT_STATUS = " . $env['REDIRECT_STATUS'] . "\nREQUEST_METHOD  = " . $env['REQUEST_METHOD'] . "\nSCRIPT_FILENAME = " . $env['SCRIPT_FILENAME'] . "\nHTTP_COOKIE     = " . $env['HTTP_COOKIE'] . "\nCOMMAND {$cmd}\n";
    }
    $out = system_with_timeout($cmd, $env, isset($section_text['STDIN']) ? $section_text['STDIN'] : null);
    if (array_key_exists('CLEAN', $section_text) && (!$no_clean || $cfg['keep']['clean'])) {
        if (trim($section_text['CLEAN'])) {
            show_file_block('clean', $section_text['CLEAN']);
            save_text($test_clean, trim($section_text['CLEAN']), $temp_clean);
            if (!$no_clean) {
                $clean_params = array();
                settings2array($ini_overwrites, $clean_params);
                settings2params($clean_params);
                $extra = substr(PHP_OS, 0, 3) !== "WIN" ? "unset REQUEST_METHOD; unset QUERY_STRING; unset PATH_TRANSLATED; unset SCRIPT_FILENAME; unset REQUEST_METHOD;" : "";
                system_with_timeout("{$extra} {$php} {$pass_options} -q {$clean_params} {$test_clean}", $env);
            }
            if (!$cfg['keep']['clean']) {
                @unlink($test_clean);
            }
        }
    }
    @unlink($tmp_post);
    $leaked = false;
    $passed = false;
    if ($leak_check) {
        // leak check
        $leaked = filesize($memcheck_filename) > 0;
        if (!$leaked) {
            @unlink($memcheck_filename);
        }
    }
    // Does the output match what is expected?
    $output = preg_replace("/\r\n/", "\n", trim($out));
    /* when using CGI, strip the headers from the output */
    $headers = "";
    if (isset($old_php) && preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $out, $match)) {
        $output = trim($match[2]);
        $rh = preg_split("/[\n\r]+/", $match[1]);
        $headers = array();
        foreach ($rh as $line) {
            if (strpos($line, ':') !== false) {
                $line = explode(':', $line, 2);
                $headers[trim($line[0])] = trim($line[1]);
            }
        }
    }
    $failed_headers = false;
    if (isset($section_text['EXPECTHEADERS'])) {
        $want = array();
        $wanted_headers = array();
        $lines = preg_split("/[\n\r]+/", $section_text['EXPECTHEADERS']);
        foreach ($lines as $line) {
            if (strpos($line, ':') !== false) {
                $line = explode(':', $line, 2);
                $want[trim($line[0])] = trim($line[1]);
                $wanted_headers[] = trim($line[0]) . ': ' . trim($line[1]);
            }
        }
        $org_headers = $headers;
        $headers = array();
        $output_headers = array();
        foreach ($want as $k => $v) {
            if (isset($org_headers[$k])) {
                $headers = $org_headers[$k];
                $output_headers[] = $k . ': ' . $org_headers[$k];
            }
            if (!isset($org_headers[$k]) || $org_headers[$k] != $v) {
                $failed_headers = true;
            }
        }
        ksort($wanted_headers);
        $wanted_headers = join("\n", $wanted_headers);
        ksort($output_headers);
        $output_headers = join("\n", $output_headers);
    }
    show_file_block('out', $output);
    if (isset($section_text['EXPECTF']) || isset($section_text['EXPECTREGEX'])) {
        if (isset($section_text['EXPECTF'])) {
            $wanted = trim($section_text['EXPECTF']);
        } else {
            $wanted = trim($section_text['EXPECTREGEX']);
        }
        show_file_block('exp', $wanted);
        $wanted_re = preg_replace('/\\r\\n/', "\n", $wanted);
        if (isset($section_text['EXPECTF'])) {
            $wanted_re = preg_quote($wanted_re, '/');
            $wanted_re = str_replace(array('%unicode_string_optional%'), version_compare(PHP_VERSION, '6.0.0-dev') == -1 ? 'string' : 'Unicode string', $wanted_re);
            $wanted_re = str_replace(array('%unicode\\|string%', '%string\\|unicode%'), version_compare(PHP_VERSION, '6.0.0-dev') == -1 ? 'string' : 'unicode', $wanted_re);
            $wanted_re = str_replace(array('%u\\|b%', '%b\\|u%'), version_compare(PHP_VERSION, '6.0.0-dev') == -1 ? '' : 'u', $wanted_re);
            // Stick to basics
            $wanted_re = str_replace('%e', '\\' . DIRECTORY_SEPARATOR, $wanted_re);
            $wanted_re = str_replace('%s', '[^\\r\\n]+', $wanted_re);
            $wanted_re = str_replace('%a', '.+', $wanted_re);
            $wanted_re = str_replace('%w', '\\s*', $wanted_re);
            $wanted_re = str_replace('%i', '[+-]?\\d+', $wanted_re);
            $wanted_re = str_replace('%d', '\\d+', $wanted_re);
            $wanted_re = str_replace('%x', '[0-9a-fA-F]+', $wanted_re);
            $wanted_re = str_replace('%f', '[+-]?\\.?\\d+\\.?\\d*(?:[Ee][+-]?\\d+)?', $wanted_re);
            $wanted_re = str_replace('%c', '.', $wanted_re);
            // %f allows two points "-.0.0" but that is the best *simple* expression
        }
        /* DEBUG YOUR REGEX HERE
        		var_dump($wanted_re);
        		print(str_repeat('=', 80) . "\n");
        		var_dump($output);
        */
        if (preg_match((string) "/^{$wanted_re}\$/s", $output)) {
            $passed = true;
            if (!$cfg['keep']['php']) {
                @unlink($test_file);
            }
            if (isset($old_php)) {
                $php = $old_php;
            }
            if (!$leaked && !$failed_headers) {
                show_result("PASS", $tested, $tested_file, '', $temp_filenames);
                return 'PASSED';
            }
        }
    } else {
        $wanted = trim($section_text['EXPECT']);
        $wanted = preg_replace('/\\r\\n/', "\n", $wanted);
        show_file_block('exp', $wanted);
        // compare and leave on success
        if (!strcmp($output, $wanted)) {
            $passed = true;
            if (!$cfg['keep']['php']) {
                @unlink($test_file);
            }
            if (isset($old_php)) {
                $php = $old_php;
            }
            if (!$leaked && !$failed_headers) {
                show_result("PASS", $tested, $tested_file, '', $temp_filenames);
                return 'PASSED';
            }
        }
        $wanted_re = null;
    }
    // Test failed so we need to report details.
    if ($failed_headers) {
        $passed = false;
        $wanted = $wanted_headers . "\n--HEADERS--\n" . $wanted;
        $output = $output_headers . "\n--HEADERS--\n" . $output;
        if (isset($wanted_re)) {
            $wanted_re = preg_quote($wanted_headers . "\n--HEADERS--\n", '/') . $wanted_re;
        }
    }
    if ($leaked) {
        $restype[] = 'LEAK';
    }
    if ($warn) {
        $restype[] = 'WARN';
    }
    if (!$passed) {
        if (isset($section_text['XFAIL'])) {
            $restype[] = 'XFAIL';
        } else {
            $restype[] = 'FAIL';
        }
    }
    if (!$passed) {
        // write .exp
        if (strpos($log_format, 'E') !== false && file_put_contents($exp_filename, (string) $wanted, FILE_BINARY) === false) {
            error("Cannot create expected test output - {$exp_filename}");
        }
        // write .out
        if (strpos($log_format, 'O') !== false && file_put_contents($output_filename, (string) $output, FILE_BINARY) === false) {
            error("Cannot create test output - {$output_filename}");
        }
        // write .diff
        $diff = generate_diff($wanted, $wanted_re, $output);
        show_file_block('diff', $diff);
        if (strpos($log_format, 'D') !== false && file_put_contents($diff_filename, (string) $diff, FILE_BINARY) === false) {
            error("Cannot create test diff - {$diff_filename}");
        }
        // write .log
        if (strpos($log_format, 'L') !== false && file_put_contents($log_filename, "\n---- EXPECTED OUTPUT\n{$wanted}\n---- ACTUAL OUTPUT\n{$output}\n---- FAILED\n", FILE_BINARY) === false) {
            error("Cannot create test log - {$log_filename}");
            error_report($file, $log_filename, $tested);
        }
    }
    show_result(implode('&', $restype), $tested, $tested_file, $info, $temp_filenames);
    foreach ($restype as $type) {
        $PHP_FAILED_TESTS[$type . 'ED'][] = array('name' => $file, 'test_name' => (is_array($IN_REDIRECT) ? $IN_REDIRECT['via'] : '') . $tested . " [{$tested_file}]", 'output' => $output_filename, 'diff' => $diff_filename, 'info' => $info);
    }
    if (isset($old_php)) {
        $php = $old_php;
    }
    return $restype[0] . 'ED';
}
示例#16
0
文件: ajax.php 项目: philum/cms
<?php

//philum_ajax_hangar
session_start();
error_report();
$_SESSION['onload'] = '';
if (!$_SESSION['stime']) {
    req('boot,art,spe');
    master_params('params/_' . $db, $qd, $aqb, $subd);
    define_hubs();
    define_qb();
    define_config();
    time_system($cache);
    cache_arts();
    define_cats_rqt();
    define_condition();
    define_clr();
}
if (!$_SESSION['picto']) {
    $_SESSION['picto'] = msql_read('system', 'edition_pictos', '', 1);
}
$res = $_GET['res'];
if (substr($res, -1) == '_') {
    $res = substr($res, 0, -1);
}
list($n, $id, $va, $opt, $optb) = ajxr($_GET['callj']);
$sz = $_GET['sz'];
$pp = $_GET['popup'];
$ar = array('plug' => 1, 'plup' => 1, 'plugin' => 1, 'plupin' => 1, 'titsav' => 1, 'popbub' => 1, 'call' => 1, 'callp' => 1);
if (!$ar[$n]) {
    require_once 'prog' . $b . '/ajxf.php';
示例#17
0
function add_signin_log($account, $accepted, $time, $ip)
{
    $sql = 'INSERT INTO `signin_log`(`account`, `accepted`, `time`, `ip`)    VALUES(?, ?, ?, ?)';
    $params = array($account, $accepted, $time, $ip);
    $cnt = (new MysqlDAO())->execute($sql, $params, 'ssii');
    if ($cnt != 1) {
        error_report('store sign in log error');
    }
    return;
}
示例#18
0
function award_microbadges_and_send_confirmations()
{
    global $config;
    $how_many_to_send = $config['bgg']['max_award_geekmails_rate_per_hour'];
    # This is a little tricky. We don't need to send a geemail to the
    # recipients, since that will get sent by the microbadge awarding in BGG. We
    # will send a geekmail to the givers, but really only a single geekmail to
    # many recipients. Howerver, because I don't want this script going crazy,
    # I'll just use the configuration value to limit how many awards are given
    # out.
    $reqs = db_get_award_requests($how_many_to_send);
    if (count($reqs) == 0) {
        print "No reqs\n";
        return TRUE;
    }
    $result = bgg_login();
    if ($result === FALSE) {
        error_report("Error logging into BGG.");
        exit;
    }
    # I don't want to bulk-award the microbadges. It will make it hard to refund
    # awards, or handle re-try. (For example, a user might accidentaly get a
    # 4-star before getting a 3-star).
    #
    # So we'll just award them to each recipient, one at a time.
    #
    $givers = array();
    foreach ($reqs as $req) {
        echo "REQ: recipient=" . $req['recipient'] . " id=" . $req['id'] . "\n";
        $user = bgg_get_profile($req['recipient']);
        if ($user === FALSE || $user['result'] === FALSE) {
            error_report("Error fetching profile of '" . $req['recipient'] . "' while awarding a microbage (req ID " . $req['id'] . ")");
            continue;
        }
        # Does the recipient already have 5 stars?
        $has_stars = array_reduce($user['stars'], "array_counter", 0);
        if ($has_stars >= 5) {
            # Refund the current request
            error_report("Warning: The user \"" . $req['recipient'] . "\" already has five stars, so the request with ID " . $req['id'] . " will be refunded to " . $req['giver_username']);
            $result = award_refund($req['id']);
            if ($result === FALSE) {
                error_report("Warning: The award could not be refunded. It will be " . "checked again later. Unless these are eventually refunded or " . "deleted, they will accumulate and clog up the award queue.");
            }
            continue;
        }
        $mb_id = $bgg_mb_stars[$has_stars];
        # Award the microbadge
        $result = bgg_award_microbadge_bulk($mb_id, $req['recipient'], $config['bgg']['mb_award_msg_template']);
        if ($result === FALSE || $result['result'] === FALSE) {
            error_report("Error while awarding microbadge for award ID " . $req['id']);
            continue;
        }
        # Mark as awarded
        db_award_set_awarded($req['id']);
        # Add the giver to the list of givers who will recieve confirmation of award.
        # Both for later geekmailing.
        array_push($givers, $req['giver_username']);
        # Sleep for a bit, to give the BGG database time to update the user's profile
        usleep(300 * 1000);
        # Verify it was received, in the recpient profile
        $user = bgg_get_profile($req['recipient']);
        if ($user === FALSE || $user['result'] === FALSE) {
            error_report("Error verifying whether award ID " . $req['id'] . " was awarded.");
        } else {
            if ($user['stars'][$has_stars - 1]) {
                # Mark as verified
                if (!db_award_set_verified($req['id'])) {
                    error_report("Error marking award ID " . $req['id'] . " as verified.");
                }
            } else {
                error_report("Warning: The star hasn't appeared yet, " . "(request ID={$id}, star={$has_stars}) so it will not be marked as verified.");
            }
        }
    }
    # Send a mass-mail to all the givers, notifying them the microbadge has been awarded
    $to_givers = implode(',', $givers);
    geekmail_send($to_givers, $config['bgg']['giver_confirmation_msg_subject'], $config['bgg']['giver_confirmation_msg_body']);
    return TRUE;
}
示例#19
0
<?php

if (!defined('PHPHOTPIC')) {
    exit('Access Denied');
}
$base['get']['id'] = intval($base['get']['id']);
$image = $db->first("SELECT * FROM {$base['config']['db']['pre']}images WHERE id={$base['get']['id']} LIMIT 1");
if (!$image) {
    error_report($base['lang']['image_not_exist']);
}
$db->query("UPDATE {$base['config']['db']['pre']}images SET views=views+1 WHERE id={$base['get']['id']} LIMIT 1");
$base['title'] = 'Show image ' . $image['originalname'];
$size = getimagesize($base['dir'] . '/i/' . $image['filename'] . $image['extension']);
$sizew = $size[0];
$other = "";
if ($sizew > 800) {
    $sizeh = ceil($size[1] * 800 / $sizew);
    $other = " width='800' height='{$sizeh}'";
}
$base['imagename'] = $image['originalname'];
$base['imageviews'] = $image['views'] + 1;
$base['imagedate'] = convertdate($image['time']);
$base['show'] = '<img src="' . $base['config']['url'] . '/i/' . $image['filename'] . $image['extension'] . '" alt="' . htmlspecialchars($image['originalname']) . '"' . $other . ' />';
$base['isthumb'] = $image['isthumb'];
$base['direct_url1'] = getlink('show', array($image['id'], '&amp;'));
$base['direct_url2'] = $base['config']['url'] . '/i/' . $image['filename'] . $image['extension'];
$base['bb_full'] = '[url=' . getlink('show', array($image['id'], '&amp;')) . '][img]' . $base['config']['url'] . '/i/' . $image['filename'] . $image['extension'] . '[/img][/url]';
$base['bb_thumb'] = '[url=' . getlink('show', array($image['id'], '&amp;')) . '][img]' . $base['config']['url'] . '/i/' . $image['filename'] . '.th' . $image['extension'] . '[/img][/url]';
$base['html_full'] = '&lt;a href=&quot;' . getlink('show', array($image['id'], '&amp;')) . '&quot; target=&quot;_blank&quot;&gt;&lt;img src=&quot;' . $base['config']['url'] . '/i/' . $image['filename'] . $image['extension'] . '&quot; alt=&quot;Host by ' . $_SERVER['HTTP_HOST'] . '&quot; /&gt;&lt;/a&gt;';
$base['html_thumb'] = '&lt;a href=&quot;' . getlink('show', array($image['id'], '&amp;')) . '&quot; target=&quot;_blank&quot;&gt;&lt;img src=&quot;' . $base['config']['url'] . '/i/' . $image['filename'] . '.th' . $image['extension'] . '&quot; alt=&quot;Host by ' . $_SERVER['HTTP_HOST'] . '&quot; /&gt;&lt;/a&gt;';
unset($image);
示例#20
0
require_once $base['dir'] . 'data/config.php';
require_once $base['dir'] . 'source/core.func.php';
require_once $base['dir'] . 'source/mysqldb.class.php';
$base['post'] = paddslashes($_POST);
$base['get'] = paddslashes($_GET);
$base['cookie'] = paddslashes($_COOKIE);
unset($_POST);
unset($_GET);
unset($_COOKIE);
$langset = $base['cookie']['lang'] ? $base['cookie']['lang'] : $config['lang'];
require_once $base['dir'] . 'lang/langset.php';
$langset = in_array($langset, array_keys($all_lang)) ? $langset : $base['cookie']['lang'];
require_once $base['dir'] . 'lang/' . $langset . '/all.lang.php';
$base['lang'] = $lang;
unset($lang);
$base['config'] = $config;
unset($config);
$db = new mysql_database();
if (!$db->connect($base['config']['db'])) {
    error_report($base['lang']['db_connect_error']);
}
if ($base['get']['mod'] == '') {
    $base['get']['mod'] = 'index';
}
if (!empty($_FILES)) {
    $base['get']['mod'] = 'upload';
}
if (!in_array($base['get']['mod'], array('index', 'upload', 'show', 'admin'))) {
    error_report(str_replace('\\1', '<code>' . htmlspecialchars($base['get']['mod']) . '</code>', $base['lang']['mod_not_found']));
}
require_once $base['dir'] . 'source/' . $base['get']['mod'] . '.mod.php';
function get_comments_of_cat($cat_id)
{
    global $config_vars, $db;
    // makes this to the first comment of content $content_id
    $sql = 'SELECT * FROM ' . $config_vars['table_prefix'] . 'cat_comments
		WHERE (owner_id = ' . $cat_id . ') and (parent_id = 0) ORDER BY creation_date';
    if (!($result = $db->sql_query($sql))) {
        error_report(SQL_ERROR, 'get_comments', __LINE__, __FILE__, $sql);
    }
    while ($row = $db->sql_fetchrow($result)) {
        $com = new cat_comment();
        $com->generate_from_row($row);
        $com_array[] = $com;
    }
    return $com_array;
}
示例#22
0
文件: test.php 项目: luka8088/phops
function runUnitTests()
{
    $result = (object) array();
    $flushResult = function () use($result) {
        if (isset($_SERVER['unitTest_result'])) {
            file_put_contents($_SERVER['unitTest_result'], json_encode($result) . "\n");
        }
    };
    $flushResult();
    $timestamp = microtime(true);
    echo 'Listing files ..';
    $files = array();
    $unitTest_excludePath = array();
    if (isset($_SERVER['unitTest_excludePath'])) {
        $addPaths = function ($paths) use(&$unitTest_excludePath, &$addPaths) {
            if (is_array($paths) || is_object($paths)) {
                foreach ($paths as $path) {
                    $addPaths($path);
                }
            } else {
                $unitTest_excludePath[] = rtrim(str_replace(array('\\', '/'), array('/', '/'), $paths), '/') . '/';
            }
        };
        $addPaths($_SERVER['unitTest_excludePath']);
    }
    $isExcluded = function ($file) use($unitTest_excludePath) {
        $sFile = str_replace(array('\\', '/'), array('/', '/'), $file);
        foreach ($unitTest_excludePath as $excludePath) {
            if (substr($sFile, 0, strlen($excludePath)) == $excludePath) {
                return true;
            }
        }
        return false;
    };
    foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($_SERVER['basePath'])) as $file) {
        if (microtime(true) > $timestamp + 1) {
            $timestamp = microtime(true);
            echo '.';
        }
        if ($isExcluded($file)) {
            continue;
        }
        if (in_array($file->getExtension(), array('php'))) {
            $fileContent = file_get_contents($file);
            if (preg_match('/(?si)function\\s*unittest/', $fileContent) == 0) {
                continue;
            }
            $files[] = $file;
        }
    }
    echo ' ' . count($files) . "\n";
    usort($files, function ($lhs, $rhs) {
        return filemtime($rhs) - filemtime($lhs);
    });
    echo 'Including files ..';
    $i = 0;
    // php include can overwrite variable values so we need to isolate include in a function
    $includeFile = function ($file) {
        ob_start();
        include_once (string) $file;
        ob_end_clean();
    };
    foreach ($files as $file) {
        if (microtime(true) > $timestamp + 1) {
            $timestamp = microtime(true);
            echo '.';
        }
        if (in_array(realpath($file), get_included_files())) {
            continue;
        }
        $i++;
        $includeFile($file);
    }
    echo ' ' . $i . "\n";
    $tests = array();
    echo 'Listing tests ..';
    $functions = get_defined_functions();
    foreach (array_merge($functions['internal'], $functions['user']) as $function) {
        if (microtime(true) > $timestamp + 1) {
            $timestamp = microtime(true);
            echo '.';
        }
        if (substr(strtolower($function), 0, 8) == 'unittest') {
            $tests[] = $function;
        }
    }
    foreach (get_declared_classes() as $class) {
        foreach (get_class_methods($class) as $method) {
            if (microtime(true) > $timestamp + 1) {
                $timestamp = microtime(true);
                echo '.';
            }
            $reflector = new ReflectionMethod($class, $method);
            if ($reflector->getDeclaringClass()->getName() != $class) {
                continue;
            }
            if (substr(strtolower($method), 0, 8) == 'unittest' && !in_array("{$class}::{$method}", array('unitTest_webBrowser::unitTestElement', 'unitTest_element::unitTestElement', 'unitTest_webContext::unitTestElement', 'unitTest_webBrowser::unitTestElements', 'unitTest_element::unitTestElements', 'unitTest_webContext::unitTestElements'))) {
                $tests[] = array($class, $method);
            }
        }
    }
    echo ' ' . count($tests) . "\n";
    $result->tests = (object) array('count' => count($tests), 'all' => array(), 'successes' => array(), 'failures' => array(), 'errors' => array());
    usort($tests, function ($lhs, $rhs) {
        $lhsReflection = is_string($lhs) ? new ReflectionFunction($lhs) : new ReflectionMethod($lhs[0], $lhs[1]);
        $rhsReflection = is_string($rhs) ? new ReflectionFunction($rhs) : new ReflectionMethod($rhs[0], $rhs[1]);
        return filemtime($rhsReflection->getFileName()) - filemtime($lhsReflection->getFileName());
    });
    echo "\nRunning " . count($tests) . " tests:\n";
    foreach ($tests as $key => $test) {
        $id = (is_string($test) ? $test : $test[0] . '::' . $test[1]) . '()';
        $result->tests->all[$id] = (object) array('status' => 'unknown');
    }
    $flushResult();
    do {
        $unhandledCount = count($tests);
        foreach ($tests as $key => $test) {
            $id = (is_string($test) ? $test : $test[0] . '::' . $test[1]) . '()';
            echo '  ' . $id;
            try {
                call_user_func($test);
                echo ": success";
                $result->tests->all[$id]->status = 'success';
                $result->tests->successes[] = $id;
                isUnitTestRun($test, true);
            } catch (unitTestRequiredException $e) {
                echo ": delayed";
                $tests[] = $test;
            } catch (unitTestEnvironmentException $e) {
                echo ": error";
                $result->tests->all[$id]->status = 'error';
                $result->tests->all[$id]->report = error_report($e);
                $result->tests->all[$id]->message = $e->getMessage();
                $result->tests->all[$id]->trace = (string) $e;
                $result->tests->errors[] = $id;
                isUnitTestRun($test, false);
            } catch (Exception $e) {
                echo ": failure - " . $e->getMessage();
                $result->tests->all[$id]->status = 'failure';
                $result->tests->all[$id]->report = error_report($e);
                $result->tests->all[$id]->message = $e->getMessage();
                $result->tests->all[$id]->trace = (string) $e;
                $result->tests->failures[] = $id;
                isUnitTestRun($test, false);
            }
            unset($tests[$key]);
            echo "\n";
            $flushResult();
        }
    } while (count($tests) > 0 && count($tests) < $unhandledCount);
    $flushResult();
    echo "\nResults: \n";
    echo "  Total:   " . $result->tests->count . "\n";
    echo "  Success: " . count($result->tests->successes) . "\n";
    echo "  Failure: " . count($result->tests->failures) . "\n";
    echo "  Errors:  " . count($result->tests->errors) . "\n";
    if (count($result->tests->successes) != $result->tests->count) {
        echo "\nTests completed with failures, errors or skipped tests !\n\n";
    } else {
        echo "\nEverything completed successfully !\n\n";
    }
    echo "Done\n";
}
示例#23
0
// get all usergroups
$sql = 'SELECT id,name FROM ' . $config_vars['table_prefix'] . 'usergroups';
if (!($result = $db->sql_query($sql))) {
    error_report(SQL_ERROR, 'get_usergroups_of_user', __LINE__, __FILE__, $sql);
}
while ($row = $db->sql_fetchrow($result)) {
    $usergroups[] = $row;
}
// get all groups
if ($type == 'usergroup') {
    $sql = 'SELECT id,name FROM ' . $config_vars['table_prefix'] . 'usergroups';
} else {
    $sql = 'SELECT id,name FROM ' . $config_vars['table_prefix'] . 'groups';
}
if (!($result = $db->sql_query($sql))) {
    error_report(SQL_ERROR, 'get_groups_of_user', __LINE__, __FILE__, $sql);
}
while ($row = $db->sql_fetchrow($result)) {
    $groups[] = $row;
}
$sql = 'SELECT usergroup_id,' . $type . 'group_id FROM ' . $config_vars['table_prefix'] . $type . "_auth where (usergroup_id = {$usergroup}) and (" . $type . "group_id = {$group})";
if (!($result = $db->sql_query($sql))) {
    message_die(GENERAL_ERROR, "Could not get groups of user", '', __LINE__, __FILE__, $sql);
}
if ($row = $db->sql_fetchrow($result)) {
    $smarty->assign('auth_exists', true);
    $auth = new $class();
    $auth->generate($row['usergroup_id'], $row[$type . 'group_id']);
    // automaticly get all vars of the class and fill the the checkboxes if set
    foreach ($auth->processing_vars as $value) {
        $get_func = "get_{$value}";
示例#24
0
$smarty->assign('viewable_total_cats', sprintf($lang['viewable_total_cats'], $child_cats_viewable_amount, $child_cats_total_amount));
if (isset($HTTP_POST_VARS['edit_cat'])) {
    for ($i = 0; $i < sizeof($child_cats); $i++) {
        $child_cats[$i]->set_name($HTTP_POST_VARS['cat_name'][$i]);
        $child_cats[$i]->set_description($HTTP_POST_VARS['cat_description'][$i]);
        $child_cats[$i]->set_catgroup_id($HTTP_POST_VARS['cat_catgroup'][$i], $HTTP_POST_VARS['cat_apply_recursive'][$i]);
        $child_cats[$i]->set_parent_id($HTTP_POST_VARS['cat_parent_cat'][$i]);
        if ($HTTP_POST_VARS['cat_delete'][$i] == 'on') {
            $error = $child_cats[$i]->delete('CDM_REMOVE_CONTENT');
            if ($error != OP_SUCCESSFUL) {
                error_report(GENERAL_ERROR, 'del_cat', __LINE__, __FILE__, $error);
            }
        } else {
            $error = $child_cats[$i]->commit();
            if ($error != OP_SUCCESSFUL) {
                error_report(GENERAL_ERROR, 'cat_commit', __LINE__, __FILE__, $error);
            }
        }
    }
    $child_cats = get_cats_of_cat($HTTP_GET_VARS['cat_id']);
}
//Get the contents of the actual cat and their thumbnails plus information like
$category = new categorie();
$category->generate_from_id($HTTP_GET_VARS['cat_id']);
if (isset($child_cats)) {
    for ($i = 0; $i < sizeof($child_cats); $i++) {
        $child_cat_infos[$i]['id'] = $child_cats[$i]->get_id();
        $child_cat_infos[$i]['parent_id'] = $child_cats[$i]->get_parent_id();
        $child_cat_infos[$i]['name'] = htmlspecialchars($child_cats[$i]->get_name());
        $child_cat_infos[$i]['description'] = htmlspecialchars($child_cats[$i]->get_description());
        $child_cat_infos[$i]['content_amount'] = $child_cats[$i]->get_content_amount();
示例#25
0
function serverInterface_error_report($a)
{
    if (G()->SET['error_report']['javascript']->v) {
        $a['error source'] = 'js';
        if (!isset($a['backtrace'])) {
            $a['backtrace'] = array();
        }
        error_report($a);
    }
}
function field_param($value, $tree)
{
    global $x, $y, $fields, $loops, $HTTP_SESSION_VARS, $HTTP_POST_VARS, $db;
    $field['name'] = $value->name;
    $field['type'] = $value->type;
    if (!isset($value->subsql)) {
        $field['descr'] = $value->descr;
        if (isset($value->displayed)) {
            $field['displayed'] = generate_values($value->displayed);
        } else {
            $field['displayed'] = generate_values($value->value);
        }
        $field['value'] = generate_values($value->value);
    } else {
        foreach ($tree->entities as $entitie) {
            if (get_class($entitie) == 'sql_subsql') {
                if ($entitie->name == $value->subsql) {
                    $sql = $entitie->sql;
                    if (!($result = $db->sql_query($sql))) {
                        error_report(SQL_ERROR, 'subsql', __LINE__, __FILE__, $sql);
                    }
                    while ($row = $db->sql_fetchrow($result)) {
                        $field['value'][] = $row[0];
                        $field['displayed'][] = $row[1];
                    }
                }
            }
        }
    }
    $field['loop'] = $loops;
    for ($x = 0; $x <= $HTTP_SESSION_VARS['lines'][$field['loop']]; $x++) {
        if (isset($HTTP_POST_VARS['returns'])) {
            if ($field['type'] == 'INPUT') {
                $field['value'] = $HTTP_POST_VARS['returns'][$value->name][$x];
            }
            if ($field['type'] == 'DROPDOWN') {
                foreach ($field['value'] as $key => $val) {
                    if ($val == $HTTP_POST_VARS['returns'][$value->name][$x]) {
                        $field['selected'] = $key;
                    }
                }
            }
        }
        $fields[$x][$y] = $field;
    }
}
示例#27
0
 function delete()
 {
     global $config_vars, $db;
     //delete all cat_auths related to this group
     $sql = "DELETE FROM " . $config_vars['table_prefix'] . "cat_auth WHERE (catgroup_id = {$this->id})";
     if (!($result = $db->sql_query($sql))) {
         error_report(SQL_ERROR, 'delete', __LINE__, __FILE__, $sql);
     }
     //delete all content_auths related to this group
     $sql = "DELETE FROM " . $config_vars['table_prefix'] . "content_auth WHERE (contentgroup_id = {$this->id})";
     if (!($result = $db->sql_query($sql))) {
         error_report(SQL_ERROR, 'delete', __LINE__, __FILE__, $sql);
     }
     //delete the group
     base_group::delete();
 }
示例#28
0
<?php

define("ROOT_PATH", '');
include_once ROOT_PATH . 'includes/common.inc.php';
include_once ROOT_PATH . 'includes/template.inc.php';
include_once ROOT_PATH . 'includes/functions.inc.php';
if ($HTTP_POST_VARS['user_basket_enable'] == 'on') {
    $HTTP_SESSION_VARS['basket_enable'] = true;
} else {
    $HTTP_SESSION_VARS['basket_enable'] = false;
}
if (isset($HTTP_POST_VARS['submit'])) {
    $userdata['phreakpic_basket_enable'] = $HTTP_SESSION_VARS['basket_enable'];
    $sql = "UPDATE {$table_prefix}users\n\t\tSET\n\t\t\tphreakpic_basket_enable = '{$userdata['phreakpic_basket_enable']}'\n\t\tWHERE user_id = {$userdata['user_id']}";
    if (!($result = $db->sql_query($sql))) {
        error_report(SQL_ERROR, 'commit', __LINE__, __FILE__, $sql);
    }
}
$HTTP_SESSION_VARS['basket_enable'] = $userdata['phreakpic_basket_enable'];
if ($HTTP_SESSION_VARS['basket_enable']) {
    $smarty->assign('basket_enable', 'checked');
}
$nav_content['name'] = $lang['profile'];
$nav_string[] = $nav_content;
$smarty->assign('nav_string', $nav_string);
$smarty->display($userdata['photo_user_template'] . '/profile.tpl');
示例#29
0
function form_processing()
{
    if (!empty($_POST)) {
        $processed_errors = error_processing();
        error_report($processed_errors);
    }
}
示例#30
0
 function query($query)
 {
     $this->query_return = @mysql_query($query, $this->link) or die(error_report(mysql_error(), 'Database Error'));
 }