Example #1
0
function xhprof_shutdown()
{
    global $xhprofMainConfig;
    $xhprof_data = xhprof_disable();
    if (function_exists('fastcgi_finish_request')) {
        fastcgi_finish_request();
    }
    try {
        require_once __DIR__ . '/../xhprof/classes/data.php';
        $xhprof_data_obj = new \ay\xhprof\Data($xhprofMainConfig['pdo']);
        $xhprof_data_obj->save($xhprof_data);
    } catch (Exception $e) {
        // old php versions don't like Exceptions in shutdown functions
        // -> log them to have some usefull info in the php-log
        if (PHP_VERSION_ID < 504000) {
            if (function_exists('log_exception')) {
                log_exception($e);
            } else {
                error_log($e->__toString());
            }
        }
        // re-throw to show the caller something went wrong
        throw $e;
    }
}
Example #2
0
function __ini_app(\Owl\Application $app)
{
    $app->middleware(function ($request, $response) {
        $start = microtime(true);
        yield;
        $use_time = (microtime(true) - $start) * 1000;
        $response->withHeader('x-run-time', (int) $use_time);
    });
    $router = new \Owl\Mvc\Router(['namespace' => '\\Controller']);
    $app->middleware(function ($request, $response) use($router) {
        $router->execute($request, $response);
    });
    $app->setExceptionHandler(function ($exception, $request, $response) {
        if ($exception instanceof \Owl\Http\Exception) {
            $status = $exception->getCode();
        } else {
            $status = 500;
            log_exception(get_logger('default'), $exception);
        }
        $response->withStatus($status);
        if (DEBUG) {
            foreach (__exception_headers($exception, 8) as $key => $value) {
                $response->withHeader($key, $value);
            }
        }
        if (!$request->isAjax()) {
            $view = new \Owl\Mvc\View(ROOT_DIR . '/View');
            $response->write($view->render('_error', ['exception' => $exception]));
        }
    });
    return $app;
}
Example #3
0
function validate_xsrf_token($token)
{
    if ($_SESSION[CONST_XSRF_TOKEN_KEY] != $token) {
        log_exception(new Exception('Invalid XSRF token. Was: "' . $token . '". Wanted: "' . $_SESSION[CONST_XSRF_TOKEN_KEY] . '"'));
        message_error('XSRF token mismatch');
        exit;
    }
}
Example #4
0
function validate_xsrf_token($token)
{
    if ($token != $_SESSION[CONST_XSRF_TOKEN_KEY]) {
        log_exception(new Exception('Invalid XSRF token. Was: "' . $token . '". Wanted: "' . $_SESSION[CONST_XSRF_TOKEN_KEY] . '"'));
        logout();
        exit;
    }
}
Example #5
0
function log_exception(LoggerInterface $logger, $exception, $level = 'error')
{
    if ($previous = $exception->getPrevious()) {
        return log_exception($logger, $previous, $level);
    }
    $message = sprintf('%s(%d): %s', get_class($exception), $exception->getCode(), $exception->getMessage());
    $logger->log($level, $message);
    $traces = explode("\n", $exception->getTraceAsString());
    foreach ($traces as $line) {
        $logger->log($level, $line);
    }
}
Example #6
0
function download_file($file)
{
    validate_id(array_get($file, 'id'));
    // do we read the file off AWS S3?
    if (CONFIG_AWS_S3_KEY_ID && CONFIG_AWS_S3_SECRET && CONFIG_AWS_S3_BUCKET) {
        try {
            // Instantiate the S3 client with your AWS credentials
            $client = S3Client::factory(array('key' => CONFIG_AWS_S3_KEY_ID, 'secret' => CONFIG_AWS_S3_SECRET));
            $file_key = '/challenges/' . $file['id'];
            $client->registerStreamWrapper();
            // Send a HEAD request to the object to get headers
            $command = $client->getCommand('HeadObject', array('Bucket' => CONFIG_AWS_S3_BUCKET, 'Key' => $file_key));
            $filePath = 's3://' . CONFIG_AWS_S3_BUCKET . $file_key;
        } catch (Exception $e) {
            message_error('Caught exception uploading file to S3: ' . $e->getMessage());
        }
    } else {
        $filePath = CONST_PATH_FILE_UPLOAD . $file['id'];
        if (!is_readable($filePath)) {
            log_exception(new Exception("Could not read the requested file: " . $filePath));
            message_error("Could not read the requested file. An error report has been lodged.");
        }
    }
    $file_title = $file['title'];
    if (defined('CONFIG_APPEND_MD5_TO_DOWNLOADS') && CONFIG_APPEND_MD5_TO_DOWNLOADS && $file['md5']) {
        $pos = strpos($file['title'], '.');
        if ($pos) {
            $file_title = substr($file['title'], 0, $pos) . '-' . $file['md5'] . substr($file['title'], $pos);
        } else {
            $file_title = $file_title . '-' . $file['md5'];
        }
    }
    // required for IE, otherwise Content-disposition is ignored
    if (ini_get('zlib.output_compression')) {
        ini_set('zlib.output_compression', 'Off');
    }
    header('Pragma: public');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Cache-Control: private', false);
    // required for certain browsers
    header('Content-Type: application/force-download');
    header('Content-Disposition: attachment; filename="' . $file_title . '";');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . $file['size']);
    // Stop output buffering
    if (ob_get_level()) {
        ob_end_flush();
    }
    flush();
    readfile($filePath);
}
Example #7
0
function validate_captcha()
{
    try {
        $captcha = new \ReCaptcha\ReCaptcha(CONFIG_RECAPTCHA_PRIVATE_KEY, new \ReCaptcha\RequestMethod\CurlPost());
        $response = $captcha->verify($_POST['g-recaptcha-response'], get_ip());
        if (!$response->isSuccess()) {
            message_error("Captcha error: " . print_r($response->getErrorCodes(), true));
        }
    } catch (Exception $e) {
        log_exception($e);
        message_error('Caught exception processing captcha. Please contact ' . (CONFIG_EMAIL_REPLYTO_EMAIL ? CONFIG_EMAIL_REPLYTO_EMAIL : CONFIG_EMAIL_FROM_EMAIL));
    }
}
Example #8
0
function lang_get($message, $replace = array())
{
    global $lang;
    if (!array_get($lang, $message)) {
        log_exception(new Exception('Could not fetch translation for key: ' . $message));
        return $message;
    }
    if (!empty($replace)) {
        $braced_replace = array();
        array_walk($replace, function (&$value, $key) use(&$braced_replace) {
            $braced_replace['{' . $key . '}'] = $value;
        });
        return str_replace(array_keys($braced_replace), array_values($braced_replace), $lang[$message]);
    }
    return $lang[$message];
}
Example #9
0
<?php

