Run formatter on all PHP code; should not change behaviour in any way

This commit is contained in:
Floorb 2021-07-12 09:03:02 -04:00
parent 2ce6eba811
commit 7289aba68d
199 changed files with 136135 additions and 155831 deletions

View file

@ -18,160 +18,167 @@ require_once('../includes/password.php');
define('IN_ADMIN', 1); define('IN_ADMIN', 1);
require_once('common.php'); require_once('common.php');
$query = $conn->query('SELECT user FROM admin LIMIT 1'); $query = $conn->query('SELECT user FROM admin LIMIT 1');
$adminid = $query->fetch()['user']; $adminid = $query->fetch()['user'];
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>Paste - Admin Settings</title> <title>Paste - Admin Settings</title>
<link rel="shortcut icon" href="favicon.ico"> <link rel="shortcut icon" href="favicon.ico">
<link href="css/paste.css" rel="stylesheet" type="text/css" /> <link href="css/paste.css" rel="stylesheet" type="text/css"/>
</head> </head>
<body> <body>
<div id="top" class="clearfix">
<!-- Start App Logo -->
<div class="applogo">
<a href="../" class="logo">Paste</a>
</div>
<!-- End App Logo -->
<!-- Start Top Right --> <div id="top" class="clearfix">
<ul class="top-right"> <!-- Start App Logo -->
<li class="dropdown link"> <div class="applogo">
<a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span class="caret"></span></a> <a href="../" class="logo">Paste</a>
<ul class="dropdown-menu dropdown-menu-list dropdown-menu-right"> </div>
<li><a href="admin.php">Settings</a></li> <!-- End App Logo -->
<li><a href="?logout">Logout</a></li>
</ul>
</li>
</ul>
<!-- End Top Right -->
</div>
<!-- END TOP -->
<div class="content"> <!-- Start Top Right -->
<!-- START CONTAINER --> <ul class="top-right">
<div class="container-widget"> <li class="dropdown link">
<!-- Start Menu --> <a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span
<?php include 'menu.php';?> class="caret"></span></a>
<!-- End Menu --> <ul class="dropdown-menu dropdown-menu-list dropdown-menu-right">
<li><a href="admin.php">Settings</a></li>
<?php <li><a href="?logout">Logout</a></li>
if ($_SERVER['REQUEST_METHOD'] == 'POST') { </ul>
$adminid = htmlentities(Trim($_POST['adminid'])); </li>
$password = password_hash($_POST['password'], PASSWORD_DEFAULT); </ul>
<!-- End Top Right -->
$query = "UPDATE admin SET user='$adminid', pass='$password' WHERE id='1'"; </div>
mysqli_query($con, $query); <!-- END TOP -->
if (mysqli_errno($con)) { <div class="content">
$msg = '<div class="paste-alert alert6" style="text-align: center;"> <!-- START CONTAINER -->
<div class="container-widget">
<!-- Start Menu -->
<?php include 'menu.php'; ?>
<!-- End Menu -->
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$adminid = htmlentities(Trim($_POST['adminid']));
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$query = "UPDATE admin SET user='$adminid', pass='$password' WHERE id='1'";
mysqli_query($con, $query);
if (mysqli_errno($con)) {
$msg = '<div class="paste-alert alert6" style="text-align: center;">
' . mysqli_error($con) . ' ' . mysqli_error($con) . '
</div>'; </div>';
} else { } else {
$msg = '<div class="paste-alert alert3" style="text-align: center;"> $msg = '<div class="paste-alert alert3" style="text-align: center;">
Account details updated. Account details updated.
</div>'; </div>';
} }
} }
?> ?>
<!-- Start Admin Settings -->
<div class="row">
<div class="col-md-12">
<div class="panel panel-widget">
<div class="panel-body">
<div role="tabpanel">
<!-- Nav tabs -->
<ul class="nav nav-tabs nav-line" role="tablist" style="text-align: center;">
<li role="presentation" class="active"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li>
<li role="presentation"><a href="#logs" aria-controls="logs" role="tab" data-toggle="tab">Login History</a></li>
</ul>
<!-- Tab panes --> <!-- Start Admin Settings -->
<div class="tab-content"> <div class="row">
<div role="tabpanel" class="tab-pane active" id="settings"> <div class="col-md-12">
<div class="login-form" style="padding:0;"> <div class="panel panel-widget">
<?php if (isset($msg)) echo $msg; ?> <div class="panel-body">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" class="form-area" method="POST"> <div role="tabpanel">
<div class="form-area"> <!-- Nav tabs -->
<div class="group"> <ul class="nav nav-tabs nav-line" role="tablist" style="text-align: center;">
<input type="text" id="adminid" name="adminid" class="form-control" placeholder="Username" value="<?php echo $adminid; ?>"> <li role="presentation" class="active"><a href="#settings" aria-controls="settings"
<i class="fa fa-user"></i> role="tab" data-toggle="tab">Settings</a></li>
</div> <li role="presentation"><a href="#logs" aria-controls="logs" role="tab"
<div class="group"> data-toggle="tab">Login History</a></li>
<input type="password" id="password" name="password" class="form-control" placeholder="Password"> </ul>
<i class="fa fa-key"></i>
</div>
<button type="submit" class="btn btn-default btn-block">Save</button>
</div>
</form>
</div>
</div>
<div role="tabpanel" class="tab-pane" id="logs"> <!-- Tab panes -->
<table class="table"> <div class="tab-content">
<tbody> <div role="tabpanel" class="tab-pane active" id="settings">
<tr> <div class="login-form" style="padding:0;">
<th>Login date</th> <?php if (isset($msg)) echo $msg; ?>
<th>IP</th> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" class="form-area"
</tr> method="POST">
<?php <div class="form-area">
$rec_limit = 10; <div class="group">
<input type="text" id="adminid" name="adminid" class="form-control"
placeholder="Username" value="<?php echo $adminid; ?>">
<i class="fa fa-user"></i>
</div>
<div class="group">
<input type="password" id="password" name="password"
class="form-control" placeholder="Password">
<i class="fa fa-key"></i>
</div>
<button type="submit" class="btn btn-default btn-block">Save</button>
</div>
</form>
</div>
</div>
$query = $conn->query('SELECT COUNT(*) FROM admin_history'); <div role="tabpanel" class="tab-pane" id="logs">
$row = $query->fetch(PDO::FETCH_NUM); <table class="table">
$rec_count = $row[0]; <tbody>
<tr>
<th>Login date</th>
<th>IP</th>
</tr>
<?php
$rec_limit = 10;
$query = $conn->prepare('SELECT ip, last_date FROM admin_history ORDER BY `id` LIMIT ?'); $query = $conn->query('SELECT COUNT(*) FROM admin_history');
$query->execute([$rec_limit]); $row = $query->fetch(PDO::FETCH_NUM);
$rec_count = $row[0];
while ($row = $query->fetch()) { $query = $conn->prepare('SELECT ip, last_date FROM admin_history ORDER BY `id` LIMIT ?');
echo '<tr>'; $query->execute([$rec_limit]);
echo '<td>' . $row['last_date'] . '</td>';
echo '<td>' . $row['ip'] . '</td>';
echo '</tr>';
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- End Admin Settings -->
</div>
<!-- END CONTAINER -->
<!-- Start Footer --> while ($row = $query->fetch()) {
<div class="row footer"> echo '<tr>';
<div class="col-md-6 text-left"> echo '<td>' . $row['last_date'] . '</td>';
<a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a> echo '<td>' . $row['ip'] . '</td>';
</div> echo '</tr>';
<div class="col-md-6 text-right"> }
Powered by <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a> ?>
</div> </tbody>
</div> </table>
<!-- End Footer --> </div>
</div> </div>
<!-- End content --> </div>
</div>
</div>
</div>
</div>
<!-- End Admin Settings -->
</div>
<!-- END CONTAINER -->
<script type="text/javascript" src="js/jquery.min.js"></script> <!-- Start Footer -->
<script type="text/javascript" src="js/bootstrap.min.js"></script> <div class="row footer">
</body> <div class="col-md-6 text-left">
<a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a
href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a>
</div>
<div class="col-md-6 text-right">
Powered by <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a>
</div>
</div>
<!-- End Footer -->
</div>
<!-- End content -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
</body>
</html> </html>
<php <php
if($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") { if($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
header("Location: http://ponepaste.org/SVOtaKqJZh4nT9Z"); header("Location: http://ponepaste.org/SVOtaKqJZh4nT9Z");
die(); die();
?> ?>

View file

@ -32,8 +32,8 @@ if ($row) {
if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$text_ads = trim($_POST['text_ads']); $text_ads = trim($_POST['text_ads']);
$ads_1 = trim($_POST['ads_1']); $ads_1 = trim($_POST['ads_1']);
$ads_2 = trim($_POST['ads_2']); $ads_2 = trim($_POST['ads_2']);
$conn->prepare('UPDATE ads SET text_ads = ?, ads_1 = ?, ads_2 = ? WHERE id = 1')->execute([$text_ads, $ads_1, $ads_2]); $conn->prepare('UPDATE ads SET text_ads = ?, ads_1 = ?, ads_2 = ? WHERE id = 1')->execute([$text_ads, $ads_1, $ads_2]);
$msg = '<div class="paste-alert alert3"> $msg = '<div class="paste-alert alert3">
@ -44,93 +44,98 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>Paste - Ads</title> <title>Paste - Ads</title>
<link rel="shortcut icon" href="favicon.ico"> <link rel="shortcut icon" href="favicon.ico">
<link href="css/paste.css" rel="stylesheet" type="text/css" /> <link href="css/paste.css" rel="stylesheet" type="text/css"/>
</head> </head>
<body> <body>
<div id="top" class="clearfix">
<!-- Start App Logo -->
<div class="applogo">
<a href="../" class="logo">Paste</a>
</div>
<!-- End App Logo -->
<!-- Start Top Right --> <div id="top" class="clearfix">
<ul class="top-right"> <!-- Start App Logo -->
<li class="dropdown link"> <div class="applogo">
<a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span class="caret"></span></a> <a href="../" class="logo">Paste</a>
<ul class="dropdown-menu dropdown-menu-list dropdown-menu-right"> </div>
<li><a href="admin.php">Settings</a></li> <!-- End App Logo -->
<li><a href="?logout">Logout</a></li>
</ul>
</li>
</ul>
<!-- End Top Right -->
</div>
<!-- END TOP -->
<div class="content"> <!-- Start Top Right -->
<!-- START CONTAINER --> <ul class="top-right">
<div class="container-widget"> <li class="dropdown link">
<!-- Start Menu --> <a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span
<?php include 'menu.php';?> class="caret"></span></a>
<!-- End Menu --> <ul class="dropdown-menu dropdown-menu-list dropdown-menu-right">
<!-- Start Ads --> <li><a href="admin.php">Settings</a></li>
<div class="row"> <li><a href="?logout">Logout</a></li>
<div class="col-md-12"> </ul>
<div class="panel panel-widget"> </li>
<div class="panel-body"> </ul>
<div class="panel-title">Manage Ads</a></div> <!-- End Top Right -->
<?php if (isset($msg)) echo $msg; ?> </div>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <!-- END TOP -->
<div class="control-group">
<label class="control-label" for="text_ads">Text Ads</label>
<div class="controls">
<textarea placeholder="Ad code" name="text_ads" rows="3" class="span6"><?php echo $text_ads; ?></textarea>
</div>
</div>
<div class="control-group">
<label class="control-label" for="ads_1">Image Ad - (Sidebar)</label>
<div class="controls">
<textarea placeholder="Ad code" name="ads_1" id="ads_1" rows="3" class="span6"><?php echo $ads_1; ?></textarea>
</div>
</div>
<div class="control-group">
<label class="control-label" for="ads_2">Image Ad (Footer)</label>
<div class="controls">
<textarea placeholder="Ad code" name="ads_2" id="ads_2" rows="3" class="span6"><?php echo $ads_2; ?></textarea>
</div>
</div>
<button type="submit" class="btn btn-default">Save</button>
</form>
</div>
</div>
</div>
</div>
<!-- End Ads -->
</div>
<!-- END CONTAINER -->
<!-- Start Footer --> <div class="content">
<div class="row footer"> <!-- START CONTAINER -->
<div class="col-md-6 text-left"> <div class="container-widget">
<a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a> <!-- Start Menu -->
</div> <?php include 'menu.php'; ?>
<div class="col-md-6 text-right"> <!-- End Menu -->
Powered by <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a> <!-- Start Ads -->
</div> <div class="row">
</div> <div class="col-md-12">
<!-- End Footer --> <div class="panel panel-widget">
</div> <div class="panel-body">
<!-- End content --> <div class="panel-title">Manage Ads</a></div>
<?php if (isset($msg)) echo $msg; ?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="control-group">
<label class="control-label" for="text_ads">Text Ads</label>
<div class="controls">
<textarea placeholder="Ad code" name="text_ads" rows="3"
class="span6"><?php echo $text_ads; ?></textarea>
</div>
</div>
<div class="control-group">
<label class="control-label" for="ads_1">Image Ad - (Sidebar)</label>
<div class="controls">
<textarea placeholder="Ad code" name="ads_1" id="ads_1" rows="3"
class="span6"><?php echo $ads_1; ?></textarea>
</div>
</div>
<script type="text/javascript" src="js/jquery.min.js"></script> <div class="control-group">
<script type="text/javascript" src="js/bootstrap.min.js"></script> <label class="control-label" for="ads_2">Image Ad (Footer)</label>
</body> <div class="controls">
<textarea placeholder="Ad code" name="ads_2" id="ads_2" rows="3"
class="span6"><?php echo $ads_2; ?></textarea>
</div>
</div>
<button type="submit" class="btn btn-default">Save</button>
</form>
</div>
</div>
</div>
</div>
<!-- End Ads -->
</div>
<!-- END CONTAINER -->
<!-- Start Footer -->
<div class="row footer">
<div class="col-md-6 text-left">
<a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a
href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a>
</div>
<div class="col-md-6 text-right">
Powered by <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a>
</div>
</div>
<!-- End Footer -->
</div>
<!-- End content -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
</body>
</html> </html>

View file

@ -11,7 +11,7 @@ if (isset($_SESSION['login'])) {
if (isset($_GET['logout'])) { if (isset($_GET['logout'])) {
if (isset($_SESSION['login'])) if (isset($_SESSION['login']))
unset($_SESSION['login']); unset($_SESSION['login']);
session_destroy(); session_destroy();
header("Location: ."); header("Location: .");
exit(); exit();
@ -29,29 +29,29 @@ $primaryKey = 'id';
// parameter represents the DataTables column identifier. In this case simple // parameter represents the DataTables column identifier. In this case simple
// indexes // indexes
$columns = array( $columns = array(
array( 'db' => 'id', 'dt' => 0 ), array('db' => 'id', 'dt' => 0),
array( 'db' => 'member', 'dt' => 1 ), array('db' => 'member', 'dt' => 1),
array( 'db' => 'ip', 'dt' => 2 ), array('db' => 'ip', 'dt' => 2),
array( 'db' => 'visible', 'dt' => 3 ) array('db' => 'visible', 'dt' => 3)
); );
$columns2 = array( $columns2 = array(
array( 'db' => 'id', 'dt' => 0 ), array('db' => 'id', 'dt' => 0),
array( 'db' => 'member', 'dt' => 1 ), array('db' => 'member', 'dt' => 1),
array( 'db' => 'ip', 'dt' => 2 ), array('db' => 'ip', 'dt' => 2),
array( 'db' => 'visible', 'dt' => 3 ), array('db' => 'visible', 'dt' => 3),
array( 'db' => 'details', 'dt' => 4 ), array('db' => 'details', 'dt' => 4),
array( 'db' => 'view', 'dt' => 5 ), array('db' => 'view', 'dt' => 5),
array( 'db' => 'delete', 'dt' => 6) array('db' => 'delete', 'dt' => 6)
); );
// SQL server connection information // SQL server connection information
$sql_details = array( $sql_details = array(
'user' => $dbuser, 'user' => $dbuser,
'pass' => $dbpassword, 'pass' => $dbpassword,
'db' => $dbname, 'db' => $dbname,
'host' => $dbhost 'host' => $dbhost
); );
@ -60,9 +60,9 @@ $sql_details = array(
* server-side, there is no need to edit below this line. * server-side, there is no need to edit below this line.
*/ */
require( 'ssp.pastes.php' ); require('ssp.pastes.php');
echo json_encode( echo json_encode(
SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns, $columns2 ) SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns, $columns2)
); );
?> ?>

View file

@ -11,7 +11,7 @@ if (isset($_SESSION['login'])) {
if (isset($_GET['logout'])) { if (isset($_GET['logout'])) {
if (isset($_SESSION['login'])) if (isset($_SESSION['login']))
unset($_SESSION['login']); unset($_SESSION['login']);
session_destroy(); session_destroy();
header("Location: ."); header("Location: .");
exit(); exit();
@ -29,29 +29,29 @@ $primaryKey = 'id';
// parameter represents the DataTables column identifier. In this case simple // parameter represents the DataTables column identifier. In this case simple
// indexes // indexes
$columns = array( $columns = array(
array( 'db' => 'id', 'dt' => 0 ), array('db' => 'id', 'dt' => 0),
array( 'db' => 'm_report', 'dt' => 1 ), array('db' => 'm_report', 'dt' => 1),
array( 'db' => 'p_report', 'dt' => 2 ), array('db' => 'p_report', 'dt' => 2),
array( 'db' => 't_report', 'dt' => 3 ) array('db' => 't_report', 'dt' => 3)
); );
$columns2 = array( $columns2 = array(
array( 'db' => 'id', 'dt' => 0 ), array('db' => 'id', 'dt' => 0),
array( 'db' => 'm_report', 'dt' => 1 ), array('db' => 'm_report', 'dt' => 1),
array( 'db' => 'p_report', 'dt' => 2 ), array('db' => 'p_report', 'dt' => 2),
array( 'db' => 't_report', 'dt' => 3 ), array('db' => 't_report', 'dt' => 3),
array( 'db' => 'details', 'dt' => 4 ), array('db' => 'details', 'dt' => 4),
array( 'db' => 'view', 'dt' => 5 ), array('db' => 'view', 'dt' => 5),
array( 'db' => 'delete', 'dt' => 6) array('db' => 'delete', 'dt' => 6)
); );
// SQL server connection information // SQL server connection information
$sql_details = array( $sql_details = array(
'user' => $dbuser, 'user' => $dbuser,
'pass' => $dbpassword, 'pass' => $dbpassword,
'db' => $dbname, 'db' => $dbname,
'host' => $dbhost 'host' => $dbhost
); );
@ -60,9 +60,9 @@ $sql_details = array(
* server-side, there is no need to edit below this line. * server-side, there is no need to edit below this line.
*/ */
require( 'ssp.reports.php' ); require('ssp.reports.php');
echo json_encode( echo json_encode(
SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns, $columns2 ) SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns, $columns2)
); );
?> ?>

View file

@ -11,33 +11,33 @@ $primaryKey = 'id';
// parameter represents the DataTables column identifier. In this case simple // parameter represents the DataTables column identifier. In this case simple
// indexes // indexes
$columns = array( $columns = array(
array( 'db' => 'id', 'dt' => 0 ), array('db' => 'id', 'dt' => 0),
array( 'db' => 'username', 'dt' => 1 ), array('db' => 'username', 'dt' => 1),
array( 'db' => 'email_id', 'dt' => 2 ), array('db' => 'email_id', 'dt' => 2),
array( 'db' => 'date', 'dt' => 3 ), array('db' => 'date', 'dt' => 3),
array( 'db' => 'platform', 'dt' => 4 ), array('db' => 'platform', 'dt' => 4),
array( 'db' => 'id', 'dt' => 5 ), array('db' => 'id', 'dt' => 5),
array( 'db' => 'verified', 'dt' => 7 ) array('db' => 'verified', 'dt' => 7)
); );
$columns2 = array( $columns2 = array(
array( 'db' => 'id', 'dt' => 0 ), array('db' => 'id', 'dt' => 0),
array( 'db' => 'username', 'dt' => 1 ), array('db' => 'username', 'dt' => 1),
array( 'db' => 'email_id', 'dt' => 2 ), array('db' => 'email_id', 'dt' => 2),
array( 'db' => 'date', 'dt' => 3), array('db' => 'date', 'dt' => 3),
array( 'db' => 'platform', 'dt' => 4 ), array('db' => 'platform', 'dt' => 4),
array( 'db' => 'ban', 'dt' => 5 ), array('db' => 'ban', 'dt' => 5),
array( 'db' => 'view', 'dt' => 6 ), array('db' => 'view', 'dt' => 6),
array( 'db' => 'delete', 'dt' => 7) array('db' => 'delete', 'dt' => 7)
); );
// SQL server connection information // SQL server connection information
$sql_details = array( $sql_details = array(
'user' => $dbuser, 'user' => $dbuser,
'pass' => $dbpassword, 'pass' => $dbpassword,
'db' => $dbname, 'db' => $dbname,
'host' => $dbhost 'host' => $dbhost
); );
@ -46,13 +46,13 @@ $sql_details = array(
* server-side, there is no need to edit below this line. * server-side, there is no need to edit below this line.
*/ */
require( 'ssp.users.php' ); require('ssp.users.php');
echo json_encode( echo json_encode(
SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns, $columns2 ) SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns, $columns2)
); );
if($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") { if ($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
header("Location: http://ponepaste.org/SVOtaKqJZh4nT9Z"); header("Location: http://ponepaste.org/SVOtaKqJZh4nT9Z");
die(); die();
} }

View file

@ -15,7 +15,7 @@ function updateAdminHistory($conn) {
if ($row = $query->fetch()) { if ($row = $query->fetch()) {
$last_date = $row['last_date']; $last_date = $row['last_date'];
$last_ip = $row['ip']; $last_ip = $row['ip'];
} }
if ($last_ip !== $ip || $last_date !== $date) { if ($last_ip !== $ip || $last_date !== $date) {

File diff suppressed because it is too large Load diff

View file

@ -16,7 +16,7 @@
define('IN_ADMIN', 1); define('IN_ADMIN', 1);
require_once('common.php'); require_once('common.php');
$today_users_count = 0; $today_users_count = 0;
$today_pastes_count = 0; $today_pastes_count = 0;
require_once('../includes/functions.php'); require_once('../includes/functions.php');
@ -32,7 +32,7 @@ $query = $conn->prepare('SELECT tpage, tvisit FROM page_view WHERE id = ?');
$query->execute([$page_last_id]); $query->execute([$page_last_id]);
while ($row = $query->fetch()) { while ($row = $query->fetch()) {
$today_page = $row['tpage']; $today_page = $row['tpage'];
$today_visit = $row['tvisit']; $today_visit = $row['tvisit'];
} }
@ -55,8 +55,8 @@ $query->execute([$c_date]);
$today_pastes_count = intval($query->fetch(PDO::FETCH_NUM)[0]); $today_pastes_count = intval($query->fetch(PDO::FETCH_NUM)[0]);
for ($loop = 0; $loop <= 6; $loop++) { for ($loop = 0; $loop <= 6; $loop++) {
$myid = $page_last_id - $loop; $myid = $page_last_id - $loop;
$query = $conn->prepare("SELECT date, tpage, tvisit FROM page_view WHERE id = ?"); $query = $conn->prepare("SELECT date, tpage, tvisit FROM page_view WHERE id = ?");
$query->execute([$myid]); $query->execute([$myid]);
while ($row = $query->fetch()) { while ($row = $query->fetch()) {
@ -66,14 +66,14 @@ for ($loop = 0; $loop <= 6; $loop++) {
$sdate = str_replace('February', 'Feb', $sdate); $sdate = str_replace('February', 'Feb', $sdate);
$sdate = str_replace('March', 'Mar', $sdate); $sdate = str_replace('March', 'Mar', $sdate);
$sdate = str_replace('April', 'Apr', $sdate); $sdate = str_replace('April', 'Apr', $sdate);
$sdate = str_replace('August', 'Aug', $sdate); $sdate = str_replace('August', 'Aug', $sdate);
$sdate = str_replace('September', 'Sep', $sdate); $sdate = str_replace('September', 'Sep', $sdate);
$sdate = str_replace('October', 'Oct', $sdate); $sdate = str_replace('October', 'Oct', $sdate);
$sdate = str_replace('November', 'Nov', $sdate); $sdate = str_replace('November', 'Nov', $sdate);
$sdate = str_replace('December', 'Dec', $sdate); $sdate = str_replace('December', 'Dec', $sdate);
$ldate[$loop] = $sdate; $ldate[$loop] = $sdate;
$tpage[$loop] = $row['tpage']; $tpage[$loop] = $row['tpage'];
$tvisit[$loop] = $row['tvisit']; $tvisit[$loop] = $row['tvisit'];
} }
} }
@ -81,108 +81,109 @@ for ($loop = 0; $loop <= 6; $loop++) {
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ponepaste - Dashboard</title> <title>Ponepaste - Dashboard</title>
<link rel="shortcut icon" href="favicon.ico"> <link rel="shortcut icon" href="favicon.ico">
<link href="css/paste.css" rel="stylesheet" type="text/css" /> <link href="css/paste.css" rel="stylesheet" type="text/css"/>
</head> </head>
<body> <body>
<div id="top" class="clearfix">
<!-- Start App Logo -->
<div class="applogo">
<a href="../" class="logo">Paste</a>
</div>
<!-- End App Logo -->
<!-- Start Top Right --> <div id="top" class="clearfix">
<ul class="top-right"> <!-- Start App Logo -->
<li class="dropdown link"> <div class="applogo">
<a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span class="caret"></span></a> <a href="../" class="logo">Paste</a>
<ul class="dropdown-menu dropdown-menu-list dropdown-menu-right"> </div>
<li><a href="admin.php">Settings</a></li> <!-- End App Logo -->
<li><a href="?logout">Logout</a></li>
</ul>
</li>
</ul>
<!-- End Top Right -->
</div>
<!-- END TOP -->
<div class="content"> <!-- Start Top Right -->
<!-- START CONTAINER --> <ul class="top-right">
<div class="container-widget"> <li class="dropdown link">
<!-- Start Menu --> <a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span
<?php include 'menu.php';?> class="caret"></span></a>
<!-- End Menu --> <ul class="dropdown-menu dropdown-menu-list dropdown-menu-right">
<li><a href="admin.php">Settings</a></li>
<!-- Start Stats --> <li><a href="?logout">Logout</a></li>
<div class="row"> </ul>
<div class="col-md-12"> </li>
<ul class="panel topstats clearfix"> </ul>
<li class="col-xs-6 col-lg-3"> <!-- End Top Right -->
<span class="title"><i class="fa fa-eye"></i> Views</span> </div>
<h3><?php echo $today_page; ?></h3> <!-- END TOP -->
<span class="diff">Today</span>
</li>
<li class="col-xs-6 col-lg-3">
<span class="title"><i class="fa fa-clipboard"></i> Pastes</span>
<h3><?php echo $today_pastes_count; ?></h3>
<span class="diff">Today</span>
</li>
<li class="col-xs-6 col-lg-3">
<span class="title"><i class="fa fa-users"></i> Users</span>
<h3><?php echo $today_users_count; ?></h3>
<span class="diff">Today</span>
</li>
<li class="col-xs-6 col-lg-3">
<span class="title"><i class="fa fa-users"></i> Unique Views</span>
<h3><?php echo $today_visit; ?></h3>
<span class="diff">Today</span>
</li>
</ul>
</div>
</div>
<!-- End Stats -->
<div class="row">
<!-- Start Recent -->
<div class="col-md-12 col-lg-6">
<div class="panel panel-widget">
<div class="panel-title">
Recent Pastes
</div>
<div class="panel-body table-responsive"> <div class="content">
<!-- START CONTAINER -->
<div class="container-widget">
<!-- Start Menu -->
<?php include 'menu.php'; ?>
<!-- End Menu -->
<table class="table table-hover"> <!-- Start Stats -->
<thead> <div class="row">
<tr> <div class="col-md-12">
<td>ID</td> <ul class="panel topstats clearfix">
<td>Username</td> <li class="col-xs-6 col-lg-3">
<td>Date</td> <span class="title"><i class="fa fa-eye"></i> Views</span>
<td>IP</td> <h3><?php echo $today_page; ?></h3>
<td>Views</td> <span class="diff">Today</span>
</tr> </li>
</thead> <li class="col-xs-6 col-lg-3">
<tbody> <span class="title"><i class="fa fa-clipboard"></i> Pastes</span>
<?php <h3><?php echo $today_pastes_count; ?></h3>
$res = getRecentadmin($conn, 7); <span class="diff">Today</span>
foreach ($res as $row) { </li>
$title = Trim($row['title']); <li class="col-xs-6 col-lg-3">
$p_id = Trim($row['id']); <span class="title"><i class="fa fa-users"></i> Users</span>
$p_date = Trim($row['s_date']); <h3><?php echo $today_users_count; ?></h3>
$p_ip = Trim($row['ip']); <span class="diff">Today</span>
$p_member = Trim($row['member']); </li>
$p_view = Trim($row['views']); <li class="col-xs-6 col-lg-3">
$p_time = Trim($row['now_time']); <span class="title"><i class="fa fa-users"></i> Unique Views</span>
$nowtime1 = time(); <h3><?php echo $today_visit; ?></h3>
$oldtime1 = $p_time; <span class="diff">Today</span>
$p_time = conTime($nowtime1 - $oldtime1); </li>
$title = truncate($title, 5, 30); </ul>
echo " </div>
</div>
<!-- End Stats -->
<div class="row">
<!-- Start Recent -->
<div class="col-md-12 col-lg-6">
<div class="panel panel-widget">
<div class="panel-title">
Recent Pastes
</div>
<div class="panel-body table-responsive">
<table class="table table-hover">
<thead>
<tr>
<td>ID</td>
<td>Username</td>
<td>Date</td>
<td>IP</td>
<td>Views</td>
</tr>
</thead>
<tbody>
<?php
$res = getRecentadmin($conn, 7);
foreach ($res as $row) {
$title = Trim($row['title']);
$p_id = Trim($row['id']);
$p_date = Trim($row['s_date']);
$p_ip = Trim($row['ip']);
$p_member = Trim($row['member']);
$p_view = Trim($row['views']);
$p_time = Trim($row['now_time']);
$nowtime1 = time();
$oldtime1 = $p_time;
$p_time = conTime($nowtime1 - $oldtime1);
$title = truncate($title, 5, 30);
echo "
<tr> <tr>
<td>$p_id</td> <td>$p_id</td>
<td>$p_member</td> <td>$p_member</td>
@ -190,91 +191,91 @@ for ($loop = 0; $loop <= 6; $loop++) {
<td><span class='label label-default'>$p_ip</span></td> <td><span class='label label-default'>$p_ip</span></td>
<td>$p_view</td> <td>$p_view</td>
</tr> "; </tr> ";
} }
?> ?>
</tbody> </tbody>
</table> </table>
</div> </div>
</div> </div>
</div> </div>
<!-- End Recent --> <!-- End Recent -->
<!-- Start Recent Users --> <!-- Start Recent Users -->
<div class="col-md-12 col-lg-6"> <div class="col-md-12 col-lg-6">
<div class="panel panel-widget"> <div class="panel panel-widget">
<div class="panel-title"> <div class="panel-title">
Recent Users Recent Users
</div> </div>
<div class="panel-body table-responsive"> <div class="panel-body table-responsive">
<table class="table table-hover"> <table class="table table-hover">
<thead> <thead>
<tr> <tr>
<td>ID</td> <td>ID</td>
<td>Username</td> <td>Username</td>
<td>Date</td> <td>Date</td>
<td>IP</td> <td>IP</td>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<?php <?php
$most_recent_users = $conn->query('SELECT id, username, date, ip FROM users ORDER BY id DESC LIMIT 7')->fetchAll(); $most_recent_users = $conn->query('SELECT id, username, date, ip FROM users ORDER BY id DESC LIMIT 7')->fetchAll();
$last_id = intval( $last_id = intval(
$conn->query('SELECT MAX(id) FROM users')->fetch(PDO::FETCH_NUM)[0] $conn->query('SELECT MAX(id) FROM users')->fetch(PDO::FETCH_NUM)[0]
); );
foreach ($most_recent_users as $user) { foreach ($most_recent_users as $user) {
echo " echo "
<tr> <tr>
<td>${user['id']}</td> <td>${user['id']}</td>
<td>${user['username']}</td> <td>${user['username']}</td>
<td>${user['date']}</td> <td>${user['date']}</td>
<td><span class='label label-default'>${user['ip']}</span></td> <td><span class='label label-default'>${user['ip']}</span></td>
</tr> "; </tr> ";
} }
?> ?>
</tbody> </tbody>
</table> </table>
</div> </div>
</div> </div>
</div> </div>
<!-- End Recent Users --> <!-- End Recent Users -->
</div> </div>
<div class="row">
<!-- Start Admin History -->
<div class="col-md-12 col-lg-6">
<div class="panel panel-widget">
<div class="panel-title">
Admin History
</div>
<div class="panel-body table-responsive"> <div class="row">
<!-- Start Admin History -->
<div class="col-md-12 col-lg-6">
<div class="panel panel-widget">
<div class="panel-title">
Admin History
</div>
<table class="table table-hover"> <div class="panel-body table-responsive">
<thead>
<tr> <table class="table table-hover">
<td>ID</td> <thead>
<td>Last Login Date</td> <tr>
<td>IP</td> <td>ID</td>
<td>ID</td> <td>Last Login Date</td>
<td>Last Login Date</td> <td>IP</td>
</tr> <td>ID</td>
</thead> <td>Last Login Date</td>
<tbody> </tr>
<?php </thead>
$res = getreports($conn, 7); <tbody>
foreach ($res as $row) { <?php
$r_paste = Trim($row['p_report']); $res = getreports($conn, 7);
$r_id = Trim($row['id']); foreach ($res as $row) {
$r_date = Trim($row['t_report']); $r_paste = Trim($row['p_report']);
$m_report = Trim($row['m_report']); $r_id = Trim($row['id']);
$r_reason = Trim($row['rep_reason']); $r_date = Trim($row['t_report']);
echo ' $m_report = Trim($row['m_report']);
$r_reason = Trim($row['rep_reason']);
echo '
<tr> <tr>
<td>' . $r_id . '</td> <td>' . $r_id . '</td>
<td>' . $r_paste . '</td> <td>' . $r_paste . '</td>
@ -282,50 +283,55 @@ for ($loop = 0; $loop <= 6; $loop++) {
<td>' . $r_date . '</td> <td>' . $r_date . '</td>
<td>' . $r_reason . '</td> <td>' . $r_reason . '</td>
</tr> '; </tr> ';
} }
?> ?>
</tbody> </tbody>
</table> </table>
</div> </div>
</div> </div>
</div> </div>
<!-- End Admin History --> <!-- End Admin History -->
<div class="col-md-12 col-lg-6">
<div class="panel panel-widget">
<div class="panel-title">
</div>
<p style="height: auto;">
<?php
$latestversion = file_get_contents('https://raw.githubusercontent.com/jordansamuel/PASTE/releases/version');
echo "Latest version: " . $latestversion . "&mdash; Installed version: " . $currentversion;
if ($currentversion == $latestversion) { echo '<br />You have the latest version'; } else { echo '<br />Your Paste installation is outdated. Get the latest version from <a href="https://sourceforge.net/projects/phpaste/files/latest/download">SourceForge</a>'; }
?>
</p>
</div>
</div>
</div>
</div>
<!-- END CONTAINER -->
<!-- Start Footer --> <div class="col-md-12 col-lg-6">
<div class="row footer"> <div class="panel panel-widget">
<div class="col-md-6 text-left"> <div class="panel-title">
<a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a> </div>
</div> <p style="height: auto;">
<div class="col-md-6 text-right"> <?php
A fork of <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a> $latestversion = file_get_contents('https://raw.githubusercontent.com/jordansamuel/PASTE/releases/version');
</div> echo "Latest version: " . $latestversion . "&mdash; Installed version: " . $currentversion;
</div> if ($currentversion == $latestversion) {
<!-- End Footer --> echo '<br />You have the latest version';
} else {
echo '<br />Your Paste installation is outdated. Get the latest version from <a href="https://sourceforge.net/projects/phpaste/files/latest/download">SourceForge</a>';
}
?>
</div> </p>
<!-- End content --> </div>
</div>
</div>
</div>
<!-- END CONTAINER -->
<!-- Start Footer -->
<div class="row footer">
<div class="col-md-6 text-left">
<a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a
href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a>
</div>
<div class="col-md-6 text-right">
A fork of <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a>
</div>
</div>
<!-- End Footer -->
</div>
<!-- End content -->
<script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script> <script type="text/javascript" src="js/bootstrap.min.js"></script>
</body> </body>
</html> </html>

View file

@ -14,11 +14,11 @@
*/ */
// PHP <5.5 compatibility // PHP <5.5 compatibility
require_once('../includes/password.php'); require_once('../includes/password.php');
session_start(); session_start();
require_once ('../config.php'); require_once('../config.php');
$conn = new PDO( $conn = new PDO(
"mysql:host=$db_host;dbname=$db_schema;charset=utf8", "mysql:host=$db_host;dbname=$db_schema;charset=utf8",
@ -27,73 +27,76 @@ $conn = new PDO(
$db_opts $db_opts
); );
$query = $conn->query('SELECT user, pass FROM admin'); $query = $conn->query('SELECT user, pass FROM admin');
while ($row = $query->fetch()) { while ($row = $query->fetch()) {
$adminid = Trim($row['user']); $adminid = Trim($row['user']);
$password = Trim($row['pass']); $password = Trim($row['pass']);
} }
if ($_SERVER['REQUEST_METHOD'] == 'POST') { if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($adminid == htmlentities(trim($_POST['username']))) { if ($adminid == htmlentities(trim($_POST['username']))) {
if (password_verify($_POST['password'], $password)) { if (password_verify($_POST['password'], $password)) {
header("Location: dashboard.php"); header("Location: dashboard.php");
$_SESSION['login'] = true; $_SESSION['login'] = true;
} else { } else {
$msg = '<div class="paste-alert alert6" style="text-align:center;"> $msg = '<div class="paste-alert alert6" style="text-align:center;">
Wrong User/Password Wrong User/Password
</div>'; </div>';
} }
} else { } else {
$msg = '<div class="paste-alert alert6" style="text-align:center;"> $msg = '<div class="paste-alert alert6" style="text-align:center;">
Wrong User/Password Wrong User/Password
</div>'; </div>';
} }
} }
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>Paste - Login</title> <title>Paste - Login</title>
<link href="css/paste.css" rel="stylesheet"> <link href="css/paste.css" rel="stylesheet">
<style type="text/css"> <style type="text/css">
body{background: #F5F5F5;} body {
</style> background: #F5F5F5;
</head> }
</style>
</head>
<body> <body>
<div class="login-form"> <div class="login-form">
<?php <?php
if (isset($msg)) { if (isset($msg)) {
echo $msg; echo $msg;
} }
?> ?>
<form action="." method="post"> <form action="." method="post">
<div class="top"> <div class="top">
<h1>Paste</h1> <h1>Paste</h1>
</div> </div>
<div class="form-area"> <div class="form-area">
<div class="group"> <div class="group">
<input type="text" class="form-control" id="username" name="username" placeholder="Username" value=""> <input type="text" class="form-control" id="username" name="username" placeholder="Username" value="">
<i class="fa fa-user"></i> <i class="fa fa-user"></i>
</div> </div>
<div class="group"> <div class="group">
<input type="password" class="form-control" id="password" name="password" placeholder="Password" value=""> <input type="password" class="form-control" id="password" name="password" placeholder="Password"
<i class="fa fa-key"></i> value="">
</div> <i class="fa fa-key"></i>
<!-- Not yet implemented </div>
<div class="checkbox checkbox-primary"> <!-- Not yet implemented
<input id="rememberme" type="checkbox" checked=""> <div class="checkbox checkbox-primary">
<label for="rememberme"> Remember Me</label> <input id="rememberme" type="checkbox" checked="">
</div> <label for="rememberme"> Remember Me</label>
--> </div>
<button type="submit" class="btn btn-default btn-block">LOGIN</button> -->
<button type="submit" class="btn btn-default btn-block">LOGIN</button>
</div> </div>
</form> </form>
</div> </div>
</body> </body>
</html> </html>

View file

@ -24,14 +24,14 @@ if (isset($_SESSION['login'])) {
if (isset($_GET['logout'])) { if (isset($_GET['logout'])) {
if (isset($_SESSION['login'])) if (isset($_SESSION['login']))
unset($_SESSION['login']); unset($_SESSION['login']);
session_destroy(); session_destroy();
header("Location: ."); header("Location: .");
exit(); exit();
} }
$date = date('jS F Y'); $date = date('jS F Y');
$ip = $_SERVER['REMOTE_ADDR']; $ip = $_SERVER['REMOTE_ADDR'];
require_once('../config.php'); require_once('../config.php');
$con = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname); $con = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname);
@ -48,17 +48,17 @@ while ($row = mysqli_fetch_array($result)) {
$last_id = $row['@last_id := MAX(id)']; $last_id = $row['@last_id := MAX(id)'];
} }
$query = "SELECT * FROM admin_history WHERE id=" . Trim($last_id); $query = "SELECT * FROM admin_history WHERE id=" . Trim($last_id);
$result = mysqli_query($con, $query); $result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) { while ($row = mysqli_fetch_array($result)) {
$last_date = $row['last_date']; $last_date = $row['last_date'];
$last_ip = $row['ip']; $last_ip = $row['ip'];
} }
if ($last_ip == $ip) { if ($last_ip == $ip) {
if ($last_date == $date) { if ($last_date == $date) {
} else { } else {
$query = "INSERT INTO admin_history (last_date,ip) VALUES ('$date','$ip')"; $query = "INSERT INTO admin_history (last_date,ip) VALUES ('$date','$ip')";
mysqli_query($con, $query); mysqli_query($con, $query);
@ -72,191 +72,193 @@ if ($last_ip == $ip) {
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>Paste - Interface</title> <title>Paste - Interface</title>
<link rel="shortcut icon" href="favicon.ico"> <link rel="shortcut icon" href="favicon.ico">
<link href="css/paste.css" rel="stylesheet" type="text/css" /> <link href="css/paste.css" rel="stylesheet" type="text/css"/>
</head> </head>
<body> <body>
<div id="top" class="clearfix">
<!-- Start App Logo -->
<div class="applogo">
<a href="../" class="logo">Paste</a>
</div>
<!-- End App Logo -->
<!-- Start Top Right --> <div id="top" class="clearfix">
<ul class="top-right"> <!-- Start App Logo -->
<li class="dropdown link"> <div class="applogo">
<a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span class="caret"></span></a> <a href="../" class="logo">Paste</a>
<ul class="dropdown-menu dropdown-menu-list dropdown-menu-right"> </div>
<li><a href="admin.php">Settings</a></li> <!-- End App Logo -->
<li><a href="?logout">Logout</a></li>
</ul>
</li>
</ul>
<!-- End Top Right -->
</div>
<!-- END TOP -->
<div class="content"> <!-- Start Top Right -->
<!-- START CONTAINER --> <ul class="top-right">
<div class="container-widget"> <li class="dropdown link">
<!-- Start Menu --> <a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span
<div class="row"> class="caret"></span></a>
<div class="col-md-12"> <ul class="dropdown-menu dropdown-menu-list dropdown-menu-right">
<ul class="panel quick-menu clearfix"> <li><a href="admin.php">Settings</a></li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li><a href="?logout">Logout</a></li>
<a href="dashboard.php"><i class="fa fa-home"></i>Dashboard</a> </ul>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> </ul>
<a href="configuration.php"><i class="fa fa-cogs"></i>Configuration</a> <!-- End Top Right -->
</li> </div>
<li class="col-xs-3 col-sm-2 col-md-1 menu-active"> <!-- END TOP -->
<a href="interface.php"><i class="fa fa-eye"></i>Interface</a>
</li> <div class="content">
<li class="col-xs-3 col-sm-2 col-md-1"> <!-- START CONTAINER -->
<a href="admin.php"><i class="fa fa-user"></i>Admin Account</a> <div class="container-widget">
</li> <!-- Start Menu -->
<li class="col-xs-3 col-sm-2 col-md-1"> <div class="row">
<a href="pastes.php"><i class="fa fa-clipboard"></i>Pastes</a> <div class="col-md-12">
</li> <ul class="panel quick-menu clearfix">
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="users.php"><i class="fa fa-users"></i>Users</a> <a href="dashboard.php"><i class="fa fa-home"></i>Dashboard</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="ipbans.php"><i class="fa fa-ban"></i>IP Bans</a> <a href="configuration.php"><i class="fa fa-cogs"></i>Configuration</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1 menu-active">
<a href="stats.php"><i class="fa fa-line-chart"></i>Statistics</a> <a href="interface.php"><i class="fa fa-eye"></i>Interface</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="ads.php"><i class="fa fa-gbp"></i>Ads</a> <a href="admin.php"><i class="fa fa-user"></i>Admin Account</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="pages.php"><i class="fa fa-file"></i>Pages</a> <a href="pastes.php"><i class="fa fa-clipboard"></i>Pastes</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="sitemap.php"><i class="fa fa-map-signs"></i>Sitemap</a> <a href="users.php"><i class="fa fa-users"></i>Users</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="tasks.php"><i class="fa fa-tasks"></i>Tasks</a> <a href="ipbans.php"><i class="fa fa-ban"></i>IP Bans</a>
</li> </li>
</ul> <li class="col-xs-3 col-sm-2 col-md-1">
</div> <a href="stats.php"><i class="fa fa-line-chart"></i>Statistics</a>
</div> </li>
<!-- End Menu --> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="ads.php"><i class="fa fa-gbp"></i>Ads</a>
<?php </li>
if ($_SERVER['REQUEST_METHOD'] == 'POST') { <li class="col-xs-3 col-sm-2 col-md-1">
$d_lang = Trim($_POST['lang']); <a href="pages.php"><i class="fa fa-file"></i>Pages</a>
$d_theme = Trim($_POST['theme']); </li>
<li class="col-xs-3 col-sm-2 col-md-1">
$query = "UPDATE interface SET lang='$d_lang', theme='$d_theme' WHERE id='1'"; <a href="sitemap.php"><i class="fa fa-map-signs"></i>Sitemap</a>
mysqli_query($con, $query); </li>
<li class="col-xs-3 col-sm-2 col-md-1">
if (mysqli_errno($con)) { <a href="tasks.php"><i class="fa fa-tasks"></i>Tasks</a>
$msg = '<div class="paste-alert alert6" style="text-align: center;"> </li>
</ul>
</div>
</div>
<!-- End Menu -->
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$d_lang = Trim($_POST['lang']);
$d_theme = Trim($_POST['theme']);
$query = "UPDATE interface SET lang='$d_lang', theme='$d_theme' WHERE id='1'";
mysqli_query($con, $query);
if (mysqli_errno($con)) {
$msg = '<div class="paste-alert alert6" style="text-align: center;">
' . mysqli_error($con) . ' ' . mysqli_error($con) . '
</div>'; </div>';
} else { } else {
$msg = '<div class="paste-alert alert3" style="text-align: center;"> $msg = '<div class="paste-alert alert3" style="text-align: center;">
Settings saved Settings saved
</div>'; </div>';
} }
} }
?> ?>
<!-- Start Interface Settings --> <!-- Start Interface Settings -->
<div class="row"> <div class="row">
<div class="col-md-12"> <div class="col-md-12">
<div class="panel panel-widget"> <div class="panel panel-widget">
<div class="panel-body"> <div class="panel-body">
<div class="login-form" style="padding:0;"> <div class="login-form" style="padding:0;">
<?php if (isset($msg)) echo $msg; ?> <?php if (isset($msg)) echo $msg; ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" class="form-area" method="post"> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" class="form-area" method="post">
<div class="form-area"> <div class="form-area">
<div class="group"> <div class="group">
<h6>Language</h6> <h6>Language</h6>
<select class="selectpicker" name="lang"> <select class="selectpicker" name="lang">
<?php <?php
$dir = '../langs'; $dir = '../langs';
$files1 = scandir($dir); $files1 = scandir($dir);
$dircount = count($files1); $dircount = count($files1);
for ($loop = 2; $loop <= $dircount - 1; $loop++) { for ($loop = 2; $loop <= $dircount - 1; $loop++) {
$fname = explode('.php', $files1[$loop]); $fname = explode('.php', $files1[$loop]);
$fname = $fname[0]; $fname = $fname[0];
$ffname = $files1[$loop]; $ffname = $files1[$loop];
if ($ffname == "index.php") {/* we don't want index.php showing */} if ($ffname == "index.php") {/* we don't want index.php showing */
else { } else {
echo '<option value="' . $ffname . '">' . $fname . '</option>'; echo '<option value="' . $ffname . '">' . $fname . '</option>';
} }
} }
?> ?>
</select> </select>
</div> </div>
<div class="group"> <div class="group">
<h6>Theme</h6> <h6>Theme</h6>
<select class="selectpicker" name="theme"> <select class="selectpicker" name="theme">
<?php <?php
// Find the current theme if not set from $_POST // Find the current theme if not set from $_POST
if ( !isset( $d_theme ) ) { if (!isset($d_theme)) {
$query = "SELECT theme FROM interface WHERE id='1'"; $query = "SELECT theme FROM interface WHERE id='1'";
$result = mysqli_query( $con, $query ); $result = mysqli_query($con, $query);
while ( $row = mysqli_fetch_array( $result ) ) { while ($row = mysqli_fetch_array($result)) {
$d_theme = $row['theme']; $d_theme = $row['theme'];
} }
} }
$dir = '../theme';
$files1 = scandir($dir);
$dircount = count($files1); $dir = '../theme';
for ($loop = 2; $loop <= $dircount - 1; $loop++) { $files1 = scandir($dir);
$fname = explode('.php', $files1[$loop]);
$fname = $fname[0];
$ffname = $files1[$loop];
echo $dir . $ffname;
if (is_dir($dir . '/' . $ffname)) {
$sel=( $d_theme == $fname )?'selected="selected"':'';
echo '<option value="' . $ffname . '" '.$sel.'>' . $fname . '</option>';
}
}
?>
</select>
</div>
<button type="submit" class="btn btn-default">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- End Interface Settings -->
</div>
<!-- END CONTAINER -->
<!-- Start Footer --> $dircount = count($files1);
<div class="row footer"> for ($loop = 2; $loop <= $dircount - 1; $loop++) {
<div class="col-md-6 text-left"> $fname = explode('.php', $files1[$loop]);
<a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a> $fname = $fname[0];
</div> $ffname = $files1[$loop];
<div class="col-md-6 text-right"> echo $dir . $ffname;
Powered by <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a> if (is_dir($dir . '/' . $ffname)) {
</div> $sel = ($d_theme == $fname) ? 'selected="selected"' : '';
</div> echo '<option value="' . $ffname . '" ' . $sel . '>' . $fname . '</option>';
<!-- End Footer --> }
</div> }
<!-- End content --> ?>
</select>
</div>
<button type="submit" class="btn btn-default">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- End Interface Settings -->
<script type="text/javascript" src="js/jquery.min.js"></script> </div>
<script type="text/javascript" src="js/bootstrap.min.js"></script> <!-- END CONTAINER -->
<script type="text/javascript" src="js/bootstrap-select.js"></script>
</body> <!-- Start Footer -->
<div class="row footer">
<div class="col-md-6 text-left">
<a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a
href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a>
</div>
<div class="col-md-6 text-right">
Powered by <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a>
</div>
</div>
<!-- End Footer -->
</div>
<!-- End content -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/bootstrap-select.js"></script>
</body>
</html> </html>

View file

@ -24,14 +24,14 @@ if (isset($_SESSION['login'])) {
if (isset($_GET['logout'])) { if (isset($_GET['logout'])) {
if (isset($_SESSION['login'])) if (isset($_SESSION['login']))
unset($_SESSION['login']); unset($_SESSION['login']);
session_destroy(); session_destroy();
header("Location: ."); header("Location: .");
exit(); exit();
} }
$date = date('jS F Y'); $date = date('jS F Y');
$ip = $_SERVER['REMOTE_ADDR']; $ip = $_SERVER['REMOTE_ADDR'];
require_once('../config.php'); require_once('../config.php');
$con = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname); $con = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname);
@ -48,17 +48,17 @@ while ($row = mysqli_fetch_array($result)) {
$last_id = $row['@last_id := MAX(id)']; $last_id = $row['@last_id := MAX(id)'];
} }
$query = "SELECT * FROM admin_history WHERE id=" . Trim($last_id); $query = "SELECT * FROM admin_history WHERE id=" . Trim($last_id);
$result = mysqli_query($con, $query); $result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) { while ($row = mysqli_fetch_array($result)) {
$last_date = $row['last_date']; $last_date = $row['last_date'];
$last_ip = $row['ip']; $last_ip = $row['ip'];
} }
if ($last_ip == $ip) { if ($last_ip == $ip) {
if ($last_date == $date) { if ($last_date == $date) {
} else { } else {
$query = "INSERT INTO admin_history (last_date,ip) VALUES ('$date','$ip')"; $query = "INSERT INTO admin_history (last_date,ip) VALUES ('$date','$ip')";
mysqli_query($con, $query); mysqli_query($con, $query);
@ -69,26 +69,26 @@ if ($last_ip == $ip) {
} }
// Get IP from form or URL // Get IP from form or URL
if ( $_SERVER['REQUEST_METHOD'] == 'POST' || isset( $_GET['banip'] ) ) { if ($_SERVER['REQUEST_METHOD'] == 'POST' || isset($_GET['banip'])) {
if ( isset( $_POST['banip'] ) ) { if (isset($_POST['banip'])) {
$ban_ip = htmlentities( Trim( $_POST['ban_ip'] ) ); $ban_ip = htmlentities(Trim($_POST['ban_ip']));
} elseif ( isset( $_GET['banip'] ) ) { } elseif (isset($_GET['banip'])) {
$ban_ip = htmlentities( Trim( $_GET['banip'] ) ); $ban_ip = htmlentities(Trim($_GET['banip']));
} }
// Check if IP is blank or already banned. // Check if IP is blank or already banned.
if ( trim($ban_ip) == '' ) { if (trim($ban_ip) == '') {
$msg = '<div class="paste-alert alert6" style="text-align: center;">Please enter an IP to ban.</div>'; $msg = '<div class="paste-alert alert6" style="text-align: center;">Please enter an IP to ban.</div>';
} else { } else {
$query = "SELECT * FROM ban_user where ip='$ban_ip'"; $query = "SELECT * FROM ban_user where ip='$ban_ip'";
$result = mysqli_query( $con, $query ); $result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows( $result ); $num_rows = mysqli_num_rows($result);
if ( $num_rows >= 1 ) { if ($num_rows >= 1) {
$msg = '<div class="paste-alert alert1" style="text-align: center;">' . $ban_ip . ' already banned</div>'; $msg = '<div class="paste-alert alert1" style="text-align: center;">' . $ban_ip . ' already banned</div>';
} else { } else {
// Valid IP which is not banned. Add to database // Valid IP which is not banned. Add to database
$query = "INSERT INTO ban_user (last_date,ip) VALUES ('$date','$ban_ip')"; $query = "INSERT INTO ban_user (last_date,ip) VALUES ('$date','$ban_ip')";
mysqli_query( $con, $query ); mysqli_query($con, $query);
if ( mysqli_errno( $con ) ) { if (mysqli_errno($con)) {
$msg = '<div class="paste-alert alert6" style="text-align: center;">' . mysqli_error($con) . '</div>'; $msg = '<div class="paste-alert alert6" style="text-align: center;">' . mysqli_error($con) . '</div>';
} else { } else {
$msg = '<div class="paste-alert alert3" style="text-align: center;">' . $ban_ip . ' added to the banlist</div>'; $msg = '<div class="paste-alert alert3" style="text-align: center;">' . $ban_ip . ' added to the banlist</div>';
@ -98,212 +98,213 @@ if ( $_SERVER['REQUEST_METHOD'] == 'POST' || isset( $_GET['banip'] ) ) {
} }
if (isset($_GET{'delete'})) { if (isset($_GET{'delete'})) {
$delete = htmlentities(Trim($_GET['delete'])); $delete = htmlentities(Trim($_GET['delete']));
$query = "DELETE FROM ban_user WHERE id=$delete"; $query = "DELETE FROM ban_user WHERE id=$delete";
$result = mysqli_query($con, $query); $result = mysqli_query($con, $query);
if (mysqli_errno($con)) { if (mysqli_errno($con)) {
$msg = '<div class="paste-alert alert6" style="text-align: center;"> $msg = '<div class="paste-alert alert6" style="text-align: center;">
' . mysqli_error($con) . ' ' . mysqli_error($con) . '
</div>'; </div>';
} else { } else {
$msg = ' $msg = '
<div class="paste-alert alert3" style="text-align: center;"> <div class="paste-alert alert3" style="text-align: center;">
IP removed from the banlist IP removed from the banlist
</div>'; </div>';
} }
} }
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>Paste - IP Bans</title> <title>Paste - IP Bans</title>
<link rel="shortcut icon" href="favicon.ico"> <link rel="shortcut icon" href="favicon.ico">
<link href="css/paste.css" rel="stylesheet" type="text/css" /> <link href="css/paste.css" rel="stylesheet" type="text/css"/>
</head> </head>
<body> <body>
<div id="top" class="clearfix">
<!-- Start App Logo -->
<div class="applogo">
<a href="../" class="logo">Paste</a>
</div>
<!-- End App Logo -->
<!-- Start Top Right --> <div id="top" class="clearfix">
<ul class="top-right"> <!-- Start App Logo -->
<li class="dropdown link"> <div class="applogo">
<a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span class="caret"></span></a> <a href="../" class="logo">Paste</a>
<ul class="dropdown-menu dropdown-menu-list dropdown-menu-right"> </div>
<li><a href="admin.php">Settings</a></li> <!-- End App Logo -->
<li><a href="?logout">Logout</a></li>
</ul>
</li>
</ul>
<!-- End Top Right -->
</div>
<!-- END TOP -->
<div class="content"> <!-- Start Top Right -->
<!-- START CONTAINER --> <ul class="top-right">
<div class="container-widget"> <li class="dropdown link">
<!-- Start Menu --> <a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span
<div class="row"> class="caret"></span></a>
<div class="col-md-12"> <ul class="dropdown-menu dropdown-menu-list dropdown-menu-right">
<ul class="panel quick-menu clearfix"> <li><a href="admin.php">Settings</a></li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li><a href="?logout">Logout</a></li>
<a href="dashboard.php"><i class="fa fa-home"></i>Dashboard</a> </ul>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> </ul>
<a href="configuration.php"><i class="fa fa-cogs"></i>Configuration</a> <!-- End Top Right -->
</li> </div>
<li class="col-xs-3 col-sm-2 col-md-1"> <!-- END TOP -->
<a href="interface.php"><i class="fa fa-eye"></i>Interface</a>
</li>
<li class="col-xs-3 col-sm-2 col-md-1">
<a href="admin.php"><i class="fa fa-user"></i>Admin Account</a>
</li>
<li class="col-xs-3 col-sm-2 col-md-1">
<a href="pastes.php"><i class="fa fa-clipboard"></i>Pastes</a>
</li>
<li class="col-xs-3 col-sm-2 col-md-1">
<a href="users.php"><i class="fa fa-users"></i>Users</a>
</li>
<li class="col-xs-3 col-sm-2 col-md-1 menu-active">
<a href="ipbans.php"><i class="fa fa-ban"></i>IP Bans</a>
</li>
<li class="col-xs-3 col-sm-2 col-md-1">
<a href="stats.php"><i class="fa fa-line-chart"></i>Statistics</a>
</li>
<li class="col-xs-3 col-sm-2 col-md-1">
<a href="ads.php"><i class="fa fa-gbp"></i>Ads</a>
</li>
<li class="col-xs-3 col-sm-2 col-md-1">
<a href="pages.php"><i class="fa fa-file"></i>Pages</a>
</li>
<li class="col-xs-3 col-sm-2 col-md-1">
<a href="sitemap.php"><i class="fa fa-map-signs"></i>Sitemap</a>
</li>
<li class="col-xs-3 col-sm-2 col-md-1">
<a href="tasks.php"><i class="fa fa-tasks"></i>Tasks</a>
</li>
</ul>
</div>
</div>
<!-- End Menu -->
<!-- Start IP bans -->
<div class="row">
<div class="col-md-12">
<div class="panel panel-widget">
<div class="panel-body">
<div class="panel-title">Ban an IP</a></div>
<?php if (isset($msg)) echo $msg; ?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="form-group">
<input type="text" class="form-control" name="ban_ip" placeholder="Enter an IP address">
<input type="hidden" name="banip" value="banip" />
</div>
<button type="submit" class="btn btn-default">Add</button>
</form>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="panel panel-widget">
<div class="panel-body">
<div class="panel-title">Banlist</div>
<table class="table table-striped">
<tbody>
<tr>
<th>Date Added</th>
<th>IP</th>
<th>Delete</th>
</tr>
<?php
$rec_limit = 20;
$query = "SELECT count(id) FROM ban_user";
$retval = mysqli_query($con, $query);
$row = mysqli_fetch_array($retval); <div class="content">
$rec_count = Trim($row[0]); <!-- START CONTAINER -->
<div class="container-widget">
<!-- Start Menu -->
<div class="row">
<div class="col-md-12">
<ul class="panel quick-menu clearfix">
<li class="col-xs-3 col-sm-2 col-md-1">
<a href="dashboard.php"><i class="fa fa-home"></i>Dashboard</a>
</li>
<li class="col-xs-3 col-sm-2 col-md-1">
<a href="configuration.php"><i class="fa fa-cogs"></i>Configuration</a>
</li>
<li class="col-xs-3 col-sm-2 col-md-1">
<a href="interface.php"><i class="fa fa-eye"></i>Interface</a>
</li>
<li class="col-xs-3 col-sm-2 col-md-1">
<a href="admin.php"><i class="fa fa-user"></i>Admin Account</a>
</li>
<li class="col-xs-3 col-sm-2 col-md-1">
<a href="pastes.php"><i class="fa fa-clipboard"></i>Pastes</a>
</li>
<li class="col-xs-3 col-sm-2 col-md-1">
<a href="users.php"><i class="fa fa-users"></i>Users</a>
</li>
<li class="col-xs-3 col-sm-2 col-md-1 menu-active">
<a href="ipbans.php"><i class="fa fa-ban"></i>IP Bans</a>
</li>
<li class="col-xs-3 col-sm-2 col-md-1">
<a href="stats.php"><i class="fa fa-line-chart"></i>Statistics</a>
</li>
<li class="col-xs-3 col-sm-2 col-md-1">
<a href="ads.php"><i class="fa fa-gbp"></i>Ads</a>
</li>
<li class="col-xs-3 col-sm-2 col-md-1">
<a href="pages.php"><i class="fa fa-file"></i>Pages</a>
</li>
<li class="col-xs-3 col-sm-2 col-md-1">
<a href="sitemap.php"><i class="fa fa-map-signs"></i>Sitemap</a>
</li>
<li class="col-xs-3 col-sm-2 col-md-1">
<a href="tasks.php"><i class="fa fa-tasks"></i>Tasks</a>
</li>
</ul>
</div>
</div>
<!-- End Menu -->
<!-- Start IP bans -->
<div class="row">
<div class="col-md-12">
<div class="panel panel-widget">
<div class="panel-body">
<div class="panel-title">Ban an IP</a></div>
<?php if (isset($msg)) echo $msg; ?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="form-group">
<input type="text" class="form-control" name="ban_ip" placeholder="Enter an IP address">
<input type="hidden" name="banip" value="banip"/>
</div>
<button type="submit" class="btn btn-default">Add</button>
</form>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="panel panel-widget">
<div class="panel-body">
<div class="panel-title">Banlist</div>
<table class="table table-striped">
<tbody>
<tr>
<th>Date Added</th>
<th>IP</th>
<th>Delete</th>
</tr>
<?php
$rec_limit = 20;
$query = "SELECT count(id) FROM ban_user";
$retval = mysqli_query($con, $query);
$row = mysqli_fetch_array($retval);
$rec_count = Trim($row[0]);
if (isset($_GET{'page'})) { // Current page
$page = $_GET{'page'} + 1;
$offset = $rec_limit * $page;
} else {
// Show first set of results
$page = 0;
$offset = 0;
}
$left_rec = $rec_count - ($page * $rec_limit);
// Set the specific query to display in the table
$sql = "SELECT * FROM ban_user ORDER BY `id` DESC LIMIT $offset, $rec_limit";
$result = mysqli_query($con, $sql);
$no = 1;
// Loop through each records
while ($row = mysqli_fetch_array($result)) {
// Populate and display result data in each row
echo '<tr>';
echo '<td>' . $row['last_date'] . '</td>';
echo '<td>' . $row['ip'] . '</td>';
$myid = $row['id'];
echo '<td>' . "<a class='btn btn-danger btn-sm' href=" . $_PHP_SELF . "?delete=" . $myid . "> Delete </a>" . '</td>';
$no++;
}
echo '</tr>';
echo '</tbody>';
echo '</table>';
// Display pagination
echo '<ul class="pager">';
if ($left_rec < $rec_limit) {
$last = $page - 2;
if ($last < 0) {
if (isset($_GET{'page'})) { // Current page } else {
$page = $_GET{'page'} + 1; echo @"<li><a href=\"$_PHP_SELF?page=$last\">Previous</a></li>";
$offset = $rec_limit * $page; }
} else { } elseif ($page == 0) {
// Show first set of results echo @"<li><a href=\"$_PHP_SELF?page=$page\">Next</a></li>";
$page = 0; } elseif ($page > 0) {
$offset = 0; $last = $page - 2;
} echo @"<li><a href=\"$_PHP_SELF?page=$last\">Previous</a></li> ";
$left_rec = $rec_count - ($page * $rec_limit); echo @"<li><a href=\"$_PHP_SELF?page=$page\">Next</a></li>";
// Set the specific query to display in the table }
$sql = "SELECT * FROM ban_user ORDER BY `id` DESC LIMIT $offset, $rec_limit"; echo '</ul>';
$result = mysqli_query($con, $sql); ?>
$no = 1;
// Loop through each records
while ($row = mysqli_fetch_array($result)) {
// Populate and display result data in each row
echo '<tr>';
echo '<td>' . $row['last_date'] . '</td>';
echo '<td>' . $row['ip'] . '</td>';
$myid = $row['id'];
echo '<td>' . "<a class='btn btn-danger btn-sm' href=" . $_PHP_SELF . "?delete=" . $myid . "> Delete </a>" . '</td>';
$no++;
}
echo '</tr>';
echo '</tbody>';
echo '</table>';
// Display pagination
echo '<ul class="pager">';
if ($left_rec < $rec_limit) {
$last = $page - 2;
if ($last < 0) {
} else {
echo @"<li><a href=\"$_PHP_SELF?page=$last\">Previous</a></li>";
}
} else if ($page == 0) {
echo @"<li><a href=\"$_PHP_SELF?page=$page\">Next</a></li>";
} else if ($page > 0) {
$last = $page - 2;
echo @"<li><a href=\"$_PHP_SELF?page=$last\">Previous</a></li> ";
echo @"<li><a href=\"$_PHP_SELF?page=$page\">Next</a></li>";
}
echo '</ul>';
?>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<!-- End IP bans --> <!-- End IP bans -->
</div> </div>
<!-- END CONTAINER --> <!-- END CONTAINER -->
<!-- Start Footer --> <!-- Start Footer -->
<div class="row footer"> <div class="row footer">
<div class="col-md-6 text-left"> <div class="col-md-6 text-left">
<a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a> <a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a
</div> href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a>
<div class="col-md-6 text-right"> </div>
Powered by <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a> <div class="col-md-6 text-right">
</div> Powered by <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a>
</div> </div>
<!-- End Footer --> </div>
</div> <!-- End Footer -->
<!-- End content --> </div>
<!-- End content -->
<script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script> <script type="text/javascript" src="js/bootstrap.min.js"></script>
</body> </body>
</html> </html>

View file

@ -7,50 +7,54 @@ For licensing, see LICENSE.md or http://ckeditor.com/license
?> ?>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<title>Sample &mdash; CKEditor</title> <title>Sample &mdash; CKEditor</title>
<link rel="stylesheet" href="sample.css"> <link rel="stylesheet" href="sample.css">
</head> </head>
<body> <body>
<h1 class="samples"> <h1 class="samples">
CKEditor &mdash; Posted Data CKEditor &mdash; Posted Data
</h1> </h1>
<table border="1" cellspacing="0" id="outputSample"> <table border="1" cellspacing="0" id="outputSample">
<colgroup><col width="120"></colgroup> <colgroup>
<thead> <col width="120">
<tr> </colgroup>
<th>Field&nbsp;Name</th> <thead>
<th>Value</th> <tr>
</tr> <th>Field&nbsp;Name</th>
</thead> <th>Value</th>
<?php </tr>
</thead>
<?php
if (!empty($_POST)) if (!empty($_POST)) {
{ foreach ($_POST as $key => $value) {
foreach ( $_POST as $key => $value ) if ((!is_string($value) && !is_numeric($value)) || !is_string($key))
{ continue;
if ( ( !is_string($value) && !is_numeric($value) ) || !is_string($key) )
continue;
$value = htmlspecialchars( (string)$value ); $value = htmlspecialchars((string)$value);
?> ?>
<tr> <tr>
<th style="vertical-align: top"><?php echo htmlspecialchars( (string)$key ); ?></th> <th style="vertical-align: top"><?php echo htmlspecialchars((string)$key); ?></th>
<td><pre class="samples"><?php echo $value; ?></pre></td> <td>
</tr> <pre class="samples"><?php echo $value; ?></pre>
<?php </td>
} </tr>
} <?php
?> }
</table> }
<div id="footer"> ?>
<hr> </table>
<p> <div id="footer">
CKEditor - The text editor for the Internet - <a class="samples" href="http://ckeditor.com/">http://ckeditor.com</a> <hr>
</p> <p>
<p id="copy"> CKEditor - The text editor for the Internet - <a class="samples"
Copyright &copy; 2003-2014, <a class="samples" href="http://cksource.com/">CKSource</a> - Frederico Knabben. All rights reserved. href="http://ckeditor.com/">http://ckeditor.com</a>
</p> </p>
</div> <p id="copy">
Copyright &copy; 2003-2014, <a class="samples" href="http://cksource.com/">CKSource</a> - Frederico Knabben. All
rights reserved.
</p>
</div>
</body> </body>
</html> </html>

View file

@ -13,4 +13,5 @@
For licensing, see LICENSE.md or <a href="http://ckeditor.com/license">http://ckeditor.com/license</a> For licensing, see LICENSE.md or <a href="http://ckeditor.com/license">http://ckeditor.com/license</a>
------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------
</pre><div style="display:none"></body> */ include "assets/posteddata.php"; ?> </pre><div style="display:none"></body> */
include "assets/posteddata.php"; ?>

View file

@ -1,42 +1,42 @@
<div class="row"> <div class="row">
<div class="col-md-12"> <div class="col-md-12">
<ul class="panel quick-menu clearfix"> <ul class="panel quick-menu clearfix">
<li class="col-xs-3 col-sm-2 col-md-1 menu-active"> <li class="col-xs-3 col-sm-2 col-md-1 menu-active">
<a href="dashboard.php"><i class="fa fa-home"></i>Dashboard</a> <a href="dashboard.php"><i class="fa fa-home"></i>Dashboard</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="configuration.php"><i class="fa fa-cogs"></i>Configuration</a> <a href="configuration.php"><i class="fa fa-cogs"></i>Configuration</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="admin.php"><i class="fa fa-user"></i>Admin Account</a> <a href="admin.php"><i class="fa fa-user"></i>Admin Account</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="reports.php"><i class="fa fa-flag"></i>Reports</a> <a href="reports.php"><i class="fa fa-flag"></i>Reports</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="pastes.php"><i class="fa fa-clipboard"></i>Pastes</a> <a href="pastes.php"><i class="fa fa-clipboard"></i>Pastes</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="users.php"><i class="fa fa-users"></i>Users</a> <a href="users.php"><i class="fa fa-users"></i>Users</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="ipbans.php"><i class="fa fa-ban"></i>IP Bans</a> <a href="ipbans.php"><i class="fa fa-ban"></i>IP Bans</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="stats.php"><i class="fa fa-line-chart"></i>Statistics</a> <a href="stats.php"><i class="fa fa-line-chart"></i>Statistics</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="ads.php"><i class="fa fa-gbp"></i>Ads</a> <a href="ads.php"><i class="fa fa-gbp"></i>Ads</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="pages.php"><i class="fa fa-file"></i>Pages</a> <a href="pages.php"><i class="fa fa-file"></i>Pages</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="sitemap.php"><i class="fa fa-map-signs"></i>Sitemap</a> <a href="sitemap.php"><i class="fa fa-map-signs"></i>Sitemap</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="tasks.php"><i class="fa fa-tasks"></i>Tasks</a> <a href="tasks.php"><i class="fa fa-tasks"></i>Tasks</a>
</li> </li>
</ul> </ul>
</div> </div>
</div> </div>

View file

@ -19,240 +19,245 @@ updateAdminHistory($conn);
if ($_SERVER['REQUEST_METHOD'] == 'POST') { if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST{'editme'})) { if (isset($_POST{'editme'})) {
$edit_me_id = htmlentities(Trim($_POST['editme'])); $edit_me_id = htmlentities(Trim($_POST['editme']));
$page_name = Trim($_POST['page_name']); $page_name = Trim($_POST['page_name']);
$page_title = Trim($_POST['page_title']); $page_title = Trim($_POST['page_title']);
$page_content = $_POST['data']; $page_content = $_POST['data'];
$query = "UPDATE pages SET last_date='$date', page_name='$page_name', page_title='$page_title', page_content='$page_content' WHERE id='$edit_me_id'"; $query = "UPDATE pages SET last_date='$date', page_name='$page_name', page_title='$page_title', page_content='$page_content' WHERE id='$edit_me_id'";
mysqli_query($con, $query); mysqli_query($con, $query);
} else { } else {
$page_name = Trim($_POST['page_name']); $page_name = Trim($_POST['page_name']);
$page_title = Trim($_POST['page_title']); $page_title = Trim($_POST['page_title']);
$page_content = $_POST['data']; $page_content = $_POST['data'];
$query = "INSERT INTO pages (last_date,page_name,page_title,page_content) VALUES ('$date','$page_name','$page_title','$page_content')"; $query = "INSERT INTO pages (last_date,page_name,page_title,page_content) VALUES ('$date','$page_name','$page_title','$page_content')";
mysqli_query($con, $query); mysqli_query($con, $query);
} }
$page_name = ""; $page_name = "";
$page_title = ""; $page_title = "";
$page_content = ""; $page_content = "";
} }
if (isset($_GET{'edit'})) { if (isset($_GET{'edit'})) {
$page_id = trim($_GET['edit']); $page_id = trim($_GET['edit']);
$sql = "SELECT * FROM pages where id='$page_id'"; $sql = "SELECT * FROM pages where id='$page_id'";
$result = mysqli_query($con, $sql); $result = mysqli_query($con, $sql);
//we loop through each records //we loop through each records
while ($row = mysqli_fetch_array($result)) { while ($row = mysqli_fetch_array($result)) {
//populate and display results data in each row //populate and display results data in each row
$page_name = $row['page_name']; $page_name = $row['page_name'];
$page_title = $row['page_title']; $page_title = $row['page_title'];
$page_content = $row['page_content']; $page_content = $row['page_content'];
} }
} }
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>Paste - Pages</title> <title>Paste - Pages</title>
<link rel="shortcut icon" href="favicon.ico"> <link rel="shortcut icon" href="favicon.ico">
<link href="css/paste.css" rel="stylesheet" type="text/css" /> <link href="css/paste.css" rel="stylesheet" type="text/css"/>
<link href="css/bootstrap3-wysihtml5.min.css" rel="stylesheet" type="text/css" /> <link href="css/bootstrap3-wysihtml5.min.css" rel="stylesheet" type="text/css"/>
</head> </head>
<body> <body>
<div id="top" class="clearfix">
<!-- Start App Logo -->
<div class="applogo">
<a href="../" class="logo">Paste</a>
</div>
<!-- End App Logo -->
<!-- Start Top Right --> <div id="top" class="clearfix">
<ul class="top-right"> <!-- Start App Logo -->
<li class="dropdown link"> <div class="applogo">
<a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span class="caret"></span></a> <a href="../" class="logo">Paste</a>
<ul class="dropdown-menu dropdown-menu-list dropdown-menu-right"> </div>
<li><a href="admin.php">Settings</a></li> <!-- End App Logo -->
<li><a href="?logout">Logout</a></li>
</ul>
</li>
</ul>
<!-- End Top Right -->
</div>
<!-- END TOP -->
<div class="content"> <!-- Start Top Right -->
<!-- START CONTAINER --> <ul class="top-right">
<div class="container-widget"> <li class="dropdown link">
<!-- Start Menu --> <a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span
<?php include 'menu.php';?> class="caret"></span></a>
<!-- End Menu --> <ul class="dropdown-menu dropdown-menu-list dropdown-menu-right">
<li><a href="admin.php">Settings</a></li>
<!-- Start Pages --> <li><a href="?logout">Logout</a></li>
<div class="row"> </ul>
<div class="col-md-12"> </li>
<div class="panel panel-widget"> </ul>
<div class="panel-body"> <!-- End Top Right -->
<div class="panel-title">Add a Page</a></div> </div>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" class="form-horizontal" method="post"> <!-- END TOP -->
<div class="control-group">
<label for="page_name">Page name (No spaces, e.g. terms_of_service)</label> <input class="span6" id=
"page_name" name="page_name" placeholder="Enter page name"
type="text" value="<?php echo isset($page_name); ?>">
</div>
<div class="control-group">
<label for="page_title">Page title</label> <input class=
"span6" id="page_title" name="page_title" placeholder=
"Enter page title" type="text" value=
"<?php echo isset($page_title); ?>">
</div>
<br />
<?php
if (isset($_GET{'edit'})) {
echo '<input type="hidden" value=' . $_GET['edit'] . 'id="editme" name="editme" />';
}
?>
<div class='control-group'>
<textarea class="span6" cols="80" id="editor1" name="data" rows="10"><?php echo isset($page_content); ?></textarea><br>
</div>
<button class="btn btn-default btn-sm">Save</button>
</form>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="panel panel-widget">
<div class="panel-body">
<div class="panel-title">Pages</div>
<table class="table table-striped">
<tbody>
<tr>
<th>Date Added</th>
<th>Page Name</th>
<th>Page Title</th>
<th>View</th>
<th>Edit</th>
<th>Delete</th>
<?php <div class="content">
if (isset($_GET{'delete'})) { <!-- START CONTAINER -->
$delete = htmlentities(Trim($_GET['delete'])); <div class="container-widget">
$query = "DELETE FROM pages WHERE id=$delete"; <!-- Start Menu -->
$result = mysqli_query($con, $query); <?php include 'menu.php'; ?>
<!-- End Menu -->
if (mysqli_errno($con)) {
echo '<div class="paste-alert alert6"> <!-- Start Pages -->
<div class="row">
<div class="col-md-12">
<div class="panel panel-widget">
<div class="panel-body">
<div class="panel-title">Add a Page</a></div>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" class="form-horizontal" method="post">
<div class="control-group">
<label for="page_name">Page name (No spaces, e.g. terms_of_service)</label> <input
class="span6" id=
"page_name" name="page_name" placeholder="Enter page name"
type="text" value="<?php echo isset($page_name); ?>">
</div>
<div class="control-group">
<label for="page_title">Page title</label> <input class=
"span6" id="page_title"
name="page_title" placeholder=
"Enter page title" type="text"
value=
"<?php echo isset($page_title); ?>">
</div>
<br/>
<?php
if (isset($_GET{'edit'})) {
echo '<input type="hidden" value=' . $_GET['edit'] . 'id="editme" name="editme" />';
}
?>
<div class='control-group'>
<textarea class="span6" cols="80" id="editor1" name="data"
rows="10"><?php echo isset($page_content); ?></textarea><br>
</div>
<button class="btn btn-default btn-sm">Save</button>
</form>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="panel panel-widget">
<div class="panel-body">
<div class="panel-title">Pages</div>
<table class="table table-striped">
<tbody>
<tr>
<th>Date Added</th>
<th>Page Name</th>
<th>Page Title</th>
<th>View</th>
<th>Edit</th>
<th>Delete</th>
<?php
if (isset($_GET{'delete'})) {
$delete = htmlentities(Trim($_GET['delete']));
$query = "DELETE FROM pages WHERE id=$delete";
$result = mysqli_query($con, $query);
if (mysqli_errno($con)) {
echo '<div class="paste-alert alert6">
' . mysqli_error($con) . ' ' . mysqli_error($con) . '
</div>'; </div>';
} else { } else {
echo ' echo '
<div class="paste-alert alert3"> <div class="paste-alert alert3">
Page deleted. Page deleted.
</div>'; </div>';
} }
} }
$rec_limit = 20; $rec_limit = 20;
$query = "SELECT count(id) FROM pages"; $query = "SELECT count(id) FROM pages";
$retval = mysqli_query($con, $query); $retval = mysqli_query($con, $query);
$row = mysqli_fetch_array($retval); $row = mysqli_fetch_array($retval);
$rec_count = Trim($row[0]); $rec_count = Trim($row[0]);
if (isset($_GET['page'])) { // Get the current page
$page = $_GET['page'] + 1;
$offset = $rec_limit * $page;
} else {
// Show first set of results
$page = 0;
$offset = 0;
}
$left_rec = $rec_count - ($page * $rec_limit);
// Set the specific query to display in the table
$sql = "SELECT * FROM pages ORDER BY `id` DESC LIMIT $offset, $rec_limit";
$result = mysqli_query($con, $sql);
$no = 1;
// Loop through each records
while ($row = mysqli_fetch_array($result)) {
// Populate and display results data in each row
echo '<tr>';
echo '<td>' . $row['last_date'] . '</td>';
echo '<td>' . $row['page_name'] . '</td>';
echo '<td>' . $row['page_title'] . '</td>';
$myid = $row['id'];
echo '<td>' . "<a class='btn btn-success btn-sm' href=../page/" . $row['page_name'] . "> View </a>" . '</td>';
echo '<td>' . "<a class='btn btn-default btn-sm' href=" . $_PHP_SELF . "?edit=" . $myid . "> Edit </a>" . '</td>';
echo '<td>' . "<a class='btn btn-danger btn-sm' href=" . $_PHP_SELF . "?delete=" . $myid . "> Delete </a>" . '</td>';
$no++;
}
echo '</tr>';
echo '</tbody>';
echo '</table>';
// Display the pagination
echo '<ul class="pager">';
if ($left_rec < $rec_limit) {
$last = $page - 2;
if ($last < 0) {
if (isset($_GET['page'])) { // Get the current page } else {
$page = $_GET['page'] + 1; echo @"<li><a href=\"$_PHP_SELF?page=$last\">Previous</a></li>";
$offset = $rec_limit * $page; }
} else { } elseif ($page == 0) {
// Show first set of results echo @"<li><a href=\"$_PHP_SELF?page=$page\">Next</a></li>";
$page = 0; } elseif ($page > 0) {
$offset = 0; $last = $page - 2;
} echo @"<li><a href=\"$_PHP_SELF?page=$last\">Previous</a></li> ";
$left_rec = $rec_count - ($page * $rec_limit); echo @"<li><a href=\"$_PHP_SELF?page=$page\">Next</a></li>";
// Set the specific query to display in the table }
$sql = "SELECT * FROM pages ORDER BY `id` DESC LIMIT $offset, $rec_limit"; echo '</ul>';
$result = mysqli_query($con, $sql); ?>
$no = 1; </div>
// Loop through each records </div>
while ($row = mysqli_fetch_array($result)) { </div>
// Populate and display results data in each row </div>
echo '<tr>'; <!-- End Pages -->
echo '<td>' . $row['last_date'] . '</td>'; </div>
echo '<td>' . $row['page_name'] . '</td>'; <!-- END CONTAINER -->
echo '<td>' . $row['page_title'] . '</td>';
$myid = $row['id'];
echo '<td>' . "<a class='btn btn-success btn-sm' href=../page/" . $row['page_name'] . "> View </a>" . '</td>';
echo '<td>' . "<a class='btn btn-default btn-sm' href=" . $_PHP_SELF . "?edit=" . $myid . "> Edit </a>" . '</td>';
echo '<td>' . "<a class='btn btn-danger btn-sm' href=" . $_PHP_SELF . "?delete=" . $myid . "> Delete </a>" . '</td>';
$no++;
}
echo '</tr>';
echo '</tbody>';
echo '</table>';
// Display the pagination
echo '<ul class="pager">';
if ($left_rec < $rec_limit) {
$last = $page - 2;
if ($last < 0) {
} else {
echo @"<li><a href=\"$_PHP_SELF?page=$last\">Previous</a></li>";
}
} else if ($page == 0) {
echo @"<li><a href=\"$_PHP_SELF?page=$page\">Next</a></li>";
} else if ($page > 0) {
$last = $page - 2;
echo @"<li><a href=\"$_PHP_SELF?page=$last\">Previous</a></li> ";
echo @"<li><a href=\"$_PHP_SELF?page=$page\">Next</a></li>";
}
echo '</ul>';
?>
</div>
</div>
</div>
</div>
<!-- End Pages -->
</div>
<!-- END CONTAINER -->
<!-- Start Footer --> <!-- Start Footer -->
<div class="row footer"> <div class="row footer">
<div class="col-md-6 text-left"> <div class="col-md-6 text-left">
<a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a> <a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a
</div> href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a>
<div class="col-md-6 text-right"> </div>
Powered by <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a> <div class="col-md-6 text-right">
</div> Powered by <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a>
</div> </div>
<!-- End Footer --> </div>
</div> <!-- End Footer -->
<!-- End content --> </div>
<!-- End content -->
<script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script> <script type="text/javascript" src="js/bootstrap.min.js"></script>
<!-- CK Editor -->
<script src="js/plugins/ckeditor/ckeditor.js" type="text/javascript"></script>
<!-- Bootstrap WYSIHTML5 --> <!-- CK Editor -->
<script src="js/bootstrap3-wysihtml5.all.min.js" type="text/javascript"></script> <script src="js/plugins/ckeditor/ckeditor.js" type="text/javascript"></script>
<script type="text/javascript"> <!-- Bootstrap WYSIHTML5 -->
$(function() { <script src="js/bootstrap3-wysihtml5.all.min.js" type="text/javascript"></script>
CKEDITOR.replace('editor1');
}); <script type="text/javascript">
</script> $(function () {
</body> CKEDITOR.replace('editor1');
</html> });
</script>
</body>
</html>
<?php mysqli_close($con); ?> <?php mysqli_close($con); ?>

View file

@ -20,231 +20,234 @@ updateAdminHistory($conn);
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>Paste - Pastes</title> <title>Paste - Pastes</title>
<link rel="shortcut icon" href="favicon.ico"> <link rel="shortcut icon" href="favicon.ico">
<link href="css/paste.css" rel="stylesheet" type="text/css" /> <link href="css/paste.css" rel="stylesheet" type="text/css"/>
<link href="css/datatables.min.css" rel="stylesheet" type="text/css" /> <link href="css/datatables.min.css" rel="stylesheet" type="text/css"/>
</head> </head>
<body> <body>
<div id="top" class="clearfix">
<!-- Start App Logo -->
<div class="applogo">
<a href="../" class="logo">Paste</a>
</div>
<!-- End App Logo -->
<!-- Start Top Right --> <div id="top" class="clearfix">
<ul class="top-right"> <!-- Start App Logo -->
<li class="dropdown link"> <div class="applogo">
<a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span class="caret"></span></a> <a href="../" class="logo">Paste</a>
<ul class="dropdown-menu dropdown-menu-list dropdown-menu-right"> </div>
<li><a href="admin.php">Settings</a></li> <!-- End App Logo -->
<li><a href="?logout">Logout</a></li>
</ul>
</li>
</ul>
<!-- End Top Right -->
</div>
<!-- END TOP -->
<div class="content"> <!-- Start Top Right -->
<!-- START CONTAINER --> <ul class="top-right">
<div class="container-widget"> <li class="dropdown link">
<!-- Start Menu --> <a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span
<?php include 'menu.php';?> class="caret"></span></a>
<!-- End Menu --> <ul class="dropdown-menu dropdown-menu-list dropdown-menu-right">
<li><a href="admin.php">Settings</a></li>
<?php <li><a href="?logout">Logout</a></li>
if (isset($_GET['delete'])) { </ul>
$delid = htmlentities(Trim($_GET['delete'])); </li>
$query = "DELETE FROM pastes WHERE id=$delid"; </ul>
$result = mysqli_query($con, $query); <!-- End Top Right -->
if (mysqli_errno($con)) { </div>
$msg = '<div class="paste-alert alert6" style="text-align: center;"> <!-- END TOP -->
<div class="content">
<!-- START CONTAINER -->
<div class="container-widget">
<!-- Start Menu -->
<?php include 'menu.php'; ?>
<!-- End Menu -->
<?php
if (isset($_GET['delete'])) {
$delid = htmlentities(Trim($_GET['delete']));
$query = "DELETE FROM pastes WHERE id=$delid";
$result = mysqli_query($con, $query);
if (mysqli_errno($con)) {
$msg = '<div class="paste-alert alert6" style="text-align: center;">
' . mysqli_error($con) . ' ' . mysqli_error($con) . '
</div>'; </div>';
} else { } else {
$msg = '<div class="paste-alert alert3" style="text-align: center;"> $msg = '<div class="paste-alert alert3" style="text-align: center;">
Paste deleted Paste deleted
</div>'; </div>';
} }
}
?>
<!-- Start Pastes --> }
<div class="row"> ?>
<div class="col-md-12">
<div class="panel panel-widget">
<?php
if (isset($_GET['details'])) {
$detail_id = htmlentities(Trim($_GET['details']));
$query = "SELECT * FROM pastes WHERE id='$detail_id'";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
$p_title = $row['title'];
$p_content = $row['content'];
$p_visible = $row['visible'];
$p_code = $row['code'];
$p_expiry = $row['expiry'];
$p_password = $row['password'];
$p_member = $row['member'];
$p_date = $row['date'];
$p_encrypt = $row['encrypt'];
$p_views = $row['views'];
$p_ip = $row['ip'];
}
if ($p_encrypt == "" || $p_encrypt == null || $p_encrypt == '0') {
$encrypt = "Not Encrypted";
} else {
$encrypt = "Encrypted";
}
if ($p_expiry == "NULL") {
$expiry = "Never";
} else {
$input_time = $p_expiry;
$current_time = mktime(date("H"), date("i"), date("s"), date("n"), date("j"), date("Y"));
if ($input_time < $current_time) {
$expiry = "Paste is expired";
} else {
$expiry = "Paste is not expired";
}
}
if ($p_password == 'NONE') {
$pass = "Not protected";
} else {
$pass = "Password protected paste";
}
if ($p_visible == '0') {
$visible = "Public";
} elseif ($p_visible == '1') {
$visible = "Unlisted";
} elseif ($p_visible == '2') {
$visible = "Private";
} else {
$visible = "Something went wrong";
}
?>
<div class="panel-title">
Details of Paste ID <?php echo $detail_id; ?>
</div>
<div class="panel-body table-responsive">
<table class="table display dataTable">
<tbody>
<tr>
<td> Username </td>
<td> <?php echo $p_member; ?> </td>
</tr>
<tr>
<td> Paste Title </td>
<td> <?php echo $p_title; ?> </td>
</tr>
<tr>
<td> Visibility </td>
<td> <?php echo $visible; ?> </td>
</tr>
<tr>
<td> Password </td>
<td> <?php echo $pass; ?> </td>
</tr>
<tr>
<td> Views </td>
<td> <?php echo $p_views; ?> </td>
</tr>
<tr>
<td> IP </td>
<td> <?php echo $p_ip; ?> </td>
</tr>
<tr>
<td> Syntax Highlighting </td>
<td> <?php echo $p_code; ?> </td>
</tr>
<tr>
<td> Expiration </td>
<td> <?php echo $expiry; ?> </td>
</tr>
<tr>
<td> Encrypted Paste </td>
<td> <?php echo $encrypt; ?></td>
</tr>
</tbody>
</table>
</div>
<?php } else { ?>
<div class="panel-body">
<div class="panel-title">
Manage Pastes
</div>
<?php if (isset($msg)) echo $msg; ?> <!-- Start Pastes -->
<div class="row">
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="pastesTable"> <div class="col-md-12">
<thead> <div class="panel panel-widget">
<tr> <?php
<th>ID</th> if (isset($_GET['details'])) {
<th>Username</th> $detail_id = htmlentities(Trim($_GET['details']));
<th>IP</th> $query = "SELECT * FROM pastes WHERE id='$detail_id'";
<th>Visibility</th> $result = mysqli_query($con, $query);
<th>More Details</th> while ($row = mysqli_fetch_array($result)) {
<th>View Paste</th> $p_title = $row['title'];
<th>Delete</th> $p_content = $row['content'];
</tr> $p_visible = $row['visible'];
</thead> $p_code = $row['code'];
<tbody> $p_expiry = $row['expiry'];
$p_password = $row['password'];
</tbody> $p_member = $row['member'];
</table> $p_date = $row['date'];
</div> $p_encrypt = $row['encrypt'];
<?php } ?> $p_views = $row['views'];
</div> $p_ip = $row['ip'];
</div> }
</div> if ($p_encrypt == "" || $p_encrypt == null || $p_encrypt == '0') {
<!-- End Admin Settings --> $encrypt = "Not Encrypted";
</div> } else {
<!-- END CONTAINER --> $encrypt = "Encrypted";
}
if ($p_expiry == "NULL") {
$expiry = "Never";
} else {
$input_time = $p_expiry;
$current_time = mktime(date("H"), date("i"), date("s"), date("n"), date("j"), date("Y"));
if ($input_time < $current_time) {
$expiry = "Paste is expired";
} else {
$expiry = "Paste is not expired";
}
}
<!-- Start Footer --> if ($p_password == 'NONE') {
<div class="row footer"> $pass = "Not protected";
<div class="col-md-6 text-left"> } else {
<a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a> $pass = "Password protected paste";
</div> }
<div class="col-md-6 text-right"> if ($p_visible == '0') {
Powered by <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a> $visible = "Public";
</div> } elseif ($p_visible == '1') {
</div> $visible = "Unlisted";
<!-- End Footer --> } elseif ($p_visible == '2') {
$visible = "Private";
} else {
$visible = "Something went wrong";
}
</div> ?>
<!-- End content --> <div class="panel-title">
Details of Paste ID <?php echo $detail_id; ?>
</div>
<script type="text/javascript" src="js/jquery.min.js"></script> <div class="panel-body table-responsive">
<script type="text/javascript" language="javascript" src="js/jquery.dataTables.js"></script> <table class="table display dataTable">
<script type="text/javascript" language="javascript" class="init"> <tbody>
$(document).ready(function() { <tr>
$('#pastesTable').dataTable( { <td> Username</td>
"processing": true, <td> <?php echo $p_member; ?> </td>
"serverSide": true, </tr>
"ajax": "ajax_pastes.php"
} ); <tr>
} ); <td> Paste Title</td>
</script> <td> <?php echo $p_title; ?> </td>
<script type="text/javascript" src="js/bootstrap.min.js"></script> </tr>
</body>
<tr>
<td> Visibility</td>
<td> <?php echo $visible; ?> </td>
</tr>
<tr>
<td> Password</td>
<td> <?php echo $pass; ?> </td>
</tr>
<tr>
<td> Views</td>
<td> <?php echo $p_views; ?> </td>
</tr>
<tr>
<td> IP</td>
<td> <?php echo $p_ip; ?> </td>
</tr>
<tr>
<td> Syntax Highlighting</td>
<td> <?php echo $p_code; ?> </td>
</tr>
<tr>
<td> Expiration</td>
<td> <?php echo $expiry; ?> </td>
</tr>
<tr>
<td> Encrypted Paste</td>
<td> <?php echo $encrypt; ?></td>
</tr>
</tbody>
</table>
</div>
<?php } else { ?>
<div class="panel-body">
<div class="panel-title">
Manage Pastes
</div>
<?php if (isset($msg)) echo $msg; ?>
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered"
id="pastesTable">
<thead>
<tr>
<th>ID</th>
<th>Username</th>
<th>IP</th>
<th>Visibility</th>
<th>More Details</th>
<th>View Paste</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<?php } ?>
</div>
</div>
</div>
<!-- End Admin Settings -->
</div>
<!-- END CONTAINER -->
<!-- Start Footer -->
<div class="row footer">
<div class="col-md-6 text-left">
<a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a
href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a>
</div>
<div class="col-md-6 text-right">
Powered by <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a>
</div>
</div>
<!-- End Footer -->
</div>
<!-- End content -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" language="javascript" src="js/jquery.dataTables.js"></script>
<script type="text/javascript" language="javascript" class="init">
$(document).ready(function () {
$('#pastesTable').dataTable({
"processing": true,
"serverSide": true,
"ajax": "ajax_pastes.php"
});
});
</script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
</body>
</html> </html>

View file

@ -24,14 +24,14 @@ if (isset($_SESSION['login'])) {
if (isset($_GET['logout'])) { if (isset($_GET['logout'])) {
if (isset($_SESSION['login'])) if (isset($_SESSION['login']))
unset($_SESSION['login']); unset($_SESSION['login']);
session_destroy(); session_destroy();
header("Location: ."); header("Location: .");
exit(); exit();
} }
$date = date('jS F Y'); $date = date('jS F Y');
$ip = $_SERVER['REMOTE_ADDR']; $ip = $_SERVER['REMOTE_ADDR'];
require_once('../config.php'); require_once('../config.php');
$con = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname); $con = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname);
@ -48,17 +48,17 @@ while ($row = mysqli_fetch_array($result)) {
$last_id = $row['@last_id := MAX(id)']; $last_id = $row['@last_id := MAX(id)'];
} }
$query = "SELECT * FROM admin_history WHERE id=" . Trim($last_id); $query = "SELECT * FROM admin_history WHERE id=" . Trim($last_id);
$result = mysqli_query($con, $query); $result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) { while ($row = mysqli_fetch_array($result)) {
$last_date = $row['last_date']; $last_date = $row['last_date'];
$last_ip = $row['ip']; $last_ip = $row['ip'];
} }
if ($last_ip == $ip) { if ($last_ip == $ip) {
if ($last_date == $date) { if ($last_date == $date) {
} else { } else {
$query = "INSERT INTO admin_history (last_date,ip) VALUES ('$date','$ip')"; $query = "INSERT INTO admin_history (last_date,ip) VALUES ('$date','$ip')";
mysqli_query($con, $query); mysqli_query($con, $query);
@ -73,247 +73,250 @@ if ($last_ip == $ip) {
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>Paste - Pastes</title> <title>Paste - Pastes</title>
<link rel="shortcut icon" href="favicon.ico"> <link rel="shortcut icon" href="favicon.ico">
<link href="css/paste.css" rel="stylesheet" type="text/css" /> <link href="css/paste.css" rel="stylesheet" type="text/css"/>
<link href="css/datatables.min.css" rel="stylesheet" type="text/css" /> <link href="css/datatables.min.css" rel="stylesheet" type="text/css"/>
</head> </head>
<body> <body>
<div id="top" class="clearfix">
<!-- Start App Logo -->
<div class="applogo">
<a href="../" class="logo">Paste</a>
</div>
<!-- End App Logo -->
<!-- Start Top Right --> <div id="top" class="clearfix">
<ul class="top-right"> <!-- Start App Logo -->
<li class="dropdown link"> <div class="applogo">
<a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span class="caret"></span></a> <a href="../" class="logo">Paste</a>
<ul class="dropdown-menu dropdown-menu-list dropdown-menu-right"> </div>
<li><a href="admin.php">Settings</a></li> <!-- End App Logo -->
<li><a href="?logout">Logout</a></li>
</ul>
</li>
</ul>
<!-- End Top Right -->
</div>
<!-- END TOP -->
<div class="content"> <!-- Start Top Right -->
<!-- START CONTAINER --> <ul class="top-right">
<div class="container-widget"> <li class="dropdown link">
<!-- Start Menu --> <a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span
<?php include 'menu.php';?> class="caret"></span></a>
<!-- End Menu --> <ul class="dropdown-menu dropdown-menu-list dropdown-menu-right">
<li><a href="admin.php">Settings</a></li>
<?php <li><a href="?logout">Logout</a></li>
if (isset($_GET['remove'])) { </ul>
$delid = htmlentities(Trim($_GET['remove'])); </li>
$query = "DELETE FROM user_reports WHERE id=$delid"; </ul>
$result = mysqli_query($con, $query); <!-- End Top Right -->
if (mysqli_errno($con)) { </div>
$msg = '<div class="paste-alert alert6" style="text-align: center;"> <!-- END TOP -->
<div class="content">
<!-- START CONTAINER -->
<div class="container-widget">
<!-- Start Menu -->
<?php include 'menu.php'; ?>
<!-- End Menu -->
<?php
if (isset($_GET['remove'])) {
$delid = htmlentities(Trim($_GET['remove']));
$query = "DELETE FROM user_reports WHERE id=$delid";
$result = mysqli_query($con, $query);
if (mysqli_errno($con)) {
$msg = '<div class="paste-alert alert6" style="text-align: center;">
' . mysqli_error($con) . ' ' . mysqli_error($con) . '
</div>'; </div>';
} else { } else {
$msg = '<div class="paste-alert alert3" style="text-align: center;"> $msg = '<div class="paste-alert alert3" style="text-align: center;">
Report Removed Report Removed
</div>'; </div>';
} }
} }
if (isset($_GET['delete'])) { if (isset($_GET['delete'])) {
$delid = htmlentities(Trim($_GET['delete'])); $delid = htmlentities(Trim($_GET['delete']));
$query = "DELETE FROM pastes WHERE id=$delid"; $query = "DELETE FROM pastes WHERE id=$delid";
$result = mysqli_query($con, $query); $result = mysqli_query($con, $query);
if (mysqli_errno($con)) { if (mysqli_errno($con)) {
$msg = '<div class="paste-alert alert6" style="text-align: center;"> $msg = '<div class="paste-alert alert6" style="text-align: center;">
' . mysqli_error($con) . ' ' . mysqli_error($con) . '
</div>'; </div>';
} else { } else {
$msg = '<div class="paste-alert alert3" style="text-align: center;"> $msg = '<div class="paste-alert alert3" style="text-align: center;">
Report Removed Report Removed
</div>'; </div>';
} }
}
?>
<!-- Start Pastes --> }
<div class="row"> ?>
<div class="col-md-12">
<div class="panel panel-widget">
<?php
if (isset($_GET['details'])) {
$detail_id = htmlentities(Trim($_GET['details']));
$query = "SELECT * FROM pastes WHERE id='$detail_id'";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
$p_title = $row['title'];
$p_content = $row['content'];
$p_visible = $row['visible'];
$p_code = $row['code'];
$p_expiry = $row['expiry'];
$p_password = $row['password'];
$p_member = $row['member'];
$p_date = $row['date'];
$p_encrypt = $row['encrypt'];
$p_views = $row['views'];
$p_ip = $row['ip'];
}
if ($p_encrypt == "" || $p_encrypt == null || $p_encrypt == '0') {
$encrypt = "Not Encrypted";
} else {
$encrypt = "Encrypted";
}
if ($p_expiry == "NULL") {
$expiry = "Never";
} else {
$input_time = $p_expiry;
$current_time = mktime(date("H"), date("i"), date("s"), date("n"), date("j"), date("Y"));
if ($input_time < $current_time) {
$expiry = "Paste is expired";
} else {
$expiry = "Paste is not expired";
}
}
if ($p_password == 'NONE') {
$pass = "Not protected";
} else {
$pass = "Password protected paste";
}
if ($p_visible == '0') {
$visible = "Public";
} elseif ($p_visible == '1') {
$visible = "Unlisted";
} elseif ($p_visible == '2') {
$visible = "Private";
} else {
$visible = "Something went wrong";
}
?>
<div class="panel-title">
Details of Paste ID <?php echo $detail_id; ?>
</div>
<div class="panel-body table-responsive">
<table class="table display dataTable">
<tbody>
<tr>
<td> Username </td>
<td> <?php echo $p_member; ?> </td>
</tr>
<tr>
<td> Paste Title </td>
<td> <?php echo $p_title; ?> </td>
</tr>
<tr>
<td> Visibility </td>
<td> <?php echo $visible; ?> </td>
</tr>
<tr>
<td> Password </td>
<td> <?php echo $pass; ?> </td>
</tr>
<tr>
<td> Views </td>
<td> <?php echo $p_views; ?> </td>
</tr>
<tr>
<td> IP </td>
<td> <?php echo $p_ip; ?> </td>
</tr>
<tr>
<td> Syntax Highlighting </td>
<td> <?php echo $p_code; ?> </td>
</tr>
<tr>
<td> Expiration </td>
<td> <?php echo $expiry; ?> </td>
</tr>
<tr>
<td> Encrypted Paste </td>
<td> <?php echo $encrypt; ?></td>
</tr>
</tbody>
</table>
</div>
<?php } else { ?>
<div class="panel-body">
<div class="panel-title">
Manage Pastes
</div>
<?php if (isset($msg)) echo $msg; ?> <!-- Start Pastes -->
<div class="row">
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="pastesTable"> <div class="col-md-12">
<thead> <div class="panel panel-widget">
<tr> <?php
<th>ID</th> if (isset($_GET['details'])) {
<th>User Reported</th> $detail_id = htmlentities(Trim($_GET['details']));
<th>Paste ID</th> $query = "SELECT * FROM pastes WHERE id='$detail_id'";
<th>Reason</th> $result = mysqli_query($con, $query);
<th>More Details</th> while ($row = mysqli_fetch_array($result)) {
<th>View Paste</th> $p_title = $row['title'];
<th>Delete</th> $p_content = $row['content'];
</tr> $p_visible = $row['visible'];
</thead> $p_code = $row['code'];
<tbody> $p_expiry = $row['expiry'];
$p_password = $row['password'];
</tbody> $p_member = $row['member'];
</table> $p_date = $row['date'];
</div> $p_encrypt = $row['encrypt'];
<?php } ?> $p_views = $row['views'];
</div> $p_ip = $row['ip'];
</div> }
</div> if ($p_encrypt == "" || $p_encrypt == null || $p_encrypt == '0') {
<!-- End Admin Settings --> $encrypt = "Not Encrypted";
</div> } else {
<!-- END CONTAINER --> $encrypt = "Encrypted";
}
if ($p_expiry == "NULL") {
$expiry = "Never";
} else {
$input_time = $p_expiry;
$current_time = mktime(date("H"), date("i"), date("s"), date("n"), date("j"), date("Y"));
if ($input_time < $current_time) {
$expiry = "Paste is expired";
} else {
$expiry = "Paste is not expired";
}
}
<!-- Start Footer --> if ($p_password == 'NONE') {
<div class="row footer"> $pass = "Not protected";
<div class="col-md-6 text-left"> } else {
<a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a> $pass = "Password protected paste";
</div> }
<div class="col-md-6 text-right"> if ($p_visible == '0') {
Powered by <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a> $visible = "Public";
</div> } elseif ($p_visible == '1') {
</div> $visible = "Unlisted";
<!-- End Footer --> } elseif ($p_visible == '2') {
$visible = "Private";
} else {
$visible = "Something went wrong";
}
</div> ?>
<!-- End content --> <div class="panel-title">
Details of Paste ID <?php echo $detail_id; ?>
</div>
<script type="text/javascript" src="js/jquery.min.js"></script> <div class="panel-body table-responsive">
<script type="text/javascript" language="javascript" src="js/jquery.dataTables.js"></script> <table class="table display dataTable">
<script type="text/javascript" language="javascript" class="init"> <tbody>
$(document).ready(function() { <tr>
$('#pastesTable').dataTable( { <td> Username</td>
"processing": true, <td> <?php echo $p_member; ?> </td>
"serverSide": true, </tr>
"ajax": "ajax_reports.php"
} ); <tr>
} ); <td> Paste Title</td>
</script> <td> <?php echo $p_title; ?> </td>
<script type="text/javascript" src="js/bootstrap.min.js"></script> </tr>
</body>
<tr>
<td> Visibility</td>
<td> <?php echo $visible; ?> </td>
</tr>
<tr>
<td> Password</td>
<td> <?php echo $pass; ?> </td>
</tr>
<tr>
<td> Views</td>
<td> <?php echo $p_views; ?> </td>
</tr>
<tr>
<td> IP</td>
<td> <?php echo $p_ip; ?> </td>
</tr>
<tr>
<td> Syntax Highlighting</td>
<td> <?php echo $p_code; ?> </td>
</tr>
<tr>
<td> Expiration</td>
<td> <?php echo $expiry; ?> </td>
</tr>
<tr>
<td> Encrypted Paste</td>
<td> <?php echo $encrypt; ?></td>
</tr>
</tbody>
</table>
</div>
<?php } else { ?>
<div class="panel-body">
<div class="panel-title">
Manage Pastes
</div>
<?php if (isset($msg)) echo $msg; ?>
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered"
id="pastesTable">
<thead>
<tr>
<th>ID</th>
<th>User Reported</th>
<th>Paste ID</th>
<th>Reason</th>
<th>More Details</th>
<th>View Paste</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<?php } ?>
</div>
</div>
</div>
<!-- End Admin Settings -->
</div>
<!-- END CONTAINER -->
<!-- Start Footer -->
<div class="row footer">
<div class="col-md-6 text-left">
<a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a
href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a>
</div>
<div class="col-md-6 text-right">
Powered by <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a>
</div>
</div>
<!-- End Footer -->
</div>
<!-- End content -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" language="javascript" src="js/jquery.dataTables.js"></script>
<script type="text/javascript" language="javascript" class="init">
$(document).ready(function () {
$('#pastesTable').dataTable({
"processing": true,
"serverSide": true,
"ajax": "ajax_reports.php"
});
});
</script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
</body>
</html> </html>

View file

@ -24,14 +24,14 @@ if (isset($_SESSION['login'])) {
if (isset($_GET['logout'])) { if (isset($_GET['logout'])) {
if (isset($_SESSION['login'])) if (isset($_SESSION['login']))
unset($_SESSION['login']); unset($_SESSION['login']);
session_destroy(); session_destroy();
header("Location: ."); header("Location: .");
exit(); exit();
} }
$date = date('jS F Y'); $date = date('jS F Y');
$ip = $_SERVER['REMOTE_ADDR']; $ip = $_SERVER['REMOTE_ADDR'];
require_once('../config.php'); require_once('../config.php');
$con = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname); $con = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname);
@ -48,17 +48,17 @@ while ($row = mysqli_fetch_array($result)) {
$last_id = $row['@last_id := MAX(id)']; $last_id = $row['@last_id := MAX(id)'];
} }
$query = "SELECT * FROM admin_history WHERE id=" . Trim($last_id); $query = "SELECT * FROM admin_history WHERE id=" . Trim($last_id);
$result = mysqli_query($con, $query); $result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) { while ($row = mysqli_fetch_array($result)) {
$last_date = $row['last_date']; $last_date = $row['last_date'];
$last_ip = $row['ip']; $last_ip = $row['ip'];
} }
if ($last_ip == $ip) { if ($last_ip == $ip) {
if ($last_date == $date) { if ($last_date == $date) {
} else { } else {
$query = "INSERT INTO admin_history (last_date,ip) VALUES ('$date','$ip')"; $query = "INSERT INTO admin_history (last_date,ip) VALUES ('$date','$ip')";
mysqli_query($con, $query); mysqli_query($con, $query);
@ -68,11 +68,11 @@ if ($last_ip == $ip) {
mysqli_query($con, $query); mysqli_query($con, $query);
} }
$query = "Select * From sitemap_options WHERE id='1'"; $query = "Select * From sitemap_options WHERE id='1'";
$result = mysqli_query($con, $query); $result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) { while ($row = mysqli_fetch_array($result)) {
$priority = $row['priority']; $priority = $row['priority'];
$changefreq = $row['changefreq']; $changefreq = $row['changefreq'];
} }
@ -80,93 +80,100 @@ while ($row = mysqli_fetch_array($result)) {
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>Paste - Sitemap</title> <title>Paste - Sitemap</title>
<link rel="shortcut icon" href="favicon.ico"> <link rel="shortcut icon" href="favicon.ico">
<link href="css/paste.css" rel="stylesheet" type="text/css" /> <link href="css/paste.css" rel="stylesheet" type="text/css"/>
</head> </head>
<body> <body>
<div id="top" class="clearfix">
<!-- Start App Logo -->
<div class="applogo">
<a href="../" class="logo">Paste</a>
</div>
<!-- End App Logo -->
<!-- Start Top Right --> <div id="top" class="clearfix">
<ul class="top-right"> <!-- Start App Logo -->
<li class="dropdown link"> <div class="applogo">
<a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span class="caret"></span></a> <a href="../" class="logo">Paste</a>
<ul class="dropdown-menu dropdown-menu-list dropdown-menu-right"> </div>
<li><a href="admin.php">Settings</a></li> <!-- End App Logo -->
<li><a href="?logout">Logout</a></li>
</ul>
</li>
</ul>
<!-- End Top Right -->
</div>
<!-- END TOP -->
<div class="content"> <!-- Start Top Right -->
<!-- START CONTAINER --> <ul class="top-right">
<div class="container-widget"> <li class="dropdown link">
<!-- Start Menu --> <a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span
<?php include 'menu.php';?> class="caret"></span></a>
<!-- End Menu --> <ul class="dropdown-menu dropdown-menu-list dropdown-menu-right">
<li><a href="admin.php">Settings</a></li>
<?php <li><a href="?logout">Logout</a></li>
if ($_SERVER['REQUEST_METHOD'] == 'POST') { </ul>
$priority = htmlentities(Trim($_POST['priority'])); </li>
$changefreq = htmlentities(Trim($_POST['changefreq'])); </ul>
<!-- End Top Right -->
$query = "UPDATE sitemap_options SET priority='$priority', changefreq='$changefreq' WHERE id='1'"; </div>
mysqli_query($con, $query); <!-- END TOP -->
if (mysqli_errno($con)) { <div class="content">
echo '<div class="paste-alert alert6"> <!-- START CONTAINER -->
<div class="container-widget">
<!-- Start Menu -->
<?php include 'menu.php'; ?>
<!-- End Menu -->
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$priority = htmlentities(Trim($_POST['priority']));
$changefreq = htmlentities(Trim($_POST['changefreq']));
$query = "UPDATE sitemap_options SET priority='$priority', changefreq='$changefreq' WHERE id='1'";
mysqli_query($con, $query);
if (mysqli_errno($con)) {
echo '<div class="paste-alert alert6">
' . mysqli_error($con) . ' ' . mysqli_error($con) . '
</div>'; </div>';
} else { } else {
echo ' echo '
<div class="paste-alert alert3"> <div class="paste-alert alert3">
Sitemap saved. Sitemap saved.
</div>'; </div>';
} }
} }
?> ?>
<!-- Start Sitemap -->
<div class="row">
<div class="col-md-12">
<div class="panel panel-widget">
<div class="panel-body">
<div class="panel-title">Sitemap</a></div>
<?php if (isset($msg)) echo $msg; ?>
<form method="POST" action="sitemap.php">
<div class="form-group">
<label for="changefreq">Change Frequency</label>
<input type="text" placeholder="Enter frequency range" name="changefreq" id="changefreq" value="<?php echo $changefreq; ?>" class="form-control">
</div>
<div class="form-group">
<label for="priority">Priority Level</label>
<input type="text" placeholder="Enter priority..." id="priority" name="priority" value="<?php echo $priority; ?>" class="form-control">
</div>
<button class="btn btn-default" type="submit">Submit</button> <!-- Start Sitemap -->
</form> <div class="row">
<br /> <div class="col-md-12">
<?php <div class="panel panel-widget">
if (isset($_GET['re'])) { <div class="panel-body">
unlink('../sitemap.xml'); <div class="panel-title">Sitemap</a></div>
// which protocol are we on <?php if (isset($msg)) echo $msg; ?>
$protocol = paste_protocol(); <form method="POST" action="sitemap.php">
// level up, dirty but meh <div class="form-group">
$x=2;$path = dirname($_SERVER['PHP_SELF']); while(max(0, --$x)) { $levelup = dirname($path); } <label for="changefreq">Change Frequency</label>
$c_date = date('Y-m-d'); <input type="text" placeholder="Enter frequency range" name="changefreq" id="changefreq"
$data = '<?xml version="1.0" encoding="UTF-8"?> value="<?php echo $changefreq; ?>" class="form-control">
</div>
<div class="form-group">
<label for="priority">Priority Level</label>
<input type="text" placeholder="Enter priority..." id="priority" name="priority"
value="<?php echo $priority; ?>" class="form-control">
</div>
<button class="btn btn-default" type="submit">Submit</button>
</form>
<br/>
<?php
if (isset($_GET['re'])) {
unlink('../sitemap.xml');
// which protocol are we on
$protocol = paste_protocol();
// level up, dirty but meh
$x = 2;
$path = dirname($_SERVER['PHP_SELF']);
while (max(0, --$x)) {
$levelup = dirname($path);
}
$c_date = date('Y-m-d');
$data = '<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url> <url>
<loc>' . $protocol . $_SERVER['SERVER_NAME'] . $levelup . '/</loc> <loc>' . $protocol . $_SERVER['SERVER_NAME'] . $levelup . '/</loc>
@ -175,32 +182,32 @@ while ($row = mysqli_fetch_array($result)) {
<lastmod>' . $c_date . '</lastmod> <lastmod>' . $c_date . '</lastmod>
</url> </url>
</urlset>'; </urlset>';
file_put_contents("../sitemap.xml", $data); file_put_contents("../sitemap.xml", $data);
$rec_limit = 10; $rec_limit = 10;
$query = "SELECT count(id) FROM pastes"; $query = "SELECT count(id) FROM pastes";
$retval = mysqli_query($con, $query); $retval = mysqli_query($con, $query);
$row = mysqli_fetch_array($retval); $row = mysqli_fetch_array($retval);
$rec_count = Trim($row[0]); $rec_count = Trim($row[0]);
$offset = 0; $offset = 0;
// Set the specific query to display in the table // Set the specific query to display in the table
$sql = "SELECT * FROM `pastes` WHERE visible='0' LIMIT $offset, $rec_count "; $sql = "SELECT * FROM `pastes` WHERE visible='0' LIMIT $offset, $rec_count ";
$result = mysqli_query($con, $sql); $result = mysqli_query($con, $sql);
// Loop through each record // Loop through each record
while ($row = mysqli_fetch_array($result)) { while ($row = mysqli_fetch_array($result)) {
$paste_id = Trim($row['id']); $paste_id = Trim($row['id']);
$site_data = file_get_contents("../sitemap.xml"); $site_data = file_get_contents("../sitemap.xml");
$site_data = str_replace("</urlset>", "", $site_data); $site_data = str_replace("</urlset>", "", $site_data);
if ($mod_rewrite == "1") { if ($mod_rewrite == "1") {
$server_name = $protocol . $_SERVER['SERVER_NAME'] . $levelup . "/" . $paste_id; $server_name = $protocol . $_SERVER['SERVER_NAME'] . $levelup . "/" . $paste_id;
} else { } else {
$server_name = $protocol . $_SERVER['SERVER_NAME'] . $levelup . "/paste.php?id=" . $paste_id; $server_name = $protocol . $_SERVER['SERVER_NAME'] . $levelup . "/paste.php?id=" . $paste_id;
} }
$c_date = date('Y-m-d'); $c_date = date('Y-m-d');
$c_sitemap = ' $c_sitemap = '
<url> <url>
<loc>' . $server_name . '</loc> <loc>' . $server_name . '</loc>
<priority>' . $priority . '</priority> <priority>' . $priority . '</priority>
@ -208,45 +215,47 @@ while ($row = mysqli_fetch_array($result)) {
<lastmod>' . $c_date . '</lastmod> <lastmod>' . $c_date . '</lastmod>
</url> </url>
</urlset>'; </urlset>';
$full_map = $site_data . $c_sitemap; $full_map = $site_data . $c_sitemap;
file_put_contents("../sitemap.xml", $full_map); file_put_contents("../sitemap.xml", $full_map);
} }
} }
?> ?>
<?php <?php
if (isset($_GET['re'])) { if (isset($_GET['re'])) {
echo ' echo '
<div class="paste-alert alert3"> <div class="paste-alert alert3">
sitemap.xml rebuilt sitemap.xml rebuilt
</div>'; </div>';
} }
?> ?>
<form method="GET" action="sitemap.php"> <form method="GET" action="sitemap.php">
<button class="btn btn-default" name="re" id="re" type="submit">Generate sitemap.xml</button> <button class="btn btn-default" name="re" id="re" type="submit">Generate sitemap.xml
</form> </button>
</div> </form>
</div> </div>
</div> </div>
</div> </div>
<!-- End Sitemap --> </div>
</div> <!-- End Sitemap -->
<!-- END CONTAINER --> </div>
<!-- END CONTAINER -->
<!-- Start Footer --> <!-- Start Footer -->
<div class="row footer"> <div class="row footer">
<div class="col-md-6 text-left"> <div class="col-md-6 text-left">
<a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a> <a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a
</div> href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a>
<div class="col-md-6 text-right"> </div>
Powered by <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a> <div class="col-md-6 text-right">
</div> Powered by <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a>
</div> </div>
<!-- End Footer --> </div>
</div> <!-- End Footer -->
<!-- End content --> </div>
<!-- End content -->
<script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script> <script type="text/javascript" src="js/bootstrap.min.js"></script>
</body> </body>
</html> </html>

View file

@ -1,417 +1,397 @@
<?php <?php
class SSP { class SSP {
/** /**
* Create the data output array for the DataTables rows * Create the data output array for the DataTables rows
* *
* @param array $columns Column information array * @param array $columns Column information array
* @param array $data Data from the SQL get * @param array $data Data from the SQL get
* @return array Formatted data in a row based format * @return array Formatted data in a row based format
*/ */
static function data_output ( $columns, $data ) static function data_output($columns, $data) {
{ $out = array();
$out = array();
for ( $i=0, $ien=count($data) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($data); $i < $ien; $i++) {
$row = array(); $row = array();
for ( $j=0, $jen=count($columns) ; $j<$jen ; $j++ ) { for ($j = 0, $jen = count($columns); $j < $jen; $j++) {
$column = $columns[$j]; $column = $columns[$j];
// Is there a formatter? // Is there a formatter?
if ( isset( $column['formatter'] ) ) { if (isset($column['formatter'])) {
$row[ $column['dt'] ] = $column['formatter']( $data[$i][ $column['db'] ], $data[$i] ); $row[$column['dt']] = $column['formatter']($data[$i][$column['db']], $data[$i]);
} } else {
else { $row[$column['dt']] = $data[$i][$columns[$j]['db']];
$row[ $column['dt'] ] = $data[$i][ $columns[$j]['db'] ]; }
} }
}
$out[] = $row; $out[] = $row;
} }
return $out; return $out;
} }
/** /**
* Paging * Paging
* *
* Construct the LIMIT clause for server-side processing SQL query * Construct the LIMIT clause for server-side processing SQL query
* *
* @param array $request Data sent to server by DataTables * @param array $request Data sent to server by DataTables
* @param array $columns Column information array * @param array $columns Column information array
* @return string SQL limit clause * @return string SQL limit clause
*/ */
static function limit ( $request, $columns ) static function limit($request, $columns) {
{ $limit = '';
$limit = '';
if ( isset($request['start']) && $request['length'] != -1 ) { if (isset($request['start']) && $request['length'] != -1) {
$limit = "LIMIT ".intval($request['start']).", ".intval($request['length']); $limit = "LIMIT " . intval($request['start']) . ", " . intval($request['length']);
} }
return $limit; return $limit;
} }
/** /**
* Ordering * Ordering
* *
* Construct the ORDER BY clause for server-side processing SQL query * Construct the ORDER BY clause for server-side processing SQL query
* *
* @param array $request Data sent to server by DataTables * @param array $request Data sent to server by DataTables
* @param array $columns Column information array * @param array $columns Column information array
* @return string SQL order by clause * @return string SQL order by clause
*/ */
static function order ( $request, $columns ) static function order($request, $columns) {
{ $order = '';
$order = '';
if ( isset($request['order']) && count($request['order']) ) { if (isset($request['order']) && count($request['order'])) {
$orderBy = array(); $orderBy = array();
$dtColumns = self::pluck( $columns, 'dt' ); $dtColumns = self::pluck($columns, 'dt');
for ( $i=0, $ien=count($request['order']) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($request['order']); $i < $ien; $i++) {
// Convert the column index into the column data property // Convert the column index into the column data property
$columnIdx = intval($request['order'][$i]['column']); $columnIdx = intval($request['order'][$i]['column']);
$requestColumn = $request['columns'][$columnIdx]; $requestColumn = $request['columns'][$columnIdx];
$columnIdx = array_search( $requestColumn['data'], $dtColumns ); $columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $columns[ $columnIdx ]; $column = $columns[$columnIdx];
if ( $requestColumn['orderable'] == 'true' ) { if ($requestColumn['orderable'] == 'true') {
$dir = $request['order'][$i]['dir'] === 'DESC' ? $dir = $request['order'][$i]['dir'] === 'DESC' ?
'ASC' : 'ASC' :
'DESC'; 'DESC';
$orderBy[] = '`'.$column['db'].'` '.$dir; $orderBy[] = '`' . $column['db'] . '` ' . $dir;
} }
} }
$order = 'ORDER BY '.implode(', ', $orderBy); $order = 'ORDER BY ' . implode(', ', $orderBy);
} }
return $order; return $order;
} }
/** /**
* Searching / Filtering * Searching / Filtering
* *
* Construct the WHERE clause for server-side processing SQL query. * Construct the WHERE clause for server-side processing SQL query.
* *
* NOTE this does not match the built-in DataTables filtering which does it * NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here performance on large * word by word on any field. It's possible to do here performance on large
* databases would be very poor * databases would be very poor
* *
* @param array $request Data sent to server by DataTables * @param array $request Data sent to server by DataTables
* @param array $columns Column information array * @param array $columns Column information array
* @param array $bindings Array of values for PDO bindings, used in the * @param array $bindings Array of values for PDO bindings, used in the
* sql_exec() function * sql_exec() function
* @return string SQL where clause * @return string SQL where clause
*/ */
static function filter ( $request, $columns, &$bindings ) static function filter($request, $columns, &$bindings) {
{ $globalSearch = array();
$globalSearch = array(); $columnSearch = array();
$columnSearch = array(); $dtColumns = self::pluck($columns, 'dt');
$dtColumns = self::pluck( $columns, 'dt' );
if ( isset($request['search']) && $request['search']['value'] != '' ) { if (isset($request['search']) && $request['search']['value'] != '') {
$str = $request['search']['value']; $str = $request['search']['value'];
for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($request['columns']); $i < $ien; $i++) {
$requestColumn = $request['columns'][$i]; $requestColumn = $request['columns'][$i];
$columnIdx = array_search( $requestColumn['data'], $dtColumns ); $columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $columns[ $columnIdx ]; $column = $columns[$columnIdx];
if ( $requestColumn['searchable'] == 'true' ) { if ($requestColumn['searchable'] == 'true') {
$binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR ); $binding = self::bind($bindings, '%' . $str . '%', PDO::PARAM_STR);
$globalSearch[] = "`".$column['db']."` LIKE ".$binding; $globalSearch[] = "`" . $column['db'] . "` LIKE " . $binding;
} }
} }
} }
// Individual column filtering // Individual column filtering
for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($request['columns']); $i < $ien; $i++) {
$requestColumn = $request['columns'][$i]; $requestColumn = $request['columns'][$i];
$columnIdx = array_search( $requestColumn['data'], $dtColumns ); $columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $columns[ $columnIdx ]; $column = $columns[$columnIdx];
$str = $requestColumn['search']['value']; $str = $requestColumn['search']['value'];
if ( $requestColumn['searchable'] == 'true' && if ($requestColumn['searchable'] == 'true' &&
$str != '' ) { $str != '') {
$binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR ); $binding = self::bind($bindings, '%' . $str . '%', PDO::PARAM_STR);
$columnSearch[] = "`".$column['db']."` LIKE ".$binding; $columnSearch[] = "`" . $column['db'] . "` LIKE " . $binding;
} }
} }
// Combine the filters into a single string // Combine the filters into a single string
$where = ''; $where = '';
if ( count( $globalSearch ) ) { if (count($globalSearch)) {
$where = '('.implode(' OR ', $globalSearch).')'; $where = '(' . implode(' OR ', $globalSearch) . ')';
} }
if ( count( $columnSearch ) ) { if (count($columnSearch)) {
$where = $where === '' ? $where = $where === '' ?
implode(' AND ', $columnSearch) : implode(' AND ', $columnSearch) :
$where .' AND '. implode(' AND ', $columnSearch); $where . ' AND ' . implode(' AND ', $columnSearch);
} }
if ( $where !== '' ) { if ($where !== '') {
$where = 'WHERE '.$where; $where = 'WHERE ' . $where;
} }
return $where; return $where;
} }
/** /**
* Perform the SQL queries needed for an server-side processing requested, * Perform the SQL queries needed for an server-side processing requested,
* utilising the helper functions of this class, limit(), order() and * utilising the helper functions of this class, limit(), order() and
* filter() among others. The returned array is ready to be encoded as JSON * filter() among others. The returned array is ready to be encoded as JSON
* in response to an SSP request, or can be modified if needed before * in response to an SSP request, or can be modified if needed before
* sending back to the client. * sending back to the client.
* *
* @param array $request Data sent to server by DataTables * @param array $request Data sent to server by DataTables
* @param array $sql_details SQL connection details - see sql_connect() * @param array $sql_details SQL connection details - see sql_connect()
* @param string $table SQL table to query * @param string $table SQL table to query
* @param string $primaryKey Primary key of the table * @param string $primaryKey Primary key of the table
* @param array $columns Column information array * @param array $columns Column information array
* @return array Server-side processing response array * @return array Server-side processing response array
*/ */
static function simple ( $request, $sql_details, $table, $primaryKey, $columns, $columns2 ) static function simple($request, $sql_details, $table, $primaryKey, $columns, $columns2) {
{ $bindings = array();
$bindings = array(); $db = self::sql_connect($sql_details);
$db = self::sql_connect( $sql_details );
// Build the SQL query string from the request // Build the SQL query string from the request
$limit = self::limit( $request, $columns ); $limit = self::limit($request, $columns);
$order = self::order( $request, $columns ); $order = self::order($request, $columns);
$where = self::filter( $request, $columns, $bindings ); $where = self::filter($request, $columns, $bindings);
// Main query to actually get the data // Main query to actually get the data
$data = self::Ssql_exec($db, $bindings, $data = self::Ssql_exec($db, $bindings,
"SELECT SQL_CALC_FOUND_ROWS `".implode("`, `", self::pluck($columns, 'db'))."` "SELECT SQL_CALC_FOUND_ROWS `" . implode("`, `", self::pluck($columns, 'db')) . "`
FROM `$table` FROM `$table`
$where $where
$order $order
$limit" $limit"
); );
// Data set length after filtering // Data set length after filtering
$resFilterLength = self::sql_exec( $db, $resFilterLength = self::sql_exec($db,
"SELECT FOUND_ROWS()" "SELECT FOUND_ROWS()"
); );
$recordsFiltered = $resFilterLength[0][0]; $recordsFiltered = $resFilterLength[0][0];
// Total data set length // Total data set length
$resTotalLength = self::sql_exec( $db, $resTotalLength = self::sql_exec($db,
"SELECT COUNT(`{$primaryKey}`) "SELECT COUNT(`{$primaryKey}`)
FROM `$table`" FROM `$table`"
); );
$recordsTotal = $resTotalLength[0][0]; $recordsTotal = $resTotalLength[0][0];
/* /*
* Output * Output
*/ */
return array( return array(
"draw" => intval( $request['draw'] ), "draw" => intval($request['draw']),
"recordsTotal" => intval( $recordsTotal ), "recordsTotal" => intval($recordsTotal),
"recordsFiltered" => intval( $recordsFiltered ), "recordsFiltered" => intval($recordsFiltered),
"data" => self::data_output( $columns2, $data ) "data" => self::data_output($columns2, $data)
); );
} }
/** /**
* Connect to the database * Connect to the database
* *
* @param array $sql_details SQL server connection details array, with the * @param array $sql_details SQL server connection details array, with the
* properties: * properties:
* * host - host name * * host - host name
* * db - database name * * db - database name
* * user - user name * * user - user name
* * pass - user password * * pass - user password
* @return resource Database connection handle * @return resource Database connection handle
*/ */
static function sql_connect ( $sql_details ) static function sql_connect($sql_details) {
{ try {
try { $db = @new PDO(
$db = @new PDO( "mysql:host={$sql_details['host']};dbname={$sql_details['db']}",
"mysql:host={$sql_details['host']};dbname={$sql_details['db']}", $sql_details['user'],
$sql_details['user'], $sql_details['pass'],
$sql_details['pass'], array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ) );
); } catch (PDOException $e) {
} self::fatal(
catch (PDOException $e) { "An error occurred while connecting to the database. " .
self::fatal( "The error reported by the server was: " . $e->getMessage()
"An error occurred while connecting to the database. ". );
"The error reported by the server was: ".$e->getMessage() }
);
}
return $db; return $db;
} }
/** /**
* Execute an SQL query on the database * Execute an SQL query on the database
* *
* @param resource $db Database handler * @param resource $db Database handler
* @param array $bindings Array of PDO binding values from bind() to be * @param array $bindings Array of PDO binding values from bind() to be
* used for safely escaping strings. Note that this can be given as the * used for safely escaping strings. Note that this can be given as the
* SQL query string if no bindings are required. * SQL query string if no bindings are required.
* @param string $sql SQL query to execute. * @param string $sql SQL query to execute.
* @return array Result from the query (all rows) * @return array Result from the query (all rows)
*/ */
static function sql_exec ( $db, $bindings, $sql=null ) static function sql_exec($db, $bindings, $sql = null) {
{ // Argument shifting
// Argument shifting if ($sql === null) {
if ( $sql === null ) { $sql = $bindings;
$sql = $bindings; }
}
$stmt = $db->prepare( $sql ); $stmt = $db->prepare($sql);
//echo $sql; //echo $sql;
// Bind parameters // Bind parameters
if ( is_array( $bindings ) ) { if (is_array($bindings)) {
for ( $i=0, $ien=count($bindings) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($bindings); $i < $ien; $i++) {
$binding = $bindings[$i]; $binding = $bindings[$i];
$stmt->bindValue( $binding['key'], $binding['val'], $binding['type'] ); $stmt->bindValue($binding['key'], $binding['val'], $binding['type']);
} }
} }
// Execute // Execute
try { try {
$stmt->execute(); $stmt->execute();
} } catch (PDOException $e) {
catch (PDOException $e) { self::fatal("An SQL error occurred: " . $e->getMessage());
self::fatal( "An SQL error occurred: ".$e->getMessage() ); }
} $result = $stmt->fetchAll();
$result= $stmt->fetchAll(); return $result;
return $result; }
}
static function Ssql_exec ($db, $bindings, $sql=null )
{
// Argument shifting
if ( $sql === null ) {
$sql = $bindings;
}
$stmt = $db->prepare( $sql ); static function Ssql_exec($db, $bindings, $sql = null) {
// Argument shifting
if ($sql === null) {
$sql = $bindings;
}
// Bind parameters $stmt = $db->prepare($sql);
if ( is_array( $bindings ) ) {
for ( $i=0, $ien=count($bindings) ; $i<$ien ; $i++ ) {
$binding = $bindings[$i];
$stmt->bindValue( $binding['key'], $binding['val'], $binding['type'] );
}
}
// Execute // Bind parameters
try { if (is_array($bindings)) {
$stmt->execute(); for ($i = 0, $ien = count($bindings); $i < $ien; $i++) {
} $binding = $bindings[$i];
catch (PDOException $e) { $stmt->bindValue($binding['key'], $binding['val'], $binding['type']);
self::fatal( "An SQL error occurred: ".$e->getMessage() ); }
} }
// Execute
try {
$stmt->execute();
} catch (PDOException $e) {
self::fatal("An SQL error occurred: " . $e->getMessage());
}
$loop = '0'; $loop = '0';
while ($arr = $stmt->fetch(PDO::FETCH_ASSOC)) { while ($arr = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[$loop]['id']= $arr['id']; $result[$loop]['id'] = $arr['id'];
$result[$loop]['member']= $arr['member']; $result[$loop]['member'] = $arr['member'];
$result[$loop]['ip']= $arr['ip']; $result[$loop]['ip'] = $arr['ip'];
$vis = Trim($arr['visible']); $vis = Trim($arr['visible']);
if ($vis == '0') if ($vis == '0') {
{ $result[$loop]['visible'] = "Public";
$result[$loop]['visible'] = "Public"; } elseif ($vis == '1') {
$result[$loop]['visible'] = "Unlisted";
} elseif ($vis == '2') {
$result[$loop]['visible'] = "Private";
}
$myid = $arr['id'];
$result[$loop]['details'] = "<a class='btn btn-default btn-sm' href=pastes.php?details=" . $myid . "> Details </a>";
$result[$loop]['view'] = "<a class='btn btn-success btn-sm' href=../paste.php?id=" . $myid . "> View </a>";
$result[$loop]['delete'] = "<a class='btn btn-danger btn-sm' href=pastes.php?delete=" . $myid . "> Delete </a> <a class='btn btn-link btn-sm' href=ipbans.php?banip=" . $arr['ip'] . "> Ban IP </a>";
$loop = $loop + 1;
} }
elseif ($vis == '1') // Return all
{ return $result;
$result[$loop]['visible'] = "Unlisted"; }
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Internal methods
*/
/**
* Throw a fatal error.
*
* This writes out an error message in a JSON string which DataTables will
* see and show to the user in the browser.
*
* @param string $msg Message to send to the client
*/
static function fatal($msg) {
echo json_encode(array(
"error" => $msg
));
exit(0);
}
/**
* Create a PDO binding key which can be used for escaping variables safely
* when executing a query with sql_exec()
*
* @param array &$a Array of bindings
* @param * $val Value to bind
* @param int $type PDO field type
* @return string Bound key to be used in the SQL where this parameter
* would be used.
*/
static function bind(&$a, $val, $type) {
$key = ':binding_' . count($a);
$a[] = array(
'key' => $key,
'val' => $val,
'type' => $type
);
return $key;
}
/**
* Pull a particular property from each assoc. array in a numeric array,
* returning and array of the property values from each item.
*
* @param array $a Array to get data from
* @param string $prop Property to read
* @return array Array of property values
*/
static function pluck($a, $prop) {
$out = array();
for ($i = 0, $len = count($a); $i < $len; $i++) {
$out[] = $a[$i][$prop];
} }
elseif ($vis == '2')
{
$result[$loop]['visible'] = "Private";
}
$myid = $arr['id'];
$result[$loop]['details'] ="<a class='btn btn-default btn-sm' href=pastes.php?details=".$myid."> Details </a>";
$result[$loop]['view'] = "<a class='btn btn-success btn-sm' href=../paste.php?id=".$myid."> View </a>";
$result[$loop]['delete'] ="<a class='btn btn-danger btn-sm' href=pastes.php?delete=".$myid."> Delete </a> <a class='btn btn-link btn-sm' href=ipbans.php?banip=".$arr['ip']."> Ban IP </a>";
$loop = $loop +1;
}
// Return all
return $result;
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * return $out;
* Internal methods }
*/
/**
* Throw a fatal error.
*
* This writes out an error message in a JSON string which DataTables will
* see and show to the user in the browser.
*
* @param string $msg Message to send to the client
*/
static function fatal ( $msg )
{
echo json_encode( array(
"error" => $msg
) );
exit(0);
}
/**
* Create a PDO binding key which can be used for escaping variables safely
* when executing a query with sql_exec()
*
* @param array &$a Array of bindings
* @param * $val Value to bind
* @param int $type PDO field type
* @return string Bound key to be used in the SQL where this parameter
* would be used.
*/
static function bind ( &$a, $val, $type )
{
$key = ':binding_'.count( $a );
$a[] = array(
'key' => $key,
'val' => $val,
'type' => $type
);
return $key;
}
/**
* Pull a particular property from each assoc. array in a numeric array,
* returning and array of the property values from each item.
*
* @param array $a Array to get data from
* @param string $prop Property to read
* @return array Array of property values
*/
static function pluck ( $a, $prop )
{
$out = array();
for ( $i=0, $len=count($a) ; $i<$len ; $i++ ) {
$out[] = $a[$i][$prop];
}
return $out;
}
} }
?> ?>

View file

@ -1,418 +1,398 @@
<?php <?php
class SSP { class SSP {
/** /**
* Create the data output array for the DataTables rows * Create the data output array for the DataTables rows
* *
* @param array $columns Column information array * @param array $columns Column information array
* @param array $data Data from the SQL get * @param array $data Data from the SQL get
* @return array Formatted data in a row based format * @return array Formatted data in a row based format
*/ */
static function data_output ( $columns, $data ) static function data_output($columns, $data) {
{ $out = array();
$out = array();
for ( $i=0, $ien=count($data) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($data); $i < $ien; $i++) {
$row = array(); $row = array();
for ( $j=0, $jen=count($columns) ; $j<$jen ; $j++ ) { for ($j = 0, $jen = count($columns); $j < $jen; $j++) {
$column = $columns[$j]; $column = $columns[$j];
// Is there a formatter? // Is there a formatter?
if ( isset( $column['formatter'] ) ) { if (isset($column['formatter'])) {
$row[ $column['dt'] ] = $column['formatter']( $data[$i][ $column['db'] ], $data[$i] ); $row[$column['dt']] = $column['formatter']($data[$i][$column['db']], $data[$i]);
} } else {
else { $row[$column['dt']] = $data[$i][$columns[$j]['db']];
$row[ $column['dt'] ] = $data[$i][ $columns[$j]['db'] ]; }
} }
}
$out[] = $row; $out[] = $row;
} }
return $out; return $out;
} }
/** /**
* Paging * Paging
* *
* Construct the LIMIT clause for server-side processing SQL query * Construct the LIMIT clause for server-side processing SQL query
* *
* @param array $request Data sent to server by DataTables * @param array $request Data sent to server by DataTables
* @param array $columns Column information array * @param array $columns Column information array
* @return string SQL limit clause * @return string SQL limit clause
*/ */
static function limit ( $request, $columns ) static function limit($request, $columns) {
{ $limit = '';
$limit = '';
if ( isset($request['start']) && $request['length'] != -1 ) { if (isset($request['start']) && $request['length'] != -1) {
$limit = "LIMIT ".intval($request['start']).", ".intval($request['length']); $limit = "LIMIT " . intval($request['start']) . ", " . intval($request['length']);
} }
return $limit; return $limit;
} }
/** /**
* Ordering * Ordering
* *
* Construct the ORDER BY clause for server-side processing SQL query * Construct the ORDER BY clause for server-side processing SQL query
* *
* @param array $request Data sent to server by DataTables * @param array $request Data sent to server by DataTables
* @param array $columns Column information array * @param array $columns Column information array
* @return string SQL order by clause * @return string SQL order by clause
*/ */
static function order ( $request, $columns ) static function order($request, $columns) {
{ $order = '';
$order = '';
if ( isset($request['order']) && count($request['order']) ) { if (isset($request['order']) && count($request['order'])) {
$orderBy = array(); $orderBy = array();
$dtColumns = self::pluck( $columns, 'dt' ); $dtColumns = self::pluck($columns, 'dt');
for ( $i=0, $ien=count($request['order']) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($request['order']); $i < $ien; $i++) {
// Convert the column index into the column data property // Convert the column index into the column data property
$columnIdx = intval($request['order'][$i]['column']); $columnIdx = intval($request['order'][$i]['column']);
$requestColumn = $request['columns'][$columnIdx]; $requestColumn = $request['columns'][$columnIdx];
$columnIdx = array_search( $requestColumn['data'], $dtColumns ); $columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $columns[ $columnIdx ]; $column = $columns[$columnIdx];
if ( $requestColumn['orderable'] == 'true' ) { if ($requestColumn['orderable'] == 'true') {
$dir = $request['order'][$i]['dir'] === 'DESC' ? $dir = $request['order'][$i]['dir'] === 'DESC' ?
'ASC' : 'ASC' :
'DESC'; 'DESC';
$orderBy[] = '`'.$column['db'].'` '.$dir; $orderBy[] = '`' . $column['db'] . '` ' . $dir;
} }
} }
$order = 'ORDER BY '.implode(', ', $orderBy); $order = 'ORDER BY ' . implode(', ', $orderBy);
} }
return $order; return $order;
} }
/** /**
* Searching / Filtering * Searching / Filtering
* *
* Construct the WHERE clause for server-side processing SQL query. * Construct the WHERE clause for server-side processing SQL query.
* *
* NOTE this does not match the built-in DataTables filtering which does it * NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here performance on large * word by word on any field. It's possible to do here performance on large
* databases would be very poor * databases would be very poor
* *
* @param array $request Data sent to server by DataTables * @param array $request Data sent to server by DataTables
* @param array $columns Column information array * @param array $columns Column information array
* @param array $bindings Array of values for PDO bindings, used in the * @param array $bindings Array of values for PDO bindings, used in the
* sql_exec() function * sql_exec() function
* @return string SQL where clause * @return string SQL where clause
*/ */
static function filter ( $request, $columns, &$bindings ) static function filter($request, $columns, &$bindings) {
{ $globalSearch = array();
$globalSearch = array(); $columnSearch = array();
$columnSearch = array(); $dtColumns = self::pluck($columns, 'dt');
$dtColumns = self::pluck( $columns, 'dt' );
if ( isset($request['search']) && $request['search']['value'] != '' ) { if (isset($request['search']) && $request['search']['value'] != '') {
$str = $request['search']['value']; $str = $request['search']['value'];
for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($request['columns']); $i < $ien; $i++) {
$requestColumn = $request['columns'][$i]; $requestColumn = $request['columns'][$i];
$columnIdx = array_search( $requestColumn['data'], $dtColumns ); $columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $columns[ $columnIdx ]; $column = $columns[$columnIdx];
if ( $requestColumn['searchable'] == 'true' ) { if ($requestColumn['searchable'] == 'true') {
$binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR ); $binding = self::bind($bindings, '%' . $str . '%', PDO::PARAM_STR);
$globalSearch[] = "`".$column['db']."` LIKE ".$binding; $globalSearch[] = "`" . $column['db'] . "` LIKE " . $binding;
} }
} }
} }
// Individual column filtering // Individual column filtering
for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($request['columns']); $i < $ien; $i++) {
$requestColumn = $request['columns'][$i]; $requestColumn = $request['columns'][$i];
$columnIdx = array_search( $requestColumn['data'], $dtColumns ); $columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $columns[ $columnIdx ]; $column = $columns[$columnIdx];
$str = $requestColumn['search']['value']; $str = $requestColumn['search']['value'];
if ( $requestColumn['searchable'] == 'true' && if ($requestColumn['searchable'] == 'true' &&
$str != '' ) { $str != '') {
$binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR ); $binding = self::bind($bindings, '%' . $str . '%', PDO::PARAM_STR);
$columnSearch[] = "`".$column['db']."` LIKE ".$binding; $columnSearch[] = "`" . $column['db'] . "` LIKE " . $binding;
} }
} }
// Combine the filters into a single string // Combine the filters into a single string
$where = ''; $where = '';
if ( count( $globalSearch ) ) { if (count($globalSearch)) {
$where = '('.implode(' OR ', $globalSearch).')'; $where = '(' . implode(' OR ', $globalSearch) . ')';
} }
if ( count( $columnSearch ) ) { if (count($columnSearch)) {
$where = $where === '' ? $where = $where === '' ?
implode(' AND ', $columnSearch) : implode(' AND ', $columnSearch) :
$where .' AND '. implode(' AND ', $columnSearch); $where . ' AND ' . implode(' AND ', $columnSearch);
} }
if ( $where !== '' ) { if ($where !== '') {
$where = 'WHERE '.$where; $where = 'WHERE ' . $where;
} }
return $where; return $where;
} }
/** /**
* Perform the SQL queries needed for an server-side processing requested, * Perform the SQL queries needed for an server-side processing requested,
* utilising the helper functions of this class, limit(), order() and * utilising the helper functions of this class, limit(), order() and
* filter() among others. The returned array is ready to be encoded as JSON * filter() among others. The returned array is ready to be encoded as JSON
* in response to an SSP request, or can be modified if needed before * in response to an SSP request, or can be modified if needed before
* sending back to the client. * sending back to the client.
* *
* @param array $request Data sent to server by DataTables * @param array $request Data sent to server by DataTables
* @param array $sql_details SQL connection details - see sql_connect() * @param array $sql_details SQL connection details - see sql_connect()
* @param string $table SQL table to query * @param string $table SQL table to query
* @param string $primaryKey Primary key of the table * @param string $primaryKey Primary key of the table
* @param array $columns Column information array * @param array $columns Column information array
* @return array Server-side processing response array * @return array Server-side processing response array
*/ */
static function simple ( $request, $sql_details, $table, $primaryKey, $columns, $columns2 ) static function simple($request, $sql_details, $table, $primaryKey, $columns, $columns2) {
{ $bindings = array();
$bindings = array(); $db = self::sql_connect($sql_details);
$db = self::sql_connect( $sql_details );
// Build the SQL query string from the request // Build the SQL query string from the request
$limit = self::limit( $request, $columns ); $limit = self::limit($request, $columns);
$order = self::order( $request, $columns ); $order = self::order($request, $columns);
$where = self::filter( $request, $columns, $bindings ); $where = self::filter($request, $columns, $bindings);
// Main query to actually get the data // Main query to actually get the data
$data = self::Ssql_exec($db, $bindings, $data = self::Ssql_exec($db, $bindings,
"SELECT SQL_CALC_FOUND_ROWS `".implode("`, `", self::pluck($columns, 'db'))."` "SELECT SQL_CALC_FOUND_ROWS `" . implode("`, `", self::pluck($columns, 'db')) . "`
FROM `$table` FROM `$table`
$where $where
$order $order
$limit" $limit"
); );
// Data set length after filtering // Data set length after filtering
$resFilterLength = self::sql_exec( $db, $resFilterLength = self::sql_exec($db,
"SELECT FOUND_ROWS()" "SELECT FOUND_ROWS()"
); );
$recordsFiltered = $resFilterLength[0][0]; $recordsFiltered = $resFilterLength[0][0];
// Total data set length // Total data set length
$resTotalLength = self::sql_exec( $db, $resTotalLength = self::sql_exec($db,
"SELECT COUNT(`{$primaryKey}`) "SELECT COUNT(`{$primaryKey}`)
FROM `$table`" FROM `$table`"
); );
$recordsTotal = $resTotalLength[0][0]; $recordsTotal = $resTotalLength[0][0];
/* /*
* Output * Output
*/ */
return array( return array(
"draw" => intval( $request['draw'] ), "draw" => intval($request['draw']),
"recordsTotal" => intval( $recordsTotal ), "recordsTotal" => intval($recordsTotal),
"recordsFiltered" => intval( $recordsFiltered ), "recordsFiltered" => intval($recordsFiltered),
"data" => self::data_output( $columns2, $data ) "data" => self::data_output($columns2, $data)
); );
} }
/** /**
* Connect to the database * Connect to the database
* *
* @param array $sql_details SQL server connection details array, with the * @param array $sql_details SQL server connection details array, with the
* properties: * properties:
* * host - host name * * host - host name
* * db - database name * * db - database name
* * user - user name * * user - user name
* * pass - user password * * pass - user password
* @return resource Database connection handle * @return resource Database connection handle
*/ */
static function sql_connect ( $sql_details ) static function sql_connect($sql_details) {
{ try {
try { $db = @new PDO(
$db = @new PDO( "mysql:host={$sql_details['host']};dbname={$sql_details['db']}",
"mysql:host={$sql_details['host']};dbname={$sql_details['db']}", $sql_details['user'],
$sql_details['user'], $sql_details['pass'],
$sql_details['pass'], array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ) );
); } catch (PDOException $e) {
} self::fatal(
catch (PDOException $e) { "An error occurred while connecting to the database. " .
self::fatal( "The error reported by the server was: " . $e->getMessage()
"An error occurred while connecting to the database. ". );
"The error reported by the server was: ".$e->getMessage() }
);
}
return $db; return $db;
} }
/** /**
* Execute an SQL query on the database * Execute an SQL query on the database
* *
* @param resource $db Database handler * @param resource $db Database handler
* @param array $bindings Array of PDO binding values from bind() to be * @param array $bindings Array of PDO binding values from bind() to be
* used for safely escaping strings. Note that this can be given as the * used for safely escaping strings. Note that this can be given as the
* SQL query string if no bindings are required. * SQL query string if no bindings are required.
* @param string $sql SQL query to execute. * @param string $sql SQL query to execute.
* @return array Result from the query (all rows) * @return array Result from the query (all rows)
*/ */
static function sql_exec ( $db, $bindings, $sql=null ) static function sql_exec($db, $bindings, $sql = null) {
{ // Argument shifting
// Argument shifting if ($sql === null) {
if ( $sql === null ) { $sql = $bindings;
$sql = $bindings; }
}
$stmt = $db->prepare( $sql ); $stmt = $db->prepare($sql);
//echo $sql; //echo $sql;
// Bind parameters // Bind parameters
if ( is_array( $bindings ) ) { if (is_array($bindings)) {
for ( $i=0, $ien=count($bindings) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($bindings); $i < $ien; $i++) {
$binding = $bindings[$i]; $binding = $bindings[$i];
$stmt->bindValue( $binding['key'], $binding['val'], $binding['type'] ); $stmt->bindValue($binding['key'], $binding['val'], $binding['type']);
} }
} }
// Execute // Execute
try { try {
$stmt->execute(); $stmt->execute();
} } catch (PDOException $e) {
catch (PDOException $e) { self::fatal("An SQL error occurred: " . $e->getMessage());
self::fatal( "An SQL error occurred: ".$e->getMessage() ); }
} $result = $stmt->fetchAll();
$result= $stmt->fetchAll(); return $result;
return $result; }
}
static function Ssql_exec ($db, $bindings, $sql=null )
{
// Argument shifting
if ( $sql === null ) {
$sql = $bindings;
}
$stmt = $db->prepare( $sql ); static function Ssql_exec($db, $bindings, $sql = null) {
// Argument shifting
if ($sql === null) {
$sql = $bindings;
}
// Bind parameters $stmt = $db->prepare($sql);
if ( is_array( $bindings ) ) {
for ( $i=0, $ien=count($bindings) ; $i<$ien ; $i++ ) {
$binding = $bindings[$i];
$stmt->bindValue( $binding['key'], $binding['val'], $binding['type'] );
}
}
// Execute // Bind parameters
try { if (is_array($bindings)) {
$stmt->execute(); for ($i = 0, $ien = count($bindings); $i < $ien; $i++) {
} $binding = $bindings[$i];
catch (PDOException $e) { $stmt->bindValue($binding['key'], $binding['val'], $binding['type']);
self::fatal( "An SQL error occurred: ".$e->getMessage() ); }
} }
// Execute
try {
$stmt->execute();
} catch (PDOException $e) {
self::fatal("An SQL error occurred: " . $e->getMessage());
}
$loop = '0'; $loop = '0';
while ($arr = $stmt->fetch(PDO::FETCH_ASSOC)) { while ($arr = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[$loop]['id']= $arr['id']; $result[$loop]['id'] = $arr['id'];
$result[$loop]['m_report']= $arr['m_report']; $result[$loop]['m_report'] = $arr['m_report'];
$result[$loop]['p_report']= $arr['p_report']; $result[$loop]['p_report'] = $arr['p_report'];
$vis = Trim($arr['rep_reason']); $vis = Trim($arr['rep_reason']);
if ($vis == '0') if ($vis == '0') {
{ $result[$loop]['rep_reason'] = "Public";
$result[$loop]['rep_reason'] = "Public"; } elseif ($vis == '1') {
$result[$loop]['rep_reason'] = "Unlisted";
} elseif ($vis == '2') {
$result[$loop]['rep_reason'] = "Private";
}
$rid = $arr['p_report'];
$result[$loop]['details'] = "<a class='btn btn-default btn-sm' href=pastes.php?details=" . $rid . "> Details </a>";
$result[$loop]['view'] = "<a class='btn btn-success btn-sm' href=../paste.php?id=" . $rid . "> View </a>";
$result[$loop]['delete'] = "<a class='btn btn-danger btn-sm' href=pastes.php?delete=" . $rid . "> Remove </a>";
$result[$loop]['delete'] = "<a class='btn btn-danger btn-sm' href=pastes.php?delete=" . $rid . "> Delete </a>";
$loop = $loop + 1;
} }
elseif ($vis == '1') // Return all
{ return $result;
$result[$loop]['rep_reason'] = "Unlisted"; }
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Internal methods
*/
/**
* Throw a fatal error.
*
* This writes out an error message in a JSON string which DataTables will
* see and show to the user in the browser.
*
* @param string $msg Message to send to the client
*/
static function fatal($msg) {
echo json_encode(array(
"error" => $msg
));
exit(0);
}
/**
* Create a PDO binding key which can be used for escaping variables safely
* when executing a query with sql_exec()
*
* @param array &$a Array of bindings
* @param * $val Value to bind
* @param int $type PDO field type
* @return string Bound key to be used in the SQL where this parameter
* would be used.
*/
static function bind(&$a, $val, $type) {
$key = ':binding_' . count($a);
$a[] = array(
'key' => $key,
'val' => $val,
'type' => $type
);
return $key;
}
/**
* Pull a particular property from each assoc. array in a numeric array,
* returning and array of the property values from each item.
*
* @param array $a Array to get data from
* @param string $prop Property to read
* @return array Array of property values
*/
static function pluck($a, $prop) {
$out = array();
for ($i = 0, $len = count($a); $i < $len; $i++) {
$out[] = $a[$i][$prop];
} }
elseif ($vis == '2')
{
$result[$loop]['rep_reason'] = "Private";
}
$rid = $arr['p_report'];
$result[$loop]['details'] ="<a class='btn btn-default btn-sm' href=pastes.php?details=".$rid."> Details </a>";
$result[$loop]['view'] = "<a class='btn btn-success btn-sm' href=../paste.php?id=".$rid."> View </a>";
$result[$loop]['delete'] ="<a class='btn btn-danger btn-sm' href=pastes.php?delete=".$rid."> Remove </a>";
$result[$loop]['delete'] ="<a class='btn btn-danger btn-sm' href=pastes.php?delete=".$rid."> Delete </a>";
$loop = $loop +1;
}
// Return all
return $result;
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * return $out;
* Internal methods }
*/
/**
* Throw a fatal error.
*
* This writes out an error message in a JSON string which DataTables will
* see and show to the user in the browser.
*
* @param string $msg Message to send to the client
*/
static function fatal ( $msg )
{
echo json_encode( array(
"error" => $msg
) );
exit(0);
}
/**
* Create a PDO binding key which can be used for escaping variables safely
* when executing a query with sql_exec()
*
* @param array &$a Array of bindings
* @param * $val Value to bind
* @param int $type PDO field type
* @return string Bound key to be used in the SQL where this parameter
* would be used.
*/
static function bind ( &$a, $val, $type )
{
$key = ':binding_'.count( $a );
$a[] = array(
'key' => $key,
'val' => $val,
'type' => $type
);
return $key;
}
/**
* Pull a particular property from each assoc. array in a numeric array,
* returning and array of the property values from each item.
*
* @param array $a Array to get data from
* @param string $prop Property to read
* @return array Array of property values
*/
static function pluck ( $a, $prop )
{
$out = array();
for ( $i=0, $len=count($a) ; $i<$len ; $i++ ) {
$out[] = $a[$i][$prop];
}
return $out;
}
} }
?> ?>

View file

@ -1,421 +1,402 @@
<?php <?php
class SSP { class SSP {
/** /**
* Create the data output array for the DataTables rows * Create the data output array for the DataTables rows
* *
* @param array $columns Column information array * @param array $columns Column information array
* @param array $data Data from the SQL get * @param array $data Data from the SQL get
* @return array Formatted data in a row based format * @return array Formatted data in a row based format
*/ */
static function data_output ( $columns, $data ) static function data_output($columns, $data) {
{ $out = array();
$out = array();
for ( $i=0, $ien=count($data) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($data); $i < $ien; $i++) {
$row = array(); $row = array();
for ( $j=0, $jen=count($columns) ; $j<$jen ; $j++ ) { for ($j = 0, $jen = count($columns); $j < $jen; $j++) {
$column = $columns[$j]; $column = $columns[$j];
// Is there a formatter? // Is there a formatter?
if ( isset( $column['formatter'] ) ) { if (isset($column['formatter'])) {
$row[ $column['dt'] ] = $column['formatter']( $data[$i][ $column['db'] ], $data[$i] ); $row[$column['dt']] = $column['formatter']($data[$i][$column['db']], $data[$i]);
} } else {
else { $row[$column['dt']] = $data[$i][$columns[$j]['db']];
$row[ $column['dt'] ] = $data[$i][ $columns[$j]['db'] ]; }
} }
}
$out[] = $row; $out[] = $row;
} }
return $out; return $out;
} }
/** /**
* Paging * Paging
* *
* Construct the LIMIT clause for server-side processing SQL query * Construct the LIMIT clause for server-side processing SQL query
* *
* @param array $request Data sent to server by DataTables * @param array $request Data sent to server by DataTables
* @param array $columns Column information array * @param array $columns Column information array
* @return string SQL limit clause * @return string SQL limit clause
*/ */
static function limit ( $request, $columns ) static function limit($request, $columns) {
{ $limit = '';
$limit = '';
if ( isset($request['start']) && $request['length'] != -1 ) { if (isset($request['start']) && $request['length'] != -1) {
$limit = "LIMIT ".intval($request['start']).", ".intval($request['length']); $limit = "LIMIT " . intval($request['start']) . ", " . intval($request['length']);
} }
return $limit; return $limit;
} }
/** /**
* Ordering * Ordering
* *
* Construct the ORDER BY clause for server-side processing SQL query * Construct the ORDER BY clause for server-side processing SQL query
* *
* @param array $request Data sent to server by DataTables * @param array $request Data sent to server by DataTables
* @param array $columns Column information array * @param array $columns Column information array
* @return string SQL order by clause * @return string SQL order by clause
*/ */
static function order ( $request, $columns ) static function order($request, $columns) {
{ $order = '';
$order = '';
if ( isset($request['order']) && count($request['order']) ) { if (isset($request['order']) && count($request['order'])) {
$orderBy = array(); $orderBy = array();
$dtColumns = self::pluck( $columns, 'dt' ); $dtColumns = self::pluck($columns, 'dt');
for ( $i=0, $ien=count($request['order']) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($request['order']); $i < $ien; $i++) {
// Convert the column index into the column data property // Convert the column index into the column data property
$columnIdx = intval($request['order'][$i]['column']); $columnIdx = intval($request['order'][$i]['column']);
$requestColumn = $request['columns'][$columnIdx]; $requestColumn = $request['columns'][$columnIdx];
$columnIdx = array_search( $requestColumn['data'], $dtColumns ); $columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $columns[ $columnIdx ]; $column = $columns[$columnIdx];
if ( $requestColumn['orderable'] == 'true' ) { if ($requestColumn['orderable'] == 'true') {
$dir = $request['order'][$i]['dir'] === 'asc' ? $dir = $request['order'][$i]['dir'] === 'asc' ?
'ASC' : 'ASC' :
'DESC'; 'DESC';
$orderBy[] = '`'.$column['db'].'` '.$dir; $orderBy[] = '`' . $column['db'] . '` ' . $dir;
} }
} }
$order = 'ORDER BY '.implode(', ', $orderBy); $order = 'ORDER BY ' . implode(', ', $orderBy);
} }
return $order; return $order;
} }
/** /**
* Searching / Filtering * Searching / Filtering
* *
* Construct the WHERE clause for server-side processing SQL query. * Construct the WHERE clause for server-side processing SQL query.
* *
* NOTE this does not match the built-in DataTables filtering which does it * NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here performance on large * word by word on any field. It's possible to do here performance on large
* databases would be very poor * databases would be very poor
* *
* @param array $request Data sent to server by DataTables * @param array $request Data sent to server by DataTables
* @param array $columns Column information array * @param array $columns Column information array
* @param array $bindings Array of values for PDO bindings, used in the * @param array $bindings Array of values for PDO bindings, used in the
* sql_exec() function * sql_exec() function
* @return string SQL where clause * @return string SQL where clause
*/ */
static function filter ( $request, $columns, &$bindings ) static function filter($request, $columns, &$bindings) {
{ $globalSearch = array();
$globalSearch = array(); $columnSearch = array();
$columnSearch = array(); $dtColumns = self::pluck($columns, 'dt');
$dtColumns = self::pluck( $columns, 'dt' );
if ( isset($request['search']) && $request['search']['value'] != '' ) { if (isset($request['search']) && $request['search']['value'] != '') {
$str = $request['search']['value']; $str = $request['search']['value'];
for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($request['columns']); $i < $ien; $i++) {
$requestColumn = $request['columns'][$i]; $requestColumn = $request['columns'][$i];
$columnIdx = array_search( $requestColumn['data'], $dtColumns ); $columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $columns[ $columnIdx ]; $column = $columns[$columnIdx];
if ( $requestColumn['searchable'] == 'true' ) { if ($requestColumn['searchable'] == 'true') {
$binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR ); $binding = self::bind($bindings, '%' . $str . '%', PDO::PARAM_STR);
$globalSearch[] = "`".$column['db']."` LIKE ".$binding; $globalSearch[] = "`" . $column['db'] . "` LIKE " . $binding;
} }
} }
} }
// Individual column filtering // Individual column filtering
for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($request['columns']); $i < $ien; $i++) {
$requestColumn = $request['columns'][$i]; $requestColumn = $request['columns'][$i];
$columnIdx = array_search( $requestColumn['data'], $dtColumns ); $columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $columns[ $columnIdx ]; $column = $columns[$columnIdx];
$str = $requestColumn['search']['value']; $str = $requestColumn['search']['value'];
if ( $requestColumn['searchable'] == 'true' && if ($requestColumn['searchable'] == 'true' &&
$str != '' ) { $str != '') {
$binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR ); $binding = self::bind($bindings, '%' . $str . '%', PDO::PARAM_STR);
$columnSearch[] = "`".$column['db']."` LIKE ".$binding; $columnSearch[] = "`" . $column['db'] . "` LIKE " . $binding;
} }
} }
// Combine the filters into a single string // Combine the filters into a single string
$where = ''; $where = '';
if ( count( $globalSearch ) ) { if (count($globalSearch)) {
$where = '('.implode(' OR ', $globalSearch).')'; $where = '(' . implode(' OR ', $globalSearch) . ')';
} }
if ( count( $columnSearch ) ) { if (count($columnSearch)) {
$where = $where === '' ? $where = $where === '' ?
implode(' AND ', $columnSearch) : implode(' AND ', $columnSearch) :
$where .' AND '. implode(' AND ', $columnSearch); $where . ' AND ' . implode(' AND ', $columnSearch);
} }
if ( $where !== '' ) { if ($where !== '') {
$where = 'WHERE '.$where; $where = 'WHERE ' . $where;
} }
return $where; return $where;
} }
/** /**
* Perform the SQL queries needed for an server-side processing requested, * Perform the SQL queries needed for an server-side processing requested,
* utilising the helper functions of this class, limit(), order() and * utilising the helper functions of this class, limit(), order() and
* filter() among others. The returned array is ready to be encoded as JSON * filter() among others. The returned array is ready to be encoded as JSON
* in response to an SSP request, or can be modified if needed before * in response to an SSP request, or can be modified if needed before
* sending back to the client. * sending back to the client.
* *
* @param array $request Data sent to server by DataTables * @param array $request Data sent to server by DataTables
* @param array $sql_details SQL connection details - see sql_connect() * @param array $sql_details SQL connection details - see sql_connect()
* @param string $table SQL table to query * @param string $table SQL table to query
* @param string $primaryKey Primary key of the table * @param string $primaryKey Primary key of the table
* @param array $columns Column information array * @param array $columns Column information array
* @return array Server-side processing response array * @return array Server-side processing response array
*/ */
static function simple ( $request, $sql_details, $table, $primaryKey, $columns, $columns2 ) static function simple($request, $sql_details, $table, $primaryKey, $columns, $columns2) {
{ $bindings = array();
$bindings = array(); $db = self::sql_connect($sql_details);
$db = self::sql_connect( $sql_details );
// Build the SQL query string from the request // Build the SQL query string from the request
$limit = self::limit( $request, $columns ); $limit = self::limit($request, $columns);
$order = self::order( $request, $columns ); $order = self::order($request, $columns);
$where = self::filter( $request, $columns, $bindings ); $where = self::filter($request, $columns, $bindings);
// Main query to actually get the data // Main query to actually get the data
$data = self::Ssql_exec($db, $bindings, $data = self::Ssql_exec($db, $bindings,
"SELECT SQL_CALC_FOUND_ROWS `".implode("`, `", self::pluck($columns, 'db'))."` "SELECT SQL_CALC_FOUND_ROWS `" . implode("`, `", self::pluck($columns, 'db')) . "`
FROM `$table` FROM `$table`
$where $where
$order $order
$limit" $limit"
); );
// Data set length after filtering // Data set length after filtering
$resFilterLength = self::sql_exec( $db, $resFilterLength = self::sql_exec($db,
"SELECT FOUND_ROWS()" "SELECT FOUND_ROWS()"
); );
$recordsFiltered = $resFilterLength[0][0]; $recordsFiltered = $resFilterLength[0][0];
// Total data set length // Total data set length
$resTotalLength = self::sql_exec( $db, $resTotalLength = self::sql_exec($db,
"SELECT COUNT(`{$primaryKey}`) "SELECT COUNT(`{$primaryKey}`)
FROM `$table`" FROM `$table`"
); );
$recordsTotal = $resTotalLength[0][0]; $recordsTotal = $resTotalLength[0][0];
/* /*
* Output * Output
*/ */
return array( return array(
"draw" => intval( $request['draw'] ), "draw" => intval($request['draw']),
"recordsTotal" => intval( $recordsTotal ), "recordsTotal" => intval($recordsTotal),
"recordsFiltered" => intval( $recordsFiltered ), "recordsFiltered" => intval($recordsFiltered),
"data" => self::data_output( $columns2, $data ) "data" => self::data_output($columns2, $data)
); );
} }
/** /**
* Connect to the database * Connect to the database
* *
* @param array $sql_details SQL server connection details array, with the * @param array $sql_details SQL server connection details array, with the
* properties: * properties:
* * host - host name * * host - host name
* * db - database name * * db - database name
* * user - user name * * user - user name
* * pass - user password * * pass - user password
* @return resource Database connection handle * @return resource Database connection handle
*/ */
static function sql_connect ( $sql_details ) static function sql_connect($sql_details) {
{ try {
try { $db = @new PDO(
$db = @new PDO( "mysql:host={$sql_details['host']};dbname={$sql_details['db']}",
"mysql:host={$sql_details['host']};dbname={$sql_details['db']}", $sql_details['user'],
$sql_details['user'], $sql_details['pass'],
$sql_details['pass'], array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ) );
); } catch (PDOException $e) {
} self::fatal(
catch (PDOException $e) { "An error occurred while connecting to the database. " .
self::fatal( "The error reported by the server was: " . $e->getMessage()
"An error occurred while connecting to the database. ". );
"The error reported by the server was: ".$e->getMessage() }
);
}
return $db; return $db;
} }
/** /**
* Execute an SQL query on the database * Execute an SQL query on the database
* *
* @param resource $db Database handler * @param resource $db Database handler
* @param array $bindings Array of PDO binding values from bind() to be * @param array $bindings Array of PDO binding values from bind() to be
* used for safely escaping strings. Note that this can be given as the * used for safely escaping strings. Note that this can be given as the
* SQL query string if no bindings are required. * SQL query string if no bindings are required.
* @param string $sql SQL query to execute. * @param string $sql SQL query to execute.
* @return array Result from the query (all rows) * @return array Result from the query (all rows)
*/ */
static function sql_exec ( $db, $bindings, $sql=null ) static function sql_exec($db, $bindings, $sql = null) {
{ // Argument shifting
// Argument shifting if ($sql === null) {
if ( $sql === null ) { $sql = $bindings;
$sql = $bindings; }
}
$stmt = $db->prepare( $sql ); $stmt = $db->prepare($sql);
//echo $sql; //echo $sql;
// Bind parameters // Bind parameters
if ( is_array( $bindings ) ) { if (is_array($bindings)) {
for ( $i=0, $ien=count($bindings) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($bindings); $i < $ien; $i++) {
$binding = $bindings[$i]; $binding = $bindings[$i];
$stmt->bindValue( $binding['key'], $binding['val'], $binding['type'] ); $stmt->bindValue($binding['key'], $binding['val'], $binding['type']);
} }
} }
// Execute // Execute
try { try {
$stmt->execute(); $stmt->execute();
} } catch (PDOException $e) {
catch (PDOException $e) { self::fatal("An SQL error occurred: " . $e->getMessage());
self::fatal( "An SQL error occurred: ".$e->getMessage() ); }
} $result = $stmt->fetchAll();
$result= $stmt->fetchAll(); return $result;
return $result; }
}
static function Ssql_exec ($db, $bindings, $sql=null )
{
// Argument shifting
if ( $sql === null ) {
$sql = $bindings;
}
$stmt = $db->prepare( $sql ); static function Ssql_exec($db, $bindings, $sql = null) {
// Argument shifting
if ($sql === null) {
$sql = $bindings;
}
// Bind parameters $stmt = $db->prepare($sql);
if ( is_array( $bindings ) ) {
for ( $i=0, $ien=count($bindings) ; $i<$ien ; $i++ ) {
$binding = $bindings[$i];
$stmt->bindValue( $binding['key'], $binding['val'], $binding['type'] );
}
}
// Execute // Bind parameters
try { if (is_array($bindings)) {
$stmt->execute(); for ($i = 0, $ien = count($bindings); $i < $ien; $i++) {
} $binding = $bindings[$i];
catch (PDOException $e) { $stmt->bindValue($binding['key'], $binding['val'], $binding['type']);
self::fatal( "An SQL error occurred: ".$e->getMessage() ); }
} }
// Execute
try {
$stmt->execute();
} catch (PDOException $e) {
self::fatal("An SQL error occurred: " . $e->getMessage());
}
$loop = '0'; $loop = '0';
while ($arr = $stmt->fetch(PDO::FETCH_ASSOC)) { while ($arr = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[$loop]['id']= $arr['id']; $result[$loop]['id'] = $arr['id'];
$result[$loop]['username']= $arr['username']; $result[$loop]['username'] = $arr['username'];
$result[$loop]['platform']= $arr['platform']; $result[$loop]['platform'] = $arr['platform'];
$result[$loop]['date']= $arr['date']; $result[$loop]['date'] = $arr['date'];
$result[$loop]['email_id']= $arr['email_id']; $result[$loop]['email_id'] = $arr['email_id'];
$ver = $arr['verified']; $ver = $arr['verified'];
$myid = $arr['id']; $myid = $arr['id'];
if ($ver == '0') if ($ver == '0') {
{ $result[$loop]['ban'] = "<span class='bg-red'>User unverified</span>";
$result[$loop]['ban'] ="<span class='bg-red'>User unverified</span>"; } elseif ($ver == '1') {
$result[$loop]['ban'] = "<a class='btn btn-danger btn-sm' href=users.php?ban=" . $myid . "> Ban </a>";
} elseif ($ver == '2') {
$result[$loop]['ban'] = "<a class='btn btn-success btn-sm' href=users.php?unban=" . $myid . "> Unban </a>";
}
$result[$loop]['view'] = "<a class='btn btn-default btn-sm' href=users.php?details=" . $myid . "> Details </a>";
$result[$loop]['delete'] = "<a class='btn btn-danger btn-sm' href=users.php?delete=" . $myid . "> Delete </a>";
$loop = $loop + 1;
} }
elseif ($ver == '1') // Return all
{ return $result;
$result[$loop]['ban'] ="<a class='btn btn-danger btn-sm' href=users.php?ban=".$myid."> Ban </a>"; }
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Internal methods
*/
/**
* Throw a fatal error.
*
* This writes out an error message in a JSON string which DataTables will
* see and show to the user in the browser.
*
* @param string $msg Message to send to the client
*/
static function fatal($msg) {
echo json_encode(array(
"error" => $msg
));
exit(0);
}
/**
* Create a PDO binding key which can be used for escaping variables safely
* when executing a query with sql_exec()
*
* @param array &$a Array of bindings
* @param * $val Value to bind
* @param int $type PDO field type
* @return string Bound key to be used in the SQL where this parameter
* would be used.
*/
static function bind(&$a, $val, $type) {
$key = ':binding_' . count($a);
$a[] = array(
'key' => $key,
'val' => $val,
'type' => $type
);
return $key;
}
/**
* Pull a particular property from each assoc. array in a numeric array,
* returning and array of the property values from each item.
*
* @param array $a Array to get data from
* @param string $prop Property to read
* @return array Array of property values
*/
static function pluck($a, $prop) {
$out = array();
for ($i = 0, $len = count($a); $i < $len; $i++) {
$out[] = $a[$i][$prop];
} }
elseif ($ver == '2')
{
$result[$loop]['ban'] ="<a class='btn btn-success btn-sm' href=users.php?unban=".$myid."> Unban </a>";
}
$result[$loop]['view'] = "<a class='btn btn-default btn-sm' href=users.php?details=".$myid."> Details </a>";
$result[$loop]['delete'] ="<a class='btn btn-danger btn-sm' href=users.php?delete=".$myid."> Delete </a>";
$loop = $loop +1;
}
// Return all
return $result;
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * return $out;
* Internal methods }
*/
/**
* Throw a fatal error.
*
* This writes out an error message in a JSON string which DataTables will
* see and show to the user in the browser.
*
* @param string $msg Message to send to the client
*/
static function fatal ( $msg )
{
echo json_encode( array(
"error" => $msg
) );
exit(0);
}
/**
* Create a PDO binding key which can be used for escaping variables safely
* when executing a query with sql_exec()
*
* @param array &$a Array of bindings
* @param * $val Value to bind
* @param int $type PDO field type
* @return string Bound key to be used in the SQL where this parameter
* would be used.
*/
static function bind ( &$a, $val, $type )
{
$key = ':binding_'.count( $a );
$a[] = array(
'key' => $key,
'val' => $val,
'type' => $type
);
return $key;
}
/**
* Pull a particular property from each assoc. array in a numeric array,
* returning and array of the property values from each item.
*
* @param array $a Array to get data from
* @param string $prop Property to read
* @return array Array of property values
*/
static function pluck ( $a, $prop )
{
$out = array();
for ( $i=0, $len=count($a) ; $i<$len ; $i++ ) {
$out[] = $a[$i][$prop];
}
return $out;
}
} }
if($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
if ($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
header("Location: http://ponepaste.org/SVOtaKqJZh4nT9Z"); header("Location: http://ponepaste.org/SVOtaKqJZh4nT9Z");
die(); die();
} }

View file

@ -24,14 +24,14 @@ if (isset($_SESSION['login'])) {
if (isset($_GET['logout'])) { if (isset($_GET['logout'])) {
if (isset($_SESSION['login'])) if (isset($_SESSION['login']))
unset($_SESSION['login']); unset($_SESSION['login']);
session_destroy(); session_destroy();
header("Location: ."); header("Location: .");
exit(); exit();
} }
$date = date('jS F Y'); $date = date('jS F Y');
$ip = $_SERVER['REMOTE_ADDR']; $ip = $_SERVER['REMOTE_ADDR'];
require_once('../config.php'); require_once('../config.php');
$con = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname); $con = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname);
@ -48,17 +48,17 @@ while ($row = mysqli_fetch_array($result)) {
$last_id = $row['@last_id := MAX(id)']; $last_id = $row['@last_id := MAX(id)'];
} }
$query = "SELECT * FROM admin_history WHERE id=" . Trim($last_id); $query = "SELECT * FROM admin_history WHERE id=" . Trim($last_id);
$result = mysqli_query($con, $query); $result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) { while ($row = mysqli_fetch_array($result)) {
$last_date = $row['last_date']; $last_date = $row['last_date'];
$last_ip = $row['ip']; $last_ip = $row['ip'];
} }
if ($last_ip == $ip) { if ($last_ip == $ip) {
if ($last_date == $date) { if ($last_date == $date) {
} else { } else {
$query = "INSERT INTO admin_history (last_date,ip) VALUES ('$date','$ip')"; $query = "INSERT INTO admin_history (last_date,ip) VALUES ('$date','$ip')";
mysqli_query($con, $query); mysqli_query($con, $query);
@ -71,276 +71,278 @@ if ($last_ip == $ip) {
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>Paste - Statistics</title> <title>Paste - Statistics</title>
<link rel="shortcut icon" href="favicon.ico"> <link rel="shortcut icon" href="favicon.ico">
<link href="css/paste.css" rel="stylesheet" type="text/css" /> <link href="css/paste.css" rel="stylesheet" type="text/css"/>
</head> </head>
<body> <body>
<div id="top" class="clearfix">
<!-- Start App Logo -->
<div class="applogo">
<a href="../" class="logo">Paste</a>
</div>
<!-- End App Logo -->
<!-- Start Top Right --> <div id="top" class="clearfix">
<ul class="top-right"> <!-- Start App Logo -->
<li class="dropdown link"> <div class="applogo">
<a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span class="caret"></span></a> <a href="../" class="logo">Paste</a>
<ul class="dropdown-menu dropdown-menu-list dropdown-menu-right"> </div>
<li><a href="admin.php">Settings</a></li> <!-- End App Logo -->
<li><a href="?logout">Logout</a></li>
</ul>
</li>
</ul>
<!-- End Top Right -->
</div>
<!-- END TOP -->
<div class="content"> <!-- Start Top Right -->
<!-- START CONTAINER --> <ul class="top-right">
<div class="container-widget"> <li class="dropdown link">
<!-- Start Menu --> <a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span
<?php include 'menu.php';?> class="caret"></span></a>
<!-- End Menu --> <ul class="dropdown-menu dropdown-menu-list dropdown-menu-right">
<li><a href="admin.php">Settings</a></li>
<!-- Start Statistics --> <li><a href="?logout">Logout</a></li>
<?php </ul>
if ($_SERVER['REQUEST_METHOD'] == 'POST') { </li>
// Post Handler </ul>
} <!-- End Top Right -->
</div>
<!-- END TOP -->
$query = "SELECT * FROM page_view"; <div class="content">
$result = mysqli_query($con, $query); <!-- START CONTAINER -->
<div class="container-widget">
<!-- Start Menu -->
<?php include 'menu.php'; ?>
<!-- End Menu -->
while ($row = mysqli_fetch_array($result)) { <!-- Start Statistics -->
$total_page = isset($total_page) + Trim($row['tpage']); <?php
$total_un = isset($total_un) + Trim($row['tvisit']); if ($_SERVER['REQUEST_METHOD'] == 'POST') {
} // Post Handler
}
$query = "SELECT * FROM page_view";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
$total_page = isset($total_page) + Trim($row['tpage']);
$total_un = isset($total_un) + Trim($row['tvisit']);
}
$query = "SELECT id, expiry FROM pastes"; $query = "SELECT id, expiry FROM pastes";
$result = mysqli_query($con, $query); $result = mysqli_query($con, $query);
$total_pastes = 0; $total_pastes = 0;
$exp_pastes = 0; $exp_pastes = 0;
while ($row = mysqli_fetch_array($result)) { while ($row = mysqli_fetch_array($result)) {
$total_pastes = $total_pastes + 1; $total_pastes = $total_pastes + 1;
$p_expiry = Trim($row['expiry']); $p_expiry = Trim($row['expiry']);
if ($p_expiry == "NULL" || $p_expiry == "SELF") { if ($p_expiry == "NULL" || $p_expiry == "SELF") {
} else { } else {
$input_time = $p_expiry; $input_time = $p_expiry;
$current_time = mktime(date("H"), date("i"), date("s"), date("n"), date("j"), date("Y")); $current_time = mktime(date("H"), date("i"), date("s"), date("n"), date("j"), date("Y"));
if ($input_time < $current_time) { if ($input_time < $current_time) {
$exp_pastes = $exp_pastes + 1; $exp_pastes = $exp_pastes + 1;
} }
} }
} }
$query = "SELECT verified FROM users"; $query = "SELECT verified FROM users";
$result = mysqli_query($con, $query); $result = mysqli_query($con, $query);
$total_users = 0; $total_users = 0;
$total_ban = 0; $total_ban = 0;
$not_ver = 0; $not_ver = 0;
while ($row = mysqli_fetch_array($result)) { while ($row = mysqli_fetch_array($result)) {
$total_users = $total_users + 1; $total_users = $total_users + 1;
$p_v = Trim($row['verified']); $p_v = Trim($row['verified']);
if ($p_v == '2') { if ($p_v == '2') {
$total_ban = $total_ban + 1; $total_ban = $total_ban + 1;
} }
if ($p_v == '0') { if ($p_v == '0') {
$not_ver = $not_ver + 1; $not_ver = $not_ver + 1;
} }
} }
?> ?>
<div class="row">
<div class="col-md-12">
<div class="panel panel-widget">
<div class="panel-body">
<div class="panel-title">Statistics</div>
<table class="table table-bordered">
<tbody>
<tr>
<th>Task</th>
<th>Stats</th>
</tr>
<tr>
<td>Total Pastes</td>
<td><span class="label label-default"><?php echo $total_pastes; ?></span></td>
</tr>
<tr>
<td>Expired Pastes</td>
<td><span class="label label-default"><?php echo $exp_pastes; ?></span></td>
</tr>
<tr>
<td>Total Users</td>
<td><span class="label label-default"><?php echo $total_users; ?></span></td>
</tr>
<tr>
<td>Total Banned Users</td>
<td><span class="label label-warning"><?php echo $total_ban; ?></span></td>
</tr>
<tr>
<td>Unverified users</td>
<td><span class="label label-warning"><?php echo $not_ver; ?></span></td>
</tr>
<tr>
<td>Total Page Views</td>
<td><span class="label label-default"><?php echo $total_page; ?></span></td>
</tr>
<tr>
<td>Total Unique Visitors</td>
<td><span class="label label-default"><?php echo $total_un; ?></span></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<?php
$query = "SELECT @last_id := MAX(id) FROM page_view";
$result = mysqli_query($con, $query); <div class="row">
<div class="col-md-12">
<div class="panel panel-widget">
<div class="panel-body">
<div class="panel-title">Statistics</div>
<table class="table table-bordered">
<tbody>
<tr>
<th>Task</th>
<th>Stats</th>
</tr>
while ($row = mysqli_fetch_array($result)) { <tr>
$page_last_id = $row['@last_id := MAX(id)']; <td>Total Pastes</td>
} <td><span class="label label-default"><?php echo $total_pastes; ?></span></td>
$query = "SELECT * FROM page_view WHERE id=" . Trim($page_last_id); </tr>
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) { <tr>
$date = $row['date']; <td>Expired Pastes</td>
$tpage = $row['tpage']; <td><span class="label label-default"><?php echo $exp_pastes; ?></span></td>
$tvisit = $row['tvisit']; </tr>
}
?>
<div class="row">
<div class="col-md-12">
<div class="panel panel-widget">
<div class="panel-body">
<div class="panel-title">Page Views</a></div>
<table class="table table-bordered">
<tbody>
<tr>
<th>Date</th>
<th>Unique Visitors</th>
<th>Views</th>
</tr>
<tr>
<td><?php echo $date; ?></td>
<td><?php echo $tvisit; ?></td>
<td><?php echo $tpage; ?></td>
</tr>
<?php
$page_last_id = $page_last_id - 1;
$query = "SELECT * FROM page_view WHERE id=" . Trim($page_last_id);
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) { <tr>
$date = $row['date']; <td>Total Users</td>
$tpage = $row['tpage']; <td><span class="label label-default"><?php echo $total_users; ?></span></td>
$tvisit = $row['tvisit']; </tr>
}
?>
<tr>
<td><?php echo $date; ?></td>
<td><?php echo $tvisit; ?></td>
<td><?php echo $tpage; ?></td>
</tr>
<?php
$page_last_id = $page_last_id - 1;
$query = "SELECT * FROM page_view WHERE id=" . Trim($page_last_id);
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) { <tr>
$date = $row['date']; <td>Total Banned Users</td>
$tpage = $row['tpage']; <td><span class="label label-warning"><?php echo $total_ban; ?></span></td>
$tvisit = $row['tvisit']; </tr>
}
?>
<tr>
<td><?php echo $date; ?></td>
<td><?php echo $tvisit; ?></td>
<td><?php echo $tpage; ?></td>
</tr>
<?php
$page_last_id = $page_last_id - 1;
$query = "SELECT * FROM page_view WHERE id=" . Trim($page_last_id);
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) { <tr>
$date = $row['date']; <td>Unverified users</td>
$tpage = $row['tpage']; <td><span class="label label-warning"><?php echo $not_ver; ?></span></td>
$tvisit = $row['tvisit']; </tr>
}
?>
<tr>
<td><?php echo $date; ?></td>
<td><?php echo $tvisit; ?></td>
<td><?php echo $tpage; ?></td>
</tr>
<?php
$page_last_id = $page_last_id - 1;
$query = "SELECT * FROM page_view WHERE id=" . Trim($page_last_id);
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) { <tr>
$date = $row['date']; <td>Total Page Views</td>
$tpage = $row['tpage']; <td><span class="label label-default"><?php echo $total_page; ?></span></td>
$tvisit = $row['tvisit']; </tr>
}
?>
<tr>
<td><?php echo $date; ?></td>
<td><?php echo $tvisit; ?></td>
<td><?php echo $tpage; ?></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- End Statistics -->
</div>
<!-- END CONTAINER -->
<!-- Start Footer --> <tr>
<div class="row footer"> <td>Total Unique Visitors</td>
<div class="col-md-6 text-left"> <td><span class="label label-default"><?php echo $total_un; ?></span></td>
<a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a> </tr>
</div> </tbody>
<div class="col-md-6 text-right"> </table>
Powered by <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a> </div>
</div> </div>
</div> </div>
<!-- End Footer --> </div>
</div>
<!-- End content -->
<script type="text/javascript" src="js/jquery.min.js"></script> <?php
<script type="text/javascript" src="js/bootstrap.min.js"></script> $query = "SELECT @last_id := MAX(id) FROM page_view";
</body>
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
$page_last_id = $row['@last_id := MAX(id)'];
}
$query = "SELECT * FROM page_view WHERE id=" . Trim($page_last_id);
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
$date = $row['date'];
$tpage = $row['tpage'];
$tvisit = $row['tvisit'];
}
?>
<div class="row">
<div class="col-md-12">
<div class="panel panel-widget">
<div class="panel-body">
<div class="panel-title">Page Views</a></div>
<table class="table table-bordered">
<tbody>
<tr>
<th>Date</th>
<th>Unique Visitors</th>
<th>Views</th>
</tr>
<tr>
<td><?php echo $date; ?></td>
<td><?php echo $tvisit; ?></td>
<td><?php echo $tpage; ?></td>
</tr>
<?php
$page_last_id = $page_last_id - 1;
$query = "SELECT * FROM page_view WHERE id=" . Trim($page_last_id);
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
$date = $row['date'];
$tpage = $row['tpage'];
$tvisit = $row['tvisit'];
}
?>
<tr>
<td><?php echo $date; ?></td>
<td><?php echo $tvisit; ?></td>
<td><?php echo $tpage; ?></td>
</tr>
<?php
$page_last_id = $page_last_id - 1;
$query = "SELECT * FROM page_view WHERE id=" . Trim($page_last_id);
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
$date = $row['date'];
$tpage = $row['tpage'];
$tvisit = $row['tvisit'];
}
?>
<tr>
<td><?php echo $date; ?></td>
<td><?php echo $tvisit; ?></td>
<td><?php echo $tpage; ?></td>
</tr>
<?php
$page_last_id = $page_last_id - 1;
$query = "SELECT * FROM page_view WHERE id=" . Trim($page_last_id);
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
$date = $row['date'];
$tpage = $row['tpage'];
$tvisit = $row['tvisit'];
}
?>
<tr>
<td><?php echo $date; ?></td>
<td><?php echo $tvisit; ?></td>
<td><?php echo $tpage; ?></td>
</tr>
<?php
$page_last_id = $page_last_id - 1;
$query = "SELECT * FROM page_view WHERE id=" . Trim($page_last_id);
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
$date = $row['date'];
$tpage = $row['tpage'];
$tvisit = $row['tvisit'];
}
?>
<tr>
<td><?php echo $date; ?></td>
<td><?php echo $tvisit; ?></td>
<td><?php echo $tpage; ?></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- End Statistics -->
</div>
<!-- END CONTAINER -->
<!-- Start Footer -->
<div class="row footer">
<div class="col-md-6 text-left">
<a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a
href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a>
</div>
<div class="col-md-6 text-right">
Powered by <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a>
</div>
</div>
<!-- End Footer -->
</div>
<!-- End content -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
</body>
</html> </html>

View file

@ -24,14 +24,14 @@ if (isset($_SESSION['login'])) {
if (isset($_GET['logout'])) { if (isset($_GET['logout'])) {
if (isset($_SESSION['login'])) if (isset($_SESSION['login']))
unset($_SESSION['login']); unset($_SESSION['login']);
session_destroy(); session_destroy();
header("Location: ."); header("Location: .");
exit(); exit();
} }
$date = date('jS F Y'); $date = date('jS F Y');
$ip = $_SERVER['REMOTE_ADDR']; $ip = $_SERVER['REMOTE_ADDR'];
require_once('../config.php'); require_once('../config.php');
$con = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname); $con = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname);
@ -48,17 +48,17 @@ while ($row = mysqli_fetch_array($result)) {
$last_id = $row['@last_id := MAX(id)']; $last_id = $row['@last_id := MAX(id)'];
} }
$query = "SELECT * FROM admin_history WHERE id=" . Trim($last_id); $query = "SELECT * FROM admin_history WHERE id=" . Trim($last_id);
$result = mysqli_query($con, $query); $result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) { while ($row = mysqli_fetch_array($result)) {
$last_date = $row['last_date']; $last_date = $row['last_date'];
$last_ip = $row['ip']; $last_ip = $row['ip'];
} }
if ($last_ip == $ip) { if ($last_ip == $ip) {
if ($last_date == $date) { if ($last_date == $date) {
} else { } else {
$query = "INSERT INTO admin_history (last_date,ip) VALUES ('$date','$ip')"; $query = "INSERT INTO admin_history (last_date,ip) VALUES ('$date','$ip')";
mysqli_query($con, $query); mysqli_query($con, $query);
@ -71,200 +71,202 @@ if ($last_ip == $ip) {
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>Paste - Tasks</title> <title>Paste - Tasks</title>
<link rel="shortcut icon" href="favicon.ico"> <link rel="shortcut icon" href="favicon.ico">
<link href="css/paste.css" rel="stylesheet" type="text/css" /> <link href="css/paste.css" rel="stylesheet" type="text/css"/>
</head> </head>
<body> <body>
<div id="top" class="clearfix">
<!-- Start App Logo -->
<div class="applogo">
<a href="../" class="logo">Paste</a>
</div>
<!-- End App Logo -->
<!-- Start Top Right --> <div id="top" class="clearfix">
<ul class="top-right"> <!-- Start App Logo -->
<li class="dropdown link"> <div class="applogo">
<a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span class="caret"></span></a> <a href="../" class="logo">Paste</a>
<ul class="dropdown-menu dropdown-menu-list dropdown-menu-right"> </div>
<li><a href="admin.php">Settings</a></li> <!-- End App Logo -->
<li><a href="?logout">Logout</a></li>
</ul>
</li>
</ul>
<!-- End Top Right -->
</div>
<!-- END TOP -->
<div class="content"> <!-- Start Top Right -->
<!-- START CONTAINER --> <ul class="top-right">
<div class="container-widget"> <li class="dropdown link">
<!-- Start Menu --> <a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span
<div class="row"> class="caret"></span></a>
<div class="col-md-12"> <ul class="dropdown-menu dropdown-menu-list dropdown-menu-right">
<ul class="panel quick-menu clearfix"> <li><a href="admin.php">Settings</a></li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li><a href="?logout">Logout</a></li>
<a href="dashboard.php"><i class="fa fa-home"></i>Dashboard</a> </ul>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> </ul>
<a href="configuration.php"><i class="fa fa-cogs"></i>Configuration</a> <!-- End Top Right -->
</li> </div>
<li class="col-xs-3 col-sm-2 col-md-1"> <!-- END TOP -->
<a href="interface.php"><i class="fa fa-eye"></i>Interface</a>
</li> <div class="content">
<li class="col-xs-3 col-sm-2 col-md-1"> <!-- START CONTAINER -->
<a href="admin.php"><i class="fa fa-user"></i>Admin Account</a> <div class="container-widget">
</li> <!-- Start Menu -->
<li class="col-xs-3 col-sm-2 col-md-1"> <div class="row">
<a href="pastes.php"><i class="fa fa-clipboard"></i>Pastes</a> <div class="col-md-12">
</li> <ul class="panel quick-menu clearfix">
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="users.php"><i class="fa fa-users"></i>Users</a> <a href="dashboard.php"><i class="fa fa-home"></i>Dashboard</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="ipbans.php"><i class="fa fa-ban"></i>IP Bans</a> <a href="configuration.php"><i class="fa fa-cogs"></i>Configuration</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="stats.php"><i class="fa fa-line-chart"></i>Statistics</a> <a href="interface.php"><i class="fa fa-eye"></i>Interface</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="ads.php"><i class="fa fa-gbp"></i>Ads</a> <a href="admin.php"><i class="fa fa-user"></i>Admin Account</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="pages.php"><i class="fa fa-file"></i>Pages</a> <a href="pastes.php"><i class="fa fa-clipboard"></i>Pastes</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="sitemap.php"><i class="fa fa-map-signs"></i>Sitemap</a> <a href="users.php"><i class="fa fa-users"></i>Users</a>
</li> </li>
<li class="col-xs-3 col-sm-2 col-md-1 menu-active"> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="tasks.php"><i class="fa fa-tasks"></i>Tasks</a> <a href="ipbans.php"><i class="fa fa-ban"></i>IP Bans</a>
</li> </li>
</ul> <li class="col-xs-3 col-sm-2 col-md-1">
</div> <a href="stats.php"><i class="fa fa-line-chart"></i>Statistics</a>
</div> </li>
<!-- End Menu --> <li class="col-xs-3 col-sm-2 col-md-1">
<a href="ads.php"><i class="fa fa-gbp"></i>Ads</a>
<?php </li>
if ($_SERVER['REQUEST_METHOD'] == 'POST') { <li class="col-xs-3 col-sm-2 col-md-1">
//POST HANDLER <a href="pages.php"><i class="fa fa-file"></i>Pages</a>
</li>
} <li class="col-xs-3 col-sm-2 col-md-1">
if (isset($_GET['expired'])) { <a href="sitemap.php"><i class="fa fa-map-signs"></i>Sitemap</a>
$query = "SELECT * FROM pastes"; </li>
$result = mysqli_query($con, $query); <li class="col-xs-3 col-sm-2 col-md-1 menu-active">
while ($row = mysqli_fetch_array($result)) { <a href="tasks.php"><i class="fa fa-tasks"></i>Tasks</a>
$p_expiry = Trim($row['expiry']); </li>
$p_id = Trim($row['id']); </ul>
if ($p_expiry == "NULL" || $p_expiry == "SELF") { </div>
} else { </div>
$input_time = $p_expiry; <!-- End Menu -->
$current_time = mktime(date("H"), date("i"), date("s"), date("n"), date("j"), date("Y"));
if ($input_time < $current_time) { <?php
$query = "DELETE FROM pastes where id='$p_id'"; if ($_SERVER['REQUEST_METHOD'] == 'POST') {
mysqli_query($con, $query); //POST HANDLER
}
} }
} if (isset($_GET['expired'])) {
if (mysqli_errno($con)) { $query = "SELECT * FROM pastes";
$msg = '<div class="paste-alert alert6"> $result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
$p_expiry = Trim($row['expiry']);
$p_id = Trim($row['id']);
if ($p_expiry == "NULL" || $p_expiry == "SELF") {
} else {
$input_time = $p_expiry;
$current_time = mktime(date("H"), date("i"), date("s"), date("n"), date("j"), date("Y"));
if ($input_time < $current_time) {
$query = "DELETE FROM pastes where id='$p_id'";
mysqli_query($con, $query);
}
}
}
if (mysqli_errno($con)) {
$msg = '<div class="paste-alert alert6">
' . mysqli_error($con) . ' ' . mysqli_error($con) . '
</div>'; </div>';
} else { } else {
$msg = '<div class="paste-alert alert3"> $msg = '<div class="paste-alert alert3">
All expired pastes have been deleted All expired pastes have been deleted
</div>'; </div>';
} }
} }
if (isset($_GET['all_pastes'])) { if (isset($_GET['all_pastes'])) {
$query = "DELETE FROM pastes"; $query = "DELETE FROM pastes";
mysqli_query($con, $query); mysqli_query($con, $query);
if (mysqli_errno($con)) { if (mysqli_errno($con)) {
$msg = '<div class="paste-alert alert6"> $msg = '<div class="paste-alert alert6">
' . mysqli_error($con) . ' ' . mysqli_error($con) . '
</div>'; </div>';
} else { } else {
$msg = '<div class="paste-alert alert3"> $msg = '<div class="paste-alert alert3">
All pastes have been deleted All pastes have been deleted
</div>'; </div>';
} }
} }
if (isset($_GET['not_verfied'])) { if (isset($_GET['not_verfied'])) {
$query = "DELETE FROM users where verified='0'"; $query = "DELETE FROM users where verified='0'";
mysqli_query($con, $query); mysqli_query($con, $query);
if (mysqli_errno($con)) { if (mysqli_errno($con)) {
$msg = '<div class="paste-alert alert6"> $msg = '<div class="paste-alert alert6">
' . mysqli_error($con) . ' ' . mysqli_error($con) . '
</div>'; </div>';
} else { } else {
$msg = '<div class="paste-alert alert3"> $msg = '<div class="paste-alert alert3">
All unverified accounts have been deleted All unverified accounts have been deleted
</div>'; </div>';
} }
} }
if (isset($_GET['admin_history'])) { if (isset($_GET['admin_history'])) {
$query = "DELETE FROM admin_history"; $query = "DELETE FROM admin_history";
mysqli_query($con, $query); mysqli_query($con, $query);
if (mysqli_errno($con)) { if (mysqli_errno($con)) {
$msg = '<div class="paste-alert alert6"> $msg = '<div class="paste-alert alert6">
' . mysqli_error($con) . ' ' . mysqli_error($con) . '
</div>'; </div>';
} else { } else {
$msg = '<div class="paste-alert alert3"> $msg = '<div class="paste-alert alert3">
Admin history has been cleared Admin history has been cleared
</div>'; </div>';
} }
} }
?> ?>
<!-- Start Tasks -->
<div class="row">
<div class="col-md-12">
<div class="panel panel-widget">
<div class="panel-body">
<div class="panel-title">Maintenance tasks</a></div>
<?php if (isset($msg)) echo $msg; ?>
<a href="?expired" class="btn btn-default btn-block">Delete all expired pastes</a>
<br />
<a href="?admin_history" class="btn btn-info btn-block">Clear admin history</a>
<br />
<a href="?not_verfied" class="btn btn-warning btn-block">Delete unverified accounts</a>
<br />
<a href="?all_pastes" class="btn btn-danger btn-block">Delete all pastes</a>
</div>
</div>
</div>
</div>
<!-- End Tasks -->
</div>
<!-- END CONTAINER -->
<!-- Start Footer --> <!-- Start Tasks -->
<div class="row footer"> <div class="row">
<div class="col-md-6 text-left"> <div class="col-md-12">
<a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a> <div class="panel panel-widget">
</div> <div class="panel-body">
<div class="col-md-6 text-right"> <div class="panel-title">Maintenance tasks</a></div>
Powered by <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a> <?php if (isset($msg)) echo $msg; ?>
</div> <a href="?expired" class="btn btn-default btn-block">Delete all expired pastes</a>
</div> <br/>
<!-- End Footer --> <a href="?admin_history" class="btn btn-info btn-block">Clear admin history</a>
</div> <br/>
<!-- End content --> <a href="?not_verfied" class="btn btn-warning btn-block">Delete unverified accounts</a>
<br/>
<a href="?all_pastes" class="btn btn-danger btn-block">Delete all pastes</a>
</div>
</div>
</div>
</div>
<!-- End Tasks -->
</div>
<!-- END CONTAINER -->
<script type="text/javascript" src="js/jquery.min.js"></script> <!-- Start Footer -->
<script type="text/javascript" src="js/bootstrap.min.js"></script> <div class="row footer">
</body> <div class="col-md-6 text-left">
<a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a
href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a>
</div>
<div class="col-md-6 text-right">
Powered by <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a>
</div>
</div>
<!-- End Footer -->
</div>
<!-- End content -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
</body>
</html> </html>

View file

@ -24,14 +24,14 @@ if (isset($_SESSION['login'])) {
if (isset($_GET['logout'])) { if (isset($_GET['logout'])) {
if (isset($_SESSION['login'])) if (isset($_SESSION['login']))
unset($_SESSION['login']); unset($_SESSION['login']);
session_destroy(); session_destroy();
header("Location: ."); header("Location: .");
exit(); exit();
} }
$date = date('jS F Y'); $date = date('jS F Y');
$ip = $_SERVER['REMOTE_ADDR']; $ip = $_SERVER['REMOTE_ADDR'];
require_once('../config.php'); require_once('../config.php');
$con = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname); $con = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname);
@ -48,17 +48,17 @@ while ($row = mysqli_fetch_array($result)) {
$last_id = $row['@last_id := MAX(id)']; $last_id = $row['@last_id := MAX(id)'];
} }
$query = "SELECT * FROM admin_history WHERE id=" . Trim($last_id); $query = "SELECT * FROM admin_history WHERE id=" . Trim($last_id);
$result = mysqli_query($con, $query); $result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) { while ($row = mysqli_fetch_array($result)) {
$last_date = $row['last_date']; $last_date = $row['last_date'];
$last_ip = $row['ip']; $last_ip = $row['ip'];
} }
if ($last_ip == $ip) { if ($last_ip == $ip) {
if ($last_date == $date) { if ($last_date == $date) {
} else { } else {
$query = "INSERT INTO admin_history (last_date,ip) VALUES ('$date','$ip')"; $query = "INSERT INTO admin_history (last_date,ip) VALUES ('$date','$ip')";
mysqli_query($con, $query); mysqli_query($con, $query);
@ -71,229 +71,232 @@ if ($last_ip == $ip) {
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>Paste - Users</title> <title>Paste - Users</title>
<link rel="shortcut icon" href="favicon.ico"> <link rel="shortcut icon" href="favicon.ico">
<link href="css/paste.css" rel="stylesheet" type="text/css" /> <link href="css/paste.css" rel="stylesheet" type="text/css"/>
<link href="css/datatables.min.css" rel="stylesheet" type="text/css" /> <link href="css/datatables.min.css" rel="stylesheet" type="text/css"/>
</head> </head>
<body> <body>
<div id="top" class="clearfix">
<!-- Start App Logo -->
<div class="applogo">
<a href="../" class="logo">Paste</a>
</div>
<!-- End App Logo -->
<!-- Start Top Right --> <div id="top" class="clearfix">
<ul class="top-right"> <!-- Start App Logo -->
<li class="dropdown link"> <div class="applogo">
<a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span class="caret"></span></a> <a href="../" class="logo">Paste</a>
<ul class="dropdown-menu dropdown-menu-list dropdown-menu-right"> </div>
<li><a href="admin.php">Settings</a></li> <!-- End App Logo -->
<li><a href="?logout">Logout</a></li>
</ul>
</li>
</ul>
<!-- End Top Right -->
</div>
<!-- END TOP -->
<div class="content"> <!-- Start Top Right -->
<!-- START CONTAINER --> <ul class="top-right">
<div class="container-widget"> <li class="dropdown link">
<?php include 'menu.php';?> <a href="#" data-toggle="dropdown" class="dropdown-toggle profilebox"><b>Admin</b><span
<!-- End Menu --> class="caret"></span></a>
<ul class="dropdown-menu dropdown-menu-list dropdown-menu-right">
<?php <li><a href="admin.php">Settings</a></li>
if (isset($_GET['delete'])) { <li><a href="?logout">Logout</a></li>
$user_id = htmlentities(Trim($_GET['delete'])); </ul>
$query = "DELETE FROM users WHERE id=$user_id"; </li>
$result = mysqli_query($con, $query); </ul>
if (mysqli_errno($con)) { <!-- End Top Right -->
$msg = '<div class="paste-alert alert6" style="text-align: center;"> </div>
<!-- END TOP -->
<div class="content">
<!-- START CONTAINER -->
<div class="container-widget">
<?php include 'menu.php'; ?>
<!-- End Menu -->
<?php
if (isset($_GET['delete'])) {
$user_id = htmlentities(Trim($_GET['delete']));
$query = "DELETE FROM users WHERE id=$user_id";
$result = mysqli_query($con, $query);
if (mysqli_errno($con)) {
$msg = '<div class="paste-alert alert6" style="text-align: center;">
' . mysqli_error($con) . ' ' . mysqli_error($con) . '
</div>'; </div>';
} else { } else {
$msg = '<div class="paste-alert alert3" style="text-align: center;"> $msg = '<div class="paste-alert alert3" style="text-align: center;">
User deleted User deleted
</div>'; </div>';
} }
} }
if (isset($_GET['ban'])) { if (isset($_GET['ban'])) {
$ban_id = htmlentities(Trim($_GET['ban'])); $ban_id = htmlentities(Trim($_GET['ban']));
$query = "UPDATE users SET verified='2' WHERE id='$ban_id'"; $query = "UPDATE users SET verified='2' WHERE id='$ban_id'";
$result = mysqli_query($con, $query); $result = mysqli_query($con, $query);
if (mysqli_errno($con)) { if (mysqli_errno($con)) {
$msg = '<div class="paste-alert alert6" style="text-align: center;"> $msg = '<div class="paste-alert alert6" style="text-align: center;">
' . mysqli_error($con) . ' ' . mysqli_error($con) . '
</div>'; </div>';
} else { } else {
$msg = '<div class="paste-alert alert3" style="text-align: center;"> $msg = '<div class="paste-alert alert3" style="text-align: center;">
User banned User banned
</div>'; </div>';
} }
} }
if (isset($_GET['unban'])) { if (isset($_GET['unban'])) {
$ban_id = htmlentities(Trim($_GET['unban'])); $ban_id = htmlentities(Trim($_GET['unban']));
$query = "UPDATE users SET verified='1' WHERE id='$ban_id'"; $query = "UPDATE users SET verified='1' WHERE id='$ban_id'";
$result = mysqli_query($con, $query); $result = mysqli_query($con, $query);
if (mysqli_errno($con)) { if (mysqli_errno($con)) {
$msg = '<div class="paste-alert alert6" style="text-align: center;"> $msg = '<div class="paste-alert alert6" style="text-align: center;">
' . mysqli_error($con) . ' ' . mysqli_error($con) . '
</div>'; </div>';
} else { } else {
$msg = '<div class="paste-alert alert3" style="text-align: center;"> $msg = '<div class="paste-alert alert3" style="text-align: center;">
User unbanned User unbanned
</div>'; </div>';
} }
} }
?> ?>
<!-- Start Users -->
<div class="row">
<div class="col-md-12">
<div class="panel panel-widget">
<?php
if (isset($_GET['details'])) {
$detail_id = htmlentities(Trim($_GET['details']));
$query = "SELECT * FROM users WHERE id='$detail_id'";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
$user_oauth_uid = $row['oauth_uid'];
$user_username = $row['username'];
$user_email_id = $row['email_id'];
$user_full_name = $row['full_name'];
$user_platform = Trim($row['platform']);
$user_verified = $row['verified'];
$user_date = $row['date'];
$user_ip = $row['ip'];
}
if ($user_oauth_uid == '0') {
$user_oauth_uid = "None";
}
if ($user_verified == '0') {
$user_verified = "Unverified";
} elseif ($user_verified == '1') {
$user_verified = "Verified";
} elseif ($user_verified == '2') {
$user_verified = "Banned";
}
?>
<div class="panel-body">
<div class="panel-title">
<?php echo $user_username . ' Details'; ?>
</div>
<table class="table table-striped table-bordered"> <!-- Start Users -->
<tbody> <div class="row">
<tr> <div class="col-md-12">
<td> Username </td> <div class="panel panel-widget">
<td> <?php echo $user_username; ?> </td> <?php
</tr> if (isset($_GET['details'])) {
$detail_id = htmlentities(Trim($_GET['details']));
<tr> $query = "SELECT * FROM users WHERE id='$detail_id'";
<td> Email ID </td> $result = mysqli_query($con, $query);
<td> <?php echo $user_email_id;?> </td> while ($row = mysqli_fetch_array($result)) {
</tr> $user_oauth_uid = $row['oauth_uid'];
$user_username = $row['username'];
<tr> $user_email_id = $row['email_id'];
<td> Platform </td> $user_full_name = $row['full_name'];
<td> <?php echo $user_platform; ?> </td> $user_platform = Trim($row['platform']);
</tr> $user_verified = $row['verified'];
$user_date = $row['date'];
<tr> $user_ip = $row['ip'];
<td> OAUTH ID </td> }
<td> <?php echo $user_oauth_uid; ?> </td> if ($user_oauth_uid == '0') {
</tr> $user_oauth_uid = "None";
}
<tr> if ($user_verified == '0') {
<td> Status </td> $user_verified = "Unverified";
<td> <?php echo $user_verified; ?> </td> } elseif ($user_verified == '1') {
</tr> $user_verified = "Verified";
} elseif ($user_verified == '2') {
<tr> $user_verified = "Banned";
<td> User IP </td> }
<td> <?php echo $user_ip; ?> </td> ?>
</tr> <div class="panel-body">
<div class="panel-title">
<tr> <?php echo $user_username . ' Details'; ?>
<td> Date Registered </td> </div>
<td> <?php echo $user_date; ?> </td>
</tr>
<tr>
<td> Full Name </td>
<td> <?php echo $user_full_name; ?> </td>
</tr>
</tbody>
</table>
</div>
<?php } else { ?>
<div class="panel-body">
<div class="panel-title">
Manage Users
</div>
<?php if (isset($msg)) echo $msg; ?> <table class="table table-striped table-bordered">
<tbody>
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="usersTable"> <tr>
<thead> <td> Username</td>
<tr> <td> <?php echo $user_username; ?> </td>
<th>ID</th> </tr>
<th>Username</th>
<th>Email ID</th>
<th>Date Registered</th>
<th>Platform</th>
<th>Ban User</th>
<th>Profile</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<?php } ?>
</div>
</div>
</div>
<!-- End Admin Settings -->
</div>
<!-- END CONTAINER -->
<!-- Start Footer --> <tr>
<div class="row footer"> <td> Email ID</td>
<div class="col-md-6 text-left"> <td> <?php echo $user_email_id; ?> </td>
<a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a> </tr>
</div>
<div class="col-md-6 text-right">
Powered by <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a>
</div>
</div>
<!-- End Footer -->
</div>
<!-- End content -->
<script type="text/javascript" src="js/jquery.min.js"></script> <tr>
<script type="text/javascript" language="javascript" src="js/jquery.dataTables.js"></script> <td> Platform</td>
<script type="text/javascript" language="javascript" class="init"> <td> <?php echo $user_platform; ?> </td>
$(document).ready(function() { </tr>
$('#usersTable').dataTable( {
"processing": true, <tr>
"serverSide": true, <td> OAUTH ID</td>
"ajax": "ajax_users.php", <td> <?php echo $user_oauth_uid; ?> </td>
"order": [[0, "desc"]] </tr>
} );
} ); <tr>
</script> <td> Status</td>
<script type="text/javascript" src="js/bootstrap.min.js"></script> <td> <?php echo $user_verified; ?> </td>
</body> </tr>
<tr>
<td> User IP</td>
<td> <?php echo $user_ip; ?> </td>
</tr>
<tr>
<td> Date Registered</td>
<td> <?php echo $user_date; ?> </td>
</tr>
<tr>
<td> Full Name</td>
<td> <?php echo $user_full_name; ?> </td>
</tr>
</tbody>
</table>
</div>
<?php } else { ?>
<div class="panel-body">
<div class="panel-title">
Manage Users
</div>
<?php if (isset($msg)) echo $msg; ?>
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered"
id="usersTable">
<thead>
<tr>
<th>ID</th>
<th>Username</th>
<th>Email ID</th>
<th>Date Registered</th>
<th>Platform</th>
<th>Ban User</th>
<th>Profile</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<?php } ?>
</div>
</div>
</div>
<!-- End Admin Settings -->
</div>
<!-- END CONTAINER -->
<!-- Start Footer -->
<div class="row footer">
<div class="col-md-6 text-left">
<a href="https://github.com/jordansamuel/PASTE" target="_blank">Updates</a> &mdash; <a
href="https://github.com/jordansamuel/PASTE/issues" target="_blank">Bugs</a>
</div>
<div class="col-md-6 text-right">
Powered by <a href="https://phpaste.sourceforge.io" target="_blank">Paste</a>
</div>
</div>
<!-- End Footer -->
</div>
<!-- End content -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" language="javascript" src="js/jquery.dataTables.js"></script>
<script type="text/javascript" language="javascript" class="init">
$(document).ready(function () {
$('#usersTable').dataTable({
"processing": true,
"serverSide": true,
"ajax": "ajax_users.php",
"order": [[0, "desc"]]
});
});
</script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
</body>
</html> </html>

View file

@ -11,26 +11,26 @@ $primaryKey = 'id';
// parameter represents the DataTables column identifier. In this case simple // parameter represents the DataTables column identifier. In this case simple
// indexes // indexes
$columns = array( $columns = array(
array( 'db' => 'id', 'dt' => 0 ), array('db' => 'id', 'dt' => 0),
array( 'db' => 'title', 'dt' => 1 ), array('db' => 'title', 'dt' => 1),
array( 'db' => 'member', 'dt' => 2 ), array('db' => 'member', 'dt' => 2),
array( 'db' => 'tagsys', 'dt' => 3 ), array('db' => 'tagsys', 'dt' => 3),
array( 'db' => 'visible', 'dt' => 4 ), array('db' => 'visible', 'dt' => 4),
); );
$columns2 = array( $columns2 = array(
array( 'db' => 'title', 'dt' => 0 ), array('db' => 'title', 'dt' => 0),
array( 'db' => 'member', 'dt' => 1 ), array('db' => 'member', 'dt' => 1),
array( 'db' => 'tagsys', 'dt' => 2 ), array('db' => 'tagsys', 'dt' => 2),
); );
// SQL server connection information // SQL server connection information
$sql_details = array( $sql_details = array(
'user' => $db_user, 'user' => $db_user,
'pass' => $db_pass, 'pass' => $db_pass,
'db' => $db_schema, 'db' => $db_schema,
'host' => $db_host 'host' => $db_host
); );
@ -39,8 +39,8 @@ $sql_details = array(
* server-side, there is no need to edit below this line. * server-side, there is no need to edit below this line.
*/ */
require( 'ssp.pastes.php' ); require('ssp.pastes.php');
echo json_encode( echo json_encode(
SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns, $columns2 ) SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns, $columns2)
); );
?> ?>

View file

@ -4,40 +4,40 @@ header('Content-Type: application/json');
require_once('config.php'); require_once('config.php');
// DB table to use // DB table to use
$table = 'pastes'; $table = 'pastes';
// Table's primary key // Table's primary key
$primaryKey = 'id'; $primaryKey = 'id';
// Array of database columns which should be read and sent back to DataTables. // Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt` // The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple // parameter represents the DataTables column identifier. In this case simple
// indexes // indexes
$columns = array( $columns = array(
array( 'db' => 'id', 'dt' => 0 ), array('db' => 'id', 'dt' => 0),
array( 'db' => 'title', 'dt' => 1 ), array('db' => 'title', 'dt' => 1),
array( 'db' => 'member', 'dt' => 2 ), array('db' => 'member', 'dt' => 2),
array( 'db' => 'tagsys', 'dt' => 3 ), array('db' => 'tagsys', 'dt' => 3),
array( 'db' => 'visible', 'dt' => 4 ), array('db' => 'visible', 'dt' => 4),
array( 'db' => 'date', 'dt' => 5 ), array('db' => 'date', 'dt' => 5),
array( 'db' => 'now_time', 'dt' => 6 ), array('db' => 'now_time', 'dt' => 6),
); );
$columns2 = array( $columns2 = array(
array( 'db' => 'id', 'dt' => "ID" ), array('db' => 'id', 'dt' => "ID"),
array( 'db' => 'title', 'dt' => "Title" ), array('db' => 'title', 'dt' => "Title"),
array( 'db' => 'member', 'dt' => "Author" ), array('db' => 'member', 'dt' => "Author"),
array( 'db' => 'tagsys', 'dt' => "Tags" ), array('db' => 'tagsys', 'dt' => "Tags"),
array( 'db' => 'date', 'dt' => "Post Date" ), array('db' => 'date', 'dt' => "Post Date"),
array( 'db' => 'now_time', 'dt' => "Modified Date" ), array('db' => 'now_time', 'dt' => "Modified Date"),
); );
// SQL server connection information // SQL server connection information
$sql_details = array( $sql_details = array(
'user' => $dbuser, 'user' => $dbuser,
'pass' => $dbpassword, 'pass' => $dbpassword,
'db' => $dbname, 'db' => $dbname,
'host' => $dbhost 'host' => $dbhost
); );
@ -46,9 +46,9 @@ $sql_details = array(
* server-side, there is no need to edit below this line. * server-side, there is no need to edit below this line.
*/ */
require( 'public.pastes.php' ); require('public.pastes.php');
echo json_encode( echo json_encode(
SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns, $columns2), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns, $columns2), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
mysqli_close('$con'); mysqli_close('$con');
?> ?>

View file

@ -1,407 +1,392 @@
<?php <?php
class SSP { class SSP {
/** /**
* Create the data output array for the DataTables rows * Create the data output array for the DataTables rows
* *
* @param array $columns Column information array * @param array $columns Column information array
* @param array $data Data from the SQL get * @param array $data Data from the SQL get
* @return array Formatted data in a row based format * @return array Formatted data in a row based format
*/ */
static function data_output ( $columns, $data ) static function data_output($columns, $data) {
{ $out = array();
$out = array();
for ( $i=0, $ien=count($data) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($data); $i < $ien; $i++) {
$row = array(); $row = array();
for ( $j=0, $jen=count($columns) ; $j<$jen ; $j++ ) { for ($j = 0, $jen = count($columns); $j < $jen; $j++) {
$column = $columns[$j]; $column = $columns[$j];
// Is there a formatter? // Is there a formatter?
if ( isset( $column['formatter'] ) ) { if (isset($column['formatter'])) {
$row[ $column['dt'] ] = $column['formatter']( $data[$i][ $column['db'] ], $data[$i] ); $row[$column['dt']] = $column['formatter']($data[$i][$column['db']], $data[$i]);
} } else {
else { $row[$column['dt']] = $data[$i][$columns[$j]['db']];
$row[ $column['dt'] ] = $data[$i][ $columns[$j]['db'] ]; }
} }
}
$out[] = $row; $out[] = $row;
} }
return $out; return $out;
} }
/** /**
* Paging * Paging
* *
* Construct the LIMIT clause for server-side processing SQL query * Construct the LIMIT clause for server-side processing SQL query
* *
* @param array $request Data sent to server by DataTables * @param array $request Data sent to server by DataTables
* @param array $columns Column information array * @param array $columns Column information array
* @return string SQL limit clause * @return string SQL limit clause
*/ */
static function limit ( $request, $columns ) static function limit($request, $columns) {
{ $limit = '';
$limit = '';
if ( isset($request['start']) && $request['length'] != -1 ) { if (isset($request['start']) && $request['length'] != -1) {
$limit = "LIMIT ".intval($request['start']).", ".intval($request['length']); $limit = "LIMIT " . intval($request['start']) . ", " . intval($request['length']);
} }
return $limit; return $limit;
} }
/** /**
* Ordering * Ordering
* *
* Construct the ORDER BY clause for server-side processing SQL query * Construct the ORDER BY clause for server-side processing SQL query
* *
* @param array $request Data sent to server by DataTables * @param array $request Data sent to server by DataTables
* @param array $columns Column information array * @param array $columns Column information array
* @return string SQL order by clause * @return string SQL order by clause
*/ */
static function order ( $request, $columns ) static function order($request, $columns) {
{ $order = '';
$order = '';
if ( isset($request['order']) && count($request['order']) ) { if (isset($request['order']) && count($request['order'])) {
$orderBy = array(); $orderBy = array();
$dtColumns = self::pluck( $columns, 'dt' ); $dtColumns = self::pluck($columns, 'dt');
for ( $i=0, $ien=count($request['order']) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($request['order']); $i < $ien; $i++) {
// Convert the column index into the column data property // Convert the column index into the column data property
$columnIdx = intval($request['order'][$i]['column']); $columnIdx = intval($request['order'][$i]['column']);
$requestColumn = $request['columns'][$columnIdx]; $requestColumn = $request['columns'][$columnIdx];
$columnIdx = array_search( $requestColumn['data'], $dtColumns ); $columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $columns[ $columnIdx ]; $column = $columns[$columnIdx];
if ( $requestColumn['orderable'] == 'true' ) { if ($requestColumn['orderable'] == 'true') {
$dir = $request['order'][$i]['dir'] === 'DESC' ? $dir = $request['order'][$i]['dir'] === 'DESC' ?
'ASC' : 'ASC' :
'DESC'; 'DESC';
$orderBy[] = '`'.$column['db'].'` '.$dir; $orderBy[] = '`' . $column['db'] . '` ' . $dir;
} }
} }
$order = 'ORDER BY '.implode(', ', $orderBy); $order = 'ORDER BY ' . implode(', ', $orderBy);
} }
return $order; return $order;
} }
/** /**
* Searching / Filtering * Searching / Filtering
* *
* Construct the WHERE clause for server-side processing SQL query. * Construct the WHERE clause for server-side processing SQL query.
* *
* NOTE this does not match the built-in DataTables filtering which does it * NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here performance on large * word by word on any field. It's possible to do here performance on large
* databases would be very poor * databases would be very poor
* *
* @param array $request Data sent to server by DataTables * @param array $request Data sent to server by DataTables
* @param array $columns Column information array * @param array $columns Column information array
* @param array $bindings Array of values for PDO bindings, used in the * @param array $bindings Array of values for PDO bindings, used in the
* sql_exec() function * sql_exec() function
* @return string SQL where clause * @return string SQL where clause
*/ */
static function filter ( $request, $columns, &$bindings ) static function filter($request, $columns, &$bindings) {
{ $globalSearch = array();
$globalSearch = array(); $columnSearch = array();
$columnSearch = array(); $dtColumns = self::pluck($columns, 'dt');
$dtColumns = self::pluck( $columns, 'dt' );
if ( isset($request['search']) && $request['search']['value'] != '' ) { if (isset($request['search']) && $request['search']['value'] != '') {
$str = $request['search']['value']; $str = $request['search']['value'];
for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($request['columns']); $i < $ien; $i++) {
$requestColumn = $request['columns'][$i]; $requestColumn = $request['columns'][$i];
$columnIdx = array_search( $requestColumn['data'], $dtColumns ); $columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $columns[ $columnIdx ]; $column = $columns[$columnIdx];
if ( $requestColumn['searchable'] == 'true' ) { if ($requestColumn['searchable'] == 'true') {
$binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR ); $binding = self::bind($bindings, '%' . $str . '%', PDO::PARAM_STR);
$globalSearch[] = "`".$column['db']."` LIKE ".$binding; $globalSearch[] = "`" . $column['db'] . "` LIKE " . $binding;
} }
} }
} }
// Individual column filtering // Individual column filtering
for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($request['columns']); $i < $ien; $i++) {
$requestColumn = $request['columns'][$i]; $requestColumn = $request['columns'][$i];
$columnIdx = array_search( $requestColumn['data'], $dtColumns ); $columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $columns[ $columnIdx ]; $column = $columns[$columnIdx];
$str = $requestColumn['search']['value']; $str = $requestColumn['search']['value'];
if ( $requestColumn['searchable'] == 'true' && if ($requestColumn['searchable'] == 'true' &&
$str != '' ) { $str != '') {
$binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR ); $binding = self::bind($bindings, '%' . $str . '%', PDO::PARAM_STR);
$columnSearch[] = "`".$column['db']."` LIKE ".$binding; $columnSearch[] = "`" . $column['db'] . "` LIKE " . $binding;
} }
} }
// Combine the filters into a single string // Combine the filters into a single string
$where = ''; $where = '';
if ( count( $globalSearch ) ) { if (count($globalSearch)) {
$where = '('.implode(' OR ', $globalSearch).')'; $where = '(' . implode(' OR ', $globalSearch) . ')';
} }
if ( count( $columnSearch ) ) { if (count($columnSearch)) {
$where = $where === '' ? $where = $where === '' ?
implode(' AND ', $columnSearch) : implode(' AND ', $columnSearch) :
$where .' AND '. implode(' AND ', $columnSearch); $where . ' AND ' . implode(' AND ', $columnSearch);
} }
if ( $where !== '' ) { if ($where !== '') {
$where = 'WHERE '.$where; $where = 'WHERE ' . $where;
} }
return $where; return $where;
} }
/** /**
* Perform the SQL queries needed for an server-side processing requested, * Perform the SQL queries needed for an server-side processing requested,
* utilising the helper functions of this class, limit(), order() and * utilising the helper functions of this class, limit(), order() and
* filter() among others. The returned array is ready to be encoded as JSON * filter() among others. The returned array is ready to be encoded as JSON
* in response to an SSP request, or can be modified if needed before * in response to an SSP request, or can be modified if needed before
* sending back to the client. * sending back to the client.
* *
* @param array $request Data sent to server by DataTables * @param array $request Data sent to server by DataTables
* @param array $sql_details SQL connection details - see sql_connect() * @param array $sql_details SQL connection details - see sql_connect()
* @param string $table SQL table to query * @param string $table SQL table to query
* @param string $primaryKey Primary key of the table * @param string $primaryKey Primary key of the table
* @param array $columns Column information array * @param array $columns Column information array
* @return array Server-side processing response array * @return array Server-side processing response array
*/ */
static function simple ( $request, $sql_details, $table, $primaryKey, $columns, $columns2 ) static function simple($request, $sql_details, $table, $primaryKey, $columns, $columns2) {
{ $bindings = array();
$bindings = array(); $db = self::sql_connect($sql_details);
$db = self::sql_connect( $sql_details );
// Build the SQL query string from the request // Build the SQL query string from the request
$limit = self::limit( $request, $columns ); $limit = self::limit($request, $columns);
$order = self::order( $request, $columns ); $order = self::order($request, $columns);
$where = self::filter( $request, $columns, $bindings ); $where = self::filter($request, $columns, $bindings);
// Main query to actually get the data // Main query to actually get the data
$data = self::Ssql_exec($db, $bindings, $data = self::Ssql_exec($db, $bindings,
"SELECT SQL_CALC_FOUND_ROWS `".implode("`, `", self::pluck($columns, 'db'))."` "SELECT SQL_CALC_FOUND_ROWS `" . implode("`, `", self::pluck($columns, 'db')) . "`
FROM `$table` WHERE visible='0' AND tagsys IS NOT NULL AND NOT title LIKE '' FROM `$table` WHERE visible='0' AND tagsys IS NOT NULL AND NOT title LIKE ''
$order $order
$limit" $limit"
); );
// Data set length after filtering // Data set length after filtering
$resFilterLength = self::sql_exec( $db, $resFilterLength = self::sql_exec($db,
"SELECT FOUND_ROWS()" "SELECT FOUND_ROWS()"
); );
$recordsFiltered = $resFilterLength[0][0]; $recordsFiltered = $resFilterLength[0][0];
// Total data set length // Total data set length
$resTotalLength = self::sql_exec( $db, $resTotalLength = self::sql_exec($db,
"SELECT COUNT(`{$primaryKey}`) "SELECT COUNT(`{$primaryKey}`)
FROM `$table`" FROM `$table`"
); );
$recordsTotal = $resTotalLength[0][0]; $recordsTotal = $resTotalLength[0][0];
/* /*
* Output * Output
*/ */
return array( return array(
"draw" => intval( $request['draw'] ), "draw" => intval($request['draw']),
"recordsTotal" => intval( $recordsTotal ), "recordsTotal" => intval($recordsTotal),
"recordsFiltered" => intval( $recordsFiltered ), "recordsFiltered" => intval($recordsFiltered),
"data" => self::data_output( $columns2, $data ) "data" => self::data_output($columns2, $data)
); );
} }
/** /**
* Connect to the database * Connect to the database
* *
* @param array $sql_details SQL server connection details array, with the * @param array $sql_details SQL server connection details array, with the
* properties: * properties:
* * host - host name * * host - host name
* * db - database name * * db - database name
* * user - user name * * user - user name
* * pass - user password * * pass - user password
* @return resource Database connection handle * @return resource Database connection handle
*/ */
static function sql_connect ( $sql_details ) static function sql_connect($sql_details) {
{ try {
try { $db = @new PDO(
$db = @new PDO( "mysql:host={$sql_details['host']};dbname={$sql_details['db']}",
"mysql:host={$sql_details['host']};dbname={$sql_details['db']}", $sql_details['user'],
$sql_details['user'], $sql_details['pass'],
$sql_details['pass'], array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ) );
); } catch (PDOException $e) {
} self::fatal(
catch (PDOException $e) { "An error occurred while connecting to the database. " .
self::fatal( "The error reported by the server was: " . $e->getMessage()
"An error occurred while connecting to the database. ". );
"The error reported by the server was: ".$e->getMessage() }
);
}
return $db; return $db;
} }
/** /**
* Execute an SQL query on the database * Execute an SQL query on the database
* *
* @param resource $db Database handler * @param resource $db Database handler
* @param array $bindings Array of PDO binding values from bind() to be * @param array $bindings Array of PDO binding values from bind() to be
* used for safely escaping strings. Note that this can be given as the * used for safely escaping strings. Note that this can be given as the
* SQL query string if no bindings are required. * SQL query string if no bindings are required.
* @param string $sql SQL query to execute. * @param string $sql SQL query to execute.
* @return array Result from the query (all rows) * @return array Result from the query (all rows)
*/ */
static function sql_exec ( $db, $bindings, $sql=null ) static function sql_exec($db, $bindings, $sql = null) {
{ // Argument shifting
// Argument shifting if ($sql === null) {
if ( $sql === null ) { $sql = $bindings;
$sql = $bindings; }
}
$stmt = $db->prepare( $sql ); $stmt = $db->prepare($sql);
//echo $sql; //echo $sql;
// Bind parameters // Bind parameters
if ( is_array( $bindings ) ) { if (is_array($bindings)) {
for ( $i=0, $ien=count($bindings) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($bindings); $i < $ien; $i++) {
$binding = $bindings[$i]; $binding = $bindings[$i];
$stmt->bindValue( $binding['key'], $binding['val'], $binding['type'] ); $stmt->bindValue($binding['key'], $binding['val'], $binding['type']);
} }
} }
// Execute // Execute
try { try {
$stmt->execute(); $stmt->execute();
} } catch (PDOException $e) {
catch (PDOException $e) { self::fatal("An SQL error occurred: " . $e->getMessage());
self::fatal( "An SQL error occurred: ".$e->getMessage() ); }
} $result = $stmt->fetchAll();
$result= $stmt->fetchAll(); return $result;
return $result; }
}
static function Ssql_exec ($db, $bindings, $sql=null )
{
// Argument shifting
if ( $sql === null ) {
$sql = $bindings;
}
$stmt = $db->prepare( $sql ); static function Ssql_exec($db, $bindings, $sql = null) {
// Argument shifting
if ($sql === null) {
$sql = $bindings;
}
// Bind parameters $stmt = $db->prepare($sql);
if ( is_array( $bindings ) ) {
for ( $i=0, $ien=count($bindings) ; $i<$ien ; $i++ ) {
$binding = $bindings[$i];
$stmt->bindValue( $binding['key'], $binding['val'], $binding['type'] );
}
}
// Execute // Bind parameters
try { if (is_array($bindings)) {
$stmt->execute(); for ($i = 0, $ien = count($bindings); $i < $ien; $i++) {
} $binding = $bindings[$i];
catch (PDOException $e) { $stmt->bindValue($binding['key'], $binding['val'], $binding['type']);
self::fatal( "An SQL error occurred: ".$e->getMessage() ); }
} }
// Execute
try {
$stmt->execute();
} catch (PDOException $e) {
self::fatal("An SQL error occurred: " . $e->getMessage());
}
$loop = '0'; $loop = '0';
while ($arr = $stmt->fetch(PDO::FETCH_ASSOC)) { while ($arr = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[$loop]['id']= $arr['id']; $result[$loop]['id'] = $arr['id'];
$result[$loop]['title']= html_entity_decode($arr['title']); $result[$loop]['title'] = html_entity_decode($arr['title']);
$result[$loop]['member']= $arr['member']; $result[$loop]['member'] = $arr['member'];
$result[$loop]['tagsys']= $arr['tagsys']; $result[$loop]['tagsys'] = $arr['tagsys'];
$date_time = strtotime($arr['date']); $date_time = strtotime($arr['date']);
$result[$loop]['date']= date(DATE_ISO8601, $date_time); $result[$loop]['date'] = date(DATE_ISO8601, $date_time);
$myupdate = $arr['now_time']; $myupdate = $arr['now_time'];
$result[$loop]['now_time']= date(DATE_ISO8601, $myupdate); $result[$loop]['now_time'] = date(DATE_ISO8601, $myupdate);
$loop = $loop +1;
$loop = $loop + 1;
} }
// Return all
return $result;
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Return all
* Internal methods return $result;
*/ }
/** /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Throw a fatal error. * Internal methods
* */
* This writes out an error message in a JSON string which DataTables will
* see and show to the user in the browser.
*
* @param string $msg Message to send to the client
*/
static function fatal ( $msg )
{
echo json_encode( array(
"error" => $msg
) );
exit(0); /**
} * Throw a fatal error.
*
* This writes out an error message in a JSON string which DataTables will
* see and show to the user in the browser.
*
* @param string $msg Message to send to the client
*/
static function fatal($msg) {
echo json_encode(array(
"error" => $msg
));
/** exit(0);
* Create a PDO binding key which can be used for escaping variables safely }
* when executing a query with sql_exec()
*
* @param array &$a Array of bindings
* @param * $val Value to bind
* @param int $type PDO field type
* @return string Bound key to be used in the SQL where this parameter
* would be used.
*/
static function bind ( &$a, $val, $type )
{
$key = ':binding_'.count( $a );
$a[] = array( /**
'key' => $key, * Create a PDO binding key which can be used for escaping variables safely
'val' => $val, * when executing a query with sql_exec()
'type' => $type *
); * @param array &$a Array of bindings
* @param * $val Value to bind
* @param int $type PDO field type
* @return string Bound key to be used in the SQL where this parameter
* would be used.
*/
static function bind(&$a, $val, $type) {
$key = ':binding_' . count($a);
return $key; $a[] = array(
} 'key' => $key,
'val' => $val,
'type' => $type
);
return $key;
}
/** /**
* Pull a particular property from each assoc. array in a numeric array, * Pull a particular property from each assoc. array in a numeric array,
* returning and array of the property values from each item. * returning and array of the property values from each item.
* *
* @param array $a Array to get data from * @param array $a Array to get data from
* @param string $prop Property to read * @param string $prop Property to read
* @return array Array of property values * @return array Array of property values
*/ */
static function pluck ( $a, $prop ) static function pluck($a, $prop) {
{ $out = array();
$out = array();
for ( $i=0, $len=count($a) ; $i<$len ; $i++ ) { for ($i = 0, $len = count($a); $i < $len; $i++) {
$out[] = $a[$i][$prop]; $out[] = $a[$i][$prop];
} }
return $out; return $out;
} }
} }
?> ?>

View file

@ -4,434 +4,416 @@
?> ?>
<?php <?php
function sandwitch($str){ function sandwitch($str) {
$output = ""; $output = "";
$arr = explode(",", $str); $arr = explode(",", $str);
foreach ($arr as $word){ foreach ($arr as $word) {
$word = ucfirst($word); $word = ucfirst($word);
if (stripos($word, 'nsfw') !== false) { if (stripos($word, 'nsfw') !== false) {
$word = strtoupper($word); $word = strtoupper($word);
$tagcolor = "tag is-danger"; $tagcolor = "tag is-danger";
} } elseif (stripos($word, 'SAFE') !== false) {
elseif (stripos($word, 'SAFE') !== false) { $word = strtoupper($word);
$word = strtoupper($word); $tagcolor = "tag is-success";
$tagcolor = "tag is-success"; } elseif (strstr($word, '/')) {
} $tagcolor = "tag is-primary";
elseif (strstr($word, '/')){ } else {
$tagcolor = "tag is-primary"; $tagcolor = "tag is-info";
}else{ }
$tagcolor = "tag is-info"; $output .= '<a href="/archive?q=' . trim($word) . '"><span class="' . $tagcolor . '">' . trim($word) . '</span>';
} }
$output .= '<a href="/archive?q='.trim($word).'"><span class="' . $tagcolor . '">'.trim($word).'</span>'; return $output;
}
return $output;
} }
class SSP { class SSP {
/** /**
* Create the data output array for the DataTables rows * Create the data output array for the DataTables rows
* *
* @param array $columns Column information array * @param array $columns Column information array
* @param array $data Data from the SQL get * @param array $data Data from the SQL get
* @return array Formatted data in a row based format * @return array Formatted data in a row based format
*/ */
static function data_output ( $columns, $data ) static function data_output($columns, $data) {
{ $out = array();
$out = array();
for ( $i=0, $ien=count($data) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($data); $i < $ien; $i++) {
$row = array(); $row = array();
for ( $j=0, $jen=count($columns) ; $j<$jen ; $j++ ) { for ($j = 0, $jen = count($columns); $j < $jen; $j++) {
$column = $columns[$j]; $column = $columns[$j];
// Is there a formatter? // Is there a formatter?
if ( isset( $column['formatter'] ) ) { if (isset($column['formatter'])) {
$row[ $column['dt'] ] = $column['formatter']( $data[$i][ $column['db'] ], $data[$i] ); $row[$column['dt']] = $column['formatter']($data[$i][$column['db']], $data[$i]);
} } else {
else { $row[$column['dt']] = $data[$i][$columns[$j]['db']];
$row[ $column['dt'] ] = $data[$i][ $columns[$j]['db'] ]; }
} }
}
$out[] = $row; $out[] = $row;
} }
return $out; return $out;
} }
/** /**
* Paging * Paging
* *
* Construct the LIMIT clause for server-side processing SQL query * Construct the LIMIT clause for server-side processing SQL query
* *
* @param array $request Data sent to server by DataTables * @param array $request Data sent to server by DataTables
* @param array $columns Column information array * @param array $columns Column information array
* @return string SQL limit clause * @return string SQL limit clause
*/ */
static function limit ( $request, $columns ) static function limit($request, $columns) {
{ $limit = '';
$limit = '';
if ( isset($request['start']) && $request['length'] != -1 ) { if (isset($request['start']) && $request['length'] != -1) {
$limit = "LIMIT ".intval($request['start']).", ".intval($request['length']); $limit = "LIMIT " . intval($request['start']) . ", " . intval($request['length']);
} }
return $limit; return $limit;
} }
/** /**
* Ordering * Ordering
* *
* Construct the ORDER BY clause for server-side processing SQL query * Construct the ORDER BY clause for server-side processing SQL query
* *
* @param array $request Data sent to server by DataTables * @param array $request Data sent to server by DataTables
* @param array $columns Column information array * @param array $columns Column information array
* @return string SQL order by clause * @return string SQL order by clause
*/ */
static function order ( $request, $columns ) static function order($request, $columns) {
{ $order = '';
$order = '';
if ( isset($request['order']) && count($request['order']) ) { if (isset($request['order']) && count($request['order'])) {
$orderBy = array(); $orderBy = array();
$dtColumns = self::pluck( $columns, 'dt' ); $dtColumns = self::pluck($columns, 'dt');
for ( $i=0, $ien=count($request['order']) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($request['order']); $i < $ien; $i++) {
// Convert the column index into the column data property // Convert the column index into the column data property
$columnIdx = intval($request['order'][$i]['column']); $columnIdx = intval($request['order'][$i]['column']);
$requestColumn = $request['columns'][$columnIdx]; $requestColumn = $request['columns'][$columnIdx];
$columnIdx = array_search( $requestColumn['data'], $dtColumns ); $columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $columns[ $columnIdx ]; $column = $columns[$columnIdx];
if ( $requestColumn['orderable'] == 'true' ) { if ($requestColumn['orderable'] == 'true') {
$dir = $request['order'][$i]['dir'] === 'DESC' ? $dir = $request['order'][$i]['dir'] === 'DESC' ?
'ASC' : 'ASC' :
'DESC'; 'DESC';
$orderBy[] = '`'.$column['db'].'` '.$dir; $orderBy[] = '`' . $column['db'] . '` ' . $dir;
} }
} }
$order = 'ORDER BY '.implode(', ', $orderBy); $order = 'ORDER BY ' . implode(', ', $orderBy);
} }
return $order; return $order;
} }
/** /**
* Searching / Filtering * Searching / Filtering
* *
* Construct the WHERE clause for server-side processing SQL query. * Construct the WHERE clause for server-side processing SQL query.
* *
* NOTE this does not match the built-in DataTables filtering which does it * NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here performance on large * word by word on any field. It's possible to do here performance on large
* databases would be very poor * databases would be very poor
* *
* @param array $request Data sent to server by DataTables * @param array $request Data sent to server by DataTables
* @param array $columns Column information array * @param array $columns Column information array
* @param array $bindings Array of values for PDO bindings, used in the * @param array $bindings Array of values for PDO bindings, used in the
* sql_exec() function * sql_exec() function
* @return string SQL where clause * @return string SQL where clause
*/ */
static function filter ( $request, $columns, &$bindings ) static function filter($request, $columns, &$bindings) {
{ $globalSearch = array();
$globalSearch = array(); $columnSearch = array();
$columnSearch = array(); $dtColumns = self::pluck($columns, 'dt');
$dtColumns = self::pluck( $columns, 'dt' );
if ( isset($request['search']) && $request['search']['value'] != '' ) { if (isset($request['search']) && $request['search']['value'] != '') {
$str = $request['search']['value']; $str = $request['search']['value'];
for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($request['columns']); $i < $ien; $i++) {
$requestColumn = $request['columns'][$i]; $requestColumn = $request['columns'][$i];
$columnIdx = array_search( $requestColumn['data'], $dtColumns ); $columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $columns[ $columnIdx ]; $column = $columns[$columnIdx];
if ( $requestColumn['searchable'] == 'true' ) { if ($requestColumn['searchable'] == 'true') {
$binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR ); $binding = self::bind($bindings, '%' . $str . '%', PDO::PARAM_STR);
$globalSearch[] = "`".$column['db']."` LIKE ".$binding; $globalSearch[] = "`" . $column['db'] . "` LIKE " . $binding;
} }
} }
} }
// Individual column filtering // Individual column filtering
for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($request['columns']); $i < $ien; $i++) {
$requestColumn = $request['columns'][$i]; $requestColumn = $request['columns'][$i];
$columnIdx = array_search( $requestColumn['data'], $dtColumns ); $columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $columns[ $columnIdx ]; $column = $columns[$columnIdx];
$str = $requestColumn['search']['value']; $str = $requestColumn['search']['value'];
if ( $requestColumn['searchable'] == 'true' && if ($requestColumn['searchable'] == 'true' &&
$str != '' ) { $str != '') {
$binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR ); $binding = self::bind($bindings, '%' . $str . '%', PDO::PARAM_STR);
$columnSearch[] = "`".$column['db']."` LIKE ".$binding; $columnSearch[] = "`" . $column['db'] . "` LIKE " . $binding;
} }
} }
// Combine the filters into a single string // Combine the filters into a single string
$where = ''; $where = '';
if ( count( $globalSearch ) ) { if (count($globalSearch)) {
$where = '('.implode(' OR ', $globalSearch).')'; $where = '(' . implode(' OR ', $globalSearch) . ')';
} }
if ( count( $columnSearch ) ) { if (count($columnSearch)) {
$where = $where === '' ? $where = $where === '' ?
implode(' AND ', $columnSearch) : implode(' AND ', $columnSearch) :
$where .' AND '. implode(' AND ', $columnSearch); $where . ' AND ' . implode(' AND ', $columnSearch);
} }
if ( $where !== '' ) { if ($where !== '') {
$where = 'WHERE '.$where; $where = 'WHERE ' . $where;
} }
return $where; return $where;
} }
/** /**
* Perform the SQL queries needed for an server-side processing requested, * Perform the SQL queries needed for an server-side processing requested,
* utilising the helper functions of this class, limit(), order() and * utilising the helper functions of this class, limit(), order() and
* filter() among others. The returned array is ready to be encoded as JSON * filter() among others. The returned array is ready to be encoded as JSON
* in response to an SSP request, or can be modified if needed before * in response to an SSP request, or can be modified if needed before
* sending back to the client. * sending back to the client.
* *
* @param array $request Data sent to server by DataTables * @param array $request Data sent to server by DataTables
* @param array $sql_details SQL connection details - see sql_connect() * @param array $sql_details SQL connection details - see sql_connect()
* @param string $table SQL table to query * @param string $table SQL table to query
* @param string $primaryKey Primary key of the table * @param string $primaryKey Primary key of the table
* @param array $columns Column information array * @param array $columns Column information array
* @return array Server-side processing response array * @return array Server-side processing response array
*/ */
static function simple ( $request, $sql_details, $table, $primaryKey, $columns, $columns2 ) static function simple($request, $sql_details, $table, $primaryKey, $columns, $columns2) {
{ $bindings = array();
$bindings = array(); $db = self::sql_connect($sql_details);
$db = self::sql_connect( $sql_details );
// Build the SQL query string from the request // Build the SQL query string from the request
$limit = self::limit( $request, $columns ); $limit = self::limit($request, $columns);
$order = self::order( $request, $columns ); $order = self::order($request, $columns);
//$where = self::filter( $request, $columns, $bindings ); //$where = self::filter( $request, $columns, $bindings );
// Main query to actually get the data // Main query to actually get the data
$data = self::Ssql_exec($db, $bindings, $data = self::Ssql_exec($db, $bindings,
"SELECT SQL_CALC_FOUND_ROWS `".implode("`, `", self::pluck($columns, 'db'))."` "SELECT SQL_CALC_FOUND_ROWS `" . implode("`, `", self::pluck($columns, 'db')) . "`
FROM `$table` WHERE visible='0' AND tagsys IS NOT NULL AND NOT title LIKE '' FROM `$table` WHERE visible='0' AND tagsys IS NOT NULL AND NOT title LIKE ''
$order $order
$limit" $limit"
); );
// Data set length after filtering // Data set length after filtering
$resFilterLength = self::sql_exec( $db, $resFilterLength = self::sql_exec($db,
"SELECT FOUND_ROWS()" "SELECT FOUND_ROWS()"
); );
$recordsFiltered = $resFilterLength[0][0]; $recordsFiltered = $resFilterLength[0][0];
// Total data set length // Total data set length
$resTotalLength = self::sql_exec( $db, $resTotalLength = self::sql_exec($db,
"SELECT COUNT(`{$primaryKey}`) "SELECT COUNT(`{$primaryKey}`)
FROM `$table`" FROM `$table`"
); );
$recordsTotal = $resTotalLength[0][0]; $recordsTotal = $resTotalLength[0][0];
/* /*
* Output * Output
*/ */
return array( return array(
"draw" => isset($request['draw']) ? intval( $request['draw'] ) : 0, "draw" => isset($request['draw']) ? intval($request['draw']) : 0,
"recordsTotal" => intval( $recordsTotal ), "recordsTotal" => intval($recordsTotal),
"recordsFiltered" => intval( $recordsFiltered ), "recordsFiltered" => intval($recordsFiltered),
"data" => self::data_output( $columns2, $data ) "data" => self::data_output($columns2, $data)
); );
} }
/** /**
* Connect to the database * Connect to the database
* *
* @param array $sql_details SQL server connection details array, with the * @param array $sql_details SQL server connection details array, with the
* properties: * properties:
* * host - host name * * host - host name
* * db - database name * * db - database name
* * user - user name * * user - user name
* * pass - user password * * pass - user password
* @return PDO Database connection handle * @return PDO Database connection handle
*/ */
static function sql_connect ( $sql_details ) static function sql_connect($sql_details) {
{ try {
try { $db = @new PDO(
$db = @new PDO( "mysql:host={$sql_details['host']};dbname={$sql_details['db']}",
"mysql:host={$sql_details['host']};dbname={$sql_details['db']}", $sql_details['user'],
$sql_details['user'], $sql_details['pass'],
$sql_details['pass'], array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ) );
); } catch (PDOException $e) {
} self::fatal(
catch (PDOException $e) { "An error occurred while connecting to the database. " .
self::fatal( "The error reported by the server was: " . $e->getMessage()
"An error occurred while connecting to the database. ". );
"The error reported by the server was: ".$e->getMessage() }
);
}
return $db; return $db;
} }
/** /**
* Execute an SQL query on the database * Execute an SQL query on the database
* *
* @param resource $db Database handler * @param resource $db Database handler
* @param array $bindings Array of PDO binding values from bind() to be * @param array $bindings Array of PDO binding values from bind() to be
* used for safely escaping strings. Note that this can be given as the * used for safely escaping strings. Note that this can be given as the
* SQL query string if no bindings are required. * SQL query string if no bindings are required.
* @param string $sql SQL query to execute. * @param string $sql SQL query to execute.
* @return array Result from the query (all rows) * @return array Result from the query (all rows)
*/ */
static function sql_exec ( $db, $bindings, $sql=null ) static function sql_exec($db, $bindings, $sql = null) {
{ // Argument shifting
// Argument shifting if ($sql === null) {
if ( $sql === null ) { $sql = $bindings;
$sql = $bindings; }
}
$stmt = $db->prepare( $sql ); $stmt = $db->prepare($sql);
//echo $sql; //echo $sql;
// Bind parameters // Bind parameters
if ( is_array( $bindings ) ) { if (is_array($bindings)) {
for ( $i=0, $ien=count($bindings) ; $i<$ien ; $i++ ) { for ($i = 0, $ien = count($bindings); $i < $ien; $i++) {
$binding = $bindings[$i]; $binding = $bindings[$i];
$stmt->bindValue( $binding['key'], $binding['val'], $binding['type'] ); $stmt->bindValue($binding['key'], $binding['val'], $binding['type']);
} }
} }
// Execute // Execute
try { try {
$stmt->execute(); $stmt->execute();
} } catch (PDOException $e) {
catch (PDOException $e) { self::fatal("An SQL error occurred: " . $e->getMessage());
self::fatal( "An SQL error occurred: ".$e->getMessage() ); }
} $result = $stmt->fetchAll();
$result= $stmt->fetchAll(); return $result;
return $result; }
}
static function Ssql_exec ($db, $bindings, $sql=null )
{
// Argument shifting
if ( $sql === null ) {
$sql = $bindings;
}
$stmt = $db->prepare( $sql ); static function Ssql_exec($db, $bindings, $sql = null) {
// Argument shifting
if ($sql === null) {
$sql = $bindings;
}
// Bind parameters $stmt = $db->prepare($sql);
if ( is_array( $bindings ) ) {
for ( $i=0, $ien=count($bindings) ; $i<$ien ; $i++ ) {
$binding = $bindings[$i];
$stmt->bindValue( $binding['key'], $binding['val'], $binding['type'] );
}
}
// Execute // Bind parameters
try { if (is_array($bindings)) {
$stmt->execute(); for ($i = 0, $ien = count($bindings); $i < $ien; $i++) {
} $binding = $bindings[$i];
catch (PDOException $e) { $stmt->bindValue($binding['key'], $binding['val'], $binding['type']);
self::fatal( "An SQL error occurred: ".$e->getMessage() ); }
} }
// Execute
try {
$stmt->execute();
} catch (PDOException $e) {
self::fatal("An SQL error occurred: " . $e->getMessage());
}
$loop = '0'; $loop = '0';
while ($arr = $stmt->fetch(PDO::FETCH_ASSOC)) { while ($arr = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[$loop]['id']= $arr['id']; $result[$loop]['id'] = $arr['id'];
$result[$loop]['member']= $arr['member']; $result[$loop]['member'] = $arr['member'];
$result[$loop]['tagsys']= sandwitch( $arr['tagsys']); $result[$loop]['tagsys'] = sandwitch($arr['tagsys']);
$date_time = strtotime(isset($arr['date']) ? $arr['date'] : '0'); $date_time = strtotime(isset($arr['date']) ? $arr['date'] : '0');
$result[$loop]['date']= date("d F Y", $date_time); $result[$loop]['date'] = date("d F Y", $date_time);
$myid = $arr['id']; $myid = $arr['id'];
$mytitle = $arr['title']; $mytitle = $arr['title'];
$mymember = $arr['member']; $mymember = $arr['member'];
$result[$loop]['title'] ="<a href=/" . $myid . ">" . $mytitle . "</a>"; $result[$loop]['title'] = "<a href=/" . $myid . ">" . $mytitle . "</a>";
$result[$loop]['member'] ="<a href=/user/" . $mymember . ">" . $mymember . "</a>"; $result[$loop]['member'] = "<a href=/user/" . $mymember . ">" . $mymember . "</a>";
$loop = $loop +1; $loop = $loop + 1;
} }
// Return all
return $result;
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Return all
* Internal methods return $result;
*/ }
/** /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Throw a fatal error. * Internal methods
* */
* This writes out an error message in a JSON string which DataTables will
* see and show to the user in the browser.
*
* @param string $msg Message to send to the client
*/
static function fatal ( $msg )
{
echo json_encode( array(
"error" => $msg
) );
exit(0); /**
} * Throw a fatal error.
*
* This writes out an error message in a JSON string which DataTables will
* see and show to the user in the browser.
*
* @param string $msg Message to send to the client
*/
static function fatal($msg) {
echo json_encode(array(
"error" => $msg
));
/** exit(0);
* Create a PDO binding key which can be used for escaping variables safely }
* when executing a query with sql_exec()
*
* @param array &$a Array of bindings
* @param * $val Value to bind
* @param int $type PDO field type
* @return string Bound key to be used in the SQL where this parameter
* would be used.
*/
static function bind ( &$a, $val, $type )
{
$key = ':binding_'.count( $a );
$a[] = array( /**
'key' => $key, * Create a PDO binding key which can be used for escaping variables safely
'val' => $val, * when executing a query with sql_exec()
'type' => $type *
); * @param array &$a Array of bindings
* @param * $val Value to bind
* @param int $type PDO field type
* @return string Bound key to be used in the SQL where this parameter
* would be used.
*/
static function bind(&$a, $val, $type) {
$key = ':binding_' . count($a);
return $key; $a[] = array(
} 'key' => $key,
'val' => $val,
'type' => $type
);
return $key;
}
/** /**
* Pull a particular property from each assoc. array in a numeric array, * Pull a particular property from each assoc. array in a numeric array,
* returning and array of the property values from each item. * returning and array of the property values from each item.
* *
* @param array $a Array to get data from * @param array $a Array to get data from
* @param string $prop Property to read * @param string $prop Property to read
* @return array Array of property values * @return array Array of property values
*/ */
static function pluck ( $a, $prop ) static function pluck($a, $prop) {
{ $out = array();
$out = array();
for ( $i=0, $len=count($a) ; $i<$len ; $i++ ) { for ($i = 0, $len = count($a); $i < $len; $i++) {
$out[] = $a[$i][$prop]; $out[] = $a[$i][$prop];
} }
return $out; return $out;
} }
} }
?> ?>

View file

@ -19,7 +19,7 @@ require_once('includes/common.php');
// UTF-8 // UTF-8
header('Content-Type: text/html; charset=utf-8'); header('Content-Type: text/html; charset=utf-8');
$date = date('jS F Y'); $date = date('jS F Y');
// Temp count for untagged pastes // Temp count for untagged pastes
$total_untagged = intval($conn->query("SELECT COUNT(*) from pastes WHERE tagsys IS NULL")->fetch(PDO::FETCH_NUM)[0]); $total_untagged = intval($conn->query("SELECT COUNT(*) from pastes WHERE tagsys IS NULL")->fetch(PDO::FETCH_NUM)[0]);

View file

@ -25,7 +25,7 @@ $currentversion = 2.2;
// The value we got on installation of Paste was: post_max_size = 128M // The value we got on installation of Paste was: post_max_size = 128M
// Otherwise, the maximum value that can be set is 4000 (4GB) // Otherwise, the maximum value that can be set is 4000 (4GB)
$pastelimit = "1"; // 0.5 = 512 kilobytes, 1 = 1MB $pastelimit = "1"; // 0.5 = 512 kilobytes, 1 = 1MB
// OAUTH (to enable, change to yes and edit) // OAUTH (to enable, change to yes and edit)
$enablefb = "no"; $enablefb = "no";
$enablegoog = "no"; $enablegoog = "no";
@ -57,12 +57,12 @@ if (gethostname() === 'thunderlane') {
$db_opts = [ $db_opts = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, /* throw a fatal exception on database errors */ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, /* throw a fatal exception on database errors */
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, /* Fetch rows as an associative array (hash table) by default */ PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, /* Fetch rows as an associative array (hash table) by default */
PDO::ATTR_EMULATE_PREPARES => false PDO::ATTR_EMULATE_PREPARES => false
]; ];
// Secret key for paste encryption // Secret key for paste encryption
$sec_key = "8ac67343e7980b16b31e8311d4377bbb"; $sec_key = "8ac67343e7980b16b31e8311d4377bbb";
define('SECRET',md5($sec_key)); define('SECRET', md5($sec_key));
// Set to 1 to enable Apache's mod_rewrite // Set to 1 to enable Apache's mod_rewrite
$mod_rewrite = "1"; $mod_rewrite = "1";
@ -77,9 +77,9 @@ $geshiformats = [
// Popular formats that are listed first. // Popular formats that are listed first.
$popular_formats = [ $popular_formats = [
'green', 'green',
'text', 'text',
'pastedown', 'pastedown',
'pastedown_old' 'pastedown_old'
]; ];

View file

@ -20,8 +20,8 @@ require_once('includes/functions.php');
// UTF-8 // UTF-8
header('Content-Type: text/html; charset=utf-8'); header('Content-Type: text/html; charset=utf-8');
$date = date('jS F Y'); $date = date('jS F Y');
$ip = $_SERVER['REMOTE_ADDR']; $ip = $_SERVER['REMOTE_ADDR'];
$p_title = $lang['archive']; // "Pastes Archive"; $p_title = $lang['archive']; // "Pastes Archive";

84
fav.php
View file

@ -7,48 +7,48 @@ require_once('includes/functions.php');
// UTF-8 // UTF-8
header('Content-Type: text/html; charset=utf-8'); header('Content-Type: text/html; charset=utf-8');
$date = date('jS F Y'); $date = date('jS F Y');
$ip = $_SERVER['REMOTE_ADDR']; $ip = $_SERVER['REMOTE_ADDR'];
$data_ip = file_get_contents('tmp/temp.tdata'); $data_ip = file_get_contents('tmp/temp.tdata');
$con = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname); $con = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname);
if (mysqli_connect_errno()) { if (mysqli_connect_errno()) {
die("Unable to connect to database"); die("Unable to connect to database");
} }
$query = "SELECT * FROM site_info"; $query = "SELECT * FROM site_info";
$result = mysqli_query($con, $query); $result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) { while ($row = mysqli_fetch_array($result)) {
$title = Trim($row['title']); $title = Trim($row['title']);
$des = Trim($row['des']); $des = Trim($row['des']);
$baseurl = Trim($row['baseurl']); $baseurl = Trim($row['baseurl']);
$keyword = Trim($row['keyword']); $keyword = Trim($row['keyword']);
$site_name = Trim($row['site_name']); $site_name = Trim($row['site_name']);
$email = Trim($row['email']); $email = Trim($row['email']);
$twit = Trim($row['twit']); $twit = Trim($row['twit']);
$face = Trim($row['face']); $face = Trim($row['face']);
$gplus = Trim($row['gplus']); $gplus = Trim($row['gplus']);
$ga = Trim($row['ga']); $ga = Trim($row['ga']);
$additional_scripts = Trim($row['additional_scripts']); $additional_scripts = Trim($row['additional_scripts']);
} }
// Set theme and language // Set theme and language
$query = "SELECT * FROM interface"; $query = "SELECT * FROM interface";
$result = mysqli_query($con, $query); $result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) { while ($row = mysqli_fetch_array($result)) {
$default_lang = Trim($row['lang']); $default_lang = Trim($row['lang']);
$default_theme = Trim($row['theme']); $default_theme = Trim($row['theme']);
} }
require_once("langs/$default_lang"); require_once("langs/$default_lang");
// Check if IP is banned // Check if IP is banned
if ( is_banned($con, $ip) ) die($lang['banned']); // "You have been banned from ".$site_name; if (is_banned($con, $ip)) die($lang['banned']); // "You have been banned from ".$site_name;
// Logout // Logout
if (isset($_GET['logout'])) { if (isset($_GET['logout'])) {
header('Location: ' . $_SERVER['HTTP_REFERER']); header('Location: ' . $_SERVER['HTTP_REFERER']);
unset($_SESSION['token']); unset($_SESSION['token']);
unset($_SESSION['oauth_uid']); unset($_SESSION['oauth_uid']);
unset($_SESSION['username']); unset($_SESSION['username']);
@ -56,34 +56,34 @@ if (isset($_GET['logout'])) {
} }
//Fav paste //Fav paste
if (isset($_POST['fid'])) { if (isset($_POST['fid'])) {
if (isset($_SESSION['token'])) { if (isset($_SESSION['token'])) {
$f_user = htmlspecialchars($_SESSION['username']); $f_user = htmlspecialchars($_SESSION['username']);
$f_pasteid = Trim(htmlspecialchars($_POST['fid'])); $f_pasteid = Trim(htmlspecialchars($_POST['fid']));
$f_pasteid = preg_replace( '/[^0-9]/', '', $f_pasteid ); $f_pasteid = preg_replace('/[^0-9]/', '', $f_pasteid);
$f_pasteid = (int) filter_var($f_pasteid, FILTER_SANITIZE_NUMBER_INT); $f_pasteid = (int)filter_var($f_pasteid, FILTER_SANITIZE_NUMBER_INT);
$f_time = gmmktime(date("H"), date("i"), date("s"), date("n"), date("j"), date("Y")); $f_time = gmmktime(date("H"), date("i"), date("s"), date("n"), date("j"), date("Y"));
//Sec //Sec
$f_user = mysqli_real_escape_string($con, $f_user); $f_user = mysqli_real_escape_string($con, $f_user);
$f_pasteid = mysqli_real_escape_string($con,$f_pasteid); $f_pasteid = mysqli_real_escape_string($con, $f_pasteid);
$f_time = mysqli_real_escape_string($con,$f_time); $f_time = mysqli_real_escape_string($con, $f_time);
$fav_check = "SELECT COUNT(fid) FROM pins WHERE f_paste='$f_pasteid' AND m_fav='$f_user'"; $fav_check = "SELECT COUNT(fid) FROM pins WHERE f_paste='$f_pasteid' AND m_fav='$f_user'";
$result = mysqli_query($con, $fav_check); $result = mysqli_query($con, $fav_check);
$count = mysqli_fetch_row($result)[0]; $count = mysqli_fetch_row($result)[0];
if($count == 0 ){ if ($count == 0) {
$faved = "INSERT INTO pins (m_fav,f_paste,f_time) VALUES $faved = "INSERT INTO pins (m_fav,f_paste,f_time) VALUES
('$f_user','$f_pasteid ','$f_time')"; ('$f_user','$f_pasteid ','$f_time')";
}else{ } else {
$faved = "DELETE FROM pins WHERE f_paste='$f_pasteid' and m_fav='$f_user'"; $faved = "DELETE FROM pins WHERE f_paste='$f_pasteid' and m_fav='$f_user'";
}
if ($con->query($faved) === true) {
$error = "Paste has been Favorited.";
} else {
$error = "Fav failed";
}
}
} }
if ($con->query($faved) === TRUE) {
$error = "Paste has been Favorited.";
} else {
$error = "Fav failed";
}
}}
// Theme // Theme

View file

@ -1,23 +1,22 @@
<?php <?php
$servername = "localhost"; $servername = "localhost";
$username = "root"; $username = "root";
$password = ""; $password = "";
$dbname = "lab"; $dbname = "lab";
// Create connection // Create connection
$conn = new mysqli($servername, $username, $password, $dbname); $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection // Check connection
if ($conn->connect_error) { if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); die("Connection failed: " . $conn->connect_error);
} }
$method = $_GET['method']; $method = $_GET['method'];
$user_id = $_GET['user_id']; $user_id = $_GET['user_id'];
$director_id = $_GET['director_id']; $director_id = $_GET['director_id'];
if ($method == "Like") { if ($method == "Like") {
mysqli_query($conn,"INSERT INTO favs (user_id, director_id) VALUES ('$user_id', '$director_id')"); mysqli_query($conn, "INSERT INTO favs (user_id, director_id) VALUES ('$user_id', '$director_id')");
} } else {
else { mysqli_query($conn, "DELETE FROM favs WHERE user_id = '$user_id' AND director_id = '$director_id'");
mysqli_query($conn,"DELETE FROM favs WHERE user_id = '$user_id' AND director_id = '$director_id'"); }
}
?> ?>

View file

@ -1,69 +1,69 @@
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head> <head>
<script src="jquery.min.js"></script> <script src="jquery.min.js"></script>
<script type="text/javascript"> <script type="text/javascript">
jQuery(document).ready(function($){ jQuery(document).ready(function ($) {
$('.button').on('click', function(e){ $('.button').on('click', function (e) {
e.preventDefault(); e.preventDefault();
var user_id = $(this).attr('user_id'); // Get the parameter user_id from the button var user_id = $(this).attr('user_id'); // Get the parameter user_id from the button
var director_id = $(this).attr('director_id'); // Get the parameter director_id from the button var director_id = $(this).attr('director_id'); // Get the parameter director_id from the button
var method = $(this).attr('method'); // Get the parameter method from the button var method = $(this).attr('method'); // Get the parameter method from the button
if (method == "Like") { if (method == "Like") {
$(this).attr('method', 'Unlike') // Change the div method attribute to Unlike $(this).attr('method', 'Unlike') // Change the div method attribute to Unlike
$('#' + director_id).replaceWith('<img class="favicon" id="' + director_id + '" src="favon.jpg">') // Replace the image with the liked button $('#' + director_id).replaceWith('<img class="favicon" id="' + director_id + '" src="favon.jpg">') // Replace the image with the liked button
} else { } else {
$(this).attr('method', 'Like') $(this).attr('method', 'Like')
$('#' + director_id).replaceWith('<img class="favicon" id="' + director_id + '" src="favoff.png">') $('#' + director_id).replaceWith('<img class="favicon" id="' + director_id + '" src="favoff.png">')
} }
$.ajax({ $.ajax({
url: 'favs.php', // Call favs.php to update the database url: 'favs.php', // Call favs.php to update the database
type: 'GET', type: 'GET',
data: {user_id: user_id, director_id: director_id, method: method}, data: {user_id: user_id, director_id: director_id, method: method},
cache: false, cache: false,
success: function(data){ success: function (data) {
} }
}); });
}); });
}); });
</script> </script>
</head> </head>
<body> <body>
<?php <?php
$servername = "localhost"; $servername = "localhost";
$username = "P0nedbAcc0unt"; $username = "P0nedbAcc0unt";
$password = "1NWO6Tp17IFz9lbl"; $password = "1NWO6Tp17IFz9lbl";
$dbname = "p0nepast3s"; $dbname = "p0nepast3s";
// Create connection // Create connection
$conn = new mysqli($servername, $username, $password, $dbname); $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection // Check connection
if ($conn->connect_error) { if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); die("Connection failed: " . $conn->connect_error);
} }
function checkFavorite($user_id, $director_id, $conn) { function checkFavorite($user_id, $director_id, $conn) {
$result = $conn->query("SELECT * FROM favs WHERE user_id = '". $user_id."' AND director_id = '". $director_id."'"); $result = $conn->query("SELECT * FROM favs WHERE user_id = '" . $user_id . "' AND director_id = '" . $director_id . "'");
$numrows = $result->num_rows; $numrows = $result->num_rows;
if ($numrows == 0) { if ($numrows == 0) {
echo "<div class = 'button' method = 'Like' user_id = ".$user_id." director_id = ".$director_id."> <img id=".$director_id." src='favoff.png'> </div>"; echo "<div class = 'button' method = 'Like' user_id = " . $user_id . " director_id = " . $director_id . "> <img id=" . $director_id . " src='favoff.png'> </div>";
} } else {
else { echo "<div class = 'button' method = 'Unlike' user_id = " . $user_id . " director_id = " . $director_id . "> <img id=" . $director_id . " src='favon.jpg'> </div>";
echo "<div class = 'button' method = 'Unlike' user_id = ".$user_id." director_id = ".$director_id."> <img id=".$director_id." src='favon.jpg'> </div>"; }
} }
}
// Query to get the user_id
$result = $conn->query("SELECT * FROM user WHERE name = 'Henrique'");
$row = $result->fetch_assoc();
$user_id = $row['id'];
// Query to Get the Director ID // Query to get the user_id
$result = $conn->query("SELECT * FROM director WHERE name = 'Donal'"); $result = $conn->query("SELECT * FROM user WHERE name = 'Henrique'");
$row = $result->fetch_assoc(); $row = $result->fetch_assoc();
$director_id = $row['id']; $user_id = $row['id'];
echo "<p>Director: ".$row['name']."</p> "; // Query to Get the Director ID
$fav_image = checkFavorite($user_id, $director_id, $conn); $result = $conn->query("SELECT * FROM director WHERE name = 'Donal'");
echo "Favorite? : ".$fav_image.""; $row = $result->fetch_assoc();
?> $director_id = $row['id'];
</body>
echo "<p>Director: " . $row['name'] . "</p> ";
$fav_image = checkFavorite($user_id, $director_id, $conn);
echo "Favorite? : " . $fav_image . "";
?>
</body>
</html> </html>

View file

@ -20,20 +20,17 @@ namespace ArdiSSoebrata\BeamParsedown;
use ParsedownExtra; use ParsedownExtra;
class BeamParsedown extends ParsedownExtra class BeamParsedown extends ParsedownExtra {
{
const version = '0.0.1'; const version = '0.0.1';
protected $isUrlRegex = "/(https?|ftp)\:\/\//i"; protected $isUrlRegex = "/(https?|ftp)\:\/\//i";
protected $regexAttribute = '(?:([#.][\w-]+\s*)|([\w-]+=[\w-]+\s*))+'; protected $regexAttribute = '(?:([#.][\w-]+\s*)|([\w-]+=[\w-]+\s*))+';
function __construct() function __construct() {
{
parent::__construct(); parent::__construct();
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
if (version_compare(parent::version, '0.8.1') < 0) if (version_compare(parent::version, '0.8.1') < 0) {
{ throw new Exception('BeamParsedown requires a later version of ParsedownExtra');
throw new Exception('BeamParsedown requires a later version of ParsedownExtra');
} }
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
@ -53,18 +50,15 @@ class BeamParsedown extends ParsedownExtra
protected $basePath = ''; protected $basePath = '';
public function setBasePath($url) public function setBasePath($url) {
{
$this->basePath = preg_replace('{/$}', '', $url) . '/'; $this->basePath = preg_replace('{/$}', '', $url) . '/';
return $this; return $this;
} }
protected function inlineImage($excerpt) protected function inlineImage($excerpt) {
{
$image = parent::inlineImage($excerpt); $image = parent::inlineImage($excerpt);
if ( ! isset($image)) if (!isset($image)) {
{
return null; return null;
} }
@ -79,11 +73,10 @@ class BeamParsedown extends ParsedownExtra
// Heading id & attributes. // Heading id & attributes.
protected function blockHeader($Line) protected function blockHeader($Line) {
{
$Block = parent::blockHeader($Line); $Block = parent::blockHeader($Line);
if (! isset($Block)) { if (!isset($Block)) {
return null; return null;
} }
@ -96,8 +89,7 @@ class BeamParsedown extends ParsedownExtra
return $Block; return $Block;
} }
protected function blockSetextHeader($Line, array $Block = null) protected function blockSetextHeader($Line, array $Block = null) {
{
$Block = parent::blockSetextHeader($Line, $Block); $Block = parent::blockSetextHeader($Line, $Block);
if (isset($Block['element']) && !isset($Block['element']['attributes']['id'])) { if (isset($Block['element']) && !isset($Block['element']['attributes']['id'])) {
@ -109,38 +101,29 @@ class BeamParsedown extends ParsedownExtra
return $Block; return $Block;
} }
protected function parseAttributeData($attributeString) protected function parseAttributeData($attributeString) {
{
$Data = array(); $Data = array();
$attributes = preg_split('/[ ]+/', $attributeString, - 1, PREG_SPLIT_NO_EMPTY); $attributes = preg_split('/[ ]+/', $attributeString, -1, PREG_SPLIT_NO_EMPTY);
foreach ($attributes as $attribute) foreach ($attributes as $attribute) {
{ if ($attribute[0] === '#') {
if ($attribute[0] === '#')
{
$Data['id'] = substr($attribute, 1); $Data['id'] = substr($attribute, 1);
} } elseif ($attribute[0] === '.') {
elseif ($attribute[0] === '.') $classes [] = substr($attribute, 1);
{ } elseif (preg_match('/([\w-]+)=([\w-]+)/', $attribute, $match)) {
$classes []= substr($attribute, 1);
}
elseif (preg_match('/([\w-]+)=([\w-]+)/', $attribute, $match))
{
$Data[$match[1]] = $match[2]; $Data[$match[1]] = $match[2];
} }
} }
if (isset($classes)) if (isset($classes)) {
{
$Data['class'] = implode(' ', $classes); $Data['class'] = implode(' ', $classes);
} }
return $Data; return $Data;
} }
public static function slugify($text) public static function slugify($text) {
{
// replace non letter or digits by - // replace non letter or digits by -
$text = preg_replace('~[^\pL\d]+~u', '-', $text); $text = preg_replace('~[^\pL\d]+~u', '-', $text);
@ -165,17 +148,15 @@ class BeamParsedown extends ParsedownExtra
return $text; return $text;
} }
// Icon // Icon
protected function InlineIcon($excerpt) protected function InlineIcon($excerpt) {
{ if (preg_match('/\[icon:(.+?)\]/', $excerpt['text'], $matches)) {
if (preg_match('/\[icon:(.+?)\]/', $excerpt['text'], $matches))
{
return array( return array(
// How many characters to advance the Parsedown's // How many characters to advance the Parsedown's
// cursor after being done processing this tag. // cursor after being done processing this tag.
'extent' => strlen($matches[0]), 'extent' => strlen($matches[0]),
'element' => array( 'element' => array(
'name' => 'i', 'name' => 'i',
'attributes' => array( 'attributes' => array(
@ -189,10 +170,8 @@ class BeamParsedown extends ParsedownExtra
// Audio // Audio
protected function InlineAudio($excerpt) protected function InlineAudio($excerpt) {
{ if (preg_match('/\[audio:(.+?)\]/', $excerpt['text'], $matches)) {
if (preg_match('/\[audio:(.+?)\]/', $excerpt['text'], $matches))
{
// Add basePath if src is relative. // Add basePath if src is relative.
$src = trim($matches[1]); $src = trim($matches[1]);
if (!preg_match($this->isUrlRegex, $src, $urlmatch)) { if (!preg_match($this->isUrlRegex, $src, $urlmatch)) {
@ -202,7 +181,7 @@ class BeamParsedown extends ParsedownExtra
return array( return array(
// How many characters to advance the Parsedown's // How many characters to advance the Parsedown's
// cursor after being done processing this tag. // cursor after being done processing this tag.
'extent' => strlen($matches[0]), 'extent' => strlen($matches[0]),
'element' => array( 'element' => array(
'name' => 'audio', 'name' => 'audio',
'attributes' => array( 'attributes' => array(
@ -222,16 +201,14 @@ class BeamParsedown extends ParsedownExtra
} }
// Youtube // Youtube
protected function BlockYoutube($excerpt) protected function BlockYoutube($excerpt) {
{ if (preg_match('/\[youtube:\s*https\:\/\/youtu\.be\/(.+?)\]/', $excerpt['text'], $matches)) {
if (preg_match('/\[youtube:\s*https\:\/\/youtu\.be\/(.+?)\]/', $excerpt['text'], $matches))
{
$video_id = trim($matches[1]); $video_id = trim($matches[1]);
return array( return array(
// How many characters to advance the Parsedown's // How many characters to advance the Parsedown's
// cursor after being done processing this tag. // cursor after being done processing this tag.
'extent' => strlen($matches[0]), 'extent' => strlen($matches[0]),
'element' => array( 'element' => array(
'name' => 'div', 'name' => 'div',
'attributes' => array( 'attributes' => array(
@ -270,11 +247,9 @@ class BeamParsedown extends ParsedownExtra
) )
); );
protected function BlockAlert($line, $block) protected function BlockAlert($line, $block) {
{
$types = implode('|', array_keys($this->alert_types)); $types = implode('|', array_keys($this->alert_types));
if (preg_match('/^:::(' . $types . ')/', $line['text'], $matches)) if (preg_match('/^:::(' . $types . ')/', $line['text'], $matches)) {
{
$type = trim($matches[1]); $type = trim($matches[1]);
return array( return array(
'char' => $line['text'][0], 'char' => $line['text'][0],
@ -314,42 +289,35 @@ class BeamParsedown extends ParsedownExtra
} }
} }
protected function BlockAlertContinue($line, $block) protected function BlockAlertContinue($line, $block) {
{ if (isset($block['complete'])) {
if (isset($block['complete']))
{
return; return;
} }
// A blank newline has occurred. // A blank newline has occurred.
if (isset($block['interrupted'])) if (isset($block['interrupted'])) {
{
unset($block['interrupted']); unset($block['interrupted']);
} }
// Check for end of the block. // Check for end of the block.
if (preg_match('/^:::/', $line['text'])) if (preg_match('/^:::/', $line['text'])) {
{
$block['complete'] = true; $block['complete'] = true;
return $block; return $block;
} }
$block['element']['text'][1]['text'][] = $line['body']; $block['element']['text'][1]['text'][] = $line['body'];
return $block; return $block;
} }
protected function BlockAlertComplete($block) protected function BlockAlertComplete($block) {
{
return $block; return $block;
} }
// draw.io // draw.io
protected function BlockDrawio($excerpt) protected function BlockDrawio($excerpt) {
{ if (preg_match('/\[drawio:\s*(.+?)\]/', $excerpt['text'], $matches)) {
if (preg_match('/\[drawio:\s*(.+?)\]/', $excerpt['text'], $matches))
{
$file = trim($matches[1]); $file = trim($matches[1]);
if (!preg_match($this->isUrlRegex, $file, $urlmatch)) { if (!preg_match($this->isUrlRegex, $file, $urlmatch)) {
$file = $this->basePath . $file; $file = $this->basePath . $file;
@ -357,7 +325,7 @@ class BeamParsedown extends ParsedownExtra
return array( return array(
// How many characters to advance the Parsedown's // How many characters to advance the Parsedown's
// cursor after being done processing this tag. // cursor after being done processing this tag.
'extent' => strlen($matches[0]), 'extent' => strlen($matches[0]),
'element' => array( 'element' => array(
'name' => 'div', 'name' => 'div',
'handler' => 'elements', 'handler' => 'elements',
@ -393,10 +361,8 @@ class BeamParsedown extends ParsedownExtra
// Mermaid // Mermaid
protected function BlockMermaid($line, $block) protected function BlockMermaid($line, $block) {
{ if (preg_match('/^:::\s*mermaid/', $line['text'], $matches)) {
if (preg_match('/^:::\s*mermaid/', $line['text'], $matches))
{
return array( return array(
'char' => $line['text'][0], 'char' => $line['text'][0],
'element' => array( 'element' => array(
@ -410,42 +376,35 @@ class BeamParsedown extends ParsedownExtra
} }
} }
protected function BlockMermaidContinue($line, $block) protected function BlockMermaidContinue($line, $block) {
{ if (isset($block['complete'])) {
if (isset($block['complete']))
{
return; return;
} }
// A blank newline has occurred. // A blank newline has occurred.
if (isset($block['interrupted'])) if (isset($block['interrupted'])) {
{
unset($block['interrupted']); unset($block['interrupted']);
} }
// Check for end of the block. // Check for end of the block.
if (preg_match('/^:::/', $line['text'])) if (preg_match('/^:::/', $line['text'])) {
{
$block['complete'] = true; $block['complete'] = true;
return $block; return $block;
} }
$block['element']['rawHtml'] .= $line['body'] . "\n"; $block['element']['rawHtml'] .= $line['body'] . "\n";
return $block; return $block;
} }
protected function BlockMermaidComplete($block) protected function BlockMermaidComplete($block) {
{
return $block; return $block;
} }
// Chart JS // Chart JS
protected function BlockChart($line, $block) protected function BlockChart($line, $block) {
{ if (preg_match('/^:::\s*chart/', $line['text'], $matches)) {
if (preg_match('/^:::\s*chart/', $line['text'], $matches))
{
return array( return array(
'char' => $line['text'][0], 'char' => $line['text'][0],
'element' => array( 'element' => array(
@ -459,33 +418,28 @@ class BeamParsedown extends ParsedownExtra
} }
} }
protected function BlockChartContinue($line, $block) protected function BlockChartContinue($line, $block) {
{ if (isset($block['complete'])) {
if (isset($block['complete']))
{
return; return;
} }
// A blank newline has occurred. // A blank newline has occurred.
if (isset($block['interrupted'])) if (isset($block['interrupted'])) {
{
unset($block['interrupted']); unset($block['interrupted']);
} }
// Check for end of the block. // Check for end of the block.
if (preg_match('/^:::/', $line['text'])) if (preg_match('/^:::/', $line['text'])) {
{
$block['complete'] = true; $block['complete'] = true;
return $block; return $block;
} }
$block['element']['rawHtml'] .= $line['body'] . "\n"; $block['element']['rawHtml'] .= $line['body'] . "\n";
return $block; return $block;
} }
protected function BlockChartComplete($block) protected function BlockChartComplete($block) {
{
return $block; return $block;
} }
} }

View file

@ -4,15 +4,13 @@ namespace ArdiSSoebrata\BeamParsedown;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
class BeamParsedownServiceProvider extends ServiceProvider class BeamParsedownServiceProvider extends ServiceProvider {
{
/** /**
* Perform post-registration booting of services. * Perform post-registration booting of services.
* *
* @return void * @return void
*/ */
public function boot(): void public function boot() : void {
{
// $this->loadTranslationsFrom(__DIR__.'/../resources/lang', ':lc:vendor'); // $this->loadTranslationsFrom(__DIR__.'/../resources/lang', ':lc:vendor');
// $this->loadViewsFrom(__DIR__.'/../resources/views', ':lc:vendor'); // $this->loadViewsFrom(__DIR__.'/../resources/views', ':lc:vendor');
// $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); // $this->loadMigrationsFrom(__DIR__.'/../database/migrations');
@ -29,14 +27,13 @@ class BeamParsedownServiceProvider extends ServiceProvider
* *
* @return void * @return void
*/ */
public function register(): void public function register() : void {
{ $this->mergeConfigFrom(__DIR__ . '/../config/beam-parsedown.php', 'beam-parsedown');
$this->mergeConfigFrom(__DIR__.'/../config/beam-parsedown.php', 'beam-parsedown');
// Register the service the package provides. // Register the service the package provides.
$this->app->singleton('beam-parsedown', function ($app) { $this->app->singleton('beam-parsedown', function ($app) {
$parse = new BeamParsedown(); $parse = new BeamParsedown();
// Set from config. // Set from config.
$parse->setBreaksEnabled(config('beam-parsedown.breaks_enabled', false)); $parse->setBreaksEnabled(config('beam-parsedown.breaks_enabled', false));
$parse->setMarkupEscaped(config('beam-parsedown.markup_escaped', false)); $parse->setMarkupEscaped(config('beam-parsedown.markup_escaped', false));
@ -52,8 +49,7 @@ class BeamParsedownServiceProvider extends ServiceProvider
* *
* @return array * @return array
*/ */
public function provides() public function provides() {
{
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
return ['beam-parsedown']; return ['beam-parsedown'];
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
@ -64,11 +60,10 @@ class BeamParsedownServiceProvider extends ServiceProvider
* *
* @return void * @return void
*/ */
protected function bootForConsole(): void protected function bootForConsole() : void {
{
// Publishing the configuration file. // Publishing the configuration file.
$this->publishes([ $this->publishes([
__DIR__.'/../config/beam-parsedown.php' => config_path('beam-parsedown.php'), __DIR__ . '/../config/beam-parsedown.php' => config_path('beam-parsedown.php'),
], 'beam-parsedown.config'); ], 'beam-parsedown.config');
// Publishing the views. // Publishing the views.

View file

@ -4,15 +4,13 @@ namespace ArdiSSoebrata\BeamParsedown\Facades;
use Illuminate\Support\Facades\Facade; use Illuminate\Support\Facades\Facade;
class BeamParsedown extends Facade class BeamParsedown extends Facade {
{
/** /**
* Get the registered name of the component. * Get the registered name of the component.
* *
* @return string * @return string
*/ */
protected static function getFacadeAccessor(): string protected static function getFacadeAccessor() : string {
{
return 'beam-parsedown'; return 'beam-parsedown';
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -13,23 +13,20 @@
# #
# #
class ParsedownExtra extends Parsedown class ParsedownExtra extends Parsedown {
{
# ~ # ~
const version = '0.8.0'; const version = '0.8.0';
# ~ # ~
function __construct() function __construct() {
{ if (version_compare(parent::version, '1.7.1') < 0) {
if (version_compare(parent::version, '1.7.1') < 0)
{
throw new Exception('ParsedownExtra requires a later version of Parsedown'); throw new Exception('ParsedownExtra requires a later version of Parsedown');
} }
$this->BlockTypes[':'] []= 'DefinitionList'; $this->BlockTypes[':'] [] = 'DefinitionList';
$this->BlockTypes['*'] []= 'Abbreviation'; $this->BlockTypes['*'] [] = 'Abbreviation';
# identify footnote definitions before reference definitions # identify footnote definitions before reference definitions
array_unshift($this->BlockTypes['['], 'Footnote'); array_unshift($this->BlockTypes['['], 'Footnote');
@ -41,8 +38,7 @@ class ParsedownExtra extends Parsedown
# #
# ~ # ~
function text($text) function text($text) {
{
$Elements = $this->textElements($text); $Elements = $this->textElements($text);
# convert to markup # convert to markup
@ -57,8 +53,7 @@ class ParsedownExtra extends Parsedown
# add footnotes # add footnotes
if (isset($this->DefinitionData['Footnote'])) if (isset($this->DefinitionData['Footnote'])) {
{
$Element = $this->buildFootnoteElement(); $Element = $this->buildFootnoteElement();
$markup .= "\n" . $this->element($Element); $markup .= "\n" . $this->element($Element);
@ -74,10 +69,8 @@ class ParsedownExtra extends Parsedown
# #
# Abbreviation # Abbreviation
protected function blockAbbreviation($Line) protected function blockAbbreviation($Line) {
{ if (preg_match('/^\*\[(.+?)\]:[ ]*(.+?)[ ]*$/', $Line['text'], $matches)) {
if (preg_match('/^\*\[(.+?)\]:[ ]*(.+?)[ ]*$/', $Line['text'], $matches))
{
$this->DefinitionData['Abbreviation'][$matches[1]] = $matches[2]; $this->DefinitionData['Abbreviation'][$matches[1]] = $matches[2];
$Block = array( $Block = array(
@ -91,10 +84,8 @@ class ParsedownExtra extends Parsedown
# #
# Footnote # Footnote
protected function blockFootnote($Line) protected function blockFootnote($Line) {
{ if (preg_match('/^\[\^(.+?)\]:[ ]?(.*)$/', $Line['text'], $matches)) {
if (preg_match('/^\[\^(.+?)\]:[ ]?(.*)$/', $Line['text'], $matches))
{
$Block = array( $Block = array(
'label' => $matches[1], 'label' => $matches[1],
'text' => $matches[2], 'text' => $matches[2],
@ -105,32 +96,25 @@ class ParsedownExtra extends Parsedown
} }
} }
protected function blockFootnoteContinue($Line, $Block) protected function blockFootnoteContinue($Line, $Block) {
{ if ($Line['text'][0] === '[' and preg_match('/^\[\^(.+?)\]:/', $Line['text'])) {
if ($Line['text'][0] === '[' and preg_match('/^\[\^(.+?)\]:/', $Line['text']))
{
return; return;
} }
if (isset($Block['interrupted'])) if (isset($Block['interrupted'])) {
{ if ($Line['indent'] >= 4) {
if ($Line['indent'] >= 4)
{
$Block['text'] .= "\n\n" . $Line['text']; $Block['text'] .= "\n\n" . $Line['text'];
return $Block; return $Block;
} }
} } else {
else
{
$Block['text'] .= "\n" . $Line['text']; $Block['text'] .= "\n" . $Line['text'];
return $Block; return $Block;
} }
} }
protected function blockFootnoteComplete($Block) protected function blockFootnoteComplete($Block) {
{
$this->DefinitionData['Footnote'][$Block['label']] = array( $this->DefinitionData['Footnote'][$Block['label']] = array(
'text' => $Block['text'], 'text' => $Block['text'],
'count' => null, 'count' => null,
@ -143,10 +127,8 @@ class ParsedownExtra extends Parsedown
# #
# Definition List # Definition List
protected function blockDefinitionList($Line, $Block) protected function blockDefinitionList($Line, $Block) {
{ if (!isset($Block) or $Block['type'] !== 'Paragraph') {
if ( ! isset($Block) or $Block['type'] !== 'Paragraph')
{
return; return;
} }
@ -157,9 +139,8 @@ class ParsedownExtra extends Parsedown
$terms = explode("\n", $Block['element']['handler']['argument']); $terms = explode("\n", $Block['element']['handler']['argument']);
foreach ($terms as $term) foreach ($terms as $term) {
{ $Element['elements'] [] = array(
$Element['elements'] []= array(
'name' => 'dt', 'name' => 'dt',
'handler' => array( 'handler' => array(
'function' => 'lineElements', 'function' => 'lineElements',
@ -176,23 +157,17 @@ class ParsedownExtra extends Parsedown
return $Block; return $Block;
} }
protected function blockDefinitionListContinue($Line, array $Block) protected function blockDefinitionListContinue($Line, array $Block) {
{ if ($Line['text'][0] === ':') {
if ($Line['text'][0] === ':')
{
$Block = $this->addDdElement($Line, $Block); $Block = $this->addDdElement($Line, $Block);
return $Block; return $Block;
} } else {
else if (isset($Block['interrupted']) and $Line['indent'] === 0) {
{
if (isset($Block['interrupted']) and $Line['indent'] === 0)
{
return; return;
} }
if (isset($Block['interrupted'])) if (isset($Block['interrupted'])) {
{
$Block['dd']['handler']['function'] = 'textElements'; $Block['dd']['handler']['function'] = 'textElements';
$Block['dd']['handler']['argument'] .= "\n\n"; $Block['dd']['handler']['argument'] .= "\n\n";
@ -212,12 +187,10 @@ class ParsedownExtra extends Parsedown
# #
# Header # Header
protected function blockHeader($Line) protected function blockHeader($Line) {
{
$Block = parent::blockHeader($Line); $Block = parent::blockHeader($Line);
if ($Block !== null && preg_match('/[ #]*{('.$this->regexAttribute.'+)}[ ]*$/', $Block['element']['handler']['argument'], $matches, PREG_OFFSET_CAPTURE)) if ($Block !== null && preg_match('/[ #]*{(' . $this->regexAttribute . '+)}[ ]*$/', $Block['element']['handler']['argument'], $matches, PREG_OFFSET_CAPTURE)) {
{
$attributeString = $matches[1][0]; $attributeString = $matches[1][0];
$Block['element']['attributes'] = $this->parseAttributeData($attributeString); $Block['element']['attributes'] = $this->parseAttributeData($attributeString);
@ -231,19 +204,15 @@ class ParsedownExtra extends Parsedown
# #
# Markup # Markup
protected function blockMarkup($Line) protected function blockMarkup($Line) {
{ if ($this->markupEscaped or $this->safeMode) {
if ($this->markupEscaped or $this->safeMode)
{
return; return;
} }
if (preg_match('/^<(\w[\w-]*)(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*(\/)?>/', $Line['text'], $matches)) if (preg_match('/^<(\w[\w-]*)(?:[ ]*' . $this->regexHtmlAttribute . ')*[ ]*(\/)?>/', $Line['text'], $matches)) {
{
$element = strtolower($matches[1]); $element = strtolower($matches[1]);
if (in_array($element, $this->textLevelElements)) if (in_array($element, $this->textLevelElements)) {
{
return; return;
} }
@ -259,22 +228,16 @@ class ParsedownExtra extends Parsedown
$length = strlen($matches[0]); $length = strlen($matches[0]);
$remainder = substr($Line['text'], $length); $remainder = substr($Line['text'], $length);
if (trim($remainder) === '') if (trim($remainder) === '') {
{ if (isset($matches[2]) or in_array($matches[1], $this->voidElements)) {
if (isset($matches[2]) or in_array($matches[1], $this->voidElements))
{
$Block['closed'] = true; $Block['closed'] = true;
$Block['void'] = true; $Block['void'] = true;
} }
} } else {
else if (isset($matches[2]) or in_array($matches[1], $this->voidElements)) {
{
if (isset($matches[2]) or in_array($matches[1], $this->voidElements))
{
return; return;
} }
if (preg_match('/<\/'.$matches[1].'>[ ]*$/i', $remainder)) if (preg_match('/<\/' . $matches[1] . '>[ ]*$/i', $remainder)) {
{
$Block['closed'] = true; $Block['closed'] = true;
} }
} }
@ -283,45 +246,37 @@ class ParsedownExtra extends Parsedown
} }
} }
protected function blockMarkupContinue($Line, array $Block) protected function blockMarkupContinue($Line, array $Block) {
{ if (isset($Block['closed'])) {
if (isset($Block['closed']))
{
return; return;
} }
if (preg_match('/^<'.$Block['name'].'(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*>/i', $Line['text'])) # open if (preg_match('/^<' . $Block['name'] . '(?:[ ]*' . $this->regexHtmlAttribute . ')*[ ]*>/i', $Line['text'])) # open
{ {
$Block['depth'] ++; $Block['depth']++;
} }
if (preg_match('/(.*?)<\/'.$Block['name'].'>[ ]*$/i', $Line['text'], $matches)) # close if (preg_match('/(.*?)<\/' . $Block['name'] . '>[ ]*$/i', $Line['text'], $matches)) # close
{ {
if ($Block['depth'] > 0) if ($Block['depth'] > 0) {
{ $Block['depth']--;
$Block['depth'] --; } else {
}
else
{
$Block['closed'] = true; $Block['closed'] = true;
} }
} }
if (isset($Block['interrupted'])) if (isset($Block['interrupted'])) {
{
$Block['element']['rawHtml'] .= "\n"; $Block['element']['rawHtml'] .= "\n";
unset($Block['interrupted']); unset($Block['interrupted']);
} }
$Block['element']['rawHtml'] .= "\n".$Line['body']; $Block['element']['rawHtml'] .= "\n" . $Line['body'];
return $Block; return $Block;
} }
protected function blockMarkupComplete($Block) protected function blockMarkupComplete($Block) {
{ if (!isset($Block['void'])) {
if ( ! isset($Block['void']))
{
$Block['element']['rawHtml'] = $this->processTag($Block['element']['rawHtml']); $Block['element']['rawHtml'] = $this->processTag($Block['element']['rawHtml']);
} }
@ -331,12 +286,10 @@ class ParsedownExtra extends Parsedown
# #
# Setext # Setext
protected function blockSetextHeader($Line, array $Block = null) protected function blockSetextHeader($Line, array $Block = null) {
{
$Block = parent::blockSetextHeader($Line, $Block); $Block = parent::blockSetextHeader($Line, $Block);
if ($Block !== null && preg_match('/[ ]*{('.$this->regexAttribute.'+)}[ ]*$/', $Block['element']['handler']['argument'], $matches, PREG_OFFSET_CAPTURE)) if ($Block !== null && preg_match('/[ ]*{(' . $this->regexAttribute . '+)}[ ]*$/', $Block['element']['handler']['argument'], $matches, PREG_OFFSET_CAPTURE)) {
{
$attributeString = $matches[1][0]; $attributeString = $matches[1][0];
$Block['element']['attributes'] = $this->parseAttributeData($attributeString); $Block['element']['attributes'] = $this->parseAttributeData($attributeString);
@ -354,30 +307,26 @@ class ParsedownExtra extends Parsedown
# #
# Footnote Marker # Footnote Marker
protected function inlineFootnoteMarker($Excerpt) protected function inlineFootnoteMarker($Excerpt) {
{ if (preg_match('/^\[\^(.+?)\]/', $Excerpt['text'], $matches)) {
if (preg_match('/^\[\^(.+?)\]/', $Excerpt['text'], $matches))
{
$name = $matches[1]; $name = $matches[1];
if ( ! isset($this->DefinitionData['Footnote'][$name])) if (!isset($this->DefinitionData['Footnote'][$name])) {
{
return; return;
} }
$this->DefinitionData['Footnote'][$name]['count'] ++; $this->DefinitionData['Footnote'][$name]['count']++;
if ( ! isset($this->DefinitionData['Footnote'][$name]['number'])) if (!isset($this->DefinitionData['Footnote'][$name]['number'])) {
{ $this->DefinitionData['Footnote'][$name]['number'] = ++$this->footnoteCount; # » &
$this->DefinitionData['Footnote'][$name]['number'] = ++ $this->footnoteCount; # » &
} }
$Element = array( $Element = array(
'name' => 'sup', 'name' => 'sup',
'attributes' => array('id' => 'fnref'.$this->DefinitionData['Footnote'][$name]['count'].':'.$name), 'attributes' => array('id' => 'fnref' . $this->DefinitionData['Footnote'][$name]['count'] . ':' . $name),
'element' => array( 'element' => array(
'name' => 'a', 'name' => 'a',
'attributes' => array('href' => '#fn:'.$name, 'class' => 'footnote-ref'), 'attributes' => array('href' => '#fn:' . $name, 'class' => 'footnote-ref'),
'text' => $this->DefinitionData['Footnote'][$name]['number'], 'text' => $this->DefinitionData['Footnote'][$name]['number'],
), ),
); );
@ -394,14 +343,12 @@ class ParsedownExtra extends Parsedown
# #
# Link # Link
protected function inlineLink($Excerpt) protected function inlineLink($Excerpt) {
{
$Link = parent::inlineLink($Excerpt); $Link = parent::inlineLink($Excerpt);
$remainder = $Link !== null ? substr($Excerpt['text'], $Link['extent']) : ''; $remainder = $Link !== null ? substr($Excerpt['text'], $Link['extent']) : '';
if (preg_match('/^[ ]*{('.$this->regexAttribute.'+)}/', $remainder, $matches)) if (preg_match('/^[ ]*{(' . $this->regexAttribute . '+)}/', $remainder, $matches)) {
{
$Link['element']['attributes'] += $this->parseAttributeData($matches[1]); $Link['element']['attributes'] += $this->parseAttributeData($matches[1]);
$Link['extent'] += strlen($matches[0]); $Link['extent'] += strlen($matches[0]);
@ -417,12 +364,10 @@ class ParsedownExtra extends Parsedown
private $currentAbreviation; private $currentAbreviation;
private $currentMeaning; private $currentMeaning;
protected function insertAbreviation(array $Element) protected function insertAbreviation(array $Element) {
{ if (isset($Element['text'])) {
if (isset($Element['text']))
{
$Element['elements'] = self::pregReplaceElements( $Element['elements'] = self::pregReplaceElements(
'/\b'.preg_quote($this->currentAbreviation, '/').'\b/', '/\b' . preg_quote($this->currentAbreviation, '/') . '\b/',
array( array(
array( array(
'name' => 'abbr', 'name' => 'abbr',
@ -441,14 +386,11 @@ class ParsedownExtra extends Parsedown
return $Element; return $Element;
} }
protected function inlineText($text) protected function inlineText($text) {
{
$Inline = parent::inlineText($text); $Inline = parent::inlineText($text);
if (isset($this->DefinitionData['Abbreviation'])) if (isset($this->DefinitionData['Abbreviation'])) {
{ foreach ($this->DefinitionData['Abbreviation'] as $abbreviation => $meaning) {
foreach ($this->DefinitionData['Abbreviation'] as $abbreviation => $meaning)
{
$this->currentAbreviation = $abbreviation; $this->currentAbreviation = $abbreviation;
$this->currentMeaning = $meaning; $this->currentMeaning = $meaning;
@ -466,8 +408,7 @@ class ParsedownExtra extends Parsedown
# Util Methods # Util Methods
# #
protected function addDdElement(array $Line, array $Block) protected function addDdElement(array $Line, array $Block) {
{
$text = substr($Line['text'], 1); $text = substr($Line['text'], 1);
$text = trim($text); $text = trim($text);
@ -482,20 +423,18 @@ class ParsedownExtra extends Parsedown
), ),
); );
if (isset($Block['interrupted'])) if (isset($Block['interrupted'])) {
{
$Block['dd']['handler']['function'] = 'textElements'; $Block['dd']['handler']['function'] = 'textElements';
unset($Block['interrupted']); unset($Block['interrupted']);
} }
$Block['element']['elements'] []= & $Block['dd']; $Block['element']['elements'] [] = &$Block['dd'];
return $Block; return $Block;
} }
protected function buildFootnoteElement() protected function buildFootnoteElement() {
{
$Element = array( $Element = array(
'name' => 'div', 'name' => 'div',
'attributes' => array('class' => 'footnotes'), 'attributes' => array('class' => 'footnotes'),
@ -510,10 +449,8 @@ class ParsedownExtra extends Parsedown
uasort($this->DefinitionData['Footnote'], 'self::sortFootnotes'); uasort($this->DefinitionData['Footnote'], 'self::sortFootnotes');
foreach ($this->DefinitionData['Footnote'] as $definitionId => $DefinitionData) foreach ($this->DefinitionData['Footnote'] as $definitionId => $DefinitionData) {
{ if (!isset($DefinitionData['number'])) {
if ( ! isset($DefinitionData['number']))
{
continue; continue;
} }
@ -525,8 +462,7 @@ class ParsedownExtra extends Parsedown
$backLinkElements = array(); $backLinkElements = array();
foreach ($numbers as $number) foreach ($numbers as $number) {
{
$backLinkElements[] = array('text' => ' '); $backLinkElements[] = array('text' => ' ');
$backLinkElements[] = array( $backLinkElements[] = array(
'name' => 'a', 'name' => 'a',
@ -543,10 +479,9 @@ class ParsedownExtra extends Parsedown
unset($backLinkElements[0]); unset($backLinkElements[0]);
$n = count($textElements) -1; $n = count($textElements) - 1;
if ($textElements[$n]['name'] === 'p') if ($textElements[$n]['name'] === 'p') {
{
$backLinkElements = array_merge( $backLinkElements = array_merge(
array( array(
array( array(
@ -566,18 +501,16 @@ class ParsedownExtra extends Parsedown
$backLinkElements $backLinkElements
), ),
); );
} } else {
else
{
$textElements[] = array( $textElements[] = array(
'name' => 'p', 'name' => 'p',
'elements' => $backLinkElements 'elements' => $backLinkElements
); );
} }
$Element['elements'][1]['elements'] []= array( $Element['elements'][1]['elements'] [] = array(
'name' => 'li', 'name' => 'li',
'attributes' => array('id' => 'fn:'.$definitionId), 'attributes' => array('id' => 'fn:' . $definitionId),
'elements' => array_merge( 'elements' => array_merge(
$textElements $textElements
), ),
@ -589,26 +522,21 @@ class ParsedownExtra extends Parsedown
# ~ # ~
protected function parseAttributeData($attributeString) protected function parseAttributeData($attributeString) {
{
$Data = array(); $Data = array();
$attributes = preg_split('/[ ]+/', $attributeString, - 1, PREG_SPLIT_NO_EMPTY); $attributes = preg_split('/[ ]+/', $attributeString, -1, PREG_SPLIT_NO_EMPTY);
foreach ($attributes as $attribute) foreach ($attributes as $attribute) {
{ if ($attribute[0] === '#') {
if ($attribute[0] === '#')
{
$Data['id'] = substr($attribute, 1); $Data['id'] = substr($attribute, 1);
} } else # "."
else # "."
{ {
$classes []= substr($attribute, 1); $classes [] = substr($attribute, 1);
} }
} }
if (isset($classes)) if (isset($classes)) {
{
$Data['class'] = implode(' ', $classes); $Data['class'] = implode(' ', $classes);
} }
@ -634,29 +562,21 @@ class ParsedownExtra extends Parsedown
$elementText = ''; $elementText = '';
if ($DOMDocument->documentElement->getAttribute('markdown') === '1') if ($DOMDocument->documentElement->getAttribute('markdown') === '1') {
{ foreach ($DOMDocument->documentElement->childNodes as $Node) {
foreach ($DOMDocument->documentElement->childNodes as $Node)
{
$elementText .= $DOMDocument->saveHTML($Node); $elementText .= $DOMDocument->saveHTML($Node);
} }
$DOMDocument->documentElement->removeAttribute('markdown'); $DOMDocument->documentElement->removeAttribute('markdown');
$elementText = "\n".$this->text($elementText)."\n"; $elementText = "\n" . $this->text($elementText) . "\n";
} } else {
else foreach ($DOMDocument->documentElement->childNodes as $Node) {
{
foreach ($DOMDocument->documentElement->childNodes as $Node)
{
$nodeMarkup = $DOMDocument->saveHTML($Node); $nodeMarkup = $DOMDocument->saveHTML($Node);
if ($Node instanceof DOMElement and ! in_array($Node->nodeName, $this->textLevelElements)) if ($Node instanceof DOMElement and !in_array($Node->nodeName, $this->textLevelElements)) {
{
$elementText .= $this->processTag($nodeMarkup); $elementText .= $this->processTag($nodeMarkup);
} } else {
else
{
$elementText .= $nodeMarkup; $elementText .= $nodeMarkup;
} }
} }

View file

@ -2,13 +2,11 @@
namespace Aidantwoods\SecureParsedown; namespace Aidantwoods\SecureParsedown;
class SecureParsedown extends \Parsedown class SecureParsedown extends \Parsedown {
{
const version = '1.0.1'; const version = '1.0.1';
function setSafeMode($safeMode) function setSafeMode($safeMode) {
{ $this->safeMode = (bool)$safeMode;
$this->safeMode = (bool) $safeMode;
return $this; return $this;
} }
@ -32,39 +30,7 @@ class SecureParsedown extends \Parsedown
'steam:', 'steam:',
); );
protected function blockCodeComplete($Block) protected function blockCodeComplete($Block) {
{
$text = $Block['element']['text']['text'];
$Block['element']['text']['text'] = $text;
return $Block;
}
protected function blockComment($Line)
{
if ($this->markupEscaped or $this->safeMode)
{
return;
}
if (isset($Line['text'][3]) and $Line['text'][3] === '-' and $Line['text'][2] === '-' and $Line['text'][1] === '!')
{
$Block = array(
'markup' => $Line['body'],
);
if (preg_match('/-->$/', $Line['text']))
{
$Block['closed'] = true;
}
return $Block;
}
}
protected function blockFencedCodeComplete($Block)
{
$text = $Block['element']['text']['text']; $text = $Block['element']['text']['text'];
$Block['element']['text']['text'] = $text; $Block['element']['text']['text'] = $text;
@ -72,19 +38,41 @@ class SecureParsedown extends \Parsedown
return $Block; return $Block;
} }
protected function blockMarkup($Line) protected function blockComment($Line) {
{ if ($this->markupEscaped or $this->safeMode) {
if ($this->markupEscaped or $this->safeMode)
{
return; return;
} }
if (preg_match('/^<(\w*)(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*(\/)?>/', $Line['text'], $matches)) if (isset($Line['text'][3]) and $Line['text'][3] === '-' and $Line['text'][2] === '-' and $Line['text'][1] === '!') {
{ $Block = array(
'markup' => $Line['body'],
);
if (preg_match('/-->$/', $Line['text'])) {
$Block['closed'] = true;
}
return $Block;
}
}
protected function blockFencedCodeComplete($Block) {
$text = $Block['element']['text']['text'];
$Block['element']['text']['text'] = $text;
return $Block;
}
protected function blockMarkup($Line) {
if ($this->markupEscaped or $this->safeMode) {
return;
}
if (preg_match('/^<(\w*)(?:[ ]*' . $this->regexHtmlAttribute . ')*[ ]*(\/)?>/', $Line['text'], $matches)) {
$element = strtolower($matches[1]); $element = strtolower($matches[1]);
if (in_array($element, $this->textLevelElements)) if (in_array($element, $this->textLevelElements)) {
{
return; return;
} }
@ -98,24 +86,18 @@ class SecureParsedown extends \Parsedown
$remainder = substr($Line['text'], $length); $remainder = substr($Line['text'], $length);
if (trim($remainder) === '') if (trim($remainder) === '') {
{ if (isset($matches[2]) or in_array($matches[1], $this->voidElements)) {
if (isset($matches[2]) or in_array($matches[1], $this->voidElements))
{
$Block['closed'] = true; $Block['closed'] = true;
$Block['void'] = true; $Block['void'] = true;
} }
} } else {
else if (isset($matches[2]) or in_array($matches[1], $this->voidElements)) {
{
if (isset($matches[2]) or in_array($matches[1], $this->voidElements))
{
return; return;
} }
if (preg_match('/<\/'.$matches[1].'>[ ]*$/i', $remainder)) if (preg_match('/<\/' . $matches[1] . '>[ ]*$/i', $remainder)) {
{
$Block['closed'] = true; $Block['closed'] = true;
} }
} }
@ -124,12 +106,10 @@ class SecureParsedown extends \Parsedown
} }
} }
protected function inlineCode($Excerpt) protected function inlineCode($Excerpt) {
{
$marker = $Excerpt['text'][0]; $marker = $Excerpt['text'][0];
if (preg_match('/^('.$marker.'+)[ ]*(.+?)[ ]*(?<!'.$marker.')\1(?!'.$marker.')/s', $Excerpt['text'], $matches)) if (preg_match('/^(' . $marker . '+)[ ]*(.+?)[ ]*(?<!' . $marker . ')\1(?!' . $marker . ')/s', $Excerpt['text'], $matches)) {
{
$text = $matches[2]; $text = $matches[2];
$text = preg_replace("/[ ]*\n/", ' ', $text); $text = preg_replace("/[ ]*\n/", ' ', $text);
@ -143,8 +123,7 @@ class SecureParsedown extends \Parsedown
} }
} }
protected function inlineLink($Excerpt) protected function inlineLink($Excerpt) {
{
$Element = array( $Element = array(
'name' => 'a', 'name' => 'a',
'handler' => 'line', 'handler' => 'line',
@ -159,46 +138,35 @@ class SecureParsedown extends \Parsedown
$remainder = $Excerpt['text']; $remainder = $Excerpt['text'];
if (preg_match('/\[((?:[^][]++|(?R))*+)\]/', $remainder, $matches)) if (preg_match('/\[((?:[^][]++|(?R))*+)\]/', $remainder, $matches)) {
{
$Element['text'] = $matches[1]; $Element['text'] = $matches[1];
$extent += strlen($matches[0]); $extent += strlen($matches[0]);
$remainder = substr($remainder, $extent); $remainder = substr($remainder, $extent);
} } else {
else
{
return; return;
} }
if (preg_match('/^[(]\s*+((?:[^ ()]++|[(][^ )]+[)])++)(?:[ ]+("[^"]*"|\'[^\']*\'))?\s*[)]/', $remainder, $matches)) if (preg_match('/^[(]\s*+((?:[^ ()]++|[(][^ )]+[)])++)(?:[ ]+("[^"]*"|\'[^\']*\'))?\s*[)]/', $remainder, $matches)) {
{
$Element['attributes']['href'] = $matches[1]; $Element['attributes']['href'] = $matches[1];
if (isset($matches[2])) if (isset($matches[2])) {
{ $Element['attributes']['title'] = substr($matches[2], 1, -1);
$Element['attributes']['title'] = substr($matches[2], 1, - 1);
} }
$extent += strlen($matches[0]); $extent += strlen($matches[0]);
} } else {
else if (preg_match('/^\s*\[(.*?)\]/', $remainder, $matches)) {
{
if (preg_match('/^\s*\[(.*?)\]/', $remainder, $matches))
{
$definition = strlen($matches[1]) ? $matches[1] : $Element['text']; $definition = strlen($matches[1]) ? $matches[1] : $Element['text'];
$definition = strtolower($definition); $definition = strtolower($definition);
$extent += strlen($matches[0]); $extent += strlen($matches[0]);
} } else {
else
{
$definition = strtolower($Element['text']); $definition = strtolower($Element['text']);
} }
if ( ! isset($this->DefinitionData['Reference'][$definition])) if (!isset($this->DefinitionData['Reference'][$definition])) {
{
return; return;
} }
@ -214,31 +182,26 @@ class SecureParsedown extends \Parsedown
); );
} }
protected function inlineMarkup($Excerpt) protected function inlineMarkup($Excerpt) {
{ if ($this->markupEscaped or $this->safeMode or strpos($Excerpt['text'], '>') === false) {
if ($this->markupEscaped or $this->safeMode or strpos($Excerpt['text'], '>') === false)
{
return; return;
} }
if ($Excerpt['text'][1] === '/' and preg_match('/^<\/\w*[ ]*>/s', $Excerpt['text'], $matches)) if ($Excerpt['text'][1] === '/' and preg_match('/^<\/\w*[ ]*>/s', $Excerpt['text'], $matches)) {
{
return array( return array(
'markup' => $matches[0], 'markup' => $matches[0],
'extent' => strlen($matches[0]), 'extent' => strlen($matches[0]),
); );
} }
if ($Excerpt['text'][1] === '!' and preg_match('/^<!---?[^>-](?:-?[^-])*-->/s', $Excerpt['text'], $matches)) if ($Excerpt['text'][1] === '!' and preg_match('/^<!---?[^>-](?:-?[^-])*-->/s', $Excerpt['text'], $matches)) {
{
return array( return array(
'markup' => $matches[0], 'markup' => $matches[0],
'extent' => strlen($matches[0]), 'extent' => strlen($matches[0]),
); );
} }
if ($Excerpt['text'][1] !== ' ' and preg_match('/^<\w*(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*\/?>/s', $Excerpt['text'], $matches)) if ($Excerpt['text'][1] !== ' ' and preg_match('/^<\w*(?:[ ]*' . $this->regexHtmlAttribute . ')*[ ]*\/?>/s', $Excerpt['text'], $matches)) {
{
return array( return array(
'markup' => $matches[0], 'markup' => $matches[0],
'extent' => strlen($matches[0]), 'extent' => strlen($matches[0]),
@ -246,15 +209,12 @@ class SecureParsedown extends \Parsedown
} }
} }
protected function inlineUrl($Excerpt) protected function inlineUrl($Excerpt) {
{ if ($this->urlsLinked !== true or !isset($Excerpt['text'][2]) or $Excerpt['text'][2] !== '/') {
if ($this->urlsLinked !== true or ! isset($Excerpt['text'][2]) or $Excerpt['text'][2] !== '/')
{
return; return;
} }
if (preg_match('/\bhttps?:[\/]{2}[^\s<]+\b\/*/ui', $Excerpt['context'], $matches, PREG_OFFSET_CAPTURE)) if (preg_match('/\bhttps?:[\/]{2}[^\s<]+\b\/*/ui', $Excerpt['context'], $matches, PREG_OFFSET_CAPTURE)) {
{
$url = $matches[0][0]; $url = $matches[0][0];
$Inline = array( $Inline = array(
@ -273,10 +233,8 @@ class SecureParsedown extends \Parsedown
} }
} }
protected function inlineUrlTag($Excerpt) protected function inlineUrlTag($Excerpt) {
{ if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<(\w+:\/{2}[^ >]+)>/i', $Excerpt['text'], $matches)) {
if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<(\w+:\/{2}[^ >]+)>/i', $Excerpt['text'], $matches))
{
$url = $matches[1]; $url = $matches[1];
return array( return array(
@ -292,76 +250,58 @@ class SecureParsedown extends \Parsedown
} }
} }
protected function element(array $Element) protected function element(array $Element) {
{ if ($this->safeMode) {
if ($this->safeMode)
{
$Element = $this->sanitiseElement($Element); $Element = $this->sanitiseElement($Element);
} }
$markup = '<'.$Element['name']; $markup = '<' . $Element['name'];
if (isset($Element['attributes'])) if (isset($Element['attributes'])) {
{ foreach ($Element['attributes'] as $name => $value) {
foreach ($Element['attributes'] as $name => $value) if ($value === null) {
{
if ($value === null)
{
continue; continue;
} }
$markup .= ' '.$name.'="'.self::escape($value).'"'; $markup .= ' ' . $name . '="' . self::escape($value) . '"';
} }
} }
if (isset($Element['text'])) if (isset($Element['text'])) {
{
$markup .= '>'; $markup .= '>';
if (isset($Element['handler'])) if (isset($Element['handler'])) {
{
$markup .= $this->{$Element['handler']}($Element['text']); $markup .= $this->{$Element['handler']}($Element['text']);
} } else {
else
{
$markup .= self::escape($Element['text'], true); $markup .= self::escape($Element['text'], true);
} }
$markup .= '</'.$Element['name'].'>'; $markup .= '</' . $Element['name'] . '>';
} } else {
else
{
$markup .= ' />'; $markup .= ' />';
} }
return $markup; return $markup;
} }
protected function sanitiseElement(array $Element) protected function sanitiseElement(array $Element) {
{
static $goodAttribute = '/^[a-zA-Z0-9][a-zA-Z0-9-_]*+$/'; static $goodAttribute = '/^[a-zA-Z0-9][a-zA-Z0-9-_]*+$/';
static $safeUrlNameToAtt = array( static $safeUrlNameToAtt = array(
'a' => 'href', 'a' => 'href',
'img' => 'src', 'img' => 'src',
); );
if (isset($safeUrlNameToAtt[$Element['name']])) if (isset($safeUrlNameToAtt[$Element['name']])) {
{
$Element = $this->filterUnsafeUrlInAttribute($Element, $safeUrlNameToAtt[$Element['name']]); $Element = $this->filterUnsafeUrlInAttribute($Element, $safeUrlNameToAtt[$Element['name']]);
} }
if ( ! empty($Element['attributes'])) if (!empty($Element['attributes'])) {
{ foreach ($Element['attributes'] as $att => $val) {
foreach ($Element['attributes'] as $att => $val)
{
# filter out badly parsed attribute # filter out badly parsed attribute
if ( ! preg_match($goodAttribute, $att)) if (!preg_match($goodAttribute, $att)) {
{
unset($Element['attributes'][$att]); unset($Element['attributes'][$att]);
} } # dump onevent attribute
# dump onevent attribute elseif (self::striAtStart($att, 'on')) {
elseif (self::striAtStart($att, 'on'))
{
unset($Element['attributes'][$att]); unset($Element['attributes'][$att]);
} }
} }
@ -370,12 +310,9 @@ class SecureParsedown extends \Parsedown
return $Element; return $Element;
} }
protected function filterUnsafeUrlInAttribute(array $Element, $attribute) protected function filterUnsafeUrlInAttribute(array $Element, $attribute) {
{ foreach ($this->safeLinksWhitelist as $scheme) {
foreach ($this->safeLinksWhitelist as $scheme) if (self::striAtStart($Element['attributes'][$attribute], $scheme)) {
{
if (self::striAtStart($Element['attributes'][$attribute], $scheme))
{
return $Element; return $Element;
} }
} }
@ -385,21 +322,16 @@ class SecureParsedown extends \Parsedown
return $Element; return $Element;
} }
protected static function escape($text, $allowQuotes = false) protected static function escape($text, $allowQuotes = false) {
{
return htmlspecialchars($text, $allowQuotes ? ENT_NOQUOTES : ENT_QUOTES, 'UTF-8'); return htmlspecialchars($text, $allowQuotes ? ENT_NOQUOTES : ENT_QUOTES, 'UTF-8');
} }
protected static function striAtStart($string, $needle) protected static function striAtStart($string, $needle) {
{
$len = strlen($needle); $len = strlen($needle);
if ($len > strlen($string)) if ($len > strlen($string)) {
{
return false; return false;
} } else {
else
{
return strtolower(substr($string, 0, $len)) === strtolower($needle); return strtolower(substr($string, 0, $len)) === strtolower($needle);
} }
} }

View file

@ -1,10 +1,9 @@
<?php <?php
function captcha($color, $mode, $mul, $allowed) function captcha($color, $mode, $mul, $allowed) {
{
$bg_path = dirname(__FILE__) . '/captchabg/';
$bg_path = dirname(__FILE__) . '/captchabg/';
$font_path = dirname(__FILE__) . '/fonts/'; $font_path = dirname(__FILE__) . '/fonts/';
if ($mode == "Easy") { if ($mode == "Easy") {
$fonr_name = 'SigmarOne.ttf'; $fonr_name = 'SigmarOne.ttf';
} elseif ($mode == "Normal") { } elseif ($mode == "Normal") {
@ -14,7 +13,7 @@ function captcha($color, $mode, $mul, $allowed)
} else { } else {
$fonr_name = 'times_new_yorker.ttf'; $fonr_name = 'times_new_yorker.ttf';
} }
if ($mul == "on") { if ($mul == "on") {
$captcha_config = array( $captcha_config = array(
'code' => '', 'code' => '',
@ -62,13 +61,13 @@ function captcha($color, $mode, $mul, $allowed)
'shadow_offset_y' => 1 'shadow_offset_y' => 1
); );
} }
// Overwrite defaults with custom config values // Overwrite defaults with custom config values
if (is_array($config)) { if (is_array($config)) {
foreach ($config as $key => $value) foreach ($config as $key => $value)
$captcha_config[$key] = $value; $captcha_config[$key] = $value;
} }
// Restrict certain values // Restrict certain values
if ($captcha_config['min_length'] < 1) if ($captcha_config['min_length'] < 1)
$captcha_config['min_length'] = 1; $captcha_config['min_length'] = 1;
@ -82,39 +81,38 @@ function captcha($color, $mode, $mul, $allowed)
$captcha_config['min_font_size'] = 10; $captcha_config['min_font_size'] = 10;
if ($captcha_config['max_font_size'] < $captcha_config['min_font_size']) if ($captcha_config['max_font_size'] < $captcha_config['min_font_size'])
$captcha_config['max_font_size'] = $captcha_config['min_font_size']; $captcha_config['max_font_size'] = $captcha_config['min_font_size'];
// Use milliseconds instead of seconds // Use milliseconds instead of seconds
srand(microtime() * 100); srand(microtime() * 100);
// Generate CAPTCHA code if not set by user // Generate CAPTCHA code if not set by user
if (empty($captcha_config['code'])) { if (empty($captcha_config['code'])) {
$captcha_config['code'] = ''; $captcha_config['code'] = '';
$length = rand($captcha_config['min_length'], $captcha_config['max_length']); $length = rand($captcha_config['min_length'], $captcha_config['max_length']);
while (strlen($captcha_config['code']) < $length) { while (strlen($captcha_config['code']) < $length) {
$captcha_config['code'] .= substr($captcha_config['characters'], rand() % (strlen($captcha_config['characters'])), 1); $captcha_config['code'] .= substr($captcha_config['characters'], rand() % (strlen($captcha_config['characters'])), 1);
} }
} }
// Generate HTML for image src // Generate HTML for image src
$image_src = substr(__FILE__, strlen(realpath($_SERVER['DOCUMENT_ROOT']))) . '?_CAPTCHA&amp;t=' . urlencode(microtime()); $image_src = substr(__FILE__, strlen(realpath($_SERVER['DOCUMENT_ROOT']))) . '?_CAPTCHA&amp;t=' . urlencode(microtime());
$image_src = '/' . ltrim(preg_replace('/\\\\/', '/', $image_src), '/'); $image_src = '/' . ltrim(preg_replace('/\\\\/', '/', $image_src), '/');
$_SESSION['_CAPTCHA']['config'] = serialize($captcha_config); $_SESSION['_CAPTCHA']['config'] = serialize($captcha_config);
return array( return array(
'code' => $captcha_config['code'], 'code' => $captcha_config['code'],
'image_src' => $image_src 'image_src' => $image_src
); );
} }
if (!function_exists('hex2rgb')) { if (!function_exists('hex2rgb')) {
function hex2rgb($hex_str, $return_string = false, $separator = ',') function hex2rgb($hex_str, $return_string = false, $separator = ',') {
{ $hex_str = preg_replace("/[^0-9A-Fa-f]/", '', $hex_str); // Gets a proper hex string
$hex_str = preg_replace("/[^0-9A-Fa-f]/", '', $hex_str); // Gets a proper hex string
$rgb_array = array(); $rgb_array = array();
if (strlen($hex_str) == 6) { if (strlen($hex_str) == 6) {
$color_val = hexdec($hex_str); $color_val = hexdec($hex_str);
$rgb_array['r'] = 0xFF & ($color_val >> 0x10); $rgb_array['r'] = 0xFF & ($color_val >> 0x10);
$rgb_array['g'] = 0xFF & ($color_val >> 0x8); $rgb_array['g'] = 0xFF & ($color_val >> 0x8);
$rgb_array['b'] = 0xFF & $color_val; $rgb_array['b'] = 0xFF & $color_val;
@ -131,61 +129,61 @@ if (!function_exists('hex2rgb')) {
// Draw the image // Draw the image
if (isset($_GET['_CAPTCHA'])) { if (isset($_GET['_CAPTCHA'])) {
session_start(); session_start();
$captcha_config = unserialize($_SESSION['_CAPTCHA']['config']); $captcha_config = unserialize($_SESSION['_CAPTCHA']['config']);
if (!$captcha_config) if (!$captcha_config)
exit(); exit();
// Use milliseconds instead of seconds // Use milliseconds instead of seconds
srand(microtime() * 100); srand(microtime() * 100);
// Pick random background, get info, and start captcha // Pick random background, get info, and start captcha
$background = $captcha_config['backgrounds'][rand(0, count($captcha_config['backgrounds']) - 1)]; $background = $captcha_config['backgrounds'][rand(0, count($captcha_config['backgrounds']) - 1)];
list($bg_width, $bg_height, $bg_type, $bg_attr) = getimagesize($background); list($bg_width, $bg_height, $bg_type, $bg_attr) = getimagesize($background);
$captcha = imagecreatefrompng($background); $captcha = imagecreatefrompng($background);
$color = hex2rgb($captcha_config['color']); $color = hex2rgb($captcha_config['color']);
$color = imagecolorallocate($captcha, $color['r'], $color['g'], $color['b']); $color = imagecolorallocate($captcha, $color['r'], $color['g'], $color['b']);
// Determine text angle // Determine text angle
$angle = rand($captcha_config['angle_min'], $captcha_config['angle_max']) * (rand(0, 1) == 1 ? -1 : 1); $angle = rand($captcha_config['angle_min'], $captcha_config['angle_max']) * (rand(0, 1) == 1 ? -1 : 1);
// Select font randomly // Select font randomly
$font = $captcha_config['fonts'][rand(0, count($captcha_config['fonts']) - 1)]; $font = $captcha_config['fonts'][rand(0, count($captcha_config['fonts']) - 1)];
// Verify font file exists // Verify font file exists
if (!file_exists($font)) if (!file_exists($font))
throw new Exception('Font file not found: ' . $font); throw new Exception('Font file not found: ' . $font);
// Set the font size // Set the font size
$font_size = rand($captcha_config['min_font_size'], $captcha_config['max_font_size']); $font_size = rand($captcha_config['min_font_size'], $captcha_config['max_font_size']);
$text_box_size = imagettfbbox($font_size, $angle, $font, $captcha_config['code']); $text_box_size = imagettfbbox($font_size, $angle, $font, $captcha_config['code']);
// Determine text position // Determine text position
$box_width = abs($text_box_size[6] - $text_box_size[2]); $box_width = abs($text_box_size[6] - $text_box_size[2]);
$box_height = abs($text_box_size[5] - $text_box_size[1]); $box_height = abs($text_box_size[5] - $text_box_size[1]);
$text_pos_x_min = 0; $text_pos_x_min = 0;
$text_pos_x_max = ($bg_width) - ($box_width); $text_pos_x_max = ($bg_width) - ($box_width);
$text_pos_x = rand($text_pos_x_min, $text_pos_x_max); $text_pos_x = rand($text_pos_x_min, $text_pos_x_max);
$text_pos_y_min = $box_height; $text_pos_y_min = $box_height;
$text_pos_y_max = ($bg_height) - ($box_height / 2); $text_pos_y_max = ($bg_height) - ($box_height / 2);
$text_pos_y = rand($text_pos_y_min, $text_pos_y_max); $text_pos_y = rand($text_pos_y_min, $text_pos_y_max);
// Draw shadow // Draw shadow
if ($captcha_config['shadow']) { if ($captcha_config['shadow']) {
$shadow_color = hex2rgb($captcha_config['shadow_color']); $shadow_color = hex2rgb($captcha_config['shadow_color']);
$shadow_color = imagecolorallocate($captcha, $shadow_color['r'], $shadow_color['g'], $shadow_color['b']); $shadow_color = imagecolorallocate($captcha, $shadow_color['r'], $shadow_color['g'], $shadow_color['b']);
imagettftext($captcha, $font_size, $angle, $text_pos_x + $captcha_config['shadow_offset_x'], $text_pos_y + $captcha_config['shadow_offset_y'], $shadow_color, $font, $captcha_config['code']); imagettftext($captcha, $font_size, $angle, $text_pos_x + $captcha_config['shadow_offset_x'], $text_pos_y + $captcha_config['shadow_offset_y'], $shadow_color, $font, $captcha_config['code']);
} }
// Draw text // Draw text
imagettftext($captcha, $font_size, $angle, $text_pos_x, $text_pos_y, $color, $font, $captcha_config['code']); imagettftext($captcha, $font_size, $angle, $text_pos_x, $text_pos_y, $color, $font, $captcha_config['code']);
// Output image // Output image
header("Content-type: image/png"); header("Content-type: image/png");
imagepng($captcha); imagepng($captcha);
} }

View file

@ -19,23 +19,25 @@ function getSitePermissions(PDO $conn) : array {
return $conn->query('SELECT * FROM site_permissions LIMIT 1')->fetch(); return $conn->query('SELECT * FROM site_permissions LIMIT 1')->fetch();
} }
function getSiteAds(PDO $conn) : array | bool { function getSiteAds(PDO $conn) : array|bool {
return $conn->query('SELECT text_ads, ads_1, ads_2 FROM ads LIMIT 1')->fetch(); return $conn->query('SELECT text_ads, ads_1, ads_2 FROM ads LIMIT 1')->fetch();
} }
function getSiteTotalPastes(PDO $conn) : int { function getSiteTotalPastes(PDO $conn) : int {
return intval($conn->query('SELECT COUNT(*) FROM pastes')->fetch(PDO::FETCH_NUM)[0]); return intval($conn->query('SELECT COUNT(*) FROM pastes')->fetch(PDO::FETCH_NUM)[0]);
} }
function getSiteTotalviews(PDO $conn) : int { function getSiteTotalviews(PDO $conn) : int {
return intval($conn->query('SELECT tpage FROM page_view ORDER BY id DESC LIMIT 1')->fetch(PDO::FETCH_NUM)[0]); return intval($conn->query('SELECT tpage FROM page_view ORDER BY id DESC LIMIT 1')->fetch(PDO::FETCH_NUM)[0]);
} }
function getSiteTotal_unique_views(PDO $conn) : int { function getSiteTotal_unique_views(PDO $conn) : int {
return intval($conn->query('SELECT tvisit FROM page_view ORDER BY id DESC LIMIT 1')->fetch(PDO::FETCH_NUM)[0]); return intval($conn->query('SELECT tvisit FROM page_view ORDER BY id DESC LIMIT 1')->fetch(PDO::FETCH_NUM)[0]);
} }
function updatePageViews(PDO $conn) : void { function updatePageViews(PDO $conn) : void {
$ip = $_SERVER['REMOTE_ADDR']; $ip = $_SERVER['REMOTE_ADDR'];
$date = date('jS F Y'); $date = date('jS F Y');
$data_ip = file_get_contents('tmp/temp.tdata'); $data_ip = file_get_contents('tmp/temp.tdata');
$last_page_view = $conn->query('SELECT * FROM page_view ORDER BY id DESC LIMIT 1')->fetch(); $last_page_view = $conn->query('SELECT * FROM page_view ORDER BY id DESC LIMIT 1')->fetch();
@ -49,7 +51,7 @@ function updatePageViews(PDO $conn) : void {
$statement = $conn->prepare("UPDATE page_view SET tpage = ? WHERE id = ?"); $statement = $conn->prepare("UPDATE page_view SET tpage = ? WHERE id = ?");
$statement->execute([$last_tpage, $last_page_view['id']]); $statement->execute([$last_tpage, $last_page_view['id']]);
} else { } else {
$last_tpage = intval($last_page_view['tpage']) + 1; $last_tpage = intval($last_page_view['tpage']) + 1;
$last_tvisit = intval($last_page_view['tvisit']) + 1; $last_tvisit = intval($last_page_view['tvisit']) + 1;
// Update both tpage and tvisit. // Update both tpage and tvisit.
@ -81,17 +83,17 @@ $conn = new PDO(
// Setup site info // Setup site info
$row = getSiteInfo($conn); $row = getSiteInfo($conn);
$title = Trim($row['title']); $title = Trim($row['title']);
$des = Trim($row['des']); $des = Trim($row['des']);
$baseurl = Trim($row['baseurl']); $baseurl = Trim($row['baseurl']);
$keyword = Trim($row['keyword']); $keyword = Trim($row['keyword']);
$site_name = Trim($row['site_name']); $site_name = Trim($row['site_name']);
$email = Trim($row['email']); $email = Trim($row['email']);
$twit = Trim($row['twit']); $twit = Trim($row['twit']);
$face = Trim($row['face']); $face = Trim($row['face']);
$gplus = Trim($row['gplus']); $gplus = Trim($row['gplus']);
$ga = Trim($row['ga']); $ga = Trim($row['ga']);
$additional_scripts = Trim($row['additional_scripts']); $additional_scripts = Trim($row['additional_scripts']);
// Setup theme and language // Setup theme and language
@ -131,8 +133,8 @@ if (in_array($default_lang, scandir('langs/'))) {
} }
// Check if IP is banned // Check if IP is banned
$ip = $_SERVER['REMOTE_ADDR']; $ip = $_SERVER['REMOTE_ADDR'];
if ( is_banned($conn, $ip) ) die($lang['banned']); // "You have been banned from ".$site_name; if (is_banned($conn, $ip)) die($lang['banned']); // "You have been banned from ".$site_name;
// Logout // Logout
if (isset($_GET['logout'])) { if (isset($_GET['logout'])) {
@ -147,4 +149,4 @@ if (isset($_GET['logout'])) {
$site_ads = getSiteAds($conn); $site_ads = getSiteAds($conn);
$total_pastes = getSiteTotalPastes($conn); $total_pastes = getSiteTotalPastes($conn);
$total_page_views = getSiteTotalviews($conn); $total_page_views = getSiteTotalviews($conn);
$total_unique_views= getSiteTotal_unique_views($conn); $total_unique_views = getSiteTotal_unique_views($conn);

View file

@ -12,33 +12,27 @@
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License in GPL.txt for more details. * GNU General Public License in GPL.txt for more details.
*/ */
function timer()
{ function timer() {
static $start; static $start;
if (is_null($start)) if (is_null($start)) {
{
$start = microtime(true); $start = microtime(true);
} } else {
else
{
$diff = round((microtime(true) - $start), 4); $diff = round((microtime(true) - $start), 4);
$start = null; $start = null;
return $diff; return $diff;
} }
} }
function getUserFavs($conn, $username) function getUserFavs($conn, $username) {
{
$query = $conn->prepare("SELECT pins.f_time, pins.m_fav, pins.f_paste, pastes.id, pastes.title, pastes.now_time, pastes.tagsys FROM pins, pastes WHERE pins.f_paste = pastes.id AND pins.m_fav=?'"); $query = $conn->prepare("SELECT pins.f_time, pins.m_fav, pins.f_paste, pastes.id, pastes.title, pastes.now_time, pastes.tagsys FROM pins, pastes WHERE pins.f_paste = pastes.id AND pins.m_fav=?'");
$query->execute([$username]); $query->execute([$username]);
return $query->fetchAll(); return $query->fetchAll();
} }
function CountPasteFavs($conn, $fav_id) function CountPasteFavs($conn, $fav_id) {
{
$query = $conn->prepare("SELECT COUNT(f_paste) FROM pins WHERE f_paste=?"); $query = $conn->prepare("SELECT COUNT(f_paste) FROM pins WHERE f_paste=?");
$query->execute([$fav_id]); $query->execute([$fav_id]);
return $query->fetchAll(); return $query->fetchAll();
@ -46,95 +40,101 @@ function CountPasteFavs($conn, $fav_id)
function checkFavorite($paste_id, $user_id, $conn) { function checkFavorite($paste_id, $user_id, $conn) {
$result = $conn->query("SELECT * FROM pins WHERE m_fav = '". $user_id."' AND f_paste = '". $paste_id."'"); $result = $conn->query("SELECT * FROM pins WHERE m_fav = '" . $user_id . "' AND f_paste = '" . $paste_id . "'");
$numrows = $result->num_rows; $numrows = $result->num_rows;
if ($numrows == 0) { if ($numrows == 0) {
echo "<a href='#' id='favorite' class='iconn tool-iconn' data-fid='". $paste_id."'><i class='far fa-star fa-lg has-text-grey' title='Favourite'></i></a>"; echo "<a href='#' id='favorite' class='iconn tool-iconn' data-fid='" . $paste_id . "'><i class='far fa-star fa-lg has-text-grey' title='Favourite'></i></a>";
} } else {
else { echo "<a href='#' id='favorite' class='iconn tool-iconn' data-fid='" . $paste_id . "'><i class='fas fa-star fa-lg has-text-grey' title='Favourite'></i></a>";
echo "<a href='#' id='favorite' class='iconn tool-iconn' data-fid='". $paste_id."'><i class='fas fa-star fa-lg has-text-grey' title='Favourite'></i></a>"; }
} }
}
function getreports($conn, $count = 10) { function getreports($conn, $count = 10) {
$query = $conn->prepare('SELECT * FROM user_reports LIMIT ?'); $query = $conn->prepare('SELECT * FROM user_reports LIMIT ?');
$query->execute([$count]); $query->execute([$count]);
return $query->fetchAll(); return $query->fetchAll();
}
function sandwitch($str){
$output = "";
$arr = explode(",", $str);
foreach ($arr as $word){
$word = ucfirst($word);
if (stripos($word, 'nsfw') !== false) {
$word = strtoupper($word);
$tagcolor = "tag is-danger";
}
elseif (stripos($word, 'SAFE') !== false) {
$word = strtoupper($word);
$tagcolor = "tag is-success";
}
elseif (strstr($word, '/')){
$tagcolor = "tag is-primary";
}else{
$tagcolor = "tag is-info";
}
$output .= '<a href="/archive?q='.trim($word).'"><span class="' . $tagcolor . '">'.trim($word).'</span>';
}
return $output;
} }
function sandwitch($str) {
function getevent($conn, $event_name, $count) $output = "";
{ $arr = explode(",", $str);
foreach ($arr as $word) {
$word = ucfirst($word);
if (stripos($word, 'nsfw') !== false) {
$word = strtoupper($word);
$tagcolor = "tag is-danger";
} elseif (stripos($word, 'SAFE') !== false) {
$word = strtoupper($word);
$tagcolor = "tag is-success";
} elseif (strstr($word, '/')) {
$tagcolor = "tag is-primary";
} else {
$tagcolor = "tag is-info";
}
$output .= '<a href="/archive?q=' . trim($word) . '"><span class="' . $tagcolor . '">' . trim($word) . '</span>';
}
return $output;
}
function getevent($conn, $event_name, $count) {
$query = $conn->prepare("SELECT id, visible, title, date, now_time, views, member, tagsys FROM pastes WHERE visible='1' AND tagsys LIKE '%?%' $query = $conn->prepare("SELECT id, visible, title, date, now_time, views, member, tagsys FROM pastes WHERE visible='1' AND tagsys LIKE '%?%'
ORDER BY RAND () LIMIT 0, ?"); ORDER BY RAND () LIMIT 0, ?");
$query->execute([$event_name,$count]); $query->execute([$event_name, $count]);
return $query->fetchAll(); return $query->fetchAll();
} }
function linkify($value, $protocols = array('http', 'mail'), array $attributes = array()) function linkify($value, $protocols = array('http', 'mail'), array $attributes = array()) {
{ // Link attributes
// Link attributes $attr = '';
$attr = ''; foreach ($attributes as $key => $val) {
foreach ($attributes as $key => $val) { $attr .= ' ' . $key . '="' . htmlentities($val) . '"';
$attr .= ' ' . $key . '="' . htmlentities($val) . '"';
}
$links = array();
// Extract existing links and tags
$value = preg_replace_callback('~(<a .*?>.*?</a>|<.*?>)~i', function ($match) use (&$links) { return '<' . array_push($links, $match[1]) . '>'; }, $value);
// Extract text links for each protocol
foreach ((array)$protocols as $protocol) {
switch ($protocol) {
case 'http':
case 'https': $value = preg_replace_callback('~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i', function ($match) use ($protocol, &$links, $attr) { if ($match[1]) $protocol = $match[1]; $link = $match[2] ?: $match[3]; return '<' . array_push($links, "<a $attr href=\"$protocol://$link\">$protocol://$link</a>") . '>'; }, $value); break;
default: $value = preg_replace_callback('~' . preg_quote($protocol, '~') . '://([^\s<]+?)(?<![\.,:])~i', function ($match) use ($protocol, &$links, $attr) { return '<' . array_push($links, "<a $attr href=\"$protocol://{$match[1]}\">$protocol://{$match[1]}</a>") . '>'; }, $value); break;
}
}
// Insert all link
return preg_replace_callback('/<(\d+)>/', function ($match) use (&$links) { return $links[$match[1] - 1]; }, $value);
} }
$links = array();
// Extract existing links and tags
$value = preg_replace_callback('~(<a .*?>.*?</a>|<.*?>)~i', function ($match) use (&$links) {
return '<' . array_push($links, $match[1]) . '>';
}, $value);
// Extract text links for each protocol
foreach ((array)$protocols as $protocol) {
switch ($protocol) {
case 'http':
case 'https':
$value = preg_replace_callback('~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i', function ($match) use ($protocol, &$links, $attr) {
if ($match[1]) $protocol = $match[1];
$link = $match[2] ?: $match[3];
return '<' . array_push($links, "<a $attr href=\"$protocol://$link\">$protocol://$link</a>") . '>';
}, $value);
break;
default:
$value = preg_replace_callback('~' . preg_quote($protocol, '~') . '://([^\s<]+?)(?<![\.,:])~i', function ($match) use ($protocol, &$links, $attr) {
return '<' . array_push($links, "<a $attr href=\"$protocol://{$match[1]}\">$protocol://{$match[1]}</a>") . '>';
}, $value);
break;
}
}
// Insert all link
return preg_replace_callback('/<(\d+)>/', function ($match) use (&$links) {
return $links[$match[1] - 1];
}, $value);
}
function getRecentreport($conn, $count) function getRecentreport($conn, $count) {
{
$query = $conn->prepare("SELECT id, m_report, p_report, rep_reason, t_report FROM user_reports $query = $conn->prepare("SELECT id, m_report, p_report, rep_reason, t_report FROM user_reports
ORDER BY id DESC ORDER BY id DESC
LIMIT 0 , ?"); LIMIT 0 , ?");
$query->execute([$count]); $query->execute([$count]);
return $query->fetchAll(); return $query->fetchAll();
} }
function getUserRecom($conn,$p_member) function getUserRecom($conn, $p_member) {
{
$query = $conn->prepare("SELECT id, member, title, visible $query = $conn->prepare("SELECT id, member, title, visible
FROM pastes where member= ? AND visible = '0' FROM pastes where member= ? AND visible = '0'
ORDER BY id DESC ORDER BY id DESC
@ -149,61 +149,56 @@ function recentupdate($conn, $count) {
$query->execute([$count]); $query->execute([$count]);
return $query->fetchAll(); return $query->fetchAll();
} }
//Cannot get this to work. //Cannot get this to work.
function monthpop($conn, $count) { function monthpop($conn, $count) {
$p_month = date('F'); $p_month = date('F');
$query = $conn->prepare("SELECT s_date, views, title, id, now_time, visible, tagsys, member FROM pastes WHERE s_date LIKE ? AND visible = '0' ORDER BY views + 0 DESC LIMIT 10, ?"); $query = $conn->prepare("SELECT s_date, views, title, id, now_time, visible, tagsys, member FROM pastes WHERE s_date LIKE ? AND visible = '0' ORDER BY views + 0 DESC LIMIT 10, ?");
$query->execute([$p_month,$count]); $query->execute([$p_month, $count]);
return $query->fetchAll(); return $query->fetchAll();
} }
function isValidEmail($email) { function isValidEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL) return filter_var($email, FILTER_VALIDATE_EMAIL)
&& preg_match('/@.+\./', $email); && preg_match('/@.+\./', $email);
} }
function formatBytes($size, $precision = 2)
{
$base = log($size, 1024);
$suffixes = array('B', 'KB', 'MB', 'GB', 'TB');
return round(pow(1024, $base - floor($base)), $precision) .' '. $suffixes[floor($base)]; function formatBytes($size, $precision = 2) {
$base = log($size, 1024);
$suffixes = array('B', 'KB', 'MB', 'GB', 'TB');
return round(pow(1024, $base - floor($base)), $precision) . ' ' . $suffixes[floor($base)];
} }
function str_conntains($haystack, $needle, $ignoreCase = false) function str_conntains($haystack, $needle, $ignoreCase = false) {
{
if ($ignoreCase) { if ($ignoreCase) {
$haystack = strtolower($haystack); $haystack = strtolower($haystack);
$needle = strtolower($needle); $needle = strtolower($needle);
} }
$needlePos = strpos($haystack, $needle); $needlePos = strpos($haystack, $needle);
return ($needlePos === false ? false : ($needlePos + 1)); return ($needlePos === false ? false : ($needlePos + 1));
} }
function encrypt($value) function encrypt($value) {
{ $salt = $sec_key;
$salt = $sec_key; $encrypted_string = openssl_encrypt($value, "AES-256-CBC", $salt);
$encrypted_string=openssl_encrypt($value,"AES-256-CBC",$salt); return $encrypted_string;
return $encrypted_string;
} }
function decrypt($value) function decrypt($value) {
{ $salt = $sec_key;
$salt = $sec_key; $decrypted_string = openssl_decrypt($value, "AES-256-CBC", $salt);
$decrypted_string=openssl_decrypt($value,"AES-256-CBC",$salt); return $decrypted_string;
return $decrypted_string;
} }
function deleteMyPaste($conn, $paste_id) function deleteMyPaste($conn, $paste_id) {
{ $query = "DELETE FROM pastes where id='$paste_id'";
$query = "DELETE FROM pastes where id='$paste_id'";
$result = mysqli_query($conn, $query); $result = mysqli_query($conn, $query);
} }
function getRecent($conn, $count) function getRecent($conn, $count) {
{
$query = $conn->prepare("SELECT id, visible, title, date, now_time, member, tagsys $query = $conn->prepare("SELECT id, visible, title, date, now_time, member, tagsys
FROM pastes where visible='0' FROM pastes where visible='0'
ORDER BY id DESC ORDER BY id DESC
@ -212,16 +207,15 @@ LIMIT ?");
return $query->fetchAll(); return $query->fetchAll();
} }
function getRecentadmin($conn, $count = 5) function getRecentadmin($conn, $count = 5) {
{
$query = $conn->prepare('SELECT id, ip title, date, now_time, s_date, views, member FROM pastes ORDER BY id DESC LIMIT 0, ?'); $query = $conn->prepare('SELECT id, ip title, date, now_time, s_date, views, member FROM pastes ORDER BY id DESC LIMIT 0, ?');
$query->execute([$count]); $query->execute([$count]);
return $query->fetchAll(); return $query->fetchAll();
} }
function getpopular($conn, $count)
{ function getpopular($conn, $count) {
$query = $conn->prepare("SELECT id, visible, title, date, now_time, views, member, tagsys $query = $conn->prepare("SELECT id, visible, title, date, now_time, views, member, tagsys
FROM pastes WHERE visible='0' FROM pastes WHERE visible='0'
ORDER BY views + 0 DESC ORDER BY views + 0 DESC
LIMIT 0, ?"); LIMIT 0, ?");
@ -229,8 +223,7 @@ LIMIT 0, ?");
return $query->fetchAll(); return $query->fetchAll();
} }
function getrandom($conn, $count) function getrandom($conn, $count) {
{
$query = $conn->prepare("SELECT id, visible, title, date, now_time, views, member, tagsys $query = $conn->prepare("SELECT id, visible, title, date, now_time, views, member, tagsys
FROM pastes where visible='0' FROM pastes where visible='0'
ORDER BY RAND() ORDER BY RAND()
@ -239,26 +232,23 @@ LIMIT ?");
return $query->fetchAll(); return $query->fetchAll();
} }
function getUserRecent($conn, $count, $username) function getUserRecent($conn, $count, $username) {
{ $query = $conn->prepare("SELECT id, member, title, date, now_time
$query = $conn->prepare("SELECT id, member, title, date, now_time
FROM pastes where member=? FROM pastes where member=?
ORDER BY id DESC ORDER BY id DESC
LIMIT 0 , ?"); LIMIT 0 , ?");
$query->execute([$username,$count]); $query->execute([$username, $count]);
return $query->fetchAll(); return $query->fetchAll();
} }
function getUserPastes($conn, $username) function getUserPastes($conn, $username) {
{
$query = $conn->prepare("SELECT id, title, code, views, s_date, now_time, visible, date, tagsys, member FROM pastes where member=? ORDER by id DESC"); $query = $conn->prepare("SELECT id, title, code, views, s_date, now_time, visible, date, tagsys, member FROM pastes where member=? ORDER by id DESC");
$query->execute([$username]); $query->execute([$username]);
return $query->fetchAll(); return $query->fetchAll();
} }
function jsonView($paste_id, $p_title, $p_conntent, $p_code) function jsonView($paste_id, $p_title, $p_conntent, $p_code) {
{
$stats = false; $stats = false;
if ($p_code) { if ($p_code) {
// Raw // Raw
@ -273,10 +263,8 @@ function jsonView($paste_id, $p_title, $p_conntent, $p_code)
} }
function getTotalPastes($conn, $username) {
function getTotalPastes($conn, $username) $count = 0;
{
$count = 0;
$query = $conn->prepare("SELECT member FROM pastes WHERE member=?"); $query = $conn->prepare("SELECT member FROM pastes WHERE member=?");
$query->execute([$username]); $query->execute([$username]);
while ($row = $site_info_rows->fetch()) { while ($row = $site_info_rows->fetch()) {
@ -293,11 +281,10 @@ function existingUser(PDO $conn, string $username) : bool {
$query = $conn->prepare('SELECT 1 FROM users WHERE username = ?'); $query = $conn->prepare('SELECT 1 FROM users WHERE username = ?');
$query->execute([$username]); $query->execute([$username]);
return (bool) $query->fetch(); return (bool)$query->fetch();
} }
function updateMyView($conn, $paste_id) function updateMyView($conn, $paste_id) {
{
$query = $conn->prepare("SELECT views, id FROM pastes WHERE id= ?"); $query = $conn->prepare("SELECT views, id FROM pastes WHERE id= ?");
$query->execute([$paste_id]); $query->execute([$paste_id]);
if ($row = $query->fetch()) { if ($row = $query->fetch()) {
@ -344,13 +331,12 @@ function conTime($secs) {
return $val; return $val;
} }
function truncate($input, $maxWords, $maxChars) function truncate($input, $maxWords, $maxChars) {
{
$words = preg_split('/\s+/', $input); $words = preg_split('/\s+/', $input);
$words = array_slice($words, 0, $maxWords); $words = array_slice($words, 0, $maxWords);
$words = array_reverse($words); $words = array_reverse($words);
$chars = 0; $chars = 0;
$truncated = array(); $truncated = array();
while (count($words) > 0) { while (count($words) > 0) {
@ -367,15 +353,16 @@ function truncate($input, $maxWords, $maxChars)
return $result . ($input == $result ? '' : '[...]'); return $result . ($input == $result ? '' : '[...]');
} }
function truncatetag($input, $maxWords, $maxChars)
{$str = $input; function truncatetag($input, $maxWords, $maxChars) {
$pattern = '/,/i'; $str = $input;
$words = preg_replace($pattern, ' ', $str); $pattern = '/,/i';
$words = preg_replace($pattern, ' ', $str);
$words = preg_split('/\s+/', $input); $words = preg_split('/\s+/', $input);
$words = array_slice($words, 0, $maxWords); $words = array_slice($words, 0, $maxWords);
$words = array_reverse($words); $words = array_reverse($words);
$chars = 0; $chars = 0;
$truncated1 = array(); $truncated1 = array();
while (count($words) > 0) { while (count($words) > 0) {
@ -392,8 +379,8 @@ function truncatetag($input, $maxWords, $maxChars)
return $result . ($input == $result ? '' : '...'); return $result . ($input == $result ? '' : '...');
} }
function doDownload($paste_id, $p_title, $p_member, $p_conntent, $p_code)
{ function doDownload($paste_id, $p_title, $p_member, $p_conntent, $p_code) {
$stats = false; $stats = false;
if ($p_code) { if ($p_code) {
// Figure out extensions. // Figure out extensions.
@ -417,8 +404,7 @@ function doDownload($paste_id, $p_title, $p_member, $p_conntent, $p_code)
return $stats; return $stats;
} }
function rawView($paste_id, $p_title, $p_conntent, $p_code) function rawView($paste_id, $p_title, $p_conntent, $p_code) {
{
$stats = false; $stats = false;
if ($p_code) { if ($p_code) {
// Raw // Raw
@ -433,14 +419,13 @@ function rawView($paste_id, $p_title, $p_conntent, $p_code)
} }
function embedView($paste_id, $p_title, $p_conntent, $p_code, $title, $baseurl, $ges_style, $lang) {
function embedView( $paste_id, $p_title, $p_conntent, $p_code, $title, $baseurl, $ges_style, $lang ) {
$stats = false; $stats = false;
if ( $p_conntent ) { if ($p_conntent) {
// Build the output // Build the output
$output = "<div class='paste_embed_conntainer'>"; $output = "<div class='paste_embed_conntainer'>";
$output .= "<style>"; // Add our own styles $output .= "<style>"; // Add our own styles
$output .= " $output .= "
.paste_embed_conntainer { .paste_embed_conntainer {
font-size: 12px; font-size: 12px;
color: #333; color: #333;
@ -483,33 +468,32 @@ function embedView( $paste_id, $p_title, $p_conntent, $p_code, $title, $baseurl,
background: #ffffff; background: #ffffff;
line-height:20px; line-height:20px;
}"; }";
$output .= "</style>"; $output .= "</style>";
$output .= "$ges_style"; // Dynamic GeSHI Style $output .= "$ges_style"; // Dynamic GeSHI Style
$output .= $p_conntent; // Paste conntent $output .= $p_conntent; // Paste conntent
$output .= "<div class='paste_embed_footer'>"; $output .= "<div class='paste_embed_footer'>";
$output .= "<a href='https://ponepaste.org/$paste_id'>$p_title</a> " . $lang['embed-hosted-by'] . " <a href='https://ponepaste.org'>$title</a> | <a href='https://ponepaste.org/raw/$paste_id'>" . strtolower( $lang['view-raw'] ) . "</a>"; $output .= "<a href='https://ponepaste.org/$paste_id'>$p_title</a> " . $lang['embed-hosted-by'] . " <a href='https://ponepaste.org'>$title</a> | <a href='https://ponepaste.org/raw/$paste_id'>" . strtolower($lang['view-raw']) . "</a>";
$output .= "</div>"; $output .= "</div>";
$output .= "</div>"; $output .= "</div>";
// Display embed conntent using json_encode since that escapes // Display embed conntent using json_encode since that escapes
// characters well enough to satisfy javascript. http://stackoverflow.com/a/169035 // characters well enough to satisfy javascript. http://stackoverflow.com/a/169035
header( 'conntent-type: text/javascript; charset=utf-8;' ); header('conntent-type: text/javascript; charset=utf-8;');
echo 'document.write(' . json_encode( $output ) . ')'; echo 'document.write(' . json_encode($output) . ')';
$stats = true; $stats = true;
} else { } else {
// 404 // 404
header( 'HTTP/1.1 404 Not Found' ); header('HTTP/1.1 404 Not Found');
} }
return $stats; return $stats;
} }
function addToSitemap($paste_id, $priority, $changefreq, $mod_rewrite) function addToSitemap($paste_id, $priority, $changefreq, $mod_rewrite) {
{ $c_date = date('Y-m-d');
$c_date = date('Y-m-d');
$site_data = file_get_contents("sitemap.xml"); $site_data = file_get_contents("sitemap.xml");
$site_data = str_replace("</urlset>", "", $site_data); $site_data = str_replace("</urlset>", "", $site_data);
// which protocol are we on // which protocol are we on
$protocol = paste_protocol(); $protocol = paste_protocol();
if ($mod_rewrite == "1") { if ($mod_rewrite == "1") {
$server_name = $protocol . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/" . $paste_id; $server_name = $protocol . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/" . $paste_id;
@ -517,8 +501,8 @@ function addToSitemap($paste_id, $priority, $changefreq, $mod_rewrite)
$server_name = $protocol . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/paste.php?id=" . $paste_id; $server_name = $protocol . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/paste.php?id=" . $paste_id;
} }
$c_sitemap = $c_sitemap =
' <url> ' <url>
<loc>' . $server_name . '</loc> <loc>' . $server_name . '</loc>
<priority>' . $priority . '</priority> <priority>' . $priority . '</priority>
<changefreq>' . $changefreq . '</changefreq> <changefreq>' . $changefreq . '</changefreq>
@ -526,20 +510,22 @@ function addToSitemap($paste_id, $priority, $changefreq, $mod_rewrite)
</url> </url>
</urlset>'; </urlset>';
$full_map = $site_data . $c_sitemap; $full_map = $site_data . $c_sitemap;
file_put_contents("sitemap.xml", $full_map); file_put_contents("sitemap.xml", $full_map);
} }
function paste_protocol() { function paste_protocol() {
$protocol = ( isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == "on" ) ? 'https://' : 'http://'; $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? 'https://' : 'http://';
return $protocol; return $protocol;
} }
function is_banned($conn, $ip) { function is_banned($conn, $ip) {
$query = $conn->prepare('SELECT 1 FROM ban_user WHERE ip = ?'); $query = $conn->prepare('SELECT 1 FROM ban_user WHERE ip = ?');
$query->execute([$ip]); $query->execute([$ip]);
return (bool) $query->fetch(); return (bool)$query->fetch();
} }
?> ?>

File diff suppressed because it is too large Load diff

View file

@ -27,7 +27,7 @@ $language_data = array(
'COMMENT_SINGLE' => array( 'COMMENT_SINGLE' => array(
1 => '>', 1 => '>',
2 => '>' 2 => '>'
), ),
'COMMENT_MULTI' => array(), 'COMMENT_MULTI' => array(),
'COMMENT_REGEXP' => array(), 'COMMENT_REGEXP' => array(),
'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE, 'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE,
@ -40,26 +40,26 @@ $language_data = array(
'KEYWORDS' => array( 'KEYWORDS' => array(
1 => array( 1 => array(
'' ''
) )
), ),
'CASE_SENSITIVE' => array( 'CASE_SENSITIVE' => array(
1 => false 1 => false
), ),
'SYMBOLS' => array( 'SYMBOLS' => array(
0 => array( 0 => array(
'' ''
) )
), ),
'STYLES' => array( 'STYLES' => array(
'KEYWORDS' => array( 'KEYWORDS' => array(
1 => 'color: #0000FF; font-weight: bold;' 1 => 'color: #0000FF; font-weight: bold;'
), ),
'COMMENTS' => array( 'COMMENTS' => array(
1 => 'font-style: normal; color: #789922; line-height: 1.2;', 1 => 'font-style: normal; color: #789922; line-height: 1.2;',
2 => 'font-style: normal color: #789922; line-height: 1.2;', 2 => 'font-style: normal color: #789922; line-height: 1.2;',
1 => 'font-style: normal; color: #789922; line-height: 1.2;', 1 => 'font-style: normal; color: #789922; line-height: 1.2;',
'MULTI' => 'font-style: normal; color: #666666; line-height: 1.2;' 'MULTI' => 'font-style: normal; color: #666666; line-height: 1.2;'
), ),
'ESCAPE_CHAR' => array(), 'ESCAPE_CHAR' => array(),
'BRACKETS' => array(), 'BRACKETS' => array(),
'STRINGS' => array(), 'STRINGS' => array(),
@ -67,7 +67,7 @@ $language_data = array(
'SYMBOLS' => array(), 'SYMBOLS' => array(),
'REGEXPS' => array(), 'REGEXPS' => array(),
'SCRIPT' => array() 'SCRIPT' => array()
), ),
'URLS' => array(), 'URLS' => array(),
'OOLANG' => false, 'OOLANG' => false,
'OBJECT_SPLITTERS' => array(), 'OBJECT_SPLITTERS' => array(),

View file

@ -49,7 +49,7 @@
* *
************************************************************************************/ ************************************************************************************/
$language_data = array ( $language_data = array(
'LANG_NAME' => 'HTML5', 'LANG_NAME' => 'HTML5',
'COMMENT_SINGLE' => array(), 'COMMENT_SINGLE' => array(),
'COMMENT_MULTI' => array(), 'COMMENT_MULTI' => array(),
@ -99,7 +99,7 @@ $language_data = array (
'var', 'video', 'var', 'video',
'wbr', 'wbr',
), ),
3 => array( 3 => array(
'abbr', 'accept-charset', 'accept', 'accesskey', 'action', 'align', 'alink', 'alt', 'archive', 'axis', 'autocomplete', 'autofocus', 'abbr', 'accept-charset', 'accept', 'accesskey', 'action', 'align', 'alink', 'alt', 'archive', 'axis', 'autocomplete', 'autofocus',
'background', 'bgcolor', 'border', 'background', 'bgcolor', 'border',
@ -120,76 +120,71 @@ $language_data = array (
'usemap', 'usemap',
'valign', 'value', 'valuetype', 'version', 'vlink', 'vspace', 'valign', 'value', 'valuetype', 'version', 'vlink', 'vspace',
'width' 'width'
) )
), ),
'SYMBOLS' => array( 'SYMBOLS' => array(
'/', '=' '/', '='
), ),
'CASE_SENSITIVE' => array( 'CASE_SENSITIVE' => array(
GESHI_COMMENTS => false, GESHI_COMMENTS => false,
2 => false, 2 => false,
3 => false, 3 => false,
), ),
'STYLES' => array( 'STYLES' => array(
'KEYWORDS' => array( 'KEYWORDS' => array(
2 => 'color: #000000; font-weight: bold;', 2 => 'color: #000000; font-weight: bold;',
3 => 'color: #000066;' 3 => 'color: #000066;'
), ),
'COMMENTS' => array( 'COMMENTS' => array(),
),
'ESCAPE_CHAR' => array( 'ESCAPE_CHAR' => array(
0 => 'color: #000099; font-weight: bold;' 0 => 'color: #000099; font-weight: bold;'
), ),
'BRACKETS' => array( 'BRACKETS' => array(
0 => 'color: #66cc66;' 0 => 'color: #66cc66;'
), ),
'STRINGS' => array( 'STRINGS' => array(
0 => 'color: #ff0000;' 0 => 'color: #ff0000;'
), ),
'NUMBERS' => array( 'NUMBERS' => array(
0 => 'color: #cc66cc;' 0 => 'color: #cc66cc;'
), ),
'METHODS' => array( 'METHODS' => array(),
),
'SYMBOLS' => array( 'SYMBOLS' => array(
0 => 'color: #66cc66;' 0 => 'color: #66cc66;'
), ),
'SCRIPT' => array( 'SCRIPT' => array(
-2 => 'color: #404040;', // CDATA -2 => 'color: #404040;', // CDATA
-1 => 'color: #808080; font-style: italic;', // comments -1 => 'color: #808080; font-style: italic;', // comments
0 => 'color: #00bbdd;', 0 => 'color: #00bbdd;',
1 => 'color: #ddbb00;', 1 => 'color: #ddbb00;',
2 => 'color: #009900;' 2 => 'color: #009900;'
),
'REGEXPS' => array(
)
), ),
'REGEXPS' => array()
),
'URLS' => array( 'URLS' => array(
2 => 'http://december.com/html/4/element/{FNAMEL}.html', 2 => 'http://december.com/html/4/element/{FNAMEL}.html',
3 => '' 3 => ''
), ),
'OOLANG' => false, 'OOLANG' => false,
'OBJECT_SPLITTERS' => array( 'OBJECT_SPLITTERS' => array(),
), 'REGEXPS' => array(),
'REGEXPS' => array(
),
'STRICT_MODE_APPLIES' => GESHI_ALWAYS, 'STRICT_MODE_APPLIES' => GESHI_ALWAYS,
'SCRIPT_DELIMITERS' => array( 'SCRIPT_DELIMITERS' => array(
-2 => array( -2 => array(
'<![CDATA[' => ']]>' '<![CDATA[' => ']]>'
), ),
-1 => array( -1 => array(
'<!--' => '-->' '<!--' => '-->'
), ),
0 => array( 0 => array(
'<!DOCTYPE' => '>' '<!DOCTYPE' => '>'
), ),
1 => array( 1 => array(
'&' => ';' '&' => ';'
), ),
2 => array( 2 => array(
'<' => '>' '<' => '>'
) )
), ),
'HIGHLIGHT_STRICT_BLOCK' => array( 'HIGHLIGHT_STRICT_BLOCK' => array(
-2 => false, -2 => false,
@ -197,7 +192,7 @@ $language_data = array (
0 => false, 0 => false,
1 => false, 1 => false,
2 => true 2 => true
), ),
'TAB_WIDTH' => 4, 'TAB_WIDTH' => 4,
'PARSER_CONTROL' => array( 'PARSER_CONTROL' => array(
'KEYWORDS' => array( 'KEYWORDS' => array(

View file

@ -51,7 +51,7 @@
* *
************************************************************************************/ ************************************************************************************/
$language_data = array ( $language_data = array(
'LANG_NAME' => 'Java', 'LANG_NAME' => 'Java',
'COMMENT_SINGLE' => array(1 => '//'), 'COMMENT_SINGLE' => array(1 => '//'),
'COMMENT_MULTI' => array('/*' => '*/'), 'COMMENT_MULTI' => array('/*' => '*/'),
@ -60,24 +60,24 @@ $language_data = array (
2 => '/(?:(?<=import[\\n\\s])|(?<=package[\\n\\s]))[\\n\\s]*([a-zA-Z0-9_]+\\.)*([a-zA-Z0-9_]+|\*)(?=[\n\s;])/i', 2 => '/(?:(?<=import[\\n\\s])|(?<=package[\\n\\s]))[\\n\\s]*([a-zA-Z0-9_]+\\.)*([a-zA-Z0-9_]+|\*)(?=[\n\s;])/i',
// javadoc comments // javadoc comments
3 => '#/\*\*(?![\*\/]).*\*/#sU' 3 => '#/\*\*(?![\*\/]).*\*/#sU'
), ),
'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE, 'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE,
'QUOTEMARKS' => array("'", '"'), 'QUOTEMARKS' => array("'", '"'),
'ESCAPE_CHAR' => '\\', 'ESCAPE_CHAR' => '\\',
'KEYWORDS' => array( 'KEYWORDS' => array(
1 => array( 1 => array(
'for', 'foreach', 'if', 'else', 'while', 'do', 'for', 'foreach', 'if', 'else', 'while', 'do',
'switch', 'case', 'return', 'public', 'switch', 'case', 'return', 'public',
'private', 'protected', 'extends', 'break', 'class', 'private', 'protected', 'extends', 'break', 'class',
'new', 'try', 'catch', 'throws', 'finally', 'implements', 'new', 'try', 'catch', 'throws', 'finally', 'implements',
'interface', 'throw', 'final', 'native', 'synchronized', 'this', 'interface', 'throw', 'final', 'native', 'synchronized', 'this',
'abstract', 'transient', 'instanceof', 'assert', 'continue', 'abstract', 'transient', 'instanceof', 'assert', 'continue',
'default', 'enum', 'package', 'static', 'strictfp', 'super', 'default', 'enum', 'package', 'static', 'strictfp', 'super',
'volatile', 'const', 'goto', 'import' 'volatile', 'const', 'goto', 'import'
), ),
2 => array( 2 => array(
'null', 'false', 'true' 'null', 'false', 'true'
), ),
3 => array( 3 => array(
'AbstractAction', 'AbstractBorder', 'AbstractButton', 'AbstractAction', 'AbstractBorder', 'AbstractButton',
'AbstractCellEditor', 'AbstractCollection', 'AbstractCellEditor', 'AbstractCollection',
@ -904,77 +904,72 @@ $language_data = array (
'_BindingIteratorImplBase', '_BindingIteratorStub', '_BindingIteratorImplBase', '_BindingIteratorStub',
'_IDLTypeStub', '_NamingContextImplBase', '_IDLTypeStub', '_NamingContextImplBase',
'_NamingContextStub', '_PolicyStub', '_Remote_Stub' '_NamingContextStub', '_PolicyStub', '_Remote_Stub'
), ),
4 => array( 4 => array(
'void', 'double', 'int', 'boolean', 'byte', 'short', 'long', 'char', 'float' 'void', 'double', 'int', 'boolean', 'byte', 'short', 'long', 'char', 'float'
) )
), ),
'SYMBOLS' => array( 'SYMBOLS' => array(
'(', ')', '[', ']', '{', '}', '(', ')', '[', ']', '{', '}',
'+', '-', '*', '/', '%', '+', '-', '*', '/', '%',
'!', '&', '|', '^', '!', '&', '|', '^',
'<', '>', '=', '<', '>', '=',
'?', ':', ';', '?', ':', ';',
), ),
'CASE_SENSITIVE' => array( 'CASE_SENSITIVE' => array(
GESHI_COMMENTS => false, GESHI_COMMENTS => false,
1 => false, 1 => false,
2 => false, 2 => false,
3 => true, 3 => true,
4 => true 4 => true
), ),
'STYLES' => array( 'STYLES' => array(
'KEYWORDS' => array( 'KEYWORDS' => array(
1 => 'color: #000000; font-weight: bold;', 1 => 'color: #000000; font-weight: bold;',
2 => 'color: #000066; font-weight: bold;', 2 => 'color: #000066; font-weight: bold;',
3 => 'color: #003399;', 3 => 'color: #003399;',
4 => 'color: #000066; font-weight: bold;' 4 => 'color: #000066; font-weight: bold;'
), ),
'COMMENTS' => array( 'COMMENTS' => array(
1 => 'color: #666666; font-style: italic;', 1 => 'color: #666666; font-style: italic;',
2 => 'color: #006699;', 2 => 'color: #006699;',
3 => 'color: #008000; font-style: italic; font-weight: bold;', 3 => 'color: #008000; font-style: italic; font-weight: bold;',
'MULTI' => 'color: #666666; font-style: italic;' 'MULTI' => 'color: #666666; font-style: italic;'
), ),
'ESCAPE_CHAR' => array( 'ESCAPE_CHAR' => array(
0 => 'color: #000099; font-weight: bold;' 0 => 'color: #000099; font-weight: bold;'
), ),
'BRACKETS' => array( 'BRACKETS' => array(
0 => 'color: #009900;' 0 => 'color: #009900;'
), ),
'STRINGS' => array( 'STRINGS' => array(
0 => 'color: #0000ff;' 0 => 'color: #0000ff;'
), ),
'NUMBERS' => array( 'NUMBERS' => array(
0 => 'color: #cc66cc;' 0 => 'color: #cc66cc;'
), ),
'METHODS' => array( 'METHODS' => array(
1 => 'color: #006633;', 1 => 'color: #006633;',
2 => 'color: #006633;' 2 => 'color: #006633;'
), ),
'SYMBOLS' => array( 'SYMBOLS' => array(
0 => 'color: #339933;' 0 => 'color: #339933;'
),
'SCRIPT' => array(
),
'REGEXPS' => array(
)
), ),
'SCRIPT' => array(),
'REGEXPS' => array()
),
'URLS' => array( 'URLS' => array(
1 => '', 1 => '',
2 => '', 2 => '',
3 => 'http://www.google.com/search?hl=en&amp;q=allinurl%3Adocs.oracle.com+javase+docs+api+{FNAMEL}', 3 => 'http://www.google.com/search?hl=en&amp;q=allinurl%3Adocs.oracle.com+javase+docs+api+{FNAMEL}',
4 => '' 4 => ''
), ),
'OOLANG' => true, 'OOLANG' => true,
'OBJECT_SPLITTERS' => array( 'OBJECT_SPLITTERS' => array(
1 => '.' 1 => '.'
), ),
'REGEXPS' => array( 'REGEXPS' => array(),
),
'STRICT_MODE_APPLIES' => GESHI_NEVER, 'STRICT_MODE_APPLIES' => GESHI_NEVER,
'SCRIPT_DELIMITERS' => array( 'SCRIPT_DELIMITERS' => array(),
), 'HIGHLIGHT_STRICT_BLOCK' => array()
'HIGHLIGHT_STRICT_BLOCK' => array(
)
); );

View file

@ -43,59 +43,59 @@
* *
************************************************************************************/ ************************************************************************************/
$language_data = array ( $language_data = array(
'LANG_NAME' => 'Javascript', 'LANG_NAME' => 'Javascript',
'COMMENT_SINGLE' => array(1 => '//'), 'COMMENT_SINGLE' => array(1 => '//'),
'COMMENT_MULTI' => array('/*' => '*/'), 'COMMENT_MULTI' => array('/*' => '*/'),
'COMMENT_REGEXP' => array( 'COMMENT_REGEXP' => array(
//Regular Expressions //Regular Expressions
2 => "/(?<=[\\s^])(s|tr|y)\\/(?!\*)(?!\s)(?:\\\\.|(?!\n)[^\\/\\\\])+(?<!\s)\\/(?!\s)(?:\\\\.|(?!\n)[^\\/\\\\])*(?<!\s)\\/[msixpogcde]*(?=[\\s$\\.\\;])|(?<=[\\s^(=])(m|q[qrwx]?)?\\/(?!\*)(?!\s)(?:\\\\.|(?!\n)[^\\/\\\\])+(?<!\s)\\/[msixpogc]*(?=[\\s$\\.\\,\\;\\)])/iU" 2 => "/(?<=[\\s^])(s|tr|y)\\/(?!\*)(?!\s)(?:\\\\.|(?!\n)[^\\/\\\\])+(?<!\s)\\/(?!\s)(?:\\\\.|(?!\n)[^\\/\\\\])*(?<!\s)\\/[msixpogcde]*(?=[\\s$\\.\\;])|(?<=[\\s^(=])(m|q[qrwx]?)?\\/(?!\*)(?!\s)(?:\\\\.|(?!\n)[^\\/\\\\])+(?<!\s)\\/[msixpogc]*(?=[\\s$\\.\\,\\;\\)])/iU"
), ),
'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE, 'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE,
'QUOTEMARKS' => array("'", '"'), 'QUOTEMARKS' => array("'", '"'),
'ESCAPE_CHAR' => '\\', 'ESCAPE_CHAR' => '\\',
'KEYWORDS' => array( 'KEYWORDS' => array(
1 => array( 1 => array(
//reserved/keywords; also some non-reserved keywords //reserved/keywords; also some non-reserved keywords
'break','case','catch','const','continue', 'break', 'case', 'catch', 'const', 'continue',
'default','delete','do', 'default', 'delete', 'do',
'else', 'else',
'finally','for','function', 'finally', 'for', 'function',
'get','goto', 'get', 'goto',
'if','in','instanceof', 'if', 'in', 'instanceof',
'new', 'new',
'prototype', 'prototype',
'return', 'return',
'set','static','switch', 'set', 'static', 'switch',
'this','throw','try','typeof', 'this', 'throw', 'try', 'typeof',
'var','void' 'var', 'void'
), ),
2 => array( 2 => array(
//reserved/non-keywords; metaconstants //reserved/non-keywords; metaconstants
'false','null','true','undefined','NaN','Infinity' 'false', 'null', 'true', 'undefined', 'NaN', 'Infinity'
), ),
3 => array( 3 => array(
//magic properties/functions //magic properties/functions
'__proto__','__defineGetter__','__defineSetter__','hasOwnProperty','hasProperty' '__proto__', '__defineGetter__', '__defineSetter__', 'hasOwnProperty', 'hasProperty'
), ),
4 => array( 4 => array(
//type constructors //type constructors
'Object', 'Function', 'Date', 'Math', 'String', 'Number', 'Boolean', 'Array' 'Object', 'Function', 'Date', 'Math', 'String', 'Number', 'Boolean', 'Array'
), ),
5 => array( 5 => array(
//reserved, but invalid in language //reserved, but invalid in language
'abstract','boolean','byte','char','class','debugger','double','enum','export','extends', 'abstract', 'boolean', 'byte', 'char', 'class', 'debugger', 'double', 'enum', 'export', 'extends',
'final','float','implements','import','int','interface','long','native', 'final', 'float', 'implements', 'import', 'int', 'interface', 'long', 'native',
'short','super','synchronized','throws','transient','volatile' 'short', 'super', 'synchronized', 'throws', 'transient', 'volatile'
),
), ),
),
'SYMBOLS' => array( 'SYMBOLS' => array(
'(', ')', '[', ']', '{', '}', '(', ')', '[', ']', '{', '}',
'+', '-', '*', '/', '%', '+', '-', '*', '/', '%',
'!', '@', '&', '|', '^', '!', '@', '&', '|', '^',
'<', '>', '=', '<', '>', '=',
',', ';', '?', ':' ',', ';', '?', ':'
), ),
'CASE_SENSITIVE' => array( 'CASE_SENSITIVE' => array(
GESHI_COMMENTS => false, GESHI_COMMENTS => false,
1 => true, 1 => true,
@ -103,46 +103,45 @@ $language_data = array (
3 => true, 3 => true,
4 => true, 4 => true,
5 => true 5 => true
), ),
'STYLES' => array( 'STYLES' => array(
'KEYWORDS' => array( 'KEYWORDS' => array(
1 => 'color: #000066; font-weight: bold;', 1 => 'color: #000066; font-weight: bold;',
2 => 'color: #003366; font-weight: bold;', 2 => 'color: #003366; font-weight: bold;',
3 => 'color: #000066;', 3 => 'color: #000066;',
5 => 'color: #FF0000;' 5 => 'color: #FF0000;'
), ),
'COMMENTS' => array( 'COMMENTS' => array(
1 => 'color: #006600; font-style: italic;', 1 => 'color: #006600; font-style: italic;',
2 => 'color: #009966; font-style: italic;', 2 => 'color: #009966; font-style: italic;',
'MULTI' => 'color: #006600; font-style: italic;' 'MULTI' => 'color: #006600; font-style: italic;'
), ),
'ESCAPE_CHAR' => array( 'ESCAPE_CHAR' => array(
0 => 'color: #000099; font-weight: bold;' 0 => 'color: #000099; font-weight: bold;'
), ),
'BRACKETS' => array( 'BRACKETS' => array(
0 => 'color: #009900;' 0 => 'color: #009900;'
), ),
'STRINGS' => array( 'STRINGS' => array(
0 => 'color: #3366CC;' 0 => 'color: #3366CC;'
), ),
'NUMBERS' => array( 'NUMBERS' => array(
0 => 'color: #CC0000;' 0 => 'color: #CC0000;'
), ),
'METHODS' => array( 'METHODS' => array(
1 => 'color: #660066;' 1 => 'color: #660066;'
), ),
'SYMBOLS' => array( 'SYMBOLS' => array(
0 => 'color: #339933;' 0 => 'color: #339933;'
), ),
'REGEXPS' => array( 'REGEXPS' => array(),
),
'SCRIPT' => array( 'SCRIPT' => array(
0 => '', 0 => '',
1 => '', 1 => '',
2 => '', 2 => '',
3 => '' 3 => ''
) )
), ),
'URLS' => array( 'URLS' => array(
1 => '', 1 => '',
2 => '', 2 => '',
@ -153,20 +152,19 @@ $language_data = array (
'OOLANG' => true, 'OOLANG' => true,
'OBJECT_SPLITTERS' => array( 'OBJECT_SPLITTERS' => array(
1 => '.' 1 => '.'
), ),
'REGEXPS' => array( 'REGEXPS' => array(),
),
'STRICT_MODE_APPLIES' => GESHI_MAYBE, 'STRICT_MODE_APPLIES' => GESHI_MAYBE,
'SCRIPT_DELIMITERS' => array( 'SCRIPT_DELIMITERS' => array(
0 => array( 0 => array(
'<script type="text/javascript">' => '</script>' '<script type="text/javascript">' => '</script>'
), ),
1 => array( 1 => array(
'<script language="javascript">' => '</script>' '<script language="javascript">' => '</script>'
) )
), ),
'HIGHLIGHT_STRICT_BLOCK' => array( 'HIGHLIGHT_STRICT_BLOCK' => array(
0 => true, 0 => true,
1 => true 1 => true
) )
); );

View file

@ -15,9 +15,9 @@ require_once 'wp-syntax/geshi/geshi.php';
class MarkdownGeshi_Parser extends MarkdownExtra_Parser { class MarkdownGeshi_Parser extends MarkdownExtra_Parser {
/** /**
* The 'processing instruction' pattern for the code blocks parser. * The 'processing instruction' pattern for the code blocks parser.
* Format is defined as : #!language@linenumber. The @linenumber * Format is defined as : #!language@linenumber. The @linenumber
* part is optional. * part is optional.
* *
* Optional parameters are allowed past a semicolon. * Optional parameters are allowed past a semicolon.
*/ */
public $shebang = '/^ public $shebang = '/^
@ -28,77 +28,76 @@ class MarkdownGeshi_Parser extends MarkdownExtra_Parser {
(?:;\s*(?P<params>.*?)\s*)?\n (?:;\s*(?P<params>.*?)\s*)?\n
(?P<code>.*) (?P<code>.*)
/sx'; /sx';
function hasShebang($code) { function hasShebang($code) {
if(preg_match($this->shebang, $code, $m)) { if (preg_match($this->shebang, $code, $m)) {
return $m; return $m;
} }
return false; return false;
} }
function _doCodeBlocks_callback($matches) { function _doCodeBlocks_callback($matches) {
if($m = $this->hasShebang($matches[1])) { if ($m = $this->hasShebang($matches[1])) {
return $this->_doGeshi($m); return $this->_doGeshi($m);
} else { } else {
return parent::_doCodeBlocks_callback($matches); return parent::_doCodeBlocks_callback($matches);
} }
} }
function _doFencedCodeBlocks_callback($matches) { function _doFencedCodeBlocks_callback($matches) {
if($m = $this->hasShebang($matches[2])) { if ($m = $this->hasShebang($matches[2])) {
return $this->_doGeshi($m); return $this->_doGeshi($m);
} else { } else {
return parent::_doFencedCodeBlocks_callback($matches); return parent::_doFencedCodeBlocks_callback($matches);
} }
} }
function _doGeshi($shebangMatch) { function _doGeshi($shebangMatch) {
$language = $shebangMatch['lang']; $language = $shebangMatch['lang'];
$line = (int) (($shebangMatch['linenumber'] > 1) ? $shebangMatch['linenumber'] : 0); $line = (int)(($shebangMatch['linenumber'] > 1) ? $shebangMatch['linenumber'] : 0);
$codeblock = $shebangMatch['code']; $codeblock = $shebangMatch['code'];
$highlighter = new GeSHi($this->outdent(trim($codeblock)), $language); $highlighter = new GeSHi($this->outdent(trim($codeblock)), $language);
$highlighted = $highlighter->parse_code(); $highlighted = $highlighter->parse_code();
if($line) { if ($line) {
preg_match('!^(\s*<pre[^>]+>)(.*)(</pre>)!s', $highlighted, $m); preg_match('!^(\s*<pre[^>]+>)(.*)(</pre>)!s', $highlighted, $m);
$ret = '<ol'; $ret = '<ol';
if($line) { if ($line) {
$ret .= ' start="' . $line .'"'; $ret .= ' start="' . $line . '"';
} }
$ret .= '>'; $ret .= '>';
$ret .= preg_replace( $ret .= preg_replace(
'/.+(\n|$)/', '/.+(\n|$)/',
'<li>$0</li>', '<li>$0</li>',
$m[2] $m[2]
); );
$ret .= '</ol>'; $ret .= '</ol>';
$ret = $m[1] . $ret . $m[3]; $ret = $m[1] . $ret . $m[3];
} else { } else {
$ret = $highlighted; $ret = $highlighted;
} }
if($shebangMatch['params']) { if ($shebangMatch['params']) {
$ret = $this->_processGeshiParams($ret, $shebangMatch['params']); $ret = $this->_processGeshiParams($ret, $shebangMatch['params']);
} }
return "\n\n" . $this->hashBlock($ret) . "\n\n"; return "\n\n" . $this->hashBlock($ret) . "\n\n";
} }
function _processGeshiParams($highlighted, $params) { function _processGeshiParams($highlighted, $params) {
foreach(explode(',', $params) as $keyValuePair) { foreach (explode(',', $params) as $keyValuePair) {
@list($key, $value) = array_map('trim', explode('=', $keyValuePair)); @list($key, $value) = array_map('trim', explode('=', $keyValuePair));
if($key && $value) { if ($key && $value) {
switch($key) { switch ($key) {
case 'gist': case 'gist':
$highlighted = $highlighted =
sprintf( sprintf(
'<cite class="gist">(GIST: <a href="https://gist.github.com/%1$d" target="_blank">%1$d</a>)</cite>', '<cite class="gist">(GIST: <a href="https://gist.github.com/%1$d" target="_blank">%1$d</a>)</cite>',
$value $value
) )
. $highlighted . $highlighted;
;
break; break;
} }
} }

View file

@ -44,23 +44,23 @@
* *
************************************************************************************/ ************************************************************************************/
$language_data = array ( $language_data = array(
'LANG_NAME' => 'MySQL', 'LANG_NAME' => 'MySQL',
//'COMMENT_SINGLE' => array(1 =>'--', 2 => '#'), // '--' MUST be folowed by whitespace,not necessarily a space //'COMMENT_SINGLE' => array(1 =>'--', 2 => '#'), // '--' MUST be folowed by whitespace,not necessarily a space
'COMMENT_SINGLE' => array( 'COMMENT_SINGLE' => array(
1 =>'-- ', 1 => '-- ',
2 => '#' 2 => '#'
), ),
'COMMENT_REGEXP' => array( 'COMMENT_REGEXP' => array(
1 => "/(?:--\s).*?$/", // double dash followed by any whitespace 1 => "/(?:--\s).*?$/", // double dash followed by any whitespace
), ),
'COMMENT_MULTI' => array('/*' => '*/'), 'COMMENT_MULTI' => array('/*' => '*/'),
'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE, // @@@ would be nice if this could be defined per group! 'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE, // @@@ would be nice if this could be defined per group!
'QUOTEMARKS' => array("'", '"', '`'), 'QUOTEMARKS' => array("'", '"', '`'),
'ESCAPE_CHAR' => '\\', // by default only, can be specified 'ESCAPE_CHAR' => '\\', // by default only, can be specified
'ESCAPE_REGEXP' => array( 'ESCAPE_REGEXP' => array(
1 => "/[_%]/", // search wildcards 1 => "/[_%]/", // search wildcards
), ),
'NUMBERS' => 'NUMBERS' =>
GESHI_NUMBER_INT_BASIC | GESHI_NUMBER_INT_BASIC |
GESHI_NUMBER_OCT_PREFIX | GESHI_NUMBER_OCT_PREFIX |
@ -72,217 +72,217 @@ $language_data = array (
1 => array( 1 => array(
// Mix: statement keywords and keywords that don't fit in any other // Mix: statement keywords and keywords that don't fit in any other
// category, or have multiple usage/meanings // category, or have multiple usage/meanings
'ACTION','ADD','AFTER','ALGORITHM','ALL','ALTER','ANALYZE','ANY', 'ACTION', 'ADD', 'AFTER', 'ALGORITHM', 'ALL', 'ALTER', 'ANALYZE', 'ANY',
'ASC','AS','BDB','BEGIN','BERKELEYDB','BINARY','BTREE','CALL', 'ASC', 'AS', 'BDB', 'BEGIN', 'BERKELEYDB', 'BINARY', 'BTREE', 'CALL',
'CASCADED','CASCADE','CHAIN','CHANGE','CHECK','COLUMNS','COLUMN', 'CASCADED', 'CASCADE', 'CHAIN', 'CHANGE', 'CHECK', 'COLUMNS', 'COLUMN',
'COMMENT','COMMIT','COMMITTED','CONSTRAINT','CONTAINS SQL', 'COMMENT', 'COMMIT', 'COMMITTED', 'CONSTRAINT', 'CONTAINS SQL',
'CONSISTENT','CONVERT','CREATE','CROSS','DATA','DATABASES', 'CONSISTENT', 'CONVERT', 'CREATE', 'CROSS', 'DATA', 'DATABASES',
'DECLARE','DEFINER','DELAYED','DELETE','DESCRIBE','DESC', 'DECLARE', 'DEFINER', 'DELAYED', 'DELETE', 'DESCRIBE', 'DESC',
'DETERMINISTIC','DISABLE','DISCARD','DISTINCTROW','DISTINCT','DO', 'DETERMINISTIC', 'DISABLE', 'DISCARD', 'DISTINCTROW', 'DISTINCT', 'DO',
'DROP','DUMPFILE','DUPLICATE KEY','ENABLE','ENCLOSED BY','ENGINE', 'DROP', 'DUMPFILE', 'DUPLICATE KEY', 'ENABLE', 'ENCLOSED BY', 'ENGINE',
'ERRORS','ESCAPED BY','EXISTS','EXPLAIN','EXTENDED','FIELDS', 'ERRORS', 'ESCAPED BY', 'EXISTS', 'EXPLAIN', 'EXTENDED', 'FIELDS',
'FIRST','FOR EACH ROW','FORCE','FOREIGN KEY','FROM','FULL', 'FIRST', 'FOR EACH ROW', 'FORCE', 'FOREIGN KEY', 'FROM', 'FULL',
'FUNCTION','GLOBAL','GRANT','GROUP BY','HANDLER','HASH','HAVING', 'FUNCTION', 'GLOBAL', 'GRANT', 'GROUP BY', 'HANDLER', 'HASH', 'HAVING',
'HELP','HIGH_PRIORITY','IF NOT EXISTS','IGNORE','IMPORT','INDEX', 'HELP', 'HIGH_PRIORITY', 'IF NOT EXISTS', 'IGNORE', 'IMPORT', 'INDEX',
'INFILE','INNER','INNODB','INOUT','INTO','INVOKER', 'INFILE', 'INNER', 'INNODB', 'INOUT', 'INTO', 'INVOKER',
'ISOLATION LEVEL','JOIN','KEYS','KEY','KILL','LANGUAGE SQL','LAST', 'ISOLATION LEVEL', 'JOIN', 'KEYS', 'KEY', 'KILL', 'LANGUAGE SQL', 'LAST',
'LIMIT','LINES','LOAD','LOCAL','LOCK','LOW_PRIORITY', 'LIMIT', 'LINES', 'LOAD', 'LOCAL', 'LOCK', 'LOW_PRIORITY',
'MASTER_SERVER_ID','MATCH','MERGE','MIDDLEINT','MODIFIES SQL DATA', 'MASTER_SERVER_ID', 'MATCH', 'MERGE', 'MIDDLEINT', 'MODIFIES SQL DATA',
'MODIFY','MRG_MYISAM','NATURAL','NEXT','NO SQL','NO','ON', 'MODIFY', 'MRG_MYISAM', 'NATURAL', 'NEXT', 'NO SQL', 'NO', 'ON',
'OPTIMIZE','OPTIONALLY','OPTION','ORDER BY','OUTER','OUTFILE','OUT', 'OPTIMIZE', 'OPTIONALLY', 'OPTION', 'ORDER BY', 'OUTER', 'OUTFILE', 'OUT',
'PARTIAL','PARTITION','PREV','PRIMARY KEY','PRIVILEGES','PROCEDURE', 'PARTIAL', 'PARTITION', 'PREV', 'PRIMARY KEY', 'PRIVILEGES', 'PROCEDURE',
'PURGE','QUICK','READS SQL DATA','READ','REFERENCES','RELEASE', 'PURGE', 'QUICK', 'READS SQL DATA', 'READ', 'REFERENCES', 'RELEASE',
'RENAME','REORGANIZE','REPEATABLE','REQUIRE','RESTRICT','RETURNS', 'RENAME', 'REORGANIZE', 'REPEATABLE', 'REQUIRE', 'RESTRICT', 'RETURNS',
'REVOKE','ROLLBACK','ROUTINE','RTREE','SAVEPOINT','SELECT', 'REVOKE', 'ROLLBACK', 'ROUTINE', 'RTREE', 'SAVEPOINT', 'SELECT',
'SERIALIZABLE','SESSION','SET','SHARE MODE','SHOW','SIMPLE', 'SERIALIZABLE', 'SESSION', 'SET', 'SHARE MODE', 'SHOW', 'SIMPLE',
'SNAPSHOT','SOME','SONAME','SQL SECURITY','SQL_BIG_RESULT', 'SNAPSHOT', 'SOME', 'SONAME', 'SQL SECURITY', 'SQL_BIG_RESULT',
'SQL_BUFFER_RESULT','SQL_CACHE','SQL_CALC_FOUND_ROWS', 'SQL_BUFFER_RESULT', 'SQL_CACHE', 'SQL_CALC_FOUND_ROWS',
'SQL_NO_CACHE','SQL_SMALL_RESULT','SSL','START','STARTING BY', 'SQL_NO_CACHE', 'SQL_SMALL_RESULT', 'SSL', 'START', 'STARTING BY',
'STATUS','STRAIGHT_JOIN','STRIPED','TABLESPACE','TABLES','TABLE', 'STATUS', 'STRAIGHT_JOIN', 'STRIPED', 'TABLESPACE', 'TABLES', 'TABLE',
'TEMPORARY','TEMPTABLE','TERMINATED BY','TO','TRANSACTIONS', 'TEMPORARY', 'TEMPTABLE', 'TERMINATED BY', 'TO', 'TRANSACTIONS',
'TRANSACTION','TRIGGER','TYPES','TYPE','UNCOMMITTED','UNDEFINED', 'TRANSACTION', 'TRIGGER', 'TYPES', 'TYPE', 'UNCOMMITTED', 'UNDEFINED',
'UNION','UNLOCK_TABLES','UPDATE','USAGE','USE','USER_RESOURCES', 'UNION', 'UNLOCK_TABLES', 'UPDATE', 'USAGE', 'USE', 'USER_RESOURCES',
'USING','VALUES','VALUE','VIEW','WARNINGS','WHERE','WITH ROLLUP', 'USING', 'VALUES', 'VALUE', 'VIEW', 'WARNINGS', 'WHERE', 'WITH ROLLUP',
'WITH','WORK','WRITE', 'WITH', 'WORK', 'WRITE',
), ),
2 => array( //No ( must follow 2 => array( //No ( must follow
// Mix: statement keywords distinguished from functions by the same name // Mix: statement keywords distinguished from functions by the same name
"CURRENT_USER", "DATABASE", "IN", "INSERT", "DEFAULT", "REPLACE", "SCHEMA", "TRUNCATE" "CURRENT_USER", "DATABASE", "IN", "INSERT", "DEFAULT", "REPLACE", "SCHEMA", "TRUNCATE"
), ),
3 => array( 3 => array(
// Values (Constants) // Values (Constants)
'FALSE','NULL','TRUE', 'FALSE', 'NULL', 'TRUE',
), ),
4 => array( 4 => array(
// Column Data Types // Column Data Types
'BIGINT','BIT','BLOB','BOOLEAN','BOOL','CHARACTER VARYING', 'BIGINT', 'BIT', 'BLOB', 'BOOLEAN', 'BOOL', 'CHARACTER VARYING',
'CHAR VARYING','DATETIME','DECIMAL','DEC','DOUBLE PRECISION', 'CHAR VARYING', 'DATETIME', 'DECIMAL', 'DEC', 'DOUBLE PRECISION',
'DOUBLE','ENUM','FIXED','FLOAT','GEOMETRYCOLLECTION','GEOMETRY', 'DOUBLE', 'ENUM', 'FIXED', 'FLOAT', 'GEOMETRYCOLLECTION', 'GEOMETRY',
'INTEGER','INT','LINESTRING','LONGBLOB','LONGTEXT','MEDIUMBLOB', 'INTEGER', 'INT', 'LINESTRING', 'LONGBLOB', 'LONGTEXT', 'MEDIUMBLOB',
'MEDIUMINT','MEDIUMTEXT','MULTIPOINT','MULTILINESTRING', 'MEDIUMINT', 'MEDIUMTEXT', 'MULTIPOINT', 'MULTILINESTRING',
'MULTIPOLYGON','NATIONAL CHARACTER','NATIONAL CHARACTER VARYING', 'MULTIPOLYGON', 'NATIONAL CHARACTER', 'NATIONAL CHARACTER VARYING',
'NATIONAL CHAR VARYING','NATIONAL VARCHAR','NCHAR VARCHAR','NCHAR', 'NATIONAL CHAR VARYING', 'NATIONAL VARCHAR', 'NCHAR VARCHAR', 'NCHAR',
'NUMERIC','POINT','POLYGON','REAL','SERIAL', 'NUMERIC', 'POINT', 'POLYGON', 'REAL', 'SERIAL',
'SMALLINT','TEXT','TIMESTAMP','TINYBLOB','TINYINT', 'SMALLINT', 'TEXT', 'TIMESTAMP', 'TINYBLOB', 'TINYINT',
'TINYTEXT','VARBINARY','VARCHARACTER','VARCHAR', 'TINYTEXT', 'VARBINARY', 'VARCHARACTER', 'VARCHAR',
), ),
5 => array( //No ( must follow 5 => array( //No ( must follow
// Column data types distinguished from functions by the same name // Column data types distinguished from functions by the same name
"CHAR", "DATE", "TIME" "CHAR", "DATE", "TIME"
), ),
6 => array( 6 => array(
// Table, Column & Index Attributes // Table, Column & Index Attributes
'AUTO_INCREMENT','AVG_ROW_LENGTH','BOTH','CHECKSUM','CONNECTION', 'AUTO_INCREMENT', 'AVG_ROW_LENGTH', 'BOTH', 'CHECKSUM', 'CONNECTION',
'DATA DIRECTORY','DEFAULT NULL','DELAY_KEY_WRITE','FULLTEXT', 'DATA DIRECTORY', 'DEFAULT NULL', 'DELAY_KEY_WRITE', 'FULLTEXT',
'INDEX DIRECTORY','INSERT_METHOD','LEADING','MAX_ROWS','MIN_ROWS', 'INDEX DIRECTORY', 'INSERT_METHOD', 'LEADING', 'MAX_ROWS', 'MIN_ROWS',
'NOT NULL','PACK_KEYS','ROW_FORMAT','SERIAL DEFAULT VALUE','SIGNED', 'NOT NULL', 'PACK_KEYS', 'ROW_FORMAT', 'SERIAL DEFAULT VALUE', 'SIGNED',
'SPATIAL','TRAILING','UNIQUE','UNSIGNED','ZEROFILL' 'SPATIAL', 'TRAILING', 'UNIQUE', 'UNSIGNED', 'ZEROFILL'
), ),
7 => array( //No ( must follow 7 => array( //No ( must follow
// Column attribute distinguished from function by the same name // Column attribute distinguished from function by the same name
"CHARSET" "CHARSET"
), ),
8 => array( 8 => array(
// Date and Time Unit Specifiers // Date and Time Unit Specifiers
'DAY_HOUR','DAY_MICROSECOND','DAY_MINUTE','DAY_SECOND', 'DAY_HOUR', 'DAY_MICROSECOND', 'DAY_MINUTE', 'DAY_SECOND',
'HOUR_MICROSECOND','HOUR_MINUTE','HOUR_SECOND', 'HOUR_MICROSECOND', 'HOUR_MINUTE', 'HOUR_SECOND',
'MINUTE_MICROSECOND','MINUTE_SECOND', 'MINUTE_MICROSECOND', 'MINUTE_SECOND',
'SECOND_MICROSECOND','YEAR_MONTH' 'SECOND_MICROSECOND', 'YEAR_MONTH'
), ),
9 => array( //No ( must follow 9 => array( //No ( must follow
// Date-time unit specifiers distinguished from functions by the same name // Date-time unit specifiers distinguished from functions by the same name
"DAY", "HOUR", "MICROSECOND", "MINUTE", "MONTH", "QUARTER", "SECOND", "WEEK", "YEAR" "DAY", "HOUR", "MICROSECOND", "MINUTE", "MONTH", "QUARTER", "SECOND", "WEEK", "YEAR"
), ),
10 => array( 10 => array(
// Operators (see also Symbols) // Operators (see also Symbols)
'AND','BETWEEN','CHARACTER SET','COLLATE','DIV','IS NOT NULL', 'AND', 'BETWEEN', 'CHARACTER SET', 'COLLATE', 'DIV', 'IS NOT NULL',
'IS NOT','IS NULL','IS','LIKE','NOT','OFFSET','OR','REGEXP','RLIKE', 'IS NOT', 'IS NULL', 'IS', 'LIKE', 'NOT', 'OFFSET', 'OR', 'REGEXP', 'RLIKE',
'SOUNDS LIKE','XOR' 'SOUNDS LIKE', 'XOR'
), ),
11 => array( //No ( must follow 11 => array( //No ( must follow
// Operator distinghuished from function by the same name // Operator distinghuished from function by the same name
"INTERVAL" "INTERVAL"
), ),
12 => array( 12 => array(
// Control Flow (functions) // Control Flow (functions)
'CASE','ELSE','END','IFNULL','IF','NULLIF','THEN','WHEN', 'CASE', 'ELSE', 'END', 'IFNULL', 'IF', 'NULLIF', 'THEN', 'WHEN',
), ),
13 => array( 13 => array(
// String Functions // String Functions
'ASCII','BIN','BIT_LENGTH','CHAR_LENGTH','CHARACTER_LENGTH', 'ASCII', 'BIN', 'BIT_LENGTH', 'CHAR_LENGTH', 'CHARACTER_LENGTH',
'CONCAT_WS','CONCAT','ELT','EXPORT_SET','FIELD', 'CONCAT_WS', 'CONCAT', 'ELT', 'EXPORT_SET', 'FIELD',
'FIND_IN_SET','FORMAT','HEX','INSTR','LCASE','LEFT','LENGTH', 'FIND_IN_SET', 'FORMAT', 'HEX', 'INSTR', 'LCASE', 'LEFT', 'LENGTH',
'LOAD_FILE','LOCATE','LOWER','LPAD','LTRIM','MAKE_SET','MID', 'LOAD_FILE', 'LOCATE', 'LOWER', 'LPAD', 'LTRIM', 'MAKE_SET', 'MID',
'OCTET_LENGTH','ORD','POSITION','QUOTE','REPEAT','REVERSE', 'OCTET_LENGTH', 'ORD', 'POSITION', 'QUOTE', 'REPEAT', 'REVERSE',
'RIGHT','RPAD','RTRIM','SOUNDEX','SPACE','STRCMP','SUBSTRING_INDEX', 'RIGHT', 'RPAD', 'RTRIM', 'SOUNDEX', 'SPACE', 'STRCMP', 'SUBSTRING_INDEX',
'SUBSTRING','TRIM','UCASE','UNHEX','UPPER', 'SUBSTRING', 'TRIM', 'UCASE', 'UNHEX', 'UPPER',
), ),
14 => array( //A ( must follow 14 => array( //A ( must follow
// String functions distinguished from other keywords by the same name // String functions distinguished from other keywords by the same name
"INSERT", "REPLACE", "CHAR" "INSERT", "REPLACE", "CHAR"
), ),
15 => array( 15 => array(
// Numeric Functions // Numeric Functions
'ABS','ACOS','ASIN','ATAN2','ATAN','CEILING','CEIL', 'ABS', 'ACOS', 'ASIN', 'ATAN2', 'ATAN', 'CEILING', 'CEIL',
'CONV','COS','COT','CRC32','DEGREES','EXP','FLOOR','LN','LOG10', 'CONV', 'COS', 'COT', 'CRC32', 'DEGREES', 'EXP', 'FLOOR', 'LN', 'LOG10',
'LOG2','LOG','MOD','OCT','PI','POWER','POW','RADIANS','RAND', 'LOG2', 'LOG', 'MOD', 'OCT', 'PI', 'POWER', 'POW', 'RADIANS', 'RAND',
'ROUND','SIGN','SIN','SQRT','TAN', 'ROUND', 'SIGN', 'SIN', 'SQRT', 'TAN',
), ),
16 => array( //A ( must follow 16 => array( //A ( must follow
// Numeric function distinguished from other keyword by the same name // Numeric function distinguished from other keyword by the same name
"TRUNCATE" "TRUNCATE"
), ),
17 => array( 17 => array(
// Date and Time Functions // Date and Time Functions
'ADDDATE','ADDTIME','CONVERT_TZ','CURDATE','CURRENT_DATE', 'ADDDATE', 'ADDTIME', 'CONVERT_TZ', 'CURDATE', 'CURRENT_DATE',
'CURRENT_TIME','CURRENT_TIMESTAMP','CURTIME','DATE_ADD', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURTIME', 'DATE_ADD',
'DATE_FORMAT','DATE_SUB','DATEDIFF','DAYNAME','DAYOFMONTH', 'DATE_FORMAT', 'DATE_SUB', 'DATEDIFF', 'DAYNAME', 'DAYOFMONTH',
'DAYOFWEEK','DAYOFYEAR','EXTRACT','FROM_DAYS','FROM_UNIXTIME', 'DAYOFWEEK', 'DAYOFYEAR', 'EXTRACT', 'FROM_DAYS', 'FROM_UNIXTIME',
'GET_FORMAT','LAST_DAY','LOCALTIME','LOCALTIMESTAMP','MAKEDATE', 'GET_FORMAT', 'LAST_DAY', 'LOCALTIME', 'LOCALTIMESTAMP', 'MAKEDATE',
'MAKETIME','MONTHNAME','NOW','PERIOD_ADD', 'MAKETIME', 'MONTHNAME', 'NOW', 'PERIOD_ADD',
'PERIOD_DIFF','SEC_TO_TIME','STR_TO_DATE','SUBDATE','SUBTIME', 'PERIOD_DIFF', 'SEC_TO_TIME', 'STR_TO_DATE', 'SUBDATE', 'SUBTIME',
'SYSDATE','TIME_FORMAT','TIME_TO_SEC', 'SYSDATE', 'TIME_FORMAT', 'TIME_TO_SEC',
'TIMESTAMPADD','TIMESTAMPDIFF','TO_DAYS', 'TIMESTAMPADD', 'TIMESTAMPDIFF', 'TO_DAYS',
'UNIX_TIMESTAMP','UTC_DATE','UTC_TIME','UTC_TIMESTAMP','WEEKDAY', 'UNIX_TIMESTAMP', 'UTC_DATE', 'UTC_TIME', 'UTC_TIMESTAMP', 'WEEKDAY',
'WEEKOFYEAR','YEARWEEK', 'WEEKOFYEAR', 'YEARWEEK',
), ),
18 => array( //A ( must follow 18 => array( //A ( must follow
// Date-time functions distinguished from other keywords by the same name // Date-time functions distinguished from other keywords by the same name
"DATE", "DAY", "HOUR", "MICROSECOND", "MINUTE", "MONTH", "QUARTER", "DATE", "DAY", "HOUR", "MICROSECOND", "MINUTE", "MONTH", "QUARTER",
"SECOND", "TIME", "WEEK", "YEAR" "SECOND", "TIME", "WEEK", "YEAR"
), ),
19 => array( 19 => array(
// Comparison Functions // Comparison Functions
'COALESCE','GREATEST','ISNULL','LEAST', 'COALESCE', 'GREATEST', 'ISNULL', 'LEAST',
), ),
20 => array( //A ( must follow 20 => array( //A ( must follow
// Comparison functions distinguished from other keywords by the same name // Comparison functions distinguished from other keywords by the same name
"IN", "INTERVAL" "IN", "INTERVAL"
), ),
21 => array( 21 => array(
// Encryption and Compression Functions // Encryption and Compression Functions
'AES_DECRYPT','AES_ENCRYPT','COMPRESS','DECODE','DES_DECRYPT', 'AES_DECRYPT', 'AES_ENCRYPT', 'COMPRESS', 'DECODE', 'DES_DECRYPT',
'DES_ENCRYPT','ENCODE','ENCRYPT','MD5','OLD_PASSWORD','PASSWORD', 'DES_ENCRYPT', 'ENCODE', 'ENCRYPT', 'MD5', 'OLD_PASSWORD', 'PASSWORD',
'SHA1','SHA','UNCOMPRESS','UNCOMPRESSED_LENGTH', 'SHA1', 'SHA', 'UNCOMPRESS', 'UNCOMPRESSED_LENGTH',
), ),
22 => array( 22 => array(
// GROUP BY (aggregate) Functions // GROUP BY (aggregate) Functions
'AVG','BIT_AND','BIT_OR','BIT_XOR','COUNT','GROUP_CONCAT', 'AVG', 'BIT_AND', 'BIT_OR', 'BIT_XOR', 'COUNT', 'GROUP_CONCAT',
'MAX','MIN','STDDEV_POP','STDDEV_SAMP','STDDEV','STD','SUM', 'MAX', 'MIN', 'STDDEV_POP', 'STDDEV_SAMP', 'STDDEV', 'STD', 'SUM',
'VAR_POP','VAR_SAMP','VARIANCE', 'VAR_POP', 'VAR_SAMP', 'VARIANCE',
), ),
23 => array( 23 => array(
// Information Functions // Information Functions
'BENCHMARK','COERCIBILITY','COLLATION','CONNECTION_ID', 'BENCHMARK', 'COERCIBILITY', 'COLLATION', 'CONNECTION_ID',
'FOUND_ROWS','LAST_INSERT_ID','ROW_COUNT', 'FOUND_ROWS', 'LAST_INSERT_ID', 'ROW_COUNT',
'SESSION_USER','SYSTEM_USER','USER','VERSION', 'SESSION_USER', 'SYSTEM_USER', 'USER', 'VERSION',
), ),
24 => array( //A ( must follow 24 => array( //A ( must follow
// Information functions distinguished from other keywords by the same name // Information functions distinguished from other keywords by the same name
"CURRENT_USER", "DATABASE", "SCHEMA", "CHARSET" "CURRENT_USER", "DATABASE", "SCHEMA", "CHARSET"
), ),
25 => array( 25 => array(
// Miscellaneous Functions // Miscellaneous Functions
'ExtractValue','BIT_COUNT','GET_LOCK','INET_ATON','INET_NTOA', 'ExtractValue', 'BIT_COUNT', 'GET_LOCK', 'INET_ATON', 'INET_NTOA',
'IS_FREE_LOCK','IS_USED_LOCK','MASTER_POS_WAIT','NAME_CONST', 'IS_FREE_LOCK', 'IS_USED_LOCK', 'MASTER_POS_WAIT', 'NAME_CONST',
'RELEASE_LOCK','SLEEP','UpdateXML','UUID', 'RELEASE_LOCK', 'SLEEP', 'UpdateXML', 'UUID',
), ),
26 => array( //A ( must follow 26 => array( //A ( must follow
// Miscellaneous function distinguished from other keyword by the same name // Miscellaneous function distinguished from other keyword by the same name
"DEFAULT" "DEFAULT"
), ),
27 => array( 27 => array(
// Geometry Functions // Geometry Functions
'Area','AsBinary','AsText','AsWKB','AsWKT','Boundary','Buffer', 'Area', 'AsBinary', 'AsText', 'AsWKB', 'AsWKT', 'Boundary', 'Buffer',
'Centroid','Contains','ConvexHull','Crosses', 'Centroid', 'Contains', 'ConvexHull', 'Crosses',
'Difference','Dimension','Disjoint','Distance', 'Difference', 'Dimension', 'Disjoint', 'Distance',
'EndPoint','Envelope','Equals','ExteriorRing', 'EndPoint', 'Envelope', 'Equals', 'ExteriorRing',
'GLength','GeomCollFromText','GeomCollFromWKB','GeomFromText', 'GLength', 'GeomCollFromText', 'GeomCollFromWKB', 'GeomFromText',
'GeomFromWKB','GeometryCollectionFromText', 'GeomFromWKB', 'GeometryCollectionFromText',
'GeometryCollectionFromWKB','GeometryFromText','GeometryFromWKB', 'GeometryCollectionFromWKB', 'GeometryFromText', 'GeometryFromWKB',
'GeometryN','GeometryType', 'GeometryN', 'GeometryType',
'InteriorRingN','Intersection','Intersects','IsClosed','IsEmpty', 'InteriorRingN', 'Intersection', 'Intersects', 'IsClosed', 'IsEmpty',
'IsRing','IsSimple', 'IsRing', 'IsSimple',
'LineFromText','LineFromWKB','LineStringFromText', 'LineFromText', 'LineFromWKB', 'LineStringFromText',
'LineStringFromWKB', 'LineStringFromWKB',
'MBRContains','MBRDisjoint','MBREqual','MBRIntersects', 'MBRContains', 'MBRDisjoint', 'MBREqual', 'MBRIntersects',
'MBROverlaps','MBRTouches','MBRWithin','MLineFromText', 'MBROverlaps', 'MBRTouches', 'MBRWithin', 'MLineFromText',
'MLineFromWKB','MPointFromText','MPointFromWKB','MPolyFromText', 'MLineFromWKB', 'MPointFromText', 'MPointFromWKB', 'MPolyFromText',
'MPolyFromWKB','MultiLineStringFromText','MultiLineStringFromWKB', 'MPolyFromWKB', 'MultiLineStringFromText', 'MultiLineStringFromWKB',
'MultiPointFromText','MultiPointFromWKB','MultiPolygonFromText', 'MultiPointFromText', 'MultiPointFromWKB', 'MultiPolygonFromText',
'MultiPolygonFromWKB', 'MultiPolygonFromWKB',
'NumGeometries','NumInteriorRings','NumPoints', 'NumGeometries', 'NumInteriorRings', 'NumPoints',
'Overlaps', 'Overlaps',
'PointFromText','PointFromWKB','PointN','PointOnSurface', 'PointFromText', 'PointFromWKB', 'PointN', 'PointOnSurface',
'PolyFromText','PolyFromWKB','PolygonFromText','PolygonFromWKB', 'PolyFromText', 'PolyFromWKB', 'PolygonFromText', 'PolygonFromWKB',
'Related','SRID','StartPoint','SymDifference', 'Related', 'SRID', 'StartPoint', 'SymDifference',
'Touches', 'Touches',
'Union', 'Union',
'Within', 'Within',
'X', 'X',
'Y', 'Y',
),
), ),
),
'SYMBOLS' => array( 'SYMBOLS' => array(
1 => array( 1 => array(
/* Operators */ /* Operators */
@ -291,13 +291,13 @@ $language_data = array (
'=', '<=>', '>=', '>', '<=', '<', '<>', '!=', // comparison operators '=', '<=>', '>=', '>', '<=', '<', '<>', '!=', // comparison operators
'|', '&', '^', '~', '<<', '>>', // bitwise operators '|', '&', '^', '~', '<<', '>>', // bitwise operators
'-', '+', '*', '/', '%', // numerical operators '-', '+', '*', '/', '%', // numerical operators
), ),
2 => array( 2 => array(
/* Other syntactical symbols */ /* Other syntactical symbols */
'(', ')', '(', ')',
',', ';', ',', ';',
),
), ),
),
'CASE_SENSITIVE' => array( 'CASE_SENSITIVE' => array(
GESHI_COMMENTS => false, GESHI_COMMENTS => false,
1 => false, 1 => false,
@ -327,7 +327,7 @@ $language_data = array (
25 => false, 25 => false,
26 => false, 26 => false,
27 => false, 27 => false,
), ),
'STYLES' => array( 'STYLES' => array(
'KEYWORDS' => array( 'KEYWORDS' => array(
1 => 'color: #990099; font-weight: bold;', // mix 1 => 'color: #990099; font-weight: bold;', // mix
@ -359,36 +359,33 @@ $language_data = array (
25 => 'color: #000099;', // miscellaneous functions 25 => 'color: #000099;', // miscellaneous functions
26 => 'color: #000099;', // miscellaneous functions 26 => 'color: #000099;', // miscellaneous functions
27 => 'color: #00CC00;', // geometry functions 27 => 'color: #00CC00;', // geometry functions
), ),
'COMMENTS' => array( 'COMMENTS' => array(
'MULTI' => 'color: #808000; font-style: italic;', 'MULTI' => 'color: #808000; font-style: italic;',
1 => 'color: #808080; font-style: italic;', 1 => 'color: #808080; font-style: italic;',
2 => 'color: #808080; font-style: italic;' 2 => 'color: #808080; font-style: italic;'
), ),
'ESCAPE_CHAR' => array( 'ESCAPE_CHAR' => array(
0 => 'color: #004000; font-weight: bold;', 0 => 'color: #004000; font-weight: bold;',
1 => 'color: #008080; font-weight: bold;' // search wildcards 1 => 'color: #008080; font-weight: bold;' // search wildcards
), ),
'BRACKETS' => array( 'BRACKETS' => array(
0 => 'color: #FF00FF;' 0 => 'color: #FF00FF;'
), ),
'STRINGS' => array( 'STRINGS' => array(
0 => 'color: #008000;' 0 => 'color: #008000;'
), ),
'NUMBERS' => array( 'NUMBERS' => array(
0 => 'color: #008080;' 0 => 'color: #008080;'
), ),
'METHODS' => array( 'METHODS' => array(),
),
'SYMBOLS' => array( 'SYMBOLS' => array(
1 => 'color: #CC0099;', // operators 1 => 'color: #CC0099;', // operators
2 => 'color: #000033;', // syntax 2 => 'color: #000033;', // syntax
),
'SCRIPT' => array(
),
'REGEXPS' => array(
)
), ),
'SCRIPT' => array(),
'REGEXPS' => array()
),
'URLS' => array( 'URLS' => array(
1 => 'http://search.oracle.com/search/search?group=MySQL&amp;q={FNAME}', 1 => 'http://search.oracle.com/search/search?group=MySQL&amp;q={FNAME}',
2 => 'http://search.oracle.com/search/search?group=MySQL&amp;q={FNAME}', 2 => 'http://search.oracle.com/search/search?group=MySQL&amp;q={FNAME}',
@ -419,54 +416,50 @@ $language_data = array (
25 => 'http://dev.mysql.com/doc/refman/%35%2E%31/en/func-op-summary-ref.html', 25 => 'http://dev.mysql.com/doc/refman/%35%2E%31/en/func-op-summary-ref.html',
26 => 'http://dev.mysql.com/doc/refman/%35%2E%31/en/func-op-summary-ref.html', 26 => 'http://dev.mysql.com/doc/refman/%35%2E%31/en/func-op-summary-ref.html',
27 => 'http://dev.mysql.com/doc/refman/%35%2E%31/en/analysing-spatial-information.html', 27 => 'http://dev.mysql.com/doc/refman/%35%2E%31/en/analysing-spatial-information.html',
), ),
'OOLANG' => false, 'OOLANG' => false,
'OBJECT_SPLITTERS' => array( 'OBJECT_SPLITTERS' => array(),
), 'REGEXPS' => array(),
'REGEXPS' => array(
),
'STRICT_MODE_APPLIES' => GESHI_NEVER, 'STRICT_MODE_APPLIES' => GESHI_NEVER,
'SCRIPT_DELIMITERS' => array( 'SCRIPT_DELIMITERS' => array(),
), 'HIGHLIGHT_STRICT_BLOCK' => array(),
'HIGHLIGHT_STRICT_BLOCK' => array(
),
'TAB_WIDTH' => 4, 'TAB_WIDTH' => 4,
'PARSER_CONTROL' => array( 'PARSER_CONTROL' => array(
'KEYWORDS' => array( 'KEYWORDS' => array(
2 => array( 2 => array(
'DISALLOWED_AFTER' => '(?![\(\w])' 'DISALLOWED_AFTER' => '(?![\(\w])'
), ),
5 => array( 5 => array(
'DISALLOWED_AFTER' => '(?![\(\w])' 'DISALLOWED_AFTER' => '(?![\(\w])'
), ),
7 => array( 7 => array(
'DISALLOWED_AFTER' => '(?![\(\w])' 'DISALLOWED_AFTER' => '(?![\(\w])'
), ),
9 => array( 9 => array(
'DISALLOWED_AFTER' => '(?![\(\w])' 'DISALLOWED_AFTER' => '(?![\(\w])'
), ),
11 => array( 11 => array(
'DISALLOWED_AFTER' => '(?![\(\w])' 'DISALLOWED_AFTER' => '(?![\(\w])'
), ),
14 => array( 14 => array(
'DISALLOWED_AFTER' => '(?=\()' 'DISALLOWED_AFTER' => '(?=\()'
), ),
16 => array( 16 => array(
'DISALLOWED_AFTER' => '(?=\()' 'DISALLOWED_AFTER' => '(?=\()'
), ),
18 => array( 18 => array(
'DISALLOWED_AFTER' => '(?=\()' 'DISALLOWED_AFTER' => '(?=\()'
), ),
20 => array( 20 => array(
'DISALLOWED_AFTER' => '(?=\()' 'DISALLOWED_AFTER' => '(?=\()'
), ),
24 => array( 24 => array(
'DISALLOWED_AFTER' => '(?=\()' 'DISALLOWED_AFTER' => '(?=\()'
), ),
26 => array( 26 => array(
'DISALLOWED_AFTER' => '(?=\()' 'DISALLOWED_AFTER' => '(?=\()'
)
) )
) )
)
); );

View file

@ -15,9 +15,9 @@ require_once 'wp-syntax/geshi/geshi.php';
class MarkdownGeshi_Parser extends MarkdownExtra_Parser { class MarkdownGeshi_Parser extends MarkdownExtra_Parser {
/** /**
* The 'processing instruction' pattern for the code blocks parser. * The 'processing instruction' pattern for the code blocks parser.
* Format is defined as : #!language@linenumber. The @linenumber * Format is defined as : #!language@linenumber. The @linenumber
* part is optional. * part is optional.
* *
* Optional parameters are allowed past a semicolon. * Optional parameters are allowed past a semicolon.
*/ */
public $shebang = '/^ public $shebang = '/^
@ -28,77 +28,76 @@ class MarkdownGeshi_Parser extends MarkdownExtra_Parser {
(?:;\s*(?P<params>.*?)\s*)?\n (?:;\s*(?P<params>.*?)\s*)?\n
(?P<code>.*) (?P<code>.*)
/sx'; /sx';
function hasShebang($code) { function hasShebang($code) {
if(preg_match($this->shebang, $code, $m)) { if (preg_match($this->shebang, $code, $m)) {
return $m; return $m;
} }
return false; return false;
} }
function _doCodeBlocks_callback($matches) { function _doCodeBlocks_callback($matches) {
if($m = $this->hasShebang($matches[1])) { if ($m = $this->hasShebang($matches[1])) {
return $this->_doGeshi($m); return $this->_doGeshi($m);
} else { } else {
return parent::_doCodeBlocks_callback($matches); return parent::_doCodeBlocks_callback($matches);
} }
} }
function _doFencedCodeBlocks_callback($matches) { function _doFencedCodeBlocks_callback($matches) {
if($m = $this->hasShebang($matches[2])) { if ($m = $this->hasShebang($matches[2])) {
return $this->_doGeshi($m); return $this->_doGeshi($m);
} else { } else {
return parent::_doFencedCodeBlocks_callback($matches); return parent::_doFencedCodeBlocks_callback($matches);
} }
} }
function _doGeshi($shebangMatch) { function _doGeshi($shebangMatch) {
$language = $shebangMatch['lang']; $language = $shebangMatch['lang'];
$line = (int) (($shebangMatch['linenumber'] > 1) ? $shebangMatch['linenumber'] : 0); $line = (int)(($shebangMatch['linenumber'] > 1) ? $shebangMatch['linenumber'] : 0);
$codeblock = $shebangMatch['code']; $codeblock = $shebangMatch['code'];
$highlighter = new GeSHi($this->outdent(trim($codeblock)), $language); $highlighter = new GeSHi($this->outdent(trim($codeblock)), $language);
$highlighted = $highlighter->parse_code(); $highlighted = $highlighter->parse_code();
if($line) { if ($line) {
preg_match('!^(\s*<pre[^>]+>)(.*)(</pre>)!s', $highlighted, $m); preg_match('!^(\s*<pre[^>]+>)(.*)(</pre>)!s', $highlighted, $m);
$ret = '<ol'; $ret = '<ol';
if($line) { if ($line) {
$ret .= ' start="' . $line .'"'; $ret .= ' start="' . $line . '"';
} }
$ret .= '>'; $ret .= '>';
$ret .= preg_replace( $ret .= preg_replace(
'/.+(\n|$)/', '/.+(\n|$)/',
'<li>$0</li>', '<li>$0</li>',
$m[2] $m[2]
); );
$ret .= '</ol>'; $ret .= '</ol>';
$ret = $m[1] . $ret . $m[3]; $ret = $m[1] . $ret . $m[3];
} else { } else {
$ret = $highlighted; $ret = $highlighted;
} }
if($shebangMatch['params']) { if ($shebangMatch['params']) {
$ret = $this->_processGeshiParams($ret, $shebangMatch['params']); $ret = $this->_processGeshiParams($ret, $shebangMatch['params']);
} }
return "\n\n" . $this->hashBlock($ret) . "\n\n"; return "\n\n" . $this->hashBlock($ret) . "\n\n";
} }
function _processGeshiParams($highlighted, $params) { function _processGeshiParams($highlighted, $params) {
foreach(explode(',', $params) as $keyValuePair) { foreach (explode(',', $params) as $keyValuePair) {
@list($key, $value) = array_map('trim', explode('=', $keyValuePair)); @list($key, $value) = array_map('trim', explode('=', $keyValuePair));
if($key && $value) { if ($key && $value) {
switch($key) { switch ($key) {
case 'gist': case 'gist':
$highlighted = $highlighted =
sprintf( sprintf(
'<cite class="gist">(GIST: <a href="https://gist.github.com/%1$d" target="_blank">%1$d</a>)</cite>', '<cite class="gist">(GIST: <a href="https://gist.github.com/%1$d" target="_blank">%1$d</a>)</cite>',
$value $value
) )
. $highlighted . $highlighted;
;
break; break;
} }
} }

View file

@ -42,29 +42,29 @@ $language_data = array(
'COMMENT_SINGLE' => array( 'COMMENT_SINGLE' => array(
1 => '>', 1 => '>',
2 => '<', 2 => '<',
3 => '**', 3 => '**',
4 => '###', 4 => '###',
5 => '##', 5 => '##',
6 => '@', 6 => '@',
7 => '++', 7 => '++',
), ),
'COMMENT_MULTI' => array( 'COMMENT_MULTI' => array(
'_' => '_' '_' => '_'
), ),
'COMMENT_REGEXP' => array( 'COMMENT_REGEXP' => array(
1 => '' 1 => ''
), ),
'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE, 'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE,
'QUOTEMARKS' => array( 'QUOTEMARKS' => array(
1 => '', 1 => '',
2 => '' 2 => ''
), ),
'ESCAPE_CHAR' => '', 'ESCAPE_CHAR' => '',
'ESCAPE_REGEXP' => array( 'ESCAPE_REGEXP' => array(
1 => '', 1 => '',
2 => '' 2 => ''
), ),
'HARDQUOTE' => array(), 'HARDQUOTE' => array(),
'HARDESCAPE' => array(), 'HARDESCAPE' => array(),
'HARDCHAR' => '', 'HARDCHAR' => '',
@ -74,50 +74,50 @@ $language_data = array(
'KEYWORDS' => array( 'KEYWORDS' => array(
1 => array( 1 => array(
'' ''
) )
), ),
'CASE_SENSITIVE' => array( 'CASE_SENSITIVE' => array(
1 => false 1 => false
), ),
'SYMBOLS' => array( 'SYMBOLS' => array(
0 => array( 0 => array(
'>' '>'
) )
), ),
'STYLES' => array( 'STYLES' => array(
'KEYWORDS' => array( 'KEYWORDS' => array(
1 => '' 1 => ''
), ),
'COMMENTS' => array( 'COMMENTS' => array(
1 => 'font-style: normal; color: #789922;', 1 => 'font-style: normal; color: #789922;',
2 => 'font-weight: normal; color: #991111;', 2 => 'font-weight: normal; color: #991111;',
3 => 'font-weight: bold; color: #000;', 3 => 'font-weight: bold; color: #000;',
4 => 'font-size: 25px; font-weight: bold; color: #000;', 4 => 'font-size: 25px; font-weight: bold; color: #000;',
5 => 'font-size: 35px; font-weight: bold; color: #000;', 5 => 'font-size: 35px; font-weight: bold; color: #000;',
6 => 'color: #440088;', 6 => 'color: #440088;',
7 => 'border: 3px dotted #000;', 7 => 'border: 3px dotted #000;',
'MULTI' => 'text-decoration: underline;color: #000;' 'MULTI' => 'text-decoration: underline;color: #000;'
), ),
'ESCAPE_CHAR' => array( 'ESCAPE_CHAR' => array(
1 => '', 1 => '',
2 => '' 2 => ''
), ),
'BRACKETS' => array(), 'BRACKETS' => array(),
'STRINGS' => array( 'STRINGS' => array(
1 => '', 1 => '',
2 => '' 2 => ''
), ),
'NUMBERS' => array(), 'NUMBERS' => array(),
'METHODS' => array(), 'METHODS' => array(),
'SYMBOLS' => array( 'SYMBOLS' => array(
0 => 'font-style: italic; color: #789922;' 0 => 'font-style: italic; color: #789922;'
), ),
'REGEXPS' => array(), 'REGEXPS' => array(),
'SCRIPT' => array() 'SCRIPT' => array()
), ),
'URLS' => array( 'URLS' => array(
1 => '' 1 => ''
), ),
'OOLANG' => false, 'OOLANG' => false,
'OBJECT_SPLITTERS' => array(), 'OBJECT_SPLITTERS' => array(),
'REGEXPS' => array(), 'REGEXPS' => array(),

File diff suppressed because it is too large Load diff

View file

@ -43,7 +43,7 @@
* *
************************************************************************************/ ************************************************************************************/
$language_data = array ( $language_data = array(
'LANG_NAME' => 'Text', 'LANG_NAME' => 'Text',
'COMMENT_SINGLE' => array(), 'COMMENT_SINGLE' => array(),
'COMMENT_MULTI' => array(), 'COMMENT_MULTI' => array(),
@ -54,7 +54,7 @@ $language_data = array (
'SYMBOLS' => array(), 'SYMBOLS' => array(),
'CASE_SENSITIVE' => array( 'CASE_SENSITIVE' => array(
GESHI_COMMENTS => false GESHI_COMMENTS => false
), ),
'STYLES' => array( 'STYLES' => array(
'KEYWORDS' => array(), 'KEYWORDS' => array(),
'COMMENTS' => array(), 'COMMENTS' => array(),
@ -66,7 +66,7 @@ $language_data = array (
'SYMBOLS' => array(), 'SYMBOLS' => array(),
'SCRIPT' => array(), 'SCRIPT' => array(),
'REGEXPS' => array() 'REGEXPS' => array()
), ),
'URLS' => array(), 'URLS' => array(),
'OOLANG' => false, 'OOLANG' => false,
'OBJECT_SPLITTERS' => array(), 'OBJECT_SPLITTERS' => array(),
@ -77,6 +77,6 @@ $language_data = array (
'PARSER_CONTROL' => array( 'PARSER_CONTROL' => array(
'ENABLE_FLAGS' => array( 'ENABLE_FLAGS' => array(
'ALL' => GESHI_NEVER 'ALL' => GESHI_NEVER
)
) )
)
); );

View file

@ -43,7 +43,7 @@
* *
************************************************************************************/ ************************************************************************************/
$language_data = array ( $language_data = array(
'LANG_NAME' => 'Python', 'LANG_NAME' => 'Python',
'COMMENT_SINGLE' => array(1 => '#'), 'COMMENT_SINGLE' => array(1 => '#'),
'COMMENT_MULTI' => array(), 'COMMENT_MULTI' => array(),
@ -66,7 +66,7 @@ $language_data = array (
'and', 'del', 'for', 'is', 'raise', 'assert', 'elif', 'from', 'lambda', 'return', 'break', 'and', 'del', 'for', 'is', 'raise', 'assert', 'elif', 'from', 'lambda', 'return', 'break',
'else', 'global', 'not', 'try', 'class', 'except', 'if', 'or', 'while', 'continue', 'exec', 'else', 'global', 'not', 'try', 'class', 'except', 'if', 'or', 'while', 'continue', 'exec',
'import', 'pass', 'yield', 'def', 'finally', 'in', 'print', 'with', 'as', 'nonlocal' 'import', 'pass', 'yield', 'def', 'finally', 'in', 'print', 'with', 'as', 'nonlocal'
), ),
/* /*
** Set 2: builtins ** Set 2: builtins
@ -97,7 +97,7 @@ $language_data = array (
'self', 'self',
// other // other
'any', 'all' 'any', 'all'
), ),
/* /*
** Set 3: standard library ** Set 3: standard library
@ -136,7 +136,7 @@ $language_data = array (
'xmllib', 'xmlrpclib', 'zipfile', 'zipimport', 'zlib', 'xmllib', 'xmlrpclib', 'zipfile', 'zipimport', 'zlib',
// Python 3.0 // Python 3.0
'bytes', 'bytearray' 'bytes', 'bytearray'
), ),
/* /*
** Set 4: special methods ** Set 4: special methods
@ -166,77 +166,72 @@ $language_data = array (
'__len__', '__getitem__', '__setitem__', '__delitem__', '__iter__', '__contains__', '__len__', '__getitem__', '__setitem__', '__delitem__', '__iter__', '__contains__',
'__getslice__', '__setslice__', '__delslice__', '__getslice__', '__setslice__', '__delslice__',
// Numeric types: http://python.org/doc/current/ref/numeric-types.html // Numeric types: http://python.org/doc/current/ref/numeric-types.html
'__abs__','__add__','__and__','__coerce__','__div__','__divmod__','__float__', '__abs__', '__add__', '__and__', '__coerce__', '__div__', '__divmod__', '__float__',
'__hex__','__iadd__','__isub__','__imod__','__idiv__','__ipow__','__iand__', '__hex__', '__iadd__', '__isub__', '__imod__', '__idiv__', '__ipow__', '__iand__',
'__ior__','__ixor__', '__ilshift__','__irshift__','__invert__','__int__', '__ior__', '__ixor__', '__ilshift__', '__irshift__', '__invert__', '__int__',
'__long__','__lshift__', '__long__', '__lshift__',
'__mod__','__mul__','__neg__','__oct__','__or__','__pos__','__pow__', '__mod__', '__mul__', '__neg__', '__oct__', '__or__', '__pos__', '__pow__',
'__radd__','__rdiv__','__rdivmod__','__rmod__','__rpow__','__rlshift__','__rrshift__', '__radd__', '__rdiv__', '__rdivmod__', '__rmod__', '__rpow__', '__rlshift__', '__rrshift__',
'__rshift__','__rsub__','__rmul__','__rand__','__rxor__','__ror__', '__rshift__', '__rsub__', '__rmul__', '__rand__', '__rxor__', '__ror__',
'__sub__','__xor__' '__sub__', '__xor__'
) )
), ),
'SYMBOLS' => array( 'SYMBOLS' => array(
'<', '>', '=', '!', '<=', '>=', //·comparison·operators '<', '>', '=', '!', '<=', '>=', //·comparison·operators
'~', '@', //·unary·operators '~', '@', //·unary·operators
';', ',' //·statement·separator ';', ',' //·statement·separator
), ),
'CASE_SENSITIVE' => array( 'CASE_SENSITIVE' => array(
GESHI_COMMENTS => false, GESHI_COMMENTS => false,
1 => true, 1 => true,
2 => true, 2 => true,
3 => true, 3 => true,
4 => true 4 => true
), ),
'STYLES' => array( 'STYLES' => array(
'KEYWORDS' => array( 'KEYWORDS' => array(
1 => 'color: #ff7700;font-weight:bold;', // Reserved 1 => 'color: #ff7700;font-weight:bold;', // Reserved
2 => 'color: #008000;', // Built-ins + self 2 => 'color: #008000;', // Built-ins + self
3 => 'color: #dc143c;', // Standard lib 3 => 'color: #dc143c;', // Standard lib
4 => 'color: #0000cd;' // Special methods 4 => 'color: #0000cd;' // Special methods
), ),
'COMMENTS' => array( 'COMMENTS' => array(
1 => 'color: #808080; font-style: italic;', 1 => 'color: #808080; font-style: italic;',
'MULTI' => 'color: #808080; font-style: italic;' 'MULTI' => 'color: #808080; font-style: italic;'
), ),
'ESCAPE_CHAR' => array( 'ESCAPE_CHAR' => array(
0 => 'color: #000099; font-weight: bold;' 0 => 'color: #000099; font-weight: bold;'
), ),
'BRACKETS' => array( 'BRACKETS' => array(
0 => 'color: black;' 0 => 'color: black;'
), ),
'STRINGS' => array( 'STRINGS' => array(
0 => 'color: #483d8b;' 0 => 'color: #483d8b;'
), ),
'NUMBERS' => array( 'NUMBERS' => array(
0 => 'color: #ff4500;' 0 => 'color: #ff4500;'
), ),
'METHODS' => array( 'METHODS' => array(
1 => 'color: black;' 1 => 'color: black;'
), ),
'SYMBOLS' => array( 'SYMBOLS' => array(
0 => 'color: #66cc66;' 0 => 'color: #66cc66;'
),
'REGEXPS' => array(
),
'SCRIPT' => array(
)
), ),
'REGEXPS' => array(),
'SCRIPT' => array()
),
'URLS' => array( 'URLS' => array(
1 => '', 1 => '',
2 => '', 2 => '',
3 => '', 3 => '',
4 => '' 4 => ''
), ),
'OOLANG' => true, 'OOLANG' => true,
'OBJECT_SPLITTERS' => array( 'OBJECT_SPLITTERS' => array(
1 => '.' 1 => '.'
), ),
'REGEXPS' => array( 'REGEXPS' => array(),
),
'STRICT_MODE_APPLIES' => GESHI_NEVER, 'STRICT_MODE_APPLIES' => GESHI_NEVER,
'SCRIPT_DELIMITERS' => array( 'SCRIPT_DELIMITERS' => array(),
), 'HIGHLIGHT_STRICT_BLOCK' => array()
'HIGHLIGHT_STRICT_BLOCK' => array(
)
); );

View file

@ -43,7 +43,7 @@
* *
************************************************************************************/ ************************************************************************************/
$language_data = array ( $language_data = array(
'LANG_NAME' => 'Text', 'LANG_NAME' => 'Text',
'COMMENT_SINGLE' => array(), 'COMMENT_SINGLE' => array(),
'COMMENT_MULTI' => array(), 'COMMENT_MULTI' => array(),
@ -54,7 +54,7 @@ $language_data = array (
'SYMBOLS' => array(), 'SYMBOLS' => array(),
'CASE_SENSITIVE' => array( 'CASE_SENSITIVE' => array(
GESHI_COMMENTS => false GESHI_COMMENTS => false
), ),
'STYLES' => array( 'STYLES' => array(
'KEYWORDS' => array(), 'KEYWORDS' => array(),
'COMMENTS' => array(), 'COMMENTS' => array(),
@ -66,7 +66,7 @@ $language_data = array (
'SYMBOLS' => array(), 'SYMBOLS' => array(),
'SCRIPT' => array(), 'SCRIPT' => array(),
'REGEXPS' => array() 'REGEXPS' => array()
), ),
'URLS' => array(), 'URLS' => array(),
'OOLANG' => false, 'OOLANG' => false,
'OBJECT_SPLITTERS' => array(), 'OBJECT_SPLITTERS' => array(),
@ -77,6 +77,6 @@ $language_data = array (
'PARSER_CONTROL' => array( 'PARSER_CONTROL' => array(
'ENABLE_FLAGS' => array( 'ENABLE_FLAGS' => array(
'ALL' => GESHI_NEVER 'ALL' => GESHI_NEVER
)
) )
)
); );

View file

@ -12,7 +12,7 @@ namespace {
if (!defined('PASSWORD_BCRYPT')) { if (!defined('PASSWORD_BCRYPT')) {
/** /**
* PHPUnit Process isolation caches constants, but not function declarations. * PHPUnit Process isolation caches constants, but not function declarations.
* So we need to check if the constants are defined separately from * So we need to check if the constants are defined separately from
* the functions to enable supporting process isolation in userland * the functions to enable supporting process isolation in userland
* code. * code.
*/ */
@ -27,8 +27,8 @@ namespace {
* Hash the password using the specified algorithm * Hash the password using the specified algorithm
* *
* @param string $password The password to hash * @param string $password The password to hash
* @param int $algo The algorithm to use (Defined by PASSWORD_* constants) * @param int $algo The algorithm to use (Defined by PASSWORD_* constants)
* @param array $options The options for the algorithm to use * @param array $options The options for the algorithm to use
* *
* @return string|false The hashed password, or false on error. * @return string|false The hashed password, or false on error.
*/ */
@ -38,7 +38,7 @@ namespace {
return null; return null;
} }
if (is_null($password) || is_int($password)) { if (is_null($password) || is_int($password)) {
$password = (string) $password; $password = (string)$password;
} }
if (!is_string($password)) { if (!is_string($password)) {
trigger_error("password_hash(): Password must be a string", E_USER_WARNING); trigger_error("password_hash(): Password must be a string", E_USER_WARNING);
@ -53,7 +53,7 @@ namespace {
case PASSWORD_BCRYPT: case PASSWORD_BCRYPT:
$cost = PASSWORD_BCRYPT_DEFAULT_COST; $cost = PASSWORD_BCRYPT_DEFAULT_COST;
if (isset($options['cost'])) { if (isset($options['cost'])) {
$cost = (int) $options['cost']; $cost = (int)$options['cost'];
if ($cost < 4 || $cost > 31) { if ($cost < 4 || $cost > 31) {
trigger_error(sprintf("password_hash(): Invalid bcrypt cost parameter specified: %d", $cost), E_USER_WARNING); trigger_error(sprintf("password_hash(): Invalid bcrypt cost parameter specified: %d", $cost), E_USER_WARNING);
return null; return null;
@ -79,11 +79,11 @@ namespace {
case 'integer': case 'integer':
case 'double': case 'double':
case 'string': case 'string':
$salt = (string) $options['salt']; $salt = (string)$options['salt'];
break; break;
case 'object': case 'object':
if (method_exists($options['salt'], '__tostring')) { if (method_exists($options['salt'], '__tostring')) {
$salt = (string) $options['salt']; $salt = (string)$options['salt'];
break; break;
} }
case 'array': case 'array':
@ -169,11 +169,11 @@ namespace {
* Verify a password against a hash using a timing attack resistant approach * Verify a password against a hash using a timing attack resistant approach
* *
* @param string $password The password to verify * @param string $password The password to verify
* @param string $hash The hash to verify against * @param string $hash The hash to verify against
* *
* @return boolean If the password matches the hash * @return boolean If the password matches the hash
*/ */
function password_verify(string $password, string $hash): bool { function password_verify(string $password, string $hash) : bool {
if (!function_exists('crypt')) { if (!function_exists('crypt')) {
trigger_error("Crypt must be loaded for password_verify to function", E_USER_WARNING); trigger_error("Crypt must be loaded for password_verify to function", E_USER_WARNING);
return false; return false;
@ -207,8 +207,8 @@ namespace PasswordCompat\binary {
* *
* @param string $binary_string The input string * @param string $binary_string The input string
* *
* @internal
* @return int The number of bytes * @return int The number of bytes
* @internal
*/ */
function _strlen($binary_string) { function _strlen($binary_string) {
if (function_exists('mb_strlen')) { if (function_exists('mb_strlen')) {
@ -220,14 +220,14 @@ namespace PasswordCompat\binary {
/** /**
* Get a substring based on byte limits * Get a substring based on byte limits
* *
* @param string $binary_string The input string
* @param int $start
* @param int $length
*
* @return string The substring
* @internal
* @see _strlen() * @see _strlen()
* *
* @param string $binary_string The input string
* @param int $start
* @param int $length
*
* @internal
* @return string The substring
*/ */
function _substr($binary_string, $start, $length) { function _substr($binary_string, $start, $length) {
if (function_exists('mb_substr')) { if (function_exists('mb_substr')) {
@ -242,7 +242,7 @@ namespace PasswordCompat\binary {
* @return boolean the check result * @return boolean the check result
*/ */
function check() { function check() {
static $pass = NULL; static $pass = null;
if (is_null($pass)) { if (is_null($pass)) {
if (function_exists('crypt')) { if (function_exists('crypt')) {

View file

@ -1,4 +1,3 @@
<?php <?php
/* /*
* Paste <https://github.com/jordansamuel/PASTE> * Paste <https://github.com/jordansamuel/PASTE>
@ -28,7 +27,7 @@ require_once('includes/captcha.php');
require_once('includes/functions.php'); require_once('includes/functions.php');
require_once('includes/password.php'); require_once('includes/password.php');
function verifyCaptcha() : string | bool { function verifyCaptcha() : string|bool {
global $cap_e; global $cap_e;
global $mode; global $mode;
global $recaptcha_secretkey; global $recaptcha_secretkey;
@ -36,7 +35,7 @@ function verifyCaptcha() : string | bool {
if ($cap_e == "on" && !isset($_SESSION['username'])) { if ($cap_e == "on" && !isset($_SESSION['username'])) {
if ($mode == "reCAPTCHA") { if ($mode == "reCAPTCHA") {
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secretkey."&response=".$_POST['g-recaptcha-response']); $response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . $recaptcha_secretkey . "&response=" . $_POST['g-recaptcha-response']);
$response = json_decode($response, true); $response = json_decode($response, true);
if ($response["success"] == false) { if ($response["success"] == false) {
// reCAPTCHA Errors // reCAPTCHA Errors
@ -48,7 +47,7 @@ function verifyCaptcha() : string | bool {
}; };
} }
} else { } else {
$scode = strtolower(htmlentities(Trim($_POST['scode']))); $scode = strtolower(htmlentities(Trim($_POST['scode'])));
$cap_code = strtolower($_SESSION['captcha']['code']); $cap_code = strtolower($_SESSION['captcha']['code']);
if ($cap_code !== $scode) { if ($cap_code !== $scode) {
return $lang['image_wrong']; // Wrong captcha. return $lang['image_wrong']; // Wrong captcha.
@ -80,19 +79,19 @@ function calculatePasteExpiry(string $expiry) {
: null; : null;
} }
function validatePasteFields() : string | null { function validatePasteFields() : string|null {
global $lang; global $lang;
global $pastelimit; global $pastelimit;
if (empty($_POST["paste_data"]) || trim($_POST['paste_data'] === '')) { /* Empty paste input */ if (empty($_POST["paste_data"]) || trim($_POST['paste_data'] === '')) { /* Empty paste input */
return $lang['empty_paste']; return $lang['empty_paste'];
} elseif(!isset($_POST['title'])) { /* No paste title POSTed */ } elseif (!isset($_POST['title'])) { /* No paste title POSTed */
return $lang['error']; return $lang['error'];
} elseif (empty($_POST["tags"])) { /* No tags provided */ } elseif (empty($_POST["tags"])) { /* No tags provided */
return $lang['notags']; return $lang['notags'];
} elseif (strlen($_POST["title"]) > 70) { /* Paste title too long */ } elseif (strlen($_POST["title"]) > 70) { /* Paste title too long */
return $lang['titlelen']; return $lang['titlelen'];
} elseif (mb_strlen($_POST["paste_data"], '8bit') > 1024 * 1024 * $pastelimit) { /* Paste size too big */ } elseif (mb_strlen($_POST["paste_data"], '8bit') > 1024 * 1024 * $pastelimit) { /* Paste size too big */
return $lang['large_paste']; return $lang['large_paste'];
} }
@ -103,26 +102,26 @@ function validatePasteFields() : string | null {
header('Content-Type: text/html; charset=utf-8'); header('Content-Type: text/html; charset=utf-8');
// Current date & user IP // Current date & user IP
$date = date('jS F Y'); $date = date('jS F Y');
$ip = $_SERVER['REMOTE_ADDR']; $ip = $_SERVER['REMOTE_ADDR'];
// Sitemap // Sitemap
$site_sitemap_rows = $conn->query('SELECT * FROM sitemap_options LIMIT 1'); $site_sitemap_rows = $conn->query('SELECT * FROM sitemap_options LIMIT 1');
if ($row = $site_sitemap_rows->fetch()) { if ($row = $site_sitemap_rows->fetch()) {
$priority = $row['priority']; $priority = $row['priority'];
$changefreq = $row['changefreq']; $changefreq = $row['changefreq'];
} }
// Captcha // Captcha
$site_captcha_rows = $conn->query("SELECT * FROM captcha LIMIT 1"); $site_captcha_rows = $conn->query("SELECT * FROM captcha LIMIT 1");
if ($row = $site_captcha_rows->fetch()) { if ($row = $site_captcha_rows->fetch()) {
$color = Trim($row['color']); $color = Trim($row['color']);
$mode = Trim($row['mode']); $mode = Trim($row['mode']);
$mul = Trim($row['mul']); $mul = Trim($row['mul']);
$allowed = Trim($row['allowed']); $allowed = Trim($row['allowed']);
$cap_e = Trim($row['cap_e']); $cap_e = Trim($row['cap_e']);
$recaptcha_sitekey = Trim($row['recaptcha_sitekey']); $recaptcha_sitekey = Trim($row['recaptcha_sitekey']);
$recaptcha_secretkey = Trim($row['recaptcha_secretkey']); $recaptcha_secretkey = Trim($row['recaptcha_secretkey']);
} }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
@ -158,18 +157,18 @@ if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$editing = isset($_POST['edit']); $editing = isset($_POST['edit']);
$p_title = Trim(htmlspecialchars($_POST['title'])); $p_title = Trim(htmlspecialchars($_POST['title']));
if (empty($p_title)) { if (empty($p_title)) {
$p_title = 'Untitled'; $p_title = 'Untitled';
} }
$p_content = htmlspecialchars($_POST['paste_data']); $p_content = htmlspecialchars($_POST['paste_data']);
$p_visible = Trim(htmlspecialchars($_POST['visibility'])); $p_visible = Trim(htmlspecialchars($_POST['visibility']));
$p_code = Trim(htmlspecialchars($_POST['format'])); $p_code = Trim(htmlspecialchars($_POST['format']));
$p_expiry = Trim(htmlspecialchars($_POST['paste_expire_date'])); $p_expiry = Trim(htmlspecialchars($_POST['paste_expire_date']));
$p_tagsys = Trim(htmlspecialchars($_POST['tags'])); $p_tagsys = Trim(htmlspecialchars($_POST['tags']));
$p_tagsys = rtrim($p_tagsys, ','); $p_tagsys = rtrim($p_tagsys, ',');
$p_password = $_POST['pass']; $p_password = $_POST['pass'];
if ($p_password == "" || $p_password == null) { if ($p_password == "" || $p_password == null) {
$p_password = "NONE"; $p_password = "NONE";
@ -195,10 +194,10 @@ if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Set expiry time // Set expiry time
$expires = calculatePasteExpiry($p_expiry); $expires = calculatePasteExpiry($p_expiry);
$p_date = date('jS F Y h:i:s A'); $p_date = date('jS F Y h:i:s A');
$date = date('jS F Y'); $date = date('jS F Y');
$now_time = mktime(date("H"), date("i"), date("s"), date("n"), date("j"), date("Y")); $now_time = mktime(date("H"), date("i"), date("s"), date("n"), date("j"), date("Y"));
$timeedit = gmmktime(date("H"), date("i"), date("s"), date("n"), date("j"), date("Y")); $timeedit = gmmktime(date("H"), date("i"), date("s"), date("n"), date("j"), date("Y"));
// Edit existing paste or create new? // Edit existing paste or create new?
if ($editing) { if ($editing) {
@ -221,7 +220,7 @@ if ($_SERVER['REQUEST_METHOD'] == 'POST') {
"INSERT INTO pastes (title, content, visible, code, expiry, password, encrypt, member, date, ip, now_time, views, s_date, tagsys) VALUES "INSERT INTO pastes (title, content, visible, code, expiry, password, encrypt, member, date, ip, now_time, views, s_date, tagsys) VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '0', ?, ?)" (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '0', ?, ?)"
); );
$statement->execute([$p_title,$p_content,$p_visible,$p_code,$expires,$p_password,$p_encrypt,$p_member,$p_date,$ip,$now_time,$date,$p_tagsys]); $statement->execute([$p_title, $p_content, $p_visible, $p_code, $expires, $p_password, $p_encrypt, $p_member, $p_date, $ip, $now_time, $date, $p_tagsys]);
$paste_id = intval($conn->lastInsertId()); /* returns the last inserted ID as per the query above */ $paste_id = intval($conn->lastInsertId()); /* returns the last inserted ID as per the query above */
if ($p_visible == '0') { if ($p_visible == '0') {
addToSitemap($paste_id, $priority, $changefreq, $mod_rewrite); addToSitemap($paste_id, $priority, $changefreq, $mod_rewrite);

View file

@ -4,117 +4,117 @@
* Translated by Plamen Vasilev <p.vasileff@gmail.com> (Oct, 2017) * Translated by Plamen Vasilev <p.vasileff@gmail.com> (Oct, 2017)
*/ */
$lang = array(); $lang = array();
$lang['banned'] = "Достъпа ви до " . $site_name . "е ограничен"; $lang['banned'] = "Достъпа ви до " . $site_name . "е ограничен";
$lang['expired'] = "Документа, който се опитваш да достъпиш е изтекъл."; $lang['expired'] = "Документа, който се опитваш да достъпиш е изтекъл.";
$lang['guestwelcome'] = $site_name . " ти позволява да публикуваш текст &amp; код."; $lang['guestwelcome'] = $site_name . " ти позволява да публикуваш текст &amp; код.";
$lang['pleaseregister'] = "<br /><br /> <a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Влез</a> или се <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Регистрирай</a> за да публикуваш съдържание. Безплатно е."; $lang['pleaseregister'] = "<br /><br /> <a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Влез</a> или се <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Регистрирай</a> за да публикуваш съдържание. Безплатно е.";
$lang['registertoedit'] = "<a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Влез</a> или се <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Регистрирай</a> за да редактираш или задържиш това съдържание."; $lang['registertoedit'] = "<a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Влез</a> или се <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Регистрирай</a> за да редактираш или задържиш това съдържание.";
$lang['editpaste'] = "Редактирай"; $lang['editpaste'] = "Редактирай";
$lang['forkpaste'] = "Задръж"; $lang['forkpaste'] = "Задръж";
$lang['guestmsgtitle'] = $site_name . " е място за публикуване на код или текст за по-лесно отстраняване на грешки."; $lang['guestmsgtitle'] = $site_name . " е място за публикуване на код или текст за по-лесно отстраняване на грешки.";
$lang['guestmsgbody'] = "<a data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Влез</a> или се <a data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Регистрай</a> за да редактираш, изтриваш или преглеждаш хронология на твоето публикувано съдържание"; $lang['guestmsgbody'] = "<a data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Влез</a> или се <a data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Регистрай</a> за да редактираш, изтриваш или преглеждаш хронология на твоето публикувано съдържание";
$lang['emptypastebin'] = "Няма публикувано съдържание"; $lang['emptypastebin'] = "Няма публикувано съдържание";
$lang['siteprivate'] = "Този документ е частен."; $lang['siteprivate'] = "Този документ е частен.";
$lang['image_wrong'] = "Wrong captcha."; $lang['image_wrong'] = "Wrong captcha.";
$lang['missing-input-response'] = "The reCAPTCHA response parameter is missing. Please verify your PASTE settings."; $lang['missing-input-response'] = "The reCAPTCHA response parameter is missing. Please verify your PASTE settings.";
$lang['missing-input-secret'] = "The reCAPTCHA secret parameter is missing. Please add it to your PASTE settings."; $lang['missing-input-secret'] = "The reCAPTCHA secret parameter is missing. Please add it to your PASTE settings.";
$lang['missing-input-response'] = "The reCAPTCHA response parameter is invalid. Please try to complete the reCAPTCHA again."; $lang['missing-input-response'] = "The reCAPTCHA response parameter is invalid. Please try to complete the reCAPTCHA again.";
$lang['invalid-input-secret'] = "The reCAPTCHA secret parameter is invalid or malformed. Please double check your PASTE settings."; $lang['invalid-input-secret'] = "The reCAPTCHA secret parameter is invalid or malformed. Please double check your PASTE settings.";
$lang['empty_paste'] = "Не може да добавите публикацията без съдържание"; $lang['empty_paste'] = "Не може да добавите публикацията без съдържание";
$lang['large_paste'] = "Вашата публикация е прекалено голяма. Максималния размер е " . $pastelimit . "MB"; $lang['large_paste'] = "Вашата публикация е прекалено голяма. Максималния размер е " . $pastelimit . "MB";
$lang['paste_db_error'] = "Unable to post to database."; $lang['paste_db_error'] = "Unable to post to database.";
$lang['error'] = "Something went wrong."; $lang['error'] = "Something went wrong.";
$lang['archive'] = "Pastes Archive"; $lang['archive'] = "Pastes Archive";
$lang['contact'] = "Contact Us"; $lang['contact'] = "Contact Us";
$lang['full_name'] = "Your full name is required."; $lang['full_name'] = "Your full name is required.";
$lang['email'] = "Your email address is required."; $lang['email'] = "Your email address is required.";
$lang['email_invalid'] = "Your email address seems to be invalid."; $lang['email_invalid'] = "Your email address seems to be invalid.";
$lang['message'] = "Your message is required."; $lang['message'] = "Your message is required.";
$lang['login/register'] = "Вход/Регистрация"; $lang['login/register'] = "Вход/Регистрация";
$lang['rememberme'] = "Keep me signed in."; $lang['rememberme'] = "Keep me signed in.";
$lang['mail_acc_con'] = "$site_name Account Confirmation"; $lang['mail_acc_con'] = "$site_name Account Confirmation";
$lang['mail_suc'] = "На имейла адреса ти е изпратен код за верификация."; $lang['mail_suc'] = "На имейла адреса ти е изпратен код за верификация.";
$lang['email_ver'] = "Имейла вече е бил потвърден."; $lang['email_ver'] = "Имейла вече е бил потвърден.";
$lang['email_not'] = "Имейла не е намерен."; $lang['email_not'] = "Имейла не е намерен.";
$lang['pass_change'] = "Паролата е променена успешно и е изпратена на имейла ти."; $lang['pass_change'] = "Паролата е променена успешно и е изпратена на имейла ти.";
$lang['notverified'] = "Акаунта не е верифициран."; $lang['notverified'] = "Акаунта не е верифициран.";
$lang['incorrect'] = "Невалидни Потребител/Парола"; $lang['incorrect'] = "Невалидни Потребител/Парола";
$lang['missingfields'] = "All fields must be filled out."; $lang['missingfields'] = "All fields must be filled out.";
$lang['userexists'] = "Това потребителско име вече се използва"; $lang['userexists'] = "Това потребителско име вече се използва";
$lang['emailexists'] = "Този имейл адрес вече съществува в системата"; $lang['emailexists'] = "Този имейл адрес вече съществува в системата";
$lang['registered'] = "Акаунтът ти беше регистриран успешно"; $lang['registered'] = "Акаунтът ти беше регистриран успешно";
$lang['usrinvalid'] = "Your username can only contain letters or numbers."; $lang['usrinvalid'] = "Your username can only contain letters or numbers.";
$lang['mypastes'] = "My Pastes"; $lang['mypastes'] = "My Pastes";
$lang['pastedeleted'] = "Paste deleted."; $lang['pastedeleted'] = "Paste deleted.";
$lang['databaseerror'] = "Unable to post to database."; $lang['databaseerror'] = "Unable to post to database.";
$lang['userchanged'] = "Username changed successfully."; $lang['userchanged'] = "Username changed successfully.";
$lang['usernotvalid'] = "Username not vaild."; $lang['usernotvalid'] = "Username not vaild.";
$lang['privatepaste'] = "This is a private paste."; $lang['privatepaste'] = "This is a private paste.";
$lang['wrongpassword'] = 'Грешна парола.'; $lang['wrongpassword'] = 'Грешна парола.';
$lang['pwdprotected'] = 'Съдържание с парола'; $lang['pwdprotected'] = 'Съдържание с парола';
$lang['notfound'] = "Not found"; $lang['notfound'] = "Not found";
$lang['wrongpwd'] = "Въведената парола е грешна. Опитай отново."; $lang['wrongpwd'] = "Въведената парола е грешна. Опитай отново.";
$lang['myprofile'] = "My Profile"; $lang['myprofile'] = "My Profile";
$lang['profileerror'] = "Unable to update the profile information "; $lang['profileerror'] = "Unable to update the profile information ";
$lang['profileupdated'] = "Your profile information is updated "; $lang['profileupdated'] = "Your profile information is updated ";
$lang['oldpasswrong'] = "Your old password is wrong."; $lang['oldpasswrong'] = "Your old password is wrong.";
$lang['archives'] = "Pastes Archive"; $lang['archives'] = "Pastes Archive";
$lang['archivestitle'] = "This page contains the most recently created 100 public pastes."; $lang['archivestitle'] = "This page contains the most recently created 100 public pastes.";
$lang['pastetitle'] = "Paste Title"; $lang['pastetitle'] = "Paste Title";
$lang['pastetime'] = "Paste Time"; $lang['pastetime'] = "Paste Time";
$lang['pastesyntax'] = "Paste Syntax"; $lang['pastesyntax'] = "Paste Syntax";
$lang['pasteviews'] = "Paste Views"; $lang['pasteviews'] = "Paste Views";
$lang['wentwrong'] = "Something went wrong."; $lang['wentwrong'] = "Something went wrong.";
$lang['versent'] = "A verification email has been sent to your email address."; $lang['versent'] = "A verification email has been sent to your email address.";
$lang['modpaste'] = "Modify Paste"; $lang['modpaste'] = "Modify Paste";
$lang['newpaste'] = "New Paste"; $lang['newpaste'] = "New Paste";
$lang['highlighting'] = "Syntax Highlighting"; $lang['highlighting'] = "Syntax Highlighting";
$lang['expiration'] = "Paste Expiration"; $lang['expiration'] = "Paste Expiration";
$lang['visibility'] = "Paste Visibility"; $lang['visibility'] = "Paste Visibility";
$lang['pwopt'] = "Password (Optional)"; $lang['pwopt'] = "Password (Optional)";
$lang['encrypt'] = "Encrypt in database"; $lang['encrypt'] = "Encrypt in database";
$lang['entercode'] = "Enter Code"; $lang['entercode'] = "Enter Code";
$lang['almostthere'] = "Almost there. One more step to go."; $lang['almostthere'] = "Almost there. One more step to go.";
$lang['username'] = "Username"; $lang['username'] = "Username";
$lang['autogen'] = "Auto generated name"; $lang['autogen'] = "Auto generated name";
$lang['setuser'] = "Set your Username"; $lang['setuser'] = "Set your Username";
$lang['keepuser'] = "Keep autogenerated name"; $lang['keepuser'] = "Keep autogenerated name";
$lang['enterpwd'] = "Enter the password"; $lang['enterpwd'] = "Enter the password";
$lang['totalpastes'] = "Total Pastes:"; $lang['totalpastes'] = "Total Pastes:";
$lang['membtype'] = "Membership Type:"; $lang['membtype'] = "Membership Type:";
$lang['email'] = "Email"; $lang['email'] = "Email";
$lang['fullname'] = "Full Name"; $lang['fullname'] = "Full Name";
$lang['chgpwd'] = "Change Password"; $lang['chgpwd'] = "Change Password";
$lang['curpwd'] = "Current Password"; $lang['curpwd'] = "Current Password";
$lang['newpwd'] = "New Password"; $lang['newpwd'] = "New Password";
$lang['confpwd'] = "Confirm Password"; $lang['confpwd'] = "Confirm Password";
$lang['mypastes'] = "My Pastes"; $lang['mypastes'] = "My Pastes";
$lang['viewpastes'] = "View all my pastes"; $lang['viewpastes'] = "View all my pastes";
$lang['recentpastes'] = "Recent Pastes"; $lang['recentpastes'] = "Recent Pastes";
$lang['user_public_pastes'] = "'s Pastes"; $lang['user_public_pastes'] = "'s Pastes";
$lang['yourpastes'] = "Your Pastes"; $lang['yourpastes'] = "Your Pastes";
$lang['mypastestitle'] = "All of your pastes, in one place."; $lang['mypastestitle'] = "All of your pastes, in one place.";
$lang['delete'] = "Delete"; $lang['delete'] = "Delete";
$lang['highlighted'] = "The text below is selected, press Ctrl+C to copy to your clipboard. (&#8984;+C on Mac)"; $lang['highlighted'] = "The text below is selected, press Ctrl+C to copy to your clipboard. (&#8984;+C on Mac)";
$lang['newpaste'] = "New Paste"; $lang['newpaste'] = "New Paste";
$lang['download'] = "Download"; $lang['download'] = "Download";
$lang['showlineno'] = "Покажи/Скрий номерата на редовете"; $lang['showlineno'] = "Покажи/Скрий номерата на редовете";
$lang['copyto'] = "Копирай съдържанието в клипборда"; $lang['copyto'] = "Копирай съдържанието в клипборда";
$lang['rawpaste'] = "Raw Paste"; $lang['rawpaste'] = "Raw Paste";
$lang['membersince'] = "Joined: "; $lang['membersince'] = "Joined: ";
$lang['delete_error_invalid'] = "Error: Paste not deleted because it does not exist or you do not own the paste."; $lang['delete_error_invalid'] = "Error: Paste not deleted because it does not exist or you do not own the paste.";
$lang['not_logged_in'] = "Грешка: Нужно е да си логнат в системата, за да направиш това."; $lang['not_logged_in'] = "Грешка: Нужно е да си логнат в системата, за да направиш това.";
$lang['public'] = "Public"; $lang['public'] = "Public";
$lang['unlisted'] = "Unlisted"; $lang['unlisted'] = "Unlisted";
$lang['private'] = "Private"; $lang['private'] = "Private";
$lang['hello'] = "Hello"; $lang['hello'] = "Hello";
$lang['profile-message'] = "This is your profile page where you can manage your pastes.<br /> All of your public, private and unlisted pastes will be shown here. You can also delete your pastes from this page. If other users visit your page they will only see pastes you have set public."; $lang['profile-message'] = "This is your profile page where you can manage your pastes.<br /> All of your public, private and unlisted pastes will be shown here. You can also delete your pastes from this page. If other users visit your page they will only see pastes you have set public.";
$lang['profile-stats'] = "Some of your statistics:"; $lang['profile-stats'] = "Some of your statistics:";
$lang['profile-total-pastes'] = "Total Pastes:"; $lang['profile-total-pastes'] = "Total Pastes:";
$lang['profile-total-pub'] = "Total public pastes:"; $lang['profile-total-pub'] = "Total public pastes:";
$lang['profile-total-unl'] = "Total unlisted pastes:"; $lang['profile-total-unl'] = "Total unlisted pastes:";
$lang['profile-total-pri'] = "Total private pastes:"; $lang['profile-total-pri'] = "Total private pastes:";
$lang['profile-total-views'] = "Total views of all your pastes:"; $lang['profile-total-views'] = "Total views of all your pastes:";
$lang['embed-hosted-by'] = "hosted by"; $lang['embed-hosted-by'] = "hosted by";
$lang['view-raw'] = "Покажи в необработен текст"; $lang['view-raw'] = "Покажи в необработен текст";
?> ?>

View file

@ -5,117 +5,117 @@
$lang = array(); $lang = array();
$lang['banned'] = "Você foi banido do " . $site_name; $lang['banned'] = "Você foi banido do " . $site_name;
$lang['expired'] = "O paste que você procura não existe mais."; $lang['expired'] = "O paste que você procura não existe mais.";
$lang['guestwelcome'] = $site_name . " é um lugar para guardar e compartilhar seus pastes e codigos."; $lang['guestwelcome'] = $site_name . " é um lugar para guardar e compartilhar seus pastes e codigos.";
$lang['pleaseregister'] = "<br /><br /> <a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Entrar</a> ou <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Cadastre-se</a> para criar um novo paste."; $lang['pleaseregister'] = "<br /><br /> <a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Entrar</a> ou <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Cadastre-se</a> para criar um novo paste.";
$lang['registertoedit'] = "<a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Entrre</a> ou <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Cadastre-se</a> para editar ou duplicar este paste."; $lang['registertoedit'] = "<a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Entrre</a> ou <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Cadastre-se</a> para editar ou duplicar este paste.";
$lang['editpaste'] = "Editar"; $lang['editpaste'] = "Editar";
$lang['forkpaste'] = "Duplicar"; $lang['forkpaste'] = "Duplicar";
$lang['guestmsgtitle'] = $site_name . ", um lugar para salvar e compartilhar textos e codigos."; $lang['guestmsgtitle'] = $site_name . ", um lugar para salvar e compartilhar textos e codigos.";
$lang['guestmsgbody'] = "<a data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Entrar</a> ou <a data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Cadastre-se</a> para editar e acomparnhar os seus pastes."; $lang['guestmsgbody'] = "<a data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Entrar</a> ou <a data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Cadastre-se</a> para editar e acomparnhar os seus pastes.";
$lang['emptypastebin'] = "Este pastebin está vazio"; $lang['emptypastebin'] = "Este pastebin está vazio";
$lang['siteprivate'] = "Este é um paste privado."; $lang['siteprivate'] = "Este é um paste privado.";
$lang['image_wrong'] = "Captha invalido."; $lang['image_wrong'] = "Captha invalido.";
$lang['missing-input-response'] = "O parametro de resposta do reCapcha está faltando. Por favor verifique as configurações do seu paste."; $lang['missing-input-response'] = "O parametro de resposta do reCapcha está faltando. Por favor verifique as configurações do seu paste.";
$lang['missing-input-secret'] = "O parametro de seguredo do reCapcha está faltando. Por favor verifique as configurações do seu paste."; $lang['missing-input-secret'] = "O parametro de seguredo do reCapcha está faltando. Por favor verifique as configurações do seu paste.";
$lang['missing-input-response'] = "O parametro de resposta do reCapcha é inválido. Por favor tente novamente."; $lang['missing-input-response'] = "O parametro de resposta do reCapcha é inválido. Por favor tente novamente.";
$lang['invalid-input-secret'] = "O parametro de seguredo do reCapcha está faltando ou é inválido. Please double check your PASTE settings."; $lang['invalid-input-secret'] = "O parametro de seguredo do reCapcha está faltando ou é inválido. Please double check your PASTE settings.";
$lang['empty_paste'] = "Você não pode publicar um paste vazio."; $lang['empty_paste'] = "Você não pode publicar um paste vazio.";
$lang['large_paste'] = "O seu paste é muito grande. O tamanho maximo é: " . $pastelimit . "MB"; $lang['large_paste'] = "O seu paste é muito grande. O tamanho maximo é: " . $pastelimit . "MB";
$lang['paste_db_error'] = "Não conseguimos eviar seu paste para o banco de dados."; $lang['paste_db_error'] = "Não conseguimos eviar seu paste para o banco de dados.";
$lang['error'] = "Algo deu errado."; $lang['error'] = "Algo deu errado.";
$lang['archive'] = "Arquivo de pastes"; $lang['archive'] = "Arquivo de pastes";
$lang['contact'] = "Entre em contato"; $lang['contact'] = "Entre em contato";
$lang['full_name'] = "É nescessario inserir o seu nome completo."; $lang['full_name'] = "É nescessario inserir o seu nome completo.";
$lang['email'] = "É nescessario inserir o seu email."; $lang['email'] = "É nescessario inserir o seu email.";
$lang['email_invalid'] = "O seu endereçõ de email não parece ser válido."; $lang['email_invalid'] = "O seu endereçõ de email não parece ser válido.";
$lang['message'] = "É nescessario inserir uma mensagem válida."; $lang['message'] = "É nescessario inserir uma mensagem válida.";
$lang['login/register'] = "Entrar/Cadastro"; $lang['login/register'] = "Entrar/Cadastro";
$lang['rememberme'] = "Manter me logado."; $lang['rememberme'] = "Manter me logado.";
$lang['mail_acc_con'] = "Informações da conta em $site_name"; $lang['mail_acc_con'] = "Informações da conta em $site_name";
$lang['mail_suc'] = "O seu codigo de verificção foi enviado ao email preenchido."; $lang['mail_suc'] = "O seu codigo de verificção foi enviado ao email preenchido.";
$lang['email_ver'] = "Email já verificado."; $lang['email_ver'] = "Email já verificado.";
$lang['email_not'] = "Email não encontrado, já fez o seu cadastro?."; $lang['email_not'] = "Email não encontrado, já fez o seu cadastro?.";
$lang['pass_change'] = "Senha alterada com sucesso, a enviamos para o seu email."; $lang['pass_change'] = "Senha alterada com sucesso, a enviamos para o seu email.";
$lang['notverified'] = "Conta não verificada."; $lang['notverified'] = "Conta não verificada.";
$lang['incorrect'] = "Senha ou usuario incorretos"; $lang['incorrect'] = "Senha ou usuario incorretos";
$lang['missingfields'] = "Todos os campos devem ser preenchidos."; $lang['missingfields'] = "Todos os campos devem ser preenchidos.";
$lang['userexists'] = "Nome de usuario já em uso."; $lang['userexists'] = "Nome de usuario já em uso.";
$lang['emailexists'] = "Email já em uso."; $lang['emailexists'] = "Email já em uso.";
$lang['registered'] = "Conta cadastrada com sucesso."; $lang['registered'] = "Conta cadastrada com sucesso.";
$lang['usrinvalid'] = "Seu nome de usuario deve conter apenas letras e numeros."; $lang['usrinvalid'] = "Seu nome de usuario deve conter apenas letras e numeros.";
$lang['mypastes'] = "Meus pastes"; $lang['mypastes'] = "Meus pastes";
$lang['pastedeleted'] = "Paste apagado."; $lang['pastedeleted'] = "Paste apagado.";
$lang['databaseerror'] = "Incapaz de enviar para o banco de dados."; $lang['databaseerror'] = "Incapaz de enviar para o banco de dados.";
$lang['userchanged'] = "Nome de usuario alterado com sucesso."; $lang['userchanged'] = "Nome de usuario alterado com sucesso.";
$lang['usernotvalid'] = "Nome de usuario inválido."; $lang['usernotvalid'] = "Nome de usuario inválido.";
$lang['privatepaste'] = "Este paste é privado."; $lang['privatepaste'] = "Este paste é privado.";
$lang['wrongpassword'] = 'Senha incorreta.'; $lang['wrongpassword'] = 'Senha incorreta.';
$lang['pwdprotected'] = 'Testo protegido por senha'; $lang['pwdprotected'] = 'Testo protegido por senha';
$lang['notfound'] = "Não encontrado"; $lang['notfound'] = "Não encontrado";
$lang['wrongpwd'] = "Senha inválida, tente novamente."; $lang['wrongpwd'] = "Senha inválida, tente novamente.";
$lang['myprofile'] = "Meu perfil"; $lang['myprofile'] = "Meu perfil";
$lang['profileerror'] = "Incapaz de atualizar as informações do perfil."; $lang['profileerror'] = "Incapaz de atualizar as informações do perfil.";
$lang['profileupdated'] = "Informações do perfil atualizadas."; $lang['profileupdated'] = "Informações do perfil atualizadas.";
$lang['oldpasswrong'] = "Senha antiga incorreta."; $lang['oldpasswrong'] = "Senha antiga incorreta.";
$lang['archives'] = "Arquivo de pastes"; $lang['archives'] = "Arquivo de pastes";
$lang['archivestitle'] = "Esta pagina contém os 100 pastes mais recentes."; $lang['archivestitle'] = "Esta pagina contém os 100 pastes mais recentes.";
$lang['pastetitle'] = "Nome do paste"; $lang['pastetitle'] = "Nome do paste";
$lang['pastetime'] = "Momento de publicação do paste"; $lang['pastetime'] = "Momento de publicação do paste";
$lang['pastesyntax'] = "Sintaxe do paste"; $lang['pastesyntax'] = "Sintaxe do paste";
$lang['pasteviews'] = "Visualizações do paste"; $lang['pasteviews'] = "Visualizações do paste";
$lang['wentwrong'] = "Algo deu errado."; $lang['wentwrong'] = "Algo deu errado.";
$lang['versent'] = "Um email de verificação foi enviado ao seu endereço de email."; $lang['versent'] = "Um email de verificação foi enviado ao seu endereço de email.";
$lang['modpaste'] = "Modificar paste"; $lang['modpaste'] = "Modificar paste";
$lang['newpaste'] = "Novo paste"; $lang['newpaste'] = "Novo paste";
$lang['highlighting'] = "Destaque de síntaxe"; $lang['highlighting'] = "Destaque de síntaxe";
$lang['expiration'] = "Expiraçaão do paste"; $lang['expiration'] = "Expiraçaão do paste";
$lang['visibility'] = "Visibilidade do paste"; $lang['visibility'] = "Visibilidade do paste";
$lang['pwopt'] = "Senha (Opcional)"; $lang['pwopt'] = "Senha (Opcional)";
$lang['encrypt'] = "Encriptar no banco de dados"; $lang['encrypt'] = "Encriptar no banco de dados";
$lang['entercode'] = "Entre o codigo"; $lang['entercode'] = "Entre o codigo";
$lang['almostthere'] = "Quase lá, apenas mais um passo."; $lang['almostthere'] = "Quase lá, apenas mais um passo.";
$lang['username'] = "Nome de usuario"; $lang['username'] = "Nome de usuario";
$lang['autogen'] = "Nome Gerado automaticamente"; $lang['autogen'] = "Nome Gerado automaticamente";
$lang['setuser'] = "Defina o seu nome de usuario"; $lang['setuser'] = "Defina o seu nome de usuario";
$lang['keepuser'] = "Manter nome gerado automaticamente"; $lang['keepuser'] = "Manter nome gerado automaticamente";
$lang['enterpwd'] = "Entre sua senha"; $lang['enterpwd'] = "Entre sua senha";
$lang['totalpastes'] = "Total de pastes:"; $lang['totalpastes'] = "Total de pastes:";
$lang['membtype'] = "Tipo de Membro:"; $lang['membtype'] = "Tipo de Membro:";
$lang['email'] = "Email"; $lang['email'] = "Email";
$lang['fullname'] = "Nome completo"; $lang['fullname'] = "Nome completo";
$lang['chgpwd'] = "Mudar senha"; $lang['chgpwd'] = "Mudar senha";
$lang['curpwd'] = "Senha atual"; $lang['curpwd'] = "Senha atual";
$lang['newpwd'] = "Nova senha"; $lang['newpwd'] = "Nova senha";
$lang['confpwd'] = "Confirmar senha"; $lang['confpwd'] = "Confirmar senha";
$lang['mypastes'] = "Meus pastes"; $lang['mypastes'] = "Meus pastes";
$lang['viewpastes'] = "Ver todos os meus pastes"; $lang['viewpastes'] = "Ver todos os meus pastes";
$lang['recentpastes'] = "pastes recentes"; $lang['recentpastes'] = "pastes recentes";
$lang['user_public_pastes'] = " publicou:"; $lang['user_public_pastes'] = " publicou:";
$lang['yourpastes'] = "Seus pastes"; $lang['yourpastes'] = "Seus pastes";
$lang['mypastestitle'] = "Todos os seus pastes, em um só lugar."; $lang['mypastestitle'] = "Todos os seus pastes, em um só lugar.";
$lang['delete'] = "Apagar"; $lang['delete'] = "Apagar";
$lang['highlighted'] = "O paste abaixo está selecionado, pressione Ctrl+C Para copiar para a area de transferencia. (&#8984;+C no mac)"; $lang['highlighted'] = "O paste abaixo está selecionado, pressione Ctrl+C Para copiar para a area de transferencia. (&#8984;+C no mac)";
$lang['newpaste'] = "Novo paste"; $lang['newpaste'] = "Novo paste";
$lang['download'] = "Baixar"; $lang['download'] = "Baixar";
$lang['showlineno'] = "Mostrar/Esconder numero da linha"; $lang['showlineno'] = "Mostrar/Esconder numero da linha";
$lang['copyto'] = "Copiar paste para a area de transferência"; $lang['copyto'] = "Copiar paste para a area de transferência";
$lang['rawpaste'] = "Novo texto bruto"; $lang['rawpaste'] = "Novo texto bruto";
$lang['membersince'] = "Se cadastrou em: "; $lang['membersince'] = "Se cadastrou em: ";
$lang['delete_error_invalid'] = "Erro: paste não foi apagado por que você não é dono dele ou ele nao existe mais."; $lang['delete_error_invalid'] = "Erro: paste não foi apagado por que você não é dono dele ou ele nao existe mais.";
$lang['not_logged_in'] = "Erro: Você deve estar logado para poder fazer isso."; $lang['not_logged_in'] = "Erro: Você deve estar logado para poder fazer isso.";
$lang['public'] = "Publico"; $lang['public'] = "Publico";
$lang['unlisted'] = "Não listado"; $lang['unlisted'] = "Não listado";
$lang['private'] = "Privado"; $lang['private'] = "Privado";
$lang['hello'] = "Olá"; $lang['hello'] = "Olá";
$lang['profile-message'] = "Esta é a pagina do seu perfil, onde você pode ver e adminnistrar todos os seus pastes.<br /> Todos os seus pastes, publicos, privados e não listados serão mostrados aqui. Você também pode deletar os seus pastes nesta pagina. Se outros usuários acessarem esta pagina eles verão apenas seus pastes públicos."; $lang['profile-message'] = "Esta é a pagina do seu perfil, onde você pode ver e adminnistrar todos os seus pastes.<br /> Todos os seus pastes, publicos, privados e não listados serão mostrados aqui. Você também pode deletar os seus pastes nesta pagina. Se outros usuários acessarem esta pagina eles verão apenas seus pastes públicos.";
$lang['profile-stats'] = "Algumas de suas estatísticas:"; $lang['profile-stats'] = "Algumas de suas estatísticas:";
$lang['profile-total-pastes'] = "Numero de pastes:"; $lang['profile-total-pastes'] = "Numero de pastes:";
$lang['profile-total-pub'] = "Numero de pastes públicos:"; $lang['profile-total-pub'] = "Numero de pastes públicos:";
$lang['profile-total-unl'] = "Numero de pastes não listados:"; $lang['profile-total-unl'] = "Numero de pastes não listados:";
$lang['profile-total-pri'] = "Numero de pastes privados:"; $lang['profile-total-pri'] = "Numero de pastes privados:";
$lang['profile-total-views'] = "Numero de visualizações nos seus pastes:"; $lang['profile-total-views'] = "Numero de visualizações nos seus pastes:";
$lang['embed-hosted-by'] = "hospedado por"; $lang['embed-hosted-by'] = "hospedado por";
$lang['view-raw'] = "Ver texto bruto"; $lang['view-raw'] = "Ver texto bruto";
?> ?>

View file

@ -6,117 +6,117 @@
$lang = array(); $lang = array();
$lang['banned'] = "Du wurdest von " . $site_name . " gebannt."; $lang['banned'] = "Du wurdest von " . $site_name . " gebannt.";
$lang['expired'] = "Dieser Paste ist abgelaufen."; $lang['expired'] = "Dieser Paste ist abgelaufen.";
$lang['guestwelcome'] = $site_name . " erlaubt es dir Text &amp; Code hochzuladen."; $lang['guestwelcome'] = $site_name . " erlaubt es dir Text &amp; Code hochzuladen.";
$lang['pleaseregister'] = "<br /><br /> <a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Login</a> oder <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Registrieren</a> um einen neuen Paste hochzuladen. Es ist kostenlos."; $lang['pleaseregister'] = "<br /><br /> <a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Login</a> oder <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Registrieren</a> um einen neuen Paste hochzuladen. Es ist kostenlos.";
$lang['registertoedit'] = "<a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Login</a> oder <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Registrieren</a> um diesen Paste zu bearbeiten oder zu forken. Es ist kostenlos."; $lang['registertoedit'] = "<a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Login</a> oder <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Registrieren</a> um diesen Paste zu bearbeiten oder zu forken. Es ist kostenlos.";
$lang['editpaste'] = "Bearbeiten"; $lang['editpaste'] = "Bearbeiten";
$lang['forkpaste'] = "Fork"; $lang['forkpaste'] = "Fork";
$lang['guestmsgtitle'] = $site_name . " ist f$uuml;r Quelltexte und generellen Debugging Text."; $lang['guestmsgtitle'] = $site_name . " ist f$uuml;r Quelltexte und generellen Debugging Text.";
$lang['guestmsgbody'] = "<a data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Login</a> oder <a data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Registrieren</a> um zu bearbeiten, l&ouml;schen, um deine Pastes zu verfolgen und mehr."; $lang['guestmsgbody'] = "<a data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Login</a> oder <a data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Registrieren</a> um zu bearbeiten, l&ouml;schen, um deine Pastes zu verfolgen und mehr.";
$lang['emptypastebin'] = "Hier sind keine Pasts zum anzeigen."; $lang['emptypastebin'] = "Hier sind keine Pasts zum anzeigen.";
$lang['siteprivate'] = "Dieser Pastebin ist privat."; $lang['siteprivate'] = "Dieser Pastebin ist privat.";
$lang['image_wrong'] = "Falsches Captcha."; $lang['image_wrong'] = "Falsches Captcha.";
$lang['missing-input-response'] = "Der reCAPTCHA Response Parameter fehlt. Bitte &Uuml;berpr&uuml;fe deine PASTE Einstellungen."; $lang['missing-input-response'] = "Der reCAPTCHA Response Parameter fehlt. Bitte &Uuml;berpr&uuml;fe deine PASTE Einstellungen.";
$lang['missing-input-secret'] = "Der reCAPTCHA Secret Parameter fehlt. Bitte f&uuml;ge ihn zu deinen PASTE Einstellungen hinzu."; $lang['missing-input-secret'] = "Der reCAPTCHA Secret Parameter fehlt. Bitte f&uuml;ge ihn zu deinen PASTE Einstellungen hinzu.";
$lang['missing-input-response'] = "Der reCAPTCHA Response Parameter fehlt. Bitte versuche das reCAPTCHA erneut zu vollenden."; $lang['missing-input-response'] = "Der reCAPTCHA Response Parameter fehlt. Bitte versuche das reCAPTCHA erneut zu vollenden.";
$lang['invalid-input-secret'] = "Der reCAPTCHA Secret Parameter fehlt oder ist falsch. Bitte &uuml;berpr&uuml;fe noch mal deine PASTE Einstellungen."; $lang['invalid-input-secret'] = "Der reCAPTCHA Secret Parameter fehlt oder ist falsch. Bitte &uuml;berpr&uuml;fe noch mal deine PASTE Einstellungen.";
$lang['empty_paste'] = "Du kannst keinen leeren Paste hochladen."; $lang['empty_paste'] = "Du kannst keinen leeren Paste hochladen.";
$lang['large_paste'] = "Dein Paste ist zu gro&szlig;. Die maximale Gr&ouml;&szlig;e betr&auml;gt " . $pastelimit . "MB"; $lang['large_paste'] = "Dein Paste ist zu gro&szlig;. Die maximale Gr&ouml;&szlig;e betr&auml;gt " . $pastelimit . "MB";
$lang['paste_db_error'] = "Der Eintrag wurde nicht in die Datenbank geschrieben."; $lang['paste_db_error'] = "Der Eintrag wurde nicht in die Datenbank geschrieben.";
$lang['error'] = "Etwas ist schief gegangen."; $lang['error'] = "Etwas ist schief gegangen.";
$lang['archive'] = "Paste Archiv"; $lang['archive'] = "Paste Archiv";
$lang['contact'] = "Kontaktiere uns"; $lang['contact'] = "Kontaktiere uns";
$lang['full_name'] = "Es wird dein voller Name ben&ouml;tigt."; $lang['full_name'] = "Es wird dein voller Name ben&ouml;tigt.";
$lang['email'] = "Deine eMail-Adresse wird ben&ouml;tigt."; $lang['email'] = "Deine eMail-Adresse wird ben&ouml;tigt.";
$lang['email_invalid'] = "Deine eMail-Adresse scheint ung&uuml;ltig zu sein."; $lang['email_invalid'] = "Deine eMail-Adresse scheint ung&uuml;ltig zu sein.";
$lang['message'] = "Deine Nachricht wird ben&ouml;tigt."; $lang['message'] = "Deine Nachricht wird ben&ouml;tigt.";
$lang['login/register'] = "Login/Registrieren"; $lang['login/register'] = "Login/Registrieren";
$lang['rememberme'] = "Lass mich eingeloggt."; $lang['rememberme'] = "Lass mich eingeloggt.";
$lang['mail_acc_con'] = "$site_name Konto Best&auml;tigung"; $lang['mail_acc_con'] = "$site_name Konto Best&auml;tigung";
$lang['mail_suc'] = "Der Verifikationscode wurde erfolgreich an deine eMail-Adresse gesendet."; $lang['mail_suc'] = "Der Verifikationscode wurde erfolgreich an deine eMail-Adresse gesendet.";
$lang['email_ver'] = "Diese eMail-Adresse wurde bereits verifiziert."; $lang['email_ver'] = "Diese eMail-Adresse wurde bereits verifiziert.";
$lang['email_not'] = "eMail-Adresse nicht gefunden."; $lang['email_not'] = "eMail-Adresse nicht gefunden.";
$lang['pass_change'] = "Passwort erfolgreich ge&auml;ndert und per eMail versendet."; $lang['pass_change'] = "Passwort erfolgreich ge&auml;ndert und per eMail versendet.";
$lang['notverified'] = "Konto nicht verifiziert."; $lang['notverified'] = "Konto nicht verifiziert.";
$lang['incorrect'] = "Falscher Benutzername/Passwort"; $lang['incorrect'] = "Falscher Benutzername/Passwort";
$lang['missingfields'] = "Alle Felder m&uuml;ssen ausgef&uuml;llt sein."; $lang['missingfields'] = "Alle Felder m&uuml;ssen ausgef&uuml;llt sein.";
$lang['userexists'] = "Benutzername existiert bereits."; $lang['userexists'] = "Benutzername existiert bereits.";
$lang['emailexists'] = "eMail-Adresse wurde bereits registriert."; $lang['emailexists'] = "eMail-Adresse wurde bereits registriert.";
$lang['registered'] = "Dein Konto wurde erfolgreich registriert."; $lang['registered'] = "Dein Konto wurde erfolgreich registriert.";
$lang['usrinvalid'] = "Dein Benutzername kann nur Buchstaben und Zahlen enthalten."; $lang['usrinvalid'] = "Dein Benutzername kann nur Buchstaben und Zahlen enthalten.";
$lang['mypastes'] = "Meine Pastes"; $lang['mypastes'] = "Meine Pastes";
$lang['pastedeleted'] = "Paste gel&ouml;scht."; $lang['pastedeleted'] = "Paste gel&ouml;scht.";
$lang['databaseerror'] = "Der Eintrag wurde nicht in die Datenbank geschrieben."; $lang['databaseerror'] = "Der Eintrag wurde nicht in die Datenbank geschrieben.";
$lang['userchanged'] = "Benutzername erfolgreich ge&auml;ndert."; $lang['userchanged'] = "Benutzername erfolgreich ge&auml;ndert.";
$lang['usernotvalid'] = "Benutzername ist nicht g&uuml;ltig."; $lang['usernotvalid'] = "Benutzername ist nicht g&uuml;ltig.";
$lang['privatepaste'] = "Das ist ein privater Paste."; $lang['privatepaste'] = "Das ist ein privater Paste.";
$lang['wrongpassword'] = 'Falsches Passwort.'; $lang['wrongpassword'] = 'Falsches Passwort.';
$lang['pwdprotected'] = 'Passwortgesch&uuml;tzter Paste'; $lang['pwdprotected'] = 'Passwortgesch&uuml;tzter Paste';
$lang['notfound'] = "Nicht gefunden"; $lang['notfound'] = "Nicht gefunden";
$lang['wrongpwd'] = "Falsches Passwort. Versuche es erneut."; $lang['wrongpwd'] = "Falsches Passwort. Versuche es erneut.";
$lang['myprofile'] = "Mein Profil"; $lang['myprofile'] = "Mein Profil";
$lang['profileerror'] = "Kann Profilinformationen nicht aktualisieren "; $lang['profileerror'] = "Kann Profilinformationen nicht aktualisieren ";
$lang['profileupdated'] = "Profilinformationen aktualisiert "; $lang['profileupdated'] = "Profilinformationen aktualisiert ";
$lang['oldpasswrong'] = "Dein altes Passwort ist falsch."; $lang['oldpasswrong'] = "Dein altes Passwort ist falsch.";
$lang['archives'] = "Paste Archiv"; $lang['archives'] = "Paste Archiv";
$lang['archivestitle'] = "Diese Seite zeigt die 100 zuletzt erstellten, &ouml;ffentlichen Pastes."; $lang['archivestitle'] = "Diese Seite zeigt die 100 zuletzt erstellten, &ouml;ffentlichen Pastes.";
$lang['pastetitle'] = "Paste Titel"; $lang['pastetitle'] = "Paste Titel";
$lang['pastetime'] = "Paste Zeit"; $lang['pastetime'] = "Paste Zeit";
$lang['pastesyntax'] = "Paste Syntax"; $lang['pastesyntax'] = "Paste Syntax";
$lang['pasteviews'] = "Paste Ansichten"; $lang['pasteviews'] = "Paste Ansichten";
$lang['wentwrong'] = "Etwas ging schief."; $lang['wentwrong'] = "Etwas ging schief.";
$lang['versent'] = "Eine Best&auml;tigungsmail wurde an deine eMail-Adresse gesendet."; $lang['versent'] = "Eine Best&auml;tigungsmail wurde an deine eMail-Adresse gesendet.";
$lang['modpaste'] = "Paste bearbeiten "; $lang['modpaste'] = "Paste bearbeiten ";
$lang['newpaste'] = "Neuer Paste"; $lang['newpaste'] = "Neuer Paste";
$lang['highlighting'] = "Syntax Highlighting"; $lang['highlighting'] = "Syntax Highlighting";
$lang['expiration'] = "Paste Ablaufdatum"; $lang['expiration'] = "Paste Ablaufdatum";
$lang['visibility'] = "Paste Sichtbarkeit"; $lang['visibility'] = "Paste Sichtbarkeit";
$lang['pwopt'] = "Passwort (Optional)"; $lang['pwopt'] = "Passwort (Optional)";
$lang['encrypt'] = "Verschl&uuml;sselt in Datenbank"; $lang['encrypt'] = "Verschl&uuml;sselt in Datenbank";
$lang['entercode'] = "Code eingeben"; $lang['entercode'] = "Code eingeben";
$lang['almostthere'] = "Fast geschafft. Noch ein Schritt."; $lang['almostthere'] = "Fast geschafft. Noch ein Schritt.";
$lang['username'] = "Benutzername"; $lang['username'] = "Benutzername";
$lang['autogen'] = "Generierter Name"; $lang['autogen'] = "Generierter Name";
$lang['setuser'] = "Setze deinen Benutzernamen"; $lang['setuser'] = "Setze deinen Benutzernamen";
$lang['keepuser'] = "Behalte generierten Namen"; $lang['keepuser'] = "Behalte generierten Namen";
$lang['enterpwd'] = "Gib das Passwort ein"; $lang['enterpwd'] = "Gib das Passwort ein";
$lang['totalpastes'] = "Total Pastes:"; $lang['totalpastes'] = "Total Pastes:";
$lang['membtype'] = "Art der Mitgliedschaft:"; $lang['membtype'] = "Art der Mitgliedschaft:";
$lang['email'] = "Email"; $lang['email'] = "Email";
$lang['fullname'] = "Voller Name"; $lang['fullname'] = "Voller Name";
$lang['chgpwd'] = "Passwort &auml;ndern"; $lang['chgpwd'] = "Passwort &auml;ndern";
$lang['curpwd'] = "Aktuelles Passwort"; $lang['curpwd'] = "Aktuelles Passwort";
$lang['newpwd'] = "Neues Passwort"; $lang['newpwd'] = "Neues Passwort";
$lang['confpwd'] = "Best&auml;#tige Passwort"; $lang['confpwd'] = "Best&auml;#tige Passwort";
$lang['mypastes'] = "Meine Pastes"; $lang['mypastes'] = "Meine Pastes";
$lang['viewpastes'] = "Zeige alle meine Pastes"; $lang['viewpastes'] = "Zeige alle meine Pastes";
$lang['recentpastes'] = "Letzte Pastes"; $lang['recentpastes'] = "Letzte Pastes";
$lang['user_public_pastes'] = "'s Pastes"; $lang['user_public_pastes'] = "'s Pastes";
$lang['yourpastes'] = "Deine Pastes"; $lang['yourpastes'] = "Deine Pastes";
$lang['mypastestitle'] = "Alle deine Pastes, in einem Platz."; $lang['mypastestitle'] = "Alle deine Pastes, in einem Platz.";
$lang['delete'] = "L&ouml;schen"; $lang['delete'] = "L&ouml;schen";
$lang['highlighted'] = "Der unten stehende Text ist ausgew&auml;hlt, dr&uuml;cke Strg+C um ihn zu kopieren. (&#8984;+C beim Mac)"; $lang['highlighted'] = "Der unten stehende Text ist ausgew&auml;hlt, dr&uuml;cke Strg+C um ihn zu kopieren. (&#8984;+C beim Mac)";
$lang['newpaste'] = "Neuer Paste"; $lang['newpaste'] = "Neuer Paste";
$lang['download'] = "Download"; $lang['download'] = "Download";
$lang['showlineno'] = "Zeige/Verstecke Zeilennr."; $lang['showlineno'] = "Zeige/Verstecke Zeilennr.";
$lang['copyto'] = "Kopiere Text"; $lang['copyto'] = "Kopiere Text";
$lang['rawpaste'] = "Raw Paste"; $lang['rawpaste'] = "Raw Paste";
$lang['membersince'] = "Beigetreten: "; $lang['membersince'] = "Beigetreten: ";
$lang['delete_error_invalid'] = "Fehler: Paste wurde nicht gel&ouml;scht, da dieser nicht existiert oder du nicht der Eigent&uuml;mer bist."; $lang['delete_error_invalid'] = "Fehler: Paste wurde nicht gel&ouml;scht, da dieser nicht existiert oder du nicht der Eigent&uuml;mer bist.";
$lang['not_logged_in'] = "Fehler: Du musst eingeloggt sein, um das zu tun."; $lang['not_logged_in'] = "Fehler: Du musst eingeloggt sein, um das zu tun.";
$lang['public'] = "&Ouml;ffentlich"; $lang['public'] = "&Ouml;ffentlich";
$lang['unlisted'] = "Ungelistet"; $lang['unlisted'] = "Ungelistet";
$lang['private'] = "Privat"; $lang['private'] = "Privat";
$lang['hello'] = "Hallo"; $lang['hello'] = "Hallo";
$lang['profile-message'] = "Dies ist deine Profilseite in der du deine Pasts verwalten kannst.<br /> All deine &ouml;ffentlichen, privaten und ungelisteten Pastes werden hier gezeigt. Du kannst sie hier auch l&ouml;schen. Falls andere Benutzer deine Seite besuchen werden sie nur deine &ouml;ffentlich gesetzten Pastes sehen k&ouml;nnen."; $lang['profile-message'] = "Dies ist deine Profilseite in der du deine Pasts verwalten kannst.<br /> All deine &ouml;ffentlichen, privaten und ungelisteten Pastes werden hier gezeigt. Du kannst sie hier auch l&ouml;schen. Falls andere Benutzer deine Seite besuchen werden sie nur deine &ouml;ffentlich gesetzten Pastes sehen k&ouml;nnen.";
$lang['profile-stats'] = "Ein paar deiner Statistiken:"; $lang['profile-stats'] = "Ein paar deiner Statistiken:";
$lang['profile-total-pastes'] = "Total Pastes:"; $lang['profile-total-pastes'] = "Total Pastes:";
$lang['profile-total-pub'] = "Total &ouml;ffentliche Pastes:"; $lang['profile-total-pub'] = "Total &ouml;ffentliche Pastes:";
$lang['profile-total-unl'] = "Total ungelistete Pastes:"; $lang['profile-total-unl'] = "Total ungelistete Pastes:";
$lang['profile-total-pri'] = "Total private Pastes:"; $lang['profile-total-pri'] = "Total private Pastes:";
$lang['profile-total-views'] = "Total Ansichten all deiner Pastes:"; $lang['profile-total-views'] = "Total Ansichten all deiner Pastes:";
$lang['embed-hosted-by'] = "gehostet von"; $lang['embed-hosted-by'] = "gehostet von";
$lang['view-raw'] = "Zeige Raw"; $lang['view-raw'] = "Zeige Raw";
?> ?>

View file

@ -9,124 +9,124 @@ $lang['notags'] = "Please tag your paste";
$lang['maxnamelimit'] = "Username too long"; $lang['maxnamelimit'] = "Username too long";
$lang['tags'] = "Tags"; $lang['tags'] = "Tags";
$lang['author'] = "Paste Author"; $lang['author'] = "Paste Author";
$lang['updatedgreen'] = "Updated Pastes"; $lang['updatedgreen'] = "Updated Pastes";
$lang['popular'] = "Popular pastes"; $lang['popular'] = "Popular pastes";
$lang['random'] = "Random pastes"; $lang['random'] = "Random pastes";
$lang['monthpopular'] = "This months Popular Pastes"; $lang['monthpopular'] = "This months Popular Pastes";
$lang['banned'] = "You have been banned from " . $site_name; $lang['banned'] = "You have been banned from " . $site_name;
$lang['expired'] = "The paste you're looking for has expired."; $lang['expired'] = "The paste you're looking for has expired.";
$lang['guestwelcome'] = $site_name . " Guest pastes temporary disabled due to spam. Please register or sign in."; $lang['guestwelcome'] = $site_name . " Guest pastes temporary disabled due to spam. Please register or sign in.";
$lang['pleaseregister'] = "<br /><br /> <a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Login</a> or <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Register</a> to submit a new paste. It's free."; $lang['pleaseregister'] = "<br /><br /> <a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Login</a> or <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Register</a> to submit a new paste. It's free.";
$lang['registertoedit'] = "<a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Login</a> or <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Register</a> to edit or fork this paste. It's free."; $lang['registertoedit'] = "<a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Login</a> or <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Register</a> to edit or fork this paste. It's free.";
$lang['editpaste'] = "Edit"; $lang['editpaste'] = "Edit";
$lang['forkpaste'] = "Fork"; $lang['forkpaste'] = "Fork";
$lang['guestmsgtitle'] = $site_name . " is for horse greens and general shitposts."; $lang['guestmsgtitle'] = $site_name . " is for horse greens and general shitposts.";
$lang['guestmsgbody'] = "<a data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Login</a> or <a data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Register</a> to edit, delete and keep track of your pastes and more."; $lang['guestmsgbody'] = "<a data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Login</a> or <a data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Register</a> to edit, delete and keep track of your pastes and more.";
$lang['emptypastebin'] = "There are no pastes to show."; $lang['emptypastebin'] = "There are no pastes to show.";
$lang['siteprivate'] = "This pastebin is private."; $lang['siteprivate'] = "This pastebin is private.";
$lang['image_wrong'] = "Wrong captcha."; $lang['image_wrong'] = "Wrong captcha.";
$lang['missing-input-response'] = "The reCAPTCHA response parameter is missing. Please verify your PASTE settings."; $lang['missing-input-response'] = "The reCAPTCHA response parameter is missing. Please verify your PASTE settings.";
$lang['missing-input-secret'] = "The reCAPTCHA secret parameter is missing. Please add it to your PASTE settings."; $lang['missing-input-secret'] = "The reCAPTCHA secret parameter is missing. Please add it to your PASTE settings.";
$lang['missing-input-response'] = "The reCAPTCHA response parameter is invalid. Please try to complete the reCAPTCHA again."; $lang['missing-input-response'] = "The reCAPTCHA response parameter is invalid. Please try to complete the reCAPTCHA again.";
$lang['invalid-input-secret'] = "The reCAPTCHA secret parameter is invalid or malformed. Please double check your PASTE settings."; $lang['invalid-input-secret'] = "The reCAPTCHA secret parameter is invalid or malformed. Please double check your PASTE settings.";
$lang['empty_paste'] = "You cannot post an empty paste."; $lang['empty_paste'] = "You cannot post an empty paste.";
$lang['large_paste'] = "Your paste is too large. Max size is " . $pastelimit . "MB"; $lang['large_paste'] = "Your paste is too large. Max size is " . $pastelimit . "MB";
$lang['paste_db_error'] = "Unable to post to database."; $lang['paste_db_error'] = "Unable to post to database.";
$lang['error'] = "Something went wrong."; $lang['error'] = "Something went wrong.";
$lang['archive'] = "Pastes Archive"; $lang['archive'] = "Pastes Archive";
$lang['contact'] = "Contact Us"; $lang['contact'] = "Contact Us";
$lang['full_name'] = "Account name is required."; $lang['full_name'] = "Account name is required.";
$lang['email'] = "Your email address is required."; $lang['email'] = "Your email address is required.";
$lang['email_invalid'] = "Your email address seems to be invalid."; $lang['email_invalid'] = "Your email address seems to be invalid.";
$lang['message'] = "Your message is required."; $lang['message'] = "Your message is required.";
$lang['login/register'] = "Login/Register"; $lang['login/register'] = "Login/Register";
$lang['rememberme'] = "Keep me signed in."; $lang['rememberme'] = "Keep me signed in.";
$lang['mail_acc_con'] = "$site_name Account Confirmation"; $lang['mail_acc_con'] = "$site_name Account Confirmation";
$lang['mail_suc'] = "Verification code successfully sent to your email address."; $lang['mail_suc'] = "Verification code successfully sent to your email address.";
$lang['email_ver'] = "Email already verified."; $lang['email_ver'] = "Email already verified.";
$lang['email_not'] = "Email not found."; $lang['email_not'] = "Email not found.";
$lang['pass_change'] = "Password changed successfully and sent to your email."; $lang['pass_change'] = "Password changed successfully and sent to your email.";
$lang['notverified'] = "Account not verified."; $lang['notverified'] = "Account not verified.";
$lang['incorrect'] = "Incorrect User/Password"; $lang['incorrect'] = "Incorrect User/Password";
$lang['missingfields'] = "All fields must be filled out."; $lang['missingfields'] = "All fields must be filled out.";
$lang['userexists'] = "Username already taken."; $lang['userexists'] = "Username already taken.";
$lang['emailexists'] = "Email already registered."; $lang['emailexists'] = "Email already registered.";
$lang['registered'] = "Your account was successfully registered."; $lang['registered'] = "Your account was successfully registered.";
$lang['usrinvalid'] = "Your username can only contain letters or numbers."; $lang['usrinvalid'] = "Your username can only contain letters or numbers.";
$lang['mypastes'] = "My Pastes"; $lang['mypastes'] = "My Pastes";
$lang['pastedeleted'] = "Paste deleted."; $lang['pastedeleted'] = "Paste deleted.";
$lang['databaseerror'] = "Unable to post to database."; $lang['databaseerror'] = "Unable to post to database.";
$lang['userchanged'] = "Username changed successfully."; $lang['userchanged'] = "Username changed successfully.";
$lang['usernotvalid'] = "Username not vaild."; $lang['usernotvalid'] = "Username not vaild.";
$lang['privatepaste'] = "This is a private paste."; $lang['privatepaste'] = "This is a private paste.";
$lang['wrongpassword'] = 'Wrong password.'; $lang['wrongpassword'] = 'Wrong password.';
$lang['pwdprotected'] = 'Password protected paste'; $lang['pwdprotected'] = 'Password protected paste';
$lang['notfound'] = "Not found"; $lang['notfound'] = "Not found";
$lang['wrongpwd'] = "Wrong password. Try again."; $lang['wrongpwd'] = "Wrong password. Try again.";
$lang['myprofile'] = "My Profile"; $lang['myprofile'] = "My Profile";
$lang['profileerror'] = "Unable to update the profile information "; $lang['profileerror'] = "Unable to update the profile information ";
$lang['profileupdated'] = "Your profile information is updated "; $lang['profileupdated'] = "Your profile information is updated ";
$lang['oldpasswrong'] = "Your old password is wrong."; $lang['oldpasswrong'] = "Your old password is wrong.";
$lang['archives'] = "Pastes Archive"; $lang['archives'] = "Pastes Archive";
$lang['archivestitle'] = "This page contains the most recently created 100 public pastes."; $lang['archivestitle'] = "This page contains the most recently created 100 public pastes.";
$lang['pastetitle'] = "Paste Title"; $lang['pastetitle'] = "Paste Title";
$lang['pastetime'] = "Paste Time"; $lang['pastetime'] = "Paste Time";
$lang['pastedate'] = "Paste Date"; $lang['pastedate'] = "Paste Date";
$lang['pastesyntax'] = "Paste Syntax"; $lang['pastesyntax'] = "Paste Syntax";
$lang['pasteviews'] = "Views"; $lang['pasteviews'] = "Views";
$lang['wentwrong'] = "Something went wrong."; $lang['wentwrong'] = "Something went wrong.";
$lang['versent'] = "A verification email has been sent to your email address."; $lang['versent'] = "A verification email has been sent to your email address.";
$lang['modpaste'] = "Modify Paste"; $lang['modpaste'] = "Modify Paste";
$lang['newpaste'] = "New Paste"; $lang['newpaste'] = "New Paste";
$lang['highlighting'] = "Syntax Highlighting"; $lang['highlighting'] = "Syntax Highlighting";
$lang['expiration'] = "Paste Expiration"; $lang['expiration'] = "Paste Expiration";
$lang['visibility'] = "Paste Visibility"; $lang['visibility'] = "Paste Visibility";
$lang['pwopt'] = "Password (Optional)"; $lang['pwopt'] = "Password (Optional)";
$lang['encrypt'] = "Encrypt in database"; $lang['encrypt'] = "Encrypt in database";
$lang['entercode'] = "Enter Code"; $lang['entercode'] = "Enter Code";
$lang['almostthere'] = "Almost there. One more step to go."; $lang['almostthere'] = "Almost there. One more step to go.";
$lang['username'] = "Username"; $lang['username'] = "Username";
$lang['autogen'] = "Auto generated name"; $lang['autogen'] = "Auto generated name";
$lang['setuser'] = "Set your Username"; $lang['setuser'] = "Set your Username";
$lang['keepuser'] = "Keep autogenerated name"; $lang['keepuser'] = "Keep autogenerated name";
$lang['enterpwd'] = "Enter the password"; $lang['enterpwd'] = "Enter the password";
$lang['totalpastes'] = "Total Pastes:"; $lang['totalpastes'] = "Total Pastes:";
$lang['membtype'] = "Membership Type:"; $lang['membtype'] = "Membership Type:";
$lang['email'] = "Email"; $lang['email'] = "Email";
$lang['fullname'] = "Full Name"; $lang['fullname'] = "Full Name";
$lang['chgpwd'] = "Change Password"; $lang['chgpwd'] = "Change Password";
$lang['curpwd'] = "Current Password"; $lang['curpwd'] = "Current Password";
$lang['newpwd'] = "New Password"; $lang['newpwd'] = "New Password";
$lang['confpwd'] = "Confirm Password"; $lang['confpwd'] = "Confirm Password";
$lang['mypastes'] = "My Pastes"; $lang['mypastes'] = "My Pastes";
$lang['viewpastes'] = "View all my pastes"; $lang['viewpastes'] = "View all my pastes";
$lang['recentpastes'] = "Recent Pastes"; $lang['recentpastes'] = "Recent Pastes";
$lang['user_public_pastes'] = "'s Pastes"; $lang['user_public_pastes'] = "'s Pastes";
$lang['yourpastes'] = "Your Pastes"; $lang['yourpastes'] = "Your Pastes";
$lang['mypastestitle'] = "All of your pastes, in one place."; $lang['mypastestitle'] = "All of your pastes, in one place.";
$lang['delete'] = "Delete"; $lang['delete'] = "Delete";
$lang['highlighted'] = "The text below is selected, press Ctrl+C to copy to your clipboard. (&#8984;+C on Mac)"; $lang['highlighted'] = "The text below is selected, press Ctrl+C to copy to your clipboard. (&#8984;+C on Mac)";
$lang['newpaste'] = "New Paste"; $lang['newpaste'] = "New Paste";
$lang['download'] = "Download"; $lang['download'] = "Download";
$lang['showlineno'] = "Show/Hide line no."; $lang['showlineno'] = "Show/Hide line no.";
$lang['copyto'] = "Copy text to clipboard"; $lang['copyto'] = "Copy text to clipboard";
$lang['rawpaste'] = "Raw Paste"; $lang['rawpaste'] = "Raw Paste";
$lang['membersince'] = "Joined: "; $lang['membersince'] = "Joined: ";
$lang['delete_error_invalid'] = "Error: Paste not deleted because it does not exist or you do not own the paste."; $lang['delete_error_invalid'] = "Error: Paste not deleted because it does not exist or you do not own the paste.";
$lang['not_logged_in'] = "Error: You must be logged in to do that."; $lang['not_logged_in'] = "Error: You must be logged in to do that.";
$lang['public'] = "Public"; $lang['public'] = "Public";
$lang['unlisted'] = "Unlisted"; $lang['unlisted'] = "Unlisted";
$lang['private'] = "Private"; $lang['private'] = "Private";
$lang['hello'] = "Hello"; $lang['hello'] = "Hello";
$lang['profile-message'] = "This is your profile page where you can manage your pastes.<br /> All of your public, private and unlisted pastes will be shown here. You can also delete your pastes from this page. If other users visit your page they will only see pastes you have set public."; $lang['profile-message'] = "This is your profile page where you can manage your pastes.<br /> All of your public, private and unlisted pastes will be shown here. You can also delete your pastes from this page. If other users visit your page they will only see pastes you have set public.";
$lang['profile-stats'] = "Some of your statistics:"; $lang['profile-stats'] = "Some of your statistics:";
$lang['profile-total-pastes'] = "Total Pastes:"; $lang['profile-total-pastes'] = "Total Pastes:";
$lang['profile-total-pub'] = "Total public pastes:"; $lang['profile-total-pub'] = "Total public pastes:";
$lang['profile-total-unl'] = "Total unlisted pastes:"; $lang['profile-total-unl'] = "Total unlisted pastes:";
$lang['profile-total-pri'] = "Total private pastes:"; $lang['profile-total-pri'] = "Total private pastes:";
$lang['profile-total-views'] = "Total views of all your pastes:"; $lang['profile-total-views'] = "Total views of all your pastes:";
$lang['pastfavs-total'] = "Total Favorites of your pastes:"; $lang['pastfavs-total'] = "Total Favorites of your pastes:";
$lang['yourfavs-total'] = "Total Favorites by you:"; $lang['yourfavs-total'] = "Total Favorites by you:";
$lang['embed-hosted-by'] = "hosted by"; $lang['embed-hosted-by'] = "hosted by";
$lang['view-raw'] = "View Raw"; $lang['view-raw'] = "View Raw";
?> ?>

View file

@ -4,110 +4,110 @@
* Author: S. Jorge * Author: S. Jorge
*/ */
$lang = array(); $lang = array();
$lang['banned'] = "Estas barneado en " . $site_name; $lang['banned'] = "Estas barneado en " . $site_name;
$lang['expired'] = "El pegado que estás buscando ha caducado."; $lang['expired'] = "El pegado que estás buscando ha caducado.";
$lang['guestwelcome'] = $site_name . " te permite enviar texto &amp; código."; $lang['guestwelcome'] = $site_name . " te permite enviar texto &amp; código.";
$lang['pleaseregister'] = "<br /><br /> <a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Iniciar sesión</a> o <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Registrarse</a> para enviar un pegado. Es gratis."; $lang['pleaseregister'] = "<br /><br /> <a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Iniciar sesión</a> o <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Registrarse</a> para enviar un pegado. Es gratis.";
$lang['registertoedit'] = "<a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Iniciar sesión</a> o <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Registrarse</a> para editar o bifurcar este pegado. Es gratis."; $lang['registertoedit'] = "<a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Iniciar sesión</a> o <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Registrarse</a> para editar o bifurcar este pegado. Es gratis.";
$lang['editpaste'] = "Editar"; $lang['editpaste'] = "Editar";
$lang['forkpaste'] = "Bifurcar"; $lang['forkpaste'] = "Bifurcar";
$lang['guestmsgtitle'] = $site_name . " es para el código fuente y el texto de depuración general."; $lang['guestmsgtitle'] = $site_name . " es para el código fuente y el texto de depuración general.";
$lang['guestmsgbody'] = "<a data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Iniciar sesión</a> o <a data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Registrarse</a> para editar, eliminar y mantener un seguimiento de sus pegados y mucho más."; $lang['guestmsgbody'] = "<a data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Iniciar sesión</a> o <a data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Registrarse</a> para editar, eliminar y mantener un seguimiento de sus pegados y mucho más.";
$lang['emptypastebin'] = "No hay pegado para mostrar."; $lang['emptypastebin'] = "No hay pegado para mostrar.";
$lang['siteprivate'] = "Este pegado es privado"; $lang['siteprivate'] = "Este pegado es privado";
$lang['image_wrong'] = "Captcha incorrecto."; $lang['image_wrong'] = "Captcha incorrecto.";
$lang['missing-input-response'] = "Falta el parámetro de respuesta reCAPTCHA. Verifique la configuración de PASTE."; $lang['missing-input-response'] = "Falta el parámetro de respuesta reCAPTCHA. Verifique la configuración de PASTE.";
$lang['missing-input-secret'] = "Falta el parámetro secreto reCAPTCHA. Añádala a su configuración de PASTE."; $lang['missing-input-secret'] = "Falta el parámetro secreto reCAPTCHA. Añádala a su configuración de PASTE.";
$lang['missing-input-response'] = "El parámetro de respuesta reCAPTCHA no es válido. Por favor, intenta completar el reCAPTCHA de nuevo."; $lang['missing-input-response'] = "El parámetro de respuesta reCAPTCHA no es válido. Por favor, intenta completar el reCAPTCHA de nuevo.";
$lang['invalid-input-secret'] = "El parámetro secreto reCAPTCHA no es válido o está mal formado. Por favor revise su configuración de PASTE."; $lang['invalid-input-secret'] = "El parámetro secreto reCAPTCHA no es válido o está mal formado. Por favor revise su configuración de PASTE.";
$lang['empty_paste'] = "No puede publicar un pegado vacío."; $lang['empty_paste'] = "No puede publicar un pegado vacío.";
$lang['large_paste'] = "El pegado es demasiado grande. El tamaño máximo es " . $pastelimit . "MB"; $lang['large_paste'] = "El pegado es demasiado grande. El tamaño máximo es " . $pastelimit . "MB";
$lang['paste_db_error'] = "No se puede publicar en la base de datos."; $lang['paste_db_error'] = "No se puede publicar en la base de datos.";
$lang['error'] = "Algo salió mal."; $lang['error'] = "Algo salió mal.";
$lang['archive'] = "Archivo de pegado"; $lang['archive'] = "Archivo de pegado";
$lang['contact'] = "Contactenos"; $lang['contact'] = "Contactenos";
$lang['full_name'] = "Su nombre completo es obligatorio."; $lang['full_name'] = "Su nombre completo es obligatorio.";
$lang['email'] = "Se requiere tu dirección de correo electrónico."; $lang['email'] = "Se requiere tu dirección de correo electrónico.";
$lang['email_invalid'] = "Su dirección de correo electrónico parece no ser válida."; $lang['email_invalid'] = "Su dirección de correo electrónico parece no ser válida.";
$lang['message'] = "Su mensaje es obligatorio."; $lang['message'] = "Su mensaje es obligatorio.";
$lang['login/register'] = "Iniciar sesión/Registro"; $lang['login/register'] = "Iniciar sesión/Registro";
$lang['rememberme'] = "Manténgame conectado."; $lang['rememberme'] = "Manténgame conectado.";
$lang['mail_acc_con'] = "$site_name Cuenta confirmada"; $lang['mail_acc_con'] = "$site_name Cuenta confirmada";
$lang['mail_suc'] = "El código de verificación se envió correctamente a su dirección de correo electrónico."; $lang['mail_suc'] = "El código de verificación se envió correctamente a su dirección de correo electrónico.";
$lang['email_ver'] = "Correo electrónico ya verificado."; $lang['email_ver'] = "Correo electrónico ya verificado.";
$lang['email_not'] = "Correo electrónico no encontrado."; $lang['email_not'] = "Correo electrónico no encontrado.";
$lang['pass_change'] = "La contraseña se ha cambiado correctamente y se ha enviado a tu correo electrónico."; $lang['pass_change'] = "La contraseña se ha cambiado correctamente y se ha enviado a tu correo electrónico.";
$lang['notverified'] = "Cuenta no verificada."; $lang['notverified'] = "Cuenta no verificada.";
$lang['incorrect'] = "Incorrecto usuario/contraseña"; $lang['incorrect'] = "Incorrecto usuario/contraseña";
$lang['missingfields'] = "Todos los campos deben ser llenados."; $lang['missingfields'] = "Todos los campos deben ser llenados.";
$lang['userexists'] = "Nombre de usuario ya tomado."; $lang['userexists'] = "Nombre de usuario ya tomado.";
$lang['emailexists'] = "Correo electrónico ya registrado."; $lang['emailexists'] = "Correo electrónico ya registrado.";
$lang ['registered'] = "Tu cuenta se ha registrado correctamente."; $lang ['registered'] = "Tu cuenta se ha registrado correctamente.";
$lang ['usrinvalid'] = "Tu nombre de usuario solo puede contener letras o números."; $lang ['usrinvalid'] = "Tu nombre de usuario solo puede contener letras o números.";
$lang ['mypastes'] = "Mis pegados"; $lang ['mypastes'] = "Mis pegados";
$lang ['pastedeleted'] = "Pegado borrado."; $lang ['pastedeleted'] = "Pegado borrado.";
$lang ['databaseerror'] = "No se puede publicar en la base de datos."; $lang ['databaseerror'] = "No se puede publicar en la base de datos.";
$lang ['userchanged'] = "El nombre de usuario ha cambiado correctamente."; $lang ['userchanged'] = "El nombre de usuario ha cambiado correctamente.";
$lang ['usernotvalid'] = "Nombre de usuario no válido."; $lang ['usernotvalid'] = "Nombre de usuario no válido.";
$lang ['privatepaste'] = "Este es un pegado privada."; $lang ['privatepaste'] = "Este es un pegado privada.";
$lang ['wrongpassword'] = "Contraseña incorrecta."; $lang ['wrongpassword'] = "Contraseña incorrecta.";
$lang ['pwdprotected'] = "Pegar con contraseña protegida"; $lang ['pwdprotected'] = "Pegar con contraseña protegida";
$lang ['notfound'] = "No encontrado"; $lang ['notfound'] = "No encontrado";
$lang ['wrongpwd'] = "Contraseña incorrecta. Vuelva a intentarlo."; $lang ['wrongpwd'] = "Contraseña incorrecta. Vuelva a intentarlo.";
$lang ['myprofile'] = "Mi perfil"; $lang ['myprofile'] = "Mi perfil";
$lang ['profileerror'] = "No se puede actualizar la información del perfil"; $lang ['profileerror'] = "No se puede actualizar la información del perfil";
$lang ['profileupdated']= "Se ha actualizado la información de tu perfil"; $lang ['profileupdated'] = "Se ha actualizado la información de tu perfil";
$lang ['oldpasswrong'] = "Su contraseña antigua es incorrecta."; $lang ['oldpasswrong'] = "Su contraseña antigua es incorrecta.";
$lang ['archives'] = "Archivos de pegado"; $lang ['archives'] = "Archivos de pegado";
$lang ['archivestitle'] = "Esta página contiene los 100 pegados publicados más recientemente."; $lang ['archivestitle'] = "Esta página contiene los 100 pegados publicados más recientemente.";
$lang ['pastetitle'] = "Pegar título"; $lang ['pastetitle'] = "Pegar título";
$lang ['pastetime'] = "Tiempo de pegado"; $lang ['pastetime'] = "Tiempo de pegado";
$lang ['pastesyntax'] = "Pegar Sintaxis"; $lang ['pastesyntax'] = "Pegar Sintaxis";
$lang ['pasteviews'] = "Pegar vistas"; $lang ['pasteviews'] = "Pegar vistas";
$lang ['wentwrong'] = "Algo salió mal."; $lang ['wentwrong'] = "Algo salió mal.";
$lang ['versent'] = "Se ha enviado un correo electrónico de verificación a su dirección de correo electrónico."; $lang ['versent'] = "Se ha enviado un correo electrónico de verificación a su dirección de correo electrónico.";
$lang ['modpaste'] = "Modificar Pegado"; $lang ['modpaste'] = "Modificar Pegado";
$lang ['newpaste'] = "Nueva Pega"; $lang ['newpaste'] = "Nueva Pega";
$lang ['highlighting'] = "Resaltado de sintaxis"; $lang ['highlighting'] = "Resaltado de sintaxis";
$lang ['expiration'] = "Pegar Expiración"; $lang ['expiration'] = "Pegar Expiración";
$lang ['visibility'] = "Pegar Visibilidad"; $lang ['visibility'] = "Pegar Visibilidad";
$lang ['pwopt'] = "Contraseña (Opcional)"; $lang ['pwopt'] = "Contraseña (Opcional)";
$lang ['encrypt'] = "Cifrar en la base de datos"; $lang ['encrypt'] = "Cifrar en la base de datos";
$lang ['entercode'] = "Introducir código"; $lang ['entercode'] = "Introducir código";
$lang ['almostthere'] = "Casi allí, un paso más."; $lang ['almostthere'] = "Casi allí, un paso más.";
$lang ['username'] = "Nombre de usuario"; $lang ['username'] = "Nombre de usuario";
$lang ['autogen'] = "Nombre generado automáticamente"; $lang ['autogen'] = "Nombre generado automáticamente";
$lang ['setuser'] = "Establecer su nombre de usuario"; $lang ['setuser'] = "Establecer su nombre de usuario";
$lang ['keepuser'] = "Mantener el nombre autogenerado"; $lang ['keepuser'] = "Mantener el nombre autogenerado";
$lang ['enterpwd'] = "Introduzca la contraseña"; $lang ['enterpwd'] = "Introduzca la contraseña";
$lang ['totalpastes'] = "Total pegado:"; $lang ['totalpastes'] = "Total pegado:";
$lang ['membtype'] = "Tipo de membresía:"; $lang ['membtype'] = "Tipo de membresía:";
$lang ['email'] = "Correo electrónico"; $lang ['email'] = "Correo electrónico";
$lang ['fullname'] = "Nombre completo"; $lang ['fullname'] = "Nombre completo";
$lang ['chgpwd'] = "Cambiar contraseña"; $lang ['chgpwd'] = "Cambiar contraseña";
$lang ['curpwd'] = "Contraseña actual"; $lang ['curpwd'] = "Contraseña actual";
$lang ['newpwd'] = "Nueva contraseña"; $lang ['newpwd'] = "Nueva contraseña";
$lang ['confpwd'] = "Confirmar contraseña"; $lang ['confpwd'] = "Confirmar contraseña";
$lang ['mypastes'] = "Mis pegados"; $lang ['mypastes'] = "Mis pegados";
$lang ['viewpastes'] = "Ver todos mis pegados"; $lang ['viewpastes'] = "Ver todos mis pegados";
$lang ['recentpastes'] = "Pegados recientes"; $lang ['recentpastes'] = "Pegados recientes";
$lang ['user_public_pastes'] = "'s pegados"; $lang ['user_public_pastes'] = "'s pegados";
$lang ['yourpastes'] = "Sus pegados"; $lang ['yourpastes'] = "Sus pegados";
$lang ['mypastestitle'] = "Todos tus pegados, en un solo lugar."; $lang ['mypastestitle'] = "Todos tus pegados, en un solo lugar.";
$lang ['delete'] = "Eliminar"; $lang ['delete'] = "Eliminar";
$lang['highlighted'] = "El texto siguiente está seleccionado, presione Ctrl+C para copiar en su portapapeles. (&#8984;+C en Mac)"; $lang['highlighted'] = "El texto siguiente está seleccionado, presione Ctrl+C para copiar en su portapapeles. (&#8984;+C en Mac)";
$lang ['newpaste'] = "Nueva Pega"; $lang ['newpaste'] = "Nueva Pega";
$lang ['download'] = "Descargar"; $lang ['download'] = "Descargar";
$lang ['showlineno'] = "Mostrar / Ocultar línea no"; $lang ['showlineno'] = "Mostrar / Ocultar línea no";
$lang ['copyto'] = "Copiar texto al portapapeles"; $lang ['copyto'] = "Copiar texto al portapapeles";
$lang ['rawpaste'] = "Pasta cruda"; $lang ['rawpaste'] = "Pasta cruda";
$lang ['membersince'] = "Registrado:"; $lang ['membersince'] = "Registrado:";
$lang ['delete_error_invalid'] = "Error: Pegado no borrado porque no existe o no posee el pegado."; $lang ['delete_error_invalid'] = "Error: Pegado no borrado porque no existe o no posee el pegado.";
$lang ['not_logged_in'] = "Error: Debes haber iniciado sesión para hacer eso."; $lang ['not_logged_in'] = "Error: Debes haber iniciado sesión para hacer eso.";
$lang ['public'] = "Público"; $lang ['public'] = "Público";
$lang ['unlisted'] = "No listado"; $lang ['unlisted'] = "No listado";
$lang ['private'] = "Privado"; $lang ['private'] = "Privado";
$lang ['hello'] = "Hola"; $lang ['hello'] = "Hola";
$lang['profile-message'] = "Esta es su página de perfil donde puede administrar sus pegados.<br /> Todos sus pegados públicos, privados y no listados se mostrarán aquí. También puede eliminar sus pegados de esta página. Si otros usuarios visitan tu página, solo verán las pastas que hayas puesto público."; $lang['profile-message'] = "Esta es su página de perfil donde puede administrar sus pegados.<br /> Todos sus pegados públicos, privados y no listados se mostrarán aquí. También puede eliminar sus pegados de esta página. Si otros usuarios visitan tu página, solo verán las pastas que hayas puesto público.";
$lang ['profile-stats'] = "Algunas de sus estadísticas:"; $lang ['profile-stats'] = "Algunas de sus estadísticas:";
$lang ['profile-total-pastes'] = "Pegados totales:"; $lang ['profile-total-pastes'] = "Pegados totales:";
@ -116,5 +116,5 @@ $lang ['profile-total-unl'] = "Total de pegados no listados:";
$lang ['perfil-total-pri'] = "Total de pegados privados:"; $lang ['perfil-total-pri'] = "Total de pegados privados:";
$lang ['profile-total-views'] = "Total de vistas de todos sus pegados:"; $lang ['profile-total-views'] = "Total de vistas de todos sus pegados:";
$lang ['embed-hosted-by'] = "alojado por"; $lang ['embed-hosted-by'] = "alojado por";
$lang ['view-raw'] = "Ver crudo"; $lang ['view-raw'] = "Ver crudo";
?> ?>

View file

@ -5,118 +5,118 @@
$lang = array(); $lang = array();
$lang['banned'] = "Vous avez été banni de " . $site_name; $lang['banned'] = "Vous avez été banni de " . $site_name;
$lang['expired'] = "Le paste que vous recherchez est expiré."; $lang['expired'] = "Le paste que vous recherchez est expiré.";
$lang['guestwelcome'] = $site_name . " vous permet de partager du texte et du code."; $lang['guestwelcome'] = $site_name . " vous permet de partager du texte et du code.";
$lang['pleaseregister'] = "<br /><br /> <a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Connectez-vous</a> ou <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Enregistrez-vous</a> pour soumettre un nouveau paste. C'est gratuit !"; $lang['pleaseregister'] = "<br /><br /> <a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Connectez-vous</a> ou <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Enregistrez-vous</a> pour soumettre un nouveau paste. C'est gratuit !";
$lang['registertoedit'] = "<a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Connectez-vous</a> ou <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Enregistrez-vous</a> pour éditer ou dupliquer ce paste. C'est gratuit !"; $lang['registertoedit'] = "<a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Connectez-vous</a> ou <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Enregistrez-vous</a> pour éditer ou dupliquer ce paste. C'est gratuit !";
$lang['editpaste'] = "Éditer"; $lang['editpaste'] = "Éditer";
$lang['forkpaste'] = "Dupliquer"; $lang['forkpaste'] = "Dupliquer";
$lang['guestmsgtitle'] = $site_name . " est fait pour le code source et le texte général de débogage."; $lang['guestmsgtitle'] = $site_name . " est fait pour le code source et le texte général de débogage.";
$lang['guestmsgbody'] = "<a data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Connectez-vous</a> ou <a data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Enregistrez-vous</a> pour éditer, supprimer et suivre vos pastes et bien plus."; $lang['guestmsgbody'] = "<a data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Connectez-vous</a> ou <a data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">Enregistrez-vous</a> pour éditer, supprimer et suivre vos pastes et bien plus.";
$lang['emptypastebin'] = "Pas de pastes."; $lang['emptypastebin'] = "Pas de pastes.";
$lang['siteprivate'] = "Ce pastebin est privé."; $lang['siteprivate'] = "Ce pastebin est privé.";
$lang['image_wrong'] = "Erreur de captcha."; $lang['image_wrong'] = "Erreur de captcha.";
$lang['missing-input-response'] = "Il manque le paramètre réponse de reCAPTCHA. Vérifier la configuration de PASTE."; $lang['missing-input-response'] = "Il manque le paramètre réponse de reCAPTCHA. Vérifier la configuration de PASTE.";
$lang['missing-input-secret'] = "Il manque le paramètre secret de reCAPTCHA. Merci de l'ajouter à la configuration de PASTE."; $lang['missing-input-secret'] = "Il manque le paramètre secret de reCAPTCHA. Merci de l'ajouter à la configuration de PASTE.";
$lang['missing-input-response'] = "Le paramètre réponse de reCAPTCHA est invalide. Recommencez."; $lang['missing-input-response'] = "Le paramètre réponse de reCAPTCHA est invalide. Recommencez.";
$lang['invalid-input-secret'] = "Le paramètre secret de reCAPTCHA est invalide ou incorrect. Vérifiez la configuration de PASTE."; $lang['invalid-input-secret'] = "Le paramètre secret de reCAPTCHA est invalide ou incorrect. Vérifiez la configuration de PASTE.";
$lang['empty_paste'] = "Vous ne pouvez pas publier un paste vide."; $lang['empty_paste'] = "Vous ne pouvez pas publier un paste vide.";
$lang['large_paste'] = "Le paste est trop volumineux. La taille maximale est " . $pastelimit . "MB"; $lang['large_paste'] = "Le paste est trop volumineux. La taille maximale est " . $pastelimit . "MB";
$lang['paste_db_error'] = "Impossible de publier dans la base de données."; $lang['paste_db_error'] = "Impossible de publier dans la base de données.";
$lang['error'] = "Erreur fatale."; $lang['error'] = "Erreur fatale.";
$lang['archive'] = "Archives"; $lang['archive'] = "Archives";
$lang['contact'] = "Nous contacter"; $lang['contact'] = "Nous contacter";
$lang['full_name'] = "Le champ nom doit être renseigné."; $lang['full_name'] = "Le champ nom doit être renseigné.";
$lang['email'] = "Le champ email doit être renseigné."; $lang['email'] = "Le champ email doit être renseigné.";
$lang['email_invalid'] = "Adresse email invalide."; $lang['email_invalid'] = "Adresse email invalide.";
$lang['message'] = "Le champ message doit être renseigné."; $lang['message'] = "Le champ message doit être renseigné.";
$lang['login/register'] = "Se connecter/S'enregistrer"; $lang['login/register'] = "Se connecter/S'enregistrer";
$lang['rememberme'] = "Rester connecter."; $lang['rememberme'] = "Rester connecter.";
$lang['mail_acc_con'] = "Confirmation de votre compte pour $site_name"; $lang['mail_acc_con'] = "Confirmation de votre compte pour $site_name";
$lang['mail_suc'] = "Le code de vérification a été transmis à votre adresse email."; $lang['mail_suc'] = "Le code de vérification a été transmis à votre adresse email.";
$lang['email_ver'] = "Adresse email déjà vérifiée."; $lang['email_ver'] = "Adresse email déjà vérifiée.";
$lang['email_not'] = "Adresse email non trouvée."; $lang['email_not'] = "Adresse email non trouvée.";
$lang['pass_change'] = "Le mot de passe a été changé et transmis à votre adresse email."; $lang['pass_change'] = "Le mot de passe a été changé et transmis à votre adresse email.";
$lang['notverified'] = "Compte non vérifié."; $lang['notverified'] = "Compte non vérifié.";
$lang['incorrect'] = "Nom d'utilisateur ou mot de passe incorrect."; $lang['incorrect'] = "Nom d'utilisateur ou mot de passe incorrect.";
$lang['missingfields'] = "Tous les champs doivent être renseignés"; $lang['missingfields'] = "Tous les champs doivent être renseignés";
$lang['userexists'] = "Le nom d'utilisateur existe déjà."; $lang['userexists'] = "Le nom d'utilisateur existe déjà.";
$lang['emailexists'] = "Adresse email déjà enregistrée."; $lang['emailexists'] = "Adresse email déjà enregistrée.";
$lang['registered'] = "Votre compte a été enregistré."; $lang['registered'] = "Votre compte a été enregistré.";
$lang['usrinvalid'] = "Votre nom d'utilisateur ne doit contenir que des lettres ou des chiffres."; $lang['usrinvalid'] = "Votre nom d'utilisateur ne doit contenir que des lettres ou des chiffres.";
$lang['mypastes'] = "Mes Pastes"; $lang['mypastes'] = "Mes Pastes";
$lang['pastedeleted'] = "Paste supprimé."; $lang['pastedeleted'] = "Paste supprimé.";
$lang['databaseerror'] = "Impossible d'enregistrer dans la base de données."; $lang['databaseerror'] = "Impossible d'enregistrer dans la base de données.";
$lang['userchanged'] = "Nom d'utilisateur changé."; $lang['userchanged'] = "Nom d'utilisateur changé.";
$lang['usernotvalid'] = "Nom d'utilisateur non valide."; $lang['usernotvalid'] = "Nom d'utilisateur non valide.";
$lang['privatepaste'] = "Ce paste est privé."; $lang['privatepaste'] = "Ce paste est privé.";
$lang['wrongpassword'] = 'Erreur mot de passe.'; $lang['wrongpassword'] = 'Erreur mot de passe.';
$lang['pwdprotected'] = 'Ce paste est protégé par mot de passe.'; $lang['pwdprotected'] = 'Ce paste est protégé par mot de passe.';
$lang['notfound'] = "Non trouvé"; $lang['notfound'] = "Non trouvé";
$lang['wrongpwd'] = "Erreur mot de passe, re-essayez."; $lang['wrongpwd'] = "Erreur mot de passe, re-essayez.";
$lang['myprofile'] = "Mon profil"; $lang['myprofile'] = "Mon profil";
$lang['profileerror'] = "Impossible de mettre à jour vos informations de profil."; $lang['profileerror'] = "Impossible de mettre à jour vos informations de profil.";
$lang['profileupdated'] = "Vos informations de profil ont été mises à jour"; $lang['profileupdated'] = "Vos informations de profil ont été mises à jour";
$lang['oldpasswrong'] = "Erreur ancien mot de passe"; $lang['oldpasswrong'] = "Erreur ancien mot de passe";
$lang['archives'] = "Archives"; $lang['archives'] = "Archives";
$lang['archivestitle'] = "Cet écran réuni les 100 derniers paste enregistrés."; $lang['archivestitle'] = "Cet écran réuni les 100 derniers paste enregistrés.";
$lang['pastetitle'] = "Titre du paste"; $lang['pastetitle'] = "Titre du paste";
$lang['pastetime'] = "Durée de vie du paste"; $lang['pastetime'] = "Durée de vie du paste";
$lang['pastesyntax'] = "Syntaxe du paste"; $lang['pastesyntax'] = "Syntaxe du paste";
$lang['pasteviews'] = "Nombre de vues du paste"; $lang['pasteviews'] = "Nombre de vues du paste";
$lang['wentwrong'] = "Erreur fatale."; $lang['wentwrong'] = "Erreur fatale.";
$lang['versent'] = "Un email de vérification a été transmis à votre adresse email."; $lang['versent'] = "Un email de vérification a été transmis à votre adresse email.";
$lang['modpaste'] = "Modifier le paste"; $lang['modpaste'] = "Modifier le paste";
$lang['newpaste'] = "Nouveau paste"; $lang['newpaste'] = "Nouveau paste";
$lang['highlighting'] = "Mise en évidence de la syntaxe."; $lang['highlighting'] = "Mise en évidence de la syntaxe.";
$lang['expiration'] = "Durée de vie du paste"; $lang['expiration'] = "Durée de vie du paste";
$lang['visibility'] = "Portée du paste"; $lang['visibility'] = "Portée du paste";
$lang['pwopt'] = "Mot de passe (Optionnel)"; $lang['pwopt'] = "Mot de passe (Optionnel)";
$lang['encrypt'] = "Crypter dans la base de données"; $lang['encrypt'] = "Crypter dans la base de données";
$lang['entercode'] = "Entrez le code"; $lang['entercode'] = "Entrez le code";
$lang['almostthere'] = "Vous avez presque terminé, il ne reste qu'une étape"; $lang['almostthere'] = "Vous avez presque terminé, il ne reste qu'une étape";
$lang['username'] = "Nom d'utilisateur"; $lang['username'] = "Nom d'utilisateur";
$lang['autogen'] = "Nom généré automatiquement"; $lang['autogen'] = "Nom généré automatiquement";
$lang['setuser'] = "Saisir votre nom d'utilisateur"; $lang['setuser'] = "Saisir votre nom d'utilisateur";
$lang['keepuser'] = "Garder le nom généré automatiquement"; $lang['keepuser'] = "Garder le nom généré automatiquement";
$lang['enterpwd'] = "Saisir le mot de passe"; $lang['enterpwd'] = "Saisir le mot de passe";
$lang['totalpastes'] = "Total pastes:"; $lang['totalpastes'] = "Total pastes:";
$lang['membtype'] = "Type de compte:"; $lang['membtype'] = "Type de compte:";
$lang['email'] = "Email"; $lang['email'] = "Email";
$lang['fullname'] = "Nom complet"; $lang['fullname'] = "Nom complet";
$lang['chgpwd'] = "Changer le mot de passe"; $lang['chgpwd'] = "Changer le mot de passe";
$lang['curpwd'] = "Mot de passe actuel"; $lang['curpwd'] = "Mot de passe actuel";
$lang['newpwd'] = "Nouveau mot de passe"; $lang['newpwd'] = "Nouveau mot de passe";
$lang['confpwd'] = "Confirmez le nouveau mot de passe"; $lang['confpwd'] = "Confirmez le nouveau mot de passe";
$lang['mypastes'] = "Mes pastes"; $lang['mypastes'] = "Mes pastes";
$lang['viewpastes'] = "Voir tous mes pastes"; $lang['viewpastes'] = "Voir tous mes pastes";
$lang['recentpastes'] = "Pastes récents"; $lang['recentpastes'] = "Pastes récents";
$lang['user_public_pastes'] = "'s Pastes"; $lang['user_public_pastes'] = "'s Pastes";
$lang['yourpastes'] = "Vos pastes"; $lang['yourpastes'] = "Vos pastes";
$lang['mypastestitle'] = "Tous vos pastes au même endroit."; $lang['mypastestitle'] = "Tous vos pastes au même endroit.";
$lang['delete'] = "Supprimer"; $lang['delete'] = "Supprimer";
$lang['highlighted'] = "Le texte ci-dessus est sélectionné, presser Ctrl+C pour le copier dans votre presse-papier. (&#8984;+C sur Mac)"; $lang['highlighted'] = "Le texte ci-dessus est sélectionné, presser Ctrl+C pour le copier dans votre presse-papier. (&#8984;+C sur Mac)";
$lang['newpaste'] = "Nouveau paste"; $lang['newpaste'] = "Nouveau paste";
$lang['download'] = "Télécharger"; $lang['download'] = "Télécharger";
$lang['showlineno'] = "Afficher/Cacher les numéros de ligne."; $lang['showlineno'] = "Afficher/Cacher les numéros de ligne.";
$lang['copyto'] = "Copier le texte dans le presse-papier."; $lang['copyto'] = "Copier le texte dans le presse-papier.";
$lang['rawpaste'] = "Paste brut"; $lang['rawpaste'] = "Paste brut";
$lang['membersince'] = "Enregistré depuis : "; $lang['membersince'] = "Enregistré depuis : ";
$lang['delete_error_invalid'] = "Erreur : le paste n'a pas été supprimé car il n'existe pas ou vous n'êtes pas son propriétaire."; $lang['delete_error_invalid'] = "Erreur : le paste n'a pas été supprimé car il n'existe pas ou vous n'êtes pas son propriétaire.";
$lang['not_logged_in'] = "Erreur : vous devez être connecté."; $lang['not_logged_in'] = "Erreur : vous devez être connecté.";
$lang['public'] = "Public"; $lang['public'] = "Public";
$lang['unlisted'] = "Fantôme"; $lang['unlisted'] = "Fantôme";
$lang['private'] = "Privé"; $lang['private'] = "Privé";
$lang['hello'] = "Bonjour"; $lang['hello'] = "Bonjour";
$lang['profile-message'] = "Vous pouvez gérer vos pastes sur cet écran de profil.<br /> Tous vos pastes publics, privés et fantômes sont listés ici. Vous pouvez également supprimer vos pastes depuis cet écran. Si un autre utilisateur visite votre profil, il ne verra que vos pastes publics."; $lang['profile-message'] = "Vous pouvez gérer vos pastes sur cet écran de profil.<br /> Tous vos pastes publics, privés et fantômes sont listés ici. Vous pouvez également supprimer vos pastes depuis cet écran. Si un autre utilisateur visite votre profil, il ne verra que vos pastes publics.";
$lang['profile-stats'] = "Quelques statistiques :"; $lang['profile-stats'] = "Quelques statistiques :";
$lang['profile-total-pastes'] = "Nombre total de pastes :"; $lang['profile-total-pastes'] = "Nombre total de pastes :";
$lang['profile-total-pub'] = "Nombre de pastes publics :"; $lang['profile-total-pub'] = "Nombre de pastes publics :";
$lang['profile-total-unl'] = "Nombre de pastes fantômes :"; $lang['profile-total-unl'] = "Nombre de pastes fantômes :";
$lang['profile-total-pri'] = "Nombre de pastes privés :"; $lang['profile-total-pri'] = "Nombre de pastes privés :";
$lang['profile-total-views'] = "Nombre total de vues :"; $lang['profile-total-views'] = "Nombre total de vues :";
$lang['embed-hosted-by'] = "hébergé par"; $lang['embed-hosted-by'] = "hébergé par";
$lang['view-raw'] = "Voir les données brutes"; $lang['view-raw'] = "Voir les données brutes";
?> ?>

View file

@ -6,117 +6,117 @@
$lang = array(); $lang = array();
$lang['banned'] = "Zostałeś zablokowany na " . $site_name; $lang['banned'] = "Zostałeś zablokowany na " . $site_name;
$lang['expired'] = "Wklejka, którą próbujesz odwiedzić, utraciła ważność."; $lang['expired'] = "Wklejka, którą próbujesz odwiedzić, utraciła ważność.";
$lang['guestwelcome'] = $site_name . " pozwala przechowywać tekst i kod."; $lang['guestwelcome'] = $site_name . " pozwala przechowywać tekst i kod.";
$lang['pleaseregister'] = "<br /><br /> <a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Zaloguj się</a> lub <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">zarejestruj</a>, aby wysłać nową wklejkę. To nic nie kosztuje."; $lang['pleaseregister'] = "<br /><br /> <a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Zaloguj się</a> lub <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">zarejestruj</a>, aby wysłać nową wklejkę. To nic nie kosztuje.";
$lang['registertoedit'] = "<a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Zaloguj się</a> lub <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">zarejestruj</a>, aby edytować lub powielić tą wklejkę. To nic nie kosztuje."; $lang['registertoedit'] = "<a class=\"btn btn-default\" data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Zaloguj się</a> lub <a class=\"btn btn-default\" data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">zarejestruj</a>, aby edytować lub powielić tą wklejkę. To nic nie kosztuje.";
$lang['editpaste'] = "Edytuj"; $lang['editpaste'] = "Edytuj";
$lang['forkpaste'] = "Powiel"; $lang['forkpaste'] = "Powiel";
$lang['guestmsgtitle'] = $site_name . " pozwala na przechowywanie kodu źródłowego i tekstu."; $lang['guestmsgtitle'] = $site_name . " pozwala na przechowywanie kodu źródłowego i tekstu.";
$lang['guestmsgbody'] = "<a data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Zaloguj się</a> lub <a data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">zarejestruj</a> aby edytować, usuwać i mieć kontrolę nad swoimi wklejkami."; $lang['guestmsgbody'] = "<a data-target=\"#signin\" data-toggle=\"modal\" href=\"#\">Zaloguj się</a> lub <a data-target=\"#signup\" data-toggle=\"modal\" href=\"#\">zarejestruj</a> aby edytować, usuwać i mieć kontrolę nad swoimi wklejkami.";
$lang['emptypastebin'] = "Brak wklejek do pokazania."; $lang['emptypastebin'] = "Brak wklejek do pokazania.";
$lang['siteprivate'] = "Ta strona jest prywatna."; $lang['siteprivate'] = "Ta strona jest prywatna.";
$lang['image_wrong'] = "Nieprawidłowy kod."; $lang['image_wrong'] = "Nieprawidłowy kod.";
$lang['missing-input-response'] = "Parametr odpowiedzi reCAPTCHA nie jest prawidłowy. Zweryfikuj ustawienia PASTE."; $lang['missing-input-response'] = "Parametr odpowiedzi reCAPTCHA nie jest prawidłowy. Zweryfikuj ustawienia PASTE.";
$lang['missing-input-secret'] = "Brak tajnego parametru reCAPTCHA. Dodaj go do ustawień reCAPTCHA."; $lang['missing-input-secret'] = "Brak tajnego parametru reCAPTCHA. Dodaj go do ustawień reCAPTCHA.";
$lang['missing-input-response'] = "Parametr odpowiedzi reCAPTCHA jest nieprawidłowy. Spróbuj wykonać reCAPTCHA ponownie."; $lang['missing-input-response'] = "Parametr odpowiedzi reCAPTCHA jest nieprawidłowy. Spróbuj wykonać reCAPTCHA ponownie.";
$lang['invalid-input-secret'] = "Patametr odpowiedzi reCAPTCHA jest nieprawidłowy. Sprawdź poprawność ustawień PASTE."; $lang['invalid-input-secret'] = "Patametr odpowiedzi reCAPTCHA jest nieprawidłowy. Sprawdź poprawność ustawień PASTE.";
$lang['empty_paste'] = "Nie możesz umieścić pustej wklejki."; $lang['empty_paste'] = "Nie możesz umieścić pustej wklejki.";
$lang['large_paste'] = "Wysłana wklejka jest zbyt duża. Maksymalny rozmiar wynosi " . $pastelimit . "MB."; $lang['large_paste'] = "Wysłana wklejka jest zbyt duża. Maksymalny rozmiar wynosi " . $pastelimit . "MB.";
$lang['paste_db_error'] = "Nie udało się umieścić w bazie danych."; $lang['paste_db_error'] = "Nie udało się umieścić w bazie danych.";
$lang['error'] = "Coś poszło nie tak."; $lang['error'] = "Coś poszło nie tak.";
$lang['archive'] = "Archiwum wklejek"; $lang['archive'] = "Archiwum wklejek";
$lang['contact'] = "Kontakt"; $lang['contact'] = "Kontakt";
$lang['full_name'] = "Musisz wprowadzić imię i nazwisko."; $lang['full_name'] = "Musisz wprowadzić imię i nazwisko.";
$lang['email'] = "Musisz wprowadzić adres e-mail."; $lang['email'] = "Musisz wprowadzić adres e-mail.";
$lang['email_invalid'] = "Wprowadzony adres e-mail jest nieprawidłowy."; $lang['email_invalid'] = "Wprowadzony adres e-mail jest nieprawidłowy.";
$lang['message'] = "Musisz wprowadzić wiadomość."; $lang['message'] = "Musisz wprowadzić wiadomość.";
$lang['login/register'] = "Zaloguj się/Zarejestruj"; $lang['login/register'] = "Zaloguj się/Zarejestruj";
$lang['rememberme'] = "Nie wylogowywuj mnie."; $lang['rememberme'] = "Nie wylogowywuj mnie.";
$lang['mail_acc_con'] = "Potwierdzenie konta na $site_name"; $lang['mail_acc_con'] = "Potwierdzenie konta na $site_name";
$lang['mail_suc'] = "Pomyślnie przesłano kod weryfikacyjny na podany e-mail."; $lang['mail_suc'] = "Pomyślnie przesłano kod weryfikacyjny na podany e-mail.";
$lang['email_ver'] = "Już zweryfikowano adres e-mail."; $lang['email_ver'] = "Już zweryfikowano adres e-mail.";
$lang['email_not'] = "Nie znaleziono adresu e-mail."; $lang['email_not'] = "Nie znaleziono adresu e-mail.";
$lang['pass_change'] = "Pomyślnie zmieniono hasło i przesłano na adres e-mail."; $lang['pass_change'] = "Pomyślnie zmieniono hasło i przesłano na adres e-mail.";
$lang['notverified'] = "Nie zweryfikowano konto."; $lang['notverified'] = "Nie zweryfikowano konto.";
$lang['incorrect'] = "Nieprawidłowa nazwa użytkownika/hasło"; $lang['incorrect'] = "Nieprawidłowa nazwa użytkownika/hasło";
$lang['missingfields'] = "Wszystkie pola muszą być wypełnione."; $lang['missingfields'] = "Wszystkie pola muszą być wypełnione.";
$lang['userexists'] = "Nazwa użytkownika jest zajęta."; $lang['userexists'] = "Nazwa użytkownika jest zajęta.";
$lang['emailexists'] = "Istnieje konto przypisane do tego adresu e-mail."; $lang['emailexists'] = "Istnieje konto przypisane do tego adresu e-mail.";
$lang['registered'] = "Pomyślnie zarejestrowano konto."; $lang['registered'] = "Pomyślnie zarejestrowano konto.";
$lang['usrinvalid'] = "Nazwa użytkownika może zawierać wyłącznie litery i cyfry."; $lang['usrinvalid'] = "Nazwa użytkownika może zawierać wyłącznie litery i cyfry.";
$lang['mypastes'] = "Moje wklejki"; $lang['mypastes'] = "Moje wklejki";
$lang['pastedeleted'] = "Usunięto wklejkę."; $lang['pastedeleted'] = "Usunięto wklejkę.";
$lang['databaseerror'] = "Nie udało się umieścić w bazie danych."; $lang['databaseerror'] = "Nie udało się umieścić w bazie danych.";
$lang['userchanged'] = "Pomyślnie zmieniono nazwę użytkownika."; $lang['userchanged'] = "Pomyślnie zmieniono nazwę użytkownika.";
$lang['usernotvalid'] = "Nieprawidłowa nazwa użytkownika."; $lang['usernotvalid'] = "Nieprawidłowa nazwa użytkownika.";
$lang['privatepaste'] = "To jest prywatna wklejka."; $lang['privatepaste'] = "To jest prywatna wklejka.";
$lang['wrongpassword'] = 'Nieprawidłowe hasło.'; $lang['wrongpassword'] = 'Nieprawidłowe hasło.';
$lang['pwdprotected'] = 'Wklejka chroniona hasłem'; $lang['pwdprotected'] = 'Wklejka chroniona hasłem';
$lang['notfound'] = "Nie znaleziono"; $lang['notfound'] = "Nie znaleziono";
$lang['wrongpwd'] = "Nieprawidłowe hasło. Spróbuj ponownie."; $lang['wrongpwd'] = "Nieprawidłowe hasło. Spróbuj ponownie.";
$lang['myprofile'] = "Moje konto"; $lang['myprofile'] = "Moje konto";
$lang['profileerror'] = "Nie udało się zaktualizować informacje o koncie "; $lang['profileerror'] = "Nie udało się zaktualizować informacje o koncie ";
$lang['profileupdated'] = "Pomyślnie zaktualizowano informacje o koncie "; $lang['profileupdated'] = "Pomyślnie zaktualizowano informacje o koncie ";
$lang['oldpasswrong'] = "Nieprawidłowe aktualne hasło."; $lang['oldpasswrong'] = "Nieprawidłowe aktualne hasło.";
$lang['archives'] = "Archiwum wklejek"; $lang['archives'] = "Archiwum wklejek";
$lang['archivestitle'] = "Ta strona zawiera 100 najnowszych publicznych wklejek."; $lang['archivestitle'] = "Ta strona zawiera 100 najnowszych publicznych wklejek.";
$lang['pastetitle'] = "Tytuł wklejki"; $lang['pastetitle'] = "Tytuł wklejki";
$lang['pastetime'] = "Czas dodania wklejki"; $lang['pastetime'] = "Czas dodania wklejki";
$lang['pastesyntax'] = "Składnia wklejki"; $lang['pastesyntax'] = "Składnia wklejki";
$lang['pasteviews'] = "Wyświetlenia wklejki"; $lang['pasteviews'] = "Wyświetlenia wklejki";
$lang['wentwrong'] = "Coś poszło nie tak."; $lang['wentwrong'] = "Coś poszło nie tak.";
$lang['versent'] = "Link weryfikacyjny został wysłany na podany adres e-mail."; $lang['versent'] = "Link weryfikacyjny został wysłany na podany adres e-mail.";
$lang['modpaste'] = "Modyfikuj wklejkę"; $lang['modpaste'] = "Modyfikuj wklejkę";
$lang['newpaste'] = "Nowa wklejka"; $lang['newpaste'] = "Nowa wklejka";
$lang['highlighting'] = "Podświetlanie składni"; $lang['highlighting'] = "Podświetlanie składni";
$lang['expiration'] = "Data ważności wklejki"; $lang['expiration'] = "Data ważności wklejki";
$lang['visibility'] = "Widoczność wklejki"; $lang['visibility'] = "Widoczność wklejki";
$lang['pwopt'] = "Hasło (opcjonalne)"; $lang['pwopt'] = "Hasło (opcjonalne)";
$lang['encrypt'] = "Zaszyfruj w bazie danych"; $lang['encrypt'] = "Zaszyfruj w bazie danych";
$lang['entercode'] = "Wprowadź kod"; $lang['entercode'] = "Wprowadź kod";
$lang['almostthere'] = "Już prawie. Pozostał jeden krok."; $lang['almostthere'] = "Już prawie. Pozostał jeden krok.";
$lang['username'] = "Nazwa użytkownika"; $lang['username'] = "Nazwa użytkownika";
$lang['autogen'] = "Wygenerowana nazwa"; $lang['autogen'] = "Wygenerowana nazwa";
$lang['setuser'] = "Ustaw swoją nazwę"; $lang['setuser'] = "Ustaw swoją nazwę";
$lang['keepuser'] = "Pozostaw wygenerowaną nazwę"; $lang['keepuser'] = "Pozostaw wygenerowaną nazwę";
$lang['enterpwd'] = "Wprowadź hasło"; $lang['enterpwd'] = "Wprowadź hasło";
$lang['totalpastes'] = "Wklejki łącznie:"; $lang['totalpastes'] = "Wklejki łącznie:";
$lang['membtype'] = "Rodzaj konta:"; $lang['membtype'] = "Rodzaj konta:";
$lang['email'] = "E-mail"; $lang['email'] = "E-mail";
$lang['fullname'] = "Nazwa"; $lang['fullname'] = "Nazwa";
$lang['chgpwd'] = "Zmień hasło"; $lang['chgpwd'] = "Zmień hasło";
$lang['curpwd'] = "Obecne hasło"; $lang['curpwd'] = "Obecne hasło";
$lang['newpwd'] = "Nowe hasło"; $lang['newpwd'] = "Nowe hasło";
$lang['confpwd'] = "Potwierdź hasło"; $lang['confpwd'] = "Potwierdź hasło";
$lang['mypastes'] = "Moje wklejki"; $lang['mypastes'] = "Moje wklejki";
$lang['viewpastes'] = "Pokaż wszystkie moje wklejki"; $lang['viewpastes'] = "Pokaż wszystkie moje wklejki";
$lang['recentpastes'] = "Najnowsze wklejki"; $lang['recentpastes'] = "Najnowsze wklejki";
$lang['user_public_pastes'] = "Wklejki użytkownika"; $lang['user_public_pastes'] = "Wklejki użytkownika";
$lang['yourpastes'] = "Twoje wklejki"; $lang['yourpastes'] = "Twoje wklejki";
$lang['mypastestitle'] = "Wszystkie twoje wklejki w jednym miejscu."; $lang['mypastestitle'] = "Wszystkie twoje wklejki w jednym miejscu.";
$lang['delete'] = "Usuń"; $lang['delete'] = "Usuń";
$lang['highlighted'] = "Tekst jest zaznaczony, naciśnij Ctrl+C aby skopiować. (&#8984;+C na Macu)"; $lang['highlighted'] = "Tekst jest zaznaczony, naciśnij Ctrl+C aby skopiować. (&#8984;+C na Macu)";
$lang['newpaste'] = "Nowa wklejka"; $lang['newpaste'] = "Nowa wklejka";
$lang['download'] = "Pobierz"; $lang['download'] = "Pobierz";
$lang['showlineno'] = "Pokaż/ukryj wiersz nr."; $lang['showlineno'] = "Pokaż/ukryj wiersz nr.";
$lang['copyto'] = "Kopiuj tekst do schowka"; $lang['copyto'] = "Kopiuj tekst do schowka";
$lang['rawpaste'] = "Surowy plik wklejki"; $lang['rawpaste'] = "Surowy plik wklejki";
$lang['membersince'] = "Data dołączenia: "; $lang['membersince'] = "Data dołączenia: ";
$lang['delete_error_invalid'] = "Błąd: Nie usunięto wklejki. Wklejka nie istnieje lub nie jesteś jej autorem."; $lang['delete_error_invalid'] = "Błąd: Nie usunięto wklejki. Wklejka nie istnieje lub nie jesteś jej autorem.";
$lang['not_logged_in'] = "Błąd: Musisz zalogować się, aby to zrobić."; $lang['not_logged_in'] = "Błąd: Musisz zalogować się, aby to zrobić.";
$lang['public'] = "Publiczna"; $lang['public'] = "Publiczna";
$lang['unlisted'] = "Niewidoczna"; $lang['unlisted'] = "Niewidoczna";
$lang['private'] = "Prywatna"; $lang['private'] = "Prywatna";
$lang['hello'] = "Witaj"; $lang['hello'] = "Witaj";
$lang['profile-message'] = "To jest strona twojego konta, na której możesz zarządzać wklejkami.<br /> Znajdują się tu twoje wszystkie prywatne, publiczne i niewidoczne wklejki. Możesz je tutaj usunąć. Inni użytkownicy mogą zobaczyć tu tylko twoje publiczne wklejki."; $lang['profile-message'] = "To jest strona twojego konta, na której możesz zarządzać wklejkami.<br /> Znajdują się tu twoje wszystkie prywatne, publiczne i niewidoczne wklejki. Możesz je tutaj usunąć. Inni użytkownicy mogą zobaczyć tu tylko twoje publiczne wklejki.";
$lang['profile-stats'] = "Twoje statystyki:"; $lang['profile-stats'] = "Twoje statystyki:";
$lang['profile-total-pastes'] = "Wklejki łącznie:"; $lang['profile-total-pastes'] = "Wklejki łącznie:";
$lang['profile-total-pub'] = "Publiczne wklejki:"; $lang['profile-total-pub'] = "Publiczne wklejki:";
$lang['profile-total-unl'] = "Niewidoczne wklejki:"; $lang['profile-total-unl'] = "Niewidoczne wklejki:";
$lang['profile-total-pri'] = "Prywatne wklejki:"; $lang['profile-total-pri'] = "Prywatne wklejki:";
$lang['profile-total-views'] = "Wyświetlenia wszystkich wklejek:"; $lang['profile-total-views'] = "Wyświetlenia wszystkich wklejek:";
$lang['embed-hosted-by'] = "przechowywane na"; $lang['embed-hosted-by'] = "przechowywane na";
$lang['view-raw'] = "Surowy plik"; $lang['view-raw'] = "Surowy plik";
?> ?>

File diff suppressed because it is too large Load diff

View file

@ -27,8 +27,7 @@
* @author Jim Jagielski (jimjag) <jimjag@gmail.com> * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
*/ */
class POP3 class POP3 {
{
/** /**
* The POP3 PHPMailer Version number. * The POP3 PHPMailer Version number.
* @var string * @var string
@ -162,8 +161,7 @@ class POP3
* @param integer $debug_level * @param integer $debug_level
* @return boolean * @return boolean
*/ */
public function authorise($host, $port = false, $timeout = false, $username = '', $password = '', $debug_level = 0) public function authorise($host, $port = false, $timeout = false, $username = '', $password = '', $debug_level = 0) {
{
$this->host = $host; $this->host = $host;
// If no port value provided, use default // If no port value provided, use default
if (false === $port) { if (false === $port) {
@ -204,8 +202,7 @@ class POP3
* @param integer $tval * @param integer $tval
* @return boolean * @return boolean
*/ */
public function connect($host, $port = false, $tval = 30) public function connect($host, $port = false, $tval = 30) {
{
// Are we already connected? // Are we already connected?
if ($this->connected) { if ($this->connected) {
return true; return true;
@ -263,8 +260,7 @@ class POP3
* @param string $password * @param string $password
* @return boolean * @return boolean
*/ */
public function login($username = '', $password = '') public function login($username = '', $password = '') {
{
if (!$this->connected) { if (!$this->connected) {
$this->setError('Not connected to POP3 server'); $this->setError('Not connected to POP3 server');
} }
@ -293,8 +289,7 @@ class POP3
* Disconnect from the POP3 server. * Disconnect from the POP3 server.
* @access public * @access public
*/ */
public function disconnect() public function disconnect() {
{
$this->sendString('QUIT'); $this->sendString('QUIT');
//The QUIT command may cause the daemon to exit, which will kill our connection //The QUIT command may cause the daemon to exit, which will kill our connection
//So ignore errors here //So ignore errors here
@ -312,8 +307,7 @@ class POP3
* @return string * @return string
* @access protected * @access protected
*/ */
protected function getResponse($size = 128) protected function getResponse($size = 128) {
{
$response = fgets($this->pop_conn, $size); $response = fgets($this->pop_conn, $size);
if ($this->do_debug >= 1) { if ($this->do_debug >= 1) {
echo "Server -> Client: $response"; echo "Server -> Client: $response";
@ -327,8 +321,7 @@ class POP3
* @return integer * @return integer
* @access protected * @access protected
*/ */
protected function sendString($string) protected function sendString($string) {
{
if ($this->pop_conn) { if ($this->pop_conn) {
if ($this->do_debug >= 2) { //Show client messages when debug >= 2 if ($this->do_debug >= 2) { //Show client messages when debug >= 2
echo "Client -> Server: $string"; echo "Client -> Server: $string";
@ -345,8 +338,7 @@ class POP3
* @return boolean * @return boolean
* @access protected * @access protected
*/ */
protected function checkResponse($string) protected function checkResponse($string) {
{
if (substr($string, 0, 3) !== '+OK') { if (substr($string, 0, 3) !== '+OK') {
$this->setError(array( $this->setError(array(
'error' => "Server reported an error: $string", 'error' => "Server reported an error: $string",
@ -365,8 +357,7 @@ class POP3
* @param $error * @param $error
* @access protected * @access protected
*/ */
protected function setError($error) protected function setError($error) {
{
$this->errors[] = $error; $this->errors[] = $error;
if ($this->do_debug >= 1) { if ($this->do_debug >= 1) {
echo '<pre>'; echo '<pre>';
@ -381,8 +372,7 @@ class POP3
* Get an array of error messages, if any. * Get an array of error messages, if any.
* @return array * @return array
*/ */
public function getErrors() public function getErrors() {
{
return $this->errors; return $this->errors;
} }
@ -394,8 +384,7 @@ class POP3
* @param integer $errline * @param integer $errline
* @access protected * @access protected
*/ */
protected function catchWarning($errno, $errstr, $errfile, $errline) protected function catchWarning($errno, $errstr, $errfile, $errline) {
{
$this->setError(array( $this->setError(array(
'error' => "Connecting to the POP3 server raised a PHP warning: ", 'error' => "Connecting to the POP3 server raised a PHP warning: ",
'errno' => $errno, 'errno' => $errno,

View file

@ -24,8 +24,7 @@
* @author Chris Ryan * @author Chris Ryan
* @author Marcus Bointon <phpmailer@synchromedia.co.uk> * @author Marcus Bointon <phpmailer@synchromedia.co.uk>
*/ */
class SMTP class SMTP {
{
/** /**
* The PHPMailer SMTP version number. * The PHPMailer SMTP version number.
* @var string * @var string
@ -150,16 +149,16 @@ class SMTP
*/ */
public $Timelimit = 300; public $Timelimit = 300;
/** /**
* @var array patterns to extract smtp transaction id from smtp reply * @var array patterns to extract smtp transaction id from smtp reply
* Only first capture group will be use, use non-capturing group to deal with it * Only first capture group will be use, use non-capturing group to deal with it
* Extend this class to override this property to fulfil your needs. * Extend this class to override this property to fulfil your needs.
*/ */
protected $smtp_transaction_id_patterns = array( protected $smtp_transaction_id_patterns = array(
'exim' => '/[0-9]{3} OK id=(.*)/', 'exim' => '/[0-9]{3} OK id=(.*)/',
'sendmail' => '/[0-9]{3} 2.0.0 (.*) Message/', 'sendmail' => '/[0-9]{3} 2.0.0 (.*) Message/',
'postfix' => '/[0-9]{3} 2.0.0 Ok: queued as (.*)/' 'postfix' => '/[0-9]{3} 2.0.0 Ok: queued as (.*)/'
); );
/** /**
* The socket for the server connection. * The socket for the server connection.
@ -204,14 +203,13 @@ class SMTP
/** /**
* Output debugging info via a user-selected method. * Output debugging info via a user-selected method.
* @see SMTP::$Debugoutput
* @see SMTP::$do_debug
* @param string $str Debug string to output * @param string $str Debug string to output
* @param integer $level The debug level of this message; see DEBUG_* constants * @param integer $level The debug level of this message; see DEBUG_* constants
* @return void * @return void
* @see SMTP::$do_debug
* @see SMTP::$Debugoutput
*/ */
protected function edebug($str, $level = 0) protected function edebug($str, $level = 0) {
{
if ($level > $this->do_debug) { if ($level > $this->do_debug) {
return; return;
} }
@ -228,21 +226,21 @@ class SMTP
case 'html': case 'html':
//Cleans up output a bit for a better looking, HTML-safe output //Cleans up output a bit for a better looking, HTML-safe output
echo htmlentities( echo htmlentities(
preg_replace('/[\r\n]+/', '', $str), preg_replace('/[\r\n]+/', '', $str),
ENT_QUOTES, ENT_QUOTES,
'UTF-8' 'UTF-8'
) )
. "<br>\n"; . "<br>\n";
break; break;
case 'echo': case 'echo':
default: default:
//Normalize line breaks //Normalize line breaks
$str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str); $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
echo gmdate('Y-m-d H:i:s') . "\t" . str_replace( echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
"\n", "\n",
"\n \t ", "\n \t ",
trim($str) trim($str)
)."\n"; ) . "\n";
} }
} }
@ -255,8 +253,7 @@ class SMTP
* @access public * @access public
* @return boolean * @return boolean
*/ */
public function connect($host, $port = null, $timeout = 30, $options = array()) public function connect($host, $port = null, $timeout = 30, $options = array()) {
{
static $streamok; static $streamok;
//This is enabled by default since 5.0.0 but some providers disable it //This is enabled by default since 5.0.0 but some providers disable it
//Check this once and cache the result //Check this once and cache the result
@ -276,7 +273,7 @@ class SMTP
} }
// Connect to the SMTP server // Connect to the SMTP server
$this->edebug( $this->edebug(
"Connection: opening to $host:$port, timeout=$timeout, options=".var_export($options, true), "Connection: opening to $host:$port, timeout=$timeout, options=" . var_export($options, true),
self::DEBUG_CONNECTION self::DEBUG_CONNECTION
); );
$errno = 0; $errno = 0;
@ -345,8 +342,7 @@ class SMTP
* @access public * @access public
* @return boolean * @return boolean
*/ */
public function startTLS() public function startTLS() {
{
if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) { if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) {
return false; return false;
} }
@ -375,7 +371,6 @@ class SMTP
/** /**
* Perform SMTP authentication. * Perform SMTP authentication.
* Must be run after hello(). * Must be run after hello().
* @see hello()
* @param string $username The user name * @param string $username The user name
* @param string $password The password * @param string $password The password
* @param string $authtype The auth type (PLAIN, LOGIN, NTLM, CRAM-MD5, XOAUTH2) * @param string $authtype The auth type (PLAIN, LOGIN, NTLM, CRAM-MD5, XOAUTH2)
@ -383,6 +378,7 @@ class SMTP
* @param string $workstation The auth workstation for NTLM * @param string $workstation The auth workstation for NTLM
* @param null|OAuth $OAuth An optional OAuth instance (@see PHPMailerOAuth) * @param null|OAuth $OAuth An optional OAuth instance (@see PHPMailerOAuth)
* @return bool True if successfully authenticated.* @access public * @return bool True if successfully authenticated.* @access public
* @see hello()
*/ */
public function authenticate( public function authenticate(
$username, $username,
@ -398,7 +394,7 @@ class SMTP
} }
if (array_key_exists('EHLO', $this->server_caps)) { if (array_key_exists('EHLO', $this->server_caps)) {
// SMTP extensions are available. Let's try to find a proper authentication method // SMTP extensions are available. Let's try to find a proper authentication method
if (!array_key_exists('AUTH', $this->server_caps)) { if (!array_key_exists('AUTH', $this->server_caps)) {
$this->setError('Authentication is not allowed at this stage'); $this->setError('Authentication is not allowed at this stage');
@ -424,7 +420,7 @@ class SMTP
$this->setError('No supported authentication methods found'); $this->setError('No supported authentication methods found');
return false; return false;
} }
self::edebug('Auth method selected: '.$authtype, self::DEBUG_LOWLEVEL); self::edebug('Auth method selected: ' . $authtype, self::DEBUG_LOWLEVEL);
} }
if (!in_array($authtype, $this->server_caps['AUTH'])) { if (!in_array($authtype, $this->server_caps['AUTH'])) {
@ -550,12 +546,11 @@ class SMTP
* Works like hash_hmac('md5', $data, $key) * Works like hash_hmac('md5', $data, $key)
* in case that function is not available * in case that function is not available
* @param string $data The data to hash * @param string $data The data to hash
* @param string $key The key to hash with * @param string $key The key to hash with
* @access protected * @access protected
* @return string * @return string
*/ */
protected function hmac($data, $key) protected function hmac($data, $key) {
{
if (function_exists('hash_hmac')) { if (function_exists('hash_hmac')) {
return hash_hmac('md5', $data, $key); return hash_hmac('md5', $data, $key);
} }
@ -586,8 +581,7 @@ class SMTP
* @access public * @access public
* @return boolean True if connected. * @return boolean True if connected.
*/ */
public function connected() public function connected() {
{
if (is_resource($this->smtp_conn)) { if (is_resource($this->smtp_conn)) {
$sock_status = stream_get_meta_data($this->smtp_conn); $sock_status = stream_get_meta_data($this->smtp_conn);
if ($sock_status['eof']) { if ($sock_status['eof']) {
@ -607,12 +601,11 @@ class SMTP
/** /**
* Close the socket and clean up the state of the class. * Close the socket and clean up the state of the class.
* Don't use this function without first trying to use QUIT. * Don't use this function without first trying to use QUIT.
* @return void
* @see quit() * @see quit()
* @access public * @access public
* @return void
*/ */
public function close() public function close() {
{
$this->setError(''); $this->setError('');
$this->server_caps = null; $this->server_caps = null;
$this->helo_rply = null; $this->helo_rply = null;
@ -636,8 +629,7 @@ class SMTP
* @access public * @access public
* @return boolean * @return boolean
*/ */
public function data($msg_data) public function data($msg_data) {
{
//This will use the standard timelimit //This will use the standard timelimit
if (!$this->sendCommand('DATA', 'DATA', 354)) { if (!$this->sendCommand('DATA', 'DATA', 354)) {
return false; return false;
@ -725,8 +717,7 @@ class SMTP
* @access public * @access public
* @return boolean * @return boolean
*/ */
public function hello($host = '') public function hello($host = '') {
{
//Try extended hello first (RFC 2821) //Try extended hello first (RFC 2821)
return (boolean)($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host)); return (boolean)($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host));
} }
@ -734,14 +725,13 @@ class SMTP
/** /**
* Send an SMTP HELO or EHLO command. * Send an SMTP HELO or EHLO command.
* Low-level implementation used by hello() * Low-level implementation used by hello()
* @see hello()
* @param string $hello The HELO string * @param string $hello The HELO string
* @param string $host The hostname to say we are * @param string $host The hostname to say we are
* @access protected * @access protected
* @return boolean * @return boolean
* @see hello()
*/ */
protected function sendHello($hello, $host) protected function sendHello($hello, $host) {
{
$noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250); $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250);
$this->helo_rply = $this->last_reply; $this->helo_rply = $this->last_reply;
if ($noerror) { if ($noerror) {
@ -758,8 +748,7 @@ class SMTP
* @access protected * @access protected
* @param string $type - 'HELO' or 'EHLO' * @param string $type - 'HELO' or 'EHLO'
*/ */
protected function parseHelloFields($type) protected function parseHelloFields($type) {
{
$this->server_caps = array(); $this->server_caps = array();
$lines = explode("\n", $this->helo_rply); $lines = explode("\n", $this->helo_rply);
@ -805,8 +794,7 @@ class SMTP
* @access public * @access public
* @return boolean * @return boolean
*/ */
public function mail($from) public function mail($from) {
{
$useVerp = ($this->do_verp ? ' XVERP' : ''); $useVerp = ($this->do_verp ? ' XVERP' : '');
return $this->sendCommand( return $this->sendCommand(
'MAIL FROM', 'MAIL FROM',
@ -823,8 +811,7 @@ class SMTP
* @access public * @access public
* @return boolean * @return boolean
*/ */
public function quit($close_on_error = true) public function quit($close_on_error = true) {
{
$noerror = $this->sendCommand('QUIT', 'QUIT', 221); $noerror = $this->sendCommand('QUIT', 'QUIT', 221);
$err = $this->error; //Save any error $err = $this->error; //Save any error
if ($noerror or $close_on_error) { if ($noerror or $close_on_error) {
@ -843,8 +830,7 @@ class SMTP
* @access public * @access public
* @return boolean * @return boolean
*/ */
public function recipient($address) public function recipient($address) {
{
return $this->sendCommand( return $this->sendCommand(
'RCPT TO', 'RCPT TO',
'RCPT TO:<' . $address . '>', 'RCPT TO:<' . $address . '>',
@ -859,8 +845,7 @@ class SMTP
* @access public * @access public
* @return boolean True on success. * @return boolean True on success.
*/ */
public function reset() public function reset() {
{
return $this->sendCommand('RSET', 'RSET', 250); return $this->sendCommand('RSET', 'RSET', 250);
} }
@ -872,8 +857,7 @@ class SMTP
* @access protected * @access protected
* @return boolean True on success. * @return boolean True on success.
*/ */
protected function sendCommand($command, $commandstring, $expect) protected function sendCommand($command, $commandstring, $expect) {
{
if (!$this->connected()) { if (!$this->connected()) {
$this->setError("Called $command without being connected"); $this->setError("Called $command without being connected");
return false; return false;
@ -893,7 +877,7 @@ class SMTP
$code_ex = (count($matches) > 2 ? $matches[2] : null); $code_ex = (count($matches) > 2 ? $matches[2] : null);
// Cut off error code from each response line // Cut off error code from each response line
$detail = preg_replace( $detail = preg_replace(
"/{$code}[ -]".($code_ex ? str_replace('.', '\\.', $code_ex).' ' : '')."/m", "/{$code}[ -]" . ($code_ex ? str_replace('.', '\\.', $code_ex) . ' ' : '') . "/m",
'', '',
$this->last_reply $this->last_reply
); );
@ -937,8 +921,7 @@ class SMTP
* @access public * @access public
* @return boolean * @return boolean
*/ */
public function sendAndMail($from) public function sendAndMail($from) {
{
return $this->sendCommand('SAML', "SAML FROM:$from", 250); return $this->sendCommand('SAML', "SAML FROM:$from", 250);
} }
@ -948,8 +931,7 @@ class SMTP
* @access public * @access public
* @return boolean * @return boolean
*/ */
public function verify($name) public function verify($name) {
{
return $this->sendCommand('VRFY', "VRFY $name", array(250, 251)); return $this->sendCommand('VRFY', "VRFY $name", array(250, 251));
} }
@ -959,8 +941,7 @@ class SMTP
* @access public * @access public
* @return boolean * @return boolean
*/ */
public function noop() public function noop() {
{
return $this->sendCommand('NOOP', 'NOOP', 250); return $this->sendCommand('NOOP', 'NOOP', 250);
} }
@ -973,8 +954,7 @@ class SMTP
* @access public * @access public
* @return boolean * @return boolean
*/ */
public function turn() public function turn() {
{
$this->setError('The SMTP TURN command is not implemented'); $this->setError('The SMTP TURN command is not implemented');
$this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT); $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT);
return false; return false;
@ -986,8 +966,7 @@ class SMTP
* @access public * @access public
* @return integer|boolean The number of bytes sent to the server or false on error * @return integer|boolean The number of bytes sent to the server or false on error
*/ */
public function client_send($data) public function client_send($data) {
{
$this->edebug("CLIENT -> SERVER: $data", self::DEBUG_CLIENT); $this->edebug("CLIENT -> SERVER: $data", self::DEBUG_CLIENT);
return fwrite($this->smtp_conn, $data); return fwrite($this->smtp_conn, $data);
} }
@ -997,8 +976,7 @@ class SMTP
* @access public * @access public
* @return array * @return array
*/ */
public function getError() public function getError() {
{
return $this->error; return $this->error;
} }
@ -1007,8 +985,7 @@ class SMTP
* @access public * @access public
* @return array|null * @return array|null
*/ */
public function getServerExtList() public function getServerExtList() {
{
return $this->server_caps; return $this->server_caps;
} }
@ -1031,8 +1008,7 @@ class SMTP
* @param string $name Name of SMTP extension or 'HELO'|'EHLO' * @param string $name Name of SMTP extension or 'HELO'|'EHLO'
* @return mixed * @return mixed
*/ */
public function getServerExt($name) public function getServerExt($name) {
{
if (!$this->server_caps) { if (!$this->server_caps) {
$this->setError('No HELO/EHLO was sent'); $this->setError('No HELO/EHLO was sent');
return null; return null;
@ -1058,8 +1034,7 @@ class SMTP
* @access public * @access public
* @return string * @return string
*/ */
public function getLastReply() public function getLastReply() {
{
return $this->last_reply; return $this->last_reply;
} }
@ -1072,8 +1047,7 @@ class SMTP
* @access protected * @access protected
* @return string * @return string
*/ */
protected function get_lines() protected function get_lines() {
{
// If the connection is bad, give up straight away // If the connection is bad, give up straight away
if (!is_resource($this->smtp_conn)) { if (!is_resource($this->smtp_conn)) {
return ''; return '';
@ -1105,7 +1079,7 @@ class SMTP
// Now check if reads took too long // Now check if reads took too long
if ($endtime and time() > $endtime) { if ($endtime and time() > $endtime) {
$this->edebug( $this->edebug(
'SMTP -> get_lines(): timelimit reached ('. 'SMTP -> get_lines(): timelimit reached (' .
$this->Timelimit . ' sec)', $this->Timelimit . ' sec)',
self::DEBUG_LOWLEVEL self::DEBUG_LOWLEVEL
); );
@ -1119,8 +1093,7 @@ class SMTP
* Enable or disable VERP address generation. * Enable or disable VERP address generation.
* @param boolean $enabled * @param boolean $enabled
*/ */
public function setVerp($enabled = false) public function setVerp($enabled = false) {
{
$this->do_verp = $enabled; $this->do_verp = $enabled;
} }
@ -1128,8 +1101,7 @@ class SMTP
* Get VERP address generation mode. * Get VERP address generation mode.
* @return boolean * @return boolean
*/ */
public function getVerp() public function getVerp() {
{
return $this->do_verp; return $this->do_verp;
} }
@ -1140,8 +1112,7 @@ class SMTP
* @param string $smtp_code An associated SMTP error code * @param string $smtp_code An associated SMTP error code
* @param string $smtp_code_ex Extended SMTP code * @param string $smtp_code_ex Extended SMTP code
*/ */
protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '') protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '') {
{
$this->error = array( $this->error = array(
'error' => $message, 'error' => $message,
'detail' => $detail, 'detail' => $detail,
@ -1154,8 +1125,7 @@ class SMTP
* Set debug output method. * Set debug output method.
* @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it. * @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it.
*/ */
public function setDebugOutput($method = 'echo') public function setDebugOutput($method = 'echo') {
{
$this->Debugoutput = $method; $this->Debugoutput = $method;
} }
@ -1163,8 +1133,7 @@ class SMTP
* Get debug output method. * Get debug output method.
* @return string * @return string
*/ */
public function getDebugOutput() public function getDebugOutput() {
{
return $this->Debugoutput; return $this->Debugoutput;
} }
@ -1172,8 +1141,7 @@ class SMTP
* Set debug output level. * Set debug output level.
* @param integer $level * @param integer $level
*/ */
public function setDebugLevel($level = 0) public function setDebugLevel($level = 0) {
{
$this->do_debug = $level; $this->do_debug = $level;
} }
@ -1181,8 +1149,7 @@ class SMTP
* Get debug output level. * Get debug output level.
* @return integer * @return integer
*/ */
public function getDebugLevel() public function getDebugLevel() {
{
return $this->do_debug; return $this->do_debug;
} }
@ -1190,8 +1157,7 @@ class SMTP
* Set SMTP timeout. * Set SMTP timeout.
* @param integer $timeout * @param integer $timeout
*/ */
public function setTimeout($timeout = 0) public function setTimeout($timeout = 0) {
{
$this->Timeout = $timeout; $this->Timeout = $timeout;
} }
@ -1199,8 +1165,7 @@ class SMTP
* Get SMTP timeout. * Get SMTP timeout.
* @return integer * @return integer
*/ */
public function getTimeout() public function getTimeout() {
{
return $this->Timeout; return $this->Timeout;
} }
@ -1209,8 +1174,7 @@ class SMTP
* @param integer $errno The error number returned by PHP. * @param integer $errno The error number returned by PHP.
* @param string $errmsg The error message returned by PHP. * @param string $errmsg The error message returned by PHP.
*/ */
protected function errorHandler($errno, $errmsg) protected function errorHandler($errno, $errmsg) {
{
$notice = 'Connection: Failed to connect to server.'; $notice = 'Connection: Failed to connect to server.';
$this->setError( $this->setError(
$notice, $notice,
@ -1223,27 +1187,26 @@ class SMTP
); );
} }
/** /**
* Will return the ID of the last smtp transaction based on a list of patterns provided * Will return the ID of the last smtp transaction based on a list of patterns provided
* in SMTP::$smtp_transaction_id_patterns. * in SMTP::$smtp_transaction_id_patterns.
* If no reply has been received yet, it will return null. * If no reply has been received yet, it will return null.
* If no pattern has been matched, it will return false. * If no pattern has been matched, it will return false.
* @return bool|null|string * @return bool|null|string
*/ */
public function getLastTransactionID() public function getLastTransactionID() {
{ $reply = $this->getLastReply();
$reply = $this->getLastReply();
if (empty($reply)) { if (empty($reply)) {
return null; return null;
} }
foreach($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) { foreach ($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) {
if(preg_match($smtp_transaction_id_pattern, $reply, $matches)) { if (preg_match($smtp_transaction_id_pattern, $reply, $matches)) {
return $matches[1]; return $matches[1];
} }
} }
return false; return false;
} }
} }

View file

@ -14,63 +14,61 @@
*/ */
error_reporting(1); error_reporting(1);
function default_mail($admin_mail, $admin_name, $sent_mail, $subject, $body) function default_mail($admin_mail, $admin_name, $sent_mail, $subject, $body) {
{
// Functions // Functions
require_once('class.phpmailer.php'); require_once('class.phpmailer.php');
$mail = new PHPMailer(); $mail = new PHPMailer();
$body = stripslashes ($body); $body = stripslashes($body);
$mail->AddReplyTo($admin_mail, $admin_name); $mail->AddReplyTo($admin_mail, $admin_name);
$mail->SetFrom($admin_mail, $admin_name); $mail->SetFrom($admin_mail, $admin_name);
$mail->AddReplyTo($admin_mail, $admin_name); $mail->AddReplyTo($admin_mail, $admin_name);
$address = $sent_mail; $address = $sent_mail;
$mail->AddAddress($address); $mail->AddAddress($address);
$mail->Subject = $subject; $mail->Subject = $subject;
$mail->MsgHTML($body); $mail->MsgHTML($body);
$mail->AltBody = "To view the message, please use an HTML compatible viewer"; $mail->AltBody = "To view the message, please use an HTML compatible viewer";
if (!$mail->Send()) { if (!$mail->Send()) {
$msg = "Mailer Error: " . $mail->ErrorInfo; $msg = "Mailer Error: " . $mail->ErrorInfo;
} else { } else {
$msg = "Message has been sent"; $msg = "Message has been sent";
} }
return $msg; return $msg;
} }
function smtp_mail($smtp_host, $smtp_port = 587, $smtp_auth, $smtp_user, $smtp_pass, $smtp_sec = 'tls', $admin_mail, $admin_name, $sent_mail, $subject, $body) function smtp_mail($smtp_host, $smtp_port = 587, $smtp_auth, $smtp_user, $smtp_pass, $smtp_sec = 'tls', $admin_mail, $admin_name, $sent_mail, $subject, $body) {
{
require_once('class.phpmailer.php'); require_once('class.phpmailer.php');
require_once('class.smtp.php'); require_once('class.smtp.php');
$mail = new PHPMailer; $mail = new PHPMailer;
$mail->IsSMTP(); // Set mailer to use SMTP $mail->IsSMTP(); // Set mailer to use SMTP
$mail->Host = $smtp_host; // Specify main and backup server $mail->Host = $smtp_host; // Specify main and backup server
$mail->Port = $smtp_port; // Set the SMTP port $mail->Port = $smtp_port; // Set the SMTP port
$mail->SMTPAuth = $smtp_auth; // Enable SMTP authentication $mail->SMTPAuth = $smtp_auth; // Enable SMTP authentication
$mail->Username = $smtp_user; // SMTP username $mail->Username = $smtp_user; // SMTP username
$mail->Password = $smtp_pass; // SMTP password $mail->Password = $smtp_pass; // SMTP password
$mail->SMTPSecure = $smtp_sec; // Enable encryption, 'ssl' also accepted $mail->SMTPSecure = $smtp_sec; // Enable encryption, 'ssl' also accepted
$mail->From = $admin_mail; $mail->From = $admin_mail;
$mail->FromName = $admin_name; $mail->FromName = $admin_name;
$mail->AddAddress($sent_mail); // Add a recipient $mail->AddAddress($sent_mail); // Add a recipient
$mail->IsHTML(true); // Set email format to HTML $mail->IsHTML(true); // Set email format to HTML
$mail->Subject = $subject; $mail->Subject = $subject;
$mail->Body = $body; $mail->Body = $body;
$mail->AltBody = $body; $mail->AltBody = $body;
if (!$mail->Send()) { if (!$mail->Send()) {
$msg = 'Mailer Error: ' . $mail->ErrorInfo; $msg = 'Mailer Error: ' . $mail->ErrorInfo;
} else { } else {
@ -78,4 +76,5 @@ function smtp_mail($smtp_host, $smtp_port = 587, $smtp_auth, $smtp_user, $smtp_p
} }
return $msg; return $msg;
} }
?> ?>

View file

@ -20,7 +20,7 @@ require_once('includes/functions.php');
// Current date & user IP // Current date & user IP
$date = date('jS F Y'); $date = date('jS F Y');
$ip = $_SERVER['REMOTE_ADDR']; $ip = $_SERVER['REMOTE_ADDR'];
// Database Connection // Database Connection
$con = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname); $con = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname);
@ -28,29 +28,29 @@ if (mysqli_connect_errno()) {
die("Unable to connect to database"); die("Unable to connect to database");
} }
// Get site info // Get site info
$query = "SELECT * FROM site_info"; $query = "SELECT * FROM site_info";
$result = mysqli_query($con, $query); $result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) { while ($row = mysqli_fetch_array($result)) {
$title = Trim($row['title']); $title = Trim($row['title']);
$des = Trim($row['des']); $des = Trim($row['des']);
$baseurl = Trim($row['baseurl']); $baseurl = Trim($row['baseurl']);
$keyword = Trim($row['keyword']); $keyword = Trim($row['keyword']);
$site_name = Trim($row['site_name']); $site_name = Trim($row['site_name']);
$email = Trim($row['email']); $email = Trim($row['email']);
$twit = Trim($row['twit']); $twit = Trim($row['twit']);
$face = Trim($row['face']); $face = Trim($row['face']);
$gplus = Trim($row['gplus']); $gplus = Trim($row['gplus']);
$ga = Trim($row['ga']); $ga = Trim($row['ga']);
$additional_scripts = Trim($row['additional_scripts']); $additional_scripts = Trim($row['additional_scripts']);
} }
// Set theme and language // Set theme and language
$query = "SELECT * FROM interface"; $query = "SELECT * FROM interface";
$result = mysqli_query($con, $query); $result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) { while ($row = mysqli_fetch_array($result)) {
$default_lang = Trim($row['lang']); $default_lang = Trim($row['lang']);
$default_theme = Trim($row['theme']); $default_theme = Trim($row['theme']);
} }
@ -74,13 +74,13 @@ if ($_SERVER['REQUEST_METHOD'] == 'POST') {
} else { } else {
$res = isValidUsername($new_username); $res = isValidUsername($new_username);
if ($res == '1') { if ($res == '1') {
$query = "SELECT * FROM users WHERE username='$new_username'"; $query = "SELECT * FROM users WHERE username='$new_username'";
$result = mysqli_query($con, $query); $result = mysqli_query($con, $query);
if (mysqli_num_rows($result) > 0) { if (mysqli_num_rows($result) > 0) {
$error = $lang['userexists']; //"Username already taken"; $error = $lang['userexists']; //"Username already taken";
} else { } else {
$client_id = Trim($_SESSION['oauth_uid']); $client_id = Trim($_SESSION['oauth_uid']);
$query = "UPDATE users SET username='$new_username' WHERE oauth_uid='$client_id'"; $query = "UPDATE users SET username='$new_username' WHERE oauth_uid='$client_id'";
mysqli_query($con, $query); mysqli_query($con, $query);
if (mysqli_error($con)) { if (mysqli_error($con)) {
$error = $lang['databaseerror']; // "Unable to access database."; $error = $lang['databaseerror']; // "Unable to access database.";
@ -91,7 +91,7 @@ if ($_SERVER['REQUEST_METHOD'] == 'POST') {
} }
} }
} else { } else {
$error = $lang['usernotvalid']; //"Username not vaild"; $error = $lang['usernotvalid']; //"Username not vaild";
$username = Trim($_SESSION['username']); $username = Trim($_SESSION['username']);
goto OutPut; goto OutPut;
} }

View file

@ -21,15 +21,15 @@ require_once "Google/Http/Request.php";
* @author Chris Chabot <chabotc@google.com> * @author Chris Chabot <chabotc@google.com>
* *
*/ */
abstract class Google_Auth_Abstract abstract class Google_Auth_Abstract {
{ /**
/** * An utility function that first calls $this->auth->sign($request) and then
* An utility function that first calls $this->auth->sign($request) and then * executes makeRequest() on that signed request. Used for when a request
* executes makeRequest() on that signed request. Used for when a request * should be authenticated
* should be authenticated * @param Google_Http_Request $request
* @param Google_Http_Request $request * @return Google_Http_Request $request
* @return Google_Http_Request $request */
*/ abstract public function authenticatedRequest(Google_Http_Request $request);
abstract public function authenticatedRequest(Google_Http_Request $request);
abstract public function sign(Google_Http_Request $request); abstract public function sign(Google_Http_Request $request);
} }

View file

@ -20,6 +20,7 @@
* which is 5.3 and above only, so if you include this in a PHP 5.2 * which is 5.3 and above only, so if you include this in a PHP 5.2
* setup or one without 5.3 things will blow up. * setup or one without 5.3 things will blow up.
*/ */
use google\appengine\api\app_identity\AppIdentityService; use google\appengine\api\app_identity\AppIdentityService;
require_once "Google/Auth/Abstract.php"; require_once "Google/Auth/Abstract.php";
@ -28,73 +29,68 @@ require_once "Google/Http/Request.php";
/** /**
* Authentication via the Google App Engine App Identity service. * Authentication via the Google App Engine App Identity service.
*/ */
class Google_Auth_AppIdentity extends Google_Auth_Abstract class Google_Auth_AppIdentity extends Google_Auth_Abstract {
{ const CACHE_PREFIX = "Google_Auth_AppIdentity::";
const CACHE_PREFIX = "Google_Auth_AppIdentity::"; const CACHE_LIFETIME = 1500;
const CACHE_LIFETIME = 1500; private $key = null;
private $key = null; private $client;
private $client; private $token = false;
private $token = false; private $tokenScopes = false;
private $tokenScopes = false;
public function __construct(Google_Client $client, $config = null) public function __construct(Google_Client $client, $config = null) {
{ $this->client = $client;
$this->client = $client;
}
/**
* Retrieve an access token for the scopes supplied.
*/
public function authenticateForScope($scopes)
{
if ($this->token && $this->tokenScopes == $scopes) {
return $this->token;
} }
$memcache = new Memcached();
$this->token = $memcache->get(self::CACHE_PREFIX . $scopes); /**
if (!$this->token) { * Retrieve an access token for the scopes supplied.
$this->token = AppIdentityService::getAccessToken($scopes); */
if ($this->token) { public function authenticateForScope($scopes) {
$memcache_key = self::CACHE_PREFIX; if ($this->token && $this->tokenScopes == $scopes) {
if (is_string($scopes)) { return $this->token;
$memcache_key .= $scopes;
} else if (is_array($scopes)) {
$memcache_key .= implode(":", $scopes);
} }
$memcache->set($memcache_key, $this->token, self::CACHE_LIFETIME); $memcache = new Memcached();
} $this->token = $memcache->get(self::CACHE_PREFIX . $scopes);
if (!$this->token) {
$this->token = AppIdentityService::getAccessToken($scopes);
if ($this->token) {
$memcache_key = self::CACHE_PREFIX;
if (is_string($scopes)) {
$memcache_key .= $scopes;
} elseif (is_array($scopes)) {
$memcache_key .= implode(":", $scopes);
}
$memcache->set($memcache_key, $this->token, self::CACHE_LIFETIME);
}
}
$this->tokenScopes = $scopes;
return $this->token;
} }
$this->tokenScopes = $scopes;
return $this->token;
}
/** /**
* Perform an authenticated / signed apiHttpRequest. * Perform an authenticated / signed apiHttpRequest.
* This function takes the apiHttpRequest, calls apiAuth->sign on it * This function takes the apiHttpRequest, calls apiAuth->sign on it
* (which can modify the request in what ever way fits the auth mechanism) * (which can modify the request in what ever way fits the auth mechanism)
* and then calls apiCurlIO::makeRequest on the signed request * and then calls apiCurlIO::makeRequest on the signed request
* *
* @param Google_Http_Request $request * @param Google_Http_Request $request
* @return Google_Http_Request The resulting HTTP response including the * @return Google_Http_Request The resulting HTTP response including the
* responseHttpCode, responseHeaders and responseBody. * responseHttpCode, responseHeaders and responseBody.
*/ */
public function authenticatedRequest(Google_Http_Request $request) public function authenticatedRequest(Google_Http_Request $request) {
{ $request = $this->sign($request);
$request = $this->sign($request); return $this->io->makeRequest($request);
return $this->io->makeRequest($request);
}
public function sign(Google_Http_Request $request)
{
if (!$this->token) {
// No token, so nothing to do.
return $request;
} }
// Add the OAuth2 header to the request
$request->setRequestHeaders(
array('Authorization' => 'Bearer ' . $this->token['access_token'])
);
return $request; public function sign(Google_Http_Request $request) {
} if (!$this->token) {
// No token, so nothing to do.
return $request;
}
// Add the OAuth2 header to the request
$request->setRequestHeaders(
array('Authorization' => 'Bearer ' . $this->token['access_token'])
);
return $request;
}
} }

View file

@ -24,115 +24,111 @@ require_once "Google/Utils.php";
* *
* @author Chirag Shah <chirags@google.com> * @author Chirag Shah <chirags@google.com>
*/ */
class Google_Auth_AssertionCredentials class Google_Auth_AssertionCredentials {
{ const MAX_TOKEN_LIFETIME_SECS = 3600;
const MAX_TOKEN_LIFETIME_SECS = 3600;
public $serviceAccountName; public $serviceAccountName;
public $scopes; public $scopes;
public $privateKey; public $privateKey;
public $privateKeyPassword; public $privateKeyPassword;
public $assertionType; public $assertionType;
public $sub; public $sub;
/** /**
* @deprecated * @deprecated
* @link http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06 * @link http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06
*/ */
public $prn; public $prn;
private $useCache; private $useCache;
/** /**
* @param $serviceAccountName * @param $serviceAccountName
* @param $scopes array List of scopes * @param $scopes array List of scopes
* @param $privateKey * @param $privateKey
* @param string $privateKeyPassword * @param string $privateKeyPassword
* @param string $assertionType * @param string $assertionType
* @param bool|string $sub The email address of the user for which the * @param bool|string $sub The email address of the user for which the
* application is requesting delegated access. * application is requesting delegated access.
* @param bool useCache Whether to generate a cache key and allow * @param bool useCache Whether to generate a cache key and allow
* automatic caching of the generated token. * automatic caching of the generated token.
*/ */
public function __construct( public function __construct(
$serviceAccountName, $serviceAccountName,
$scopes, $scopes,
$privateKey, $privateKey,
$privateKeyPassword = 'notasecret', $privateKeyPassword = 'notasecret',
$assertionType = 'http://oauth.net/grant_type/jwt/1.0/bearer', $assertionType = 'http://oauth.net/grant_type/jwt/1.0/bearer',
$sub = false, $sub = false,
$useCache = true $useCache = true
) { ) {
$this->serviceAccountName = $serviceAccountName; $this->serviceAccountName = $serviceAccountName;
$this->scopes = is_string($scopes) ? $scopes : implode(' ', $scopes); $this->scopes = is_string($scopes) ? $scopes : implode(' ', $scopes);
$this->privateKey = $privateKey; $this->privateKey = $privateKey;
$this->privateKeyPassword = $privateKeyPassword; $this->privateKeyPassword = $privateKeyPassword;
$this->assertionType = $assertionType; $this->assertionType = $assertionType;
$this->sub = $sub; $this->sub = $sub;
$this->prn = $sub; $this->prn = $sub;
$this->useCache = $useCache; $this->useCache = $useCache;
}
/**
* Generate a unique key to represent this credential.
* @return string
*/
public function getCacheKey()
{
if (!$this->useCache) {
return false;
}
$h = $this->sub;
$h .= $this->assertionType;
$h .= $this->privateKey;
$h .= $this->scopes;
$h .= $this->serviceAccountName;
return md5($h);
}
public function generateAssertion()
{
$now = time();
$jwtParams = array(
'aud' => Google_Auth_OAuth2::OAUTH2_TOKEN_URI,
'scope' => $this->scopes,
'iat' => $now,
'exp' => $now + self::MAX_TOKEN_LIFETIME_SECS,
'iss' => $this->serviceAccountName,
);
if ($this->sub !== false) {
$jwtParams['sub'] = $this->sub;
} else if ($this->prn !== false) {
$jwtParams['prn'] = $this->prn;
} }
return $this->makeSignedJwt($jwtParams); /**
} * Generate a unique key to represent this credential.
* @return string
*/
public function getCacheKey() {
if (!$this->useCache) {
return false;
}
$h = $this->sub;
$h .= $this->assertionType;
$h .= $this->privateKey;
$h .= $this->scopes;
$h .= $this->serviceAccountName;
return md5($h);
}
/** public function generateAssertion() {
* Creates a signed JWT. $now = time();
* @param array $payload
* @return string The signed JWT.
*/
private function makeSignedJwt($payload)
{
$header = array('typ' => 'JWT', 'alg' => 'RS256');
$payload = json_encode($payload); $jwtParams = array(
// Handle some overzealous escaping in PHP json that seemed to cause some errors 'aud' => Google_Auth_OAuth2::OAUTH2_TOKEN_URI,
// with claimsets. 'scope' => $this->scopes,
$payload = str_replace('\/', '/', $payload); 'iat' => $now,
'exp' => $now + self::MAX_TOKEN_LIFETIME_SECS,
'iss' => $this->serviceAccountName,
);
$segments = array( if ($this->sub !== false) {
Google_Utils::urlSafeB64Encode(json_encode($header)), $jwtParams['sub'] = $this->sub;
Google_Utils::urlSafeB64Encode($payload) } elseif ($this->prn !== false) {
); $jwtParams['prn'] = $this->prn;
}
$signingInput = implode('.', $segments); return $this->makeSignedJwt($jwtParams);
$signer = new Google_Signer_P12($this->privateKey, $this->privateKeyPassword); }
$signature = $signer->sign($signingInput);
$segments[] = Google_Utils::urlSafeB64Encode($signature);
return implode(".", $segments); /**
} * Creates a signed JWT.
* @param array $payload
* @return string The signed JWT.
*/
private function makeSignedJwt($payload) {
$header = array('typ' => 'JWT', 'alg' => 'RS256');
$payload = json_encode($payload);
// Handle some overzealous escaping in PHP json that seemed to cause some errors
// with claimsets.
$payload = str_replace('\/', '/', $payload);
$segments = array(
Google_Utils::urlSafeB64Encode(json_encode($header)),
Google_Utils::urlSafeB64Encode($payload)
);
$signingInput = implode('.', $segments);
$signer = new Google_Signer_P12($this->privateKey, $this->privateKeyPassword);
$signature = $signer->sign($signingInput);
$segments[] = Google_Utils::urlSafeB64Encode($signature);
return implode(".", $segments);
}
} }

View file

@ -17,6 +17,5 @@
require_once "Google/Exception.php"; require_once "Google/Exception.php";
class Google_Auth_Exception extends Google_Exception class Google_Auth_Exception extends Google_Exception {
{
} }

View file

@ -22,48 +22,44 @@ require_once "Google/Auth/Exception.php";
* *
* @author Brian Eaton <beaton@google.com> * @author Brian Eaton <beaton@google.com>
*/ */
class Google_Auth_LoginTicket class Google_Auth_LoginTicket {
{ const USER_ATTR = "sub";
const USER_ATTR = "sub";
// Information from id token envelope. // Information from id token envelope.
private $envelope; private $envelope;
// Information from id token payload. // Information from id token payload.
private $payload; private $payload;
/** /**
* Creates a user based on the supplied token. * Creates a user based on the supplied token.
* *
* @param string $envelope Header from a verified authentication token. * @param string $envelope Header from a verified authentication token.
* @param string $payload Information from a verified authentication token. * @param string $payload Information from a verified authentication token.
*/ */
public function __construct($envelope, $payload) public function __construct($envelope, $payload) {
{ $this->envelope = $envelope;
$this->envelope = $envelope; $this->payload = $payload;
$this->payload = $payload;
}
/**
* Returns the numeric identifier for the user.
* @throws Google_Auth_Exception
* @return
*/
public function getUserId()
{
if (array_key_exists(self::USER_ATTR, $this->payload)) {
return $this->payload[self::USER_ATTR];
} }
throw new Google_Auth_Exception("No user_id in token");
}
/** /**
* Returns attributes from the login ticket. This can contain * Returns the numeric identifier for the user.
* various information about the user session. * @return
* @return array * @throws Google_Auth_Exception
*/ */
public function getAttributes() public function getUserId() {
{ if (array_key_exists(self::USER_ATTR, $this->payload)) {
return array("envelope" => $this->envelope, "payload" => $this->payload); return $this->payload[self::USER_ATTR];
} }
throw new Google_Auth_Exception("No user_id in token");
}
/**
* Returns attributes from the login ticket. This can contain
* various information about the user session.
* @return array
*/
public function getAttributes() {
return array("envelope" => $this->envelope, "payload" => $this->payload);
}
} }

File diff suppressed because it is too large Load diff

View file

@ -25,38 +25,34 @@ require_once "Google/Http/Request.php";
* @author Chris Chabot <chabotc@google.com> * @author Chris Chabot <chabotc@google.com>
* @author Chirag Shah <chirags@google.com> * @author Chirag Shah <chirags@google.com>
*/ */
class Google_Auth_Simple extends Google_Auth_Abstract class Google_Auth_Simple extends Google_Auth_Abstract {
{ private $key = null;
private $key = null; private $client;
private $client;
public function __construct(Google_Client $client, $config = null) public function __construct(Google_Client $client, $config = null) {
{ $this->client = $client;
$this->client = $client; }
}
/**
/** * Perform an authenticated / signed apiHttpRequest.
* Perform an authenticated / signed apiHttpRequest. * This function takes the apiHttpRequest, calls apiAuth->sign on it
* This function takes the apiHttpRequest, calls apiAuth->sign on it * (which can modify the request in what ever way fits the auth mechanism)
* (which can modify the request in what ever way fits the auth mechanism) * and then calls apiCurlIO::makeRequest on the signed request
* and then calls apiCurlIO::makeRequest on the signed request *
* * @param Google_Http_Request $request
* @param Google_Http_Request $request * @return Google_Http_Request The resulting HTTP response including the
* @return Google_Http_Request The resulting HTTP response including the * responseHttpCode, responseHeaders and responseBody.
* responseHttpCode, responseHeaders and responseBody. */
*/ public function authenticatedRequest(Google_Http_Request $request) {
public function authenticatedRequest(Google_Http_Request $request) $request = $this->sign($request);
{ return $this->io->makeRequest($request);
$request = $this->sign($request); }
return $this->io->makeRequest($request);
} public function sign(Google_Http_Request $request) {
$key = $this->client->getClassConfig($this, 'developer_key');
public function sign(Google_Http_Request $request) if ($key) {
{ $request->setQueryParam('key', $key);
$key = $this->client->getClassConfig($this, 'developer_key'); }
if ($key) { return $request;
$request->setQueryParam('key', $key);
} }
return $request;
}
} }

View file

@ -20,34 +20,33 @@
* *
* @author Chris Chabot <chabotc@google.com> * @author Chris Chabot <chabotc@google.com>
*/ */
abstract class Google_Cache_Abstract abstract class Google_Cache_Abstract {
{
abstract public function __construct(Google_Client $client);
/** abstract public function __construct(Google_Client $client);
* Retrieves the data for the given key, or false if they
* key is unknown or expired
*
* @param String $key The key who's data to retrieve
* @param boolean|int $expiration Expiration time in seconds
*
*/
abstract public function get($key, $expiration = false);
/** /**
* Store the key => $value set. The $value is serialized * Retrieves the data for the given key, or false if they
* by this function so can be of any type * key is unknown or expired
* *
* @param string $key Key of the data * @param String $key The key who's data to retrieve
* @param string $value data * @param boolean|int $expiration Expiration time in seconds
*/ *
abstract public function set($key, $value); */
abstract public function get($key, $expiration = false);
/** /**
* Removes the key/data pair for the given $key * Store the key => $value set. The $value is serialized
* * by this function so can be of any type
* @param String $key *
*/ * @param string $key Key of the data
abstract public function delete($key); * @param string $value data
*/
abstract public function set($key, $value);
/**
* Removes the key/data pair for the given $key
*
* @param String $key
*/
abstract public function delete($key);
} }

View file

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
require_once "Google/Cache/Abstract.php"; require_once "Google/Cache/Abstract.php";
require_once "Google/Cache/Exception.php"; require_once "Google/Cache/Exception.php";
@ -26,48 +26,43 @@ require_once "Google/Cache/Exception.php";
* *
* @author Chris Chabot <chabotc@google.com> * @author Chris Chabot <chabotc@google.com>
*/ */
class Google_Cache_Apc extends Google_Cache_Abstract class Google_Cache_Apc extends Google_Cache_Abstract {
{ public function __construct(Google_Client $client) {
public function __construct(Google_Client $client) if (!function_exists('apc_add')) {
{ throw new Google_Cache_Exception("Apc functions not available");
if (! function_exists('apc_add') ) { }
throw new Google_Cache_Exception("Apc functions not available");
} }
}
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function get($key, $expiration = false) public function get($key, $expiration = false) {
{ $ret = apc_fetch($key);
$ret = apc_fetch($key); if ($ret === false) {
if ($ret === false) { return false;
return false; }
if (is_numeric($expiration) && (time() - $ret['time'] > $expiration)) {
$this->delete($key);
return false;
}
return $ret['data'];
} }
if (is_numeric($expiration) && (time() - $ret['time'] > $expiration)) {
$this->delete($key);
return false;
}
return $ret['data'];
}
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function set($key, $value) public function set($key, $value) {
{ $rc = apc_store($key, array('time' => time(), 'data' => $value));
$rc = apc_store($key, array('time' => time(), 'data' => $value)); if ($rc == false) {
if ($rc == false) { throw new Google_Cache_Exception("Couldn't store data");
throw new Google_Cache_Exception("Couldn't store data"); }
} }
}
/** /**
* @inheritDoc * @inheritDoc
* @param String $key * @param String $key
*/ */
public function delete($key) public function delete($key) {
{ apc_delete($key);
apc_delete($key); }
}
} }

View file

@ -16,6 +16,5 @@
*/ */
require_once "Google/Exception.php"; require_once "Google/Exception.php";
class Google_Cache_Exception extends Google_Exception class Google_Cache_Exception extends Google_Exception {
{
} }

View file

@ -26,120 +26,109 @@ require_once "Google/Cache/Exception.php";
* *
* @author Chris Chabot <chabotc@google.com> * @author Chris Chabot <chabotc@google.com>
*/ */
class Google_Cache_File extends Google_Cache_Abstract
{
const MAX_LOCK_RETRIES = 10;
private $path;
private $fh;
public function __construct(Google_Client $client) class Google_Cache_File extends Google_Cache_Abstract {
{ const MAX_LOCK_RETRIES = 10;
$this->path = $client->getClassConfig($this, 'directory'); private $path;
} private $fh;
public function get($key, $expiration = false) public function __construct(Google_Client $client) {
{ $this->path = $client->getClassConfig($this, 'directory');
$storageFile = $this->getCacheFile($key);
$data = false;
if (!file_exists($storageFile)) {
return false;
} }
if ($expiration) { public function get($key, $expiration = false) {
$mtime = filemtime($storageFile); $storageFile = $this->getCacheFile($key);
if ((time() - $mtime) >= $expiration) { $data = false;
$this->delete($key);
return false; if (!file_exists($storageFile)) {
} return false;
}
if ($expiration) {
$mtime = filemtime($storageFile);
if ((time() - $mtime) >= $expiration) {
$this->delete($key);
return false;
}
}
if ($this->acquireReadLock($storageFile)) {
$data = fread($this->fh, filesize($storageFile));
$data = unserialize($data);
$this->unlock($storageFile);
}
return $data;
} }
if ($this->acquireReadLock($storageFile)) { public function set($key, $value) {
$data = fread($this->fh, filesize($storageFile)); $storageFile = $this->getWriteableCacheFile($key);
$data = unserialize($data); if ($this->acquireWriteLock($storageFile)) {
$this->unlock($storageFile); // We serialize the whole request object, since we don't only want the
// responseContent but also the postBody used, headers, size, etc.
$data = serialize($value);
$result = fwrite($this->fh, $data);
$this->unlock($storageFile);
}
} }
return $data; public function delete($key) {
} $file = $this->getCacheFile($key);
if (file_exists($file) && !unlink($file)) {
throw new Google_Cache_Exception("Cache file could not be deleted");
}
}
public function set($key, $value) private function getWriteableCacheFile($file) {
{ return $this->getCacheFile($file, true);
$storageFile = $this->getWriteableCacheFile($key);
if ($this->acquireWriteLock($storageFile)) {
// We serialize the whole request object, since we don't only want the
// responseContent but also the postBody used, headers, size, etc.
$data = serialize($value);
$result = fwrite($this->fh, $data);
$this->unlock($storageFile);
} }
}
public function delete($key) private function getCacheFile($file, $forWrite = false) {
{ return $this->getCacheDir($file, $forWrite) . '/' . md5($file);
$file = $this->getCacheFile($key);
if (file_exists($file) && !unlink($file)) {
throw new Google_Cache_Exception("Cache file could not be deleted");
} }
}
private function getWriteableCacheFile($file)
{
return $this->getCacheFile($file, true);
}
private function getCacheFile($file, $forWrite = false) private function getCacheDir($file, $forWrite) {
{ // use the first 2 characters of the hash as a directory prefix
return $this->getCacheDir($file, $forWrite) . '/' . md5($file); // this should prevent slowdowns due to huge directory listings
} // and thus give some basic amount of scalability
$storageDir = $this->path . '/' . substr(md5($file), 0, 2);
private function getCacheDir($file, $forWrite) if ($forWrite && !is_dir($storageDir)) {
{ if (!mkdir($storageDir, 0755, true)) {
// use the first 2 characters of the hash as a directory prefix throw new Google_Cache_Exception("Could not create storage directory: $storageDir");
// this should prevent slowdowns due to huge directory listings }
// and thus give some basic amount of scalability }
$storageDir = $this->path . '/' . substr(md5($file), 0, 2); return $storageDir;
if ($forWrite && ! is_dir($storageDir)) {
if (! mkdir($storageDir, 0755, true)) {
throw new Google_Cache_Exception("Could not create storage directory: $storageDir");
}
} }
return $storageDir;
} private function acquireReadLock($storageFile) {
return $this->acquireLock(LOCK_SH, $storageFile);
private function acquireReadLock($storageFile)
{
return $this->acquireLock(LOCK_SH, $storageFile);
}
private function acquireWriteLock($storageFile)
{
$rc = $this->acquireLock(LOCK_EX, $storageFile);
if (!$rc) {
$this->delete($storageFile);
} }
return $rc;
} private function acquireWriteLock($storageFile) {
$rc = $this->acquireLock(LOCK_EX, $storageFile);
private function acquireLock($type, $storageFile) if (!$rc) {
{ $this->delete($storageFile);
$mode = $type == LOCK_EX ? "w" : "r"; }
$this->fh = fopen($storageFile, $mode); return $rc;
$count = 0;
while (!flock($this->fh, $type | LOCK_NB)) {
// Sleep for 10ms.
usleep(10000);
if (++$count < self::MAX_LOCK_RETRIES) {
return false;
}
} }
return true;
} private function acquireLock($type, $storageFile) {
$mode = $type == LOCK_EX ? "w" : "r";
public function unlock($storageFile) $this->fh = fopen($storageFile, $mode);
{ $count = 0;
if ($this->fh) { while (!flock($this->fh, $type | LOCK_NB)) {
flock($this->fh, LOCK_UN); // Sleep for 10ms.
usleep(10000);
if (++$count < self::MAX_LOCK_RETRIES) {
return false;
}
}
return true;
}
public function unlock($storageFile) {
if ($this->fh) {
flock($this->fh, LOCK_UN);
}
} }
}
} }

View file

@ -28,110 +28,104 @@ require_once "Google/Cache/Exception.php";
* *
* @author Chris Chabot <chabotc@google.com> * @author Chris Chabot <chabotc@google.com>
*/ */
class Google_Cache_Memcache extends Google_Cache_Abstract class Google_Cache_Memcache extends Google_Cache_Abstract {
{ private $connection = false;
private $connection = false; private $mc = false;
private $mc = false; private $host;
private $host; private $port;
private $port;
public function __construct(Google_Client $client) public function __construct(Google_Client $client) {
{ if (!function_exists('memcache_connect') && !class_exists("Memcached")) {
if (!function_exists('memcache_connect') && !class_exists("Memcached")) { throw new Google_Cache_Exception("Memcache functions not available");
throw new Google_Cache_Exception("Memcache functions not available"); }
} if ($client->isAppEngine()) {
if ($client->isAppEngine()) { // No credentials needed for GAE.
// No credentials needed for GAE. $this->mc = new Memcached();
$this->mc = new Memcached(); $this->connection = true;
$this->connection = true; } else {
} else { $this->host = $client->getClassConfig($this, 'host');
$this->host = $client->getClassConfig($this, 'host'); $this->port = $client->getClassConfig($this, 'port');
$this->port = $client->getClassConfig($this, 'port'); if (empty($this->host) || empty($this->port)) {
if (empty($this->host) || empty($this->port)) { throw new Google_Cache_Exception("You need to supply a valid memcache host and port");
throw new Google_Cache_Exception("You need to supply a valid memcache host and port"); }
} }
}
}
/**
* @inheritDoc
*/
public function get($key, $expiration = false)
{
$this->connect();
$ret = false;
if ($this->mc) {
$ret = $this->mc->get($key);
} else {
$ret = memcache_get($this->connection, $key);
}
if ($ret === false) {
return false;
}
if (is_numeric($expiration) && (time() - $ret['time'] > $expiration)) {
$this->delete($key);
return false;
}
return $ret['data'];
}
/**
* @inheritDoc
* @param string $key
* @param string $value
* @throws Google_Cache_Exception
*/
public function set($key, $value)
{
$this->connect();
// we store it with the cache_time default expiration so objects will at
// least get cleaned eventually.
$data = array('time' => time(), 'data' => $value);
$rc = false;
if ($this->mc) {
$rc = $this->mc->set($key, $data);
} else {
$rc = memcache_set($this->connection, $key, $data, false);
}
if ($rc == false) {
throw new Google_Cache_Exception("Couldn't store data in cache");
}
}
/**
* @inheritDoc
* @param String $key
*/
public function delete($key)
{
$this->connect();
if ($this->mc) {
$this->mc->delete($key, 0);
} else {
memcache_delete($this->connection, $key, 0);
}
}
/**
* Lazy initialiser for memcache connection. Uses pconnect for to take
* advantage of the persistence pool where possible.
*/
private function connect()
{
if ($this->connection) {
return;
} }
if (class_exists("Memcached")) { /**
$this->mc = new Memcached(); * @inheritDoc
$this->mc->addServer($this->host, $this->port); */
$this->connection = true; public function get($key, $expiration = false) {
} else { $this->connect();
$this->connection = memcache_pconnect($this->host, $this->port); $ret = false;
if ($this->mc) {
$ret = $this->mc->get($key);
} else {
$ret = memcache_get($this->connection, $key);
}
if ($ret === false) {
return false;
}
if (is_numeric($expiration) && (time() - $ret['time'] > $expiration)) {
$this->delete($key);
return false;
}
return $ret['data'];
} }
if (! $this->connection) { /**
throw new Google_Cache_Exception("Couldn't connect to memcache server"); * @inheritDoc
* @param string $key
* @param string $value
* @throws Google_Cache_Exception
*/
public function set($key, $value) {
$this->connect();
// we store it with the cache_time default expiration so objects will at
// least get cleaned eventually.
$data = array('time' => time(), 'data' => $value);
$rc = false;
if ($this->mc) {
$rc = $this->mc->set($key, $data);
} else {
$rc = memcache_set($this->connection, $key, $data, false);
}
if ($rc == false) {
throw new Google_Cache_Exception("Couldn't store data in cache");
}
}
/**
* @inheritDoc
* @param String $key
*/
public function delete($key) {
$this->connect();
if ($this->mc) {
$this->mc->delete($key, 0);
} else {
memcache_delete($this->connection, $key, 0);
}
}
/**
* Lazy initialiser for memcache connection. Uses pconnect for to take
* advantage of the persistence pool where possible.
*/
private function connect() {
if ($this->connection) {
return;
}
if (class_exists("Memcached")) {
$this->mc = new Memcached();
$this->mc->addServer($this->host, $this->port);
$this->connection = true;
} else {
$this->connection = memcache_pconnect($this->host, $this->port);
}
if (!$this->connection) {
throw new Google_Cache_Exception("Couldn't connect to memcache server");
}
} }
}
} }

View file

@ -22,35 +22,30 @@ require_once "Google/Cache/Exception.php";
* A blank storage class, for cases where caching is not * A blank storage class, for cases where caching is not
* required. * required.
*/ */
class Google_Cache_Null extends Google_Cache_Abstract class Google_Cache_Null extends Google_Cache_Abstract {
{ public function __construct(Google_Client $client) {
public function __construct(Google_Client $client)
{
} }
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function get($key, $expiration = false) public function get($key, $expiration = false) {
{ return false;
return false; }
}
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function set($key, $value) public function set($key, $value) {
{ // Nop.
// Nop. }
}
/** /**
* @inheritDoc * @inheritDoc
* @param String $key * @param String $key
*/ */
public function delete($key) public function delete($key) {
{ // Nop.
// Nop. }
}
} }

File diff suppressed because it is too large Load diff

View file

@ -7,90 +7,78 @@ require_once "Google/Model.php";
* exposes the items array for iteration, so you can just * exposes the items array for iteration, so you can just
* iterate over the object rather than a reference inside. * iterate over the object rather than a reference inside.
*/ */
class Google_Collection extends Google_Model implements Iterator, Countable class Google_Collection extends Google_Model implements Iterator, Countable {
{ protected $collection_key = 'items';
protected $collection_key = 'items';
public function rewind() public function rewind() {
{ if (isset($this->modelData[$this->collection_key])
if (isset($this->modelData[$this->collection_key]) && is_array($this->modelData[$this->collection_key])) {
&& is_array($this->modelData[$this->collection_key])) { reset($this->modelData[$this->collection_key]);
reset($this->modelData[$this->collection_key]); }
} }
}
public function current() public function current() {
{ $this->coerceType($this->key());
$this->coerceType($this->key()); if (is_array($this->modelData[$this->collection_key])) {
if (is_array($this->modelData[$this->collection_key])) { return current($this->modelData[$this->collection_key]);
return current($this->modelData[$this->collection_key]); }
} }
}
public function key() public function key() {
{ if (isset($this->modelData[$this->collection_key])
if (isset($this->modelData[$this->collection_key]) && is_array($this->modelData[$this->collection_key])) {
&& is_array($this->modelData[$this->collection_key])) { return key($this->modelData[$this->collection_key]);
return key($this->modelData[$this->collection_key]); }
} }
}
public function next() public function next() {
{ return next($this->modelData[$this->collection_key]);
return next($this->modelData[$this->collection_key]);
}
public function valid()
{
$key = $this->key();
return $key !== null && $key !== false;
}
public function count()
{
return count($this->modelData[$this->collection_key]);
}
public function offsetExists ($offset)
{
if (!is_numeric($offset)) {
return parent::offsetExists($offset);
} }
return isset($this->modelData[$this->collection_key][$offset]);
}
public function offsetGet($offset) public function valid() {
{ $key = $this->key();
if (!is_numeric($offset)) { return $key !== null && $key !== false;
return parent::offsetGet($offset);
} }
$this->coerceType($offset);
return $this->modelData[$this->collection_key][$offset];
}
public function offsetSet($offset, $value) public function count() {
{ return count($this->modelData[$this->collection_key]);
if (!is_numeric($offset)) {
return parent::offsetSet($offset, $value);
} }
$this->modelData[$this->collection_key][$offset] = $value;
}
public function offsetUnset($offset) public function offsetExists($offset) {
{ if (!is_numeric($offset)) {
if (!is_numeric($offset)) { return parent::offsetExists($offset);
return parent::offsetUnset($offset); }
return isset($this->modelData[$this->collection_key][$offset]);
} }
unset($this->modelData[$this->collection_key][$offset]);
}
private function coerceType($offset) public function offsetGet($offset) {
{ if (!is_numeric($offset)) {
$typeKey = $this->keyType($this->collection_key); return parent::offsetGet($offset);
if (isset($this->$typeKey) && !is_object($this->modelData[$this->collection_key][$offset])) { }
$type = $this->$typeKey; $this->coerceType($offset);
$this->modelData[$this->collection_key][$offset] = return $this->modelData[$this->collection_key][$offset];
new $type($this->modelData[$this->collection_key][$offset]); }
public function offsetSet($offset, $value) {
if (!is_numeric($offset)) {
return parent::offsetSet($offset, $value);
}
$this->modelData[$this->collection_key][$offset] = $value;
}
public function offsetUnset($offset) {
if (!is_numeric($offset)) {
return parent::offsetUnset($offset);
}
unset($this->modelData[$this->collection_key][$offset]);
}
private function coerceType($offset) {
$typeKey = $this->keyType($this->collection_key);
if (isset($this->$typeKey) && !is_object($this->modelData[$this->collection_key][$offset])) {
$type = $this->$typeKey;
$this->modelData[$this->collection_key][$offset] =
new $type($this->modelData[$this->collection_key][$offset]);
}
} }
}
} }

View file

@ -18,309 +18,286 @@
/** /**
* A class to contain the library configuration for the Google API client. * A class to contain the library configuration for the Google API client.
*/ */
class Google_Config class Google_Config {
{ const GZIP_DISABLED = true;
const GZIP_DISABLED = true; const GZIP_ENABLED = false;
const GZIP_ENABLED = false; const GZIP_UPLOADS_ENABLED = true;
const GZIP_UPLOADS_ENABLED = true; const GZIP_UPLOADS_DISABLED = false;
const GZIP_UPLOADS_DISABLED = false; const USE_AUTO_IO_SELECTION = "auto";
const USE_AUTO_IO_SELECTION = "auto"; private $configuration;
private $configuration;
/** /**
* Create a new Google_Config. Can accept an ini file location with the * Create a new Google_Config. Can accept an ini file location with the
* local configuration. For example: * local configuration. For example:
* application_name: "My App"; * application_name: "My App";
* *
* @param [$ini_file_location] - optional - The location of the ini file to load * @param [$ini_file_location] - optional - The location of the ini file to load
*/ */
public function __construct($ini_file_location = null) public function __construct($ini_file_location = null) {
{ require_once('../config.php');
require_once('../config.php');
$this->configuration = array(
// The application_name is included in the User-Agent HTTP header.
'application_name' => G_Application_Name,
// Which Authentication, Storage and HTTP IO classes to use. $this->configuration = array(
'auth_class' => 'Google_Auth_OAuth2', // The application_name is included in the User-Agent HTTP header.
'io_class' => self::USE_AUTO_IO_SELECTION, 'application_name' => G_Application_Name,
'cache_class' => 'Google_Cache_File',
// Don't change these unless you're working against a special development // Which Authentication, Storage and HTTP IO classes to use.
// or testing environment. 'auth_class' => 'Google_Auth_OAuth2',
'base_path' => 'https://www.googleapis.com', 'io_class' => self::USE_AUTO_IO_SELECTION,
'cache_class' => 'Google_Cache_File',
// Definition of class specific values, like file paths and so on. // Don't change these unless you're working against a special development
'classes' => array( // or testing environment.
'Google_IO_Abstract' => array( 'base_path' => 'https://www.googleapis.com',
'request_timeout_seconds' => 100,
),
'Google_Http_Request' => array(
// Disable the use of gzip on calls if set to true. Defaults to false.
'disable_gzip' => self::GZIP_ENABLED,
// We default gzip to disabled on uploads even if gzip is otherwise // Definition of class specific values, like file paths and so on.
// enabled, due to some issues seen with small packet sizes for uploads. 'classes' => array(
// Please test with this option before enabling gzip for uploads in 'Google_IO_Abstract' => array(
// a production environment. 'request_timeout_seconds' => 100,
'enable_gzip_for_uploads' => self::GZIP_UPLOADS_DISABLED, ),
), 'Google_Http_Request' => array(
// If you want to pass in OAuth 2.0 settings, they will need to be // Disable the use of gzip on calls if set to true. Defaults to false.
// structured like this. 'disable_gzip' => self::GZIP_ENABLED,
'Google_Auth_OAuth2' => array(
// Keys for OAuth 2.0 access, see the API console at
// https://developers.google.com/console
'client_id' => G_Client_ID,
'client_secret' => G_Client_Secret,
'redirect_uri' => G_Redirect_Uri,
// Simple API access key, also from the API console. Ensure you get
// a Server key, and not a Browser key.
'developer_key' => '',
// Other parameters. // We default gzip to disabled on uploads even if gzip is otherwise
'access_type' => 'online', // enabled, due to some issues seen with small packet sizes for uploads.
'approval_prompt' => 'auto', // Please test with this option before enabling gzip for uploads in
'login_hint' => '', // a production environment.
'request_visible_actions' => '', 'enable_gzip_for_uploads' => self::GZIP_UPLOADS_DISABLED,
'federated_signon_certs_url' => ),
'https://www.googleapis.com/oauth2/v1/certs', // If you want to pass in OAuth 2.0 settings, they will need to be
), // structured like this.
// Set a default directory for the file cache. 'Google_Auth_OAuth2' => array(
'Google_Cache_File' => array( // Keys for OAuth 2.0 access, see the API console at
'directory' => sys_get_temp_dir() . '/Google_Client' // https://developers.google.com/console
) 'client_id' => G_Client_ID,
), 'client_secret' => G_Client_Secret,
'redirect_uri' => G_Redirect_Uri,
// Simple API access key, also from the API console. Ensure you get
// a Server key, and not a Browser key.
'developer_key' => '',
// Definition of service specific values like scopes, oauth token URLs, // Other parameters.
// etc. Example: 'access_type' => 'online',
'services' => array( 'approval_prompt' => 'auto',
), 'login_hint' => '',
); 'request_visible_actions' => '',
if ($ini_file_location) { 'federated_signon_certs_url' =>
$ini = parse_ini_file($ini_file_location, true); 'https://www.googleapis.com/oauth2/v1/certs',
if (is_array($ini) && count($ini)) { ),
$this->configuration = array_merge($this->configuration, $ini); // Set a default directory for the file cache.
} 'Google_Cache_File' => array(
'directory' => sys_get_temp_dir() . '/Google_Client'
)
),
// Definition of service specific values like scopes, oauth token URLs,
// etc. Example:
'services' => array(),
);
if ($ini_file_location) {
$ini = parse_ini_file($ini_file_location, true);
if (is_array($ini) && count($ini)) {
$this->configuration = array_merge($this->configuration, $ini);
}
}
} }
}
/** /**
* Set configuration specific to a given class. * Set configuration specific to a given class.
* $config->setClassConfig('Google_Cache_File', * $config->setClassConfig('Google_Cache_File',
* array('directory' => '/tmp/cache')); * array('directory' => '/tmp/cache'));
* @param $class The class name for the configuration * @param $class The class name for the configuration
* @param $config string key or an array of configuration values * @param $config string key or an array of configuration values
* @param $value optional - if $config is a key, the value * @param $value optional - if $config is a key, the value
*/ */
public function setClassConfig($class, $config, $value = null) public function setClassConfig($class, $config, $value = null) {
{ if (!is_array($config)) {
if (!is_array($config)) { if (!isset($this->configuration['classes'][$class])) {
if (!isset($this->configuration['classes'][$class])) { $this->configuration['classes'][$class] = array();
$this->configuration['classes'][$class] = array(); }
} $this->configuration['classes'][$class][$config] = $value;
$this->configuration['classes'][$class][$config] = $value; } else {
} else { $this->configuration['classes'][$class] = $config;
$this->configuration['classes'][$class] = $config; }
} }
}
public function getClassConfig($class, $key = null) public function getClassConfig($class, $key = null) {
{ if (!isset($this->configuration['classes'][$class])) {
if (!isset($this->configuration['classes'][$class])) { return null;
return null; }
if ($key === null) {
return $this->configuration['classes'][$class];
} else {
return $this->configuration['classes'][$class][$key];
}
} }
if ($key === null) {
return $this->configuration['classes'][$class]; /**
} else { * Return the configured cache class.
return $this->configuration['classes'][$class][$key]; * @return string
*/
public function getCacheClass() {
return $this->configuration['cache_class'];
} }
}
/** /**
* Return the configured cache class. * Return the configured Auth class.
* @return string * @return string
*/ */
public function getCacheClass() public function getAuthClass() {
{ return $this->configuration['auth_class'];
return $this->configuration['cache_class'];
}
/**
* Return the configured Auth class.
* @return string
*/
public function getAuthClass()
{
return $this->configuration['auth_class'];
}
/**
* Set the auth class.
*
* @param $class the class name to set
*/
public function setAuthClass($class)
{
$prev = $this->configuration['auth_class'];
if (!isset($this->configuration['classes'][$class]) &&
isset($this->configuration['classes'][$prev])) {
$this->configuration['classes'][$class] =
$this->configuration['classes'][$prev];
} }
$this->configuration['auth_class'] = $class;
}
/** /**
* Set the IO class. * Set the auth class.
* *
* @param $class the class name to set * @param $class the class name to set
*/ */
public function setIoClass($class) public function setAuthClass($class) {
{ $prev = $this->configuration['auth_class'];
$prev = $this->configuration['io_class']; if (!isset($this->configuration['classes'][$class]) &&
if (!isset($this->configuration['classes'][$class]) && isset($this->configuration['classes'][$prev])) {
isset($this->configuration['classes'][$prev])) { $this->configuration['classes'][$class] =
$this->configuration['classes'][$class] = $this->configuration['classes'][$prev];
$this->configuration['classes'][$prev]; }
$this->configuration['auth_class'] = $class;
} }
$this->configuration['io_class'] = $class;
}
/** /**
* Set the cache class. * Set the IO class.
* *
* @param $class the class name to set * @param $class the class name to set
*/ */
public function setCacheClass($class) public function setIoClass($class) {
{ $prev = $this->configuration['io_class'];
$prev = $this->configuration['cache_class']; if (!isset($this->configuration['classes'][$class]) &&
if (!isset($this->configuration['classes'][$class]) && isset($this->configuration['classes'][$prev])) {
isset($this->configuration['classes'][$prev])) { $this->configuration['classes'][$class] =
$this->configuration['classes'][$class] = $this->configuration['classes'][$prev];
$this->configuration['classes'][$prev]; }
$this->configuration['io_class'] = $class;
} }
$this->configuration['cache_class'] = $class;
}
/** /**
* Return the configured IO class. * Set the cache class.
* @return string *
*/ * @param $class the class name to set
public function getIoClass() */
{ public function setCacheClass($class) {
return $this->configuration['io_class']; $prev = $this->configuration['cache_class'];
} if (!isset($this->configuration['classes'][$class]) &&
isset($this->configuration['classes'][$prev])) {
/** $this->configuration['classes'][$class] =
* Set the application name, this is included in the User-Agent HTTP header. $this->configuration['classes'][$prev];
* @param string $name }
*/ $this->configuration['cache_class'] = $class;
public function setApplicationName($name) }
{
$this->configuration['application_name'] = $name; /**
} * Return the configured IO class.
* @return string
/** */
* @return string the name of the application public function getIoClass() {
*/ return $this->configuration['io_class'];
public function getApplicationName() }
{
return $this->configuration['application_name']; /**
} * Set the application name, this is included in the User-Agent HTTP header.
* @param string $name
/** */
* Set the client ID for the auth class. public function setApplicationName($name) {
* @param $key string - the API console client ID $this->configuration['application_name'] = $name;
*/ }
public function setClientId($clientId)
{ /**
$this->setAuthConfig('client_id', $clientId); * @return string the name of the application
} */
public function getApplicationName() {
/** return $this->configuration['application_name'];
* Set the client secret for the auth class. }
* @param $key string - the API console client secret
*/ /**
public function setClientSecret($secret) * Set the client ID for the auth class.
{ * @param $key string - the API console client ID
$this->setAuthConfig('client_secret', $secret); */
} public function setClientId($clientId) {
$this->setAuthConfig('client_id', $clientId);
/** }
* Set the redirect uri for the auth class. Note that if using the
* Javascript based sign in flow, this should be the string 'postmessage'. /**
* @param $key string - the URI that users should be redirected to * Set the client secret for the auth class.
*/ * @param $key string - the API console client secret
public function setRedirectUri($uri) */
{ public function setClientSecret($secret) {
$this->setAuthConfig('redirect_uri', $uri); $this->setAuthConfig('client_secret', $secret);
} }
/** /**
* Set the app activities for the auth class. * Set the redirect uri for the auth class. Note that if using the
* @param $rva string a space separated list of app activity types * Javascript based sign in flow, this should be the string 'postmessage'.
*/ * @param $key string - the URI that users should be redirected to
public function setRequestVisibleActions($rva) */
{ public function setRedirectUri($uri) {
$this->setAuthConfig('request_visible_actions', $rva); $this->setAuthConfig('redirect_uri', $uri);
} }
/** /**
* Set the the access type requested (offline or online.) * Set the app activities for the auth class.
* @param $access string - the access type * @param $rva string a space separated list of app activity types
*/ */
public function setAccessType($access) public function setRequestVisibleActions($rva) {
{ $this->setAuthConfig('request_visible_actions', $rva);
$this->setAuthConfig('access_type', $access); }
}
/**
/** * Set the the access type requested (offline or online.)
* Set when to show the approval prompt (auto or force) * @param $access string - the access type
* @param $approval string - the approval request */
*/ public function setAccessType($access) {
public function setApprovalPrompt($approval) $this->setAuthConfig('access_type', $access);
{ }
$this->setAuthConfig('approval_prompt', $approval);
} /**
* Set when to show the approval prompt (auto or force)
/** * @param $approval string - the approval request
* Set the login hint (email address or sub identifier) */
* @param $hint string public function setApprovalPrompt($approval) {
*/ $this->setAuthConfig('approval_prompt', $approval);
public function setLoginHint($hint) }
{
$this->setAuthConfig('login_hint', $hint); /**
} * Set the login hint (email address or sub identifier)
* @param $hint string
/** */
* Set the developer key for the auth class. Note that this is separate value public function setLoginHint($hint) {
* from the client ID - if it looks like a URL, its a client ID! $this->setAuthConfig('login_hint', $hint);
* @param $key string - the API console developer key }
*/
public function setDeveloperKey($key) /**
{ * Set the developer key for the auth class. Note that this is separate value
$this->setAuthConfig('developer_key', $key); * from the client ID - if it looks like a URL, its a client ID!
} * @param $key string - the API console developer key
*/
/** public function setDeveloperKey($key) {
* @return string the base URL to use for API calls $this->setAuthConfig('developer_key', $key);
*/ }
public function getBasePath()
{ /**
return $this->configuration['base_path']; * @return string the base URL to use for API calls
} */
public function getBasePath() {
/** return $this->configuration['base_path'];
* Set the auth configuration for the current auth class. }
* @param $key - the key to set
* @param $value - the parameter value /**
*/ * Set the auth configuration for the current auth class.
private function setAuthConfig($key, $value) * @param $key - the key to set
{ * @param $value - the parameter value
if (!isset($this->configuration['classes'][$this->getAuthClass()])) { */
$this->configuration['classes'][$this->getAuthClass()] = array(); private function setAuthConfig($key, $value) {
if (!isset($this->configuration['classes'][$this->getAuthClass()])) {
$this->configuration['classes'][$this->getAuthClass()] = array();
}
$this->configuration['classes'][$this->getAuthClass()][$key] = $value;
} }
$this->configuration['classes'][$this->getAuthClass()][$key] = $value;
}
} }

View file

@ -15,6 +15,5 @@
* limitations under the License. * limitations under the License.
*/ */
class Google_Exception extends Exception class Google_Exception extends Exception {
{
} }

View file

@ -22,122 +22,117 @@ require_once 'Google/Http/REST.php';
/** /**
* @author Chirag Shah <chirags@google.com> * @author Chirag Shah <chirags@google.com>
*/ */
class Google_Http_Batch class Google_Http_Batch {
{ /** @var string Multipart Boundary. */
/** @var string Multipart Boundary. */ private $boundary;
private $boundary;
/** @var array service requests to be executed. */ /** @var array service requests to be executed. */
private $requests = array(); private $requests = array();
/** @var Google_Client */ /** @var Google_Client */
private $client; private $client;
private $expected_classes = array(); private $expected_classes = array();
private $base_path; private $base_path;
public function __construct(Google_Client $client, $boundary = false) public function __construct(Google_Client $client, $boundary = false) {
{ $this->client = $client;
$this->client = $client; $this->base_path = $this->client->getBasePath();
$this->base_path = $this->client->getBasePath(); $this->expected_classes = array();
$this->expected_classes = array(); $boundary = (false == $boundary) ? mt_rand() : $boundary;
$boundary = (false == $boundary) ? mt_rand() : $boundary; $this->boundary = str_replace('"', '', $boundary);
$this->boundary = str_replace('"', '', $boundary);
}
public function add(Google_Http_Request $request, $key = false)
{
if (false == $key) {
$key = mt_rand();
} }
$this->requests[$key] = $request; public function add(Google_Http_Request $request, $key = false) {
} if (false == $key) {
$key = mt_rand();
public function execute()
{
$body = '';
/** @var Google_Http_Request $req */
foreach ($this->requests as $key => $req) {
$body .= "--{$this->boundary}\n";
$body .= $req->toBatchString($key) . "\n";
$this->expected_classes["response-" . $key] = $req->getExpectedClass();
}
$body = rtrim($body);
$body .= "\n--{$this->boundary}--";
$url = $this->base_path . '/batch';
$httpRequest = new Google_Http_Request($url, 'POST');
$httpRequest->setRequestHeaders(
array('Content-Type' => 'multipart/mixed; boundary=' . $this->boundary)
);
$httpRequest->setPostBody($body);
$response = $this->client->getIo()->makeRequest($httpRequest);
return $this->parseResponse($response);
}
public function parseResponse(Google_Http_Request $response)
{
$contentType = $response->getResponseHeader('content-type');
$contentType = explode(';', $contentType);
$boundary = false;
foreach ($contentType as $part) {
$part = (explode('=', $part, 2));
if (isset($part[0]) && 'boundary' == trim($part[0])) {
$boundary = $part[1];
}
}
$body = $response->getResponseBody();
if ($body) {
$body = str_replace("--$boundary--", "--$boundary", $body);
$parts = explode("--$boundary", $body);
$responses = array();
foreach ($parts as $part) {
$part = trim($part);
if (!empty($part)) {
list($metaHeaders, $part) = explode("\r\n\r\n", $part, 2);
$metaHeaders = $this->client->getIo()->getHttpResponseHeaders($metaHeaders);
$status = substr($part, 0, strpos($part, "\n"));
$status = explode(" ", $status);
$status = $status[1];
list($partHeaders, $partBody) = $this->client->getIo()->ParseHttpResponse($part, false);
$response = new Google_Http_Request("");
$response->setResponseHttpCode($status);
$response->setResponseHeaders($partHeaders);
$response->setResponseBody($partBody);
// Need content id.
$key = $metaHeaders['content-id'];
if (isset($this->expected_classes[$key]) &&
strlen($this->expected_classes[$key]) > 0) {
$class = $this->expected_classes[$key];
$response->setExpectedClass($class);
}
try {
$response = Google_Http_REST::decodeHttpResponse($response);
$responses[$key] = $response;
} catch (Google_Service_Exception $e) {
// Store the exception as the response, so succesful responses
// can be processed.
$responses[$key] = $e;
}
} }
}
return $responses; $this->requests[$key] = $request;
} }
return null; public function execute() {
} $body = '';
/** @var Google_Http_Request $req */
foreach ($this->requests as $key => $req) {
$body .= "--{$this->boundary}\n";
$body .= $req->toBatchString($key) . "\n";
$this->expected_classes["response-" . $key] = $req->getExpectedClass();
}
$body = rtrim($body);
$body .= "\n--{$this->boundary}--";
$url = $this->base_path . '/batch';
$httpRequest = new Google_Http_Request($url, 'POST');
$httpRequest->setRequestHeaders(
array('Content-Type' => 'multipart/mixed; boundary=' . $this->boundary)
);
$httpRequest->setPostBody($body);
$response = $this->client->getIo()->makeRequest($httpRequest);
return $this->parseResponse($response);
}
public function parseResponse(Google_Http_Request $response) {
$contentType = $response->getResponseHeader('content-type');
$contentType = explode(';', $contentType);
$boundary = false;
foreach ($contentType as $part) {
$part = (explode('=', $part, 2));
if (isset($part[0]) && 'boundary' == trim($part[0])) {
$boundary = $part[1];
}
}
$body = $response->getResponseBody();
if ($body) {
$body = str_replace("--$boundary--", "--$boundary", $body);
$parts = explode("--$boundary", $body);
$responses = array();
foreach ($parts as $part) {
$part = trim($part);
if (!empty($part)) {
list($metaHeaders, $part) = explode("\r\n\r\n", $part, 2);
$metaHeaders = $this->client->getIo()->getHttpResponseHeaders($metaHeaders);
$status = substr($part, 0, strpos($part, "\n"));
$status = explode(" ", $status);
$status = $status[1];
list($partHeaders, $partBody) = $this->client->getIo()->ParseHttpResponse($part, false);
$response = new Google_Http_Request("");
$response->setResponseHttpCode($status);
$response->setResponseHeaders($partHeaders);
$response->setResponseBody($partBody);
// Need content id.
$key = $metaHeaders['content-id'];
if (isset($this->expected_classes[$key]) &&
strlen($this->expected_classes[$key]) > 0) {
$class = $this->expected_classes[$key];
$response->setExpectedClass($class);
}
try {
$response = Google_Http_REST::decodeHttpResponse($response);
$responses[$key] = $response;
} catch (Google_Service_Exception $e) {
// Store the exception as the response, so succesful responses
// can be processed.
$responses[$key] = $e;
}
}
}
return $responses;
}
return null;
}
} }

View file

@ -22,163 +22,158 @@ require_once 'Google/Http/Request.php';
* implementation is guided by the guidance offered in rfc2616-sec13. * implementation is guided by the guidance offered in rfc2616-sec13.
* @author Chirag Shah <chirags@google.com> * @author Chirag Shah <chirags@google.com>
*/ */
class Google_Http_CacheParser class Google_Http_CacheParser {
{ public static $CACHEABLE_HTTP_METHODS = array('GET', 'HEAD');
public static $CACHEABLE_HTTP_METHODS = array('GET', 'HEAD'); public static $CACHEABLE_STATUS_CODES = array('200', '203', '300', '301');
public static $CACHEABLE_STATUS_CODES = array('200', '203', '300', '301');
/** /**
* Check if an HTTP request can be cached by a private local cache. * Check if an HTTP request can be cached by a private local cache.
* *
* @static * @static
* @param Google_Http_Request $resp * @param Google_Http_Request $resp
* @return bool True if the request is cacheable. * @return bool True if the request is cacheable.
* False if the request is uncacheable. * False if the request is uncacheable.
*/ */
public static function isRequestCacheable(Google_Http_Request $resp) public static function isRequestCacheable(Google_Http_Request $resp) {
{ $method = $resp->getRequestMethod();
$method = $resp->getRequestMethod(); if (!in_array($method, self::$CACHEABLE_HTTP_METHODS)) {
if (! in_array($method, self::$CACHEABLE_HTTP_METHODS)) { return false;
return false; }
}
// Don't cache authorized requests/responses. // Don't cache authorized requests/responses.
// [rfc2616-14.8] When a shared cache receives a request containing an // [rfc2616-14.8] When a shared cache receives a request containing an
// Authorization field, it MUST NOT return the corresponding response // Authorization field, it MUST NOT return the corresponding response
// as a reply to any other request... // as a reply to any other request...
if ($resp->getRequestHeader("authorization")) { if ($resp->getRequestHeader("authorization")) {
return false; return false;
} }
return true;
}
/**
* Check if an HTTP response can be cached by a private local cache.
*
* @static
* @param Google_Http_Request $resp
* @return bool True if the response is cacheable.
* False if the response is un-cacheable.
*/
public static function isResponseCacheable(Google_Http_Request $resp)
{
// First, check if the HTTP request was cacheable before inspecting the
// HTTP response.
if (false == self::isRequestCacheable($resp)) {
return false;
}
$code = $resp->getResponseHttpCode();
if (! in_array($code, self::$CACHEABLE_STATUS_CODES)) {
return false;
}
// The resource is uncacheable if the resource is already expired and
// the resource doesn't have an ETag for revalidation.
$etag = $resp->getResponseHeader("etag");
if (self::isExpired($resp) && $etag == false) {
return false;
}
// [rfc2616-14.9.2] If [no-store is] sent in a response, a cache MUST NOT
// store any part of either this response or the request that elicited it.
$cacheControl = $resp->getParsedCacheControl();
if (isset($cacheControl['no-store'])) {
return false;
}
// Pragma: no-cache is an http request directive, but is occasionally
// used as a response header incorrectly.
$pragma = $resp->getResponseHeader('pragma');
if ($pragma == 'no-cache' || strpos($pragma, 'no-cache') !== false) {
return false;
}
// [rfc2616-14.44] Vary: * is extremely difficult to cache. "It implies that
// a cache cannot determine from the request headers of a subsequent request
// whether this response is the appropriate representation."
// Given this, we deem responses with the Vary header as uncacheable.
$vary = $resp->getResponseHeader('vary');
if ($vary) {
return false;
}
return true;
}
/**
* @static
* @param Google_Http_Request $resp
* @return bool True if the HTTP response is considered to be expired.
* False if it is considered to be fresh.
*/
public static function isExpired(Google_Http_Request $resp)
{
// HTTP/1.1 clients and caches MUST treat other invalid date formats,
// especially including the value “0”, as in the past.
$parsedExpires = false;
$responseHeaders = $resp->getResponseHeaders();
if (isset($responseHeaders['expires'])) {
$rawExpires = $responseHeaders['expires'];
// Check for a malformed expires header first.
if (empty($rawExpires) || (is_numeric($rawExpires) && $rawExpires <= 0)) {
return true; return true;
} }
/**
* Check if an HTTP response can be cached by a private local cache.
*
* @static
* @param Google_Http_Request $resp
* @return bool True if the response is cacheable.
* False if the response is un-cacheable.
*/
public static function isResponseCacheable(Google_Http_Request $resp) {
// First, check if the HTTP request was cacheable before inspecting the
// HTTP response.
if (false == self::isRequestCacheable($resp)) {
return false;
}
$code = $resp->getResponseHttpCode();
if (!in_array($code, self::$CACHEABLE_STATUS_CODES)) {
return false;
}
// The resource is uncacheable if the resource is already expired and
// the resource doesn't have an ETag for revalidation.
$etag = $resp->getResponseHeader("etag");
if (self::isExpired($resp) && $etag == false) {
return false;
}
// [rfc2616-14.9.2] If [no-store is] sent in a response, a cache MUST NOT
// store any part of either this response or the request that elicited it.
$cacheControl = $resp->getParsedCacheControl();
if (isset($cacheControl['no-store'])) {
return false;
}
// Pragma: no-cache is an http request directive, but is occasionally
// used as a response header incorrectly.
$pragma = $resp->getResponseHeader('pragma');
if ($pragma == 'no-cache' || strpos($pragma, 'no-cache') !== false) {
return false;
}
// [rfc2616-14.44] Vary: * is extremely difficult to cache. "It implies that
// a cache cannot determine from the request headers of a subsequent request
// whether this response is the appropriate representation."
// Given this, we deem responses with the Vary header as uncacheable.
$vary = $resp->getResponseHeader('vary');
if ($vary) {
return false;
}
// See if we can parse the expires header.
$parsedExpires = strtotime($rawExpires);
if (false == $parsedExpires || $parsedExpires <= 0) {
return true; return true;
}
} }
// Calculate the freshness of an http response. /**
$freshnessLifetime = false; * @static
$cacheControl = $resp->getParsedCacheControl(); * @param Google_Http_Request $resp
if (isset($cacheControl['max-age'])) { * @return bool True if the HTTP response is considered to be expired.
$freshnessLifetime = $cacheControl['max-age']; * False if it is considered to be fresh.
*/
public static function isExpired(Google_Http_Request $resp) {
// HTTP/1.1 clients and caches MUST treat other invalid date formats,
// especially including the value “0”, as in the past.
$parsedExpires = false;
$responseHeaders = $resp->getResponseHeaders();
if (isset($responseHeaders['expires'])) {
$rawExpires = $responseHeaders['expires'];
// Check for a malformed expires header first.
if (empty($rawExpires) || (is_numeric($rawExpires) && $rawExpires <= 0)) {
return true;
}
// See if we can parse the expires header.
$parsedExpires = strtotime($rawExpires);
if (false == $parsedExpires || $parsedExpires <= 0) {
return true;
}
}
// Calculate the freshness of an http response.
$freshnessLifetime = false;
$cacheControl = $resp->getParsedCacheControl();
if (isset($cacheControl['max-age'])) {
$freshnessLifetime = $cacheControl['max-age'];
}
$rawDate = $resp->getResponseHeader('date');
$parsedDate = strtotime($rawDate);
if (empty($rawDate) || false == $parsedDate) {
// We can't default this to now, as that means future cache reads
// will always pass with the logic below, so we will require a
// date be injected if not supplied.
throw new Google_Exception("All cacheable requests must have creation dates.");
}
if (false == $freshnessLifetime && isset($responseHeaders['expires'])) {
$freshnessLifetime = $parsedExpires - $parsedDate;
}
if (false == $freshnessLifetime) {
return true;
}
// Calculate the age of an http response.
$age = max(0, time() - $parsedDate);
if (isset($responseHeaders['age'])) {
$age = max($age, strtotime($responseHeaders['age']));
}
return $freshnessLifetime <= $age;
} }
$rawDate = $resp->getResponseHeader('date'); /**
$parsedDate = strtotime($rawDate); * Determine if a cache entry should be revalidated with by the origin.
*
if (empty($rawDate) || false == $parsedDate) { * @param Google_Http_Request $response
// We can't default this to now, as that means future cache reads * @return bool True if the entry is expired, else return false.
// will always pass with the logic below, so we will require a */
// date be injected if not supplied. public static function mustRevalidate(Google_Http_Request $response) {
throw new Google_Exception("All cacheable requests must have creation dates."); // [13.3] When a cache has a stale entry that it would like to use as a
// response to a client's request, it first has to check with the origin
// server to see if its cached entry is still usable.
return self::isExpired($response);
} }
if (false == $freshnessLifetime && isset($responseHeaders['expires'])) {
$freshnessLifetime = $parsedExpires - $parsedDate;
}
if (false == $freshnessLifetime) {
return true;
}
// Calculate the age of an http response.
$age = max(0, time() - $parsedDate);
if (isset($responseHeaders['age'])) {
$age = max($age, strtotime($responseHeaders['age']));
}
return $freshnessLifetime <= $age;
}
/**
* Determine if a cache entry should be revalidated with by the origin.
*
* @param Google_Http_Request $response
* @return bool True if the entry is expired, else return false.
*/
public static function mustRevalidate(Google_Http_Request $response)
{
// [13.3] When a cache has a stale entry that it would like to use as a
// response to a client's request, it first has to check with the origin
// server to see if its cached entry is still usable.
return self::isExpired($response);
}
} }

View file

@ -25,268 +25,259 @@ require_once 'Google/Utils.php';
* @author Chirag Shah <chirags@google.com> * @author Chirag Shah <chirags@google.com>
* *
*/ */
class Google_Http_MediaFileUpload class Google_Http_MediaFileUpload {
{ const UPLOAD_MEDIA_TYPE = 'media';
const UPLOAD_MEDIA_TYPE = 'media'; const UPLOAD_MULTIPART_TYPE = 'multipart';
const UPLOAD_MULTIPART_TYPE = 'multipart'; const UPLOAD_RESUMABLE_TYPE = 'resumable';
const UPLOAD_RESUMABLE_TYPE = 'resumable';
/** @var string $mimeType */ /** @var string $mimeType */
private $mimeType; private $mimeType;
/** @var string $data */ /** @var string $data */
private $data; private $data;
/** @var bool $resumable */ /** @var bool $resumable */
private $resumable; private $resumable;
/** @var int $chunkSize */ /** @var int $chunkSize */
private $chunkSize; private $chunkSize;
/** @var int $size */ /** @var int $size */
private $size; private $size;
/** @var string $resumeUri */ /** @var string $resumeUri */
private $resumeUri; private $resumeUri;
/** @var int $progress */ /** @var int $progress */
private $progress; private $progress;
/** @var Google_Client */ /** @var Google_Client */
private $client; private $client;
/** @var Google_Http_Request */ /** @var Google_Http_Request */
private $request; private $request;
/** @var string */ /** @var string */
private $boundary; private $boundary;
/** /**
* Result code from last HTTP call * Result code from last HTTP call
* @var int * @var int
*/ */
private $httpResultCode; private $httpResultCode;
/** /**
* @param $mimeType string * @param $mimeType string
* @param $data string The bytes you want to upload. * @param $data string The bytes you want to upload.
* @param $resumable bool * @param $resumable bool
* @param bool $chunkSize File will be uploaded in chunks of this many bytes. * @param bool $chunkSize File will be uploaded in chunks of this many bytes.
* only used if resumable=True * only used if resumable=True
*/ */
public function __construct( public function __construct(
Google_Client $client, Google_Client $client,
Google_Http_Request $request, Google_Http_Request $request,
$mimeType, $mimeType,
$data, $data,
$resumable = false, $resumable = false,
$chunkSize = false, $chunkSize = false,
$boundary = false $boundary = false
) { ) {
$this->client = $client; $this->client = $client;
$this->request = $request; $this->request = $request;
$this->mimeType = $mimeType; $this->mimeType = $mimeType;
$this->data = $data; $this->data = $data;
$this->size = strlen($this->data); $this->size = strlen($this->data);
$this->resumable = $resumable; $this->resumable = $resumable;
if (!$chunkSize) { if (!$chunkSize) {
$chunkSize = 256 * 1024; $chunkSize = 256 * 1024;
} }
$this->chunkSize = $chunkSize; $this->chunkSize = $chunkSize;
$this->progress = 0; $this->progress = 0;
$this->boundary = $boundary; $this->boundary = $boundary;
// Process Media Request // Process Media Request
$this->process(); $this->process();
}
/**
* Set the size of the file that is being uploaded.
* @param $size - int file size in bytes
*/
public function setFileSize($size)
{
$this->size = $size;
}
/**
* Return the progress on the upload
* @return int progress in bytes uploaded.
*/
public function getProgress()
{
return $this->progress;
}
/**
* Return the HTTP result code from the last call made.
* @return int code
*/
public function getHttpResultCode()
{
return $this->httpResultCode;
}
/**
* Send the next part of the file to upload.
* @param [$chunk] the next set of bytes to send. If false will used $data passed
* at construct time.
*/
public function nextChunk($chunk = false)
{
if (false == $this->resumeUri) {
$this->resumeUri = $this->getResumeUri();
} }
if (false == $chunk) { /**
$chunk = substr($this->data, $this->progress, $this->chunkSize); * Set the size of the file that is being uploaded.
* @param $size - int file size in bytes
*/
public function setFileSize($size) {
$this->size = $size;
} }
$lastBytePos = $this->progress + strlen($chunk) - 1; /**
$headers = array( * Return the progress on the upload
'content-range' => "bytes $this->progress-$lastBytePos/$this->size", * @return int progress in bytes uploaded.
'content-type' => $this->request->getRequestHeader('content-type'), */
'content-length' => $this->chunkSize, public function getProgress() {
'expect' => '', return $this->progress;
);
$httpRequest = new Google_Http_Request(
$this->resumeUri,
'PUT',
$headers,
$chunk
);
if ($this->client->getClassConfig("Google_Http_Request", "enable_gzip_for_uploads")) {
$httpRequest->enableGzip();
} else {
$httpRequest->disableGzip();
} }
$response = $this->client->getIo()->makeRequest($httpRequest); /**
$response->setExpectedClass($this->request->getExpectedClass()); * Return the HTTP result code from the last call made.
$code = $response->getResponseHttpCode(); * @return int code
$this->httpResultCode = $code; */
public function getHttpResultCode() {
if (308 == $code) { return $this->httpResultCode;
// Track the amount uploaded.
$range = explode('-', $response->getResponseHeader('range'));
$this->progress = $range[1] + 1;
// Allow for changing upload URLs.
$location = $response->getResponseHeader('location');
if ($location) {
$this->resumeUri = $location;
}
// No problems, but upload not complete.
return false;
} else {
return Google_Http_REST::decodeHttpResponse($response);
}
}
/**
* @param $meta
* @param $params
* @return array|bool
* @visible for testing
*/
private function process()
{
$postBody = false;
$contentType = false;
$meta = $this->request->getPostBody();
$meta = is_string($meta) ? json_decode($meta, true) : $meta;
$uploadType = $this->getUploadType($meta);
$this->request->setQueryParam('uploadType', $uploadType);
$this->transformToUploadUrl();
$mimeType = $this->mimeType ?
$this->mimeType :
$this->request->getRequestHeader('content-type');
if (self::UPLOAD_RESUMABLE_TYPE == $uploadType) {
$contentType = $mimeType;
$postBody = is_string($meta) ? $meta : json_encode($meta);
} else if (self::UPLOAD_MEDIA_TYPE == $uploadType) {
$contentType = $mimeType;
$postBody = $this->data;
} else if (self::UPLOAD_MULTIPART_TYPE == $uploadType) {
// This is a multipart/related upload.
$boundary = $this->boundary ? $this->boundary : mt_rand();
$boundary = str_replace('"', '', $boundary);
$contentType = 'multipart/related; boundary=' . $boundary;
$related = "--$boundary\r\n";
$related .= "Content-Type: application/json; charset=UTF-8\r\n";
$related .= "\r\n" . json_encode($meta) . "\r\n";
$related .= "--$boundary\r\n";
$related .= "Content-Type: $mimeType\r\n";
$related .= "Content-Transfer-Encoding: base64\r\n";
$related .= "\r\n" . base64_encode($this->data) . "\r\n";
$related .= "--$boundary--";
$postBody = $related;
} }
$this->request->setPostBody($postBody); /**
* Send the next part of the file to upload.
* @param [$chunk] the next set of bytes to send. If false will used $data passed
* at construct time.
*/
public function nextChunk($chunk = false) {
if (false == $this->resumeUri) {
$this->resumeUri = $this->getResumeUri();
}
if (isset($contentType) && $contentType) { if (false == $chunk) {
$contentTypeHeader['content-type'] = $contentType; $chunk = substr($this->data, $this->progress, $this->chunkSize);
$this->request->setRequestHeaders($contentTypeHeader); }
}
}
private function transformToUploadUrl() $lastBytePos = $this->progress + strlen($chunk) - 1;
{ $headers = array(
$base = $this->request->getBaseComponent(); 'content-range' => "bytes $this->progress-$lastBytePos/$this->size",
$this->request->setBaseComponent($base . '/upload'); 'content-type' => $this->request->getRequestHeader('content-type'),
} 'content-length' => $this->chunkSize,
'expect' => '',
);
/** $httpRequest = new Google_Http_Request(
* Valid upload types: $this->resumeUri,
* - resumable (UPLOAD_RESUMABLE_TYPE) 'PUT',
* - media (UPLOAD_MEDIA_TYPE) $headers,
* - multipart (UPLOAD_MULTIPART_TYPE) $chunk
* @param $meta );
* @return string
* @visible for testing if ($this->client->getClassConfig("Google_Http_Request", "enable_gzip_for_uploads")) {
*/ $httpRequest->enableGzip();
public function getUploadType($meta) } else {
{ $httpRequest->disableGzip();
if ($this->resumable) { }
return self::UPLOAD_RESUMABLE_TYPE;
$response = $this->client->getIo()->makeRequest($httpRequest);
$response->setExpectedClass($this->request->getExpectedClass());
$code = $response->getResponseHttpCode();
$this->httpResultCode = $code;
if (308 == $code) {
// Track the amount uploaded.
$range = explode('-', $response->getResponseHeader('range'));
$this->progress = $range[1] + 1;
// Allow for changing upload URLs.
$location = $response->getResponseHeader('location');
if ($location) {
$this->resumeUri = $location;
}
// No problems, but upload not complete.
return false;
} else {
return Google_Http_REST::decodeHttpResponse($response);
}
} }
if (false == $meta && $this->data) { /**
return self::UPLOAD_MEDIA_TYPE; * @param $meta
* @param $params
* @return array|bool
* @visible for testing
*/
private function process() {
$postBody = false;
$contentType = false;
$meta = $this->request->getPostBody();
$meta = is_string($meta) ? json_decode($meta, true) : $meta;
$uploadType = $this->getUploadType($meta);
$this->request->setQueryParam('uploadType', $uploadType);
$this->transformToUploadUrl();
$mimeType = $this->mimeType ?
$this->mimeType :
$this->request->getRequestHeader('content-type');
if (self::UPLOAD_RESUMABLE_TYPE == $uploadType) {
$contentType = $mimeType;
$postBody = is_string($meta) ? $meta : json_encode($meta);
} elseif (self::UPLOAD_MEDIA_TYPE == $uploadType) {
$contentType = $mimeType;
$postBody = $this->data;
} elseif (self::UPLOAD_MULTIPART_TYPE == $uploadType) {
// This is a multipart/related upload.
$boundary = $this->boundary ? $this->boundary : mt_rand();
$boundary = str_replace('"', '', $boundary);
$contentType = 'multipart/related; boundary=' . $boundary;
$related = "--$boundary\r\n";
$related .= "Content-Type: application/json; charset=UTF-8\r\n";
$related .= "\r\n" . json_encode($meta) . "\r\n";
$related .= "--$boundary\r\n";
$related .= "Content-Type: $mimeType\r\n";
$related .= "Content-Transfer-Encoding: base64\r\n";
$related .= "\r\n" . base64_encode($this->data) . "\r\n";
$related .= "--$boundary--";
$postBody = $related;
}
$this->request->setPostBody($postBody);
if (isset($contentType) && $contentType) {
$contentTypeHeader['content-type'] = $contentType;
$this->request->setRequestHeaders($contentTypeHeader);
}
} }
return self::UPLOAD_MULTIPART_TYPE; private function transformToUploadUrl() {
} $base = $this->request->getBaseComponent();
$this->request->setBaseComponent($base . '/upload');
private function getResumeUri()
{
$result = null;
$body = $this->request->getPostBody();
if ($body) {
$headers = array(
'content-type' => 'application/json; charset=UTF-8',
'content-length' => Google_Utils::getStrLen($body),
'x-upload-content-type' => $this->mimeType,
'x-upload-content-length' => $this->size,
'expect' => '',
);
$this->request->setRequestHeaders($headers);
} }
$response = $this->client->getIo()->makeRequest($this->request); /**
$location = $response->getResponseHeader('location'); * Valid upload types:
$code = $response->getResponseHttpCode(); * - resumable (UPLOAD_RESUMABLE_TYPE)
* - media (UPLOAD_MEDIA_TYPE)
* - multipart (UPLOAD_MULTIPART_TYPE)
* @param $meta
* @return string
* @visible for testing
*/
public function getUploadType($meta) {
if ($this->resumable) {
return self::UPLOAD_RESUMABLE_TYPE;
}
if (200 == $code && true == $location) { if (false == $meta && $this->data) {
return $location; return self::UPLOAD_MEDIA_TYPE;
}
return self::UPLOAD_MULTIPART_TYPE;
}
private function getResumeUri() {
$result = null;
$body = $this->request->getPostBody();
if ($body) {
$headers = array(
'content-type' => 'application/json; charset=UTF-8',
'content-length' => Google_Utils::getStrLen($body),
'x-upload-content-type' => $this->mimeType,
'x-upload-content-length' => $this->size,
'expect' => '',
);
$this->request->setRequestHeaders($headers);
}
$response = $this->client->getIo()->makeRequest($this->request);
$location = $response->getResponseHeader('location');
$code = $response->getResponseHttpCode();
if (200 == $code && true == $location) {
return $location;
}
throw new Google_Exception("Failed to start the resumable upload");
} }
throw new Google_Exception("Failed to start the resumable upload");
}
} }

View file

@ -26,114 +26,110 @@ require_once 'Google/Utils/URITemplate.php';
* @author Chris Chabot <chabotc@google.com> * @author Chris Chabot <chabotc@google.com>
* @author Chirag Shah <chirags@google.com> * @author Chirag Shah <chirags@google.com>
*/ */
class Google_Http_REST class Google_Http_REST {
{ /**
/** * Executes a Google_Http_Request
* Executes a Google_Http_Request *
* * @param Google_Client $client
* @param Google_Client $client * @param Google_Http_Request $req
* @param Google_Http_Request $req * @return array decoded result
* @return array decoded result * @throws Google_Service_Exception on server side error (ie: not authenticated,
* @throws Google_Service_Exception on server side error (ie: not authenticated, * invalid or malformed post body, invalid url)
* invalid or malformed post body, invalid url) */
*/ public static function execute(Google_Client $client, Google_Http_Request $req) {
public static function execute(Google_Client $client, Google_Http_Request $req) $httpRequest = $client->getIo()->makeRequest($req);
{ $httpRequest->setExpectedClass($req->getExpectedClass());
$httpRequest = $client->getIo()->makeRequest($req); return self::decodeHttpResponse($httpRequest);
$httpRequest->setExpectedClass($req->getExpectedClass());
return self::decodeHttpResponse($httpRequest);
}
/**
* Decode an HTTP Response.
* @static
* @throws Google_Service_Exception
* @param Google_Http_Request $response The http response to be decoded.
* @return mixed|null
*/
public static function decodeHttpResponse($response)
{
$code = $response->getResponseHttpCode();
$body = $response->getResponseBody();
$decoded = null;
if ((intVal($code)) >= 300) {
$decoded = json_decode($body, true);
$err = 'Error calling ' . $response->getRequestMethod() . ' ' . $response->getUrl();
if (isset($decoded['error']) &&
isset($decoded['error']['message']) &&
isset($decoded['error']['code'])) {
// if we're getting a json encoded error definition, use that instead of the raw response
// body for improved readability
$err .= ": ({$decoded['error']['code']}) {$decoded['error']['message']}";
} else {
$err .= ": ($code) $body";
}
$errors = null;
// Specific check for APIs which don't return error details, such as Blogger.
if (isset($decoded['error']) && isset($decoded['error']['errors'])) {
$errors = $decoded['error']['errors'];
}
throw new Google_Service_Exception($err, $code, null, $errors);
} }
// Only attempt to decode the response, if the response code wasn't (204) 'no content' /**
if ($code != '204') { * Decode an HTTP Response.
$decoded = json_decode($body, true); * @static
if ($decoded === null || $decoded === "") { * @param Google_Http_Request $response The http response to be decoded.
throw new Google_Service_Exception("Invalid json in service response: $body"); * @return mixed|null
} * @throws Google_Service_Exception
*/
public static function decodeHttpResponse($response) {
$code = $response->getResponseHttpCode();
$body = $response->getResponseBody();
$decoded = null;
if ($response->getExpectedClass()) { if ((intVal($code)) >= 300) {
$class = $response->getExpectedClass(); $decoded = json_decode($body, true);
$decoded = new $class($decoded); $err = 'Error calling ' . $response->getRequestMethod() . ' ' . $response->getUrl();
} if (isset($decoded['error']) &&
} isset($decoded['error']['message']) &&
return $decoded; isset($decoded['error']['code'])) {
} // if we're getting a json encoded error definition, use that instead of the raw response
// body for improved readability
$err .= ": ({$decoded['error']['code']}) {$decoded['error']['message']}";
} else {
$err .= ": ($code) $body";
}
/** $errors = null;
* Parse/expand request parameters and create a fully qualified // Specific check for APIs which don't return error details, such as Blogger.
* request uri. if (isset($decoded['error']) && isset($decoded['error']['errors'])) {
* @static $errors = $decoded['error']['errors'];
* @param string $servicePath }
* @param string $restPath
* @param array $params throw new Google_Service_Exception($err, $code, null, $errors);
* @return string $requestUrl
*/
public static function createRequestUri($servicePath, $restPath, $params)
{
$requestUrl = $servicePath . $restPath;
$uriTemplateVars = array();
$queryVars = array();
foreach ($params as $paramName => $paramSpec) {
if ($paramSpec['type'] == 'boolean') {
$paramSpec['value'] = ($paramSpec['value']) ? 'true' : 'false';
}
if ($paramSpec['location'] == 'path') {
$uriTemplateVars[$paramName] = $paramSpec['value'];
} else if ($paramSpec['location'] == 'query') {
if (isset($paramSpec['repeated']) && is_array($paramSpec['value'])) {
foreach ($paramSpec['value'] as $value) {
$queryVars[] = $paramName . '=' . rawurlencode($value);
}
} else {
$queryVars[] = $paramName . '=' . rawurlencode($paramSpec['value']);
} }
}
// Only attempt to decode the response, if the response code wasn't (204) 'no content'
if ($code != '204') {
$decoded = json_decode($body, true);
if ($decoded === null || $decoded === "") {
throw new Google_Service_Exception("Invalid json in service response: $body");
}
if ($response->getExpectedClass()) {
$class = $response->getExpectedClass();
$decoded = new $class($decoded);
}
}
return $decoded;
} }
if (count($uriTemplateVars)) { /**
$uriTemplateParser = new Google_Utils_URITemplate(); * Parse/expand request parameters and create a fully qualified
$requestUrl = $uriTemplateParser->parse($requestUrl, $uriTemplateVars); * request uri.
} * @static
* @param string $servicePath
* @param string $restPath
* @param array $params
* @return string $requestUrl
*/
public static function createRequestUri($servicePath, $restPath, $params) {
$requestUrl = $servicePath . $restPath;
$uriTemplateVars = array();
$queryVars = array();
foreach ($params as $paramName => $paramSpec) {
if ($paramSpec['type'] == 'boolean') {
$paramSpec['value'] = ($paramSpec['value']) ? 'true' : 'false';
}
if ($paramSpec['location'] == 'path') {
$uriTemplateVars[$paramName] = $paramSpec['value'];
} elseif ($paramSpec['location'] == 'query') {
if (isset($paramSpec['repeated']) && is_array($paramSpec['value'])) {
foreach ($paramSpec['value'] as $value) {
$queryVars[] = $paramName . '=' . rawurlencode($value);
}
} else {
$queryVars[] = $paramName . '=' . rawurlencode($paramSpec['value']);
}
}
}
if (count($queryVars)) { if (count($uriTemplateVars)) {
$requestUrl .= '?' . implode($queryVars, '&'); $uriTemplateParser = new Google_Utils_URITemplate();
} $requestUrl = $uriTemplateParser->parse($requestUrl, $uriTemplateVars);
}
return $requestUrl; if (count($queryVars)) {
} $requestUrl .= '?' . implode($queryVars, '&');
}
return $requestUrl;
}
} }

View file

@ -25,452 +25,418 @@ require_once 'Google/Utils.php';
* @author Chirag Shah <chirags@google.com> * @author Chirag Shah <chirags@google.com>
* *
*/ */
class Google_Http_Request class Google_Http_Request {
{ const GZIP_UA = " (gzip)";
const GZIP_UA = " (gzip)";
private $batchHeaders = array( private $batchHeaders = array(
'Content-Type' => 'application/http', 'Content-Type' => 'application/http',
'Content-Transfer-Encoding' => 'binary', 'Content-Transfer-Encoding' => 'binary',
'MIME-Version' => '1.0', 'MIME-Version' => '1.0',
); );
protected $queryParams; protected $queryParams;
protected $requestMethod; protected $requestMethod;
protected $requestHeaders; protected $requestHeaders;
protected $baseComponent = null; protected $baseComponent = null;
protected $path; protected $path;
protected $postBody; protected $postBody;
protected $userAgent; protected $userAgent;
protected $canGzip = null; protected $canGzip = null;
protected $responseHttpCode; protected $responseHttpCode;
protected $responseHeaders; protected $responseHeaders;
protected $responseBody; protected $responseBody;
protected $expectedClass;
public $accessKey; protected $expectedClass;
public function __construct( public $accessKey;
$url,
$method = 'GET',
$headers = array(),
$postBody = null
) {
$this->setUrl($url);
$this->setRequestMethod($method);
$this->setRequestHeaders($headers);
$this->setPostBody($postBody);
}
/** public function __construct(
* Misc function that returns the base url component of the $url $url,
* used by the OAuth signing class to calculate the base string $method = 'GET',
* @return string The base url component of the $url. $headers = array(),
*/ $postBody = null
public function getBaseComponent()
{
return $this->baseComponent;
}
/**
* Set the base URL that path and query parameters will be added to.
* @param $baseComponent string
*/
public function setBaseComponent($baseComponent)
{
$this->baseComponent = $baseComponent;
}
/**
* Enable support for gzipped responses with this request.
*/
public function enableGzip()
{
$this->setRequestHeaders(array("Accept-Encoding" => "gzip"));
$this->canGzip = true;
$this->setUserAgent($this->userAgent);
}
/**
* Disable support for gzip responses with this request.
*/
public function disableGzip()
{
if (
isset($this->requestHeaders['accept-encoding']) &&
$this->requestHeaders['accept-encoding'] == "gzip"
) { ) {
unset($this->requestHeaders['accept-encoding']); $this->setUrl($url);
} $this->setRequestMethod($method);
$this->canGzip = false; $this->setRequestHeaders($headers);
$this->userAgent = str_replace(self::GZIP_UA, "", $this->userAgent); $this->setPostBody($postBody);
}
/**
* Can this request accept a gzip response?
* @return bool
*/
public function canGzip()
{
return $this->canGzip;
}
/**
* Misc function that returns an array of the query parameters of the current
* url used by the OAuth signing class to calculate the signature
* @return array Query parameters in the query string.
*/
public function getQueryParams()
{
return $this->queryParams;
}
/**
* Set a new query parameter.
* @param $key - string to set, does not need to be URL encoded
* @param $value - string to set, does not need to be URL encoded
*/
public function setQueryParam($key, $value)
{
$this->queryParams[$key] = $value;
}
/**
* @return string HTTP Response Code.
*/
public function getResponseHttpCode()
{
return (int) $this->responseHttpCode;
}
/**
* @param int $responseHttpCode HTTP Response Code.
*/
public function setResponseHttpCode($responseHttpCode)
{
$this->responseHttpCode = $responseHttpCode;
}
/**
* @return $responseHeaders (array) HTTP Response Headers.
*/
public function getResponseHeaders()
{
return $this->responseHeaders;
}
/**
* @return string HTTP Response Body
*/
public function getResponseBody()
{
return $this->responseBody;
}
/**
* Set the class the response to this request should expect.
*
* @param $class string the class name
*/
public function setExpectedClass($class)
{
$this->expectedClass = $class;
}
/**
* Retrieve the expected class the response should expect.
* @return string class name
*/
public function getExpectedClass()
{
return $this->expectedClass;
}
/**
* @param array $headers The HTTP response headers
* to be normalized.
*/
public function setResponseHeaders($headers)
{
$headers = Google_Utils::normalize($headers);
if ($this->responseHeaders) {
$headers = array_merge($this->responseHeaders, $headers);
} }
$this->responseHeaders = $headers; /**
} * Misc function that returns the base url component of the $url
* used by the OAuth signing class to calculate the base string
/** * @return string The base url component of the $url.
* @param string $key */
* @return array|boolean Returns the requested HTTP header or public function getBaseComponent() {
* false if unavailable. return $this->baseComponent;
*/
public function getResponseHeader($key)
{
return isset($this->responseHeaders[$key])
? $this->responseHeaders[$key]
: false;
}
/**
* @param string $responseBody The HTTP response body.
*/
public function setResponseBody($responseBody)
{
$this->responseBody = $responseBody;
}
/**
* @return string $url The request URL.
*/
public function getUrl()
{
return $this->baseComponent . $this->path .
(count($this->queryParams) ?
"?" . $this->buildQuery($this->queryParams) :
'');
}
/**
* @return string $method HTTP Request Method.
*/
public function getRequestMethod()
{
return $this->requestMethod;
}
/**
* @return array $headers HTTP Request Headers.
*/
public function getRequestHeaders()
{
return $this->requestHeaders;
}
/**
* @param string $key
* @return array|boolean Returns the requested HTTP header or
* false if unavailable.
*/
public function getRequestHeader($key)
{
return isset($this->requestHeaders[$key])
? $this->requestHeaders[$key]
: false;
}
/**
* @return string $postBody HTTP Request Body.
*/
public function getPostBody()
{
return $this->postBody;
}
/**
* @param string $url the url to set
*/
public function setUrl($url)
{
if (substr($url, 0, 4) != 'http') {
// Force the path become relative.
if (substr($url, 0, 1) !== '/') {
$url = '/' . $url;
}
}
$parts = parse_url($url);
if (isset($parts['host'])) {
$this->baseComponent = sprintf(
"%s%s%s",
isset($parts['scheme']) ? $parts['scheme'] . "://" : '',
isset($parts['host']) ? $parts['host'] : '',
isset($parts['port']) ? ":" . $parts['port'] : ''
);
}
$this->path = isset($parts['path']) ? $parts['path'] : '';
$this->queryParams = array();
if (isset($parts['query'])) {
$this->queryParams = $this->parseQuery($parts['query']);
}
}
/**
* @param string $method Set he HTTP Method and normalize
* it to upper-case, as required by HTTP.
*
*/
public function setRequestMethod($method)
{
$this->requestMethod = strtoupper($method);
}
/**
* @param array $headers The HTTP request headers
* to be set and normalized.
*/
public function setRequestHeaders($headers)
{
$headers = Google_Utils::normalize($headers);
if ($this->requestHeaders) {
$headers = array_merge($this->requestHeaders, $headers);
}
$this->requestHeaders = $headers;
}
/**
* @param string $postBody the postBody to set
*/
public function setPostBody($postBody)
{
$this->postBody = $postBody;
}
/**
* Set the User-Agent Header.
* @param string $userAgent The User-Agent.
*/
public function setUserAgent($userAgent)
{
$this->userAgent = $userAgent;
if ($this->canGzip) {
$this->userAgent = $userAgent . self::GZIP_UA;
}
}
/**
* @return string The User-Agent.
*/
public function getUserAgent()
{
return $this->userAgent;
}
/**
* Returns a cache key depending on if this was an OAuth signed request
* in which case it will use the non-signed url and access key to make this
* cache key unique per authenticated user, else use the plain request url
* @return string The md5 hash of the request cache key.
*/
public function getCacheKey()
{
$key = $this->getUrl();
if (isset($this->accessKey)) {
$key .= $this->accessKey;
} }
if (isset($this->requestHeaders['authorization'])) { /**
$key .= $this->requestHeaders['authorization']; * Set the base URL that path and query parameters will be added to.
* @param $baseComponent string
*/
public function setBaseComponent($baseComponent) {
$this->baseComponent = $baseComponent;
} }
return md5($key); /**
} * Enable support for gzipped responses with this request.
*/
public function getParsedCacheControl() public function enableGzip() {
{ $this->setRequestHeaders(array("Accept-Encoding" => "gzip"));
$parsed = array(); $this->canGzip = true;
$rawCacheControl = $this->getResponseHeader('cache-control'); $this->setUserAgent($this->userAgent);
if ($rawCacheControl) {
$rawCacheControl = str_replace(', ', '&', $rawCacheControl);
parse_str($rawCacheControl, $parsed);
} }
return $parsed; /**
} * Disable support for gzip responses with this request.
*/
/** public function disableGzip() {
* @param string $id if (
* @return string A string representation of the HTTP Request. isset($this->requestHeaders['accept-encoding']) &&
*/ $this->requestHeaders['accept-encoding'] == "gzip"
public function toBatchString($id) ) {
{ unset($this->requestHeaders['accept-encoding']);
$str = '';
$path = parse_url($this->getUrl(), PHP_URL_PATH) . "?" .
http_build_query($this->queryParams);
$str .= $this->getRequestMethod() . ' ' . $path . " HTTP/1.1\n";
foreach ($this->getRequestHeaders() as $key => $val) {
$str .= $key . ': ' . $val . "\n";
}
if ($this->getPostBody()) {
$str .= "\n";
$str .= $this->getPostBody();
}
$headers = '';
foreach ($this->batchHeaders as $key => $val) {
$headers .= $key . ': ' . $val . "\n";
}
$headers .= "Content-ID: $id\n";
$str = $headers . "\n" . $str;
return $str;
}
/**
* Our own version of parse_str that allows for multiple variables
* with the same name.
* @param $string - the query string to parse
*/
private function parseQuery($string)
{
$return = array();
$parts = explode("&", $string);
foreach ($parts as $part) {
list($key, $value) = explode('=', $part, 2);
$value = urldecode($value);
if (isset($return[$key])) {
if (!is_array($return[$key])) {
$return[$key] = array($return[$key]);
} }
$return[$key][] = $value; $this->canGzip = false;
} else { $this->userAgent = str_replace(self::GZIP_UA, "", $this->userAgent);
$return[$key] = $value;
}
} }
return $return;
} /**
* Can this request accept a gzip response?
/** * @return bool
* A version of build query that allows for multiple */
* duplicate keys. public function canGzip() {
* @param $parts array of key value pairs return $this->canGzip;
*/ }
private function buildQuery($parts)
{ /**
$return = array(); * Misc function that returns an array of the query parameters of the current
foreach ($parts as $key => $value) { * url used by the OAuth signing class to calculate the signature
if (is_array($value)) { * @return array Query parameters in the query string.
foreach ($value as $v) { */
$return[] = urlencode($key) . "=" . urlencode($v); public function getQueryParams() {
return $this->queryParams;
}
/**
* Set a new query parameter.
* @param $key - string to set, does not need to be URL encoded
* @param $value - string to set, does not need to be URL encoded
*/
public function setQueryParam($key, $value) {
$this->queryParams[$key] = $value;
}
/**
* @return string HTTP Response Code.
*/
public function getResponseHttpCode() {
return (int)$this->responseHttpCode;
}
/**
* @param int $responseHttpCode HTTP Response Code.
*/
public function setResponseHttpCode($responseHttpCode) {
$this->responseHttpCode = $responseHttpCode;
}
/**
* @return $responseHeaders (array) HTTP Response Headers.
*/
public function getResponseHeaders() {
return $this->responseHeaders;
}
/**
* @return string HTTP Response Body
*/
public function getResponseBody() {
return $this->responseBody;
}
/**
* Set the class the response to this request should expect.
*
* @param $class string the class name
*/
public function setExpectedClass($class) {
$this->expectedClass = $class;
}
/**
* Retrieve the expected class the response should expect.
* @return string class name
*/
public function getExpectedClass() {
return $this->expectedClass;
}
/**
* @param array $headers The HTTP response headers
* to be normalized.
*/
public function setResponseHeaders($headers) {
$headers = Google_Utils::normalize($headers);
if ($this->responseHeaders) {
$headers = array_merge($this->responseHeaders, $headers);
} }
} else {
$return[] = urlencode($key) . "=" . urlencode($value); $this->responseHeaders = $headers;
}
} }
return implode('&', $return);
} /**
* @param string $key
/** * @return array|boolean Returns the requested HTTP header or
* If we're POSTing and have no body to send, we can send the query * false if unavailable.
* parameters in there, which avoids length issues with longer query */
* params. public function getResponseHeader($key) {
*/ return isset($this->responseHeaders[$key])
public function maybeMoveParametersToBody() ? $this->responseHeaders[$key]
{ : false;
if ($this->getRequestMethod() == "POST" && empty($this->postBody)) { }
$this->setRequestHeaders(
array( /**
"content-type" => * @param string $responseBody The HTTP response body.
"application/x-www-form-urlencoded; charset=UTF-8" */
) public function setResponseBody($responseBody) {
); $this->responseBody = $responseBody;
$this->setPostBody($this->buildQuery($this->queryParams)); }
$this->queryParams = array();
/**
* @return string $url The request URL.
*/
public function getUrl() {
return $this->baseComponent . $this->path .
(count($this->queryParams) ?
"?" . $this->buildQuery($this->queryParams) :
'');
}
/**
* @return string $method HTTP Request Method.
*/
public function getRequestMethod() {
return $this->requestMethod;
}
/**
* @return array $headers HTTP Request Headers.
*/
public function getRequestHeaders() {
return $this->requestHeaders;
}
/**
* @param string $key
* @return array|boolean Returns the requested HTTP header or
* false if unavailable.
*/
public function getRequestHeader($key) {
return isset($this->requestHeaders[$key])
? $this->requestHeaders[$key]
: false;
}
/**
* @return string $postBody HTTP Request Body.
*/
public function getPostBody() {
return $this->postBody;
}
/**
* @param string $url the url to set
*/
public function setUrl($url) {
if (substr($url, 0, 4) != 'http') {
// Force the path become relative.
if (substr($url, 0, 1) !== '/') {
$url = '/' . $url;
}
}
$parts = parse_url($url);
if (isset($parts['host'])) {
$this->baseComponent = sprintf(
"%s%s%s",
isset($parts['scheme']) ? $parts['scheme'] . "://" : '',
isset($parts['host']) ? $parts['host'] : '',
isset($parts['port']) ? ":" . $parts['port'] : ''
);
}
$this->path = isset($parts['path']) ? $parts['path'] : '';
$this->queryParams = array();
if (isset($parts['query'])) {
$this->queryParams = $this->parseQuery($parts['query']);
}
}
/**
* @param string $method Set he HTTP Method and normalize
* it to upper-case, as required by HTTP.
*
*/
public function setRequestMethod($method) {
$this->requestMethod = strtoupper($method);
}
/**
* @param array $headers The HTTP request headers
* to be set and normalized.
*/
public function setRequestHeaders($headers) {
$headers = Google_Utils::normalize($headers);
if ($this->requestHeaders) {
$headers = array_merge($this->requestHeaders, $headers);
}
$this->requestHeaders = $headers;
}
/**
* @param string $postBody the postBody to set
*/
public function setPostBody($postBody) {
$this->postBody = $postBody;
}
/**
* Set the User-Agent Header.
* @param string $userAgent The User-Agent.
*/
public function setUserAgent($userAgent) {
$this->userAgent = $userAgent;
if ($this->canGzip) {
$this->userAgent = $userAgent . self::GZIP_UA;
}
}
/**
* @return string The User-Agent.
*/
public function getUserAgent() {
return $this->userAgent;
}
/**
* Returns a cache key depending on if this was an OAuth signed request
* in which case it will use the non-signed url and access key to make this
* cache key unique per authenticated user, else use the plain request url
* @return string The md5 hash of the request cache key.
*/
public function getCacheKey() {
$key = $this->getUrl();
if (isset($this->accessKey)) {
$key .= $this->accessKey;
}
if (isset($this->requestHeaders['authorization'])) {
$key .= $this->requestHeaders['authorization'];
}
return md5($key);
}
public function getParsedCacheControl() {
$parsed = array();
$rawCacheControl = $this->getResponseHeader('cache-control');
if ($rawCacheControl) {
$rawCacheControl = str_replace(', ', '&', $rawCacheControl);
parse_str($rawCacheControl, $parsed);
}
return $parsed;
}
/**
* @param string $id
* @return string A string representation of the HTTP Request.
*/
public function toBatchString($id) {
$str = '';
$path = parse_url($this->getUrl(), PHP_URL_PATH) . "?" .
http_build_query($this->queryParams);
$str .= $this->getRequestMethod() . ' ' . $path . " HTTP/1.1\n";
foreach ($this->getRequestHeaders() as $key => $val) {
$str .= $key . ': ' . $val . "\n";
}
if ($this->getPostBody()) {
$str .= "\n";
$str .= $this->getPostBody();
}
$headers = '';
foreach ($this->batchHeaders as $key => $val) {
$headers .= $key . ': ' . $val . "\n";
}
$headers .= "Content-ID: $id\n";
$str = $headers . "\n" . $str;
return $str;
}
/**
* Our own version of parse_str that allows for multiple variables
* with the same name.
* @param $string - the query string to parse
*/
private function parseQuery($string) {
$return = array();
$parts = explode("&", $string);
foreach ($parts as $part) {
list($key, $value) = explode('=', $part, 2);
$value = urldecode($value);
if (isset($return[$key])) {
if (!is_array($return[$key])) {
$return[$key] = array($return[$key]);
}
$return[$key][] = $value;
} else {
$return[$key] = $value;
}
}
return $return;
}
/**
* A version of build query that allows for multiple
* duplicate keys.
* @param $parts array of key value pairs
*/
private function buildQuery($parts) {
$return = array();
foreach ($parts as $key => $value) {
if (is_array($value)) {
foreach ($value as $v) {
$return[] = urlencode($key) . "=" . urlencode($v);
}
} else {
$return[] = urlencode($key) . "=" . urlencode($value);
}
}
return implode('&', $return);
}
/**
* If we're POSTing and have no body to send, we can send the query
* parameters in there, which avoids length issues with longer query
* params.
*/
public function maybeMoveParametersToBody() {
if ($this->getRequestMethod() == "POST" && empty($this->postBody)) {
$this->setRequestHeaders(
array(
"content-type" =>
"application/x-www-form-urlencoded; charset=UTF-8"
)
);
$this->setPostBody($this->buildQuery($this->queryParams));
$this->queryParams = array();
}
} }
}
} }

View file

@ -24,306 +24,294 @@ require_once 'Google/IO/Exception.php';
require_once 'Google/Http/CacheParser.php'; require_once 'Google/Http/CacheParser.php';
require_once 'Google/Http/Request.php'; require_once 'Google/Http/Request.php';
abstract class Google_IO_Abstract abstract class Google_IO_Abstract {
{ const UNKNOWN_CODE = 0;
const UNKNOWN_CODE = 0; const FORM_URLENCODED = 'application/x-www-form-urlencoded';
const FORM_URLENCODED = 'application/x-www-form-urlencoded'; private static $CONNECTION_ESTABLISHED_HEADERS = array(
private static $CONNECTION_ESTABLISHED_HEADERS = array( "HTTP/1.0 200 Connection established\r\n\r\n",
"HTTP/1.0 200 Connection established\r\n\r\n", "HTTP/1.1 200 Connection established\r\n\r\n",
"HTTP/1.1 200 Connection established\r\n\r\n", );
); private static $ENTITY_HTTP_METHODS = array("POST" => null, "PUT" => null);
private static $ENTITY_HTTP_METHODS = array("POST" => null, "PUT" => null);
/** @var Google_Client */ /** @var Google_Client */
protected $client; protected $client;
public function __construct(Google_Client $client) public function __construct(Google_Client $client) {
{ $this->client = $client;
$this->client = $client; $timeout = $client->getClassConfig('Google_IO_Abstract', 'request_timeout_seconds');
$timeout = $client->getClassConfig('Google_IO_Abstract', 'request_timeout_seconds'); if ($timeout > 0) {
if ($timeout > 0) { $this->setTimeout($timeout);
$this->setTimeout($timeout);
}
}
/**
* Executes a Google_Http_Request and returns the resulting populated Google_Http_Request
* @param Google_Http_Request $request
* @return Google_Http_Request $request
*/
abstract public function executeRequest(Google_Http_Request $request);
/**
* Set options that update the transport implementation's behavior.
* @param $options
*/
abstract public function setOptions($options);
/**
* Set the maximum request time in seconds.
* @param $timeout in seconds
*/
abstract public function setTimeout($timeout);
/**
* Get the maximum request time in seconds.
* @return timeout in seconds
*/
abstract public function getTimeout();
/**
* Test for the presence of a cURL header processing bug
*
* The cURL bug was present in versions prior to 7.30.0 and caused the header
* length to be miscalculated when a "Connection established" header added by
* some proxies was present.
*
* @return boolean
*/
abstract protected function needsQuirk();
/**
* @visible for testing.
* Cache the response to an HTTP request if it is cacheable.
* @param Google_Http_Request $request
* @return bool Returns true if the insertion was successful.
* Otherwise, return false.
*/
public function setCachedRequest(Google_Http_Request $request)
{
// Determine if the request is cacheable.
if (Google_Http_CacheParser::isResponseCacheable($request)) {
$this->client->getCache()->set($request->getCacheKey(), $request);
return true;
}
return false;
}
/**
* Execute an HTTP Request
*
* @param Google_HttpRequest $request the http request to be executed
* @return Google_HttpRequest http request with the response http code,
* response headers and response body filled in
* @throws Google_IO_Exception on curl or IO error
*/
public function makeRequest(Google_Http_Request $request)
{
// First, check to see if we have a valid cached version.
$cached = $this->getCachedRequest($request);
if ($cached !== false && $cached instanceof Google_Http_Request) {
if (!$this->checkMustRevalidateCachedRequest($cached, $request)) {
return $cached;
}
}
if (array_key_exists($request->getRequestMethod(), self::$ENTITY_HTTP_METHODS)) {
$request = $this->processEntityRequest($request);
}
list($responseData, $responseHeaders, $respHttpCode) = $this->executeRequest($request);
if ($respHttpCode == 304 && $cached) {
// If the server responded NOT_MODIFIED, return the cached request.
$this->updateCachedRequest($cached, $responseHeaders);
return $cached;
}
if (!isset($responseHeaders['Date']) && !isset($responseHeaders['date'])) {
$responseHeaders['Date'] = date("r");
}
$request->setResponseHttpCode($respHttpCode);
$request->setResponseHeaders($responseHeaders);
$request->setResponseBody($responseData);
// Store the request in cache (the function checks to see if the request
// can actually be cached)
$this->setCachedRequest($request);
return $request;
}
/**
* @visible for testing.
* @param Google_Http_Request $request
* @return Google_Http_Request|bool Returns the cached object or
* false if the operation was unsuccessful.
*/
public function getCachedRequest(Google_Http_Request $request)
{
if (false === Google_Http_CacheParser::isRequestCacheable($request)) {
return false;
}
return $this->client->getCache()->get($request->getCacheKey());
}
/**
* @visible for testing
* Process an http request that contains an enclosed entity.
* @param Google_Http_Request $request
* @return Google_Http_Request Processed request with the enclosed entity.
*/
public function processEntityRequest(Google_Http_Request $request)
{
$postBody = $request->getPostBody();
$contentType = $request->getRequestHeader("content-type");
// Set the default content-type as application/x-www-form-urlencoded.
if (false == $contentType) {
$contentType = self::FORM_URLENCODED;
$request->setRequestHeaders(array('content-type' => $contentType));
}
// Force the payload to match the content-type asserted in the header.
if ($contentType == self::FORM_URLENCODED && is_array($postBody)) {
$postBody = http_build_query($postBody, '', '&');
$request->setPostBody($postBody);
}
// Make sure the content-length header is set.
if (!$postBody || is_string($postBody)) {
$postsLength = strlen($postBody);
$request->setRequestHeaders(array('content-length' => $postsLength));
}
return $request;
}
/**
* Check if an already cached request must be revalidated, and if so update
* the request with the correct ETag headers.
* @param Google_Http_Request $cached A previously cached response.
* @param Google_Http_Request $request The outbound request.
* return bool If the cached object needs to be revalidated, false if it is
* still current and can be re-used.
*/
protected function checkMustRevalidateCachedRequest($cached, $request)
{
if (Google_Http_CacheParser::mustRevalidate($cached)) {
$addHeaders = array();
if ($cached->getResponseHeader('etag')) {
// [13.3.4] If an entity tag has been provided by the origin server,
// we must use that entity tag in any cache-conditional request.
$addHeaders['If-None-Match'] = $cached->getResponseHeader('etag');
} elseif ($cached->getResponseHeader('date')) {
$addHeaders['If-Modified-Since'] = $cached->getResponseHeader('date');
}
$request->setRequestHeaders($addHeaders);
return true;
} else {
return false;
}
}
/**
* Update a cached request, using the headers from the last response.
* @param Google_HttpRequest $cached A previously cached response.
* @param mixed Associative array of response headers from the last request.
*/
protected function updateCachedRequest($cached, $responseHeaders)
{
if (isset($responseHeaders['connection'])) {
$hopByHop = array_merge(
self::$HOP_BY_HOP,
explode(
',',
$responseHeaders['connection']
)
);
$endToEnd = array();
foreach ($hopByHop as $key) {
if (isset($responseHeaders[$key])) {
$endToEnd[$key] = $responseHeaders[$key];
} }
}
$cached->setResponseHeaders($endToEnd);
} }
}
/** /**
* Used by the IO lib and also the batch processing. * Executes a Google_Http_Request and returns the resulting populated Google_Http_Request
* * @param Google_Http_Request $request
* @param $respData * @return Google_Http_Request $request
* @param $headerSize */
* @return array abstract public function executeRequest(Google_Http_Request $request);
*/
public function parseHttpResponse($respData, $headerSize) /**
{ * Set options that update the transport implementation's behavior.
// check proxy header * @param $options
foreach (self::$CONNECTION_ESTABLISHED_HEADERS as $established_header) { */
if (stripos($respData, $established_header) !== false) { abstract public function setOptions($options);
// existed, remove it
$respData = str_ireplace($established_header, '', $respData); /**
// Subtract the proxy header size unless the cURL bug prior to 7.30.0 * Set the maximum request time in seconds.
// is present which prevented the proxy header size from being taken into * @param $timeout in seconds
// account. */
if (!$this->needsQuirk()) { abstract public function setTimeout($timeout);
$headerSize -= strlen($established_header);
/**
* Get the maximum request time in seconds.
* @return timeout in seconds
*/
abstract public function getTimeout();
/**
* Test for the presence of a cURL header processing bug
*
* The cURL bug was present in versions prior to 7.30.0 and caused the header
* length to be miscalculated when a "Connection established" header added by
* some proxies was present.
*
* @return boolean
*/
abstract protected function needsQuirk();
/**
* @visible for testing.
* Cache the response to an HTTP request if it is cacheable.
* @param Google_Http_Request $request
* @return bool Returns true if the insertion was successful.
* Otherwise, return false.
*/
public function setCachedRequest(Google_Http_Request $request) {
// Determine if the request is cacheable.
if (Google_Http_CacheParser::isResponseCacheable($request)) {
$this->client->getCache()->set($request->getCacheKey(), $request);
return true;
} }
break;
} return false;
} }
if ($headerSize) { /**
$responseBody = substr($respData, $headerSize); * Execute an HTTP Request
$responseHeaders = substr($respData, 0, $headerSize); *
} else { * @param Google_HttpRequest $request the http request to be executed
list($responseHeaders, $responseBody) = explode("\r\n\r\n", $respData, 2); * @return Google_HttpRequest http request with the response http code,
* response headers and response body filled in
* @throws Google_IO_Exception on curl or IO error
*/
public function makeRequest(Google_Http_Request $request) {
// First, check to see if we have a valid cached version.
$cached = $this->getCachedRequest($request);
if ($cached !== false && $cached instanceof Google_Http_Request) {
if (!$this->checkMustRevalidateCachedRequest($cached, $request)) {
return $cached;
}
}
if (array_key_exists($request->getRequestMethod(), self::$ENTITY_HTTP_METHODS)) {
$request = $this->processEntityRequest($request);
}
list($responseData, $responseHeaders, $respHttpCode) = $this->executeRequest($request);
if ($respHttpCode == 304 && $cached) {
// If the server responded NOT_MODIFIED, return the cached request.
$this->updateCachedRequest($cached, $responseHeaders);
return $cached;
}
if (!isset($responseHeaders['Date']) && !isset($responseHeaders['date'])) {
$responseHeaders['Date'] = date("r");
}
$request->setResponseHttpCode($respHttpCode);
$request->setResponseHeaders($responseHeaders);
$request->setResponseBody($responseData);
// Store the request in cache (the function checks to see if the request
// can actually be cached)
$this->setCachedRequest($request);
return $request;
} }
$responseHeaders = $this->getHttpResponseHeaders($responseHeaders); /**
return array($responseHeaders, $responseBody); * @visible for testing.
} * @param Google_Http_Request $request
* @return Google_Http_Request|bool Returns the cached object or
* false if the operation was unsuccessful.
*/
public function getCachedRequest(Google_Http_Request $request) {
if (false === Google_Http_CacheParser::isRequestCacheable($request)) {
return false;
}
/** return $this->client->getCache()->get($request->getCacheKey());
* Parse out headers from raw headers
* @param rawHeaders array or string
* @return array
*/
public function getHttpResponseHeaders($rawHeaders)
{
if (is_array($rawHeaders)) {
return $this->parseArrayHeaders($rawHeaders);
} else {
return $this->parseStringHeaders($rawHeaders);
} }
}
private function parseStringHeaders($rawHeaders) /**
{ * @visible for testing
$headers = array(); * Process an http request that contains an enclosed entity.
$responseHeaderLines = explode("\r\n", $rawHeaders); * @param Google_Http_Request $request
foreach ($responseHeaderLines as $headerLine) { * @return Google_Http_Request Processed request with the enclosed entity.
if ($headerLine && strpos($headerLine, ':') !== false) { */
list($header, $value) = explode(': ', $headerLine, 2); public function processEntityRequest(Google_Http_Request $request) {
$header = strtolower($header); $postBody = $request->getPostBody();
if (isset($responseHeaders[$header])) { $contentType = $request->getRequestHeader("content-type");
$headers[$header] .= "\n" . $value;
// Set the default content-type as application/x-www-form-urlencoded.
if (false == $contentType) {
$contentType = self::FORM_URLENCODED;
$request->setRequestHeaders(array('content-type' => $contentType));
}
// Force the payload to match the content-type asserted in the header.
if ($contentType == self::FORM_URLENCODED && is_array($postBody)) {
$postBody = http_build_query($postBody, '', '&');
$request->setPostBody($postBody);
}
// Make sure the content-length header is set.
if (!$postBody || is_string($postBody)) {
$postsLength = strlen($postBody);
$request->setRequestHeaders(array('content-length' => $postsLength));
}
return $request;
}
/**
* Check if an already cached request must be revalidated, and if so update
* the request with the correct ETag headers.
* @param Google_Http_Request $cached A previously cached response.
* @param Google_Http_Request $request The outbound request.
* return bool If the cached object needs to be revalidated, false if it is
* still current and can be re-used.
*/
protected function checkMustRevalidateCachedRequest($cached, $request) {
if (Google_Http_CacheParser::mustRevalidate($cached)) {
$addHeaders = array();
if ($cached->getResponseHeader('etag')) {
// [13.3.4] If an entity tag has been provided by the origin server,
// we must use that entity tag in any cache-conditional request.
$addHeaders['If-None-Match'] = $cached->getResponseHeader('etag');
} elseif ($cached->getResponseHeader('date')) {
$addHeaders['If-Modified-Since'] = $cached->getResponseHeader('date');
}
$request->setRequestHeaders($addHeaders);
return true;
} else { } else {
$headers[$header] = $value; return false;
} }
}
}
return $headers;
}
private function parseArrayHeaders($rawHeaders)
{
$header_count = count($rawHeaders);
$headers = array();
for ($i = 0; $i < $header_count; $i++) {
$header = $rawHeaders[$i];
// Times will have colons in - so we just want the first match.
$header_parts = explode(': ', $header, 2);
if (count($header_parts) == 2) {
$headers[$header_parts[0]] = $header_parts[1];
}
} }
return $headers; /**
} * Update a cached request, using the headers from the last response.
* @param Google_HttpRequest $cached A previously cached response.
* @param mixed Associative array of response headers from the last request.
*/
protected function updateCachedRequest($cached, $responseHeaders) {
if (isset($responseHeaders['connection'])) {
$hopByHop = array_merge(
self::$HOP_BY_HOP,
explode(
',',
$responseHeaders['connection']
)
);
$endToEnd = array();
foreach ($hopByHop as $key) {
if (isset($responseHeaders[$key])) {
$endToEnd[$key] = $responseHeaders[$key];
}
}
$cached->setResponseHeaders($endToEnd);
}
}
/**
* Used by the IO lib and also the batch processing.
*
* @param $respData
* @param $headerSize
* @return array
*/
public function parseHttpResponse($respData, $headerSize) {
// check proxy header
foreach (self::$CONNECTION_ESTABLISHED_HEADERS as $established_header) {
if (stripos($respData, $established_header) !== false) {
// existed, remove it
$respData = str_ireplace($established_header, '', $respData);
// Subtract the proxy header size unless the cURL bug prior to 7.30.0
// is present which prevented the proxy header size from being taken into
// account.
if (!$this->needsQuirk()) {
$headerSize -= strlen($established_header);
}
break;
}
}
if ($headerSize) {
$responseBody = substr($respData, $headerSize);
$responseHeaders = substr($respData, 0, $headerSize);
} else {
list($responseHeaders, $responseBody) = explode("\r\n\r\n", $respData, 2);
}
$responseHeaders = $this->getHttpResponseHeaders($responseHeaders);
return array($responseHeaders, $responseBody);
}
/**
* Parse out headers from raw headers
* @param rawHeaders array or string
* @return array
*/
public function getHttpResponseHeaders($rawHeaders) {
if (is_array($rawHeaders)) {
return $this->parseArrayHeaders($rawHeaders);
} else {
return $this->parseStringHeaders($rawHeaders);
}
}
private function parseStringHeaders($rawHeaders) {
$headers = array();
$responseHeaderLines = explode("\r\n", $rawHeaders);
foreach ($responseHeaderLines as $headerLine) {
if ($headerLine && strpos($headerLine, ':') !== false) {
list($header, $value) = explode(': ', $headerLine, 2);
$header = strtolower($header);
if (isset($responseHeaders[$header])) {
$headers[$header] .= "\n" . $value;
} else {
$headers[$header] = $value;
}
}
}
return $headers;
}
private function parseArrayHeaders($rawHeaders) {
$header_count = count($rawHeaders);
$headers = array();
for ($i = 0; $i < $header_count; $i++) {
$header = $rawHeaders[$i];
// Times will have colons in - so we just want the first match.
$header_parts = explode(': ', $header, 2);
if (count($header_parts) == 2) {
$headers[$header_parts[0]] = $header_parts[1];
}
}
return $headers;
}
} }

View file

@ -23,115 +23,110 @@
require_once 'Google/IO/Abstract.php'; require_once 'Google/IO/Abstract.php';
class Google_IO_Curl extends Google_IO_Abstract class Google_IO_Curl extends Google_IO_Abstract {
{ // cURL hex representation of version 7.30.0
// cURL hex representation of version 7.30.0 const NO_QUIRK_VERSION = 0x071E00;
const NO_QUIRK_VERSION = 0x071E00;
private $options = array(); private $options = array();
/**
* Execute an HTTP Request
*
* @param Google_HttpRequest $request the http request to be executed
* @return Google_HttpRequest http request with the response http code,
* response headers and response body filled in
* @throws Google_IO_Exception on curl or IO error
*/
public function executeRequest(Google_Http_Request $request)
{
$curl = curl_init();
if ($request->getPostBody()) { /**
curl_setopt($curl, CURLOPT_POSTFIELDS, $request->getPostBody()); * Execute an HTTP Request
*
* @param Google_HttpRequest $request the http request to be executed
* @return Google_HttpRequest http request with the response http code,
* response headers and response body filled in
* @throws Google_IO_Exception on curl or IO error
*/
public function executeRequest(Google_Http_Request $request) {
$curl = curl_init();
if ($request->getPostBody()) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $request->getPostBody());
}
$requestHeaders = $request->getRequestHeaders();
if ($requestHeaders && is_array($requestHeaders)) {
$curlHeaders = array();
foreach ($requestHeaders as $k => $v) {
$curlHeaders[] = "$k: $v";
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $curlHeaders);
}
curl_setopt($curl, CURLOPT_URL, $request->getUrl());
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $request->getRequestMethod());
curl_setopt($curl, CURLOPT_USERAGENT, $request->getUserAgent());
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
if ($request->canGzip()) {
curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
}
foreach ($this->options as $key => $var) {
curl_setopt($curl, $key, $var);
}
if (!isset($this->options[CURLOPT_CAINFO])) {
curl_setopt($curl, CURLOPT_CAINFO, dirname(__FILE__) . '/cacerts.pem');
}
$response = curl_exec($curl);
if ($response === false) {
throw new Google_IO_Exception(curl_error($curl));
}
$headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
list($responseHeaders, $responseBody) = $this->parseHttpResponse($response, $headerSize);
$responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
return array($responseBody, $responseHeaders, $responseCode);
} }
$requestHeaders = $request->getRequestHeaders(); /**
if ($requestHeaders && is_array($requestHeaders)) { * Set options that update the transport implementation's behavior.
$curlHeaders = array(); * @param $options
foreach ($requestHeaders as $k => $v) { */
$curlHeaders[] = "$k: $v"; public function setOptions($options) {
} $this->options = $options + $this->options;
curl_setopt($curl, CURLOPT_HTTPHEADER, $curlHeaders);
} }
curl_setopt($curl, CURLOPT_URL, $request->getUrl()); /**
* Set the maximum request time in seconds.
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $request->getRequestMethod()); * @param $timeout in seconds
curl_setopt($curl, CURLOPT_USERAGENT, $request->getUserAgent()); */
public function setTimeout($timeout) {
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false); // Since this timeout is really for putting a bound on the time
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); // we'll set them both to the same. If you need to specify a longer
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // CURLOPT_TIMEOUT, or a tigher CONNECTTIMEOUT, the best thing to
curl_setopt($curl, CURLOPT_HEADER, true); // do is use the setOptions method for the values individually.
$this->options[CURLOPT_CONNECTTIMEOUT] = $timeout;
if ($request->canGzip()) { $this->options[CURLOPT_TIMEOUT] = $timeout;
curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
} }
foreach ($this->options as $key => $var) { /**
curl_setopt($curl, $key, $var); * Get the maximum request time in seconds.
* @return timeout in seconds
*/
public function getTimeout() {
return $this->options[CURLOPT_TIMEOUT];
} }
if (!isset($this->options[CURLOPT_CAINFO])) { /**
curl_setopt($curl, CURLOPT_CAINFO, dirname(__FILE__) . '/cacerts.pem'); * Test for the presence of a cURL header processing bug
*
* {@inheritDoc}
*
* @return boolean
*/
protected function needsQuirk() {
$ver = curl_version();
$versionNum = $ver['version_number'];
return $versionNum < Google_IO_Curl::NO_QUIRK_VERSION;
} }
$response = curl_exec($curl);
if ($response === false) {
throw new Google_IO_Exception(curl_error($curl));
}
$headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
list($responseHeaders, $responseBody) = $this->parseHttpResponse($response, $headerSize);
$responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
return array($responseBody, $responseHeaders, $responseCode);
}
/**
* Set options that update the transport implementation's behavior.
* @param $options
*/
public function setOptions($options)
{
$this->options = $options + $this->options;
}
/**
* Set the maximum request time in seconds.
* @param $timeout in seconds
*/
public function setTimeout($timeout)
{
// Since this timeout is really for putting a bound on the time
// we'll set them both to the same. If you need to specify a longer
// CURLOPT_TIMEOUT, or a tigher CONNECTTIMEOUT, the best thing to
// do is use the setOptions method for the values individually.
$this->options[CURLOPT_CONNECTTIMEOUT] = $timeout;
$this->options[CURLOPT_TIMEOUT] = $timeout;
}
/**
* Get the maximum request time in seconds.
* @return timeout in seconds
*/
public function getTimeout()
{
return $this->options[CURLOPT_TIMEOUT];
}
/**
* Test for the presence of a cURL header processing bug
*
* {@inheritDoc}
*
* @return boolean
*/
protected function needsQuirk()
{
$ver = curl_version();
$versionNum = $ver['version_number'];
return $versionNum < Google_IO_Curl::NO_QUIRK_VERSION;
}
} }

View file

@ -17,6 +17,5 @@
require_once 'Google/Exception.php'; require_once 'Google/Exception.php';
class Google_IO_Exception extends Google_Exception class Google_IO_Exception extends Google_Exception {
{
} }

View file

@ -23,189 +23,181 @@
require_once 'Google/IO/Abstract.php'; require_once 'Google/IO/Abstract.php';
class Google_IO_Stream extends Google_IO_Abstract class Google_IO_Stream extends Google_IO_Abstract {
{ const TIMEOUT = "timeout";
const TIMEOUT = "timeout"; const ZLIB = "compress.zlib://";
const ZLIB = "compress.zlib://"; private $options = array();
private $options = array(); private $trappedErrorNumber;
private $trappedErrorNumber; private $trappedErrorString;
private $trappedErrorString;
private static $DEFAULT_HTTP_CONTEXT = array( private static $DEFAULT_HTTP_CONTEXT = array(
"follow_location" => 0, "follow_location" => 0,
"ignore_errors" => 1, "ignore_errors" => 1,
);
private static $DEFAULT_SSL_CONTEXT = array(
"verify_peer" => true,
);
/**
* Execute an HTTP Request
*
* @param Google_HttpRequest $request the http request to be executed
* @return Google_HttpRequest http request with the response http code,
* response headers and response body filled in
* @throws Google_IO_Exception on curl or IO error
*/
public function executeRequest(Google_Http_Request $request)
{
$default_options = stream_context_get_options(stream_context_get_default());
$requestHttpContext = array_key_exists('http', $default_options) ?
$default_options['http'] : array();
if ($request->getPostBody()) {
$requestHttpContext["content"] = $request->getPostBody();
}
$requestHeaders = $request->getRequestHeaders();
if ($requestHeaders && is_array($requestHeaders)) {
$headers = "";
foreach ($requestHeaders as $k => $v) {
$headers .= "$k: $v\r\n";
}
$requestHttpContext["header"] = $headers;
}
$requestHttpContext["method"] = $request->getRequestMethod();
$requestHttpContext["user_agent"] = $request->getUserAgent();
$requestSslContext = array_key_exists('ssl', $default_options) ?
$default_options['ssl'] : array();
if (!array_key_exists("cafile", $requestSslContext)) {
$requestSslContext["cafile"] = dirname(__FILE__) . '/cacerts.pem';
}
$options = array(
"http" => array_merge(
self::$DEFAULT_HTTP_CONTEXT,
$requestHttpContext
),
"ssl" => array_merge(
self::$DEFAULT_SSL_CONTEXT,
$requestSslContext
)
); );
$context = stream_context_create($options); private static $DEFAULT_SSL_CONTEXT = array(
"verify_peer" => true,
);
$url = $request->getUrl(); /**
* Execute an HTTP Request
*
* @param Google_HttpRequest $request the http request to be executed
* @return Google_HttpRequest http request with the response http code,
* response headers and response body filled in
* @throws Google_IO_Exception on curl or IO error
*/
public function executeRequest(Google_Http_Request $request) {
$default_options = stream_context_get_options(stream_context_get_default());
if ($request->canGzip()) { $requestHttpContext = array_key_exists('http', $default_options) ?
$url = self::ZLIB . $url; $default_options['http'] : array();
if ($request->getPostBody()) {
$requestHttpContext["content"] = $request->getPostBody();
}
$requestHeaders = $request->getRequestHeaders();
if ($requestHeaders && is_array($requestHeaders)) {
$headers = "";
foreach ($requestHeaders as $k => $v) {
$headers .= "$k: $v\r\n";
}
$requestHttpContext["header"] = $headers;
}
$requestHttpContext["method"] = $request->getRequestMethod();
$requestHttpContext["user_agent"] = $request->getUserAgent();
$requestSslContext = array_key_exists('ssl', $default_options) ?
$default_options['ssl'] : array();
if (!array_key_exists("cafile", $requestSslContext)) {
$requestSslContext["cafile"] = dirname(__FILE__) . '/cacerts.pem';
}
$options = array(
"http" => array_merge(
self::$DEFAULT_HTTP_CONTEXT,
$requestHttpContext
),
"ssl" => array_merge(
self::$DEFAULT_SSL_CONTEXT,
$requestSslContext
)
);
$context = stream_context_create($options);
$url = $request->getUrl();
if ($request->canGzip()) {
$url = self::ZLIB . $url;
}
// We are trapping any thrown errors in this method only and
// throwing an exception.
$this->trappedErrorNumber = null;
$this->trappedErrorString = null;
// START - error trap.
set_error_handler(array($this, 'trapError'));
$fh = fopen($url, 'r', false, $context);
restore_error_handler();
// END - error trap.
if ($this->trappedErrorNumber) {
throw new Google_IO_Exception(
sprintf(
"HTTP Error: Unable to connect: '%s'",
$this->trappedErrorString
),
$this->trappedErrorNumber
);
}
$response_data = false;
$respHttpCode = self::UNKNOWN_CODE;
if ($fh) {
if (isset($this->options[self::TIMEOUT])) {
stream_set_timeout($fh, $this->options[self::TIMEOUT]);
}
$response_data = stream_get_contents($fh);
fclose($fh);
$respHttpCode = $this->getHttpResponseCode($http_response_header);
}
if (false === $response_data) {
throw new Google_IO_Exception(
sprintf(
"HTTP Error: Unable to connect: '%s'",
$respHttpCode
),
$respHttpCode
);
}
$responseHeaders = $this->getHttpResponseHeaders($http_response_header);
return array($response_data, $responseHeaders, $respHttpCode);
} }
// We are trapping any thrown errors in this method only and /**
// throwing an exception. * Set options that update the transport implementation's behavior.
$this->trappedErrorNumber = null; * @param $options
$this->trappedErrorString = null; */
public function setOptions($options) {
// START - error trap. $this->options = $options + $this->options;
set_error_handler(array($this, 'trapError'));
$fh = fopen($url, 'r', false, $context);
restore_error_handler();
// END - error trap.
if ($this->trappedErrorNumber) {
throw new Google_IO_Exception(
sprintf(
"HTTP Error: Unable to connect: '%s'",
$this->trappedErrorString
),
$this->trappedErrorNumber
);
} }
$response_data = false; /**
$respHttpCode = self::UNKNOWN_CODE; * Method to handle errors, used for error handling around
if ($fh) { * stream connection methods.
if (isset($this->options[self::TIMEOUT])) { */
stream_set_timeout($fh, $this->options[self::TIMEOUT]); public function trapError($errno, $errstr) {
} $this->trappedErrorNumber = $errno;
$this->trappedErrorString = $errstr;
$response_data = stream_get_contents($fh);
fclose($fh);
$respHttpCode = $this->getHttpResponseCode($http_response_header);
} }
if (false === $response_data) { /**
throw new Google_IO_Exception( * Set the maximum request time in seconds.
sprintf( * @param $timeout in seconds
"HTTP Error: Unable to connect: '%s'", */
$respHttpCode public function setTimeout($timeout) {
), $this->options[self::TIMEOUT] = $timeout;
$respHttpCode
);
} }
$responseHeaders = $this->getHttpResponseHeaders($http_response_header); /**
* Get the maximum request time in seconds.
return array($response_data, $responseHeaders, $respHttpCode); * @return timeout in seconds
} */
public function getTimeout() {
/** return $this->options[self::TIMEOUT];
* Set options that update the transport implementation's behavior. }
* @param $options
*/ /**
public function setOptions($options) * Test for the presence of a cURL header processing bug
{ *
$this->options = $options + $this->options; * {@inheritDoc}
} *
* @return boolean
/** */
* Method to handle errors, used for error handling around protected function needsQuirk() {
* stream connection methods. return false;
*/ }
public function trapError($errno, $errstr)
{ protected function getHttpResponseCode($response_headers) {
$this->trappedErrorNumber = $errno; $header_count = count($response_headers);
$this->trappedErrorString = $errstr;
} for ($i = 0; $i < $header_count; $i++) {
$header = $response_headers[$i];
/** if (strncasecmp("HTTP", $header, strlen("HTTP")) == 0) {
* Set the maximum request time in seconds. $response = explode(' ', $header);
* @param $timeout in seconds return $response[1];
*/ }
public function setTimeout($timeout) }
{ return self::UNKNOWN_CODE;
$this->options[self::TIMEOUT] = $timeout;
}
/**
* Get the maximum request time in seconds.
* @return timeout in seconds
*/
public function getTimeout()
{
return $this->options[self::TIMEOUT];
}
/**
* Test for the presence of a cURL header processing bug
*
* {@inheritDoc}
*
* @return boolean
*/
protected function needsQuirk()
{
return false;
}
protected function getHttpResponseCode($response_headers)
{
$header_count = count($response_headers);
for ($i = 0; $i < $header_count; $i++) {
$header = $response_headers[$i];
if (strncasecmp("HTTP", $header, strlen("HTTP")) == 0) {
$response = explode(' ', $header);
return $response[1];
}
} }
return self::UNKNOWN_CODE;
}
} }

View file

@ -23,228 +23,211 @@
* @author Chirag Shah <chirags@google.com> * @author Chirag Shah <chirags@google.com>
* *
*/ */
class Google_Model implements ArrayAccess class Google_Model implements ArrayAccess {
{ protected $modelData = array();
protected $modelData = array(); protected $processed = array();
protected $processed = array();
/** /**
* Polymorphic - accepts a variable number of arguments dependent * Polymorphic - accepts a variable number of arguments dependent
* on the type of the model subclass. * on the type of the model subclass.
*/ */
public function __construct() public function __construct() {
{ if (func_num_args() == 1 && is_array(func_get_arg(0))) {
if (func_num_args() == 1 && is_array(func_get_arg(0))) { // Initialize the model with the array's contents.
// Initialize the model with the array's contents. $array = func_get_arg(0);
$array = func_get_arg(0); $this->mapTypes($array);
$this->mapTypes($array); }
} }
}
public function __get($key) public function __get($key) {
{ $keyTypeName = $this->keyType($key);
$keyTypeName = $this->keyType($key); $keyDataType = $this->dataType($key);
$keyDataType = $this->dataType($key); if (isset($this->$keyTypeName) && !isset($this->processed[$key])) {
if (isset($this->$keyTypeName) && !isset($this->processed[$key])) { if (isset($this->modelData[$key])) {
if (isset($this->modelData[$key])) { $val = $this->modelData[$key];
$val = $this->modelData[$key]; } elseif (isset($this->$keyDataType) &&
} else if (isset($this->$keyDataType) && ($this->$keyDataType == 'array' || $this->$keyDataType == 'map')) {
($this->$keyDataType == 'array' || $this->$keyDataType == 'map')) { $val = array();
$val = array(); } else {
} else { $val = null;
$val = null; }
}
if ($this->isAssociativeArray($val)) { if ($this->isAssociativeArray($val)) {
if (isset($this->$keyDataType) && 'map' == $this->$keyDataType) { if (isset($this->$keyDataType) && 'map' == $this->$keyDataType) {
foreach ($val as $arrayKey => $arrayItem) { foreach ($val as $arrayKey => $arrayItem) {
$this->modelData[$key][$arrayKey] = $this->modelData[$key][$arrayKey] =
$this->createObjectFromName($keyTypeName, $arrayItem); $this->createObjectFromName($keyTypeName, $arrayItem);
} }
} else {
$this->modelData[$key] = $this->createObjectFromName($keyTypeName, $val);
}
} elseif (is_array($val)) {
$arrayObject = array();
foreach ($val as $arrayIndex => $arrayItem) {
$arrayObject[$arrayIndex] =
$this->createObjectFromName($keyTypeName, $arrayItem);
}
$this->modelData[$key] = $arrayObject;
}
$this->processed[$key] = true;
}
return $this->modelData[$key];
}
/**
* Initialize this object's properties from an array.
*
* @param array $array Used to seed this object's properties.
* @return void
*/
protected function mapTypes($array) {
// Hard initilise simple types, lazy load more complex ones.
foreach ($array as $key => $val) {
if (!property_exists($this, $this->keyType($key)) &&
property_exists($this, $key)) {
$this->$key = $val;
unset($array[$key]);
} elseif (property_exists($this, $camelKey = Google_Utils::camelCase($key))) {
// This checks if property exists as camelCase, leaving it in array as snake_case
// in case of backwards compatibility issues.
$this->$camelKey = $val;
}
}
$this->modelData = $array;
}
/**
* Create a simplified object suitable for straightforward
* conversion to JSON. This is relatively expensive
* due to the usage of reflection, but shouldn't be called
* a whole lot, and is the most straightforward way to filter.
*/
public function toSimpleObject() {
$object = new stdClass();
// Process all other data.
foreach ($this->modelData as $key => $val) {
$result = $this->getSimpleValue($val);
if ($result !== null) {
$object->$key = $result;
}
}
// Process all public properties.
$reflect = new ReflectionObject($this);
$props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
foreach ($props as $member) {
$name = $member->getName();
$result = $this->getSimpleValue($this->$name);
if ($result !== null) {
$object->$name = $result;
}
}
return $object;
}
/**
* Handle different types of values, primarily
* other objects and map and array data types.
*/
private function getSimpleValue($value) {
if ($value instanceof Google_Model) {
return $value->toSimpleObject();
} elseif (is_array($value)) {
$return = array();
foreach ($value as $key => $a_value) {
$a_value = $this->getSimpleValue($a_value);
if ($a_value !== null) {
$return[$key] = $a_value;
}
}
return $return;
}
return $value;
}
/**
* Returns true only if the array is associative.
* @param array $array
* @return bool True if the array is associative.
*/
protected function isAssociativeArray($array) {
if (!is_array($array)) {
return false;
}
$keys = array_keys($array);
foreach ($keys as $key) {
if (is_string($key)) {
return true;
}
}
return false;
}
/**
* Given a variable name, discover its type.
*
* @param $name
* @param $item
* @return object The object from the item.
*/
private function createObjectFromName($name, $item) {
$type = $this->$name;
return new $type($item);
}
/**
* Verify if $obj is an array.
* @throws Google_Exception Thrown if $obj isn't an array.
* @param array $obj Items that should be validated.
* @param string $method Method expecting an array as an argument.
*/
public function assertIsArray($obj, $method) {
if ($obj && !is_array($obj)) {
throw new Google_Exception(
"Incorrect parameter type passed to $method(). Expected an array."
);
}
}
public function offsetExists($offset) {
return isset($this->$offset) || isset($this->modelData[$offset]);
}
public function offsetGet($offset) {
return isset($this->$offset) ?
$this->$offset :
$this->__get($offset);
}
public function offsetSet($offset, $value) {
if (property_exists($this, $offset)) {
$this->$offset = $value;
} else { } else {
$this->modelData[$key] = $this->createObjectFromName($keyTypeName, $val); $this->modelData[$offset] = $value;
$this->processed[$offset] = true;
} }
} else if (is_array($val)) {
$arrayObject = array();
foreach ($val as $arrayIndex => $arrayItem) {
$arrayObject[$arrayIndex] =
$this->createObjectFromName($keyTypeName, $arrayItem);
}
$this->modelData[$key] = $arrayObject;
}
$this->processed[$key] = true;
} }
return $this->modelData[$key]; public function offsetUnset($offset) {
} unset($this->modelData[$offset]);
/**
* Initialize this object's properties from an array.
*
* @param array $array Used to seed this object's properties.
* @return void
*/
protected function mapTypes($array)
{
// Hard initilise simple types, lazy load more complex ones.
foreach ($array as $key => $val) {
if ( !property_exists($this, $this->keyType($key)) &&
property_exists($this, $key)) {
$this->$key = $val;
unset($array[$key]);
} elseif (property_exists($this, $camelKey = Google_Utils::camelCase($key))) {
// This checks if property exists as camelCase, leaving it in array as snake_case
// in case of backwards compatibility issues.
$this->$camelKey = $val;
}
}
$this->modelData = $array;
}
/**
* Create a simplified object suitable for straightforward
* conversion to JSON. This is relatively expensive
* due to the usage of reflection, but shouldn't be called
* a whole lot, and is the most straightforward way to filter.
*/
public function toSimpleObject()
{
$object = new stdClass();
// Process all other data.
foreach ($this->modelData as $key => $val) {
$result = $this->getSimpleValue($val);
if ($result !== null) {
$object->$key = $result;
}
} }
// Process all public properties. protected function keyType($key) {
$reflect = new ReflectionObject($this); return $key . "Type";
$props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
foreach ($props as $member) {
$name = $member->getName();
$result = $this->getSimpleValue($this->$name);
if ($result !== null) {
$object->$name = $result;
}
} }
return $object; protected function dataType($key) {
} return $key . "DataType";
/**
* Handle different types of values, primarily
* other objects and map and array data types.
*/
private function getSimpleValue($value)
{
if ($value instanceof Google_Model) {
return $value->toSimpleObject();
} else if (is_array($value)) {
$return = array();
foreach ($value as $key => $a_value) {
$a_value = $this->getSimpleValue($a_value);
if ($a_value !== null) {
$return[$key] = $a_value;
}
}
return $return;
} }
return $value;
}
/** public function __isset($key) {
* Returns true only if the array is associative. return isset($this->modelData[$key]);
* @param array $array
* @return bool True if the array is associative.
*/
protected function isAssociativeArray($array)
{
if (!is_array($array)) {
return false;
} }
$keys = array_keys($array);
foreach ($keys as $key) { public function __unset($key) {
if (is_string($key)) { unset($this->modelData[$key]);
return true;
}
} }
return false;
}
/**
* Given a variable name, discover its type.
*
* @param $name
* @param $item
* @return object The object from the item.
*/
private function createObjectFromName($name, $item)
{
$type = $this->$name;
return new $type($item);
}
/**
* Verify if $obj is an array.
* @throws Google_Exception Thrown if $obj isn't an array.
* @param array $obj Items that should be validated.
* @param string $method Method expecting an array as an argument.
*/
public function assertIsArray($obj, $method)
{
if ($obj && !is_array($obj)) {
throw new Google_Exception(
"Incorrect parameter type passed to $method(). Expected an array."
);
}
}
public function offsetExists($offset)
{
return isset($this->$offset) || isset($this->modelData[$offset]);
}
public function offsetGet($offset)
{
return isset($this->$offset) ?
$this->$offset :
$this->__get($offset);
}
public function offsetSet($offset, $value)
{
if (property_exists($this, $offset)) {
$this->$offset = $value;
} else {
$this->modelData[$offset] = $value;
$this->processed[$offset] = true;
}
}
public function offsetUnset($offset)
{
unset($this->modelData[$offset]);
}
protected function keyType($key)
{
return $key . "Type";
}
protected function dataType($key)
{
return $key . "DataType";
}
public function __isset($key)
{
return isset($this->modelData[$key]);
}
public function __unset($key)
{
unset($this->modelData[$key]);
}
} }

View file

@ -15,25 +15,22 @@
* limitations under the License. * limitations under the License.
*/ */
class Google_Service class Google_Service {
{ public $version;
public $version; public $servicePath;
public $servicePath; public $availableScopes;
public $availableScopes; public $resource;
public $resource; private $client;
private $client;
public function __construct(Google_Client $client) public function __construct(Google_Client $client) {
{ $this->client = $client;
$this->client = $client; }
}
/** /**
* Return the associated Google_Client class. * Return the associated Google_Client class.
* @return Google_Client * @return Google_Client
*/ */
public function getClient() public function getClient() {
{ return $this->client;
return $this->client; }
}
} }

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

Some files were not shown because too many files have changed in this diff Show more