require '../include/mellivora.inc.php';
$user = db_select_one('users', array('id', 'enabled'), array('download_key' => $_GET['team_key']));
if (!is_valid_id($user['id'])) {
    log_exception(new Exception('Invalid team key used for download'));
    message_error(lang_get('invalid_team_key'));
}
if (!$user['enabled']) {
    message_error(lang_get('user_not_enabled'));
}
$file = db_query_fetch_one('
    SELECT
      f.id,
      f.title,
      f.size,
      f.md5,
      c.available_from
    FROM files AS f
    LEFT JOIN challenges AS c ON c.id = f.challenge
    WHERE f.download_key = :download_key', array('download_key' => $_GET['file_key']));
if (!is_valid_id($file['id'])) {
    log_exception(new Exception('Invalid file key used for download'));
    message_error(lang_get('no_file_found'));
}
if (time() < $file['available_from'] && !user_is_staff()) {
    message_error(lang_get('file_not_available'));
}
download_file($file);
Example #10
0
function delete_challenge_cascading($id)
{
    if (!is_valid_id($id)) {
        message_error('Invalid ID.');
    }
    try {
        db_begin_transaction();
        db_delete('challenges', array('id' => $id));
        db_delete('submissions', array('challenge' => $id));
        db_delete('hints', array('challenge' => $id));
        $files = db_select_all('files', array('id'), array('challenge' => $id));
        foreach ($files as $file) {
            delete_file($file['id']);
        }
        db_end_transaction();
    } catch (PDOException $e) {
        db_rollback_transaction();
        log_exception($e);
    }
}
Example #11
0
function enforce_authentication($min_class = CONST_USER_CLASS_USER, $force_user_data_reload = false)
{
    login_session_refresh($force_user_data_reload);
    if (!user_is_logged_in()) {
        logout();
    }
    if ($_SESSION['class'] < $min_class) {
        log_exception(new Exception('Class less than required'));
        logout();
    }
    if (user_is_staff() && $_SESSION['fingerprint'] != get_fingerprint()) {
        logout();
    }
    enforce_2fa();
}
Example #12
0
function validate_email($email)
{
    if (!valid_email($email)) {
        log_exception(new Exception('Invalid Email'));
        message_error('That doesn\'t look like an email. Please go back and double check the form.');
    }
}
Example #13
0
function validate_email($email)
{
    if (!valid_email($email)) {
        log_exception(new Exception('Invalid Email'));
        message_error(lang_get('not_a_valid_email'));
    }
}
Example #14
0
function enforce_authentication($minClass = CONFIG_UC_USER)
{
    login_session_refresh();
    if (!user_is_logged_in()) {
        logout();
    }
    if ($_SESSION['IID'] != $_SESSION['UIID'] && !verifySAGlobal()) {
        logout();
    }
    if ($_SESSION['class'] < $minClass) {
        log_exception(new Exception('Class less than required'));
        logout();
    }
    if (user_is_staff() && $_SESSION['fingerprint'] != get_fingerprint()) {
        logout();
    }
    enforce_2fa();
}
Example #15
0
             $last = $pdo->query("SELECT MAX(`time`) AS `last`\n     FROM {$board}_post\n     WHERE resto = {$thread}\n     GROUP BY resto")->fetchColumn(0);
             if ($last != '') {
                 $pdo->query("UPDATE {$board}_thread SET `lastreply`='{$last}' WHERE `threadid`='{$thread}'");
             }
         }
     } else {
         log_error("No threads could be downloaded.");
     }
     /*
      * Update "Last updated" server var
      */
     o("Updating last update time: " . date("Y-m-d H:i:s"));
     $pdo->query("UPDATE `boards` SET `last_crawl`='" . $highestTime . "' WHERE `shortname`='{$board}'");
     $lastTime = $highestTime;
 } catch (Throwable $e) {
     log_exception($e);
     o("Restarting script...");
     $pdo = null;
     Config::closePDOConnectionRW();
     sleep(5);
     if (PHP_OS != "WINNT") {
         // spawn a new process
         if (!pcntl_fork()) {
             pcntl_exec(PHP_BINARY, $argv);
         }
         die;
     } else {
         $args = implode(' ', $argv);
         exec("psexec -d -accepteula C:\\php\\php.exe {$args}");
         die;
     }
Example #16
0
/**
 * Error handler, passes flow over the exception logger with new ErrorException.
 */
function log_error($num, $str, $file, $line, $context = null)
{
    log_exception(new ErrorException($str, 0, $num, $file, $line));
}
Example #17
0
function sql_exception(PDOException $e)
{
    log_exception($e);
    message_error('An SQL exception occurred. Please check the exceptions log.');
}
Example #18
0
/**
 * Error handler, passes flow over the exception logger with new ErrorException.
 */
function log_error($num, $str, $file, $line, $context = null)
{
    if (ERROR_REPORT < 2 && $num == 8) {
        return '';
    }
    log_exception(new ErrorException($str, 0, $num, $file, $line));
}
Example #19
0
$msg_type = "error";
$ret = false;
$msg = "";
$data = array();
do {
    global $F;
    if (!isset($F)) {
        break;
    }
    if (qwp_ops_pre_check($msg) === false) {
        break;
    }
    $msg = qwp_validate_form();
    if ($msg !== true) {
        break;
    }
    $msg = "";
    if (qwp_custom_validate_form($msg) === false) {
        break;
    }
    _qwp_process_ops($msg, $data, $msg_type, $ret);
} while (false);
if (!$ret && !$msg) {
    $msg = L("Invalid parameters");
}
try {
    qwp_custom_ops_logger($ret, $msg);
} catch (Exception $e) {
    log_exception($e, 'ops logger error');
}
qwp_echo_json_response($ret, $msg, $msg_type, $data);