code stringlengths 1 2.01M | language stringclasses 1 value |
|---|---|
<?php
if (isset($_POST['submit'])) {
$error = false;
$name = trim($_POST['name']);
$slug = implode("-",explode(" ", strtolower(trim($name))));
if($name == '') {
$error = true;
$name_error = "Please provide username";
}
//if ($username != "" && $password !="" && $email !="" ) {
if(!$error) {
$con = mysql_connect("localhost", "root", "");
mysql_select_db("cms");
$sql = "INSERT INTO `navigation_groups` (`id`, `name`, `slug`) VALUES (NULL, '$name','$slug');";
mysql_query($sql);
header ("location: ../navigations.php");
}
}
?> | PHP |
<?php
include "includes/common.php";
//Step - 3 (SQL / Get result)
$id = $_GET['id'];
$sql = "delete from `navigations` where `id` = $id";
mysql_query($sql);
//echo "user id ". $_GET['id'] . " deleted";
header ("location: ../navigations.php");
?> | PHP |
<?php
session_start();
if (!$_SESSION['login']) header ("location: ../login.php");
//Step - 1 (Connection)
$con = mysql_connect("localhost", "root", "");
//Step - 2 (Database)
mysql_select_db("test");
$id= $_GET['id'];
//Step - 3 (SQL / Get result)
$sql = "SELECT * from `users` where `id` = $id";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if (isset($_POST['submit'])) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$email = trim($_POST['email']);
$password = md5($password);
$sql_update = "UPDATE `users` SET `username` = '$username', `password` = '$password', `email` = '$email' WHERE `id` = $id";
mysql_query($sql_update);
header ("location: ../database.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Course</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="../assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PHP Course</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">Users</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>PHP / MySql</h1>
<p>Basic CRUD oparations on Database</p>
<br/>
<h3>Update User '<?php echo $row['username']; ?>' </h3>
<br/><br/>
<form class="form-horizontal" action="" method="POST">
<div class="control-group <?php if ($username_error) { echo 'error'; } ?> ">
<label class="control-label" for="first_name">Username</label>
<div class="controls">
<input type="text" name="username" value="<?php echo $row['username']; ?>">
<?php if ($username_error) { ?>
<span class="help-inline"><?php echo $username_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group <?php if ($password_error) { echo 'error'; } ?>">
<label class="control-label" for="username">Password</label>
<div class="controls">
<input type="password" id="password" name="password" value="<?php echo $row['password']; ?>" >
<?php if ($password_error) { ?>
<span class="help-inline"><?php echo $password_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group <?php if ($email_error) { echo 'error'; } ?>">
<label class="control-label" for="last_name">Email</label>
<div class="controls">
<input type="text" id="email" name="email" value="<?php echo $row['email']; ?>">
<?php if ($email_error) { ?>
<span class="help-inline"><?php echo $email_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group">
<div class="controls">
<input name="submit" value="Update User" type="submit" class="btn" />
</div>
</div>
</form>
<?php
//Step - 5 (Close connection)
mysql_close($con);
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
| PHP |
<?php
include "../includes/common.php";
if (isset($_POST['submit'])) {
$link_text = $_POST['link_text'];
$url = $_POST['url'];
$description = $_POST['description'];
$group_id = $_POST['group_id'];
//if ($username != "" && $password !="" && $email !="" ) {
if($link_text !="" && $url != "" && $group_id !="") {
$now = time();
$con = mysql_connect("localhost", "root", "");
mysql_select_db("cms");
$sql = "INSERT INTO `navigations` (`id`, `link_text`, `url`, `description`, `group_id`, `created_at`) VALUES (NULL, '$link_text','$url', '$description','$group_id', '$now');";
mysql_query($sql);
}
}
header ("location: ../navigations.php");
?> | PHP |
<?php
if(isset($_POST['submit'])) {
include "includes/common.php";
//get user input from GET / POST method
/*
echo "<pre>";
print_r($_POST);
var_export($_POST);
echo "</pre>";
*/
$action = $_GET['action'];
$name = $_POST['name'];
$caption = $_POST['caption'];
$submit = $data['submit'];
if ($name !="" && $caption != "" && isset($_FILES)) {
$upload_dir = '../uploads';
//tmp_name holds temporary file for uploaded file
$source_file = $_FILES['image']['tmp_name'];
//the 'name' key of the array holds original filename
//we can use original file name here as our destination filename. it will be saved inside our upload directory
$destination_file = time()."_".$_FILES['image']['name'];
$ext = substr($_FILES['image']['name'], -3);
if (in_array($ext, array("jpg","gif","bmp","png") )){
if (move_uploaded_file($source_file, $upload_dir."/".$destination_file)){
//file upload done;
}else {
$hasError = true;
$file_error = "Couldn't upload file. Retry later";
}
}else {
$hasError = true;
$file_error = "Only images are allowed";
}
}
/*
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'youremail@yoursite.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
} */
if($hasError != true){
if ($action=="update") {
$id = $data['userid'];
$password = md5($password);
//server side validation of input data
//build query
$sql = "update `users` set `username` = \"$username\", `password` = \"$password\", `email` = \"$email\", `first_name`= \"$firstname\", `mid_name` = \"$midname\", `last_name` =\"$lastname\", `phone` = \"$phone\", `address` = \"$address\", `website` = \"$website\", `picture` = \"$destination_file\", `created_at` =$created_at , `user_type`= $usertype where `id` = $id ;";
} else { // insert date
$password = md5($password);
//build query
$sql = "INSERT INTO `users` (`id`, `username`, `password`, `email`, `first_name`, `mid_name`, `last_name`, `phone`, `address`, `website`, `picture`, `created_at`, `user_type`) VALUES (NULL, \"$username\", \"$password\", \"$email\", \"$firstname\", \"$midname\", \"$lastname\", \"$phone\", \"$address\", \"$website\", \"$destination_file\", $created_at, $usertype);";
}
mysql_query ($sql);
header ("location: users.php");
}
}
?>
| PHP |
<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("cms");
$id = $_GET['id'];
$sql = "delete from `users` where `id` = $id";
if (mysql_query($sql)){
echo "SUCCESS";
}else {
echo "ERROR";
}
exit;
//echo "user id ". $_GET['id'] . " deleted";
//header ("location: ../database.php");
?> | PHP |
<?php
include "includes/common.php";
//Step - 3 (SQL / Get result)
$id = $_GET['id'];
$sql = "delete from `navigation_groups` where `id` = $id";
mysql_query($sql);
//echo "user id ". $_GET['id'] . " deleted";
header ("location: ../navigations.php");
?> | PHP |
<?php
if (!$_SESSION['login']) header ("location: ../index.php");
//Step - 1 (Connection)
$con = mysql_connect("localhost", "root", "");
//Step - 2 (Database)
mysql_select_db("cms");
if (isset($_POST['submit'])) {
$site_name = trim($_POST['site_name']);
$site_slogan = trim($_POST['site_slogan']);
$sql_update = "UPDATE `settings` SET `site_name` = '$site_name', `site_slogan` = '$site_slogan'";
mysql_query($sql_update);
header ("location: settings.php");
}
?>
| PHP |
<?php
if (isset($_POST['submit'])) {
$error = false;
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$email = trim($_POST['email']);
if($username == '') {
$error = true;
$username_error = "Please provide username";
}
if($password == '') {
$error = true;
$password_error = "Please provide password";
}else {
$password = md5($_POST['password']);
}
if($email == '') {
$error = true;
$email_error = "Please provide email";
}
//if ($username != "" && $password !="" && $email !="" ) {
if(!$error) {
$con = mysql_connect("localhost", "root", "");
mysql_select_db("cms");
$sql = "INSERT INTO `users` (`id`, `username`, `password`, `email`) VALUES (NULL, '$username','$password','$email');";
mysql_query($sql);
header ("location: admin.php");
}
}
?> | PHP |
<?php
session_start();
//unset session
$_SESSION['login'] = 0;
$_SESSION['username'] = "";
$_SESSION['user_id'] = 0;
//or
//unset($_SESSION['login']);
//unset($_SESSION['username']);
session_destroy();
//redirect to login page
header ("location: index.php");
?>
| PHP |
<?php
session_start();
if ($_SESSION['login']) header ("location: admin.php");
include "includes/common.php";
//$username = addslashes($_POST['username']);
$username = addslashes($_POST['username']);
$password = addslashes($_POST['password']);
if ($_POST['submit'] && ($username !="" && $password !="" )) {
$password = md5($_POST['password']);
$sql = "select * from `users` where `username` = '$username' and `password` = '$password'";
$result = mysql_query($sql);
$count_result = mysql_num_rows($result);
if ($count_result == 1 ) {
//echo "Login Success!";
//set session
$_SESSION['login'] = 1;
$_SESSION['username'] = $username;
$user = mysql_fetch_assoc($result);
$_SESSION['user_id'] = $user['id'];
//redirect to database
header ("location: admin.php");
}else {
echo "Login failed!";
}
} else {
echo "Please provide username & password!";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sign in · Twitter Bootstrap</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style type="text/css">
body {
padding-top: 40px;
padding-bottom: 40px;
background-color: #f5f5f5;
}
.form-signin {
max-width: 300px;
padding: 19px 29px 29px;
margin: 0 auto 20px;
background-color: #fff;
border: 1px solid #e5e5e5;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
box-shadow: 0 1px 2px rgba(0,0,0,.05);
}
.form-signin .form-signin-heading,
.form-signin .checkbox {
margin-bottom: 10px;
}
.form-signin input[type="text"],
.form-signin input[type="password"] {
font-size: 16px;
height: auto;
margin-bottom: 15px;
padding: 7px 9px;
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="../assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="../assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="../assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="../assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="../assets/ico/favicon.png">
</head>
<body>
<div class="container">
<form class="form-signin" action="" method="POST" >
<h2 class="form-signin-heading">Login</h2>
Username: <input name="username" value="" type="text" class="input-block-level" >
Password: <input name="password" value="" type="password" class="input-block-level" >
<button name="submit" value="Sign In" class="btn btn-large btn-primary" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
| PHP |
<?php
session_start();
if (!$_SESSION['login']) header ("location: index.php");
include "dbactions/settings_update.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Course</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
<script type="text/javascript">
function sure(){
if (confirm("Are you sure delete this user ?")){
return true;
}else {
return false;
}
}
</script>
</head>
<body>
<!-- include navigation here -->
<?php include "views/nav.php"; ?>
<div class="container">
<h1>Settings</h1>
<br/>
<?php
//Step - 1 (Connection)
$con = mysql_connect("localhost", "root", "");
//Step - 2 (Database)
mysql_select_db("cms");
//Step - 3 (SQL / Get result)
$sql = "SELECT * from `settings`";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
?>
<table class="table table-hover">
<thead>
<tr>
<th>Sitename</th>
<th>Slogan</th>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo $row['site_name'];?></td>
<td><?php echo $row['site_slogan'];?></td>
</tr>
</tbody>
</table>
<?php
//Step - 5 (Close connection)
mysql_close($con);
?>
<h3>Update Settings</h3>
<form class="form-horizontal" action="" method="POST">
<div class="control-group <?php if ($username_error) { echo 'error'; } ?> ">
<label class="control-label" for="first_name">Site Name</label>
<div class="controls">
<input type="text" name="site_name" value="<?php if (isset($site_name)) {echo $site_name; } else {echo $row['site_name'];} ?>">
<?php if ($username_error) { ?>
<span class="help-inline"><?php echo $username_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group <?php if ($password_error) { echo 'error'; } ?>">
<label class="control-label" for="username">Site Slgan</label>
<div class="controls">
<input type="text" id="site_slogan" name="site_slogan" value="<?php if (isset($site_slogan)) {echo $site_slogan;} else {echo $row['site_slogan'];} ?>" >
<?php if ($password_error) { ?>
<span class="help-inline"><?php echo $password_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group">
<div class="controls">
<input name="submit" value="Update Settings" type="submit" class="btn" />
</div>
</div>
</form>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
| PHP |
<?php
session_start();
if (!$_SESSION['login']) header ("location: index.php");
include "dbactions/user_add.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Course</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
<script src="assets/js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".delete").click(function(){
var url = $(this).attr("href"); //alert(url);
var btn = $(this);
//$(this).closest('tr').fadeOut("slow");
$.ajax({
type: "GET",
url: url,
success: function(res) {
if (res == "SUCCESS") {
$(btn).closest('tr').fadeOut('slow');
}else {
alert("Couldn't delete ! Retry.");
}
}
});
return false;
});
});
</script>
</head>
<body>
<!-- include navigation here -->
<?php include "views/nav.php"; ?>
<div class="container">
<h1>Users</h1>
<br/>
<?php
//Step - 1 (Connection)
$con = mysql_connect("localhost", "root", "");
//Step - 2 (Database)
mysql_select_db("cms");
//Step - 3 (SQL / Get result)
$sql = "SELECT * from `users`";
$result = mysql_query($sql);
?>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Username</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
//Step - 4 (Grab / Process result of query)
$i=0;
while ($row = mysql_fetch_assoc($result)) {
$i++;
//echo "<pre>";print_r($row);echo "</pre>";
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $row['username'];?></td>
<td><?php echo $row['email'];?></td>
<td>
<a href="">View</a> |
<a href="dbactions/user_edit.php?id=<?php echo $row['id']; ?>">Edit</a> |
<a class="delete" href="dbactions/user_delete.php?id=<?php echo $row['id']; ?>">Delete</a>
</td>
</tr>
<?php }?>
</tbody>
</table>
<?php
//Step - 5 (Close connection)
mysql_close($con);
?>
<h3>Add New Users</h3>
<form class="form-horizontal" action="" method="POST">
<div class="control-group <?php if ($username_error) { echo 'error'; } ?> ">
<label class="control-label" for="first_name">Username</label>
<div class="controls">
<input type="text" name="username" value="<?php if (isset($username)) echo $username; ?>">
<?php if ($username_error) { ?>
<span class="help-inline"><?php echo $username_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group <?php if ($password_error) { echo 'error'; } ?>">
<label class="control-label" for="username">Password</label>
<div class="controls">
<input type="password" id="password" name="password" value="" >
<?php if ($password_error) { ?>
<span class="help-inline"><?php echo $password_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group <?php if ($email_error) { echo 'error'; } ?>">
<label class="control-label" for="last_name">Email</label>
<div class="controls">
<input type="text" id="email" name="email" value="<?php if (isset($email)) echo $email; ?>">
<?php if ($email_error) { ?>
<span class="help-inline"><?php echo $email_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group">
<div class="controls">
<input name="submit" value="Add User" type="submit" class="btn" />
</div>
</div>
</form>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
| PHP |
<?php
$site_url = "http://localhost/ambition/class/";
$upload_url = "http://localhost/ambition/class/uploads/";
define('UPLOAD_PATH', 'http://localhost/ambition/class/uploads/' );
$con = mysql_connect("localhost", "root", "");
mysql_select_db("cms");
?>
| PHP |
<?php
session_start();
if (!$_SESSION['login']) header ("location: index.php");
include "includes/common.php";
include "dbactions/user_add.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Course</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
<script type="text/javascript">
function sure(){
if (confirm("Are you sure delete?")){
return true;
}else {
return false;
}
}
</script>
</head>
<body>
<!-- include navigation here -->
<?php include "views/nav.php"; ?>
<div class="container">
<h1>Navigations</h1>
<br/>
<?php
//Step - 3 (SQL / Get result)
/*
$sql = "SELECT navigation_groups.*,navigations.* from `navigations`
JOIN `navigation_group`
ON navigations.group_id = navigation_groups.id
"; */
$sql = "SELECT * FROM `navigations`
LEFT JOIN `navigation_groups`
ON navigations.group_id = navigation_groups.id ";
$result = mysql_query($sql);
if ($result && mysql_num_rows($result)) {
?>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Link</th>
<th>Description</th>
<th>Group</th>
<th>Click Count</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
//Step - 4 (Grab / Process result of query)
$i=0;
while ($row = mysql_fetch_assoc($result)) {
$i++;
//echo "<pre>";print_r($row);echo "</pre>";
?>
<tr>
<td><?php echo $i; ?></td>
<td><a href="<?php echo $site_url.$row['url'];?>"><?php echo $row['link_text'];?> </a></td>
<td><?php echo $row['description']; ?></td>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['click_count']; ?></td>
<td>
<a href="dbactions/user_edit.php?id=<?php echo $row['id']; ?>">Edit</a> |
<a onclick="return sure()" href="dbactions/nav_delete.php?id=<?php echo $row['id']; ?>">Delete</a>
</td>
</tr>
<?php }?>
</tbody>
</table>
<?php
} else {
echo "No navigation links found";
}
//Step - 5 (Close connection)
?>
<h3>Add New Link</h3>
<form class="form-horizontal" action="dbactions/nav_add.php" method="POST">
<div class="control-group">
<label class="control-label" for="first_name">Link Text</label>
<div class="controls">
<input type="text" name="link_text" value="">
</div>
</div>
<div class="control-group">
<label class="control-label" for="first_name">URL</label>
<div class="controls">
<input type="text" name="url" value="">
</div>
</div>
<div class="control-group">
<label class="control-label" for="first_name">Description</label>
<div class="controls">
<input type="text" name="description" value="">
</div>
</div>
<div class="control-group">
<label class="control-label" for="first_name">Group</label>
<div class="controls">
<select name="group_id">
<option value="">Select Group</option>
<?php
$sql_group = "SELECT * from `navigation_groups`";
$result_group = mysql_query($sql_group);
while ($row = mysql_fetch_assoc($result_group)) {
?>
<option value="<?php echo $row['id'];?>"><?php echo $row['name'];?></option>
<?php } ?>
</select>
</div>
</div>
<div class="control-group">
<div class="controls">
<input name="submit" value="Add Link" type="submit" class="btn" />
</div>
</div>
</form>
<h1>Navigation Groups</h1>
<br/>
<?php
//Step - 3 (SQL / Get result)
$sql_group = "SELECT * from `navigation_groups`";
$result_group = mysql_query($sql_group);
if ($result_group && mysql_num_rows($result_group)) {
?>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Slug</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
//Step - 4 (Grab / Process result of query)
$i=0;
while ($row = mysql_fetch_assoc($result_group)) {
$i++;
//echo "<pre>";print_r($row);echo "</pre>";
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['slug']; ?></td>
<td>
<a href="dbactions/user_edit.php?id=<?php echo $row['id']; ?>">Edit</a> |
<a onclick="return sure()" href="dbactions/nav_group_delete.php?id=<?php echo $row['id']; ?>">Delete</a>
</td>
</tr>
<?php }?>
</tbody>
</table>
<?php
} else {
echo "No navigation groups found";
}
//Step - 5 (Close connection)
mysql_close($con);
?>
<h3>Add New Navigation Group</h3>
<form class="form-horizontal" action="dbactions/nav_group_add.php" method="POST">
<div class="control-group">
<label class="control-label" for="first_name">Name</label>
<div class="controls">
<input type="text" name="name" value="">
</div>
</div>
<div class="control-group">
<div class="controls">
<input name="submit" value="Add Link" type="submit" class="btn" />
</div>
</div>
</form>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
| PHP |
<?php
session_start();
if (!$_SESSION['login']) header ("location: index.php");
include "includes/common.php";
if(isset($_POST['submit'])) {
/* echo "<pre>";
echo "post";
print_r($_POST);
echo "files";
print_r($_FILES);
echo "session";
print_r($_SESSION);
echo "</pre>";
exit; */
$title = $_POST['title'];
$content = $_POST['content'];
$category = $_POST['category'];
$status = $_POST['status'];
$error = "";
if ($title !="" && $content != "") {
$upload_dir = '../uploads';
//tmp_name holds temporary file for uploaded file
$source_file = $_FILES['image']['tmp_name'];
//the 'name' key of the array holds original filename
//we can use original file name here as our destination filename. it will be saved inside our upload directory
$destination_file = time()."_".$_FILES['image']['name'];
if (move_uploaded_file($source_file, $upload_dir."/".$destination_file)){
//file upload done;
$now = time();
$user_id = $_SESSION['user_id'];
$sql = "INSERT INTO `post` VALUES (NULL, \"$user_id\", \"$title\", \"$content\",\"$category\",\"$destination_file\",\"$now\", '$status');";
mysql_query ($sql);
//header ("location: gallery.php");
}else {
$error .= "Couldn't upload file. Retry later";
}
}else {
$error .= "Please provide title and content.";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Course</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
<script src="../third_party/ckeditor/ckeditor.js"></script>
<link rel="stylesheet" href="../third_party/ckeditor/sample.css">
<script type="text/javascript">
function sure(){
if (confirm("Are you sure delete?")){
return true;
}else {
return false;
}
}
</script>
</head>
<body>
<!-- include navigation here -->
<?php include "views/nav.php"; ?>
<div class="container">
<h1>POSTS</h1>
<br/>
<?php
//Step - 3 (SQL / Get result)
$sql = "SELECT post.*, post_categories.name, users.username from `post`
JOIN `post_categories` ON post.category = post_categories.id
JOIN `users` ON post.user_id = users.id
";
//$sql = "SELECT * FROM `post`";
$result = mysql_query($sql);
if ($result && mysql_num_rows($result)) {
?>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Title</th>
<th>Image</th>
<th>Category</th>
<th>Posted By</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
//Step - 4 (Grab / Process result of query)
$i=0;
while ($row = mysql_fetch_assoc($result)) {
$i++;
//echo "<pre>";print_r($row);echo "</pre>";
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $row['title']; ?></td>
<td><img width="100" height="100" src="<?php echo UPLOAD_PATH.$row['image']; ?>" /></td>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['username'];?></td>
<td><?php echo ($row['status'])? "Published" : "Draft";?></td>
<td>
<a href="dbactions/user_edit.php?id=<?php echo $row['id']; ?>">Edit</a> |
<a onclick="return sure()" href="dbactions/gallery_delete.php?id=<?php echo $row['id']; ?>">Delete</a>
</td>
</tr>
<?php }?>
</tbody>
</table>
<?php
} else {
echo "No posts found";
}
//Step - 5 (Close connection)
?>
<h3>Add Post</h3>
<?php
if (isset($error)) {
echo "<p style='color:red;'>$error<br/></p>";
}
?>
<form class="form-horizontal" enctype="multipart/form-data" action="" method="POST">
<div class="control-group">
<label class="control-label" for="first_name">Title</label>
<div class="controls">
<input type="text" name="title" value="">
</div>
</div>
<div class="control-group">
<label class="control-label" for="first_name">Image</label>
<div class="controls">
<input type="file" name="image" value="">
</div>
</div>
<div class="control-group">
<label class="control-label" for="first_name">Publish</label>
<div class="controls">
<input type="checkbox" name="status" value="1">
</div>
</div>
<div class="control-group">
<label class="control-label" for="first_name">Category</label>
<div class="controls">
<select name="category">
<option value="">Select Category</option>
<?php
$sql_group = "SELECT * from `post_categories`";
$result_group = mysql_query($sql_group);
while ($row = mysql_fetch_assoc($result_group)) {
?>
<option value="<?php echo $row['id'];?>"><?php echo $row['name'];?></option>
<?php } ?>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="first_name">Content</label>
<div class="controls">
<textarea class="ckeditor input-xxlarge" name="content" rows="10" col="80"></textarea>
</div>
</div>
<div class="control-group">
<div class="controls">
<input name="submit" value="Add Post" type="submit" class="btn" />
</div>
</div>
</form>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
| PHP |
<?php
session_start();
if (!$_SESSION['login']) header ("location: index.php");
include "includes/common.php";
if(isset($_POST['submit'])) {
/*
echo "<pre>";
print_r($_POST);
print_r($_FILES);
echo "</pre>";
*/
$name = $_POST['name'];
$caption = $_POST['caption'];
$status = $_POST['status'];
$error = "";
if ($name !="" && $caption != "" && isset($_FILES)) {
$upload_dir = '../uploads';
//tmp_name holds temporary file for uploaded file
$source_file = $_FILES['image']['tmp_name'];
//the 'name' key of the array holds original filename
//we can use original file name here as our destination filename. it will be saved inside our upload directory
$destination_file = time()."_".$_FILES['image']['name'];
$ext = substr($_FILES['image']['name'], -3);
if (in_array($ext, array("jpg","gif","bmp","png") )){
if (move_uploaded_file($source_file, $upload_dir."/".$destination_file)){
//file upload done;
$now = time();
$sql = "INSERT INTO `gallery` (`id`, `name`, `path`, `caption`, `status`, `created_at`) VALUES (NULL, \"$name\", \"$destination_file\", \"$caption\",\"$status\", '$now');";
mysql_query ($sql);
//header ("location: gallery.php");
}else {
$error .= "Couldn't upload file. Retry later";
}
}else {
$error .= "Only images are allowed";
}
}else {
$error .= "Please provide all info.";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Course</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
<script type="text/javascript">
function sure(){
if (confirm("Are you sure delete?")){
return true;
}else {
return false;
}
}
</script>
</head>
<body>
<!-- include navigation here -->
<?php include "views/nav.php"; ?>
<div class="container">
<h1>Gallery</h1>
<br/>
<?php
//Step - 3 (SQL / Get result)
/*
$sql = "SELECT navigation_groups.*,navigations.* from `navigations`
JOIN `navigation_group`
ON navigations.group_id = navigation_groups.id
"; */
$sql = "SELECT * FROM `gallery`";
$result = mysql_query($sql);
if ($result && mysql_num_rows($result)) {
?>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Image</th>
<th>Name</th>
<th>Caption</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
//Step - 4 (Grab / Process result of query)
$i=0;
while ($row = mysql_fetch_assoc($result)) {
$i++;
//echo "<pre>";print_r($row);echo "</pre>";
?>
<tr>
<td><?php echo $i; ?></td>
<td><a href="<?php echo $upload_url."/".$row['path'];?>"><img height="100" width="100" src="<?php echo $upload_url.$row['path']; ?>"/> </a></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['caption'];?></td>
<td><?php echo ($row['status'])? "Published" : "Draft";?></td>
<td>
<a href="dbactions/user_edit.php?id=<?php echo $row['id']; ?>">Edit</a> |
<a onclick="return sure()" href="dbactions/gallery_delete.php?id=<?php echo $row['id']; ?>">Delete</a>
</td>
</tr>
<?php }?>
</tbody>
</table>
<?php
} else {
echo "No images found";
}
//Step - 5 (Close connection)
?>
<h3>Add New Image</h3>
<?php
if (isset($error)) {
echo "<p style='color:red;'>$error<br/></p>";
}
?>
<form class="form-horizontal" enctype="multipart/form-data" action="" method="POST">
<div class="control-group">
<label class="control-label" for="first_name">Name</label>
<div class="controls">
<input type="text" name="name" value="">
</div>
</div>
<div class="control-group">
<label class="control-label" for="first_name">Image</label>
<div class="controls">
<input type="file" name="image" value="">
</div>
</div>
<div class="control-group">
<label class="control-label" for="first_name">Caption</label>
<div class="controls">
<input type="text" class="span4" name="caption" value="">
</div>
</div>
<div class="control-group">
<label class="control-label" for="first_name">Publish</label>
<div class="controls">
<input type="checkbox" name="status" value="1">
</div>
</div>
<div class="control-group">
<div class="controls">
<input name="submit" value="Upload Image" type="submit" class="btn" />
</div>
</div>
</form>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
| PHP |
<?php
$site_url = "http://localhost/ambition/class/";
$upload_url = "http://localhost/ambition/class/uploads/";
define('UPLOAD_PATH', 'http://localhost/ambition/class/uploads/' );
$con = mysql_connect("localhost", "root", "");
mysql_select_db("cms");
?>
| PHP |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootstrap, from Twitter</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PV Gallery</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">USers</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>Welcome to PV Gallery</h1>
<p>Use this document as a way to quick start any new project.<br> All you get is this message and a barebones HTML document.</p>
<?php
$fruits = array ("apple","mango","orange","banana");
echo "<pre>";
print_r($fruits);
echo "</pre>";
echo "<br/>My favorite fruits : ";
for ($i=0; $i < count($fruits) ; $i++){
echo "<br/>" ;
echo $fruits [$i];
}
echo "<br/><br/><br/> foreach<br/>------------";
$fruits = array ("apple","mango","orange","banana");
foreach ($fruits as $fruit){
echo $fruit;
}
$fruits = array ("orange","apple","banana");
$users = array (
array (
"username" => "sanju",
"password" => "ihg987656gggyfhvhg9876456",
"email" => "sanju@gmail.com",
"address" =>"baneshwor",
"phone" => "9841",
"status" => 1
),
array (
"username" => "rudra",
"password" => "ihg987656gggyfhvhg9876456",
"email" => "rudra@gmail.com",
"address" =>"baneshwor",
"phone" => "9841",
"status" => 1
),
array (
"username" => "bimala",
"password" => "ihg987656gggyfhvhg9876456",
"email" => "bimala@gmail.com",
"address" =>"baneshwor",
"phone" => "9841",
"status" => 1
),
);
echo "<pre>";
print_r($users);
echo "</pre>";
?>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Username</th>
<th>Email</th>
<th>Address</th>
<th>Phone</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user) {?>
<tr>
<td>1</td>
<td><?php echo $user['username'];?></td>
<td><?php echo $user['email'];?></td>
<td><?php echo $user['address'];?></td>
<td><?php echo $user['phone'];?></td>
<td>
<?php if ($user['status'] == 1){
echo "Active";
}else {
echo "Inactive";
}
?>
</td>
<td><a href="">View</a> | <a href="">Edit</a> | <a href="">Delete</a></td>
</tr>
<?php }?>
</tbody>
</table>
<?php
//CSV - Comma Separated Values
$sports = "football, cricket, basketball";
$sports_array = explode ("," , $sports );
echo "<pre>"; print_r($sports_array); echo "</pre>";
echo $string = implode ("," , $sports_array );
$filename = "sample.exe";
$e = substr($filename,-3);
$allowed_ext = array ("jpg","bmp","gif","png");
if (in_array($e, $allowed_ext)) {
echo "<br/><strong>File allowed to upload</strong>";
}else {
echo "<br/><strong>Not supported file format</strong>";
}
echo "<br/>Array Push/Pop";
$allowed_ext = array ("jpg","bmp","gif","png");
echo "<pre>"; print_r($allowed_ext); echo "</pre>";
array_push($allowed_ext,"psd");
echo "<pre>"; print_r($allowed_ext); echo "</pre>";
array_push($allowed_ext,"doc");
array_push($allowed_ext,"txt");
array_push($allowed_ext,"bmp");
echo "<pre>"; print_r($allowed_ext); echo "</pre>";
$unique = array_unique ($allowed_ext);
echo "<pre>"; print_r($unique); echo "</pre>";
echo array_pop($unique);
echo "<pre>"; print_r($unique); echo "</pre>";
asort($unique);
echo "<pre>"; print_r($unique); echo "</pre>";
arsort($unique);
echo "<pre>"; print_r($unique); echo "</pre>";
ksort($unique);
echo "<pre>"; print_r($unique); echo "</pre>";
$merged = array_merge($sports_array, $unique);
echo "<pre>"; print_r($merged); echo "</pre>";
$rand_key = array_rand($merged);
echo $merged[$rand_key];
?>
<br>
<br>
<br>
<br>
<br>
<br>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
| PHP |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootstrap, from Twitter</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PV Gallery</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">USers</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>Welcome to PV Gallery</h1>
<p>Use this document as a way to quick start any new project.<br> All you get is this message and a barebones HTML document.</p>
<?php
function add($a,$b){
return $a + $b;
}
echo "Sum is ".add(2,10);
//echo "Sum is ".add($_GET['a'],$_GET['b']);
//string functions
echo strlen("bhupal")."<br/>";
echo "<pre>";
//print_r( count_chars ("hello world"));
echo "</pre>";
echo strtoupper('hello world')."<br/>";
echo strtolower('Hello World')."<br/>";
echo ucfirst("ambition college")."<br/>";
echo ucwords("ambition college")."<br/>";
$str = "Hi it's 9 o'Clock";
echo addslashes ($str)."<br/>";
echo stripslashes (addslashes ($str))."<br/>";
echo $data = 5/3;
echo "<br/>";
echo number_format($data,2);
$str = "filename.jpeg";
echo "<br/>";
echo substr($str, -3, 3);
echo "<br/>";
echo substr($str, 0, 4);
echo "<br/>";
echo $dot_position = strpos($str,".");
echo "<br/>";
echo substr( $str, $dot_position+1);
echo "<br/>";
echo sha1("password");
echo "<br/>";
echo md5("password");
echo "<br/>";
echo sin(deg2rad(30));
echo "<br/>";
echo cos(30);
$value = 5.8;
echo "<br/>";
echo ceil($value);
echo "<br/>";
echo floor($value);
echo "<br/>";
echo rand();
echo "<br/>";
echo rand(1,10);
echo "<br/>";
echo abs(-10);
echo abs(+10);
echo sqrt(25);
echo pow(5,2);
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
| PHP |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootstrap, from Twitter</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">Calculator</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">USers</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>Calculator</h1>
<p>Simple calculator</p>
<br/>
<br/>
<form class="form-inline" method="GET" action="calculator.php">
<input type="text" class="input-small" name="num1" placeholder="1st number">
<select name="operator" class="input-small">
<option value="+">Add</option>
<option value="-">Substract</option>
<option value="*">Multiply</option>
<option value="/">Divide</option>
</select>
<input type="text" class="input-small" name ="num2" placeholder="2nd Number">
<button name="submit" value="submit" type="submit" class="btn">Calculate</button>
</form>
<?php
if ($_GET['submit'] != ""){
$num1 = $_GET['num1'];$num2 = $_GET['num2'];
if ($num1 == "" || $num2 == "") {
echo "Please enter both numbers.";
}else {
//echo "<pre>"; print_r($_GET); echo "</pre>";
$op = $_GET['operator'];
if ($op == "+"){ $result = $num1+$num2; }
else if ($op== "-"){ $result = $num1 - $num2;}
else if ($op== "*"){ $result = $num1 * $num2;}
else if ($op== "/"){ $result = $num1 / $num2;}
else { $result = 0; }
echo "Output of $num1 $op $num2 is : $result ";
}
}
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
| PHP |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootstrap, from Twitter</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PV Gallery</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">USers</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>Welcome to PV Gallery</h1>
<p>Use this document as a way to quick start any new project.<br> All you get is this message and a barebones HTML document.</p>
<?php
$fruits = array ("apple","mango","orange","banana");
echo "<pre>";
print_r($fruits);
echo "</pre>";
echo "<br/>My favorite fruits : ";
for ($i=0; $i < count($fruits) ; $i++){
echo "<br/>" ;
echo $fruits [$i];
}
echo "<br/><br/><br/> foreach<br/>------------";
$fruits = array ("apple","mango","orange","banana");
foreach ($fruits as $fruit){
echo $fruit;
}
$fruits = array ("orange","apple","banana");
$users = array (
array (
"username" => "sanju",
"password" => "ihg987656gggyfhvhg9876456",
"email" => "sanju@gmail.com",
"address" =>"baneshwor",
"phone" => "9841",
"status" => 1
),
array (
"username" => "rudra",
"password" => "ihg987656gggyfhvhg9876456",
"email" => "rudra@gmail.com",
"address" =>"baneshwor",
"phone" => "9841",
"status" => 1
),
array (
"username" => "bimala",
"password" => "ihg987656gggyfhvhg9876456",
"email" => "bimala@gmail.com",
"address" =>"baneshwor",
"phone" => "9841",
"status" => 1
),
);
echo "<pre>";
print_r($users);
echo "</pre>";
?>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Username</th>
<th>Email</th>
<th>Address</th>
<th>Phone</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user) {?>
<tr>
<td>1</td>
<td><?php echo $user['username'];?></td>
<td><?php echo $user['email'];?></td>
<td><?php echo $user['address'];?></td>
<td><?php echo $user['phone'];?></td>
<td>
<?php if ($user['status'] == 1){
echo "Active";
}else {
echo "Inactive";
}
?>
</td>
<td><a href="">View</a> | <a href="">Edit</a> | <a href="">Delete</a></td>
</tr>
<?php }?>
</tbody>
</table>
<?php
//CSV - Comma Separated Values
$sports = "football, cricket, basketball";
$sports_array = explode ("," , $sports );
echo "<pre>"; print_r($sports_array); echo "</pre>";
echo $string = implode ("," , $sports_array );
$filename = "sample.exe";
$e = substr($filename,-3);
$allowed_ext = array ("jpg","bmp","gif","png");
if (in_array($e, $allowed_ext)) {
echo "<br/><strong>File allowed to upload</strong>";
}else {
echo "<br/><strong>Not supported file format</strong>";
}
echo "<br/>Array Push/Pop";
$allowed_ext = array ("jpg","bmp","gif","png");
echo "<pre>"; print_r($allowed_ext); echo "</pre>";
array_push($allowed_ext,"psd");
echo "<pre>"; print_r($allowed_ext); echo "</pre>";
array_push($allowed_ext,"doc");
array_push($allowed_ext,"txt");
array_push($allowed_ext,"bmp");
echo "<pre>"; print_r($allowed_ext); echo "</pre>";
$unique = array_unique ($allowed_ext);
echo "<pre>"; print_r($unique); echo "</pre>";
echo array_pop($unique);
echo "<pre>"; print_r($unique); echo "</pre>";
asort($unique);
echo "<pre>"; print_r($unique); echo "</pre>";
arsort($unique);
echo "<pre>"; print_r($unique); echo "</pre>";
ksort($unique);
echo "<pre>"; print_r($unique); echo "</pre>";
$merged = array_merge($sports_array, $unique);
echo "<pre>"; print_r($merged); echo "</pre>";
$rand_key = array_rand($merged);
echo $merged[$rand_key];
?>
<br>
<br>
<br>
<br>
<br>
<br>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
| PHP |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Course</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PHP Course</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">Users</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>Welcome to Database</h1>
<?php
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
| PHP |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootstrap, from Twitter</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PV Gallery</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">USers</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>Welcome to PV Gallery</h1>
<p>Use this document as a way to quick start any new project.<br> All you get is this message and a barebones HTML document.</p>
<?php
function add($a,$b){
return $a + $b;
}
echo "Sum is ".add(2,10);
//echo "Sum is ".add($_GET['a'],$_GET['b']);
//string functions
echo strlen("bhupal")."<br/>";
echo "<pre>";
//print_r( count_chars ("hello world"));
echo "</pre>";
echo strtoupper('hello world')."<br/>";
echo strtolower('Hello World')."<br/>";
echo ucfirst("ambition college")."<br/>";
echo ucwords("ambition college")."<br/>";
$str = "Hi it's 9 o'Clock";
echo addslashes ($str)."<br/>";
echo stripslashes (addslashes ($str))."<br/>";
echo $data = 5/3;
echo "<br/>";
echo number_format($data,2);
$str = "filename.jpeg";
echo "<br/>";
echo substr($str, -3, 3);
echo "<br/>";
echo substr($str, 0, 4);
echo "<br/>";
echo $dot_position = strpos($str,".");
echo "<br/>";
echo substr( $str, $dot_position+1);
echo "<br/>";
echo sha1("password");
echo "<br/>";
echo md5("password");
echo "<br/>";
echo sin(deg2rad(30));
echo "<br/>";
echo cos(30);
$value = 5.8;
echo "<br/>";
echo ceil($value);
echo "<br/>";
echo floor($value);
echo "<br/>";
echo rand();
echo "<br/>";
echo rand(1,10);
echo "<br/>";
echo abs(-10);
echo abs(+10);
echo sqrt(25);
echo pow(5,2);
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
| PHP |
<?php
session_start();
if (!$_SESSION['login']) header ("location: login.php");
include "dbactions/user_add.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Course</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
<script type="text/javascript">
function sure(){
if (confirm("Are you sure delete this user ?")){
return true;
}else {
return false;
}
}
</script>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PHP Course</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">Users</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
<li><a href="logout.php">Logout - <?php echo $_SESSION['username']; ?></a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>PHP / MySql</h1>
<p>Basic CRUD oparations on Database</p>
<br/>
<?php
//Step - 1 (Connection)
$con = mysql_connect("localhost", "root", "");
//Step - 2 (Database)
mysql_select_db("test");
//Step - 3 (SQL / Get result)
$sql = "SELECT * from `users`";
$result = mysql_query($sql);
?>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Username</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
//Step - 4 (Grab / Process result of query)
$i=0;
while ($row = mysql_fetch_assoc($result)) {
$i++;
//echo "<pre>";print_r($row);echo "</pre>";
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $row['username'];?></td>
<td><?php echo $row['email'];?></td>
<td>
<a href="">View</a> |
<a href="dbactions/user_edit.php?id=<?php echo $row['id']; ?>">Edit</a> |
<a onclick="return sure()" href="dbactions/user_delete.php?id=<?php echo $row['id']; ?>">Delete</a>
</td>
</tr>
<?php }?>
</tbody>
</table>
<?php
//Step - 5 (Close connection)
mysql_close($con);
?>
<h3>Add New Users</h3>
<form class="form-horizontal" action="" method="POST">
<div class="control-group <?php if ($username_error) { echo 'error'; } ?> ">
<label class="control-label" for="first_name">Username</label>
<div class="controls">
<input type="text" name="username" value="<?php if (isset($username)) echo $username; ?>">
<?php if ($username_error) { ?>
<span class="help-inline"><?php echo $username_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group <?php if ($password_error) { echo 'error'; } ?>">
<label class="control-label" for="username">Password</label>
<div class="controls">
<input type="password" id="password" name="password" value="" >
<?php if ($password_error) { ?>
<span class="help-inline"><?php echo $password_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group <?php if ($email_error) { echo 'error'; } ?>">
<label class="control-label" for="last_name">Email</label>
<div class="controls">
<input type="text" id="email" name="email" value="<?php if (isset($email)) echo $email; ?>">
<?php if ($email_error) { ?>
<span class="help-inline"><?php echo $email_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group">
<div class="controls">
<input name="submit" value="Add User" type="submit" class="btn" />
</div>
</div>
</form>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
| PHP |
<?php
//Step - 1 (Connection)
$con = mysql_connect("localhost", "root", "");
//Step - 2 (Database)
mysql_select_db("test");
//Step - 3 (SQL / Get result)
$sql = "";
//Step - 4 (Grab / Process / Execute query)
$sql = "delete from `users` where `id` = $id";
mysql_query($sql);
//Step - 5 (Close connection)
mysql_close($con);
//redirect to main page
header ("location: ../database.php");
?> | PHP |
<?php
session_start();
if (!$_SESSION['login']) header ("location: ../login.php");
//Step - 1 (Connection)
$con = mysql_connect("localhost", "root", "");
//Step - 2 (Database)
mysql_select_db("test");
$id= $_GET['id'];
//Step - 3 (SQL / Get result)
$sql = "SELECT * from `users` where `id` = $id";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if (isset($_POST['submit'])) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$email = trim($_POST['email']);
$password = md5($password);
$sql_update = "UPDATE `users` SET `username` = '$username', `password` = '$password', `email` = '$email' WHERE `id` = $id";
mysql_query($sql_update);
header ("location: ../database.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Course</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="../assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PHP Course</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">Users</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>PHP / MySql</h1>
<p>Basic CRUD oparations on Database</p>
<br/>
<h3>Update User '<?php echo $row['username']; ?>' </h3>
<br/><br/>
<form class="form-horizontal" action="" method="POST">
<div class="control-group <?php if ($username_error) { echo 'error'; } ?> ">
<label class="control-label" for="first_name">Username</label>
<div class="controls">
<input type="text" name="username" value="<?php echo $row['username']; ?>">
<?php if ($username_error) { ?>
<span class="help-inline"><?php echo $username_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group <?php if ($password_error) { echo 'error'; } ?>">
<label class="control-label" for="username">Password</label>
<div class="controls">
<input type="password" id="password" name="password" value="<?php echo $row['password']; ?>" >
<?php if ($password_error) { ?>
<span class="help-inline"><?php echo $password_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group <?php if ($email_error) { echo 'error'; } ?>">
<label class="control-label" for="last_name">Email</label>
<div class="controls">
<input type="text" id="email" name="email" value="<?php echo $row['email']; ?>">
<?php if ($email_error) { ?>
<span class="help-inline"><?php echo $email_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group">
<div class="controls">
<input name="submit" value="Update User" type="submit" class="btn" />
</div>
</div>
</form>
<?php
//Step - 5 (Close connection)
mysql_close($con);
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
| PHP |
<?php
//Step - 1 (Connection)
$con = mysql_connect("localhost", "root", "");
//Step - 2 (Database)
mysql_select_db("test");
//Step - 3 (SQL / Get result)
$id = $_GET['id'];
$sql = "delete from `users` where `id` = $id";
mysql_query($sql);
//echo "user id ". $_GET['id'] . " deleted";
header ("location: ../database.php");
?> | PHP |
<?php
if (isset($_POST['submit'])) {
$error = false;
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$email = trim($_POST['email']);
if($username == '') {
$error = true;
$username_error = "Please provide username";
}
if($password == '') {
$error = true;
$password_error = "Please provide password";
}else {
$password = md5($_POST['password']);
}
if($email == '') {
$error = true;
$email_error = "Please provide email";
}
//if ($username != "" && $password !="" && $email !="" ) {
if(!$error) {
$con = mysql_connect("localhost", "root", "");
mysql_select_db("test");
$sql = "INSERT INTO `users` (`id`, `username`, `password`, `email`) VALUES (NULL, '$username','$password','$email');";
mysql_query($sql);
header ("location: database.php");
}
}
?> | PHP |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootstrap, from Twitter</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">Calculator</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">USers</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>Calculator</h1>
<p>Simple calculator</p>
<br/>
<br/>
<form class="form-inline" method="GET" action="calculator.php">
<input type="text" class="input-small" name="num1" placeholder="1st number">
<select name="operator" class="input-small">
<option value="+">Add</option>
<option value="-">Substract</option>
<option value="*">Multiply</option>
<option value="/">Divide</option>
</select>
<input type="text" class="input-small" name ="num2" placeholder="2nd Number">
<button name="submit" value="submit" type="submit" class="btn">Calculate</button>
</form>
<?php
if ($_GET['submit'] != ""){
$num1 = $_GET['num1'];$num2 = $_GET['num2'];
if ($num1 == "" || $num2 == "") {
echo "Please enter both numbers.";
}else {
//echo "<pre>"; print_r($_GET); echo "</pre>";
$op = $_GET['operator'];
if ($op == "+"){ $result = $num1+$num2; }
else if ($op== "-"){ $result = $num1 - $num2;}
else if ($op== "*"){ $result = $num1 * $num2;}
else if ($op== "/"){ $result = $num1 / $num2;}
else { $result = 0; }
echo "Output of $num1 $op $num2 is : $result ";
}
}
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
| PHP |
<?php
session_start();
//unset session
$_SESSION['login'] = 0;
$_SESSION['username'] = "";
//or
//unset($_SESSION['login']);
//unset($_SESSION['username']);
session_destroy();
//redirect to login page
header ("location: login.php");
?>
| PHP |
<?php
session_start();
$username = $_POST['username']; $password = $_POST['password'];
if ($_POST['submit'] && ($username !="" && $password !="" )) {
$password = md5($_POST['password']);
$con = mysql_connect("localhost", "root", "");
mysql_select_db("test");
$sql = "select * from `users` where `username` = '$username' and `password` = '$password'";
$result = mysql_query($sql);
$count_result = mysql_num_rows($result);
if ($count_result == 1 ) {
//echo "Login Success!";
//set session
$_SESSION['login'] = 1;
$_SESSION['username'] = $username;
//redirect to database
header ("location: database.php");
}else {
echo "Login failed!";
}
} else {
echo "Please provide username & password!";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sign in · Twitter Bootstrap</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style type="text/css">
body {
padding-top: 40px;
padding-bottom: 40px;
background-color: #f5f5f5;
}
.form-signin {
max-width: 300px;
padding: 19px 29px 29px;
margin: 0 auto 20px;
background-color: #fff;
border: 1px solid #e5e5e5;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
box-shadow: 0 1px 2px rgba(0,0,0,.05);
}
.form-signin .form-signin-heading,
.form-signin .checkbox {
margin-bottom: 10px;
}
.form-signin input[type="text"],
.form-signin input[type="password"] {
font-size: 16px;
height: auto;
margin-bottom: 15px;
padding: 7px 9px;
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="../assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="../assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="../assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="../assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="../assets/ico/favicon.png">
</head>
<body>
<div class="container">
<form class="form-signin" action="" method="POST" >
<h2 class="form-signin-heading">Login</h2>
Username: <input name="username" value="" type="text" class="input-block-level" >
Password: <input name="password" value="" type="password" class="input-block-level" >
<button name="submit" value="Sign In" class="btn btn-large btn-primary" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
| PHP |
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?>
<?php
// (C) Copyright 2001
// Murray Jensen <Murray.Jensen@csiro.au>
// CSIRO Manufacturing Science and Technology, Preston Lab
// doedit page (hymod_bddb / boards)
require("defs.php");
pg_head("$bddb_label - Add Log Entry Results");
if (!isset($_REQUEST['serno']) || $_REQUEST['serno'] == '')
die("serial number not specified!");
$serno=intval($_REQUEST['serno']);
if (isset($_REQUEST['logno'])) {
$logno=$_REQUEST['logno'];
die("log number must not be set ($logno) when Creating!");
}
$query="update log set serno=$serno";
list($y, $m, $d) = split("-", $date);
if (!checkdate($m, $d, $y) || $y < 1999)
die("date is invalid (input '$date', yyyy-mm-dd '$y-$m-$d')");
$query.=", date='$date'";
if (isset($_REQUEST['who'])) {
$who=$_REQUEST['who'];
$query.=", who='" . $who . "'";
}
if (isset($_REQUEST['details'])) {
$details=$_REQUEST['details'];
$query.=", details='" . rawurlencode($details) . "'";
}
// echo "final query = '$query'<br>\n";
$sqlerr = '';
mysql_query("insert into log (logno) values (null)");
if (mysql_errno())
$sqlerr = mysql_error();
else {
$logno = mysql_insert_id();
if (!$logno)
$sqlerr = "couldn't allocate new serial number";
else {
mysql_query($query . " where logno=$logno");
if (mysql_errno())
$sqlerr = mysql_error();
}
}
if ($sqlerr == '') {
echo "<font size=+2>\n";
echo "\t<p>\n";
echo "\t\tA log entry with log number '$logno' was " .
"added to the board with serial number '$serno'\n";
echo "\t</p>\n";
echo "</font>\n";
}
else {
echo "\t<font size=+4>\n";
echo "\t\t<p>\n";
echo "\t\t\tThe following SQL error was encountered:\n";
echo "\t\t</p>\n";
echo "\t\t<center>\n";
printf("\t\t\t<b>%s</b>\n", $sqlerr);
echo "\t\t</center>\n";
echo "\t</font>\n";
}
?>
<p></p>
<table width="100%">
<tr>
<td align=center><a href="brlog.php?serno=<?php echo "$serno"; ?>">Go to Browse</a></td>
<td align=center><a href="index.php">Back to Start</a></td>
</tr>
</table>
<?php
pg_foot();
?>
| PHP |
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?>
<?php
// (C) Copyright 2001
// Murray Jensen <Murray.Jensen@csiro.au>
// CSIRO Manufacturing Science and Technology, Preston Lab
// edit page (hymod_bddb / boards)
require("defs.php");
pg_head("$bddb_label - New Board Registration");
?>
<form action=donew.php method=POST>
<p></p>
<?php
$serno=intval($serno);
// if a serial number was supplied, fetch the record
// and use its contents as defaults
if ($serno != 0) {
$r=mysql_query("select * from boards where serno=$serno");
$row=mysql_fetch_array($r);
if(!$row)die("no record of serial number '$serno' in database");
}
else
$row = array();
begin_table(5);
// date date
print_field("date", array('date' => date("Y-m-d")));
// batch char(32)
print_field("batch", $row, 32);
// type enum('IO','CLP','DSP','INPUT','ALT-INPUT','DISPLAY')
print_enum("type", $row, $type_vals, 0);
// rev tinyint(3) unsigned zerofill
print_field("rev", $row, 3, 'rev_filter');
// sdram[0-3] enum('32M','64M','128M','256M')
print_enum_multi("sdram", $row, $sdram_vals, 4, array(2));
// flash[0-3] enum('4M','8M','16M','32M','64M')
print_enum_multi("flash", $row, $flash_vals, 4, array(2));
// zbt[0-f] enum('512K','1M','2M','4M')
print_enum_multi("zbt", $row, $zbt_vals, 16, array(2, 2));
// xlxtyp[0-3] enum('XCV300E','XCV400E','XCV600E')
print_enum_multi("xlxtyp", $row, $xlxtyp_vals, 4, array(1), 1);
// xlxspd[0-3] enum('6','7','8')
print_enum_multi("xlxspd", $row, $xlxspd_vals, 4, array(1), 1);
// xlxtmp[0-3] enum('COM','IND')
print_enum_multi("xlxtmp", $row, $xlxtmp_vals, 4, array(1), 1);
// xlxgrd[0-3] enum('NORMAL','ENGSAMP')
print_enum_multi("xlxgrd", $row, $xlxgrd_vals, 4, array(1), 1);
// cputyp enum('MPC8260(HIP3)','MPC8260A(HIP4)','MPC8280(HIP7)')
print_enum("cputyp", $row, $cputyp_vals, 1);
// cpuspd enum('33MHZ','66MHZ','100MHZ','133MHZ','166MHZ','200MHZ','233MHZ','266MHZ')
print_enum_select("cpuspd", $row, $clk_vals, 4);
// cpmspd enum('33MHZ','66MHZ','100MHZ','133MHZ','166MHZ','200MHZ','233MHZ','266MHZ')
print_enum_select("cpmspd", $row, $clk_vals, 4);
// busspd enum('33MHZ','66MHZ','100MHZ','133MHZ','166MHZ','200MHZ','233MHZ','266MHZ')
print_enum_select("busspd", $row, $clk_vals, 2);
// hstype enum('AMCC-S2064A')
print_enum("hstype", $row, $hstype_vals, 1);
// hschin enum('0','1','2','3','4')
print_enum("hschin", $row, $hschin_vals, 4);
// hschout enum('0','1','2','3','4')
print_enum("hschout", $row, $hschout_vals, 4);
end_table();
?>
<p></p>
<table width="100%">
<tr>
<td align=center colspan=3>
Allocate
<input type=text name=quant size=2 maxlength=2 value=" 1">
board serial number(s)
</td>
</tr>
<tr>
<td align=center colspan=3>
<input type=checkbox name=geneths checked>
Generate Ethernet Address(es)
</td>
</tr>
<tr>
<td colspan=3>
</td>
</tr>
<tr>
<td align=center>
<input type=submit value="Register Board">
</td>
<td>
</td>
<td align=center>
<input type=reset value="Reset Form Contents">
</td>
</tr>
</table>
</form>
<?php
pg_foot();
?>
| PHP |
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?>
<?php
// (C) Copyright 2001
// Murray Jensen <Murray.Jensen@csiro.au>
// CSIRO Manufacturing Science and Technology, Preston Lab
// dodelete page (hymod_bddb / boards)
require("defs.php");
pg_head("$bddb_label - Delete Log Entry Results");
if (!isset($_REQUEST['serno']))
die("the board serial number was not specified");
$serno=intval($_REQUEST['serno']);
if (!isset($_REQUEST['logno']) || $_REQUEST['logno'] == 0)
die("the log entry number not specified!");
$logno=$_REQUEST['logno'];
mysql_query("delete from log where serno=$serno and logno=$logno");
if(mysql_errno()) {
$errstr = mysql_error();
echo "\t<font size=+4>\n";
echo "\t\t<p>\n";
echo "\t\t\tThe following error was encountered:\n";
echo "\t\t</p>\n";
echo "\t\t<center>\n";
printf("\t\t\t<b>%s</b>\n", $errstr);
echo "\t\t</center>\n";
echo "\t</font>\n";
}
else {
echo "\t<font size=+2>\n";
echo "\t\t<p>\n";
echo "\t\t\tThe log entry with log number <b>$logno</b>\n";
echo "\t\t\tand serial number <b>$serno</b> ";
echo "was successfully deleted\n";
echo "\t\t</p>\n";
echo "\t</font>\n";
}
?>
<p>
<table width="100%">
<tr>
<td align=center>
<a href="brlog.php?serno=<?php echo "$serno"; ?>">Back to Log</a>
</td>
<td align=center>
<a href="index.php">Back to Start</a>
</td>
</tr>
</table>
<?php
pg_foot();
?>
| PHP |
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?>
<?php
// (C) Copyright 2001
// Murray Jensen <Murray.Jensen@csiro.au>
// CSIRO Manufacturing Science and Technology, Preston Lab
require("defs.php");
pg_head("$bddb_label - Unknown Submit Type");
?>
<center>
<font size="+4">
<b>
The <?php echo "$bddb_label"; ?> form was submitted with an
unknown SUBMIT type <?php echo "(value was '$submit')" ?>.
<br></br>
Perhaps you typed the URL in directly? Click here to go to the
home page of the <a href="index.php"><?php echo "$bddb_label"; ?></a>.
</b>
</font>
</center>
<?php
pg_foot();
?>
| PHP |
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?>
<?php
// (C) Copyright 2001
// Murray Jensen <Murray.Jensen@csiro.au>
// CSIRO Manufacturing Science and Technology, Preston Lab
// doedit page (hymod_bddb / boards)
require("defs.php");
pg_head("$bddb_label - Board Registration Results");
if (isset($_REQUEST['serno'])) {
$serno=$_REQUEST['serno'];
die("serial number must not be set ($serno) when Creating!");
}
$query="update boards set";
list($y, $m, $d) = split("-", $date);
if (!checkdate($m, $d, $y) || $y < 1999)
die("date is invalid (input '$date', yyyy-mm-dd '$y-$m-$d')");
$query.=" date='$date'";
if ($batch != '') {
if (strlen($batch) > 32)
die("batch field too long (>32)");
$query.=", batch='$batch'";
}
if (!in_array($type, $type_vals))
die("Invalid type ($type) specified");
$query.=", type='$type'";
if (($rev = intval($rev)) <= 0 || $rev > 255)
die("Revision number is invalid ($rev)");
$query.=sprintf(", rev=%d", $rev);
$query.=gather_enum_multi_query("sdram", 4);
$query.=gather_enum_multi_query("flash", 4);
$query.=gather_enum_multi_query("zbt", 16);
$query.=gather_enum_multi_query("xlxtyp", 4);
$nxlx = count_enum_multi("xlxtyp", 4);
$query.=gather_enum_multi_query("xlxspd", 4);
if (count_enum_multi("xlxspd", 4) != $nxlx)
die("number of xilinx speeds not same as number of types");
$query.=gather_enum_multi_query("xlxtmp", 4);
if (count_enum_multi("xlxtmp", 4) != $nxlx)
die("number of xilinx temps. not same as number of types");
$query.=gather_enum_multi_query("xlxgrd", 4);
if (count_enum_multi("xlxgrd", 4) != $nxlx)
die("number of xilinx grades not same as number of types");
if ($cputyp == '') {
if ($cpuspd != '')
die("can't specify cpu speed if there is no cpu");
if ($cpmspd != '')
die("can't specify cpm speed if there is no cpu");
if ($busspd != '')
die("can't specify bus speed if there is no cpu");
}
else {
$query.=", cputyp='$cputyp'";
if ($cpuspd == '')
die("must specify cpu speed if cpu type is defined");
$query.=", cpuspd='$cpuspd'";
if ($cpmspd == '')
die("must specify cpm speed if cpu type is defined");
$query.=", cpmspd='$cpmspd'";
if ($busspd == '')
die("must specify bus speed if cpu type is defined");
$query.=", busspd='$busspd'";
}
if (($hschin = intval($hschin)) < 0 || $hschin > 4)
die("Invalid number of hs input chans ($hschin)");
if (($hschout = intval($hschout)) < 0 || $hschout > 4)
die("Invalid number of hs output chans ($hschout)");
if ($hstype == '') {
if ($hschin != 0)
die("number of high-speed input channels must be zero"
. " if high-speed chip is not present");
if ($hschout != 0)
die("number of high-speed output channels must be zero"
. " if high-speed chip is not present");
}
else
$query.=", hstype='$hstype'";
$query.=", hschin='$hschin'";
$query.=", hschout='$hschout'";
// echo "final query = '$query'<br>\n";
$quant = intval($quant);
if ($quant <= 0) $quant = 1;
$sernos = array();
if ($geneths)
$ethaddrs = array();
$sqlerr = '';
while ($quant-- > 0) {
mysql_query("insert into boards (serno) values (null)");
if (mysql_errno()) {
$sqlerr = mysql_error();
break;
}
$serno = mysql_insert_id();
if (!$serno) {
$sqlerr = "couldn't allocate new serial number";
break;
}
mysql_query($query . " where serno=$serno");
if (mysql_errno()) {
$sqlerr = mysql_error();
break;
}
array_push($sernos, $serno);
if ($geneths) {
$ethaddr = gen_eth_addr($serno);
mysql_query("update boards set ethaddr='$ethaddr'" .
" where serno=$serno");
if (mysql_errno()) {
$sqlerr = mysql_error();
array_push($ethaddrs,
"<font color=#ff0000><b>" .
"db save fail" .
"</b></font>");
break;
}
array_push($ethaddrs, $ethaddr);
}
}
$nsernos = count($sernos);
if ($nsernos > 0) {
write_eeprom_cfg_file();
echo "<font size=+2>\n";
echo "\t<p>\n";
echo "\t\tThe following board serial numbers were"
. " successfully allocated";
if ($numerrs > 0)
echo " (but with $numerrs cfg file error" .
($numerrs > 1 ? "s" : "") . ")";
echo ":\n";
echo "\t</p>\n";
echo "</font>\n";
echo "<table align=center width=\"100%\">\n";
echo "<tr>\n";
echo "\t<th>Serial Number</th>\n";
if ($numerrs > 0)
echo "\t<th>Cfg File Errs</th>\n";
if ($geneths)
echo "\t<th>Ethernet Address</th>\n";
echo "</tr>\n";
for ($i = 0; $i < $nsernos; $i++) {
$serno = sprintf("%010d", $sernos[$i]);
echo "<tr>\n";
echo "\t<td align=center><font size=+2>" .
"<b>$serno</b></font></td>\n";
if ($numerrs > 0) {
if (($errstr = $cfgerrs[$i]) == '')
$errstr = ' ';
echo "\t<td align=center>" .
"<font size=+2 color=#ff0000><b>" .
$errstr .
"</b></font></td>\n";
}
if ($geneths) {
echo "\t<td align=center>" .
"<font size=+2 color=#00ff00><b>" .
$ethaddrs[$i] .
"</b></font></td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
}
if ($sqlerr != '') {
echo "\t<font size=+4>\n";
echo "\t\t<p>\n";
echo "\t\t\tThe following SQL error was encountered:\n";
echo "\t\t</p>\n";
echo "\t\t<center>\n";
printf("\t\t\t<b>%s</b>\n", $sqlerr);
echo "\t\t</center>\n";
echo "\t</font>\n";
}
?>
<p>
<table align=center width="100%">
<tr>
<td align=center><a href="browse.php">Go to Browse</a></td>
<td align=center><a href="index.php">Back to Start</a></td>
</tr>
</table>
<?php
pg_foot();
?>
| PHP |
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?>
<?php
// (C) Copyright 2001
// Murray Jensen <Murray.Jensen@csiro.au>
// CSIRO Manufacturing Science and Technology, Preston Lab
$serno=isset($_REQUEST['serno'])?$_REQUEST['serno']:'';
$submit=isset($_REQUEST['submit'])?$_REQUEST['submit']:"[NOT SET]";
switch ($submit) {
case "New":
require("new.php");
break;
case "Edit":
require("edit.php");
break;
case "Browse":
require("browse.php");
break;
case "Log":
require("brlog.php");
break;
default:
require("badsubmit.php");
break;
}
?>
| PHP |
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?>
<?php
// (C) Copyright 2001
// Murray Jensen <Murray.Jensen@csiro.au>
// CSIRO Manufacturing Science and Technology, Preston Lab
// contains mysql user id and password - keep secret
require("config.php");
if (isset($_REQUEST['logout'])) {
Header("status: 401 Unauthorized");
Header("HTTP/1.0 401 Unauthorized");
Header("WWW-authenticate: basic realm=\"$bddb_label\"");
echo "<html><head><title>" .
"Access to '$bddb_label' Denied" .
"</title></head>\n";
echo "<body bgcolor=#ffffff><br></br><br></br><center><h1>" .
"You must be an Authorised User " .
"to access the '$bddb_label'" .
"</h1>\n</center></body></html>\n";
exit;
}
// contents of the various enumerated types - if first item is
// empty ('') then the enum is allowed to be null (ie "not null"
// is not set on the column)
// all column names in the database table
$columns = array(
'serno','ethaddr','date','batch',
'type','rev','location','comments',
'sdram0','sdram1','sdram2','sdram3',
'flash0','flash1','flash2','flash3',
'zbt0','zbt1','zbt2','zbt3','zbt4','zbt5','zbt6','zbt7',
'zbt8','zbt9','zbta','zbtb','zbtc','zbtd','zbte','zbtf',
'xlxtyp0','xlxtyp1','xlxtyp2','xlxtyp3',
'xlxspd0','xlxspd1','xlxspd2','xlxspd3',
'xlxtmp0','xlxtmp1','xlxtmp2','xlxtmp3',
'xlxgrd0','xlxgrd1','xlxgrd2','xlxgrd3',
'cputyp','cpuspd','cpmspd','busspd',
'hstype','hschin','hschout'
);
// board type
$type_vals = array('IO','CLP','DSP','INPUT','ALT-INPUT','DISPLAY');
// Xilinx fpga types
$xlxtyp_vals = array('','XCV300E','XCV400E','XCV600E','XC2V2000','XC2V3000','XC2V4000','XC2V6000','XC2VP2','XC2VP4','XC2VP7','XC2VP20','XC2VP30','XC2VP50','XC4VFX20','XC4VFX40','XC4VFX60','XC4VFX100','XC4VFX140');
// Xilinx fpga speeds
$xlxspd_vals = array('','6','7','8','4','5','9','10','11','12');
// Xilinx fpga temperatures (commercial or industrial)
$xlxtmp_vals = array('','COM','IND');
// Xilinx fpga grades (normal or engineering sample)
$xlxgrd_vals = array('','NORMAL','ENGSAMP');
// CPU types
$cputyp_vals = array('','MPC8260(HIP3)','MPC8260A(HIP4)','MPC8280(HIP7)','MPC8560');
// CPU/BUS/CPM clock speeds
$clk_vals = array('','33MHZ','66MHZ','100MHZ','133MHZ','166MHZ','200MHZ','233MHZ','266MHZ','300MHZ','333MHZ','366MHZ','400MHZ','433MHZ','466MHZ','500MHZ','533MHZ','566MHZ','600MHZ','633MHZ','666MHZ','700MHZ','733MHZ','766MHZ','800MHZ','833MHZ','866MHZ','900MHZ','933MHZ','966MHZ','1000MHZ','1033MHZ','1066MHZ','1100MHZ','1133MHZ','1166MHZ','1200MHZ','1233MHZ','1266MHZ','1300MHZ','1333MHZ');
// sdram sizes (nbits array is for eeprom config file)
$sdram_vals = array('','32M','64M','128M','256M','512M','1G','2G','4G');
$sdram_nbits = array(0,25,26,27,28,29,30,31,32);
// flash sizes (nbits array is for eeprom config file)
$flash_vals = array('','4M','8M','16M','32M','64M','128M','256M','512M','1G');
$flash_nbits = array(0,22,23,24,25,26,27,28,29,30);
// zbt ram sizes (nbits array is for write into eeprom config file)
$zbt_vals = array('','512K','1M','2M','4M','8M','16M');
$zbt_nbits = array(0,19,20,21,22,23,24);
// high-speed serial attributes
$hstype_vals = array('','AMCC-S2064A','Xilinx-Rockets');
$hschin_vals = array('0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16');
$hschout_vals = array('0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16');
// value filters - used when outputting html
function rev_filter($num) {
if ($num == 0)
return "001";
else
return sprintf("%03d", $num);
}
function text_filter($str) {
return urldecode($str);
}
mt_srand(time() | getmypid());
// set up MySQL connection
mysql_connect("", $mysql_user, $mysql_pw) || die("cannot connect");
mysql_select_db($mysql_db) || die("cannot select db");
// page header
function pg_head($title)
{
echo "<html>\n<head>\n";
echo "<link rel=stylesheet href=\"bddb.css\" type=\"text/css\" title=\"style sheet\"></link>\n";
echo "<title>$title</title>\n";
echo "</head>\n";
echo "<body>\n";
echo "<center><h1>$title</h1></center>\n";
echo "<hr></hr>\n";
}
// page footer
function pg_foot()
{
echo "<hr></hr>\n";
echo "<table width=\"100%\"><tr><td align=left>\n<address>" .
"If you have any problems, email " .
"<a href=\"mailto:Murray.Jensen@csiro.au\">" .
"Murray Jensen" .
"</a></address>\n" .
"</td><td align=right>\n" .
"<a href=\"index.php?logout=true\">logout</a>\n" .
"</td></tr></table>\n";
echo "<p><small><i>Made with " .
"<a href=\"http://kyber.dk/phpMyBuilder/\">" .
"Kyber phpMyBuilder</a></i></small></p>\n";
echo "</body>\n";
echo "</html>\n";
}
// some support functions
if (!function_exists('array_search')) {
function array_search($needle, $haystack, $strict = false) {
if (is_array($haystack) && count($haystack)) {
$ntype = gettype($needle);
foreach ($haystack as $key => $value) {
if ($value == $needle && (!$strict ||
gettype($value) == $ntype))
return $key;
}
}
return false;
}
}
if (!function_exists('in_array')) {
function in_array($needle, $haystack, $strict = false) {
if (is_array($haystack) && count($haystack)) {
$ntype = gettype($needle);
foreach ($haystack as $key => $value) {
if ($value == $needle && (!$strict ||
gettype($value) == $ntype))
return true;
}
}
return false;
}
}
function key_in_array($key, $array) {
return in_array($key, array_keys($array), true);
}
function enum_to_index($name, $vals) {
$index = array_search($GLOBALS[$name], $vals);
if ($vals[0] != '')
$index++;
return $index;
}
// fetch a value from an array - return empty string is not present
function get_key_value($key, $array) {
if (key_in_array($key, $array))
return $array[$key];
else
return '';
}
function fprintf() {
$n = func_num_args();
if ($n < 2)
return FALSE;
$a = func_get_args();
$fp = array_shift($a);
$x = "\$s = sprintf";
$sep = '(';
foreach ($a as $z) {
$x .= "$sep'$z'";
$sep = ',';
}
$x .= ');';
eval($x);
$l = strlen($s);
$r = fwrite($fp, $s, $l);
if ($r != $l)
return FALSE;
else
return TRUE;
}
// functions to display (print) a database table and its columns
function begin_table($ncols) {
global $table_ncols;
$table_ncols = $ncols;
echo "<table align=center width=\"100%\""
. " border=1 cellpadding=4 cols=$table_ncols>\n";
}
function begin_field($name, $span = 0) {
global $table_ncols;
echo "<tr valign=top>\n";
echo "\t<th align=center>$name</th>\n";
if ($span <= 0)
$span = $table_ncols - 1;
if ($span > 1)
echo "\t<td colspan=$span>\n";
else
echo "\t<td>\n";
}
function cont_field($span = 1) {
echo "\t</td>\n";
if ($span > 1)
echo "\t<td colspan=$span>\n";
else
echo "\t<td>\n";
}
function end_field() {
echo "\t</td>\n";
echo "</tr>\n";
}
function end_table() {
echo "</table>\n";
}
function print_field($name, $array, $size = 0, $filt='') {
begin_field($name);
if (key_in_array($name, $array))
$value = $array[$name];
else
$value = '';
if ($filt != '')
$value = $filt($value);
echo "\t\t<input name=$name value=\"$value\"";
if ($size > 0)
echo " size=$size maxlength=$size";
echo "></input>\n";
end_field();
}
function print_field_multiline($name, $array, $cols, $rows, $filt='') {
begin_field($name);
if (key_in_array($name, $array))
$value = $array[$name];
else
$value = '';
if ($filt != '')
$value = $filt($value);
echo "\t\t<textarea name=$name " .
"cols=$cols rows=$rows wrap=off>\n";
echo "$value";
echo "</textarea>\n";
end_field();
}
// print a mysql ENUM as an html RADIO INPUT
function print_enum($name, $array, $vals, $def = -1) {
begin_field($name);
if (key_in_array($name, $array))
$chk = array_search($array[$name], $vals, FALSE);
else
$chk = $def;
$nval = count($vals);
for ($i = 0; $i < $nval; $i++) {
$val = $vals[$i];
if ($val == '')
$pval = "none";
else
$pval = "$val";
printf("\t\t<input type=radio name=$name"
. " value=\"$val\"%s>$pval</input>\n",
$i == $chk ? " checked" : "");
}
end_field();
}
// print a mysql ENUM as an html SELECT INPUT
function print_enum_select($name, $array, $vals, $def = -1) {
begin_field($name);
echo "\t\t<select name=$name>\n";
if (key_in_array($name, $array))
$chk = array_search($array[$name], $vals, FALSE);
else
$chk = $def;
$nval = count($vals);
for ($i = 0; $i < $nval; $i++) {
$val = $vals[$i];
if ($val == '')
$pval = "none";
else
$pval = "$val";
printf("\t\t\t<option " .
"value=\"%s\"%s>%s</option>\n",
$val, $i == $chk ? " selected" : "", $pval);
}
echo "\t\t</select>\n";
end_field();
}
// print a group of mysql ENUMs (e.g. name0,name1,...) as an html SELECT
function print_enum_multi($base, $array, $vals, $cnt, $defs, $grp = 0) {
global $table_ncols;
if ($grp <= 0)
$grp = $cnt;
$ncell = $cnt / $grp;
$span = ($table_ncols - 1) / $ncell;
begin_field($base, $span);
$nval = count($vals);
for ($i = 0; $i < $cnt; $i++) {
if ($i > 0 && ($i % $grp) == 0)
cont_field($span);
$name = sprintf("%s%x", $base, $i);
echo "\t\t<select name=$name>\n";
if (key_in_array($name, $array))
$ai = array_search($array[$name], $vals, FALSE);
else {
if (key_in_array($i, $defs))
$ai = $defs[$i];
else
$ai = 0;
}
for ($j = 0; $j < $nval; $j++) {
$val = $vals[$j];
if ($val == '')
$pval = " ";
else
$pval = "$val";
printf("\t\t\t<option " .
"value=\"%s\"%s>%s</option>\n",
$val,
$j == $ai ? " selected" : "",
$pval);
}
echo "\t\t</select>\n";
}
end_field();
}
// functions to handle the form input
// fetch all the parts of an "enum_multi" into a string suitable
// for a MySQL query
function gather_enum_multi_query($base, $cnt) {
$retval = '';
for ($i = 0; $i < $cnt; $i++) {
$name = sprintf("%s%x", $base, $i);
if (isset($_REQUEST[$name])) {
$retval .= sprintf(", %s='%s'",
$name, $_REQUEST[$name]);
}
}
return $retval;
}
// fetch all the parts of an "enum_multi" into a string suitable
// for a display e.g. in an html table cell
function gather_enum_multi_print($base, $cnt, $array) {
$retval = '';
for ($i = 0; $i < $cnt; $i++) {
$name = sprintf("%s%x", $base, $i);
if ($array[$name] != '') {
if ($retval != '')
$retval .= ',';
$retval .= $array[$name];
}
}
return $retval;
}
// fetch all the parts of an "enum_multi" into a string suitable
// for writing to the eeprom data file
function gather_enum_multi_write($base, $cnt, $vals, $xfrm = array()) {
$retval = '';
for ($i = 0; $i < $cnt; $i++) {
$name = sprintf("%s%x", $base, $i);
if ($GLOBALS[$name] != '') {
if ($retval != '')
$retval .= ',';
$index = enum_to_index($name, $vals);
if ($xfrm != array())
$retval .= $xfrm[$index];
else
$retval .= $index;
}
}
return $retval;
}
// count how many parts of an "enum_multi" are actually set
function count_enum_multi($base, $cnt) {
$retval = 0;
for ($i = 0; $i < $cnt; $i++) {
$name = sprintf("%s%x", $base, $i);
if (isset($_REQUEST[$name]))
$retval++;
}
return $retval;
}
// ethernet address functions
// generate a (possibly not unique) random vendor ethernet address
// (setting bit 6 in the ethernet address - motorola wise i.e. bit 0
// is the most significant bit - means it is not an assigned ethernet
// address - it is a "locally administered" address). Also, make sure
// it is NOT a multicast ethernet address (by setting bit 7 to 0).
// e.g. the first byte of all ethernet addresses generated here will
// have 2 in the bottom two bits (incidentally, these are the first
// two bits transmitted on the wire, since the octets in ethernet
// addresses are transmitted LSB first).
function gen_eth_addr($serno) {
$ethaddr_hgh = (mt_rand(0, 65535) & 0xfeff) | 0x0200;
$ethaddr_mid = mt_rand(0, 65535);
$ethaddr_low = mt_rand(0, 65535);
return sprintf("%02lx:%02lx:%02lx:%02lx:%02lx:%02lx",
$ethaddr_hgh >> 8, $ethaddr_hgh & 0xff,
$ethaddr_mid >> 8, $ethaddr_mid & 0xff,
$ethaddr_low >> 8, $ethaddr_low & 0xff);
}
// check that an ethernet address is valid
function eth_addr_is_valid($ethaddr) {
$ethbytes = split(':', $ethaddr);
if (count($ethbytes) != 6)
return FALSE;
for ($i = 0; $i < 6; $i++) {
$ethbyte = $ethbytes[$i];
if (!ereg('^[0-9a-f][0-9a-f]$', $ethbyte))
return FALSE;
}
return TRUE;
}
// write a simple eeprom configuration file
function write_eeprom_cfg_file() {
global $sernos, $nsernos, $bddb_cfgdir, $numerrs, $cfgerrs;
global $date, $batch, $type_vals, $rev;
global $sdram_vals, $sdram_nbits;
global $flash_vals, $flash_nbits;
global $zbt_vals, $zbt_nbits;
global $xlxtyp_vals, $xlxspd_vals, $xlxtmp_vals, $xlxgrd_vals;
global $cputyp, $cputyp_vals, $clk_vals;
global $hstype, $hstype_vals, $hschin, $hschout;
$numerrs = 0;
$cfgerrs = array();
for ($i = 0; $i < $nsernos; $i++) {
$serno = sprintf("%010d", $sernos[$i]);
$wfp = @fopen($bddb_cfgdir . "/$serno.cfg", "w");
if (!$wfp) {
$cfgerrs[$i] = 'file create fail';
$numerrs++;
continue;
}
set_file_buffer($wfp, 0);
if (!fprintf($wfp, "serno=%d\n", $sernos[$i])) {
$cfgerrs[$i] = 'cfg wr fail (serno)';
fclose($wfp);
$numerrs++;
continue;
}
if (!fprintf($wfp, "date=%s\n", $date)) {
$cfgerrs[$i] = 'cfg wr fail (date)';
fclose($wfp);
$numerrs++;
continue;
}
if ($batch != '') {
if (!fprintf($wfp, "batch=%s\n", $batch)) {
$cfgerrs[$i] = 'cfg wr fail (batch)';
fclose($wfp);
$numerrs++;
continue;
}
}
$typei = enum_to_index("type", $type_vals);
if (!fprintf($wfp, "type=%d\n", $typei)) {
$cfgerrs[$i] = 'cfg wr fail (type)';
fclose($wfp);
$numerrs++;
continue;
}
if (!fprintf($wfp, "rev=%d\n", $rev)) {
$cfgerrs[$i] = 'cfg wr fail (rev)';
fclose($wfp);
$numerrs++;
continue;
}
$s = gather_enum_multi_write("sdram", 4,
$sdram_vals, $sdram_nbits);
if ($s != '') {
$b = fprintf($wfp, "sdram=%s\n", $s);
if (!$b) {
$cfgerrs[$i] = 'cfg wr fail (sdram)';
fclose($wfp);
$numerrs++;
continue;
}
}
$s = gather_enum_multi_write("flash", 4,
$flash_vals, $flash_nbits);
if ($s != '') {
$b = fprintf($wfp, "flash=%s\n", $s);
if (!$b) {
$cfgerrs[$i] = 'cfg wr fail (flash)';
fclose($wfp);
$numerrs++;
continue;
}
}
$s = gather_enum_multi_write("zbt", 16,
$zbt_vals, $zbt_nbits);
if ($s != '') {
$b = fprintf($wfp, "zbt=%s\n", $s);
if (!$b) {
$cfgerrs[$i] = 'cfg wr fail (zbt)';
fclose($wfp);
$numerrs++;
continue;
}
}
$s = gather_enum_multi_write("xlxtyp", 4, $xlxtyp_vals);
if ($s != '') {
$b = fprintf($wfp, "xlxtyp=%s\n", $s);
if (!$b) {
$cfgerrs[$i] = 'cfg wr fail (xlxtyp)';
fclose($wfp);
$numerrs++;
continue;
}
}
$s = gather_enum_multi_write("xlxspd", 4, $xlxspd_vals);
if ($s != '') {
$b = fprintf($wfp, "xlxspd=%s\n", $s);
if (!$b) {
$cfgerrs[$i] = 'cfg wr fail (xlxspd)';
fclose($wfp);
$numerrs++;
continue;
}
}
$s = gather_enum_multi_write("xlxtmp", 4, $xlxtmp_vals);
if ($s != '') {
$b = fprintf($wfp, "xlxtmp=%s\n", $s);
if (!$b) {
$cfgerrs[$i] = 'cfg wr fail (xlxtmp)';
fclose($wfp);
$numerrs++;
continue;
}
}
$s = gather_enum_multi_write("xlxgrd", 4, $xlxgrd_vals);
if ($s != '') {
$b = fprintf($wfp, "xlxgrd=%s\n", $s);
if (!$b) {
$cfgerrs[$i] = 'cfg wr fail (xlxgrd)';
fclose($wfp);
$numerrs++;
continue;
}
}
if ($cputyp != '') {
$cputypi = enum_to_index("cputyp",$cputyp_vals);
$cpuspdi = enum_to_index("cpuspd", $clk_vals);
$busspdi = enum_to_index("busspd", $clk_vals);
$cpmspdi = enum_to_index("cpmspd", $clk_vals);
$b = fprintf($wfp, "cputyp=%d\ncpuspd=%d\n" .
"busspd=%d\ncpmspd=%d\n",
$cputypi, $cpuspdi, $busspdi, $cpmspdi);
if (!$b) {
$cfgerrs[$i] = 'cfg wr fail (cputyp)';
fclose($wfp);
$numerrs++;
continue;
}
}
if ($hstype != '') {
$hstypei = enum_to_index("hstype",$hstype_vals);
$b = fprintf($wfp, "hstype=%d\n" .
"hschin=%s\nhschout=%s\n",
$hstypei, $hschin, $hschout);
if (!$b) {
$cfgerrs[$i] = 'cfg wr fail (hstype)';
fclose($wfp);
$numerrs++;
continue;
}
}
if (!fclose($wfp)) {
$cfgerrs[$i] = 'file cls fail';
$numerrs++;
}
}
return $numerrs;
}
?>
| PHP |
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?>
<?php
// (C) Copyright 2001
// Murray Jensen <Murray.Jensen@csiro.au>
// CSIRO Manufacturing Science and Technology, Preston Lab
// list page (hymod_bddb / boards)
require("defs.php");
pg_head("$bddb_label - Browse Board Log");
$serno=intval($serno);
if ($serno == 0)
die("serial number not specified or invalid!");
function print_cell($str) {
if ($str == '')
$str = ' ';
echo "\t<td>$str</td>\n";
}
?>
<table align=center border=1 cellpadding=10>
<tr>
<th>serno / edit</th>
<th>ethaddr</th>
<th>date</th>
<th>batch</th>
<th>type</th>
<th>rev</th>
<th>location</th>
</tr>
<?php
$r=mysql_query("select * from boards where serno=$serno");
while($row=mysql_fetch_array($r)){
foreach ($columns as $key) {
if (!key_in_array($key, $row))
$row[$key] = '';
}
echo "<tr>\n";
print_cell("<a href=\"edit.php?serno=$row[serno]\">$row[serno]</a>");
print_cell($row['ethaddr']);
print_cell($row['date']);
print_cell($row['batch']);
print_cell($row['type']);
print_cell($row['rev']);
print_cell($row['location']);
echo "</tr>\n";
}
mysql_free_result($r);
?>
</table>
<hr></hr>
<p></p>
<?php
$limit=abs(isset($_REQUEST['limit'])?$_REQUEST['limit']:20);
$offset=abs(isset($_REQUEST['offset'])?$_REQUEST['offset']:0);
$lr=mysql_query("select count(*) as n from log where serno=$serno");
$lrow=mysql_fetch_array($lr);
if($lrow['n']>$limit){
$preoffset=max(0,$offset-$limit);
$postoffset=$offset+$limit;
echo "<table width=\"100%\">\n<tr align=center>\n";
printf("<td><%sa href=\"%s?submit=Log&serno=$serno&offset=%d\"><img border=0 alt=\"<\" src=\"/icons/left.gif\"></a></td>\n", $offset>0?"":"no", $PHP_SELF, $preoffset);
printf("<td><%sa href=\"%s?submit=Log&serno=$serno&offset=%d\"><img border=0 alt=\">\" src=\"/icons/right.gif\"></a></td>\n", $postoffset<$lrow['n']?"":"no", $PHP_SELF, $postoffset);
echo "</tr>\n</table>\n";
}
mysql_free_result($lr);
?>
<table width="100%" border=1 cellpadding=10>
<tr valign=top>
<th>logno / edit</th>
<th>date</th>
<th>who</th>
<th width="70%">details</th>
</tr>
<?php
$r=mysql_query("select * from log where serno=$serno order by logno limit $offset,$limit");
while($row=mysql_fetch_array($r)){
echo "<tr>\n";
print_cell("<a href=\"edlog.php?serno=$row[serno]&logno=$row[logno]\">$row[logno]</a>");
print_cell($row['date']);
print_cell($row['who']);
print_cell("<pre>" . urldecode($row['details']) . "</pre>");
echo "</tr>\n";
}
mysql_free_result($r);
?>
</table>
<hr></hr>
<p></p>
<table width="100%">
<tr>
<td align=center>
<a href="newlog.php?serno=<?php echo "$serno"; ?>">Add to Log</a>
</td>
<td align=center>
<a href="index.php">Back to Start</a>
</td>
</tr>
</table>
<?php
pg_foot();
?>
| PHP |
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?>
<?php
// (C) Copyright 2001
// Murray Jensen <Murray.Jensen@csiro.au>
// CSIRO Manufacturing Science and Technology, Preston Lab
// edit page (hymod_bddb / boards)
require("defs.php");
pg_head("$bddb_label - New Log Entry");
if (!isset($_REQUEST['serno']) || $_REQUEST['serno'] == '')
die("serial number not specified or invalid!");
$serno=intval($_REQUEST['serno']);
if (isset($_REQUEST['logno'])) {
$logno=$_REQUEST['logno'];
die("log number must not be specified when adding! ($logno)");
}
?>
<form action=donewlog.php method=POST>
<p></p>
<?php
echo "<input type=hidden name=serno value=$serno>\n";
begin_table(3);
// date date
print_field("date", array('date' => date("Y-m-d")));
// who char(20)
print_field("who", array());
// details text
print_field_multiline("details", array(), 60, 10, 'text_filter');
end_table();
?>
<p></p>
<table width="100%">
<tr>
<td align=center>
<input type=submit value="Add Log Entry">
</td>
<td align=center>
<input type=reset value="Reset Form Contents">
</td>
</tr>
</table>
</form>
<?php
pg_foot();
?>
| PHP |
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?>
<?php
// (C) Copyright 2001
// Murray Jensen <Murray.Jensen@csiro.au>
// CSIRO Manufacturing Science and Technology, Preston Lab
// edit page (hymod_bddb / boards)
require("defs.php");
pg_head("$bddb_label - Edit Board Registration");
if ($serno == 0)
die("serial number not specified or invalid!");
$pserno = sprintf("%010d", $serno);
echo "<center><b><font size=+2>";
echo "Board Serial Number: $pserno";
echo "</font></b></center>\n";
?>
<p>
<form action=doedit.php method=POST>
<?php
echo "<input type=hidden name=serno value=$serno>\n";
$r=mysql_query("select * from boards where serno=$serno");
$row=mysql_fetch_array($r);
if(!$row) die("no record of serial number '$serno' in database");
begin_table(5);
// ethaddr char(17)
print_field("ethaddr", $row, 17);
// date date
print_field("date", $row);
// batch char(32)
print_field("batch", $row, 32);
// type enum('IO','CLP','DSP','INPUT','ALT-INPUT','DISPLAY')
print_enum("type", $row, $type_vals);
// rev tinyint(3) unsigned zerofill
print_field("rev", $row, 3, 'rev_filter');
// location char(64)
print_field("location", $row, 64);
// comments text
print_field_multiline("comments", $row, 60, 10, 'text_filter');
// sdram[0-3] enum('32M','64M','128M','256M')
print_enum_multi("sdram", $row, $sdram_vals, 4, array());
// flash[0-3] enum('4M','8M','16M','32M','64M')
print_enum_multi("flash", $row, $flash_vals, 4, array());
// zbt[0-f] enum('512K','1M','2M','4M')
print_enum_multi("zbt", $row, $zbt_vals, 16, array());
// xlxtyp[0-3] enum('XCV300E','XCV400E','XCV600E')
print_enum_multi("xlxtyp", $row, $xlxtyp_vals, 4, array(), 1);
// xlxspd[0-3] enum('6','7','8')
print_enum_multi("xlxspd", $row, $xlxspd_vals, 4, array(), 1);
// xlxtmp[0-3] enum('COM','IND')
print_enum_multi("xlxtmp", $row, $xlxtmp_vals, 4, array(), 1);
// xlxgrd[0-3] enum('NORMAL','ENGSAMP')
print_enum_multi("xlxgrd", $row, $xlxgrd_vals, 4, array(), 1);
// cputyp enum('MPC8260(HIP3)','MPC8260A(HIP4)','MPC8280(HIP7)')
print_enum("cputyp", $row, $cputyp_vals);
// cpuspd enum('33MHZ','66MHZ','100MHZ','133MHZ','166MHZ','200MHZ','233MHZ','266MHZ')
print_enum_select("cpuspd", $row, $clk_vals);
// cpmspd enum('33MHZ','66MHZ','100MHZ','133MHZ','166MHZ','200MHZ','233MHZ','266MHZ')
print_enum_select("cpmspd", $row, $clk_vals);
// busspd enum('33MHZ','66MHZ','100MHZ','133MHZ','166MHZ','200MHZ','233MHZ','266MHZ')
print_enum_select("busspd", $row, $clk_vals);
// hstype enum('AMCC-S2064A')
print_enum("hstype", $row, $hstype_vals);
// hschin enum('0','1','2','3','4')
print_enum("hschin", $row, $hschin_vals);
// hschout enum('0','1','2','3','4')
print_enum("hschout", $row, $hschout_vals);
end_table();
echo "<p>\n";
echo "<center><b>";
echo "<font color=#ff0000>WARNING: NO UNDO ON DELETE!</font>";
echo "<br></br>\n";
echo "<tt>[ <a href=\"dodelete.php?serno=$serno\">delete</a> ]</tt>";
echo "</b></center>\n";
echo "</p>\n";
?>
<p>
<table align=center width="100%">
<tr>
<td align=center>
<input type=submit value=Edit>
</td>
<td>
</td>
<td align=center>
<input type=reset value=Reset>
</td>
<td>
</td>
<td align=center>
<a href="index.php">Back to Start</a>
</td>
</tr>
</table>
</p>
</form>
<?php
pg_foot();
?>
| PHP |
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?>
<?php
// (C) Copyright 2001
// Murray Jensen <Murray.Jensen@csiro.au>
// CSIRO Manufacturing Science and Technology, Preston Lab
// doedit page (hymod_bddb / boards)
require("defs.php");
pg_head("$bddb_label - Edit Board Results");
if (!isset($_REQUEST['serno']) || $_REQUEST['serno'] == '')
die("the board serial number was not specified");
$serno=intval($_REQUEST['serno']);
$query="update boards set";
if (isset($_REQUEST['ethaddr'])) {
$ethaddr=$_REQUEST['ethaddr'];
if (!eth_addr_is_valid($ethaddr))
die("ethaddr is invalid ('$ethaddr')");
$query.=" ethaddr='$ethaddr',";
}
if (isset($_REQUEST['date'])) {
$date=$_REQUEST['date'];
list($y, $m, $d) = split("-", $date);
if (!checkdate($m, $d, $y) || $y < 1999)
die("date is invalid (input '$date', " .
"yyyy-mm-dd '$y-$m-$d')");
$query.=" date='$date'";
}
if (isset($_REQUEST['batch'])) {
$batch=$_REQUEST['batch'];
if (strlen($batch) > 32)
die("batch field too long (>32)");
$query.=", batch='$batch'";
}
if (isset($_REQUEST['type'])) {
$type=$_REQUEST['type'];
if (!in_array($type, $type_vals))
die("Invalid type ($type) specified");
$query.=", type='$type'";
}
if (isset($_REQUEST['rev'])) {
$rev=$_REQUEST['rev'];
if (($rev = intval($rev)) <= 0 || $rev > 255)
die("Revision number is invalid ($rev)");
$query.=sprintf(", rev=%d", $rev);
}
if (isset($_REQUEST['location'])) {
$location=$_REQUEST['location'];
if (strlen($location) > 64)
die("location field too long (>64)");
$query.=", location='$location'";
}
if (isset($_REQUEST['comments']))
$comments=$_REQUEST['comments'];
$query.=", comments='" . rawurlencode($comments) . "'";
$query.=gather_enum_multi_query("sdram", 4);
$query.=gather_enum_multi_query("flash", 4);
$query.=gather_enum_multi_query("zbt", 16);
$query.=gather_enum_multi_query("xlxtyp", 4);
$nxlx = count_enum_multi("xlxtyp", 4);
$query.=gather_enum_multi_query("xlxspd", 4);
if (count_enum_multi("xlxspd", 4) != $nxlx)
die("number of xilinx speeds not same as number of types");
$query.=gather_enum_multi_query("xlxtmp", 4);
if (count_enum_multi("xlxtmp", 4) != $nxlx)
die("number of xilinx temps. not same as number of types");
$query.=gather_enum_multi_query("xlxgrd", 4);
if (count_enum_multi("xlxgrd", 4) != $nxlx)
die("number of xilinx grades not same as number of types");
if (isset($_REQUEST['cputyp'])) {
$cputyp=$_REQUEST['cputyp'];
$query.=", cputyp='$cputyp'";
if (!isset($_REQUEST['cpuspd']) || $_REQUEST['cpuspd'] == '')
die("must specify cpu speed if cpu type is defined");
$cpuspd=$_REQUEST['cpuspd'];
$query.=", cpuspd='$cpuspd'";
if (!isset($_REQUEST['cpmspd']) || $_REQUEST['cpmspd'] == '')
die("must specify cpm speed if cpu type is defined");
$cpmspd=$_REQUEST['cpmspd'];
$query.=", cpmspd='$cpmspd'";
if (!isset($_REQUEST['busspd']) || $_REQUEST['busspd'] == '')
die("must specify bus speed if cpu type is defined");
$busspd=$_REQUEST['busspd'];
$query.=", busspd='$busspd'";
}
else {
if (isset($_REQUEST['cpuspd']))
die("can't specify cpu speed if there is no cpu");
if (isset($_REQUEST['cpmspd']))
die("can't specify cpm speed if there is no cpu");
if (isset($_REQUEST['busspd']))
die("can't specify bus speed if there is no cpu");
}
if (isset($_REQUEST['hschin'])) {
$hschin=$_REQUEST['hschin'];
if (($hschin = intval($hschin)) < 0 || $hschin > 4)
die("Invalid number of hs input chans ($hschin)");
}
else
$hschin = 0;
if (isset($_REQUEST['hschout'])) {
$hschout=$_REQUEST['hschout'];
if (($hschout = intval($hschout)) < 0 || $hschout > 4)
die("Invalid number of hs output chans ($hschout)");
}
else
$hschout = 0;
if (isset($_REQUEST['hstype'])) {
$hstype=$_REQUEST['hstype'];
$query.=", hstype='$hstype'";
}
else {
if ($_REQUEST['hschin'] != 0)
die("number of high-speed input channels must be zero"
. " if high-speed chip is not present");
if ($_REQUEST['hschout'] != 0)
die("number of high-speed output channels must be zero"
. " if high-speed chip is not present");
}
$query.=", hschin='$hschin'";
$query.=", hschout='$hschout'";
$query.=" where serno=$serno";
mysql_query($query);
if(mysql_errno()) {
$errstr = mysql_error();
echo "\t<font size=+4>\n";
echo "\t\t<p>\n";
echo "\t\t\tThe following error was encountered:\n";
echo "\t\t</p>\n";
echo "\t\t<center>\n";
printf("\t\t\t<b>%s</b>\n", $errstr);
echo "\t\t</center>\n";
echo "\t</font>\n";
}
else {
$sernos = array($serno);
$nsernos = 1;
write_eeprom_cfg_file();
echo "\t<font size=+2>\n";
echo "\t\t<p>\n";
echo "\t\t\tThe board with serial number <b>$serno</b> was"
. " successfully updated";
if ($numerrs > 0) {
$errstr = $cfgerrs[0];
echo "<br>\n\t\t\t";
echo "(but the cfg file update failed: $errstr)";
}
echo "\n";
echo "\t\t</p>\n";
echo "\t</font>\n";
}
?>
<p>
<table align=center width="100%">
<tr>
<td align=center><a href="browse.php">Back to Browse</a></td>
<td align=center><a href="index.php">Back to Start</a></td>
</tr>
</table>
<?php
pg_foot();
?>
| PHP |
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?>
<?php
// (C) Copyright 2001
// Murray Jensen <Murray.Jensen@csiro.au>
// CSIRO Manufacturing Science and Technology, Preston Lab
// doedit page (hymod_bddb / boards)
require("defs.php");
pg_head("$bddb_label - Edit Log Entry Results");
if (!isset($_REQUEST['serno']) || $_REQUEST['serno'] == '')
die("the board serial number was not specified");
$serno=intval($_REQUEST['serno']);
if (!isset($_REQUEST['logno']) || $_REQUEST['logno'] == '')
die("log number not specified!");
$logno=intval($_REQUEST['logno']);
$query="update log set";
if (isset($_REQUEST['date'])) {
$date=$_REQUEST['date'];
list($y, $m, $d) = split("-", $date);
if (!checkdate($m, $d, $y) || $y < 1999)
die("date is invalid (input '$date', " .
"yyyy-mm-dd '$y-$m-$d')");
$query.=" date='$date'";
}
if (isset($_REQUEST['who'])) {
$who=$_REQUEST['who'];
$query.=", who='" . $who . "'";
}
if (isset($_REQUEST['details'])) {
$details=$_REQUEST['details'];
$query.=", details='" . rawurlencode($details) . "'";
}
$query.=" where serno=$serno and logno=$logno";
mysql_query($query);
if(mysql_errno()) {
$errstr = mysql_error();
echo "\t<font size=+4>\n";
echo "\t\t<p>\n";
echo "\t\t\tThe following error was encountered:\n";
echo "\t\t</p>\n";
echo "\t\t<center>\n";
printf("\t\t\t<b>%s</b>\n", $errstr);
echo "\t\t</center>\n";
echo "\t</font>\n";
}
else {
echo "\t<font size=+2>\n";
echo "\t\t<p>\n";
echo "\t\t\tThe log entry with log number <b>$logno</b> and\n";
echo "\t\t\tserial number <b>$serno</b> ";
echo "was successfully updated\n";
echo "\t\t</p>\n";
echo "\t</font>\n";
}
?>
<p>
<table align=center width="100%">
<tr>
<td align=center><a href="brlog.php?serno=<?php echo "$serno"; ?>">Back to Log</a></td>
<td align=center><a href="index.php">Back to Start</a></td>
</tr>
</table>
<?php
pg_foot();
?>
| PHP |
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?>
<?php
// (C) Copyright 2001
// Murray Jensen <Murray.Jensen@csiro.au>
// CSIRO Manufacturing Science and Technology, Preston Lab
// edit page (hymod_bddb / boards)
require("defs.php");
pg_head("$bddb_label - Edit Board Log Entry");
if (!isset($_REQUEST['serno']) || $_REQUEST['serno'] == '')
die("serial number not specified!");
$serno=intval($_REQUEST['serno']);
if (!isset($_REQUEST['logno']) || $_REQUEST['logno'] == '')
die("log number not specified!");
$logno=intval($_REQUEST['logno']);
$pserno = sprintf("%010d", $serno);
$plogno = sprintf("%010d", $logno);
echo "<center><b><font size=+2>";
echo "Board Serial Number: $pserno, Log Number: $plogno";
echo "</font></b></center>\n";
?>
<p>
<form action=doedlog.php method=POST>
<?php
echo "<input type=hidden name=serno value=$serno>\n";
echo "<input type=hidden name=logno value=$logno>\n";
$r=mysql_query("select * from log where serno=$serno and logno=$logno");
$row=mysql_fetch_array($r);
if(!$row)
die("no record of log entry with serial number '$serno' " .
"and log number '$logno' in database");
begin_table(3);
// date date
print_field("date", $row);
// who char(20)
print_field("who", $row);
// details text
print_field_multiline("details", $row, 60, 10, 'text_filter');
end_table();
echo "<p>\n";
echo "<center><b>";
echo "<font color=#ff0000>WARNING: NO UNDO ON DELETE!</font>";
echo "<br></br>\n";
echo "<tt>[ <a href=\"dodellog.php?serno=$serno&logno=$logno\">delete</a> ]</tt>";
echo "</b></center>\n";
echo "</p>\n";
?>
<p>
<table align=center width="100%">
<tr>
<td align=center>
<input type=submit value=Edit>
</td>
<td>
</td>
<td align=center>
<input type=reset value=Reset>
</td>
<td>
</td>
<td align=center>
<a href="index.php">Back to Start</a>
</td>
</tr>
</table>
</p>
</form>
<?php
pg_foot();
?>
| PHP |
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?>
<?php
// (C) Copyright 2001
// Murray Jensen <Murray.Jensen@csiro.au>
// CSIRO Manufacturing Science and Technology, Preston Lab
// dodelete page (hymod_bddb / boards)
require("defs.php");
pg_head("$bddb_label - Delete Board Results");
if (!isset($_REQUEST['serno']))
die("the board serial number was not specified");
$serno=intval($_REQUEST['serno']);
mysql_query("delete from boards where serno=$serno");
if(mysql_errno()) {
$errstr = mysql_error();
echo "\t<font size=+4>\n";
echo "\t\t<p>\n";
echo "\t\t\tThe following error was encountered:\n";
echo "\t\t</p>\n";
echo "\t\t<center>\n";
printf("\t\t\t<b>%s</b>\n", $errstr);
echo "\t\t</center>\n";
echo "\t</font>\n";
}
else {
echo "\t<font size=+2>\n";
echo "\t\t<p>\n";
echo "\t\t\tThe board with serial number <b>$serno</b> was"
. " successfully deleted\n";
mysql_query("delete from log where serno=$serno");
if (mysql_errno()) {
$errstr = mysql_error();
echo "\t\t\t<font size=+4>\n";
echo "\t\t\t\t<p>\n";
echo "\t\t\t\t\tBut the following error occurred " .
"when deleting the log entries:\n";
echo "\t\t\t\t</p>\n";
echo "\t\t\t\t<center>\n";
printf("\t\t\t\t\t<b>%s</b>\n", $errstr);
echo "\t\t\t\t</center>\n";
echo "\t\t\t</font>\n";
}
echo "\t\t</p>\n";
echo "\t</font>\n";
}
?>
<p>
<table width="100%">
<tr>
<td align=center>
<a href="browse.php">Back to Browse</a>
</td>
<td align=center>
<a href="index.php">Back to Start</a>
</td>
</tr>
</table>
<?php
pg_foot();
?>
| PHP |
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?>
<?php
// (C) Copyright 2001
// Murray Jensen <Murray.Jensen@csiro.au>
// CSIRO Manufacturing Science and Technology, Preston Lab
// list page (hymod_bddb / boards)
require("defs.php");
$serno=isset($_REQUEST['serno'])?$_REQUEST['serno']:'';
$verbose=isset($_REQUEST['verbose'])?intval($_REQUEST['verbose']):0;
pg_head("$bddb_label - Browse database" . ($verbose?" (verbose)":""));
?>
<p></p>
<?php
$limit=isset($_REQUEST['limit'])?abs(intval($_REQUEST['limit'])):20;
$offset=isset($_REQUEST['offset'])?abs(intval($_REQUEST['offset'])):0;
if ($serno == '') {
$lr=mysql_query("select count(*) as n from boards");
$lrow=mysql_fetch_array($lr);
if($lrow['n']>$limit){
$preoffset=max(0,$offset-$limit);
$postoffset=$offset+$limit;
echo "<table width=\"100%\">\n<tr>\n";
printf("<td align=left><%sa href=\"%s?submit=Browse&offset=%d&verbose=%d\"><img border=0 alt=\"<\" src=\"/icons/left.gif\"></a></td>\n", $offset>0?"":"no", $PHP_SELF, $preoffset, $verbose);
printf("<td align=right><%sa href=\"%s?submit=Browse&offset=%d&verbose=%d\"><img border=0 alt=\">\" src=\"/icons/right.gif\"></a></td>\n", $postoffset<$lrow['n']?"":"no", $PHP_SELF, $postoffset, $offset);
echo "</tr>\n</table>\n";
}
mysql_free_result($lr);
}
?>
<table align=center border=1 cellpadding=10>
<tr>
<th></th>
<th>serno / edit</th>
<th>ethaddr</th>
<th>date</th>
<th>batch</th>
<th>type</th>
<th>rev</th>
<th>location</th>
<?php
if ($verbose) {
echo "<th>comments</th>\n";
echo "<th>sdram</th>\n";
echo "<th>flash</th>\n";
echo "<th>zbt</th>\n";
echo "<th>xlxtyp</th>\n";
echo "<th>xlxspd</th>\n";
echo "<th>xlxtmp</th>\n";
echo "<th>xlxgrd</th>\n";
echo "<th>cputyp</th>\n";
echo "<th>cpuspd</th>\n";
echo "<th>cpmspd</th>\n";
echo "<th>busspd</th>\n";
echo "<th>hstype</th>\n";
echo "<th>hschin</th>\n";
echo "<th>hschout</th>\n";
}
?>
</tr>
<?php
$query = "select * from boards";
if ($serno != '') {
$pre = " where ";
foreach (preg_split("/[\s,]+/", $serno) as $s) {
if (preg_match('/^[0-9]+$/',$s))
$query .= $pre . "serno=" . $s;
else if (preg_match('/^([0-9]+)-([0-9]+)$/',$s,$m)) {
$m1 = intval($m[1]); $m2 = intval($m[2]);
if ($m2 <= $m1)
die("bad serial number range ($s)");
$query .= $pre . "(serno>=$m[1] and serno<=$m[2])";
}
else
die("illegal serial number ($s)");
$pre = " or ";
}
}
$query .= " order by serno";
if ($serno == '')
$query .= " limit $offset,$limit";
$r = mysql_query($query);
function print_cell($str) {
if ($str == '')
$str = ' ';
echo "\t<td>$str</td>\n";
}
while($row=mysql_fetch_array($r)){
foreach ($columns as $key) {
if (!key_in_array($key, $row))
$row[$key] = '';
}
echo "<tr>\n";
print_cell("<a href=\"brlog.php?serno=$row[serno]\">Log</a>");
print_cell("<a href=\"edit.php?serno=$row[serno]\">$row[serno]</a>");
print_cell($row['ethaddr']);
print_cell($row['date']);
print_cell($row['batch']);
print_cell($row['type']);
print_cell($row['rev']);
print_cell($row['location']);
if ($verbose) {
print_cell("<pre>\n" . urldecode($row['comments']) .
"\n\t</pre>");
print_cell(gather_enum_multi_print("sdram", 4, $row));
print_cell(gather_enum_multi_print("flash", 4, $row));
print_cell(gather_enum_multi_print("zbt", 16, $row));
print_cell(gather_enum_multi_print("xlxtyp", 4, $row));
print_cell(gather_enum_multi_print("xlxspd", 4, $row));
print_cell(gather_enum_multi_print("xlxtmp", 4, $row));
print_cell(gather_enum_multi_print("xlxgrd", 4, $row));
print_cell($row['cputyp']);
print_cell($row['cpuspd']);
print_cell($row['cpmspd']);
print_cell($row['busspd']);
print_cell($row['hstype']);
print_cell($row['hschin']);
print_cell($row['hschout']);
}
echo "</tr>\n";
}
?>
</table>
<p></p>
<table width="100%">
<tr>
<td align=center><?php
printf("<a href=\"%s?submit=Browse&offset=%d&verbose=%d%s\">%s Listing</a>\n", $PHP_SELF, $offset, $verbose?0:1, $serno!=''?"&serno=$serno":'', $verbose?"Terse":"Verbose");
?></td>
<td align=center><a href="index.php">Back to Start</a></td>
</tr>
</table>
<?php
pg_foot();
?>
| PHP |
<?php
// (C) Copyright 2001
// Murray Jensen <Murray.Jensen@csiro.au>
// CSIRO Manufacturing Science and Technology, Preston Lab
// mysql database access info
$mysql_user="fred";
$mysql_pw="apassword";
$mysql_db="mydbname";
// where to put the eeprom config files
$bddb_cfgdir = '/tftpboot/bddb';
// what this database is called
$bddb_label = 'Hymod Board Database';
?>
| PHP |
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?>
<?php
// (C) Copyright 2001
// Murray Jensen <Murray.Jensen@csiro.au>
// CSIRO Manufacturing Science and Technology, Preston Lab
require("defs.php");
pg_head("$bddb_label");
?>
<font size="+4">
<form action=execute.php method=POST>
<table width="100%" cellspacing=10 cellpadding=10>
<tr>
<td align=center>
<input type=submit name=submit value="New"></input>
</td>
<td align=center>
<input type=submit name=submit value="Edit"></input>
</td>
<td align=center>
<input type=submit name=submit value="Browse"></input>
</td>
<td align=center>
<input type=submit name=submit value="Log"></input>
</td>
</tr>
<tr>
<td align=center colspan=4>
<b>Serial Number:</b>
<input type=text name=serno size=10 maxsize=10 value=""></input>
</td>
</tr>
</table>
</form>
</font>
<?php
pg_foot();
?>
| PHP |
<?php
/**
* index.php PHPCMS 入口
*
* @copyright (C) 2005-2010 PHPCMS
* @license http://www.phpcms.cn/license/
* @lastmodify 2010-6-1
*/
define('PHPCMS_PATH', dirname(__FILE__).'/');
include PHPCMS_PATH.'/phpcms/base.php';
pc_base::creat_app();
?> | PHP |
<?php
/**
* base.php PHPCMS框架入口文件
*
* @copyright (C) 2005-2010 PHPCMS
* @license http://www.phpcms.cn/license/
* @lastmodify 2010-6-7
*/
define('IN_PHPCMS', true);
//PHPCMS框架路径
define('PC_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR);
if(!defined('PHPCMS_PATH')) define('PHPCMS_PATH', PC_PATH.'..'.DIRECTORY_SEPARATOR);
//缓存文件夹地址
define('CACHE_PATH', PC_PATH.'..'.DIRECTORY_SEPARATOR.'caches'.DIRECTORY_SEPARATOR);
//主机协议
define('SITE_PROTOCOL', isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://');
//当前访问的主机名
define('SITE_URL', (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''));
//来源
define('HTTP_REFERER', isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '');
//系统开始时间
define('SYS_START_TIME', microtime());
//加载公用函数库
pc_base::load_sys_func('global');
pc_base::load_config('system','errorlog') ? set_error_handler('my_error_handler') : error_reporting(E_ERROR | E_WARNING | E_PARSE);
//设置本地时差
function_exists('date_default_timezone_set') && date_default_timezone_set(pc_base::load_config('system','timezone'));
define('CHARSET' ,pc_base::load_config('system','charset'));
//输出页面字符集
header('Content-type: text/html; charset='.CHARSET);
define('SYS_TIME', time());
//定义网站根路径
define('WEB_PATH',pc_base::load_config('system','web_path'));
//js 路径
define('JS_PATH',pc_base::load_config('system','js_path'));
//css 路径
define('CSS_PATH',pc_base::load_config('system','css_path'));
//img 路径
define('IMG_PATH',pc_base::load_config('system','img_path'));
//动态程序路径
define('APP_PATH',pc_base::load_config('system','app_path'));
if(pc_base::load_config('system','gzip') && function_exists('ob_gzhandler')) {
ob_start('ob_gzhandler');
} else {
ob_start();
}
class pc_base {
/**
* 初始化应用程序
*/
public static function creat_app() {
return self::load_sys_class('application');
}
/**
* 加载系统类方法
* @param string $classname 类名
* @param string $path 扩展地址
* @param intger $initialize 是否初始化
*/
public static function load_sys_class($classname, $path = '', $initialize = 1) {
return self::_load_class($classname, $path, $initialize);
}
/**
* 加载应用类方法
* @param string $classname 类名
* @param string $m 模块
* @param intger $initialize 是否初始化
*/
public static function load_app_class($classname, $m = '', $initialize = 1) {
$m = empty($m) && defined('ROUTE_M') ? ROUTE_M : $m;
if (empty($m)) return false;
return self::_load_class($classname, 'modules'.DIRECTORY_SEPARATOR.$m.DIRECTORY_SEPARATOR.'classes', $initialize);
}
/**
* 加载数据模型
* @param string $classname 类名
*/
public static function load_model($classname) {
return self::_load_class($classname,'model');
}
/**
* 加载类文件函数
* @param string $classname 类名
* @param string $path 扩展地址
* @param intger $initialize 是否初始化
*/
private static function _load_class($classname, $path = '', $initialize = 1) {
static $classes = array();
if (empty($path)) $path = 'libs'.DIRECTORY_SEPARATOR.'classes';
$key = md5($path.$classname);
if (isset($classes[$key])) {
if (!empty($classes[$key])) {
return $classes[$key];
} else {
return true;
}
}
if (file_exists(PC_PATH.$path.DIRECTORY_SEPARATOR.$classname.'.class.php')) {
include PC_PATH.$path.DIRECTORY_SEPARATOR.$classname.'.class.php';
$name = $classname;
if ($my_path = self::my_path(PC_PATH.$path.DIRECTORY_SEPARATOR.$classname.'.class.php')) {
include $my_path;
$name = 'MY_'.$classname;
}
if ($initialize) {
$classes[$key] = new $name;
} else {
$classes[$key] = true;
}
return $classes[$key];
} else {
return false;
}
}
/**
* 加载系统的函数库
* @param string $func 函数库名
*/
public static function load_sys_func($func) {
return self::_load_func($func);
}
/**
* 加载应用函数库
* @param string $func 函数库名
* @param string $m 模型名
*/
public static function load_app_func($func, $m = '') {
$m = empty($m) && defined('ROUTE_M') ? ROUTE_M : $m;
if (empty($m)) return false;
return self::_load_func($func, 'modules'.DIRECTORY_SEPARATOR.$m.DIRECTORY_SEPARATOR.'functions');
}
/**
* 加载函数库
* @param string $func 函数名
* @param string $path 地址
*/
private static function _load_func($func, $path = '') {
static $funcs = array();
if (empty($path)) $path = 'libs'.DIRECTORY_SEPARATOR.'functions';
$path .= DIRECTORY_SEPARATOR.$func.'.func.php';
$key = md5($path);
if (isset($funcs[$key])) return true;
if (file_exists(PC_PATH.$path)) {
include PC_PATH.$path;
} else {
$funcs[$key] = false;
return false;
}
$funcs[$key] = true;
return true;
}
/**
* 是否有自己的扩展文件
* @param string $filepath 路径
*/
public static function my_path($filepath) {
$path = pathinfo($filepath);
if (file_exists($path['dirname'].DIRECTORY_SEPARATOR.'MY_'.$path['basename'])) {
return $path['dirname'].DIRECTORY_SEPARATOR.'MY_'.$path['basename'];
} else {
return false;
}
}
/**
* 加载配置文件
* @param string $file 配置文件
* @param string $key 要获取的配置荐
* @param string $default 默认配置。当获取配置项目失败时该值发生作用。
* @param boolean $reload 强制重新加载。
*/
public static function load_config($file, $key = '', $default = '', $reload = false) {
static $configs = array();
if (!$reload && isset($configs[$file])) {
if (empty($key)) {
return $configs[$file];
} elseif (isset($configs[$file][$key])) {
return $configs[$file][$key];
} else {
return $default;
}
}
$path = CACHE_PATH.'configs'.DIRECTORY_SEPARATOR.$file.'.php';
if (file_exists($path)) {
$configs[$file] = include $path;
}
if (empty($key)) {
return $configs[$file];
} elseif (isset($configs[$file][$key])) {
return $configs[$file][$key];
} else {
return $default;
}
}
} | PHP |
<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_sys_class('http', '', 0);
class messagequeue extends admin {
private $db;
/**
* 析构函数
*/
public function __construct() {
parent::__construct();
$this->db = pc_base::load_model('messagequeue_model');
}
/**
* 队列管理
*/
public function manage() {
$where = '';
$messagequeue = array();
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$messagequeuearr = $this->db->listinfo($where, 'id DESC', $page, 12);
foreach ($messagequeuearr as $k=>$v) {
$messagequeue[] = $v;
$messagequeue[$k]['appstatus'] = json_decode($v['appstatus'], 1);
}
$pages = $this->db->pages;
$applist = getcache('applist');
include $this->admin_tpl('messagequeue_list');
}
/**
* 删除队列信息
*/
public function delete() {
$idarr = isset($_POST['id']) ? $_POST['id'] : showmessage(L('illegal_parameters'), HTTP_REFERER);
$where = to_sqls($idarr, '', 'id');
if ($this->db->delete($where)) {
showmessage(L('operation_success'), HTTP_REFERER);
} else {
showmessage(L('operation_failure'), HTTP_REFERER);
}
}
/**
* 重新通知
*/
public function renotice() {
$noticeid = isset($_POST['noticeid']) ? $_POST['noticeid'] : showmessage(L('illegal_parameters'), HTTP_REFERER);
$appid = isset($_POST['appid']) ? $_POST['appid'] : showmessage(L('illegal_parameters'), HTTP_REFERER);
if ($noticeinfo = $this->db->get_one(array('id'=>$noticeid))) {
//通知app noticedata 返回通知成功的appid 1
//debug post appid.phpsso.php?data=noticeinfo[noticedata];
$applist = getcache('applist');
$url = $applist[$appid]['url'].$applist[$appid]['apifilename'];
$data = string2array($noticeinfo['noticedata']);
$data['action'] = $noticeinfo['operation'];
//转换中文编码
if (CHARSET != $applist[$appid]['charset'] && isset($data['action']) && $data['action'] == 'member_add') {
if(isset($data['username']) && !empty($data['username'])) {
if(CHARSET == 'utf-8') { //判断phpsso字符集是否为utf-8编码
//应用字符集如果是utf-8,并且用户名是utf-8编码,转换用户名为phpsso字符集,如果为英文,is_utf8返回false,不进行转换
if(!is_utf8($data['username'])) {
$data['username'] = iconv(CHARSET, $applist[$appid]['charset'], $data['username']);
}
} else {
if(!is_utf8($data['username'])) {
$data['username'] = iconv(CHARSET, $applist[$appid]['charset'], $data['username']);
}
}
}
}
$tmp_s = strstr($url, '?') ? '&' : '?';
$status = ps_send($url.$tmp_s.'appid='.$appid, $data, $applist[$appid]['authkey']);
//通信次数+1
$this->db->update(array('totalnum'=>'+=1', 'dateline'=>SYS_TIME), array('id'=>$noticeid));
if($status == 1) {
//重置消息队列app通信状态
$appstatusarr = json_decode($noticeinfo['appstatus'], 1);
$appstatusarr[$appid] = 1;
$appstatus = json_encode($appstatusarr);
//全部通知成功后更新消息队列状态
if (!strstr($appstatus, ':0')) {
$this->db->update(array('succeed'=>1), array('id'=>$noticeid));
}
//更新消息队列
$this->db->update(array('appstatus'=>$appstatus), array('id'=>$noticeid));
exit('1');
} else {
exit('0');
}
} else {
exit('0');
}
}
}
?> | PHP |
<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_app_class('messagequeue', 'admin' , 0);
pc_base::load_sys_class('format', '', 0);
pc_base::load_sys_class('form', '', 0);
class member extends admin {
private $db, $config;
/**
* 析构函数
*/
public function __construct() {
parent::__construct();
$this->db = pc_base::load_model('member_model');
$this->config = pc_base::load_config('system');
}
/**
* 管理会员
*/
public function manage() {
/*搜索用户*/
$keyword = isset($_GET['keyword']) ? $_GET['keyword'] : '';
$type = isset($_GET['type']) ? $_GET['type'] : '';
$start_time = isset($_GET['start_time']) ? $_GET['start_time'] : date('Y-m-d', SYS_TIME-date('t', SYS_TIME)*86400);
$end_time = isset($_GET['end_time']) ? $_GET['end_time'] : date('Y-m-d', SYS_TIME);
if (isset($_GET['search'])) {
//默认选取一个月内的用户,防止用户量过大给数据造成灾难
$where_start_time = strtotime($start_time);
$where_end_time = strtotime($end_time) + 86400;
//开始时间大于结束时间,置换变量
if($where_start_time > $where_end_time) {
$tmp = $where_start_time;
$where_start_time = $where_end_time;
$where_end_time = $tmp;
unset($tmp);
}
$where = "regdate BETWEEN '$where_start_time' AND '$where_end_time' AND ";
if ($type == '1') {
$where .= "username LIKE '%$keyword%'";
} elseif($type == '2') {
$where .= "uid = '$keyword'";
} elseif($type == '3') {
$where .= "email like '%$keyword%'";
} elseif($type == '4') {
$where .= "regip = '$keyword'";
} else {
$where .= "username like '%$keyword%'";
}
} else {
$where = '';
}
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$memberlist = $this->db->listinfo($where, 'uid DESC', $page, 12);
$pages = $this->db->pages;
include $this->admin_tpl('member_list');
}
/**
* 添加会员
*/
public function add() {
if (isset($_POST['dosubmit'])) {
$username = isset($_POST['username']) && trim($_POST['username']) ? trim($_POST['username']) : showmessage(L('nameerror'), HTTP_REFERER);
$password = isset($_POST['password']) && trim($_POST['password']) ? trim($_POST['password']) : showmessage(L('password_can_not_be_empty'), HTTP_REFERER);
$email = isset($_POST['email']) && is_email($_POST['email']) ? trim($_POST['email']) : showmessage(L('email_format_incorrect'), HTTP_REFERER);
$regdate = SYS_TIME;
if ($this->db->get_one(array('username'=>$username))) {
showmessage(L('user_already_exist'), HTTP_REFERER);
} elseif ($this->db->get_one(array('email'=>$email))) {
showmessage(L('email_already_exist'), HTTP_REFERER);
} else {
if (strlen($password) > 20 || strlen($password) < 6) {
showmessage(L('password_len_error'), HTTP_REFERER);
}
$old_password = $password;
list($password, $random) = creat_password($password);
//UCenter会员注册
$ucuserid = 0;
if ($this->config['ucuse']) {
pc_base::load_config('uc_config');
include PHPCMS_PATH.'api/uc_client/client.php';
$uid= uc_user_register($username, $old_password, $email, $random);
switch ($uid) {
case '-3':
case '-6':
case '-2':
case '-5':
case '-1':
case '-4':
showmessage(L('ucenter_error_code', array('code'=>$uid)), HTTP_REFERER);
break;
default :
$ucuserid = $uid;
break;
}
}
if ($uid = $this->db->insert(array('username'=>$username, 'password'=>$password, 'random'=>$random, 'email'=>$email, 'regdate'=>$regdate, 'lastdate'=>SYS_TIME, 'type'=>'app', 'regip'=>ip(), 'appname'=>'phpsso', 'ucuserid'=>$ucuserid), 1)) {
/*插入消息队列*/
$noticedata = array('uid'=>$uid, 'username'=>$username, 'password'=>$password, 'random'=>$random, 'email'=>$email, 'regip'=>ip());
messagequeue::add('member_add', $noticedata);
showmessage(L('member_add').L('operation_success'), 'm=admin&c=member&a=manage');
} else {
showmessage(L('database_error'), HTTP_REFERER);
}
}
} else {
include $this->admin_tpl('member_add');
}
}
/**
* 编辑会员
*/
public function edit() {
if (isset($_POST['dosubmit'])) {
$uid = isset($_POST['uid']) && trim($_POST['uid']) ? trim($_POST['uid']) : showmessage(L('nameerror'), HTTP_REFERER);
$password = isset($_POST['password']) && trim($_POST['password']) ? trim($_POST['password']) : '';
$email = isset($_POST['email']) && is_email(trim($_POST['email'])) ? trim($_POST['email']) : showmessage(L('email_format_incorrect'), HTTP_REFERER);
$updateinfo['random'] = '';
if (!empty($password)) {
if (strlen($password) > 20 || strlen($password) < 6) {
showmessage(L('password_len_error'), HTTP_REFERER);
} else {
$passwordarr = creat_password($password);
$updateinfo['password'] = $passwordarr[0];
$updateinfo['random'] = $passwordarr[1];
}
}
if ($this->db->get_one("`email` = '$email' AND `uid` != '$uid'")) {
showmessage(L('email_already_exist'), HTTP_REFERER);
}
$updateinfo['email'] = $email;
//是否删除头像
if(isset($_POST['avatar']) && $_POST['avatar']==1) {
$updateinfo['avatar'] = 0;
$dir = ps_getavatar($uid, 1);
ps_unlink($dir);
}
//ucenter部份
if ($this->config['ucuse']) {
pc_base::load_config('uc_config');
include PHPCMS_PATH.'api/uc_client/client.php';
$userinfo = $this->db->get_one(array('uid'=>$uid));
$r = uc_user_edit($userinfo['username'], '', (!empty($password) ? $password : ''), $updateinfo['email'], $updateinfo['random'], 1);
if ($r < 0) {
//{-1:用户不存在;-2:旧密码错误;-3:email已经存在 ;1:成功;0:未作修改}
showmessage(L('ucenter_error_code', array('code'=>$r)), HTTP_REFERER);
}
}
if (empty($updateinfo['random'])) {
unset($updateinfo['random']);
}
if ($this->db->update($updateinfo, array('uid'=>$uid))) {
/*插入消息队列*/
$noticedata = $updateinfo;
$noticedata['uid'] = $uid;
messagequeue::add('member_edit', $noticedata);
showmessage(L('operation_success'), HTTP_REFERER);
} else {
showmessage(L('operation_failure'), HTTP_REFERER);
}
} else {
$uid = isset($_GET['uid']) && trim($_GET['uid']) ? trim($_GET['uid']) : showmessage(L('user_not_exist'), HTTP_REFERER);
if (!$userinfo = $this->db->get_one(array('uid'=>$uid))) {
showmessage(L('user_not_exist'), HTTP_REFERER);
}
include $this->admin_tpl('member_edit');
}
}
/**
* 删除会员
*/
public function delete() {
$uidarr = isset($_POST['uid']) ? $_POST['uid'] : showmessage(L('illegal_parameters'), HTTP_REFERER);
foreach($uidarr as $v) {
//删除头像
$dir = ps_getavatar($v, 1);
ps_unlink($dir);
}
$where = to_sqls($uidarr, '', 'uid');
//ucenter部份
if ($this->config['ucuse']) {
pc_base::load_config('uc_config');
include PHPCMS_PATH.'api/uc_client/client.php';
$s = $this->db->select($where, 'ucuserid');
if ($s) {
$uc_data = array();
foreach ($s as $k=>$v) {
$uc_data[$k] = $v['ucuserid'];
}
if (!empty($uc_data)) $r = uc_user_delete($uc_data);
if (!$r) {
showmessage(L('operation_failure'), HTTP_REFERER);
}
} else {
showmessage(L('operation_failure'), HTTP_REFERER);
}
}
if ($this->db->delete($where)) {
/*插入消息队列*/
$noticedata = array('uids'=>$uidarr);
messagequeue::add('member_delete', $noticedata);
showmessage(L('operation_success'), HTTP_REFERER);
} else {
showmessage(L('operation_failure'), HTTP_REFERER);
}
}
public function ajax_username() {
$username = isset($_GET['username']) && trim($_GET['username']) ? trim($_GET['username']) : exit('0');
if(CHARSET != 'utf-8') {
$username = iconv('utf-8', CHARSET, $username);
$username = addslashes($username);
}
if ($this->db->get_one(array('username'=>$username))) {
exit('0');
} else {
//UCenter部分
if ($this->config['ucuse']) {
pc_base::load_config('uc_config');
include PHPCMS_PATH.'api/uc_client/client.php';
$rs= uc_user_checkname($username);
if ($rs < 1) {
exit('0');
}
}
exit('1');
}
}
public function ajax_email() {
$email = isset($_GET['email']) && trim($_GET['email']) ? trim($_GET['email']) : exit('0');
$uid = isset($_GET['uid']) && trim($_GET['uid']) ? trim($_GET['uid']) : '';
$where = !empty($uid) ? "`email` = '$email' AND `uid` != '$uid'" : array('email'=>$email);
if ($this->db->get_one($where)) {
exit('0');
} else {
//UCenter部分
if ($this->config['ucuse']) {
pc_base::load_config('uc_config');
include PHPCMS_PATH.'api/uc_client/client.php';
$rs= uc_user_checkemail($email);
if ($rs < 1) {
exit('0');
}
}
exit('1');
}
}
}
?> | PHP |
<?php defined('IN_ADMIN') or exit('No permission resources.');?>
<?php
$page_title = L('credit_manage');
include $this->admin_tpl('header');
?>
<div class="subnav">
<h2 class="title-1 line-x f14 fb blue lh28"><?php echo L('credit_add')?></h2>
<div class="content-menu ib-a blue line-x">
<a href="?m=admin&c=credit&a=manage">
<em><?php echo L('credit_manage')?></em></a>
<span>|</span>
<a href="?m=admin&c=credit&a=add" class="on">
<em><?php echo L('credit_add')?></em></a>
</div>
</div>
<div class="pad-lr-10">
<form method=post action="?m=admin&c=credit&a=add">
<table width="100%" class="table_form">
<tr>
<th width="80" ><?php echo L('change_position')?>:</th>
<td class="y-bg">
<select name="fromid" style="width:160px" onchange="showcredit('from', this.value)">
<option value='0' ><?php echo L('pleace_select')?></option>
<?php foreach($applist as $v) {?>
<option value='<?php echo $v['appid']?>' ><?php echo $v['name']?></option>
<?php }?>
</select>
<span id="from"></span>
>
<select name="toid" style="width:160px" onchange="showcredit('to', this.value)">
<option value='0' ><?php echo L('pleace_select')?></option>
<?php foreach($applist as $v) {?>
<option value='<?php echo $v['appid']?>' ><?php echo $v['name']?></option>
<?php }?>
</select>
<span id="to"></span>
</td>
</tr>
<tr>
<th><?php echo L('change_rate')?>:</th>
<td class="y-bg"><input type="text" class="input-text" name="fromrate" value="" /> :
<input type="text" class="input-text" name="torate" value="" /></td>
</tr>
</table>
<div class="bk15"></div>
<input type="submit" class="button" name="dosubmit" value="<?php echo L('submit')?>" />
</form>
</div>
<script language="JavaScript">
<!--
function showcredit(pos, val) {
$.post('?m=admin&c=credit&a=creditlist&appid='+val+'&'+Math.random(),function(data){
$("#"+pos+"").html("<select name="+pos+">"+data+"</select>");
});
}
//-->
</script>
</body>
</html> | PHP |
<?php defined('IN_ADMIN') or exit('No permission resources.');?>
<?php
$page_title = L('system_setting');
include $this->admin_tpl('header');
?>
<div class="subnav">
<h2 class="title-1 line-x f14 fb blue lh28"><?php echo L('system_setting')?></h2>
<div class="content-menu ib-a blue line-x"><a href="?m=admin&c=system&a=init"><em><?php echo L('register_setting')?></em></a><span>|</span> <a href="?m=admin&c=system&a=uc" class="on"><em><?php echo L('uc_setting')?></em></a><span>|</span><a href="?m=admin&c=system&a=sp4"><em><?php echo L('sp4_password_compatible')?></em></a></div>
</div>
<div class="pad-lr-10">
<form action="?m=admin&c=system&a=uc" method="post" name="form_messagequeue_manage">
<table width="100%" cellspacing="0" class="table_form">
<tbody>
<tr>
<td colspan="2">
<?php echo L('uc_notice')?></td>
</tr>
<tr>
<th width="140"><?php echo L('enable')?></th>
<td>
<input type="radio" name="ucuse" value="1" <?php if(isset($data['ucuse']) && $data['ucuse']==1){echo 'checked';}?>/> <?php echo L('yes')?> <input type="radio" name="ucuse" value="0" <?php if(!isset($data['ucuse']) || !$data['ucuse']){echo 'checked';}?> /> <?php echo L('no')?></td>
</tr>
<tr>
<th width="140"><?php echo L('uc_api_host')?></th>
<td>
<input type="text" class="input-text" name="data[uc_api]" id="uc_api" value="<?php if(isset($data['uc_api'])){echo $data['uc_api'];}?>" /><?php echo L('uc_host_notice')?></td>
</tr>
<tr>
<th width="140">Ucenter api IP:</th>
<td>
<input type="text" class="input-text" name="data[uc_ip]" id="uc_ip" value="<?php if(isset($data['uc_ip'])){echo $data['uc_ip'];}?>" /><?php echo L('uc_ip_notice')?></td>
</tr>
<tr>
<th><?php echo L('uc_db_host')?></th>
<td>
<input type="text" class="input-text" name="data[uc_dbhost]" id="uc_dbhost" value="<?php if(isset($data['uc_dbhost'])){echo $data['uc_dbhost'];}?>" /></td>
</tr>
<tr>
<th><?php echo L('uc_db_username')?></th>
<td>
<input type="text" class="input-text" name="data[uc_dbuser]" id="uc_dbuser" value="<?php if(isset($data['uc_dbuser'])){echo $data['uc_dbuser'];}?>" /></td>
</tr>
<tr>
<th><?php echo L('uc_db_password')?></th>
<td>
<input type="password" class="input-text" name="data[uc_dbpw]" id="uc_dbpw" value="<?php if(isset($data['uc_dbpw'])){echo $data['uc_dbpw'];}?>" /></td>
</tr>
<tr>
<th><?php echo L('uc_dbname')?></th>
<td>
<input type="text" class="input-text" name="data[uc_dbname]" id="uc_dbname" value="<?php if(isset($data['uc_dbname'])){echo $data['uc_dbname'];}?>" /></td>
</tr>
<tr>
<th><?php echo L('uc_db_pre')?></th>
<td>
<input type="text" class="input-text" name="data[uc_dbtablepre]" id="uc_dbtablepre" value="<?php if(isset($data['uc_dbtablepre'])){echo $data['uc_dbtablepre'];}?>" /> <input type="button" value="<?php echo L('uc_test_database')?>" class="button" onclick="mysql_test()" /></td>
</tr>
</tr>
<tr>
<th><?php echo L('uc_db_charset')?></th>
<td>
<select name="data[uc_dbcharset]" id="uc_dbcharset" />
<option value=""><?php echo L('please_select')?></option>
<option value="gbk" <?php if(isset($data['uc_dbcharset']) && $data['uc_dbcharset'] == 'gbk'){echo 'selected';}?>>GBK</option>
<option value="utf8" <?php if(isset($data['uc_dbcharset']) && $data['uc_dbcharset'] == 'utf8'){echo 'selected';}?>>UTF-8</option>
</select></td>
</tr>
</tr>
<tr>
<th><?php echo L('uc_appid')?></th>
<td>
<input type="text" class="input-text" name="data[uc_appid]" id="uc_appid" value="<?php if(isset($data['uc_appid'])){echo $data['uc_appid'];}?>" /></td>
</tr>
</tr>
<tr>
<th><?php echo L('uc_key')?></th>
<td>
<input type="text" class="input-text" name="data[uc_key]" id="uc_key" value="<?php if(isset($data['uc_key'])){echo $data['uc_key'];}?>" /></td>
</tr>
</tbody>
</table>
<div class="bk15"></div>
<input type="submit" class="button" name="dosubmit" value="<?php echo L('submit')?>" />
</form>
</div>
<script type="text/javascript">
<!--
function mysql_test() {
$.get('?m=admin&c=system&a=myqsl_test', {host:$('#uc_dbhost').val(),username:$('#uc_dbuser').val(), password:$('#uc_dbpw').val()}, function(data){if(data==1){alert('<?php echo L('connect_success')?>')}else{alert('<?php echo L('connect_failed')?>')}});
}
//-->
</script>
</body>
</html> | PHP |
<?php defined('IN_ADMIN') or exit('No permission resources.');?>
<?php
$page_title=L('application_manage');
include $this->admin_tpl('header');
?>
<div class="subnav">
<h2 class="title-1 line-x f14 fb blue lh28"><?php echo L('application_manage')?></h2>
<div class="content-menu ib-a blue line-x"><a href="?m=admin&c=applications&a=init" class="on"><em><?php echo L('application_list')?></em></a><span>|</span> <a href="?m=admin&c=applications&a=add"><em><?php echo L('application_add')?></em></a></div>
</div>
<div class="table-list pad-lr-10">
<table width="100%" cellspacing="0">
<thead>
<tr>
<th width="30">ID</th>
<th><?php echo L('application_name')?></th>
<th><?php echo L('type')?></th>
<th><?php echo L('charset')?></th>
<th><?php echo L('synlogin')?></th>
<th><?php echo L('apifilename')?></th>
<th><?php echo L('communications_status')?></th>
<th><?php echo L('operation')?></th>
</tr>
</thead>
</table>
<table width="100%" cellspacing="0" class="wrap">
<?php foreach ($list as $v):?>
<tr>
<td align="center"><?php echo $v['appid']?></td>
<td align="center"><?php echo $v['name']?></td>
<td align="center"><?php echo $v['type']?></td>
<td align="center"><?php echo $v['charset']?></td>
<td align="center"><?php echo $v['synlogin']?></td>
<td align="center"><?php echo $v['apifilename']?></td>
<td align="center"><span id="status_<?php echo $v['appid']?>"><?php echo L('testing_communication')?></span><script type="text/javascript">$(function(){check_status(<?php echo $v['appid']?>)})</script></td>
<td align="center"><a href="?m=admin&c=applications&a=edit&appid=<?php echo $v['appid']?>">[<?php echo L('edit')?>]</a> | <a href="?m=admin&c=applications&a=del&appid=<?php echo $v['appid']?>" onclick="return confirm('<?php echo L('sure_delete')?>')">[<?php echo L('delete')?>]</a></td>
</tr>
<?php endforeach;?>
</table>
<div id="pages"><?php echo $pages?></div>
</div>
</div>
<script type="text/javascript">
<!--
function check_status(id) {
$.get('?m=admin&c=applications&a=check_status&appid='+id+'&'+Math.random(),function(data){
if(data == 1) {
$('#status_'+id).html('<?php echo '<div class="onCorrect">'.L('communication_success').'</div>'?>');
} else {
$('#status_'+id).html('<?php echo '<div class="onError">'.L('communication_failure').'</div>'?>');
}
});
}
//-->
</script>
</body>
</html> | PHP |
<?php defined('IN_ADMIN') or exit('No permission resources.');?>
<?php
$page_title = L('modification_succeed');
include $this->admin_tpl('header');
?>
<script language="javascript" type="text/javascript" src="<?php echo JS_PATH?>formvalidator.js" charset="UTF-8"></script>
<script type="text/javascript">
<!--
$(function(){
$.formValidator.initConfig({autotip:true,formid:"myform"});
$("#password").formValidator({empty:true,onshow:"<?php echo L('not_change_the_password_please_leave_a_blank')?>",onfocus:"<?php echo L('password_len_error')?>"}).inputValidator({min:6,max:20,onerror:"<?php echo L('password_len_error')?>"});
})
//-->
</script>
<div class="subnav">
<h2 class="title-1 line-x f14 fb blue lh28"><?php echo L('admin_manage')?></h2>
<div class="content-menu ib-a blue line-x"><a href="?m=admin&c=administrator&a=init"><em><?php echo L('listadmins')?></em></a><span>|</span> <a href="?m=admin&c=administrator&a=add"><em><?php echo L('add_admin')?></em></a></div>
</div>
<div class="pad-lr-10">
<form action="?m=admin&c=administrator&a=edit&id=<?php echo $id?>" method="post" id="myform">
<table width="100%" class="table_form">
<tr>
<th width="80" ><?php echo L('username')?>:</th>
<td class="y-bg"><?php echo $data['username']?></td>
</tr>
<tr>
<th><?php echo L('password')?>:</th>
<td class="y-bg"><input type="password" class="input-text" name="password" value="" id="password" /></td>
</tr>
<tr>
<th><?php echo L('subminiature_tube')?>:</th>
<td class="y-bg"><input type="checkbox" name="issuper" value="1" <?php if ($data['issuper']) {echo 'checked';}?> /> <?php echo L('yes')?></td>
</tr>
</table>
<div class="bk15"></div>
<input type="submit" class="button" name="dosubmit" value="<?php echo L('submit')?>" />
</form>
</div>
</body>
</html> | PHP |
<?php defined('IN_ADMIN') or exit('No permission resources.');?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php echo L('phpsso')?></title>
<script language="javascript" type="text/javascript" src="<?php echo JS_PATH?>jquery.min.js"></script>
<style type="text/css">
*{margin:0;padding:0;border:0; vertical-align:middle}
body{background:#3a6ea5;}
img{ vertical-align:middle}
.login_box{width:580px;height:320px;position:absolute;top:50%;left:50%;margin-left:-290px;margin-top:-160px;}
.login_box_top{background:url(<?php echo IMG_PATH?>login_box_top.gif) no-repeat;width:580px;height:13px; overflow:hidden}
.login_box_mid{background:url(<?php echo IMG_PATH?>login_box_mid.gif) repeat-y;width:580px;height:289px;}
.login_box_bot{background:url(<?php echo IMG_PATH?>login_box_bot.gif) no-repeat;width:580px;height:13px;}
.login_logo{float:left;display:inline; background:url(<?php echo IMG_PATH?>login_logo.gif) no-repeat;width:97px;height:67px;margin:30px 20px 0px 60px;}
.logo_content{float:left;width:360px;overflow:hidden;margin-top:36px;}
.logo_content .tit{ margin:0 0 30px}
.logo_content p{color:#464646;}
.login_input{background:url(<?php echo IMG_PATH?>login_input.gif) no-repeat;height:19px;border:1px solid #ccc;padding:2px 0px 2px 4px;font-family: Arial, Helvetica, sans-serif}
.login_list li{margin-bottom:10px;display:inline;font-size:14px;width:360px;float:left; line-height:24px}
.login_list li label{display:inline-block;display:-moz-inline-stack;zoom:1;*display:inline; width:55px; font-family:"宋体"; font-size:14px; }
.login_button{ background:url(<?php echo IMG_PATH?>login_button.gif) no-repeat;width:60px;height:28px;border:none; text-align:center; cursor:pointer;font-size:14px;margin-left:55px;}
</style>
</head>
<body>
<div class="login_box">
<div class="login_box_top"></div>
<div class="login_box_mid">
<div class="login_logo"></div>
<div class="logo_content">
<div class="tit"><img src="<?php echo IMG_PATH?>guanli_center.gif" /></div>
<form action="?m=admin&c=login&a=logind" method="post">
<input type="hidden" name="forward" value="<?php echo urlencode($_GET['forward'])?>" />
<ul class="login_list">
<li><label><?php echo L('username')?></label><input type="text" class="login_input" name="username" id="username" size="24" /></li>
<li><label><?php echo L('password')?></label><input type="password" class="login_input" name="password" id="password" size="24"/></li>
<li><label><?php echo L('checkcode')?></label><input name="code" type="text" class="login_input" size="4" /><span> <?php echo form::checkcode('code_img', '4', '14', 84, 24)?></span></li>
<li><input type="submit" class="login_button" value="<?php echo L('loging')?>"/></li>
</ul>
</form>
</div>
<script type="text/javascript">
$(function(){
$('#username').focus();
})
</script>
</div>
<div class="login_box_bot"></div>
</div>
</body>
</html> | PHP |
<?php defined('IN_ADMIN') or exit('No permission resources.');?>
<?php
$page_title = L('index');$show_scroll = 1;
include $this->admin_tpl('header');
?>
<div class="pad-lr-10">
<h2 class="title-1 line-x f14 fb blue lh28"><?php echo L('phpsso')?></h2>
<table width="100%" class="table_form">
<tr>
<th width="100"><?php echo L('version_info')?>:</th>
<td>v1.0</td>
</tr>
<tr>
<th><?php echo L('application_info')?>:</th>
<td><?php echo $appnum?></td>
</tr>
<tr>
<th><?php echo L('member_info')?>:</th>
<td>
<?php echo L('total')?><?php echo $total_member?>
<?php echo L('member_today')?><?php echo $today_member?></td>
</tr>
<tr>
<th><?php echo L('queue_info')?>:</th>
<td><?php echo $total_messagequeue?></td>
</tr>
</table>
<div class="bk15"></div>
<h2 class="title-1 line-x f14 fb blue lh28"><?php echo L('system_info')?></h2>
<table width="100%" class="table_form">
<tr>
<th width="100"><?php echo L('server_info')?>:</th>
<td><?php echo PHP_OS.' '.$_SERVER['SERVER_SOFTWARE'];?></td>
</tr>
<tr>
<th><?php echo L('host_info')?>:</th>
<td><?php echo $_SERVER['SERVER_NAME'].'('.$_SERVER['SERVER_ADDR'].':'.$_SERVER['SERVER_PORT'].')'?> </td>
</tr>
<tr>
<th><?php echo L('php_info')?>:</th>
<td>get_magic_quotes_gpc():<?php echo get_magic_quotes_gpc() ? 'On' : 'Off';?></td>
</tr>
<tr>
<th><?php echo L('mysql_info')?>:</th>
<td><?php echo L('mysql_version')?>:<?php echo $mysql_version?>、
<?php echo L('table_size')?>:<?php echo $mysql_table_size?>、
<?php echo L('index_size')?>:<?php echo $mysql_table_index_size?>
</td>
</tr>
</table>
<div class="bk15"></div>
<h2 class="title-1 line-x f14 fb blue lh28"><?php echo L('service_info')?></h2>
<table width="100%" class="table_form">
<tr>
<th width="100"><?php echo L('development_team')?>:</th>
<td><?php echo L('phpcms_chenzhouyu')?>、<?php echo L('phpcms_wangtiecheng')?></td>
</tr>
<tr>
<th><?php echo L('design_team')?>:</th>
<td><?php echo L('phpcms_dongfeilong')?></td>
</tr>
</table>
</div>
</body>
</html>
| PHP |
<?php defined('IN_ADMIN') or exit('No permission resources.');?>
<?php
$page_title = L('clean_cache');
include $this->admin_tpl('header');
?>
<div class="subnav">
<h2 class="title-1 line-x f14 fb blue lh28"><?php echo L('clean_cache')?></h2>
<div class="content-menu ib-a blue line-x">
<em>
<?php echo L('cache_size')?>:<span id='filesize'><?php echo sizecount($applistinfo['filesize'])?></span> |
<?php echo L('last_modify_time')?>:<span id='filemtime'><?php echo date('Y-m-d H:i:s', $applistinfo['filemtime'])?></span>
</em>
<a href="javascript:clearcache('applist');" class="on">
<em><?php echo L('clean_applist_cache')?></em></a>
</div>
</div>
<div class="table-list pad-lr-10">
</div>
<script language="JavaScript">
<!--
function clearcache(type) {
$.getJSON("?m=admin&c=cache&a=ajax_clear&radom="+Math.random(), {type:type},
function(data){
if (data) {
$('#filesize').html('<font color=red>'+data.filesize+'</font>');
$('#filemtime').html('<font color=red>'+data.filemtime+'</font>');
}
parent.showloading();
});
}
//-->
</script>
</body>
</html>
| PHP |
<?php defined('IN_ADMIN') or exit('No permission resources.'); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET?>" />
<meta http-equiv="X-UA-Compatible" content="IE=7" />
<title><?php echo L('alert_message')?></title>
<style type="text/css">
<!--
*{ padding:0; margin:0; font-size:12px}
a:link,a:visited{text-decoration:none;color:#0068a6}
a:hover,a:active{color:#ff6600;text-decoration: underline}
.showMsg{border: 1px solid #1e64c8; zoom:1; width:450px; height:172px;position:absolute;top:44%;left:50%;margin:-87px 0 0 -225px}
.showMsg h5{background-image: url(<?php echo IMG_PATH?>msg_img/msg.png);background-repeat: no-repeat; color:#fff; padding-left:35px; height:25px; line-height:26px;*line-height:28px; overflow:hidden; font-size:14px; text-align:left}
.showMsg .content{ padding:10px 12px 10px 45px; font-size:14px; height:100px; line-height:96px}
.showMsg .bottom{ background:#e4ecf7; margin: 0 1px 1px 1px;line-height:26px; *line-height:30px; height:26px; text-align:center}
.showMsg .ok,.showMsg .guery{background: url(<?php echo IMG_PATH?>msg_img/msg_bg.png) no-repeat 0px -560px;}
.showMsg .guery{background-position: left -460px;}
-->
</style>
<script type="text/javaScript" src="<?php echo JS_PATH?>jquery.min.js"></script>
<script language="JavaScript" src="<?php echo JS_PATH?>admin_common.js"></script>
</head>
<body>
<div class="showMsg" style="text-align:center">
<h5><?php echo L('alert_message')?></h5>
<div class="content guery" style="display:inline-block;display:-moz-inline-stack;zoom:1;*display:inline;">
<?php echo $msg?>
</div>
<div class="bottom">
<?php if($url_forward=='goback' || $url_forward=='') {?>
<a href="javascript:history.back();" ><?php echo L('go_history')?></a>
<?php } elseif($url_forward=="close") {?>
<input type="button" name="close" value=" 关闭 " onClick="window.close();">
<?php } elseif($url_forward=="blank") {?>
<?php } elseif($url_forward) { ?>
<a href="<?php echo url($url_forward, 1)?>"><?php echo L('jump_message')?></a>
<script language="javascript">setTimeout("redirect('<?php echo url($url_forward, 1)?>');",<?php echo $ms?>);</script>
<?php }?>
<?php if ($dialog):?><script style="text/javascript">window.top.right.location.reload();window.top.art.dialog({id:"<?php echo $dialog?>"}).close();</script><?php endif;?>
</div>
</div>
</body>
</html> | PHP |
<?php defined('IN_ADMIN') or exit('No permission resources.');?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET?>" />
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<title><?php echo L('phpsso')?></title>
<link href="<?php echo CSS_PATH?>reset.css" rel="stylesheet" type="text/css" />
<link href="<?php echo CSS_PATH?>system.css" rel="stylesheet" type="text/css" />
<style>
#loading{position:absolute;left:600px;display:none}
</style>
<script language="javascript" type="text/javascript" src="<?php echo JS_PATH?>jquery.min.js"></script>
</head>
<body scroll="no">
<div id="loading"><div class="msg lf"><p class="attention"><?php echo L('loading');?><span id="loadsecond"></span>...</p></div></div>
<div class="header">
<div class="logo lf"><span class="invisible"><?php echo L('phpsso')?></span></div>
<div class="lf">
<div class="log white cut_line"><?php echo L('hellow')?> <?php echo $userinfo['username']?> <?php if($userinfo['issuper']) echo '['.L('subminiature_tube').']'?><span>|</span><a href="?m=admin&c=password&a=init" target="right_iframe">[<?php echo L('account_setting')?>]</a><span>|</span><a href="?m=admin&c=login&a=logout">[<?php echo L('logout')?>]</a></div>
</div>
</div>
<div id="content" class="content-on">
<div class="col-left left_menu">
<div>
<a href="/"><h3 class="f14"><?php echo L('manage_center')?></h3></a>
<ul>
<li class="menuli" onclick="menu_show(this);"><a hidefocus="true" style="outline:none" href="?m=admin&c=member&a=manage" target="right_iframe"><?php echo L('member_manage')?></a></li>
<li class="menuli" onclick="menu_show(this);"><a hidefocus="true" style="outline:none" href="?m=admin&c=applications&a=init" target="right_iframe"><?php echo L('application_manage')?></a></li>
<li class="menuli" onclick="menu_show(this);"><a hidefocus="true" style="outline:none" href="?m=admin&c=messagequeue&a=manage" target="right_iframe"><?php echo L('communicate_info')?></a></li>
<li class="menuli" onclick="menu_show(this);"><a hidefocus="true" style="outline:none" href="?m=admin&c=credit&a=manage" target="right_iframe"><?php echo L('credit_change')?></a></li>
<li class="menuli" onclick="menu_show(this);"><a hidefocus="true" style="outline:none" href="?m=admin&c=password&a=init" target="right_iframe"><?php echo L('account_setting')?></a></li>
</ul>
<?php if($this->get_userinfo('issuper')):?>
<div class="line-x"></div>
<ul>
<li class="menuli" onclick="menu_show(this);"><a hidefocus="true" style="outline:none" href="?m=admin&c=administrator&a=init" target="right_iframe"><?php echo L('admin_manage')?></a></li>
<li class="menuli" onclick="menu_show(this);"><a hidefocus="true" style="outline:none" href="?m=admin&c=system&a=init" target="right_iframe"><?php echo L('system_setting')?></a></li>
<li class="menuli" onclick="menu_show(this);"><a hidefocus="true" style="outline:none" href="?m=admin&c=cache&a=init" target="right_iframe"><?php echo L('clean_cache')?></a></li>
</ul>
<?php endif;?>
</div>
<a hidefocus="true" style="outline:none" href="javascript:;" id="openClose" class="open" title="<?php echo L('spread_or_closed')?>"><span class="hidden"><?php echo L('expand')?></span></a>
</div>
<div class="col-auto mr8">
<div class="crumbs"><?php echo L('local')?><span id="local"></span></div>
<div class="col-1">
<div class="content">
<iframe name="right_iframe" id="right_iframe" src="?m=admin&c=index&a=right" frameborder="false" scrolling="auto" style="overflow-x:hidden;border:none" width="100%" height="auto" allowtransparency="true" onload="showloading()"></iframe>
</div>
</div>
</div>
</div>
<script type="text/javascript">
//clientHeight-0; 空白值 iframe自适应高度
function windowW(){
if($(window).width()<940){
$('.header').css('width',940+'px');
$('#content').css('width',940+'px');
$('body').attr('scroll','');
$('body').css('overflow','');
}
}
windowW();
$(window).resize(function(){
if($(window).width()<940){
windowW();
}else{
$('.header').css('width','auto');
$('#content').css('width','auto');
$('body').attr('scroll','no');
$('body').css('overflow','hidden');
}
});
window.onresize = function(){
var heights = document.documentElement.clientHeight-120;document.getElementById('right_iframe').height = heights;
var openClose = $("#right_iframe").height()+39;
$("#openClose").height(openClose);$("#content").height(openClose);
}
window.onresize();
//左侧开关
$("#openClose").toggle(
function () {
$(".left_menu").addClass("left_menu_on");
$(this).addClass("close");
$("#content").addClass("content-off")
},
function () {
$(".left_menu").removeClass("left_menu_on");
$(this).removeClass("close");
$("#content").removeClass("content-off")
}
);
function menu_show(obj) {
$('.menuli').removeClass('on fb blue');
$(obj).addClass('on fb blue');
}
function span_local(name) {
$('#local').html(name);
}
if(top.location != self.location) {
top.location=self.location;
}
var read;
function showloading(type) {
if(type) {
$('#loadsecond').html('');
$('#loading').show();
//second = 1;
//read = setInterval(readsecond, 1000);
} else {
$('#loading').fadeOut("slow");
//if(read) clearInterval(read);
}
}
function readsecond() {
$('#loadsecond').html('('+second+')');
second++;
}
</script>
</body>
</html> | PHP |
<?php defined('IN_ADMIN') or exit('No permission resources.');?>
<?php
$page_title = L('member_manage');
include $this->admin_tpl('header');
?>
<div class="subnav">
<h2 class="title-1 line-x f14 fb blue lh28"><?php echo L('member_manage')?></h2>
<div class="content-menu ib-a blue line-x">
<div class="rt">
<form action="index.php" method="get" name="form_member_search">
<?php echo L('regtime')?>:
<?php echo form::date('start_time', $start_time)?>
<?php echo form::date('end_time', $end_time)?>
<select name="type">
<option value='1' <?php if(isset($_GET['type']) && $_GET['type']==1){?>selected<?php }?>><?php echo L('username')?></option>
<option value='2' <?php if(isset($_GET['type']) && $_GET['type']==2){?>selected<?php }?>><?php echo L('uid')?></option>
<option value='3' <?php if(isset($_GET['type']) && $_GET['type']==3){?>selected<?php }?>><?php echo L('email')?></option>
<option value='4' <?php if(isset($_GET['type']) && $_GET['type']==4){?>selected<?php }?>><?php echo L('regip')?></option>
</select>
<input name="keyword" type="text" value="<?php if(isset($_GET['keyword'])) {echo $_GET['keyword'];}?>" class="input-text" />
<input type="submit" name="search" class="button" value="<?php echo L('search')?>" />
<input type="hidden" name="m" value="admin" />
<input type="hidden" name="c" value="member" />
<input type="hidden" name="a" value="manage" />
</form>
</div>
<a href="?m=admin&c=member&a=manage" class="on">
<em><?php echo L('member_manage')?></em></a>
<span>|</span>
<a href="?m=admin&c=member&a=add">
<em><?php echo L('member_add')?></em></a>
</div>
</div>
<div class="pad-lr-10">
<form action="?m=admin&c=member&a=delete" method="post" name="form_member_manage">
<div class="table-list">
<table width="100%" cellspacing="0">
<thead>
<tr>
<th align="left" width="40"><input type="checkbox" value="" id="check_box" onclick="selectall('uid[]');"></th>
<th align="left" width="60"><?php echo L('uid')?></th>
<th align="left"><?php echo L('username')?></th>
<th align="left"><?php echo L('email')?></th>
<th align="left"><?php echo L('application')?></th>
<th align="left"><?php echo L('type')?></th>
<th align="left"><?php echo L('regip')?></th>
<th align="left"><?php echo L('regtime')?></th>
<th align="left"><?php echo L('lastlogintime')?></th>
<th align="left"><?php echo L('operation')?></th>
</tr>
</thead>
<tbody>
<?php
foreach($memberlist as $k=>$v) {
?>
<tr>
<td align="left" width="40"><input type="checkbox" value="<?php echo $v['uid']?>" name="uid[]"></td>
<td align="left" width="60"><?php echo $v['uid']?></td>
<td align="left"><?php if($v['avatar']) {?><img src="<?php echo ps_getavatar($v['uid']);?>" height=18 width=18><?php }?><?php echo $v['username']?></td>
<td align="left"><?php echo $v['email']?></td>
<td align="left"><?php echo $v['appname']?></td>
<td align="left"><?php echo $v['type']?></td>
<td align="left"><?php echo $v['regip']?></td>
<td align="left"><?php echo format::date($v['regdate'], 1);?></td>
<td align="left"><?php echo format::date($v['lastdate'], 1);?></td>
<td align="left"><a href="?m=admin&c=member&a=edit&uid=<?php echo $v['uid']?>">[<?php echo L('edit')?>]</a></td>
</tr>
<?php
}
?> </tbody>
</table>
<div class="btn">
<label for="check_box"><?php echo L('select_all')?>/<?php echo L('cancel')?></label>
<input type="submit" class="button" value="<?php echo L('delete')?>" onclick="return confirm('<?php echo L('sure_delete')?>')"/>
</div>
<div id="pages">
<?php echo $pages?>
</div>
</form>
</div>
</body>
</html>
| PHP |
<?php defined('IN_ADMIN') or exit('No permission resources.');?>
<?php
$page_title = L('application_add');
include $this->admin_tpl('header');
?>
<script language="javascript" type="text/javascript" src="<?php echo JS_PATH?>formvalidator.js" charset="UTF-8"></script>
<script language="javascript" type="text/javascript" src="<?php echo JS_PATH?>formValidatorRegex.js" charset="UTF-8"></script>
<script type="text/javascript">
<!--
$(function(){
$.formValidator.initConfig({autotip:true,formid:"myform"});
$("#name").formValidator({onshow:"<?php echo L('input').L('application_name')?>",onfocus:"<?php echo L('input').L('application_name')?>"}).inputValidator({min:1,max:20,onerror:"<?php echo L('input').L('application_name')?>"}).ajaxValidator({type : "get",url : "",data :"m=admin&c=applications&a=ajax_name",datatype : "html",async:'false',success : function(data){ if( data == "1" ){return true;}else{return false;}},buttons: $("#dosubmit"),onerror : "<?php echo L('application_name').L('exist')?>",onwait : "<?php echo L('connecting_please_wait')?>"});
$("#url").formValidator({onshow:'<?php echo L('application_url_msg')?>',onfocus:'<?php echo L('application_url_msg')?>',tipcss:{width:"400px"}}).inputValidator({min:1,max:255,onerror:'<?php echo L('application_url_msg')?>'}).regexValidator({regexp:"http:\/\/(.+)\/$",onerror:'<?php echo L('application_url_msg')?>'}).ajaxValidator({type : "get",url : "",data :"m=admin&c=applications&a=ajax_url",datatype : "html",async:'false',success : function(data){ if( data == "1" ){return true;}else{return false;}},buttons: $("#dosubmit"),onerror : "<?php echo L('application_url').L('exist')?>",onwait : "<?php echo L('connecting_please_wait')?>"});
$("#authkey").formValidator({onshow:'<?php echo L('input').L('authkey')?>',onfocus:'<?php echo L('input').L('authkey')?>'}).inputValidator({min:1,max:255,onerror:'<?php echo L('input').L('authkey')?>'});
})
//-->
</script>
<div class="subnav">
<h2 class="title-1 line-x f14 fb blue lh28"><?php echo L('application_manage')?></h2>
<div class="content-menu ib-a blue line-x"><a href="?m=admin&c=applications&a=init"><em><?php echo L('application_list')?></em></a><span>|</span> <a href="?m=admin&c=applications&a=add" class="on"><em><?php echo L('application_add')?></em></a></div>
</div>
<div class="pad-lr-10">
<form action="?m=admin&c=applications&a=add" method="post" id="myform">
<table width="100%" class="table_form">
<tr>
<th width="80"><?php echo L('application_name')?>:</th>
<td class="y-bg"><input type="text" class="input-text" name="name" id="name" /></td>
</tr><tr>
<th><?php echo L('application_url')?>:</th>
<td class="y-bg"><input type="text" class="input-text" name="url" id="url" /></td>
</tr>
<tr>
<th><?php echo L('authkey')?>:</th>
<td class="y-bg"><input type="text" class="input-text" name="authkey" id="authkey" /> <input type="button" class="button" name="dosubmit" value="<?php echo L('automatic_generation')?>" onclick="creat_authkey()" /> </td>
</tr>
<tr>
<th><?php echo L('type')?>:</th>
<td class="y-bg"><select name="type" onchange="change_apifile(this.value)">
<option value="phpcms_v9">phpcms_v9</option>
<option value="phpcms_2008_sp4">phpcms_2008_sp4</option>
<option value="other"><?php echo L('other')?></option>
</select></td>
</tr>
<tr>
<th><?php echo L('application_ip')?>:</th>
<td class="y-bg"><input type="text" class="input-text" name="ip" /> <?php echo L('application_ip_msg')?></td>
</tr>
<tr>
<th><?php echo L('application_apifilename')?>:</th>
<td class="y-bg"><input type="text" class="input-text" name="apifilename" id="apifilename" value="phpsso.php" /></td>
</tr>
<tr>
<th><?php echo L('application_charset')?>:</th>
<td class="y-bg"><select name="charset">
<option value="gbk">GBK</option>
<option value="utf-8">utf-8</option>
</select></td>
</tr>
<tr>
<th><?php echo L('application_synlogin')?>:</th>
<td class="y-bg"><input type="checkbox" name="synlogin" value="1" /> <?php echo L('yes')?></td>
</tr>
</table>
<div class="bk15"></div>
<input type="submit" class="button" name="dosubmit" id="dosubmit"value="<?php echo L('submit')?>" />
</form>
</div>
<script type="text/javascript">
function creat_authkey() {
var x="0123456789qwertyuioplkjhgfdsazxcvbnm";
var tmp="";
for(var i=0;i< 32;i++) {
tmp += x.charAt(Math.ceil(Math.random()*100000000)%x.length);
}
$('#authkey').val(tmp);
}
function change_apifile(value) {
if (value=='phpcms' && $('#apifilename').val() == '') {
$('#apifilename').val('?m=api&c=phpsso');
}
}
</script>
</body>
</html> | PHP |
<?php defined('IN_ADMIN') or exit('No permission resources.');?>
<?php
$page_title = L('system_setting');
include $this->admin_tpl('header');
?>
<div class="subnav">
<h2 class="title-1 line-x f14 fb blue lh28"><?php echo L('system_setting')?></h2>
<div class="content-menu ib-a blue line-x"><a href="?m=admin&c=system&a=init" class="on"><em><?php echo L('register_setting')?></em></a><span>|</span> <a href="?m=admin&c=system&a=uc"><em><?php echo L('uc_setting')?></em></a><span>|</span><a href="?m=admin&c=system&a=sp4"><em><?php echo L('sp4_password_compatible')?></em></a></div>
</div>
<div class="pad-lr-10">
<form action="?m=admin&c=system&a=init" method="post" name="form_messagequeue_manage">
<table width="100%" cellspacing="0" class="table_form">
<tbody>
<tr>
<th width="120"><?php echo L('denyed_username')?></th>
<td>
<textarea name="denyusername" style="height:160px; width:30%"><?php foreach($setting['denyusername'] as $v) {?><?php echo $v."\r\n";?><?php }?></textarea><?php echo L('denyed_username_setting')?></td>
</tr>
<tr>
<th><?php echo L('denyed_email')?></th>
<td>
<textarea name="denyemail" style="height:160px; width:30%"><?php foreach($setting['denyemail'] as $v) {?><?php echo $v."\r\n";?><?php }?></textarea><?php echo L('denyed_email_setting')?></td>
</tr>
</tbody>
</table>
<div class="bk15"></div>
<input type="submit" class="button" name="dosubmit" value="<?php echo L('submit')?>" />
</form>
</div>
</body>
</html> | PHP |
<?php defined('IN_ADMIN') or exit('No permission resources.');?>
<?php
$page_title = L('credit_change');
include $this->admin_tpl('header');
?>
<div class="subnav">
<h2 class="title-1 line-x f14 fb blue lh28"><?php echo L('credit_manage')?></h2>
<div class="content-menu ib-a blue line-x">
<a href="?m=admin&c=credit&a=manage" class="on">
<em><?php echo L('credit_manage')?></em></a>
<span>|</span>
<a href="?m=admin&c=credit&a=add">
<em><?php echo L('credit_add')?></em></a>
</div>
</div>
<form action="?m=admin&c=credit&a=delete" method="post" name="form_member_manage">
<div class="table-list pad-lr-10">
<table width="100%" cellspacing="0">
<thead>
<tr>
<th width="40"><input type="checkbox" value="" id="check_box" onclick="selectall('id[]');"></th>
<th align="left"><?php echo L('id')?></th>
<th align="left"><?php echo L('change_pos')?></th>
<th align="left"><?php echo L('change_rate')?></th>
<th align="left"></th>
</tr>
</thead>
<tbody>
<?php
foreach($creditlist as $k=>$v) {
?>
<tr>
<td align="center"><input type="checkbox" value="<?php echo $k?>" name="id[]"></td>
<td align="left"><?php echo $k?></td>
<td align="left"><?php echo $applist[$v['fromid']]['name']?>[<?php echo $v['fromname']?>]-><?php echo $applist[$v['toid']]['name']?>[<?php echo $v['toname']?>]</td>
<td align="left"><?php echo $v['fromrate']?>:<?php echo $v['torate']?></td>
<td align="left"></td>
</tr>
<?php
}
?> </tbody>
</table>
<div class="btn">
<label for="check_box"><?php echo L('select_all')?>/<?php echo L('cancel')?></label>
<input type="submit" class="button" value="<?php echo L('delete')?>" onclick="return confirm('<?php echo L('sure_delete')?>')"/>
</div>
<div id="pages">
</div>
</div>
</form>
</body>
</html>
| PHP |
<?php defined('IN_ADMIN') or exit('No permission resources.');?>
<?php
$page_title=L('admin_manage');
include $this->admin_tpl('header');
?>
<div class="subnav">
<h2 class="title-1 line-x f14 fb blue lh28"><?php echo L('admin_manage')?></h2>
<div class="content-menu ib-a blue line-x"><a href="?m=admin&c=administrator&a=init" class="on"><em><?php echo L('listadmins')?></em></a><span>|</span> <a href="?m=admin&c=administrator&a=add"><em><?php echo L('add_admin')?></em></a></div>
</div>
<div class="pad-lr-10">
<div class="table-list">
<table width="100%" cellspacing="0">
<thead>
<tr>
<th align="center"><?php echo L('id')?></th>
<th align="left"><?php echo L('username')?></th>
<th align="left"><?php echo L('type')?></th>
<th align="left"><?php echo L('lastlogintime')?></th>
<th align="left"><?php echo L('landing_ip')?></th>
<th align="left"><?php echo L('operation')?></th>
</tr>
</thead>
<tbody>
<?php foreach ($list as $v):?>
<tr>
<td align="center"><?php echo $v['id']?></td>
<td align="left"><?php echo $v['username']?></td>
<td align="left"><?php if ($v['issuper']) {echo L('subminiature_tube');} else {echo L('administrator');}?></td>
<td align="left"><?php echo $v['lastlogin']?></td>
<td align="left"><?php echo $v['ip']?></td>
<td align="left"><a href="?m=admin&c=administrator&a=edit&id=<?php echo $v['id']?>">[<?php echo L('edit')?>]</a> | <a href="?m=admin&c=administrator&a=del&id=<?php echo $v['id']?>" onclick="return confirm('<?php echo L('sure_delete')?>')">[<?php echo L('delete')?>]</a></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
<div id="pages"><?php echo $pages?></div>
</div>
</div>
</body>
</html> | PHP |
<?php defined('IN_ADMIN') or exit('No permission resources.');?>
<?php
$page_title = L('member_edit');
include $this->admin_tpl('header');
?>
<script language="javascript" type="text/javascript" src="<?php echo JS_PATH?>formvalidator.js" charset="UTF-8"></script>
<script language="javascript" type="text/javascript" src="<?php echo JS_PATH?>formValidatorRegex.js" charset="UTF-8"></script>
<script type="text/javascript">
<!--
$(function(){
$.formValidator.initConfig({autotip:true,formid:"myform"});
$("#password").formValidator({empty:true,onshow:"<?php echo L('not_change_the_password_please_leave_a_blank')?>",onfocus:"<?php echo L('password_len_error')?>"}).inputValidator({min:6,max:20,onerror:"<?php echo L('password_len_error')?>"});
$("#email").formValidator({onshow:"<?php echo L('input')?>email",onfocus:"<?php echo L('notice_format')?>",oncorrect:"<?php echo L('right')?>"}).regexValidator({regexp:"email",datatype:"enum",onerror:"email<?php echo L('format_incorrect')?>"}).ajaxValidator({
type : "get",
url : "",
data :"m=admin&c=member&a=ajax_email&uid=<?php echo $userinfo['uid']?>",
datatype : "html",
async:'true',
success : function(data){
if( data == "1" ) {
return true;
} else {
return false;
}
},
buttons: $("#dosubmit"),
onerror : "<?php echo L('email_already_exist')?>",
onwait : "<?php echo L('connecting_please_wait')?>"
}).defaultPassed();
})
//-->
</script>
<div class="subnav">
<h2 class="title-1 line-x f14 fb blue lh28"><?php echo L('member_edit')?></h2>
<div class="content-menu ib-a blue line-x">
<a href="?m=admin&c=member&a=manage">
<em><?php echo L('member_manage')?></em></a>
<span>|</span>
<a href="?m=admin&c=member&a=edit&uid=<?php echo $userinfo['uid']?>" class="on">
<em><?php echo L('member_edit')?></em></a>
</div>
</div>
<div class="pad-lr-10">
<form method=post action="?m=admin&c=member&a=edit" id="myform">
<table width="100%" class="table_form">
<input type="hidden" name="uid" value="<?php echo $userinfo['uid']?>">
<?php if($userinfo['avatar']) {?>
<tr>
<th><?php echo L('avatar')?>:</th>
<td class="y-bg">
<img src="<?php echo ps_getavatar($userinfo['uid']);?>">
<input type="checkbox" name="avatar" id="avatar" class="input-text" value="1" ><label for="avatar"><?php echo L('delete').L('avatar')?></label>
</td>
</tr>
<?php }?>
<tr>
<th width="80" ><?php echo L('username')?>:</th>
<td class="y-bg"><?php echo $userinfo['username']?></td>
</tr>
<tr>
<th><?php echo L('password')?>:</th>
<td class="y-bg"><input type="password" class="input-text" name="password" id="password" value="" /></td>
</tr>
<tr>
<th><?php echo L('email')?>:</th>
<td class="y-bg"><input type="text" name="email" id="email" class="input-text" value="<?php echo $userinfo['email']?>" ></td>
</tr>
</table>
<div class="bk15"></div>
<input type="submit" class="button" name="dosubmit" value="<?php echo L('submit')?>" />
</form>
</div>
</body>
</html>
| PHP |
<?php defined('IN_ADMIN') or exit('No permission resources.');?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="IE=7" http-equiv="X-UA-Compatible">
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET?>" />
<title><?php echo L('phpsso')?></title>
<link href="<?php echo CSS_PATH?>reset.css" rel="stylesheet" type="text/css" />
<link href="<?php echo CSS_PATH?>system.css" rel="stylesheet" type="text/css" />
<link href="<?php echo CSS_PATH?>table_form.css" rel="stylesheet" type="text/css" />
<link href="<?php echo CSS_PATH?>dialog.css" rel="stylesheet" type="text/css" />
<script language="javascript" type="text/javascript" src="<?php echo JS_PATH?>jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$(".table-list .wrap").wrap("<div style='overflow-y:auto;overflow-x:hidden;' class='scrolltable'></div>");
window.onresize = function(){
var wrapTr = $(".table-list .wrap tr").length*$(".table-list .wrap tr:eq(0)").height();
var scrolltable = $(window).height()-$(".subnav").height()-160;
if(wrapTr > scrolltable){
$(".scrolltable").height(scrolltable);
}
}
window.onresize();
$(".table-list tr th").each(function(i){
i=i+1;
var tabTh = $(".table-list tr th:eq("+i+")").width();
$(".table-list .wrap tr:eq(0) td:eq("+i+")").width(tabTh)
});
<?php if($page_title && empty($_GET['forward'])) {echo 'parent.span_local("'.$page_title.'");';}?>
})
/**
* 全选checkbox,注意:标识checkbox id固定为为check_box
* @param string name 列表check名称,如 uid[]
*/
function selectall(name) {
if ($("#check_box").attr("checked")==false) {
$("input[name='"+name+"']").each(function() {
this.checked=false;
});
} else {
$("input[name='"+name+"']").each(function() {
this.checked=true;
});
}
}
/**
* 屏蔽js错误
*/
function killerrors() {
return true;
}
window.onerror = killerrors;
</script>
<style type="text/css">
html{_overflow-y:scroll}
</style>
</head>
<body<?php if(empty($_GET['forward'])) {echo " onbeforeunload=\"parent.showloading(1)\"";}?>> | PHP |
<?php defined('IN_ADMIN') or exit('No permission resources.');?>
<?php
$page_title = L('communicate_info');
include $this->admin_tpl('header');
?>
<div class="subnav">
<h2 class="title-1 line-x f14 fb blue lh28"><?php echo L('communicate_info')?></h2>
</div>
<form action="?m=admin&c=messagequeue&a=delete" method="post" name="form_messagequeue_manage">
<div class="table-list pad-lr-10">
<table width="100%" cellspacing="0">
<thead>
<tr>
<th width="40"><input type="checkbox" value="" id="check_box" onclick="selectall('id[]');"></th>
<th><?php echo L('operation')?></th>
<th><?php echo L('notice_data')?></th>
<th><?php echo L('notice_num')?></th>
<th><?php echo L('notice_dateline')?></th>
<?php
foreach($applist as $k=>$v) {
?>
<th><?php echo $v['name']?></th>
<?php
}
?>
</tr>
</thead>
<tbody>
<?php
foreach($messagequeue as $k=>$v) {
?>
<tr>
<td align="center" width="40"><input type="checkbox" value="<?php echo $v['id']?>" name="id[]"></td>
<td align="center"><?php echo L($v['operation'])?></td>
<td align="center" title="<?php echo $v['noticedata']?>"><?php echo L('view')?></td>
<td align="center"><span id="totalnum"><?php echo $v['totalnum']?></span></td>
<td align="center"><?php echo date('Y-m-d H:i:s', $v['dateline']);?></td>
<?php
foreach($applist as $app_k=>$app_v) {
?>
<td align="center" id='status_<?php echo $v['id'].'_'.$app_k;?>'>
<!--<script type="text/javascript">$(function(){notice(<?php echo $v['id']?>, <?php echo $app_k?>)})</script>-->
<?php echo isset($v['appstatus'][$app_k]) && $v['appstatus'][$app_k]==1 ? '<div class="onCorrect">'.L('notice_success').'</div>' : '<a href="javascript:renotice('.$v['id'].', '.$app_k.');" class="onError">'.L('notice_fail').'</a>'?>
</td>
<?php
}
?>
</tr>
<?php
}
?> </tbody>
</table>
<div class="btn">
<label for="check_box"><?php echo L('select_all')?>/<?php echo L('cancel')?></label>
<input type="button" class="button" value="<?php echo L('delete')?>" onclick="this.form.submit();"/>
</div>
<div id="pages">
<?php echo $pages?>
</div>
</div>
</form>
<script language="JavaScript">
<!--
function renotice(noticeid, appid) {
$.post('?m=admin&c=messagequeue&a=renotice'+'&'+Math.random(), {noticeid:noticeid, appid:appid},
function(data){
$('#totalnum').html(parseInt($('#totalnum').html())+1);
if (data==1) {
$('#status_'+noticeid+'_'+appid).html('<?php echo '<div class="onCorrect">'.L('notice_success').'</div>'?>');
}
parent.showloading();
});
}
function notice(noticeid, appid) {
$.post('?m=admin&c=messagequeue&a=notice¬iceid='+noticeid+'&appid='+appid+'&'+Math.random(),function(data){
if(data == 1) {
$('#status_'+noticeid+'_'+appid).html('<?php echo '<div class="onCorrect">'.L('notice_success').'</div>'?>');
}
});
}
//-->
</script>
</body>
</html> | PHP |
<?php defined('IN_ADMIN') or exit('No permission resources.');?>
<?php
$page_title = L('application_edit');
include $this->admin_tpl('header');
?>
<script language="javascript" type="text/javascript" src="<?php echo JS_PATH?>formvalidator.js" charset="UTF-8"></script>
<script language="javascript" type="text/javascript" src="<?php echo JS_PATH?>formValidatorRegex.js" charset="UTF-8"></script>
<script type="text/javascript">
<!--
$(function(){
$.formValidator.initConfig({autotip:true,formid:"myform"});
$("#name").formValidator({onshow:"<?php echo L('input').L('application_name')?>",onfocus:"<?php echo L('input').L('application_name')?>"}).inputValidator({min:1,max:20,onerror:"<?php echo L('input').L('application_name')?>"}).ajaxValidator({type : "get",url : "",data :"m=admin&c=applications&a=ajax_name&id=<?php echo $appid?>",datatype : "html",async:'false',success : function(data){ if( data == "1" ){return true;}else{return false;}},buttons: $("#dosubmit"),onerror : "<?php echo L('application_name').L('exist')?>",onwait : "<?php echo L('connecting_please_wait')?>"}).defaultPassed();
$("#url").formValidator({onshow:'<?php echo L('application_url_msg')?>',onfocus:'<?php echo L('application_url_msg')?>',tipcss:{width:'400px'}}).inputValidator({min:1,max:255,onerror:'<?php echo L('application_url_msg')?>'}).inputValidator({min:1,max:255,onerror:'<?php echo L('application_url_msg')?>'}).regexValidator({regexp:"http:\/\/(.+)\/$",onerror:'<?php echo L('application_url_msg')?>'}).ajaxValidator({type : "get",url : "",data :"m=admin&c=applications&a=ajax_url&id=<?php echo $appid?>",datatype : "html",async:'false',success : function(data){ if( data == "1" ){return true;}else{return false;}},buttons: $("#dosubmit"),onerror : "<?php echo L('application_url').L('exist')?>",onwait : "<?php echo L('connecting_please_wait')?>"}).defaultPassed();
$("#authkey").formValidator({onshow:'<?php echo L('input').L('authkey')?>',onfocus:'<?php echo L('input').L('authkey')?>'}).inputValidator({min:1,max:255,onerror:'<?php echo L('input').L('authkey')?>'});
})
//-->
</script>
<div class="subnav">
<h2 class="title-1 line-x f14 fb blue lh28"><?php echo L('application_manage')?></h2>
<div class="content-menu ib-a blue line-x"><a href="?m=admin&c=applications&a=init"><em><?php echo L('application_list')?></em></a><span>|</span> <a href="?m=admin&c=applications&a=add"><em><?php echo L('application_add')?></em></a></div>
</div>
<div class="pad-lr-10">
<form action="?m=admin&c=applications&a=edit&appid=<?php echo $appid?>" method="post" id="myform">
<table width="100%" class="table_form">
<tr>
<th width="80"><?php echo L('application_name')?>:</th>
<td class="y-bg"><input type="text" class="input-text" name="name" value="<?php echo $data['name']?>" id="name" /></td>
</tr><tr>
<th><?php echo L('application_url')?>:</th>
<td class="y-bg"><input type="text" class="input-text" name="url" value="<?php echo $data['url']?>" id="url" /> </td>
</tr>
<tr>
<th><?php echo L('authkey')?>:</th>
<td class="y-bg"><input type="text" class="input-text" name="authkey" id="authkey" value="<?php echo $data['authkey']?>" /> <input type="button" class="button" name="dosubmit" value="<?php echo L('automatic_generation')?>" onclick="creat_authkey()" /></td>
</tr>
<tr>
<th><?php echo L('type')?>:</th>
<td class="y-bg"><select name="type" onchange="change_apifile(this.value)">
<option value="phpcms_v9"<?php if ($data['type']=='phpcms_v9'){echo ' selected';}?>>phpcms_v9</option>
<option value="phpcms_2008_sp4"<?php if ($data['type']=='phpcms_2008_sp4'){echo ' selected';}?>>phpcms_2008_sp4</option>
<option value="other"<?php if ($data['type']=='other'){echo ' selected';}?>><?php echo L('other')?></option>
</select></td>
</tr>
<tr>
<th><?php echo L('application_ip')?>:</th>
<td class="y-bg"><input type="text" class="input-text" name="ip" value="<?php echo $data['ip']?>" /> <?php echo L('application_ip_msg')?></td>
</tr>
<tr>
<th><?php echo L('application_apifilename')?>:</th>
<td class="y-bg"><input type="text" class="input-text" name="apifilename" id="apifilename" value="<?php echo $data['apifilename']?>" /></td>
</tr>
<tr>
<th><?php echo L('application_charset')?>:</th>
<td class="y-bg"><select name="charset">
<option value="gbk"<?php if ($data['charset']=='gbk'){echo ' selected';}?>>GBK</option>
<option value="utf-8"<?php if ($data['charset']=='utf-8'){echo ' selected';}?>>utf-8</option>
</select></td>
</tr>
<tr>
<th><?php echo L('application_synlogin')?>:</th>
<td class="y-bg"><input type="checkbox" name="synlogin" value="1"<?php if ($data['synlogin']){echo ' checked';}?> /> <?php echo L('yes')?></td>
</tr>
</table>
<div class="bk15"></div>
<input type="submit" class="button" name="dosubmit" value="<?php echo L('submit')?>" />
</form>
</div>
<script type="text/javascript">
function creat_authkey() {
var x="0123456789qwertyuioplkjhgfdsazxcvbnm";
var tmp="";
for(var i=0;i< 32;i++) {
tmp += x.charAt(Math.ceil(Math.random()*100000000)%x.length);
}
$('#authkey').val(tmp);
}
function change_apifile(value) {
if (value=='phpcms' && $('#apifilename').val() == '') {
$('#apifilename').val('?m=api&c=phpsso');
}
}
</script>
</body>
</html> | PHP |
<?php defined('IN_ADMIN') or exit('No permission resources.');?>
<?php
$page_title = L('member_add');
include $this->admin_tpl('header');
?>
<script language="javascript" type="text/javascript" src="<?php echo JS_PATH?>formvalidator.js" charset="UTF-8"></script>
<script language="javascript" type="text/javascript" src="<?php echo JS_PATH?>formValidatorRegex.js" charset="UTF-8"></script>
<script type="text/javascript">
<!--
$(function(){
$.formValidator.initConfig({autotip:true,formid:"myform",onerror:function(msg){}});
$("#username").formValidator({onshow:"<?php echo L('input').L('username')?>",onfocus:"<?php echo L('between_6_to_20')?>"}).inputValidator({min:4,max:20,onerror:"<?php echo L('between_6_to_20')?>"}).regexValidator({regexp:"ps_username",datatype:"enum",onerror:"<?php echo L('username').L('format_incorrect')?>"}).ajaxValidator({
type : "get",
url : "",
data :"m=admin&c=member&a=ajax_username",
datatype : "html",
async:'false',
success : function(data){
if( data == "1" ) {
return true;
}
else {
return false;
}
},
buttons: $("#dosubmit"),
onerror : "<?php echo L('user_already_exist')?>",
onwait : "<?php echo L('connecting_please_wait')?>"
});
$("#password").formValidator({onshow:"<?php echo L('inputpassword')?>",onfocus:"<?php echo L('between_6_to_20')?>"}).inputValidator({min:6,max:20,onerror:"<?php echo L('between_6_to_20')?>"});
$("#email").formValidator({onshow:"<?php echo L('input')?>email",onfocus:"email<?php echo L('format_incorrect')?>",oncorrect:"<?php echo L('right')?>"}).regexValidator({regexp:"email",datatype:"enum",onerror:"email<?php echo L('format_incorrect')?>"}).ajaxValidator({
type : "get",
url : "",
data :"m=admin&c=member&a=ajax_email",
datatype : "html",
async:'false',
success : function(data){
if( data == "1" ) {
return true;
}
else {
return false;
}
},
buttons: $("#dosubmit"),
onerror : "<?php echo L('email_already_exist')?>",
onwait : "<?php echo L('connecting_please_wait')?>"
});
})
//-->
</script>
<div class="subnav">
<h2 class="title-1 line-x f14 fb blue lh28"><?php echo L('member_add')?></h2>
<div class="content-menu ib-a blue line-x">
<a href="?m=admin&c=member&a=manage">
<em><?php echo L('member_manage')?></em></a>
<span>|</span>
<a href="?m=admin&c=member&a=add" class="on">
<em><?php echo L('member_add')?></em></a>
</div>
</div>
<div class="pad-lr-10">
<form method=post action="?m=admin&c=member&a=add" id='myform'>
<table width="100%" class="table_form">
<tr>
<th width="80" ><?php echo L('username')?>:</th>
<td class="y-bg"><input type="text" name="username" id="username" class="input-text"></td>
</tr>
<tr>
<th><?php echo L('password')?>:</th>
<td class="y-bg"><input type="password" class="input-text" name="password" id="password" value="" /></td>
</tr>
<tr>
<th><?php echo L('email')?>:</th>
<td class="y-bg"><input type="text" name="email" id="email" class="input-text" ></td>
</tr>
</table>
<div class="bk15"></div>
<input type="submit" class="button" name="dosubmit" value="<?php echo L('submit')?>" />
</form>
</div>
</body>
</html>
| PHP |
<?php defined('IN_ADMIN') or exit('No permission resources.');?>
<?php
$page_title=L('change_password');
include $this->admin_tpl('header');
?>
<script language="javascript" type="text/javascript" src="<?php echo JS_PATH?>formvalidator.js" charset="UTF-8"></script>
<script language="javascript" type="text/javascript" src="<?php echo JS_PATH?>formValidatorRegex.js" charset="UTF-8"></script>
<script type="text/javascript">
<!--
$(function(){
$.formValidator.initConfig({autotip:true,formid:"myform"});
$("#password").formValidator({onshow:"<?php echo L('inputpassword')?>",onfocus:"<?php echo L('password_len_error')?>"}).inputValidator({min:6,max:20,onerror:"<?php echo L('password_len_error')?>"});
$("#newpassword").formValidator({onshow:"<?php echo L('inputpassword')?>",onfocus:"<?php echo L('password_len_error')?>"}).inputValidator({min:6,max:20,onerror:"<?php echo L('password_len_error')?>"});
$("#newpassword2").formValidator({onshow:"<?php echo L('means_code')?>",onfocus:"<?php echo L('the_two_passwords_are_not_the_same_admin_zh')?>",oncorrect:"<?php echo L('right')?>"}).inputValidator({min:6,max:20,onerror:"<?php echo L('password_len_error')?>"}).compareValidator({desid:"newpassword",operateor:"=",onerror:"<?php echo L('the_two_passwords_are_not_the_same_admin_zh')?>"});
})
//-->
</script>
<div class="subnav">
<h2 class="title-1 line-x f14 fb blue lh28"><?php echo L('change_password')?></h2>
</div>
<div class="pad-lr-10">
<form action="?m=admin&c=password&a=init" method="post">
<table width="100%" class="table_form">
<tr>
<th width="100"><?php echo L('current_password')?>:</th>
<td><input type="password" class="input-text" name="password" id="password" value="" /></td>
</tr>
<tr>
<th width="100" align="right"><?php echo L('new_password')?>:</th>
<td><input type="password" class="input-text" name="newpassword" id="newpassword" value="" /></td>
</tr>
<tr>
<th width="100" align="right"><?php echo L('bootos_x')?>:</th>
<td><input type="password" class="input-text" name="newpassword2" id="newpassword2" value="" /></td>
</tr>
</table>
<div class="bk15"></div>
<input type="submit" class="button" name="dosubmit" value="<?php echo L('submit')?>" />
</form>
</div>
</body>
</html> | PHP |
<?php defined('IN_ADMIN') or exit('No permission resources.');?>
<?php
$page_title = L('add_admin');
include $this->admin_tpl('header');
?>
<script language="javascript" type="text/javascript" src="<?php echo JS_PATH?>formvalidator.js" charset="UTF-8"></script>
<script type="text/javascript">
<!--
$(function(){
$.formValidator.initConfig({autotip:true,formid:"myform"});
$("#username").formValidator({onshow:"<?php echo L('input').L('username')?>",onfocus:"<?php echo L('username').L('between_6_to_20')?>"}).inputValidator({min:6,max:20,onerror:"<?php echo L('username').L('between_6_to_20')?>"}).ajaxValidator({
type : "get",
url : "",
data :"m=admin&c=administrator&a=ajax_username",
datatype : "html",
async:'false',
success : function(data){
if( data == "1" )
{
return true;
}
else
{
return false;
}
},
buttons: $("#dosubmit"),
onerror : "<?php echo L('user_already_exist')?>",
onwait : "<?php echo L('connecting_please_wait')?>"
});
$("#password").formValidator({onshow:"<?php echo L('inputpassword')?>",onfocus:"<?php echo L('password_len_error')?>"}).inputValidator({min:6,max:20,onerror:"<?php echo L('password_len_error')?>"});
})
//-->
</script>
<div class="subnav">
<h2 class="title-1 line-x f14 fb blue lh28"><?php echo L('admin_manage')?></h2>
<div class="content-menu ib-a blue line-x"><a href="?m=admin&c=administrator&a=init"><em><?php echo L('listadmins')?></em></a><span>|</span> <a href="?m=admin&c=administrator&a=add" class="on"><em><?php echo L('add_admin')?></em></a></div>
</div>
<div class="pad-lr-10">
<form action="?m=admin&c=administrator&a=add" method="post" id="myform">
<table width="100%" class="table_form">
<tr>
<th width="80"><?php echo L('username')?>:</th>
<td class="y-bg"><input type="text" class="input-text" name="username" id="username" /></td>
</tr><tr>
<th><?php echo L('password')?>:</th>
<td class="y-bg"><input type="password" class="input-text" name="password" id="password" /></td>
</tr>
<tr>
<th><?php echo L('subminiature_tube')?>:</th>
<td class="y-bg"><input type="checkbox" name="issuper" value="1" /> <?php echo L('yes')?></td>
</tr>
</table>
<div class="bk15"></div>
<input type="submit" class="button" id="dosubmit" name="dosubmit" value="<?php echo L('submit')?>" />
</form>
</div>
</body>
</html> | PHP |
<?php defined('IN_ADMIN') or exit('No permission resources.');?>
<?php
$page_title = L('system_setting');
include $this->admin_tpl('header');
?>
<div class="subnav">
<h2 class="title-1 line-x f14 fb blue lh28"><?php echo L('system_setting')?></h2>
<div class="content-menu ib-a blue line-x"><a href="?m=admin&c=system&a=init"><em><?php echo L('register_setting')?></em></a><span>|</span> <a href="?m=admin&c=system&a=uc"><em><?php echo L('uc_setting')?></em></a><span>|</span><a href="?m=admin&c=system&a=sp4" class="on"><em><?php echo L('sp4_password_compatible')?></em></a></div>
</div>
<div class="pad-lr-10">
<form action="?m=admin&c=system&a=sp4" method="post" name="form_messagequeue_manage">
<table width="100%" cellspacing="0" class="table_form">
<tbody>
<tr>
<td colspan="2">
<?php echo L('sp4_password_compatible')?></td>
</tr>
<tr>
<th width="140"><?php echo L('enable')?></th>
<td>
<input type="radio" name="sp4use" value="1" <?php if(isset($data['sp4use']) && $data['sp4use']==1){echo 'checked';}?>/> <?php echo L('yes')?> <input type="radio" name="sp4use" value="0" <?php if(!isset($data['sp4use']) || !$data['sp4use']){echo 'checked';}?> /> <?php echo L('no')?></td>
</tr>
<tr>
<th width="140">PASSWORD_KEY</th>
<td>
<input type="text" class="input-text" name="sp4_password_key" id="sp4_password_key" value="<?php if(isset($data['sp4_password_key'])){echo $data['sp4_password_key'];}?>" /><?php echo L('sp4_password_key')?></td>
</tr>
</tbody>
</table>
<div class="bk15"></div>
<input type="submit" class="button" name="dosubmit" value="<?php echo L('submit')?>" />
</form>
</div>
</body>
</html> | PHP |
<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin','admin',0);
class password extends admin {
private $db;
public function __construct() {
$this->db = pc_base::load_model('admin_model');
parent::__construct();
}
public function init() {
if (isset($_POST['dosubmit'])) {
$password = isset($_POST['password']) && trim($_POST['password']) ? trim($_POST['password']) : showmessage(L('the_password_cannot_be_empty'), HTTP_REFERER);
$newpassword = isset($_POST['newpassword']) && trim($_POST['newpassword']) ? trim($_POST['newpassword']) : showmessage(L('new_password_cannot_be_empty'), HTTP_REFERER);
$newpassword2 = isset($_POST['newpassword2']) && trim($_POST['newpassword2']) ? trim($_POST['newpassword2']) : '';
if (strlen($newpassword) > 20 || strlen($newpassword) < 6) {
showmessage(L('password_len_error'), HTTP_REFERER);
} elseif ($newpassword != $newpassword2) {
showmessage(L('the_two_passwords_are_not_the_same_admin_zh'), HTTP_REFERER);
}
$info = $this->get_userinfo();
if (md5(md5($password).$info['encrypt']) != $info['password']) {
showmessage(L('old_password_incorrect'), HTTP_REFERER);
}
list($password, $encrypt) = creat_password($newpassword);
if ($this->db->update(array('password'=>$password, 'encrypt'=>$encrypt), array('id'=>$this->get_userid()))) {
showmessage(L('operation_success'), HTTP_REFERER);
} else {
showmessage(L('operation_failure'), HTTP_REFERER);
}
}
include $this->admin_tpl('password');
}
} | PHP |
<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin','admin',0);
class applications extends admin {
private $db;
public function __construct() {
$this->db = pc_base::load_model('applications_model');
parent::__construct();
}
public function init() {
$page = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']) : 1;
$pagesize = 20;
$offset = ($page - 1) * $pagesize;
$total = $this->db->count();
$pages = pages($total, $page, $pagesize);
$list = $this->db->select('', '*', $offset.','.$pagesize);
include $this->admin_tpl('applications_list');
}
public function add() {
header("Cache-control: private");
if (isset($_POST['dosubmit'])) {
$name = isset($_POST['name']) && trim($_POST['name']) ? trim($_POST['name']) : showmessage(L('application_name').L('can_not_be_empty'));
$url = isset($_POST['url']) && trim($_POST['url']) ? trim($_POST['url']) : showmessage(L('application_url').L('can_not_be_empty'));
$authkey = isset($_POST['authkey']) && trim($_POST['authkey']) ? trim($_POST['authkey']) : showmessage(L('authkey').L('can_not_be_empty'));
$type = isset($_POST['type']) && trim($_POST['type']) ? trim($_POST['type']) : showmessage(L('type').L('can_not_be_empty'));
$ip = isset($_POST['ip']) && trim($_POST['ip']) ? trim($_POST['ip']) : '';
$apifilename = isset($_POST['apifilename']) && trim($_POST['apifilename']) ? trim($_POST['apifilename']) : showmessage(L('application_apifilename').L('can_not_be_empty'));
$charset = isset($_POST['charset']) && trim($_POST['charset']) ? trim($_POST['charset']) : showmessage(L('application_charset').L('can_not_be_empty'));
$synlogin = isset($_POST['synlogin']) && intval($_POST['synlogin']) ? intval($_POST['synlogin']) : 0;
if ($this->db->get_one(array('name'=>$name))) {
showmessage(L('application_name').L('exist'));
}
if ($this->db->get_one(array('url'=>$url))) {
showmessage(L('application_url').L('exist'));
}
if ($this->db->insert(array('name'=>$name,'url'=>$url, 'authkey'=>$authkey, 'type'=>$type, 'ip'=>$ip, 'apifilename'=>$apifilename, 'charset'=>$charset, 'synlogin'=>$synlogin))) {
/*写入应用列表缓存*/
$applist = $this->db->listinfo('', '', 1, 100, 'appid');
setcache('applist', $applist);
showmessage(L('operation_success'), '?m=admin&c=applications&a=init');
} else {
showmessage(L('operation_failure'));
}
}
include $this->admin_tpl('applications_add');
}
public function del() {
$appid = isset($_GET['appid']) && intval($_GET['appid']) ? intval($_GET['appid']) : showmessage(L('illegal_parameters'), HTTP_REFERER);
if ($r = $this->db->get_one(array('appid'=>$appid))) {
if ($this->db->delete(array('appid'=>$appid))) {
/*写入应用列表缓存*/
$applist = $this->db->listinfo('', '', 1, 100, 'appid');
setcache('applist', $applist);
showmessage(L('operation_success'), HTTP_REFERER);
} else {
showmessage(L('operation_failure'), HTTP_REFERER);
}
} else {
showmessage(L('application_not_exist'), HTTP_REFERER);
}
}
public function edit() {
header("Cache-control: private");
$appid = isset($_GET['appid']) && intval($_GET['appid']) ? intval($_GET['appid']) : showmessage(L('illegal_parameters'), HTTP_REFERER);
if ($data = $this->db->get_one(array('appid'=>$appid))) {
if (isset($_POST['dosubmit'])) {
$name = isset($_POST['name']) && trim($_POST['name']) ? trim($_POST['name']) : showmessage(L('application_name').L('can_not_be_empty'));
$url = isset($_POST['url']) && trim($_POST['url']) ? trim($_POST['url']) : showmessage(L('application_url').L('can_not_be_empty'));
$authkey = isset($_POST['authkey']) && trim($_POST['authkey']) ? trim($_POST['authkey']) : showmessage(L('authkey').L('can_not_be_empty'));
$type = isset($_POST['type']) && trim($_POST['type']) ? trim($_POST['type']) : showmessage(L('type').L('can_not_be_empty'));
$ip = isset($_POST['ip']) && trim($_POST['ip']) ? trim($_POST['ip']) : '';
$apifilename = isset($_POST['apifilename']) && trim($_POST['apifilename']) ? trim($_POST['apifilename']) : showmessage(L('application_apifilename').L('can_not_be_empty'));
$charset = isset($_POST['charset']) && trim($_POST['charset']) ? trim($_POST['charset']) : showmessage(L('application_charset').L('can_not_be_empty'));
$synlogin = isset($_POST['synlogin']) && intval($_POST['synlogin']) ? intval($_POST['synlogin']) : 0;
if ($data['name'] != $name && $this->db->get_one(array('name'=>$name))) {
showmessage(L('application_name').L('exist'));
}
if ($data['url'] != $url && $this->db->get_one(array('url'=>$url))) {
showmessage(L('application_url').L('exist'));
}
if ($this->db->update(array('name'=>$name,'url'=>$url, 'authkey'=>$authkey, 'type'=>$type, 'ip'=>$ip, 'apifilename'=>$apifilename, 'charset'=>$charset, 'synlogin'=>$synlogin), array('appid'=>$appid))) {
/*写入应用列表缓存*/
$applist = $this->db->listinfo('', '', 1, 100, 'appid');
setcache('applist', $applist);
showmessage(L('operation_success'), '?m=admin&c=applications&a=init');
} else {
showmessage(L('operation_failure'));
}
}
include $this->admin_tpl('applications_edit');
} else {
showmessage(L('application_not_exist'));
}
}
public function ajax_name() {
$name = isset($_GET['name']) && trim($_GET['name']) ? (pc_base::load_config('system','charset')=='gbk' ? iconv('utf-8', 'gbk', trim($_GET['name'])) : trim($_GET['name'])) : exit('0');
$id = isset($_GET['id']) && intval($_GET['id']) ? intval($_GET['id']) : '';
if ($id) {
$r = $this->db->get_one(array('appid'=>$id), 'name');
if ($r['name'] == $name) {
exit('1');
}
}
if ($this->db->get_one(array("name"=>$name), 'appid')) {
echo 0;
} else {
echo 1;
}
}
public function ajax_url() {
$url = isset($_GET['url']) && trim($_GET['url']) ? trim($_GET['url']) : exit('0');
$id = isset($_GET['id']) && intval($_GET['id']) ? intval($_GET['id']) : '';
if ($id) {
$r = $this->db->get_one(array('appid'=>$id), 'url');
if ($r['url'] == $url) {
exit('1');
}
}
if ($this->db->get_one(array("url"=>$url), 'appid')) {
exit('0');
} else {
exit('1');
}
}
public function check_status() {
$appid = isset($_GET['appid']) && intval($_GET['appid']) ? intval($_GET['appid']) : exit('0');
$applist = getcache('applist');
if(empty($applist)) {
/*写入应用列表缓存*/
$applist = $this->db->listinfo('', '', 1, 100, 'appid');
setcache('applist', $applist);
}
if (!empty($applist)) {
$param = sys_auth('action=check_status', 'ENCODE', $applist[$appid]['authkey']);
//如果填写ip则通信地址为ip地址,此时绑定了多个虚拟主机有可能出现错误
$appurl = !empty($applist[$appid]['ip']) ? 'http://'.$applist[$appid]['ip'].'/api/' : $applist[$appid]['url'];
$url = $appurl.$applist[$appid]['apifilename'];
if (strpos($url, '?')) {
$url .= '&';
} else {
$url .= "?";
}
if ($data = @file_get_contents($url.'code='.urlencode($param))) {
exit($data);
} else {
exit('0');
}
} else {
exit('0');
}
}
} | PHP |
<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin', 'admin', 0);
class index extends admin {
private $db, $messagequeue_db;
/**
* 析构函数
*/
public function __construct() {
parent::__construct();
}
public function init() {
$userinfo = $this->get_userinfo();
include $this->admin_tpl('index');
}
public function right() {
$this->member_db = pc_base::load_model('member_model');
$this->messagequeue_db = pc_base::load_model('messagequeue_model');
$total_member = $this->member_db->count(); //会员总数
$todaytime = strtotime(date('Y-m-d', SYS_TIME)); //今日会员数
$today_member = $this->member_db->count("`regdate` > '$todaytime'");
$total_messagequeue = $this->messagequeue_db->count(); //消息总数
$mysql_version = $this->member_db->get_version(); //mysql版本
$mysql_table_status = $this->member_db->get_table_status();
$mysql_table_size = $mysql_table_index_size = '';
foreach($mysql_table_status as $table) {
$mysql_table_size += $table['Data_length'];
$mysql_table_index_size += $table['Index_length'];
}
$mysql_table_size = sizecount($mysql_table_size);
$mysql_table_index_size = sizecount($mysql_table_index_size);
//应用个数
$applist = getcache('applist');
$appnum = empty($applist) ? 0 : count($applist);
include $this->admin_tpl('right');
}
}
?> | PHP |
<?php
define('IN_ADMIN', true);
class admin {
//数据库连接
private $db;
//错误代码
private $err_code;
/**
* 构造函数
* @param integer $issuper 是否为超级管理员
*/
public function __construct($issuper = 0) {
$this->db = pc_base::load_model('admin_model');
$this->check_admin($issuper);
pc_base::load_app_func('global');
}
/**
* 管理员权限判断
* @param integer $issuper 是否为超级管理员
*/
public function check_admin($issuper = 0) {
if (ROUTE_C != 'login') {
if (!$this->get_userid() || !$this->get_username()) {
$forward = isset($_GET['forward']) ? urlencode($_GET['forward']) : '';
showmessage(L('relogin'),'?m=admin&c=login&a=init&forward='.$forward);
unset($forward);
}
if ($issuper) {
$r = $this->get_userinfo();
if ($r['issuper'] != 1) {
showmessage(L('eaccess'));
}
}
}
}
/**
* 管理员登陆
* @param string $username 用户名
* @param string $password 密码
* @return boolean
*/
public function login($username, $password) {
if (!$this->db) {
$this->db = pc_base::load_model('admin_model');
}
if ($data = $this->db->get_one(array('username'=>$username))) {
$password = md5(md5($password).$data['encrypt']);
if ($password != $data['password']) {
$this->err_code = 2;
return false;
} elseif ($password == $data['password']) {
$this->db->update(array('ip'=>ip(), 'lastlogin'=>SYS_TIME),array('id'=>$data['id']));
param::set_cookie('username', $username);
param::set_cookie('userid', $data['id']);
return true;
}
$this->err_code = 0;
return false;
} else {
$this->err_code = 1;
return false;
}
}
public function log_out() {
param::set_cookie('username', '');
param::set_cookie('userid', '');
}
/**
* 获取当前用户ID号
*/
public function get_userid() {
return param::get_cookie('userid');
}
/**
* 获取当前用户名
*/
public function get_username() {
return param::get_cookie('username');
}
/**
* 获取当前用户信息
* @param string $filed 获取指定字段
* @param string $enforce 强制更新
*/
public function get_userinfo($filed = '', $enforce = 0) {
static $data;
if ($data && !$enforce) {
if($filed && isset($data[$filed])) {
return $data[$filed];
} elseif ($filed && !isset($data[$filed])) {
return false;
} else {
return $data;
}
}
$data = $this->db->get_one(array('username'=>$this->get_username(),'id'=>$this->get_userid()));
if($filed && isset($data[$filed])) {
return $data[$filed];
} elseif ($filed && !isset($data[$filed])) {
return false;
} else {
return $data;
}
}
/**
* 获取错误原因
*/
public function get_err() {
$msg = array(
'-1'=>L('database_error'),
'0'=>L('unknown_error'),
'1'=>L('User_name_could_not_find'),
'2'=>L('incorrect_password'),
);
return $msg[$this->err_code];
}
/**
* 加载后台模板
* @param string $file 文件名
* @param string $m 模型名
*/
public static function admin_tpl($file, $m = '') {
$m = empty($m) ? ROUTE_M : $m;
if(empty($m)) return false;
return PC_PATH.'modules'.DIRECTORY_SEPARATOR.$m.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.$file.'.tpl.php';
}
} | PHP |
<?php
class messagequeue {
private $db;
private static function get_db() {
return pc_base::load_model('messagequeue_model');
}
/**
* 添加队列信息
*/
public static function add($operation, $noticedata_send) {
$db = self::get_db();
$noticedata_send['action'] = $operation;
$noticedata_send_string = array2string($noticedata_send);
if ($noticeid = $db->insert(array('operation'=>$operation, 'noticedata'=>$noticedata_send_string, 'dateline'=>SYS_TIME), 1)) {
self::notice($operation, $noticedata_send, $noticeid);
return 1;
} else {
return 0;
}
}
/**
* 通知应用
*/
public static function notice($operation, $noticedata, $noticeid) {
$db = self::get_db();
$applist = getcache('applist', 'admin');
foreach($applist as $k=>$v) {
//由于编码转换会改变notice_send的值,所以每次循环需要重新赋值noticedate_send
$noticedata_send = $noticedata;
//应用添加用户时不重复通知该应用
if(isset($noticedata_send['appname']) && $noticedata_send['appname'] == $v['name']) {
$appstatus[$k] = 1;
continue;
}
$url = $v['url'].$v['apifilename'];
if (CHARSET != $v['charset'] && isset($noticedata_send['action']) && $noticedata_send['action'] == 'member_add') {
if(isset($noticedata_send['username']) && !empty($noticedata_send['username'])) {
if(CHARSET == 'utf-8') { //判断phpsso字符集是否为utf-8编码
//应用字符集如果是utf-8,并且用户名是utf-8编码,转换用户名为phpsso字符集,如果为英文,is_utf8返回false,不进行转换
if(!is_utf8($noticedata_send['username'])) {
$noticedata_send['username'] = iconv(CHARSET, $v['charset'], $noticedata_send['username']);
}
} else {
if(!is_utf8($noticedata_send['username'])) {
$noticedata_send['username'] = iconv(CHARSET, $v['charset'], $noticedata_send['username']);
}
}
}
}
$tmp_s = strstr($url, '?') ? '&' : '?';
$status = ps_send($url.$tmp_s.'appid='.$k, $noticedata_send, $v['authkey']);
if ($status == 1) {
$appstatus[$k] = 1;
} else {
$appstatus[$k] = 0;
}
}
$db->update(array('totalnum'=>'+=1', 'appstatus'=>json_encode($appstatus)), array('id'=>$noticeid));
}
}
?> | PHP |
<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin','admin',0);
class administrator extends admin{
private $db;
public function __construct() {
$this->db = pc_base::load_model('admin_model');
parent::__construct(1);
}
public function init() {
$total = $this->db->count();
$page = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']) : 1;
$pagesize = 20;
$offset = ($page - 1) * $pagesize;
$list = $this->db->select('', '*', $offset.','.$pagesize);
pc_base::load_sys_class('format', '', 0);
foreach ($list as $key=> $v) {
$list[$key]['lastlogin'] = format::date($v['lastlogin'], 1);
}
$pages = pages($total, $page, $pagesize);
include $this->admin_tpl('administrator_list');
}
public function add() {
if (isset($_POST['dosubmit'])) {
$username = isset($_POST['username']) && trim($_POST['username']) ? trim($_POST['username']) : showmessage(L('nameerror'), HTTP_REFERER);
$password = isset($_POST['password']) && trim($_POST['password']) ? trim($_POST['password']) : showmessage(L('password_can_not_be_empty'), HTTP_REFERER);
$issuper = isset($_POST['issuper']) && intval($_POST['issuper']) ? intval($_POST['issuper']) : 0;
if ($this->db->get_one(array('username'=>$username))) {
showmessage(L('user_already_exist'), HTTP_REFERER);
} else {
if (strlen($username) > 20 || strlen($username) < 6) {
showmessage(L('username').L('between_6_to_20'), HTTP_REFERER);
}
if (strlen($password) > 20 || strlen($password) < 6) {
showmessage(L('password_len_error'), HTTP_REFERER);
}
list($password, $encrypt) = creat_password($password);
if ($this->db->insert(array('username'=>$username, 'password'=>$password, 'encrypt'=>$encrypt, 'issuper'=>$issuper))) {
showmessage(L('add_admin').L('operation_success'), 'm=admin&c=administrator&a=init');
} else {
showmessage(L('database_error'), HTTP_REFERER);
}
}
}
include $this->admin_tpl('administrator_add');
}
public function del() {
$id = isset($_GET['id']) && intval($_GET['id']) ? intval($_GET['id']) : showmessage(L('illegal_parameters'), HTTP_REFERER);
$r = $this->db->get_one(array('id'=>$id));
if ($r) {
if ($r['issuper']) {
$super_num = $this->db->count(array('issuper'=>1));
if ($super_num <=1) {
showmessage(L('least_there_is_a_super_administrator'), HTTP_REFERER);
}
}
if ($this->db->delete(array('id'=>$id))) {
showmessage(L('operation_success'), HTTP_REFERER);
} else {
showmessage(L('operation_failure'), HTTP_REFERER);
}
} else {
showmessage(L('User_name_could_not_find'), HTTP_REFERER);
}
}
public function edit() {
$id = isset($_GET['id']) && intval($_GET['id']) ? intval($_GET['id']) : showmessage(L('illegal_parameters'), HTTP_REFERER);
$data = $this->db->get_one(array('id'=>$id));
if ($data) {
if (isset($_POST['dosubmit'])) {
$password = isset($_POST['password']) && trim($_POST['password']) ? trim($_POST['password']) : '';
$issuper = isset($_POST['issuper']) && intval($_POST['issuper']) ? intval($_POST['issuper']) : 0;
$update = array('issuper'=>$issuper);
if ($password) {
if (strlen($password) > 20 || strlen($password) < 6) {
showmessage(L('password_len_error'), HTTP_REFERER);
}
list($password, $encrypt) = creat_password($password);
$update['password'] = $password;
$update['encrypt'] = $encrypt;
}
if ($this->db->update($update, array('id'=>$id))) {
showmessage(L('operation_success'), 'm=admin&c=administrator&a=init');
} else {
showmessage(L('database_error'), HTTP_REFERER);
}
}
include $this->admin_tpl('administrator_edit');
} else {
showmessage(L('User_name_could_not_find'), HTTP_REFERER);
}
}
public function ajax_username() {
$username = isset($_GET['username']) && trim($_GET['username']) ? trim($_GET['username']) : exit(0);
if ($this->db->get_one(array('username'=>$username))) {
echo 0;exit();
} else {
echo 1;exit();
}
}
} | PHP |
<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin', 'admin', 0);
class system extends admin {
private $db;
/**
* 析构函数
*/
public function __construct() {
parent::__construct(1);
$this->db = pc_base::load_model('settings_model');
}
/**
* 首页
*/
public function init() {
if (isset($_POST['dosubmit'])) {
$denyusername = isset($_POST['denyusername']) ? new_stripslashes(trim($_POST['denyusername'])) : '';
$denyemail = isset($_POST['denyemail']) ? new_stripslashes(trim($_POST['denyemail'])) : '';
$denyemaildata = array2string(explode("\r\n", $denyemail));
$denyusernamedata = array2string(explode("\r\n", $denyusername));
$this->db->insert(array('name'=>'denyemail', 'data'=>$denyemaildata), 1, 1);
$this->db->insert(array('name'=>'denyusername', 'data'=>$denyusernamedata), 1, 1);
/*写入缓存*/
setcache('settings', array('denyemail'=>explode("\r\n", $denyemail), 'denyusername'=>explode("\r\n", $denyusername)));
showmessage(L('operation_success'), HTTP_REFERER);
}
$where = to_sqls(array('denyemail', 'denyusername'), '', 'name');
$settingarr = $this->db->listinfo($where);
foreach ($settingarr as $v) {
$setting[$v['name']] = string2array($v['data']);
}
include $this->admin_tpl('system');
}
public function uc() {
if (isset($_POST['dosubmit'])) {
$data = isset($_POST['data']) ? $_POST['data'] : '';
$data['ucuse'] = isset($_POST['ucuse']) && intval($_POST['ucuse']) ? intval($_POST['ucuse']) : 0;
$filepath = CACHE_PATH.'configs'.DIRECTORY_SEPARATOR.'system.php';
$config = include $filepath;
$uc_config = '<?php '."\ndefine('UC_CONNECT', 'mysql');\n";
foreach ($data as $k => $v) {
$old[] = "'$k'=>'".(isset($config[$k]) ? $config[$k] : $v)."',";
$new[] = "'$k'=>'$v',";
$uc_config .= "define('".strtoupper($k)."', '$v');\n";
}
$html = file_get_contents($filepath);
$html = str_replace($old, $new, $html);
$uc_config_filepath = CACHE_PATH.'configs'.DIRECTORY_SEPARATOR.'uc_config.php';
@file_put_contents($uc_config_filepath, $uc_config);
@file_put_contents($filepath, $html);
$this->db->insert(array('name'=>'ucenter', 'data'=>array2string($data)), 1,1);
showmessage(L('operation_success'), HTTP_REFERER);
}
$data = array();
$r = $this->db->get_one(array('name'=>'ucenter'));
if ($r) {
$data = string2array($r['data']);
}
include $this->admin_tpl('system_uc');
}
public function myqsl_test() {
$host = isset($_GET['host']) && trim($_GET['host']) ? trim($_GET['host']) : exit('0');
$password = isset($_GET['password']) && trim($_GET['password']) ? trim($_GET['password']) : exit('0');
$username = isset($_GET['username']) && trim($_GET['username']) ? trim($_GET['username']) : exit('0');
if (@mysql_connect($host, $username, $password)) {
exit('1');
} else {
exit('0');
}
}
public function sp4() {
if (isset($_POST['dosubmit'])) {
$data = isset($_POST['data']) ? $_POST['data'] : '';
$data['sp4use'] = isset($_POST['sp4use']) && intval($_POST['sp4use']) ? intval($_POST['sp4use']) : 0;
$data['sp4_password_key'] = isset($_POST['sp4_password_key']) && $_POST[sp4_password_key] ? $_POST['sp4_password_key'] : '';
$this->db->insert(array('name'=>'sp4', 'data'=>array2string($data)), 1, 1);
setcache('settings_sp4', $data);
showmessage(L('operation_success'), HTTP_REFERER);
}
$data = array();
$data = getcache('settings_sp4');
include $this->admin_tpl('system_sp4');
}
}
?> | PHP |
<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_app_class('messagequeue', 'admin' , 0);
class credit extends admin {
private $db;
/**
* 析构函数
*/
public function __construct() {
parent::__construct();
$this->db = pc_base::load_model('settings_model');
}
/**
* 首页
*/
public function manage() {
$applist = getcache('applist');
$creditlist = getcache('creditlist');
if(empty($creditlist)) $creditlist = array();
include $this->admin_tpl('credit_list');
}
/**
* 首页
*/
public function delete() {
$id = isset($_POST['id']) ? $_POST['id'] : showmessage(L('illegal_parameters'), HTTP_REFERER);
$creditlist = getcache('creditlist');
foreach($id as $v) {
unset($creditlist[$v]);
}
$this->db->insert(array('name'=>'creditrate', 'data'=>array2string($creditlist)), 1, 1);
setcache('creditlist', $creditlist);
showmessage(L('operation_success'), HTTP_REFERER);
}
/**
* 添加规则
*/
public function add() {
if (isset($_POST['dosubmit'])) {
$ruledata['fromid'] = isset($_POST['fromid']) ? intval($_POST['fromid']) : showmessage(L('illegal_parameters'), HTTP_REFERER);
$ruledata['toid'] = isset($_POST['toid']) ? intval($_POST['toid']) : showmessage(L('illegal_parameters'), HTTP_REFERER);
$ruledata['fromrate'] = isset($_POST['fromrate']) ? intval($_POST['fromrate']) : showmessage(L('illegal_parameters'), HTTP_REFERER);
$ruledata['torate'] = isset($_POST['torate']) ? intval($_POST['torate']) : showmessage(L('illegal_parameters'), HTTP_REFERER);
if(empty($_POST['from']) || empty($_POST['to'])) {
showmessage(L('illegal_parameters'), HTTP_REFERER);
}
$fromarr = explode('_', $_POST['from']);
$toarr = explode('_', $_POST['to']);
$ruledata['from'] = isset($fromarr[0]) ? $fromarr[0] : '';
$ruledata['fromname'] = isset($fromarr[1]) ? $fromarr[1] : '';
$ruledata['fromunit'] = isset($fromarr[2]) ? $fromarr[2] : '';
$ruledata['to'] = isset($toarr[0]) ? $toarr[0] : '';
$ruledata['toname'] = isset($toarr[1]) ? $toarr[1] : '';
$ruledata['tounit'] = isset($toarr[2]) ? $toarr[2] : '';
$creditlistarr = $this->db->get_one(array('name'=>'creditrate'));
$creditlist = string2array($creditlistarr['data']);
$creditlist[] = $ruledata;
$noticedata['creditlist'] = $creditlist;
//加入消息队列
messagequeue::add('credit_update', $noticedata);
setcache('creditlist', $creditlist);
$this->db->insert(array('name'=>'creditrate', 'data'=>array2string($creditlist)), 1, 1);
showmessage(L('operation_success'), HTTP_REFERER);
}
$applist = getcache('applist');
include $this->admin_tpl('credit_add');
}
/**
* 获取应用积分列表
*/
public function creditlist() {
$appid = isset($_GET['appid']) ? $_GET['appid'] : exit('0');
$applist = getcache('applist');
$url = isset($applist[$appid]) ? $applist[$appid]['url'].$applist[$appid]['apifilename'] : exit('0');
$data['action'] = 'credit_list';
$res = ps_send($url.'?appid='.$appid, $data, $applist[$appid]['authkey']);
if(!empty($res)) {
$creditlist = string2array($res);
$str = '';
foreach($creditlist as $k=>$v) {
$str .="<option value=".$k.'_'.$v[0].'_'.$v[1].">".$v[0]."(".$v[1].")</option>";
}
echo $str;exit;
} else {
exit('0');
}
}
}
?> | PHP |
<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin', 'admin', 0);
class cache extends admin {
private $db, $applications_db;
/**
* 析构函数
*/
public function __construct() {
parent::__construct(1);
$this->db = pc_base::load_model('setting_model');
$this->applications_db = pc_base::load_model('applications_model');
}
/**
* 首页
*/
public function init() {
$applistinfo = getcacheinfo('applist');
include $this->admin_tpl('cache');
}
public function ajax_clear() {
/*写入应用列表缓存*/
$applist = $this->applications_db->listinfo('', '', 1, 100,'appid');
setcache('applist', $applist);
$applistinfo = getcacheinfo('applist');
$return['filesize'] = sizecount($applistinfo['filesize']);
$return['filemtime'] = date('Y-m-d H:i:s', $applistinfo['filemtime']);
exit(json_encode($return));
}
}
?> | PHP |
<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin','admin',0);
pc_base::load_sys_class('form', '', 0);
$session_storage = 'session_'.pc_base::load_config('system','session_storage');
pc_base::load_sys_class($session_storage);
class login extends admin {
/**
* 初始化页面
*/
public function init() {
include $this->admin_tpl('login');
}
/**
* 登陆
*/
public function logind() {
header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
$username = isset($_POST['username']) && trim($_POST['username']) ? trim($_POST['username']) : showmessage(L('nameerror'), '?m=admin&a=init&c=login');
$password = isset($_POST['password']) && trim($_POST['password']) ? trim($_POST['password']) : showmessage(L('password_can_not_be_empty'), '?m=admin&a=init&c=login');
$code = isset($_POST['code']) && trim($_POST['code']) ? trim($_POST['code']) : showmessage(L('input_code'), HTTP_REFERER);
if ($_SESSION['code'] != strtolower($code)) {
showmessage(L('code_error'), HTTP_REFERER);
}
if ($this->login($username,$password)) {
$forward = isset($_POST['forward']) ? urldecode($_POST['forward']) : '';
showmessage(L('login_succeeded'), '?m=admin&c=index&a=init&forward='.$forward);
} else {
showmessage($this->get_err(), '?m=admin&c=login&a=init&forward='.$_POST['forward']);
}
}
/**
* 退出登录
*/
public function logout() {
$this->log_out();
$forward = isset($_GET['forward']) ? urlencode($_GET['forward']) : '';
showmessage(L('logout_succeeded'), '?m=admin&c=login&a=init&forward='.$forward);
}
} | PHP |
<?php
/**
* 生成加密后的密码
* @param string $password 密码
* @return array 加密后的密码
*/
function creat_password($password) {
$encrypt = substr(md5(rand()), 0, 6);
return array(md5(md5($password).$encrypt),$encrypt);
}
/**
* 发送数据
* @param $action 操作
* @param $data 数据
*/
function ps_send($url, $data = null, $key) {
$s = $sep = '';
foreach($data as $k => $v) {
if(is_array($v)) {
$s2 = $sep2 = '';
foreach($v as $k2 => $v2) {
if(is_array($v2)) {
$s3 = $sep3 = '';
foreach($v2 as $k3=>$v3) {
$k3 = $k3;
$s3 .= "$sep3{$k}[$k2][$k3]=".ps_stripslashes($v3);
$sep3 = '&';
}
$s .= $sep2.$s3;
} else {
$s2 .= "$sep2{$k}[$k2]=".ps_stripslashes($v2);
$sep2 = '&';
$s .= $sep.$s2;
}
}
} else {
$s .= "$sep$k=".ps_stripslashes($v);
}
$sep = '&';
}
$auth_s = 'code='.urlencode(sys_auth($s, 'ENCODE', $key));
return ps_post($url, 500000, $auth_s);
}
/**
* post数据
* @param string $url post的url
* @param int $limit 返回的数据的长度
* @param string $post post数据,字符串形式username='dalarge'&password='123456'
* @param string $cookie 模拟 cookie,字符串形式username='dalarge'&password='123456'
* @param string $ip ip地址
* @param int $timeout 连接超时时间
* @param bool $block 是否为阻塞模式
* @return string 返回字符串
*/
function ps_post($url, $limit = 0, $post = '', $cookie = '', $ip = '', $timeout = 15, $block = true) {
$return = '';
$matches = parse_url($url);
$host = $matches['host'];
$path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/';
$port = !empty($matches['port']) ? $matches['port'] : 80;
$siteurl = get_url();
if($post) {
$out = "POST $path HTTP/1.1\r\n";
$out .= "Accept: */*\r\n";
$out .= "Referer: ".$siteurl."\r\n";
$out .= "Accept-Language: zh-cn\r\n";
$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
$out .= "Host: $host\r\n" ;
$out .= 'Content-Length: '.strlen($post)."\r\n" ;
$out .= "Connection: Close\r\n" ;
$out .= "Cache-Control: no-cache\r\n" ;
$out .= "Cookie: $cookie\r\n\r\n" ;
$out .= $post ;
} else {
$out = "GET $path HTTP/1.1\r\n";
$out .= "Accept: */*\r\n";
$out .= "Referer: ".$siteurl."\r\n";
$out .= "Accept-Language: zh-cn\r\n";
$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
$out .= "Host: $host\r\n";
$out .= "Connection: Close\r\n";
$out .= "Cookie: $cookie\r\n\r\n";
}
$fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
if(!$fp) return '';
stream_set_blocking($fp, $block);
stream_set_timeout($fp, $timeout);
@fwrite($fp, $out);
$status = stream_get_meta_data($fp);
if($status['timed_out']) return '';
while (!feof($fp)) {
if(($header = @fgets($fp)) && ($header == "\r\n" || $header == "\n")) break;
}
$stop = false;
while(!feof($fp) && !$stop) {
$data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
$return .= $data;
if($limit) {
$limit -= strlen($data);
$stop = $limit <= 0;
}
}
@fclose($fp);
return $return;
}
/**
* 过滤字符串
* @param $string
*/
function ps_stripslashes($string) {
!defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
if(MAGIC_QUOTES_GPC) {
return stripslashes($string);
} else {
return $string;
}
}
/**
* 根据phpsso uid获取头像url
*/
function ps_getavatar($uid, $is_url=0) {
$dir1 = ceil($uid / 10000);
$dir2 = ceil($uid % 10000 / 1000);
//$avatar = array($url.'30x30.jpg', $url.'45x45.jpg', $url.'90x90.jpg', $url.'180x180.jpg');
if($is_url) {
$url = PHPCMS_PATH.'uploadfile'.DIRECTORY_SEPARATOR.'avatar'.DIRECTORY_SEPARATOR.$dir1.DIRECTORY_SEPARATOR.$dir2.DIRECTORY_SEPARATOR.$uid.DIRECTORY_SEPARATOR;
return $url;
} else {
$url = APP_PATH.'uploadfile/avatar/'.$dir1.'/'.$dir2.'/'.$uid.'/';
return $url.'45x45.jpg';
}
}
/**
* 删除目录
*/
function ps_unlink($dir) {
if(is_dir($dir)) {
if($handle = opendir($dir)) {
while(false !== ($file = readdir($handle))) {
if($file !== '.' && $file !== '..') {
if(file_exists($dir.$file)) {
@unlink($dir.$file);
}
}
}
closedir($handle);
}
@rmdir($dir);
} else {
@unlink($dir);
}
}
?> | PHP |
<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('phpsso', 'phpsso', 0);
pc_base::load_app_class('messagequeue', 'admin' , 0);
pc_base::load_app_func('global', 'admin');
class index extends phpsso {
private $username, $config;
public function __construct() {
parent::__construct();
$this->config = pc_base::load_config('system');
/*判断应用字符集和phpsso字符集是否相同,如果不相同,转换用户名为phpsso所用字符集*/
$this->username = isset($this->data['username']) ? $this->data['username'] : '';
if ($this->username && CHARSET != $this->applist[$this->appid]['charset']) {
if($this->applist[$this->appid]['charset'] == 'utf-8') { //判断应用字符集是否为utf-8编码
//应用字符集如果是utf-8,并且用户名是utf-8编码,转换用户名为phpsso字符集,如果为英文,is_utf8返回false,不进行转换
if(is_utf8($this->username)) {
$this->username = iconv($this->applist[$this->appid]['charset'], CHARSET, $this->username);
}
} else {
if(!is_utf8($this->username)) {
$this->username = iconv($this->applist[$this->appid]['charset'], CHARSET, $this->username);
}
}
}
}
/**
* 用户注册
* @param string $username 用户名
* @param string $password 密码
* @param string $email email
* @return int {-1:用户名已经存在 ;-2:email已存在;-4:用户名禁止注册;-5:邮箱禁止注册;-6:uc注册失败;int(uid):成功}
*/
public function register() {
$this->random = isset($this->data['random']) && !empty($this->data['random']) ? $this->data['random'] : create_randomstr(6);
$this->password = isset($this->data['password']) ? create_password($this->data['password'], $this->random) : '';
$this->email = isset($this->data['email']) ? $this->data['email'] : '';
$this->type = isset($this->appid) ? 'app' : 'connect';
$this->regip = isset($this->data['regip']) ? $this->data['regip'] : '';
$this->appid = isset($this->appid) ? $this->appid : '';
$this->appname = $this->applist[$this->appid]['name'];
$checkname = $this->checkname(1);
if ($checkname == -1) {
exit('-1');
} elseif ($checkname == -4) {
exit('-4');
}
$checkemail = $this->checkemail(1);
if($checkemail == -1) {
exit('-2');
} elseif ($checkemail == -5) {
exit('-5');
}
//UCenter会员注册
$ucuserid = 0;
if ($this->config['ucuse']) {
pc_base::load_config('uc_config');
require_once PHPCMS_PATH.'api/uc_client/client.php';
$uid= uc_user_register($this->username, $this->data['password'], $this->email, $this->random);
if(is_numeric($uid)) {
switch ($uid) {
case '-3':
exit('-1');
break;
case '-6':
exit('-2');
break;
case '-2':
exit('-4');
break;
case '-5':
exit('-5');
break;
case '-1':
exit('-4');
break;
case '-4':
exit('-5');
break;
default :
$ucuserid = $uid;
break;
}
} else {
exit('-6');
}
}
$data = array(
'username' => $this->username,
'password' => $this->password,
'email' => $this->email,
'regip' => $this->regip,
'regdate' => SYS_TIME,
'lastdate' => SYS_TIME,
'appname' => $this->appname,
'type' => $this->type,
'random' => $this->random,
'ucuserid'=>$ucuserid
);
$uid = $this->db->insert($data, 1);
/*插入消息队列*/
$noticedata = $data;
$noticedata['uid'] = $uid;
messagequeue::add('member_add', $noticedata);
exit("$uid"); //exit($uid) 不可以If status is an integer, that value will also be used as the exit status.
}
/**
* 编辑用户,可以不传入旧密码和新密码
* 如果传入新密码,则修改密码为新密码
* @param string $username 用户名
* @param string $password 旧密码
* @param string $newpassword 新密码
* @param string $email email
* @param string $random 密码随机数
* @return int {-1:用户不存在;-2:旧密码错误;-3:email已经存在 ;1:成功;0:未作修改}
*/
public function edit() {
$this->email = isset($this->data['email']) ? $this->data['email'] : '';
$this->uid = isset($this->data['uid']) ? $this->data['uid'] : '';
$userinfo = $this->getuserinfo(1);
if (isset($this->data['password']) && !empty($this->data['password'])) {
$this->password = create_password($this->data['password'], $userinfo['random']);
}
$this->random = !empty($this->data['random']) ? $this->data['random'] : $userinfo['random'];
if (isset($this->data['newpassword']) && !empty($this->data['newpassword'])) {
$this->newpassword = create_password($this->data['newpassword'], $this->random);
}
if ($userinfo == -1) {
exit('-1');
}
if (isset($this->password) && !empty($this->password) && $userinfo['password'] != $this->password) {
exit('-2');
}
if ($this->email && $userinfo['email'] != $this->email) {
if($this->checkemail(1) == -1) exit('-3');
}
$data = array();
$data['appname'] = $this->applist[$this->appid]['name'];
if (!empty($this->email) && $userinfo['email'] != $this->email) {
$data['email'] = $this->email;
}
if (isset($this->newpassword) && $userinfo['password'] != $this->newpassword) {
$data['password'] = $this->newpassword;
$data['random'] = $this->random;
}
if (!empty($data)) {
//ucenter部份
if ($this->config['ucuse']) {
pc_base::load_config('uc_config');
require_once PHPCMS_PATH.'api/uc_client/client.php';
$r = uc_user_edit($userinfo['username'], '', (isset($this->data['newpassword']) && !empty($this->data['newpassword']) ? $this->data['newpassword'] : ''), $data['email'], $data['random'], 1);
if ($r != 1) {
//{-1:用户不存在;-2:旧密码错误;-3:email已经存在 ;1:成功;0:未作修改}
switch ($r) {
case '-1':
exit('-2');
break;
case '0':
case '-4':
case '-5':
case '-6':
case '-7':
case '-8':
exit('0');
break;
}
}
}
if (empty($data['email'])) unset($data['email']);
/*插入消息队列*/
$noticedata = $data;
$noticedata['uid'] = $userinfo['uid'];
messagequeue::add('member_edit', $noticedata);
if($this->username) {
$res = $this->db->update($data, array('username'=>$this->username));
} else {
$res = $this->db->update($data, array('uid'=>$this->uid));
}
exit("$res");
} else {
exit('0');
}
}
/**
* 删除用户
* @param string {$uid:用户id;$username:用户名;$email:email}
* @return array {-1:删除失败;>0:删除成功}
*/
public function delete() {
$this->uid = isset($this->data['uid']) ? $this->data['uid'] : '';
$this->email = isset($this->data['email']) ? $this->data['email'] : '';
if($this->uid > 0 || is_array($this->uid)) {
$where = to_sqls($this->uid, '', 'uid');
//ucenter部份
if ($this->config['ucuse']) {
pc_base::load_config('uc_config');
require_once PHPCMS_PATH.'api/uc_client/client.php';
$s = $this->db->select($where, 'ucuserid');
if ($s) {
$uc_data = array();
foreach ($s as $k=>$v) {
$uc_data[$k] = $v['ucuserid'];
}
if (!empty($uc_data)) $r = uc_user_delete($uc_data);
if (!$r) {
exit('-1');
}
} else {
exit('-1');
}
}
/*插入消息队列*/
$noticedata['uids'] = $this->uid;
messagequeue::add('member_delete', $noticedata);
$this->db->delete($where);
exit('1');
} elseif(!empty($this->username)) {
$this->db->delete(array('username'=>$this->username));
exit('2');
} elseif(!empty($this->email)) {
$this->db->delete(array('email'=>$this->email));
exit('3');
} else {
exit('-1');
}
}
/**
* 获取用户信息
* @param string {$uid:用户id;$username:用户名;$email:email}
* @return array {-1:用户不存在;array(userinfo):用户信息}
*/
public function getuserinfo($is_return = 0) {
$this->uid = isset($this->data['uid']) ? $this->data['uid'] : '';
$this->email = isset($this->data['email']) ? $this->data['email'] : '';
if($this->uid > 0) {
$r = $this->db->get_one(array('uid'=>$this->uid));
} elseif(!empty($this->username)) {
$r = $this->db->get_one(array('username'=>$this->username));
} elseif(!empty($this->email)) {
$r = $this->db->get_one(array('email'=>$this->email));
} else {
return false;
}
if(!empty($r)) {
if($is_return) {
return $r;
} else {
exit(serialize($r));
}
} else {
exit('-1');
}
}
/**
* 用户登录
* @param string $username 用户名
* @param string $password 密码
* @return array {-2;密码错误;-1:用户不存在;array(userinfo):用户信息}
*/
public function login() {
$this->password = isset($this->data['password']) ? $this->data['password'] : '';
$this->email = isset($this->data['email']) ? $this->data['email'] : '';
if($this->email) {
$userinfo = $this->db->get_one(array('email'=>$this->email));
} else {
$userinfo = $this->db->get_one(array('username'=>$this->username));
}
if ($this->config['ucuse']) {
pc_base::load_config('uc_config');
require_once PHPCMS_PATH.'api/uc_client/client.php';
list($uid, $uc['username'], $uc['password'], $uc['email']) = uc_user_login($this->username, $this->password, 0);
}
if($userinfo) {
//ucenter登陆部份
if ($this->config['ucuse']) {
if($uid == -1) { //uc不存在该用户,调用注册接口注册用户
$uid = uc_user_register($this->username , $this->password, $userinfo['email'], $userinfo['random']);
if($uid >0) {
$this->db->update(array('ucuserid'=>$uid), array('username'=>$this->username));
}
}
}
} else { //用户在phpsso中不存在
//ucenter登陆部份
if ($this->config['ucuse']) {
if ($uid < 0) { //用户不存在或者密码错误
exit('-1');
} else {
//当前使用只在uc中存在,在PHPSSO中是不存在的。需要进行注册。
pc_base::load_sys_class('uc_model', 'model', 0);
$db_config = get_uc_database();
$uc_db = new uc_model($db_config);
//获取UC中用户的信息
$r = $uc_db->get_one(array('uid'=>$uid));
$datas = $data = array('username'=>$r['username'], 'password'=>$r['password'], 'random'=>$r['salt'], 'email'=>$r['email'], 'regip'=>$r['regip'], 'regdate'=>$r['regdate'], 'lastdate'=>$r['lastlogindate'], 'appname'=>'ucenter', 'type'=>'app');
$datas['ucuserid'] = $uid;
$datas['lastip'] = $r['lastloginip'];
if ($data['uid'] = $this->db->insert($datas, true)) {
//向所有的应用中发布新用户注册通知
messagequeue::add('member_add', $data);
}
$userinfo = $data;
}
} else {
exit('-1');
}
}
//如果开启phpcms_2008_sp4兼容模式,根据sp4规则验证密码,如果不成功再根据phpsso规则验证密码
$setting_sp4 = getcache('settings_sp4', 'admin');
if($setting_sp4['sp4use']) {
if(!empty($userinfo) && $userinfo['password'] == md5($setting_sp4['sp4_password_key'].$this->password)) {
//登录成功更新用户最近登录时间和ip
$this->db->update(array('lastdate'=>SYS_TIME, 'lastip'=>ip()), array('uid'=>$userinfo['uid']));
exit(serialize($userinfo));
}
}
if(!empty($userinfo) && $userinfo['password'] == create_password($this->password, $userinfo['random'])) {
//登录成功更新用户最近登录时间和ip
$this->db->update(array('lastdate'=>SYS_TIME, 'lastip'=>ip()), array('uid'=>$userinfo['uid']));
exit(serialize($userinfo));
} else {
exit('-2');
}
}
/**
* 同步登陆
* @param string $uid 用户id
* @return string javascript用户同步登陆js
*/
public function synlogin() {
//判断本应用是否开启同步登陆
if($this->applist[$this->appid]['synlogin']) {
$this->uid = isset($this->data['uid']) ? $this->data['uid'] : '';
$this->password = isset($this->data['password']) ? $this->data['password'] : '';
$res = '';
//ucenter登陆部份
if ($this->config['ucuse']) {
pc_base::load_config('uc_config');
require_once PHPCMS_PATH.'api/uc_client/client.php';
$r = $this->db->get_one(array('uid'=>$this->uid), "ucuserid");
if($r['ucuserid']) $res .= uc_user_synlogin($r['ucuserid']);
}
foreach($this->applist as $v) {
if (!$v['synlogin']) continue;
if($v['appid'] != $this->appid) {
$tmp_s = strstr($v['url'].$v['apifilename'], '?') ? '&' : '?';
$res .= '<script type="text/javascript" src="'.$v['url'].$v['apifilename'].$tmp_s.'time='.SYS_TIME.'&code='.urlencode(sys_auth('action=synlogin&username='.$this->username.'&uid='.$this->uid.'&password='.$this->password."&time=".SYS_TIME, 'ENCODE', $v['authkey'])).'" reload="1"></script>';
}
}
exit($res);
} else {
exit('0');
}
}
/**
* 同步退出
* @return string javascript用户同步退出js
*/
public function synlogout() {
if($this->applist[$this->appid]['synlogin']) {
$res = '';
//ucenter登陆部份
if ($this->config['ucuse']) {
pc_base::load_config('uc_config');
require_once PHPCMS_PATH.'api/uc_client/client.php';
$res .= uc_user_synlogout();
}
foreach($this->applist as $v) {
if (!$v['synlogin']) continue;
if($v['appid'] != $this->appid) {
$tmp_s = strstr($v['url'].$v['apifilename'], '?') ? '&' : '?';
$res .= '<script type="text/javascript" src="'.$v['url'].$v['apifilename'].$tmp_s.'time='.SYS_TIME.'&code='.urlencode(sys_auth('action=synlogout&time='.SYS_TIME, 'ENCODE', $v['authkey'])).'" reload="1"></script>';
}
}
exit($res);
} else {
exit;
}
}
/**
* 获取应用列表
*/
public function getapplist() {
$applist = getcache('applist', 'admin');
exit(serialize($applist));
}
/**
* 获取积分兑换规则
*/
public function getcredit($return='') {
$creditcache = getcache('creditlist', 'admin');
foreach($creditcache as $v) {
if($v['fromid'] == $this->appid) {
$creditlist[$v['from'].'_'.$v['to']] = $v;
}
}
if($return) {
return $creditlist;
} else {
exit(serialize($creditlist));
}
}
/**
* 兑换积分
* @param int $uid phpssouid
* @param int $from 本系统积分类型id
* @param int $toappid 目标系统应用appid
* @param int $to 目标系统积分类型id
* @param int $credit 本系统扣除积分数
* @return bool {1:成功;0:失败}
*/
public function changecredit() {
$this->uid = isset($this->data['uid']) ? $this->data['uid'] : exit('0');
$this->toappid = isset($this->data['toappid']) ? $this->data['toappid'] : exit('0');
$this->from = isset($this->data['from']) ? $this->data['from'] : exit('0');
$this->to = isset($this->data['to']) ? $this->data['to'] : exit('0');
$this->credit = isset($this->data['credit']) ? $this->data['credit'] : exit('0');
$this->appname = $this->applist[$this->appid]['name'];
$outcredit = $this->getcredit(1);
//目标系统积分增加数
$this->credit = floor($this->credit * $outcredit[$this->from.'_'.$this->to]['torate'] / $outcredit[$this->from.'_'.$this->to]['fromrate']);
/*插入消息队列*/
$noticedata['appname'] = $this->appname;
$noticedata['uid'] = $this->uid;
$noticedata['toappid'] = $this->toappid;
$noticedata['totypeid'] = $this->to;
$noticedata['credit'] = $this->credit;
messagequeue::add('change_credit', $noticedata);
exit('1');
}
/**
* 检查用户名
* @param string $username 用户名
* @return int {-4:用户名禁止注册;-1:用户名已经存在 ;1:成功}
*/
public function checkname($is_return=0) {
if(empty($this->username)) {
if ($is_return) {
return -1;
} else {
exit('-1');
}
}
//非法关键词判断
$denyusername = $this->settings['denyusername'];
if(is_array($denyusername)) {
$denyusername = implode("|", $denyusername);
$pattern = '/^('.str_replace(array('\\*', ' ', "\|"), array('.*', '', '|'), preg_quote($denyusername, '/')).')$/i';
if(preg_match($pattern, $this->username)) {
if ($is_return) {
return -4;
} else {
exit('-4');
}
}
}
//UCenter部分
if ($this->config['ucuse']) {
pc_base::load_config('uc_config');
require_once PHPCMS_PATH.'api/uc_client/client.php';
$rs= uc_user_checkname($this->username);
if ($rs < 1) {
exit('-4');
}
}
$r = $this->db->get_one(array('username'=>$this->username));
if ($is_return) {
return !empty($r) ? -1 : 1;
} else {
echo !empty($r) ? -1 : 1;
exit;
}
}
/**
* 检查email
* @param string $email email
* @return int {-1:email已经存在 ;-5:邮箱禁止注册;1:成功}
*/
public function checkemail($is_return=0) {
$this->email = isset($this->email) ? $this->email : isset($this->data['email']) ? $this->data['email'] : '';
if(empty($this->email)) {
if ($is_return) {
return -1;
} else {
exit('-1');
}
}
//非法关键词判断
$denyemail = $this->settings['denyemail'];
if(is_array($denyemail)) {
$denyemail = implode("|", $denyemail);
$pattern = '/^('.str_replace(array('\\*', ' ', "\|"), array('.*', '', '|'), preg_quote($denyemail, '/')).')$/i';
if(preg_match($pattern, $this->email)) {
if ($is_return) {
return -5;
} else {
exit('-5');
}
}
}
//UCenter部分
if ($this->config['ucuse']) {
pc_base::load_config('uc_config');
require_once PHPCMS_PATH.'api/uc_client/client.php';
$rs= uc_user_checkemail($this->email);
if ($rs < 1) {
exit('-5');
}
}
$r = $this->db->get_one(array('email'=>$this->email));
if ($is_return) {
return !empty($r) ? -1 : 1;
} else {
!empty($r) ? exit('-1') : exit('1');
}
}
/**
* 上传头像处理
* 传入头像压缩包,解压到指定文件夹后删除非图片文件
*/
public function uploadavatar() {
//根据用户id创建文件夹
if(isset($this->data['uid']) && isset($this->data['avatardata'])) {
$this->uid = $this->data['uid'];
$this->avatardata = $this->data['avatardata'];
} else {
exit('0');
}
$dir1 = ceil($this->uid / 10000);
$dir2 = ceil($this->uid % 10000 / 1000);
//创建图片存储文件夹
$avatarfile = pc_base::load_config('system', 'upload_path').'avatar/';
$dir = $avatarfile.$dir1.'/'.$dir2.'/'.$this->uid.'/';
if(!file_exists($dir)) {
mkdir($dir, 0777, true);
}
//存储flashpost图片
$filename = $dir.$this->uid.'.zip';
file_put_contents($filename, $this->avatardata);
//解压缩文件
pc_base::load_app_class('pclzip', 'phpsso', 0);
$archive = new PclZip($filename);
if ($archive->extract(PCLZIP_OPT_PATH, $dir) == 0) {
die("Error : ".$archive->errorInfo(true));
}
//判断文件安全,删除压缩包和非jpg图片
$avatararr = array('180x180.jpg', '30x30.jpg', '45x45.jpg', '90x90.jpg');
if($handle = opendir($dir)) {
while(false !== ($file = readdir($handle))) {
if($file !== '.' && $file !== '..') {
if(!in_array($file, $avatararr)) {
@unlink($dir.$file);
} else {
$info = @getimagesize($dir.$file);
if(!$info || $info[2] !=2) {
@unlink($dir.$file);
}
}
}
}
closedir($handle);
}
$this->db->update(array('avatar'=>1), array('uid'=>$this->uid));
exit('1');
}
/**
* 删除用户头像
* @return {0:失败;1:成功}
*/
public function deleteavatar() {
//根据用户id创建文件夹
if(isset($this->data['uid'])) {
$this->uid = $this->data['uid'];
} else {
exit('0');
}
$dir1 = ceil($this->uid / 10000);
$dir2 = ceil($this->uid % 10000 / 1000);
//图片存储文件夹
$avatarfile = pc_base::load_config('system', 'upload_path').'avatar/';
$dir = $avatarfile.$dir1.'/'.$dir2.'/'.$this->uid.'/';
$this->db->update(array('avatar'=>0), array('uid'=>$this->uid));
if(!file_exists($dir)) {
exit('1');
} else {
if($handle = opendir($dir)) {
while(false !== ($file = readdir($handle))) {
if($file !== '.' && $file !== '..') {
@unlink($dir.$file);
}
}
closedir($handle);
@rmdir($dir);
exit('1');
}
}
}
}
?> | PHP |
<?php
// --------------------------------------------------------------------------------
// PhpConcept Library - Zip Module 2.6
// --------------------------------------------------------------------------------
// License GNU/LGPL - Vincent Blavet - March 2006
// http://www.phpconcept.net
// --------------------------------------------------------------------------------
//
// Presentation :
// PclZip is a PHP library that manage ZIP archives.
// So far tests show that archives generated by PclZip are readable by
// WinZip application and other tools.
//
// Description :
// See readme.txt and http://www.phpconcept.net
//
// Warning :
// This library and the associated files are non commercial, non professional
// work.
// It should not have unexpected results. However if any damage is caused by
// this software the author can not be responsible.
// The use of this software is at the risk of the user.
//
// --------------------------------------------------------------------------------
// $Id: pclzip.lib.php,v 1.47 2007/07/20 13:56:07 vblavet Exp $
// --------------------------------------------------------------------------------
// ----- Constants
if (!defined('PCLZIP_READ_BLOCK_SIZE')) {
define( 'PCLZIP_READ_BLOCK_SIZE', 2048 );
}
// ----- File list separator
// In version 1.x of PclZip, the separator for file list is a space
// (which is not a very smart choice, specifically for windows paths !).
// A better separator should be a comma (,). This constant gives you the
// abilty to change that.
// However notice that changing this value, may have impact on existing
// scripts, using space separated filenames.
// Recommanded values for compatibility with older versions :
//define( 'PCLZIP_SEPARATOR', ' ' );
// Recommanded values for smart separation of filenames.
if (!defined('PCLZIP_SEPARATOR')) {
define( 'PCLZIP_SEPARATOR', ',' );
}
// ----- Error configuration
// 0 : PclZip Class integrated error handling
// 1 : PclError external library error handling. By enabling this
// you must ensure that you have included PclError library.
// [2,...] : reserved for futur use
if (!defined('PCLZIP_ERROR_EXTERNAL')) {
define( 'PCLZIP_ERROR_EXTERNAL', 0 );
}
// ----- Optional static temporary directory
// By default temporary files are generated in the script current
// path.
// If defined :
// - MUST BE terminated by a '/'.
// - MUST be a valid, already created directory
// Samples :
// define( 'PCLZIP_TEMPORARY_DIR', '/temp/' );
// define( 'PCLZIP_TEMPORARY_DIR', 'C:/Temp/' );
if (!defined('PCLZIP_TEMPORARY_DIR')) {
define( 'PCLZIP_TEMPORARY_DIR', '' );
}
// --------------------------------------------------------------------------------
// ***** UNDER THIS LINE NOTHING NEEDS TO BE MODIFIED *****
// --------------------------------------------------------------------------------
// ----- Global variables
$g_pclzip_version = "2.6";
// ----- Error codes
// -1 : Unable to open file in binary write mode
// -2 : Unable to open file in binary read mode
// -3 : Invalid parameters
// -4 : File does not exist
// -5 : Filename is too long (max. 255)
// -6 : Not a valid zip file
// -7 : Invalid extracted file size
// -8 : Unable to create directory
// -9 : Invalid archive extension
// -10 : Invalid archive format
// -11 : Unable to delete file (unlink)
// -12 : Unable to rename file (rename)
// -13 : Invalid header checksum
// -14 : Invalid archive size
define( 'PCLZIP_ERR_USER_ABORTED', 2 );
define( 'PCLZIP_ERR_NO_ERROR', 0 );
define( 'PCLZIP_ERR_WRITE_OPEN_FAIL', -1 );
define( 'PCLZIP_ERR_READ_OPEN_FAIL', -2 );
define( 'PCLZIP_ERR_INVALID_PARAMETER', -3 );
define( 'PCLZIP_ERR_MISSING_FILE', -4 );
define( 'PCLZIP_ERR_FILENAME_TOO_LONG', -5 );
define( 'PCLZIP_ERR_INVALID_ZIP', -6 );
define( 'PCLZIP_ERR_BAD_EXTRACTED_FILE', -7 );
define( 'PCLZIP_ERR_DIR_CREATE_FAIL', -8 );
define( 'PCLZIP_ERR_BAD_EXTENSION', -9 );
define( 'PCLZIP_ERR_BAD_FORMAT', -10 );
define( 'PCLZIP_ERR_DELETE_FILE_FAIL', -11 );
define( 'PCLZIP_ERR_RENAME_FILE_FAIL', -12 );
define( 'PCLZIP_ERR_BAD_CHECKSUM', -13 );
define( 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', -14 );
define( 'PCLZIP_ERR_MISSING_OPTION_VALUE', -15 );
define( 'PCLZIP_ERR_INVALID_OPTION_VALUE', -16 );
define( 'PCLZIP_ERR_ALREADY_A_DIRECTORY', -17 );
define( 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', -18 );
define( 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION', -19 );
define( 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE', -20 );
define( 'PCLZIP_ERR_DIRECTORY_RESTRICTION', -21 );
// ----- Options values
define( 'PCLZIP_OPT_PATH', 77001 );
define( 'PCLZIP_OPT_ADD_PATH', 77002 );
define( 'PCLZIP_OPT_REMOVE_PATH', 77003 );
define( 'PCLZIP_OPT_REMOVE_ALL_PATH', 77004 );
define( 'PCLZIP_OPT_SET_CHMOD', 77005 );
define( 'PCLZIP_OPT_EXTRACT_AS_STRING', 77006 );
define( 'PCLZIP_OPT_NO_COMPRESSION', 77007 );
define( 'PCLZIP_OPT_BY_NAME', 77008 );
define( 'PCLZIP_OPT_BY_INDEX', 77009 );
define( 'PCLZIP_OPT_BY_EREG', 77010 );
define( 'PCLZIP_OPT_BY_PREG', 77011 );
define( 'PCLZIP_OPT_COMMENT', 77012 );
define( 'PCLZIP_OPT_ADD_COMMENT', 77013 );
define( 'PCLZIP_OPT_PREPEND_COMMENT', 77014 );
define( 'PCLZIP_OPT_EXTRACT_IN_OUTPUT', 77015 );
define( 'PCLZIP_OPT_REPLACE_NEWER', 77016 );
define( 'PCLZIP_OPT_STOP_ON_ERROR', 77017 );
// Having big trouble with crypt. Need to multiply 2 long int
// which is not correctly supported by PHP ...
//define( 'PCLZIP_OPT_CRYPT', 77018 );
define( 'PCLZIP_OPT_EXTRACT_DIR_RESTRICTION', 77019 );
// ----- File description attributes
define( 'PCLZIP_ATT_FILE_NAME', 79001 );
define( 'PCLZIP_ATT_FILE_NEW_SHORT_NAME', 79002 );
define( 'PCLZIP_ATT_FILE_NEW_FULL_NAME', 79003 );
define( 'PCLZIP_ATT_FILE_MTIME', 79004 );
define( 'PCLZIP_ATT_FILE_CONTENT', 79005 );
define( 'PCLZIP_ATT_FILE_COMMENT', 79006 );
// ----- Call backs values
define( 'PCLZIP_CB_PRE_EXTRACT', 78001 );
define( 'PCLZIP_CB_POST_EXTRACT', 78002 );
define( 'PCLZIP_CB_PRE_ADD', 78003 );
define( 'PCLZIP_CB_POST_ADD', 78004 );
/* For futur use
define( 'PCLZIP_CB_PRE_LIST', 78005 );
define( 'PCLZIP_CB_POST_LIST', 78006 );
define( 'PCLZIP_CB_PRE_DELETE', 78007 );
define( 'PCLZIP_CB_POST_DELETE', 78008 );
*/
// --------------------------------------------------------------------------------
// Class : PclZip
// Description :
// PclZip is the class that represent a Zip archive.
// The public methods allow the manipulation of the archive.
// Attributes :
// Attributes must not be accessed directly.
// Methods :
// PclZip() : Object creator
// create() : Creates the Zip archive
// listContent() : List the content of the Zip archive
// extract() : Extract the content of the archive
// properties() : List the properties of the archive
// --------------------------------------------------------------------------------
class PclZip
{
// ----- Filename of the zip file
var $zipname = '';
// ----- File descriptor of the zip file
var $zip_fd = 0;
// ----- Internal error handling
var $error_code = 1;
var $error_string = '';
// ----- Current status of the magic_quotes_runtime
// This value store the php configuration for magic_quotes
// The class can then disable the magic_quotes and reset it after
var $magic_quotes_status;
// --------------------------------------------------------------------------------
// Function : PclZip()
// Description :
// Creates a PclZip object and set the name of the associated Zip archive
// filename.
// Note that no real action is taken, if the archive does not exist it is not
// created. Use create() for that.
// --------------------------------------------------------------------------------
function PclZip($p_zipname)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::PclZip', "zipname=$p_zipname");
// ----- Tests the zlib
if (!function_exists('gzopen'))
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 1, "zlib extension seems to be missing");
die('Abort '.basename(__FILE__).' : Missing zlib extensions');
}
// ----- Set the attributes
$this->zipname = $p_zipname;
$this->zip_fd = 0;
$this->magic_quotes_status = -1;
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 1);
return;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function :
// create($p_filelist, $p_add_dir="", $p_remove_dir="")
// create($p_filelist, $p_option, $p_option_value, ...)
// Description :
// This method supports two different synopsis. The first one is historical.
// This method creates a Zip Archive. The Zip file is created in the
// filesystem. The files and directories indicated in $p_filelist
// are added in the archive. See the parameters description for the
// supported format of $p_filelist.
// When a directory is in the list, the directory and its content is added
// in the archive.
// In this synopsis, the function takes an optional variable list of
// options. See bellow the supported options.
// Parameters :
// $p_filelist : An array containing file or directory names, or
// a string containing one filename or one directory name, or
// a string containing a list of filenames and/or directory
// names separated by spaces.
// $p_add_dir : A path to add before the real path of the archived file,
// in order to have it memorized in the archive.
// $p_remove_dir : A path to remove from the real path of the file to archive,
// in order to have a shorter path memorized in the archive.
// When $p_add_dir and $p_remove_dir are set, $p_remove_dir
// is removed first, before $p_add_dir is added.
// Options :
// PCLZIP_OPT_ADD_PATH :
// PCLZIP_OPT_REMOVE_PATH :
// PCLZIP_OPT_REMOVE_ALL_PATH :
// PCLZIP_OPT_COMMENT :
// PCLZIP_CB_PRE_ADD :
// PCLZIP_CB_POST_ADD :
// Return Values :
// 0 on failure,
// The list of the added files, with a status of the add action.
// (see PclZip::listContent() for list entry format)
// --------------------------------------------------------------------------------
function create($p_filelist)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::create', "filelist='$p_filelist', ...");
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Set default values
$v_options = array();
$v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE;
// ----- Look for variable options arguments
$v_size = func_num_args();
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "$v_size arguments passed to the method");
// ----- Look for arguments
if ($v_size > 1) {
// ----- Get the arguments
$v_arg_list = func_get_args();
// ----- Remove from the options list the first argument
array_shift($v_arg_list);
$v_size--;
// ----- Look for first arg
if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Variable list of options detected");
// ----- Parse the options
$v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
array (PCLZIP_OPT_REMOVE_PATH => 'optional',
PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
PCLZIP_OPT_ADD_PATH => 'optional',
PCLZIP_CB_PRE_ADD => 'optional',
PCLZIP_CB_POST_ADD => 'optional',
PCLZIP_OPT_NO_COMPRESSION => 'optional',
PCLZIP_OPT_COMMENT => 'optional'
//, PCLZIP_OPT_CRYPT => 'optional'
));
if ($v_result != 1) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return 0;
}
}
// ----- Look for 2 args
// Here we need to support the first historic synopsis of the
// method.
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Static synopsis");
// ----- Get the first argument
$v_options[PCLZIP_OPT_ADD_PATH] = $v_arg_list[0];
// ----- Look for the optional second argument
if ($v_size == 2) {
$v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1];
}
else if ($v_size > 2) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER,
"Invalid number / type of arguments");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return 0;
}
}
}
// ----- Init
$v_string_list = array();
$v_att_list = array();
$v_filedescr_list = array();
$p_result_list = array();
// ----- Look if the $p_filelist is really an array
if (is_array($p_filelist)) {
// ----- Look if the first element is also an array
// This will mean that this is a file description entry
if (isset($p_filelist[0]) && is_array($p_filelist[0])) {
$v_att_list = $p_filelist;
}
// ----- The list is a list of string names
else {
$v_string_list = $p_filelist;
}
}
// ----- Look if the $p_filelist is a string
else if (is_string($p_filelist)) {
// ----- Create a list from the string
$v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist);
}
// ----- Invalid variable type for $p_filelist
else {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return 0;
}
// ----- Reformat the string list
if (sizeof($v_string_list) != 0) {
foreach ($v_string_list as $v_string) {
if ($v_string != '') {
$v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string;
}
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Ignore an empty filename");
}
}
}
// ----- For each file in the list check the attributes
$v_supported_attributes
= array ( PCLZIP_ATT_FILE_NAME => 'mandatory'
,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional'
,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional'
,PCLZIP_ATT_FILE_MTIME => 'optional'
,PCLZIP_ATT_FILE_CONTENT => 'optional'
,PCLZIP_ATT_FILE_COMMENT => 'optional'
);
foreach ($v_att_list as $v_entry) {
$v_result = $this->privFileDescrParseAtt($v_entry,
$v_filedescr_list[],
$v_options,
$v_supported_attributes);
if ($v_result != 1) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return 0;
}
}
// ----- Expand the filelist (expand directories)
$v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options);
if ($v_result != 1) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return 0;
}
// ----- Call the create fct
$v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options);
if ($v_result != 1) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return 0;
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $p_result_list);
return $p_result_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function :
// add($p_filelist, $p_add_dir="", $p_remove_dir="")
// add($p_filelist, $p_option, $p_option_value, ...)
// Description :
// This method supports two synopsis. The first one is historical.
// This methods add the list of files in an existing archive.
// If a file with the same name already exists, it is added at the end of the
// archive, the first one is still present.
// If the archive does not exist, it is created.
// Parameters :
// $p_filelist : An array containing file or directory names, or
// a string containing one filename or one directory name, or
// a string containing a list of filenames and/or directory
// names separated by spaces.
// $p_add_dir : A path to add before the real path of the archived file,
// in order to have it memorized in the archive.
// $p_remove_dir : A path to remove from the real path of the file to archive,
// in order to have a shorter path memorized in the archive.
// When $p_add_dir and $p_remove_dir are set, $p_remove_dir
// is removed first, before $p_add_dir is added.
// Options :
// PCLZIP_OPT_ADD_PATH :
// PCLZIP_OPT_REMOVE_PATH :
// PCLZIP_OPT_REMOVE_ALL_PATH :
// PCLZIP_OPT_COMMENT :
// PCLZIP_OPT_ADD_COMMENT :
// PCLZIP_OPT_PREPEND_COMMENT :
// PCLZIP_CB_PRE_ADD :
// PCLZIP_CB_POST_ADD :
// Return Values :
// 0 on failure,
// The list of the added files, with a status of the add action.
// (see PclZip::listContent() for list entry format)
// --------------------------------------------------------------------------------
function add($p_filelist)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::add', "filelist='$p_filelist', ...");
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Set default values
$v_options = array();
$v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE;
// ----- Look for variable options arguments
$v_size = func_num_args();
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "$v_size arguments passed to the method");
// ----- Look for arguments
if ($v_size > 1) {
// ----- Get the arguments
$v_arg_list = func_get_args();
// ----- Remove form the options list the first argument
array_shift($v_arg_list);
$v_size--;
// ----- Look for first arg
if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Variable list of options detected");
// ----- Parse the options
$v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
array (PCLZIP_OPT_REMOVE_PATH => 'optional',
PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
PCLZIP_OPT_ADD_PATH => 'optional',
PCLZIP_CB_PRE_ADD => 'optional',
PCLZIP_CB_POST_ADD => 'optional',
PCLZIP_OPT_NO_COMPRESSION => 'optional',
PCLZIP_OPT_COMMENT => 'optional',
PCLZIP_OPT_ADD_COMMENT => 'optional',
PCLZIP_OPT_PREPEND_COMMENT => 'optional'
//, PCLZIP_OPT_CRYPT => 'optional'
));
if ($v_result != 1) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return 0;
}
}
// ----- Look for 2 args
// Here we need to support the first historic synopsis of the
// method.
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Static synopsis");
// ----- Get the first argument
$v_options[PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0];
// ----- Look for the optional second argument
if ($v_size == 2) {
$v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1];
}
else if ($v_size > 2) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return 0;
}
}
}
// ----- Init
$v_string_list = array();
$v_att_list = array();
$v_filedescr_list = array();
$p_result_list = array();
// ----- Look if the $p_filelist is really an array
if (is_array($p_filelist)) {
// ----- Look if the first element is also an array
// This will mean that this is a file description entry
if (isset($p_filelist[0]) && is_array($p_filelist[0])) {
$v_att_list = $p_filelist;
}
// ----- The list is a list of string names
else {
$v_string_list = $p_filelist;
}
}
// ----- Look if the $p_filelist is a string
else if (is_string($p_filelist)) {
// ----- Create a list from the string
$v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist);
}
// ----- Invalid variable type for $p_filelist
else {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return 0;
}
// ----- Reformat the string list
if (sizeof($v_string_list) != 0) {
foreach ($v_string_list as $v_string) {
$v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string;
}
}
// ----- For each file in the list check the attributes
$v_supported_attributes
= array ( PCLZIP_ATT_FILE_NAME => 'mandatory'
,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional'
,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional'
,PCLZIP_ATT_FILE_MTIME => 'optional'
,PCLZIP_ATT_FILE_CONTENT => 'optional'
,PCLZIP_ATT_FILE_COMMENT => 'optional'
);
foreach ($v_att_list as $v_entry) {
$v_result = $this->privFileDescrParseAtt($v_entry,
$v_filedescr_list[],
$v_options,
$v_supported_attributes);
if ($v_result != 1) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return 0;
}
}
// ----- Expand the filelist (expand directories)
$v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options);
if ($v_result != 1) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return 0;
}
// ----- Call the create fct
$v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options);
if ($v_result != 1) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return 0;
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $p_result_list);
return $p_result_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : listContent()
// Description :
// This public method, gives the list of the files and directories, with their
// properties.
// The properties of each entries in the list are (used also in other functions) :
// filename : Name of the file. For a create or add action it is the filename
// given by the user. For an extract function it is the filename
// of the extracted file.
// stored_filename : Name of the file / directory stored in the archive.
// size : Size of the stored file.
// compressed_size : Size of the file's data compressed in the archive
// (without the headers overhead)
// mtime : Last known modification date of the file (UNIX timestamp)
// comment : Comment associated with the file
// folder : true | false
// index : index of the file in the archive
// status : status of the action (depending of the action) :
// Values are :
// ok : OK !
// filtered : the file / dir is not extracted (filtered by user)
// already_a_directory : the file can not be extracted because a
// directory with the same name already exists
// write_protected : the file can not be extracted because a file
// with the same name already exists and is
// write protected
// newer_exist : the file was not extracted because a newer file exists
// path_creation_fail : the file is not extracted because the folder
// does not exists and can not be created
// write_error : the file was not extracted because there was a
// error while writing the file
// read_error : the file was not extracted because there was a error
// while reading the file
// invalid_header : the file was not extracted because of an archive
// format error (bad file header)
// Note that each time a method can continue operating when there
// is an action error on a file, the error is only logged in the file status.
// Return Values :
// 0 on an unrecoverable failure,
// The list of the files in the archive.
// --------------------------------------------------------------------------------
function listContent()
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::listContent', "");
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Check archive
if (!$this->privCheckFormat()) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return(0);
}
// ----- Call the extracting fct
$p_list = array();
if (($v_result = $this->privList($p_list)) != 1)
{
unset($p_list);
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0, PclZip::errorInfo());
return(0);
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $p_list);
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function :
// extract($p_path="./", $p_remove_path="")
// extract([$p_option, $p_option_value, ...])
// Description :
// This method supports two synopsis. The first one is historical.
// This method extract all the files / directories from the archive to the
// folder indicated in $p_path.
// If you want to ignore the 'root' part of path of the memorized files
// you can indicate this in the optional $p_remove_path parameter.
// By default, if a newer file with the same name already exists, the
// file is not extracted.
//
// If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions
// are used, the path indicated in PCLZIP_OPT_ADD_PATH is append
// at the end of the path value of PCLZIP_OPT_PATH.
// Parameters :
// $p_path : Path where the files and directories are to be extracted
// $p_remove_path : First part ('root' part) of the memorized path
// (if any similar) to remove while extracting.
// Options :
// PCLZIP_OPT_PATH :
// PCLZIP_OPT_ADD_PATH :
// PCLZIP_OPT_REMOVE_PATH :
// PCLZIP_OPT_REMOVE_ALL_PATH :
// PCLZIP_CB_PRE_EXTRACT :
// PCLZIP_CB_POST_EXTRACT :
// Return Values :
// 0 or a negative value on failure,
// The list of the extracted files, with a status of the action.
// (see PclZip::listContent() for list entry format)
// --------------------------------------------------------------------------------
function extract()
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::extract", "");
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Check archive
if (!$this->privCheckFormat()) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return(0);
}
// ----- Set default values
$v_options = array();
// $v_path = "./";
$v_path = '';
$v_remove_path = "";
$v_remove_all_path = false;
// ----- Look for variable options arguments
$v_size = func_num_args();
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "$v_size arguments passed to the method");
// ----- Default values for option
$v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE;
// ----- Look for arguments
if ($v_size > 0) {
// ----- Get the arguments
$v_arg_list = func_get_args();
// ----- Look for first arg
if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Variable list of options");
// ----- Parse the options
$v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
array (PCLZIP_OPT_PATH => 'optional',
PCLZIP_OPT_REMOVE_PATH => 'optional',
PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
PCLZIP_OPT_ADD_PATH => 'optional',
PCLZIP_CB_PRE_EXTRACT => 'optional',
PCLZIP_CB_POST_EXTRACT => 'optional',
PCLZIP_OPT_SET_CHMOD => 'optional',
PCLZIP_OPT_BY_NAME => 'optional',
PCLZIP_OPT_BY_EREG => 'optional',
PCLZIP_OPT_BY_PREG => 'optional',
PCLZIP_OPT_BY_INDEX => 'optional',
PCLZIP_OPT_EXTRACT_AS_STRING => 'optional',
PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional',
PCLZIP_OPT_REPLACE_NEWER => 'optional'
,PCLZIP_OPT_STOP_ON_ERROR => 'optional'
,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional'
));
if ($v_result != 1) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return 0;
}
// ----- Set the arguments
if (isset($v_options[PCLZIP_OPT_PATH])) {
$v_path = $v_options[PCLZIP_OPT_PATH];
}
if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) {
$v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH];
}
if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) {
$v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH];
}
if (isset($v_options[PCLZIP_OPT_ADD_PATH])) {
// ----- Check for '/' in last path char
if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) {
$v_path .= '/';
}
$v_path .= $v_options[PCLZIP_OPT_ADD_PATH];
}
}
// ----- Look for 2 args
// Here we need to support the first historic synopsis of the
// method.
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Static synopsis");
// ----- Get the first argument
$v_path = $v_arg_list[0];
// ----- Look for the optional second argument
if ($v_size == 2) {
$v_remove_path = $v_arg_list[1];
}
else if ($v_size > 2) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0, PclZip::errorInfo());
return 0;
}
}
}
// ----- Trace
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "path='$v_path', remove_path='$v_remove_path', remove_all_path='".($v_remove_path?'true':'false')."'");
// ----- Call the extracting fct
$p_list = array();
$v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path,
$v_remove_all_path, $v_options);
if ($v_result < 1) {
unset($p_list);
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0, PclZip::errorInfo());
return(0);
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $p_list);
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function :
// extractByIndex($p_index, $p_path="./", $p_remove_path="")
// extractByIndex($p_index, [$p_option, $p_option_value, ...])
// Description :
// This method supports two synopsis. The first one is historical.
// This method is doing a partial extract of the archive.
// The extracted files or folders are identified by their index in the
// archive (from 0 to n).
// Note that if the index identify a folder, only the folder entry is
// extracted, not all the files included in the archive.
// Parameters :
// $p_index : A single index (integer) or a string of indexes of files to
// extract. The form of the string is "0,4-6,8-12" with only numbers
// and '-' for range or ',' to separate ranges. No spaces or ';'
// are allowed.
// $p_path : Path where the files and directories are to be extracted
// $p_remove_path : First part ('root' part) of the memorized path
// (if any similar) to remove while extracting.
// Options :
// PCLZIP_OPT_PATH :
// PCLZIP_OPT_ADD_PATH :
// PCLZIP_OPT_REMOVE_PATH :
// PCLZIP_OPT_REMOVE_ALL_PATH :
// PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and
// not as files.
// The resulting content is in a new field 'content' in the file
// structure.
// This option must be used alone (any other options are ignored).
// PCLZIP_CB_PRE_EXTRACT :
// PCLZIP_CB_POST_EXTRACT :
// Return Values :
// 0 on failure,
// The list of the extracted files, with a status of the action.
// (see PclZip::listContent() for list entry format)
// --------------------------------------------------------------------------------
//function extractByIndex($p_index, options...)
function extractByIndex($p_index)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::extractByIndex", "index='$p_index', ...");
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Check archive
if (!$this->privCheckFormat()) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return(0);
}
// ----- Set default values
$v_options = array();
// $v_path = "./";
$v_path = '';
$v_remove_path = "";
$v_remove_all_path = false;
// ----- Look for variable options arguments
$v_size = func_num_args();
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "$v_size arguments passed to the method");
// ----- Default values for option
$v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE;
// ----- Look for arguments
if ($v_size > 1) {
// ----- Get the arguments
$v_arg_list = func_get_args();
// ----- Remove form the options list the first argument
array_shift($v_arg_list);
$v_size--;
// ----- Look for first arg
if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Variable list of options");
// ----- Parse the options
$v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
array (PCLZIP_OPT_PATH => 'optional',
PCLZIP_OPT_REMOVE_PATH => 'optional',
PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
PCLZIP_OPT_EXTRACT_AS_STRING => 'optional',
PCLZIP_OPT_ADD_PATH => 'optional',
PCLZIP_CB_PRE_EXTRACT => 'optional',
PCLZIP_CB_POST_EXTRACT => 'optional',
PCLZIP_OPT_SET_CHMOD => 'optional',
PCLZIP_OPT_REPLACE_NEWER => 'optional'
,PCLZIP_OPT_STOP_ON_ERROR => 'optional'
,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional'
));
if ($v_result != 1) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return 0;
}
// ----- Set the arguments
if (isset($v_options[PCLZIP_OPT_PATH])) {
$v_path = $v_options[PCLZIP_OPT_PATH];
}
if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) {
$v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH];
}
if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) {
$v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH];
}
if (isset($v_options[PCLZIP_OPT_ADD_PATH])) {
// ----- Check for '/' in last path char
if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) {
$v_path .= '/';
}
$v_path .= $v_options[PCLZIP_OPT_ADD_PATH];
}
if (!isset($v_options[PCLZIP_OPT_EXTRACT_AS_STRING])) {
$v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE;
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Option PCLZIP_OPT_EXTRACT_AS_STRING not set.");
}
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Option PCLZIP_OPT_EXTRACT_AS_STRING set.");
}
}
// ----- Look for 2 args
// Here we need to support the first historic synopsis of the
// method.
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Static synopsis");
// ----- Get the first argument
$v_path = $v_arg_list[0];
// ----- Look for the optional second argument
if ($v_size == 2) {
$v_remove_path = $v_arg_list[1];
}
else if ($v_size > 2) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return 0;
}
}
}
// ----- Trace
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "index='$p_index', path='$v_path', remove_path='$v_remove_path', remove_all_path='".($v_remove_path?'true':'false')."'");
// ----- Trick
// Here I want to reuse extractByRule(), so I need to parse the $p_index
// with privParseOptions()
$v_arg_trick = array (PCLZIP_OPT_BY_INDEX, $p_index);
$v_options_trick = array();
$v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick,
array (PCLZIP_OPT_BY_INDEX => 'optional' ));
if ($v_result != 1) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return 0;
}
$v_options[PCLZIP_OPT_BY_INDEX] = $v_options_trick[PCLZIP_OPT_BY_INDEX];
// ----- Call the extracting fct
if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0, PclZip::errorInfo());
return(0);
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $p_list);
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function :
// delete([$p_option, $p_option_value, ...])
// Description :
// This method removes files from the archive.
// If no parameters are given, then all the archive is emptied.
// Parameters :
// None or optional arguments.
// Options :
// PCLZIP_OPT_BY_INDEX :
// PCLZIP_OPT_BY_NAME :
// PCLZIP_OPT_BY_EREG :
// PCLZIP_OPT_BY_PREG :
// Return Values :
// 0 on failure,
// The list of the files which are still present in the archive.
// (see PclZip::listContent() for list entry format)
// --------------------------------------------------------------------------------
function delete()
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::delete", "");
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Check archive
if (!$this->privCheckFormat()) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return(0);
}
// ----- Set default values
$v_options = array();
// ----- Look for variable options arguments
$v_size = func_num_args();
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "$v_size arguments passed to the method");
// ----- Look for arguments
if ($v_size > 0) {
// ----- Get the arguments
$v_arg_list = func_get_args();
// ----- Parse the options
$v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
array (PCLZIP_OPT_BY_NAME => 'optional',
PCLZIP_OPT_BY_EREG => 'optional',
PCLZIP_OPT_BY_PREG => 'optional',
PCLZIP_OPT_BY_INDEX => 'optional' ));
if ($v_result != 1) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return 0;
}
}
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Call the delete fct
$v_list = array();
if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) {
$this->privSwapBackMagicQuotes();
unset($v_list);
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0, PclZip::errorInfo());
return(0);
}
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_list);
return $v_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : deleteByIndex()
// Description :
// ***** Deprecated *****
// delete(PCLZIP_OPT_BY_INDEX, $p_index) should be prefered.
// --------------------------------------------------------------------------------
function deleteByIndex($p_index)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::deleteByIndex", "index='$p_index'");
$p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index);
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $p_list);
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : properties()
// Description :
// This method gives the properties of the archive.
// The properties are :
// nb : Number of files in the archive
// comment : Comment associated with the archive file
// status : not_exist, ok
// Parameters :
// None
// Return Values :
// 0 on failure,
// An array with the archive properties.
// --------------------------------------------------------------------------------
function properties()
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::properties", "");
// ----- Reset the error handler
$this->privErrorReset();
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Check archive
if (!$this->privCheckFormat()) {
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return(0);
}
// ----- Default properties
$v_prop = array();
$v_prop['comment'] = '';
$v_prop['nb'] = 0;
$v_prop['status'] = 'not_exist';
// ----- Look if file exists
if (@is_file($this->zipname))
{
// ----- Open the zip file
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode");
if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0)
{
$this->privSwapBackMagicQuotes();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), 0);
return 0;
}
// ----- Read the central directory informations
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return 0;
}
// ----- Close the zip file
$this->privCloseFd();
// ----- Set the user attributes
$v_prop['comment'] = $v_central_dir['comment'];
$v_prop['nb'] = $v_central_dir['entries'];
$v_prop['status'] = 'ok';
}
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_prop);
return $v_prop;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : duplicate()
// Description :
// This method creates an archive by copying the content of an other one. If
// the archive already exist, it is replaced by the new one without any warning.
// Parameters :
// $p_archive : The filename of a valid archive, or
// a valid PclZip object.
// Return Values :
// 1 on success.
// 0 or a negative value on error (error code).
// --------------------------------------------------------------------------------
function duplicate($p_archive)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::duplicate", "");
$v_result = 1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Look if the $p_archive is a PclZip object
if ((is_object($p_archive)) && (get_class($p_archive) == 'pclzip'))
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "The parameter is valid PclZip object '".$p_archive->zipname."'");
// ----- Duplicate the archive
$v_result = $this->privDuplicate($p_archive->zipname);
}
// ----- Look if the $p_archive is a string (so a filename)
else if (is_string($p_archive))
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "The parameter is a filename '$p_archive'");
// ----- Check that $p_archive is a valid zip file
// TBC : Should also check the archive format
if (!is_file($p_archive)) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '".$p_archive."'");
$v_result = PCLZIP_ERR_MISSING_FILE;
}
else {
// ----- Duplicate the archive
$v_result = $this->privDuplicate($p_archive);
}
}
// ----- Invalid variable
else
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add");
$v_result = PCLZIP_ERR_INVALID_PARAMETER;
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : merge()
// Description :
// This method merge the $p_archive_to_add archive at the end of the current
// one ($this).
// If the archive ($this) does not exist, the merge becomes a duplicate.
// If the $p_archive_to_add archive does not exist, the merge is a success.
// Parameters :
// $p_archive_to_add : It can be directly the filename of a valid zip archive,
// or a PclZip object archive.
// Return Values :
// 1 on success,
// 0 or negative values on error (see below).
// --------------------------------------------------------------------------------
function merge($p_archive_to_add)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::merge", "");
$v_result = 1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Check archive
if (!$this->privCheckFormat()) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return(0);
}
// ----- Look if the $p_archive_to_add is a PclZip object
if ((is_object($p_archive_to_add)) && (get_class($p_archive_to_add) == 'pclzip'))
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The parameter is valid PclZip object");
// ----- Merge the archive
$v_result = $this->privMerge($p_archive_to_add);
}
// ----- Look if the $p_archive_to_add is a string (so a filename)
else if (is_string($p_archive_to_add))
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The parameter is a filename");
// ----- Create a temporary archive
$v_object_archive = new PclZip($p_archive_to_add);
// ----- Merge the archive
$v_result = $this->privMerge($v_object_archive);
}
// ----- Invalid variable
else
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add");
$v_result = PCLZIP_ERR_INVALID_PARAMETER;
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : errorCode()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function errorCode()
{
if (PCLZIP_ERROR_EXTERNAL == 1) {
return(PclErrorCode());
}
else {
return($this->error_code);
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : errorName()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function errorName($p_with_code=false)
{
$v_name = array ( PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR',
PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL',
PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL',
PCLZIP_ERR_INVALID_PARAMETER => 'PCLZIP_ERR_INVALID_PARAMETER',
PCLZIP_ERR_MISSING_FILE => 'PCLZIP_ERR_MISSING_FILE',
PCLZIP_ERR_FILENAME_TOO_LONG => 'PCLZIP_ERR_FILENAME_TOO_LONG',
PCLZIP_ERR_INVALID_ZIP => 'PCLZIP_ERR_INVALID_ZIP',
PCLZIP_ERR_BAD_EXTRACTED_FILE => 'PCLZIP_ERR_BAD_EXTRACTED_FILE',
PCLZIP_ERR_DIR_CREATE_FAIL => 'PCLZIP_ERR_DIR_CREATE_FAIL',
PCLZIP_ERR_BAD_EXTENSION => 'PCLZIP_ERR_BAD_EXTENSION',
PCLZIP_ERR_BAD_FORMAT => 'PCLZIP_ERR_BAD_FORMAT',
PCLZIP_ERR_DELETE_FILE_FAIL => 'PCLZIP_ERR_DELETE_FILE_FAIL',
PCLZIP_ERR_RENAME_FILE_FAIL => 'PCLZIP_ERR_RENAME_FILE_FAIL',
PCLZIP_ERR_BAD_CHECKSUM => 'PCLZIP_ERR_BAD_CHECKSUM',
PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP',
PCLZIP_ERR_MISSING_OPTION_VALUE => 'PCLZIP_ERR_MISSING_OPTION_VALUE',
PCLZIP_ERR_INVALID_OPTION_VALUE => 'PCLZIP_ERR_INVALID_OPTION_VALUE',
PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION',
PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION'
,PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE'
,PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION'
);
if (isset($v_name[$this->error_code])) {
$v_value = $v_name[$this->error_code];
}
else {
$v_value = 'NoName';
}
if ($p_with_code) {
return($v_value.' ('.$this->error_code.')');
}
else {
return($v_value);
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : errorInfo()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function errorInfo($p_full=false)
{
if (PCLZIP_ERROR_EXTERNAL == 1) {
return(PclErrorString());
}
else {
if ($p_full) {
return($this->errorName(true)." : ".$this->error_string);
}
else {
return($this->error_string." [code ".$this->error_code."]");
}
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS *****
// ***** *****
// ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY *****
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCheckFormat()
// Description :
// This method check that the archive exists and is a valid zip archive.
// Several level of check exists. (futur)
// Parameters :
// $p_level : Level of check. Default 0.
// 0 : Check the first bytes (magic codes) (default value))
// 1 : 0 + Check the central directory (futur)
// 2 : 1 + Check each file header (futur)
// Return Values :
// true on success,
// false on error, the error code is set.
// --------------------------------------------------------------------------------
function privCheckFormat($p_level=0)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privCheckFormat", "");
$v_result = true;
// ----- Reset the file system cache
clearstatcache();
// ----- Reset the error handler
$this->privErrorReset();
// ----- Look if the file exits
if (!is_file($this->zipname)) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, false, PclZip::errorInfo());
return(false);
}
// ----- Check that the file is readeable
if (!is_readable($this->zipname)) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, false, PclZip::errorInfo());
return(false);
}
// ----- Check the magic code
// TBC
// ----- Check the central header
// TBC
// ----- Check each file header
// TBC
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privParseOptions()
// Description :
// This internal methods reads the variable list of arguments ($p_options_list,
// $p_size) and generate an array with the options and values ($v_result_list).
// $v_requested_options contains the options that can be present and those that
// must be present.
// $v_requested_options is an array, with the option value as key, and 'optional',
// or 'mandatory' as value.
// Parameters :
// See above.
// Return Values :
// 1 on success.
// 0 on failure.
// --------------------------------------------------------------------------------
function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options=false)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privParseOptions", "");
$v_result=1;
// ----- Read the options
$i=0;
while ($i<$p_size) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Looking for table index $i, option = '".PclZipUtilOptionText($p_options_list[$i])."(".$p_options_list[$i].")'");
// ----- Check if the option is supported
if (!isset($v_requested_options[$p_options_list[$i]])) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '".$p_options_list[$i]."' for this method");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Look for next option
switch ($p_options_list[$i]) {
// ----- Look for options that request a path value
case PCLZIP_OPT_PATH :
case PCLZIP_OPT_REMOVE_PATH :
case PCLZIP_OPT_ADD_PATH :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Get the value
$v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'");
$i++;
break;
case PCLZIP_OPT_EXTRACT_DIR_RESTRICTION :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Get the value
if ( is_string($p_options_list[$i+1])
&& ($p_options_list[$i+1] != '')) {
$v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'");
$i++;
}
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." set with an empty value is ignored.");
}
break;
// ----- Look for options that request an array of string for value
case PCLZIP_OPT_BY_NAME :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Get the value
if (is_string($p_options_list[$i+1])) {
$v_result_list[$p_options_list[$i]][0] = $p_options_list[$i+1];
}
else if (is_array($p_options_list[$i+1])) {
$v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
}
else {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
////--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'");
$i++;
break;
// ----- Look for options that request an EREG or PREG expression
case PCLZIP_OPT_BY_EREG :
case PCLZIP_OPT_BY_PREG :
//case PCLZIP_OPT_CRYPT :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Get the value
if (is_string($p_options_list[$i+1])) {
$v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
}
else {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'");
$i++;
break;
// ----- Look for options that takes a string
case PCLZIP_OPT_COMMENT :
case PCLZIP_OPT_ADD_COMMENT :
case PCLZIP_OPT_PREPEND_COMMENT :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE,
"Missing parameter value for option '"
.PclZipUtilOptionText($p_options_list[$i])
."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Get the value
if (is_string($p_options_list[$i+1])) {
$v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
}
else {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE,
"Wrong parameter value for option '"
.PclZipUtilOptionText($p_options_list[$i])
."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'");
$i++;
break;
// ----- Look for options that request an array of index
case PCLZIP_OPT_BY_INDEX :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Get the value
$v_work_list = array();
if (is_string($p_options_list[$i+1])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Index value is a string '".$p_options_list[$i+1]."'");
// ----- Remove spaces
$p_options_list[$i+1] = strtr($p_options_list[$i+1], ' ', '');
// ----- Parse items
$v_work_list = explode(",", $p_options_list[$i+1]);
}
else if (is_integer($p_options_list[$i+1])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Index value is an integer '".$p_options_list[$i+1]."'");
$v_work_list[0] = $p_options_list[$i+1].'-'.$p_options_list[$i+1];
}
else if (is_array($p_options_list[$i+1])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Index value is an array");
$v_work_list = $p_options_list[$i+1];
}
else {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Reduce the index list
// each index item in the list must be a couple with a start and
// an end value : [0,3], [5-5], [8-10], ...
// ----- Check the format of each item
$v_sort_flag=false;
$v_sort_value=0;
for ($j=0; $j<sizeof($v_work_list); $j++) {
// ----- Explode the item
$v_item_list = explode("-", $v_work_list[$j]);
$v_size_item_list = sizeof($v_item_list);
// ----- TBC : Here we might check that each item is a
// real integer ...
// ----- Look for single value
if ($v_size_item_list == 1) {
// ----- Set the option value
$v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0];
$v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[0];
}
elseif ($v_size_item_list == 2) {
// ----- Set the option value
$v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0];
$v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[1];
}
else {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Too many values in index range for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extracted index item = [".$v_result_list[$p_options_list[$i]][$j]['start'].",".$v_result_list[$p_options_list[$i]][$j]['end']."]");
// ----- Look for list sort
if ($v_result_list[$p_options_list[$i]][$j]['start'] < $v_sort_value) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The list should be sorted ...");
$v_sort_flag=true;
// ----- TBC : An automatic sort should be writen ...
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Invalid order of index range for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
$v_sort_value = $v_result_list[$p_options_list[$i]][$j]['start'];
}
// ----- Sort the items
if ($v_sort_flag) {
// TBC : To Be Completed
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "List sorting is not yet write ...");
}
// ----- Next option
$i++;
break;
// ----- Look for options that request no value
case PCLZIP_OPT_REMOVE_ALL_PATH :
case PCLZIP_OPT_EXTRACT_AS_STRING :
case PCLZIP_OPT_NO_COMPRESSION :
case PCLZIP_OPT_EXTRACT_IN_OUTPUT :
case PCLZIP_OPT_REPLACE_NEWER :
case PCLZIP_OPT_STOP_ON_ERROR :
$v_result_list[$p_options_list[$i]] = true;
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'");
break;
// ----- Look for options that request an octal value
case PCLZIP_OPT_SET_CHMOD :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Get the value
$v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'");
$i++;
break;
// ----- Look for options that request a call-back
case PCLZIP_CB_PRE_EXTRACT :
case PCLZIP_CB_POST_EXTRACT :
case PCLZIP_CB_PRE_ADD :
case PCLZIP_CB_POST_ADD :
/* for futur use
case PCLZIP_CB_PRE_DELETE :
case PCLZIP_CB_POST_DELETE :
case PCLZIP_CB_PRE_LIST :
case PCLZIP_CB_POST_LIST :
*/
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Get the value
$v_function_name = $p_options_list[$i+1];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "call-back ".PclZipUtilOptionText($p_options_list[$i])." = '".$v_function_name."'");
// ----- Check that the value is a valid existing function
if (!function_exists($v_function_name)) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Function '".$v_function_name."()' is not an existing function for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Set the attribute
$v_result_list[$p_options_list[$i]] = $v_function_name;
$i++;
break;
default :
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER,
"Unknown parameter '"
.$p_options_list[$i]."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Next options
$i++;
}
// ----- Look for mandatory options
if ($v_requested_options !== false) {
for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) {
// ----- Look for mandatory option
if ($v_requested_options[$key] == 'mandatory') {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Detect a mandatory option : ".PclZipUtilOptionText($key)."(".$key.")");
// ----- Look if present
if (!isset($v_result_list[$key])) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
}
}
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privFileDescrParseAtt()
// Description :
// Parameters :
// Return Values :
// 1 on success.
// 0 on failure.
// --------------------------------------------------------------------------------
function privFileDescrParseAtt(&$p_file_list, &$p_filedescr, $v_options, $v_requested_options=false)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privFileDescrParseAtt", "");
$v_result=1;
// ----- For each file in the list check the attributes
foreach ($p_file_list as $v_key => $v_value) {
// ----- Check if the option is supported
if (!isset($v_requested_options[$v_key])) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file attribute '".$v_key."' for this file");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Look for attribute
switch ($v_key) {
case PCLZIP_ATT_FILE_NAME :
if (!is_string($v_value)) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
$p_filedescr['filename'] = PclZipUtilPathReduction($v_value);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($v_key)." = '".$v_value."'");
if ($p_filedescr['filename'] == '') {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty filename for attribute '".PclZipUtilOptionText($v_key)."'");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
break;
case PCLZIP_ATT_FILE_NEW_SHORT_NAME :
if (!is_string($v_value)) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
$p_filedescr['new_short_name'] = PclZipUtilPathReduction($v_value);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($v_key)." = '".$v_value."'");
if ($p_filedescr['new_short_name'] == '') {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty short filename for attribute '".PclZipUtilOptionText($v_key)."'");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
break;
case PCLZIP_ATT_FILE_NEW_FULL_NAME :
if (!is_string($v_value)) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
$p_filedescr['new_full_name'] = PclZipUtilPathReduction($v_value);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($v_key)." = '".$v_value."'");
if ($p_filedescr['new_full_name'] == '') {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty full filename for attribute '".PclZipUtilOptionText($v_key)."'");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
break;
// ----- Look for options that takes a string
case PCLZIP_ATT_FILE_COMMENT :
if (!is_string($v_value)) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
$p_filedescr['comment'] = $v_value;
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($v_key)." = '".$v_value."'");
break;
case PCLZIP_ATT_FILE_MTIME :
if (!is_integer($v_value)) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". Integer expected for attribute '".PclZipUtilOptionText($v_key)."'");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
$p_filedescr['mtime'] = $v_value;
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($v_key)." = '".$v_value."'");
break;
case PCLZIP_ATT_FILE_CONTENT :
$p_filedescr['content'] = $v_value;
////--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($v_key)." = '".$v_value."'");
break;
default :
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER,
"Unknown parameter '".$v_key."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Look for mandatory options
if ($v_requested_options !== false) {
for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) {
// ----- Look for mandatory option
if ($v_requested_options[$key] == 'mandatory') {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Detect a mandatory option : ".PclZipUtilOptionText($key)."(".$key.")");
// ----- Look if present
if (!isset($p_file_list[$key])) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
}
}
}
// end foreach
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privFileDescrExpand()
// Description :
// Parameters :
// Return Values :
// 1 on success.
// 0 on failure.
// --------------------------------------------------------------------------------
function privFileDescrExpand(&$p_filedescr_list, &$p_options)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privFileDescrExpand", "");
$v_result=1;
// ----- Create a result list
$v_result_list = array();
// ----- Look each entry
for ($i=0; $i<sizeof($p_filedescr_list); $i++) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Looking for file ".$i.".");
// ----- Get filedescr
$v_descr = $p_filedescr_list[$i];
// ----- Reduce the filename
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Filedescr before reduction :'".$v_descr['filename']."'");
$v_descr['filename'] = PclZipUtilTranslateWinPath($v_descr['filename']);
$v_descr['filename'] = PclZipUtilPathReduction($v_descr['filename']);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Filedescr after reduction :'".$v_descr['filename']."'");
// ----- Look for real file or folder
if (file_exists($v_descr['filename'])) {
if (@is_file($v_descr['filename'])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "This is a file");
$v_descr['type'] = 'file';
}
else if (@is_dir($v_descr['filename'])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "This is a folder");
$v_descr['type'] = 'folder';
}
else if (@is_link($v_descr['filename'])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Unsupported file type : link");
// skip
continue;
}
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Unsupported file type : unknown type");
// skip
continue;
}
}
// ----- Look for string added as file
else if (isset($v_descr['content'])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "This is a string added as a file");
$v_descr['type'] = 'virtual_file';
}
// ----- Missing file
else {
// ----- Error log
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File '".$v_descr['filename']."' does not exists");
PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "File '".$v_descr['filename']."' does not exists");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Calculate the stored filename
$this->privCalculateStoredFilename($v_descr, $p_options);
// ----- Add the descriptor in result list
$v_result_list[sizeof($v_result_list)] = $v_descr;
// ----- Look for folder
if ($v_descr['type'] == 'folder') {
// ----- List of items in folder
$v_dirlist_descr = array();
$v_dirlist_nb = 0;
if ($v_folder_handler = @opendir($v_descr['filename'])) {
while (($v_item_handler = @readdir($v_folder_handler)) !== false) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Looking for '".$v_item_handler."' in the directory");
// ----- Skip '.' and '..'
if (($v_item_handler == '.') || ($v_item_handler == '..')) {
continue;
}
// ----- Compose the full filename
$v_dirlist_descr[$v_dirlist_nb]['filename'] = $v_descr['filename'].'/'.$v_item_handler;
// ----- Look for different stored filename
// Because the name of the folder was changed, the name of the
// files/sub-folders also change
if ($v_descr['stored_filename'] != $v_descr['filename']) {
if ($v_descr['stored_filename'] != '') {
$v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_descr['stored_filename'].'/'.$v_item_handler;
}
else {
$v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_item_handler;
}
}
$v_dirlist_nb++;
}
@closedir($v_folder_handler);
}
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unable to open dir '".$v_descr['filename']."' in read mode. Skipped.");
// TBC : unable to open folder in read mode
}
// ----- Expand each element of the list
if ($v_dirlist_nb != 0) {
// ----- Expand
if (($v_result = $this->privFileDescrExpand($v_dirlist_descr, $p_options)) != 1) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Concat the resulting list
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Merging result list (size '".sizeof($v_result_list)."') with dirlist (size '".sizeof($v_dirlist_descr)."')");
$v_result_list = array_merge($v_result_list, $v_dirlist_descr);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "merged result list is size '".sizeof($v_result_list)."'");
}
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Nothing in this folder to expand.");
}
// ----- Free local array
unset($v_dirlist_descr);
}
}
// ----- Get the result list
$p_filedescr_list = $v_result_list;
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCreate()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privCreate($p_filedescr_list, &$p_result_list, &$p_options)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privCreate", "list");
$v_result=1;
$v_list_detail = array();
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Open the file in write mode
if (($v_result = $this->privOpenFd('wb')) != 1)
{
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Add the list of files
$v_result = $this->privAddList($p_filedescr_list, $p_result_list, $p_options);
// ----- Close
$this->privCloseFd();
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privAdd()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privAdd($p_filedescr_list, &$p_result_list, &$p_options)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privAdd", "list");
$v_result=1;
$v_list_detail = array();
// ----- Look if the archive exists or is empty
if ((!is_file($this->zipname)) || (filesize($this->zipname) == 0))
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Archive does not exist, or is empty, create it.");
// ----- Do a create
$v_result = $this->privCreate($p_filedescr_list, $p_result_list, $p_options);
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Open the zip file
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode");
if (($v_result=$this->privOpenFd('rb')) != 1)
{
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Read the central directory informations
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Go to beginning of File
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in file : ".ftell($this->zip_fd)."'");
@rewind($this->zip_fd);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in file : ".ftell($this->zip_fd)."'");
// ----- Creates a temporay file
$v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
// ----- Open the temporary file in write mode
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode");
if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0)
{
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Copy the files from the archive to the temporary file
// TBC : Here I should better append the file and go back to erase the central dir
$v_size = $v_central_dir['offset'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes");
$v_buffer = fread($this->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Swap the file descriptor
// Here is a trick : I swap the temporary fd with the zip fd, in order to use
// the following methods on the temporary fil and not the real archive
$v_swap = $this->zip_fd;
$this->zip_fd = $v_zip_temp_fd;
$v_zip_temp_fd = $v_swap;
// ----- Add the files
$v_header_list = array();
if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1)
{
fclose($v_zip_temp_fd);
$this->privCloseFd();
@unlink($v_zip_temp_name);
$this->privSwapBackMagicQuotes();
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Store the offset of the central dir
$v_offset = @ftell($this->zip_fd);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "New offset of central dir : $v_offset");
// ----- Copy the block of file headers from the old archive
$v_size = $v_central_dir['size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes");
$v_buffer = @fread($v_zip_temp_fd, $v_read_size);
@fwrite($this->zip_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Create the Central Dir files header
for ($i=0, $v_count=0; $i<sizeof($v_header_list); $i++)
{
// ----- Create the file header
if ($v_header_list[$i]['status'] == 'ok') {
if (($v_result = $this->privWriteCentralFileHeader($v_header_list[$i])) != 1) {
fclose($v_zip_temp_fd);
$this->privCloseFd();
@unlink($v_zip_temp_name);
$this->privSwapBackMagicQuotes();
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
$v_count++;
}
// ----- Transform the header to a 'usable' info
$this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
}
// ----- Zip file comment
$v_comment = $v_central_dir['comment'];
if (isset($p_options[PCLZIP_OPT_COMMENT])) {
$v_comment = $p_options[PCLZIP_OPT_COMMENT];
}
if (isset($p_options[PCLZIP_OPT_ADD_COMMENT])) {
$v_comment = $v_comment.$p_options[PCLZIP_OPT_ADD_COMMENT];
}
if (isset($p_options[PCLZIP_OPT_PREPEND_COMMENT])) {
$v_comment = $p_options[PCLZIP_OPT_PREPEND_COMMENT].$v_comment;
}
// ----- Calculate the size of the central header
$v_size = @ftell($this->zip_fd)-$v_offset;
// ----- Create the central dir footer
if (($v_result = $this->privWriteCentralHeader($v_count+$v_central_dir['entries'], $v_size, $v_offset, $v_comment)) != 1)
{
// ----- Reset the file list
unset($v_header_list);
$this->privSwapBackMagicQuotes();
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Swap back the file descriptor
$v_swap = $this->zip_fd;
$this->zip_fd = $v_zip_temp_fd;
$v_zip_temp_fd = $v_swap;
// ----- Close
$this->privCloseFd();
// ----- Close the temporary file
@fclose($v_zip_temp_fd);
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Delete the zip file
// TBC : I should test the result ...
@unlink($this->zipname);
// ----- Rename the temporary file
// TBC : I should test the result ...
//@rename($v_zip_temp_name, $this->zipname);
PclZipUtilRename($v_zip_temp_name, $this->zipname);
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privOpenFd()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function privOpenFd($p_mode)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privOpenFd", 'mode='.$p_mode);
$v_result=1;
// ----- Look if already open
if ($this->zip_fd != 0)
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Zip file \''.$this->zipname.'\' already open');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Open the zip file
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Open file in '.$p_mode.' mode');
if (($this->zip_fd = @fopen($this->zipname, $p_mode)) == 0)
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in '.$p_mode.' mode');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCloseFd()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function privCloseFd()
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privCloseFd", "");
$v_result=1;
if ($this->zip_fd != 0)
@fclose($this->zip_fd);
$this->zip_fd = 0;
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privAddList()
// Description :
// $p_add_dir and $p_remove_dir will give the ability to memorize a path which is
// different from the real path of the file. This is usefull if you want to have PclTar
// running in any directory, and memorize relative path from an other directory.
// Parameters :
// $p_list : An array containing the file or directory names to add in the tar
// $p_result_list : list of added files with their properties (specially the status field)
// $p_add_dir : Path to add in the filename path archived
// $p_remove_dir : Path to remove in the filename path archived
// Return Values :
// --------------------------------------------------------------------------------
// function privAddList($p_list, &$p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_options)
function privAddList($p_filedescr_list, &$p_result_list, &$p_options)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privAddList", "list");
$v_result=1;
// ----- Add the files
$v_header_list = array();
if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1)
{
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Store the offset of the central dir
$v_offset = @ftell($this->zip_fd);
// ----- Create the Central Dir files header
for ($i=0,$v_count=0; $i<sizeof($v_header_list); $i++)
{
// ----- Create the file header
if ($v_header_list[$i]['status'] == 'ok') {
if (($v_result = $this->privWriteCentralFileHeader($v_header_list[$i])) != 1) {
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
$v_count++;
}
// ----- Transform the header to a 'usable' info
$this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
}
// ----- Zip file comment
$v_comment = '';
if (isset($p_options[PCLZIP_OPT_COMMENT])) {
$v_comment = $p_options[PCLZIP_OPT_COMMENT];
}
// ----- Calculate the size of the central header
$v_size = @ftell($this->zip_fd)-$v_offset;
// ----- Create the central dir footer
if (($v_result = $this->privWriteCentralHeader($v_count, $v_size, $v_offset, $v_comment)) != 1)
{
// ----- Reset the file list
unset($v_header_list);
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privAddFileList()
// Description :
// Parameters :
// $p_filedescr_list : An array containing the file description
// or directory names to add in the zip
// $p_result_list : list of added files with their properties (specially the status field)
// Return Values :
// --------------------------------------------------------------------------------
function privAddFileList($p_filedescr_list, &$p_result_list, &$p_options)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privAddFileList", "filedescr_list");
$v_result=1;
$v_header = array();
// ----- Recuperate the current number of elt in list
$v_nb = sizeof($p_result_list);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Before add, list have ".$v_nb." elements");
// ----- Loop on the files
for ($j=0; ($j<sizeof($p_filedescr_list)) && ($v_result==1); $j++) {
// ----- Format the filename
$p_filedescr_list[$j]['filename']
= PclZipUtilTranslateWinPath($p_filedescr_list[$j]['filename'], false);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Looking for file '".$p_filedescr_list[$j]['filename']."'");
// ----- Skip empty file names
// TBC : Can this be possible ? not checked in DescrParseAtt ?
if ($p_filedescr_list[$j]['filename'] == "") {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Skip empty filename");
continue;
}
// ----- Check the filename
if ( ($p_filedescr_list[$j]['type'] != 'virtual_file')
&& (!file_exists($p_filedescr_list[$j]['filename']))) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File '".$p_filedescr_list[$j]['filename']."' does not exists");
PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "File '".$p_filedescr_list[$j]['filename']."' does not exists");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Look if it is a file or a dir with no all path remove option
// or a dir with all its path removed
// if ( (is_file($p_filedescr_list[$j]['filename']))
// || ( is_dir($p_filedescr_list[$j]['filename'])
if ( ($p_filedescr_list[$j]['type'] == 'file')
|| ($p_filedescr_list[$j]['type'] == 'virtual_file')
|| ( ($p_filedescr_list[$j]['type'] == 'folder')
&& ( !isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH])
|| !$p_options[PCLZIP_OPT_REMOVE_ALL_PATH]))
) {
// ----- Add the file
$v_result = $this->privAddFile($p_filedescr_list[$j], $v_header,
$p_options);
if ($v_result != 1) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Store the file infos
$p_result_list[$v_nb++] = $v_header;
}
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "After add, list have ".$v_nb." elements");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privAddFile()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privAddFile($p_filedescr, &$p_header, &$p_options)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privAddFile", "filename='".$p_filedescr['filename']."'");
$v_result=1;
// ----- Working variable
$p_filename = $p_filedescr['filename'];
// TBC : Already done in the fileAtt check ... ?
if ($p_filename == "") {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file list parameter (invalid or empty list)");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Look for a stored different filename
/* TBC : Removed
if (isset($p_filedescr['stored_filename'])) {
$v_stored_filename = $p_filedescr['stored_filename'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, 'Stored filename is NOT the same "'.$v_stored_filename.'"');
}
else {
$v_stored_filename = $p_filedescr['stored_filename'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, 'Stored filename is the same');
}
*/
// ----- Set the file properties
clearstatcache();
$p_header['version'] = 20;
$p_header['version_extracted'] = 10;
$p_header['flag'] = 0;
$p_header['compression'] = 0;
$p_header['crc'] = 0;
$p_header['compressed_size'] = 0;
$p_header['filename_len'] = strlen($p_filename);
$p_header['extra_len'] = 0;
$p_header['disk'] = 0;
$p_header['internal'] = 0;
$p_header['offset'] = 0;
$p_header['filename'] = $p_filename;
// TBC : Removed $p_header['stored_filename'] = $v_stored_filename;
$p_header['stored_filename'] = $p_filedescr['stored_filename'];
$p_header['extra'] = '';
$p_header['status'] = 'ok';
$p_header['index'] = -1;
// ----- Look for regular file
if ($p_filedescr['type']=='file') {
$p_header['external'] = 0x00000000;
$p_header['size'] = filesize($p_filename);
}
// ----- Look for regular folder
else if ($p_filedescr['type']=='folder') {
$p_header['external'] = 0x00000010;
$p_header['mtime'] = filemtime($p_filename);
$p_header['size'] = filesize($p_filename);
}
// ----- Look for virtual file
else if ($p_filedescr['type'] == 'virtual_file') {
$p_header['external'] = 0x00000000;
$p_header['size'] = strlen($p_filedescr['content']);
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Header external extension '".sprintf("0x%X",$p_header['external'])."'");
// ----- Look for filetime
if (isset($p_filedescr['mtime'])) {
$p_header['mtime'] = $p_filedescr['mtime'];
}
else if ($p_filedescr['type'] == 'virtual_file') {
$p_header['mtime'] = mktime();
}
else {
$p_header['mtime'] = filemtime($p_filename);
}
// ------ Look for file comment
if (isset($p_filedescr['comment'])) {
$p_header['comment_len'] = strlen($p_filedescr['comment']);
$p_header['comment'] = $p_filedescr['comment'];
}
else {
$p_header['comment_len'] = 0;
$p_header['comment'] = '';
}
// ----- Look for pre-add callback
if (isset($p_options[PCLZIP_CB_PRE_ADD])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "A pre-callback '".$p_options[PCLZIP_CB_PRE_ADD]."()') is defined for the extraction");
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_header, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
eval('$v_result = '.$p_options[PCLZIP_CB_PRE_ADD].'(PCLZIP_CB_PRE_ADD, $v_local_header);');
if ($v_result == 0) {
// ----- Change the file status
$p_header['status'] = "skipped";
$v_result = 1;
}
// ----- Update the informations
// Only some fields can be modified
if ($p_header['stored_filename'] != $v_local_header['stored_filename']) {
$p_header['stored_filename'] = PclZipUtilPathReduction($v_local_header['stored_filename']);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "New stored filename is '".$p_header['stored_filename']."'");
}
}
// ----- Look for empty stored filename
if ($p_header['stored_filename'] == "") {
$p_header['status'] = "filtered";
}
// ----- Check the path length
if (strlen($p_header['stored_filename']) > 0xFF) {
$p_header['status'] = 'filename_too_long';
}
// ----- Look if no error, or file not skipped
if ($p_header['status'] == 'ok') {
// ----- Look for a file
// if (is_file($p_filename))
if ( ($p_filedescr['type'] == 'file')
|| ($p_filedescr['type'] == 'virtual_file')) {
// ----- Get content from real file
if ($p_filedescr['type'] == 'file') {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "'".$p_filename."' is a file");
// ----- Open the source file
if (($v_file = @fopen($p_filename, "rb")) == 0) {
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Read the file content
$v_content = @fread($v_file, $p_header['size']);
// ----- Close the file
@fclose($v_file);
}
else if ($p_filedescr['type'] == 'virtual_file') {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Add by string");
$v_content = $p_filedescr['content'];
}
// ----- Calculate the CRC
$p_header['crc'] = @crc32($v_content);
// ----- Look for no compression
if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File will not be compressed");
// ----- Set header parameters
$p_header['compressed_size'] = $p_header['size'];
$p_header['compression'] = 0;
}
// ----- Look for normal compression
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File will be compressed");
// ----- Compress the content
$v_content = @gzdeflate($v_content);
// ----- Set header parameters
$p_header['compressed_size'] = strlen($v_content);
$p_header['compression'] = 8;
}
// ----- Look for encryption
/*
if ((isset($p_options[PCLZIP_OPT_CRYPT]))
&& ($p_options[PCLZIP_OPT_CRYPT] != "")) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File need to be crypted ....");
// Should be a random header
$v_header = 'xxxxxxxxxxxx';
$v_content_compressed = PclZipUtilZipEncrypt($v_content_compressed,
$p_header['compressed_size'],
$v_header,
$p_header['crc'],
"test");
$p_header['compressed_size'] += 12;
$p_header['flag'] = 1;
// ----- Add the header to the data
$v_content_compressed = $v_header.$v_content_compressed;
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Size after header : ".strlen($v_content_compressed)."");
}
*/
// ----- Call the header generation
if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
@fclose($v_file);
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Write the compressed (or not) content
@fwrite($this->zip_fd, $v_content, $p_header['compressed_size']);
}
// ----- Look for a directory
else if ($p_filedescr['type'] == 'folder') {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "'".$p_filename."' is a folder");
// ----- Look for directory last '/'
if (@substr($p_header['stored_filename'], -1) != '/') {
$p_header['stored_filename'] .= '/';
}
// ----- Set the file properties
$p_header['size'] = 0;
//$p_header['external'] = 0x41FF0010; // Value for a folder : to be checked
$p_header['external'] = 0x00000010; // Value for a folder : to be checked
// ----- Call the header generation
if (($v_result = $this->privWriteFileHeader($p_header)) != 1)
{
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
}
}
// ----- Look for post-add callback
if (isset($p_options[PCLZIP_CB_POST_ADD])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "A post-callback '".$p_options[PCLZIP_CB_POST_ADD]."()') is defined for the extraction");
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_header, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
eval('$v_result = '.$p_options[PCLZIP_CB_POST_ADD].'(PCLZIP_CB_POST_ADD, $v_local_header);');
if ($v_result == 0) {
// ----- Ignored
$v_result = 1;
}
// ----- Update the informations
// Nothing can be modified
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCalculateStoredFilename()
// Description :
// Based on file descriptor properties and global options, this method
// calculate the filename that will be stored in the archive.
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privCalculateStoredFilename(&$p_filedescr, &$p_options)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privCalculateStoredFilename", "filename='".$p_filedescr['filename']."'");
$v_result=1;
// ----- Working variables
$p_filename = $p_filedescr['filename'];
if (isset($p_options[PCLZIP_OPT_ADD_PATH])) {
$p_add_dir = $p_options[PCLZIP_OPT_ADD_PATH];
}
else {
$p_add_dir = '';
}
if (isset($p_options[PCLZIP_OPT_REMOVE_PATH])) {
$p_remove_dir = $p_options[PCLZIP_OPT_REMOVE_PATH];
}
else {
$p_remove_dir = '';
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Remove path ='".$p_remove_dir."'");
if (isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH])) {
$p_remove_all_dir = $p_options[PCLZIP_OPT_REMOVE_ALL_PATH];
}
else {
$p_remove_all_dir = 0;
}
// ----- Look for full name change
if (isset($p_filedescr['new_full_name'])) {
$v_stored_filename = $p_filedescr['new_full_name'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Changing full name of '".$p_filename."' for '".$v_stored_filename."'");
}
// ----- Look for path and/or short name change
else {
// ----- Look for short name change
if (isset($p_filedescr['new_short_name'])) {
$v_path_info = pathinfo($p_filename);
$v_dir = '';
if ($v_path_info['dirname'] != '') {
$v_dir = $v_path_info['dirname'].'/';
}
$v_stored_filename = $v_dir.$p_filedescr['new_short_name'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Changing short name of '".$p_filename."' for '".$v_stored_filename."'");
}
else {
// ----- Calculate the stored filename
$v_stored_filename = $p_filename;
}
// ----- Look for all path to remove
if ($p_remove_all_dir) {
$v_stored_filename = basename($p_filename);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Remove all path selected change '".$p_filename."' for '".$v_stored_filename."'");
}
// ----- Look for partial path remove
else if ($p_remove_dir != "") {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Partial path to remove");
if (substr($p_remove_dir, -1) != '/')
$p_remove_dir .= "/";
if ( (substr($p_filename, 0, 2) == "./")
|| (substr($p_remove_dir, 0, 2) == "./")) {
if ( (substr($p_filename, 0, 2) == "./")
&& (substr($p_remove_dir, 0, 2) != "./")) {
$p_remove_dir = "./".$p_remove_dir;
}
if ( (substr($p_filename, 0, 2) != "./")
&& (substr($p_remove_dir, 0, 2) == "./")) {
$p_remove_dir = substr($p_remove_dir, 2);
}
}
$v_compare = PclZipUtilPathInclusion($p_remove_dir,
$v_stored_filename);
if ($v_compare > 0) {
if ($v_compare == 2) {
$v_stored_filename = "";
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Path to remove is the current folder");
}
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Remove path '$p_remove_dir' in file '$v_stored_filename'");
$v_stored_filename = substr($v_stored_filename,
strlen($p_remove_dir));
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Result is '$v_stored_filename'");
}
}
}
// ----- Look for path to add
if ($p_add_dir != "") {
if (substr($p_add_dir, -1) == "/")
$v_stored_filename = $p_add_dir.$v_stored_filename;
else
$v_stored_filename = $p_add_dir."/".$v_stored_filename;
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Add path '$p_add_dir' in file '$p_filename' = '$v_stored_filename'");
}
}
// ----- Filename (reduce the path of stored name)
$v_stored_filename = PclZipUtilPathReduction($v_stored_filename);
$p_filedescr['stored_filename'] = $v_stored_filename;
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Stored filename will be '".$p_filedescr['stored_filename']."', strlen ".strlen($p_filedescr['stored_filename']));
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privWriteFileHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privWriteFileHeader(&$p_header)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privWriteFileHeader", 'file="'.$p_header['filename'].'", stored as "'.$p_header['stored_filename'].'"');
$v_result=1;
// ----- Store the offset position of the file
$p_header['offset'] = ftell($this->zip_fd);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, 'File offset of the header :'.$p_header['offset']);
// ----- Transform UNIX mtime to DOS format mdate/mtime
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Date : \''.date("d/m/y H:i:s", $p_header['mtime']).'\'');
$v_date = getdate($p_header['mtime']);
$v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2;
$v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday'];
// ----- Packed data
$v_binary_data = pack("VvvvvvVVVvv", 0x04034b50,
$p_header['version_extracted'], $p_header['flag'],
$p_header['compression'], $v_mtime, $v_mdate,
$p_header['crc'], $p_header['compressed_size'],
$p_header['size'],
strlen($p_header['stored_filename']),
$p_header['extra_len']);
// ----- Write the first 148 bytes of the header in the archive
fputs($this->zip_fd, $v_binary_data, 30);
// ----- Write the variable fields
if (strlen($p_header['stored_filename']) != 0)
{
fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename']));
}
if ($p_header['extra_len'] != 0)
{
fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']);
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privWriteCentralFileHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privWriteCentralFileHeader(&$p_header)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privWriteCentralFileHeader", 'file="'.$p_header['filename'].'", stored as "'.$p_header['stored_filename'].'"');
$v_result=1;
// TBC
//for(reset($p_header); $key = key($p_header); next($p_header)) {
// //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "header[$key] = ".$p_header[$key]);
//}
// ----- Transform UNIX mtime to DOS format mdate/mtime
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Date : \''.date("d/m/y H:i:s", $p_header['mtime']).'\'');
$v_date = getdate($p_header['mtime']);
$v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2;
$v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Comment size : \''.$p_header['comment_len'].'\'');
// ----- Packed data
$v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50,
$p_header['version'], $p_header['version_extracted'],
$p_header['flag'], $p_header['compression'],
$v_mtime, $v_mdate, $p_header['crc'],
$p_header['compressed_size'], $p_header['size'],
strlen($p_header['stored_filename']),
$p_header['extra_len'], $p_header['comment_len'],
$p_header['disk'], $p_header['internal'],
$p_header['external'], $p_header['offset']);
// ----- Write the 42 bytes of the header in the zip file
fputs($this->zip_fd, $v_binary_data, 46);
// ----- Write the variable fields
if (strlen($p_header['stored_filename']) != 0)
{
fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename']));
}
if ($p_header['extra_len'] != 0)
{
fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']);
}
if ($p_header['comment_len'] != 0)
{
fputs($this->zip_fd, $p_header['comment'], $p_header['comment_len']);
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privWriteCentralHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privWriteCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privWriteCentralHeader", 'nb_entries='.$p_nb_entries.', size='.$p_size.', offset='.$p_offset.', comment="'.$p_comment.'"');
$v_result=1;
// ----- Packed data
$v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries,
$p_nb_entries, $p_size,
$p_offset, strlen($p_comment));
// ----- Write the 22 bytes of the header in the zip file
fputs($this->zip_fd, $v_binary_data, 22);
// ----- Write the variable fields
if (strlen($p_comment) != 0)
{
fputs($this->zip_fd, $p_comment, strlen($p_comment));
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privList()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privList(&$p_list)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privList", "list");
$v_result=1;
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Open the zip file
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode");
if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0)
{
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Read the central directory informations
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Go to beginning of Central Dir
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Offset : ".$v_central_dir['offset']."'");
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Position in file : ".ftell($this->zip_fd)."'");
@rewind($this->zip_fd);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Position in file : ".ftell($this->zip_fd)."'");
if (@fseek($this->zip_fd, $v_central_dir['offset']))
{
$this->privSwapBackMagicQuotes();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Position in file : ".ftell($this->zip_fd)."'");
// ----- Read each entry
for ($i=0; $i<$v_central_dir['entries']; $i++)
{
// ----- Read the file header
if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1)
{
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
$v_header['index'] = $i;
// ----- Get the only interesting attributes
$this->privConvertHeader2FileInfo($v_header, $p_list[$i]);
unset($v_header);
}
// ----- Close the zip file
$this->privCloseFd();
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privConvertHeader2FileInfo()
// Description :
// This function takes the file informations from the central directory
// entries and extract the interesting parameters that will be given back.
// The resulting file infos are set in the array $p_info
// $p_info['filename'] : Filename with full path. Given by user (add),
// extracted in the filesystem (extract).
// $p_info['stored_filename'] : Stored filename in the archive.
// $p_info['size'] = Size of the file.
// $p_info['compressed_size'] = Compressed size of the file.
// $p_info['mtime'] = Last modification date of the file.
// $p_info['comment'] = Comment associated with the file.
// $p_info['folder'] = true/false : indicates if the entry is a folder or not.
// $p_info['status'] = status of the action on the file.
// $p_info['crc'] = CRC of the file content.
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privConvertHeader2FileInfo($p_header, &$p_info)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privConvertHeader2FileInfo", "Filename='".$p_header['filename']."'");
$v_result=1;
// ----- Get the interesting attributes
$p_info['filename'] = $p_header['filename'];
$p_info['stored_filename'] = $p_header['stored_filename'];
$p_info['size'] = $p_header['size'];
$p_info['compressed_size'] = $p_header['compressed_size'];
$p_info['mtime'] = $p_header['mtime'];
$p_info['comment'] = $p_header['comment'];
$p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010);
$p_info['index'] = $p_header['index'];
$p_info['status'] = $p_header['status'];
$p_info['crc'] = $p_header['crc'];
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractByRule()
// Description :
// Extract a file or directory depending of rules (by index, by name, ...)
// Parameters :
// $p_file_list : An array where will be placed the properties of each
// extracted file
// $p_path : Path to add while writing the extracted files
// $p_remove_path : Path to remove (from the file memorized path) while writing the
// extracted files. If the path does not match the file path,
// the file is extracted with its memorized path.
// $p_remove_path does not apply to 'list' mode.
// $p_path and $p_remove_path are commulative.
// Return Values :
// 1 on success,0 or less on error (see error code list)
// --------------------------------------------------------------------------------
function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privExtractByRule", "path='$p_path', remove_path='$p_remove_path', remove_all_path='".($p_remove_all_path?'true':'false')."'");
$v_result=1;
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Check the path
if ( ($p_path == "")
|| ( (substr($p_path, 0, 1) != "/")
&& (substr($p_path, 0, 3) != "../")
&& (substr($p_path,1,2)!=":/")))
$p_path = "./".$p_path;
// ----- Reduce the path last (and duplicated) '/'
if (($p_path != "./") && ($p_path != "/"))
{
// ----- Look for the path end '/'
while (substr($p_path, -1) == "/")
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Destination path [$p_path] ends by '/'");
$p_path = substr($p_path, 0, strlen($p_path)-1);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Modified to [$p_path]");
}
}
// ----- Look for path to remove format (should end by /)
if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/'))
{
$p_remove_path .= '/';
}
$p_remove_path_size = strlen($p_remove_path);
// ----- Open the zip file
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode");
if (($v_result = $this->privOpenFd('rb')) != 1)
{
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Read the central directory informations
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Start at beginning of Central Dir
$v_pos_entry = $v_central_dir['offset'];
// ----- Read each entry
$j_start = 0;
for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Read next file header entry : '$i'");
// ----- Read next Central dir entry
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Position before rewind : ".ftell($this->zip_fd)."'");
@rewind($this->zip_fd);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Position after rewind : ".ftell($this->zip_fd)."'");
if (@fseek($this->zip_fd, $v_pos_entry))
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Position after fseek : ".ftell($this->zip_fd)."'");
// ----- Read the file header
$v_header = array();
if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Store the index
$v_header['index'] = $i;
// ----- Store the file position
$v_pos_entry = ftell($this->zip_fd);
// ----- Look for the specific extract rules
$v_extract = false;
// ----- Look for extract by name rule
if ( (isset($p_options[PCLZIP_OPT_BY_NAME]))
&& ($p_options[PCLZIP_OPT_BY_NAME] != 0)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with rule 'ByName'");
// ----- Look if the filename is in the list
for ($j=0; ($j<sizeof($p_options[PCLZIP_OPT_BY_NAME])) && (!$v_extract); $j++) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Compare with file '".$p_options[PCLZIP_OPT_BY_NAME][$j]."'");
// ----- Look for a directory
if (substr($p_options[PCLZIP_OPT_BY_NAME][$j], -1) == "/") {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The searched item is a directory");
// ----- Look if the directory is in the filename path
if ( (strlen($v_header['stored_filename']) > strlen($p_options[PCLZIP_OPT_BY_NAME][$j]))
&& (substr($v_header['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The directory is in the file path");
$v_extract = true;
}
}
// ----- Look for a filename
elseif ($v_header['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The file is the right one.");
$v_extract = true;
}
}
}
// ----- Look for extract by ereg rule
else if ( (isset($p_options[PCLZIP_OPT_BY_EREG]))
&& ($p_options[PCLZIP_OPT_BY_EREG] != "")) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract by ereg '".$p_options[PCLZIP_OPT_BY_EREG]."'");
if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header['stored_filename'])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Filename match the regular expression");
$v_extract = true;
}
}
// ----- Look for extract by preg rule
else if ( (isset($p_options[PCLZIP_OPT_BY_PREG]))
&& ($p_options[PCLZIP_OPT_BY_PREG] != "")) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with rule 'ByEreg'");
if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Filename match the regular expression");
$v_extract = true;
}
}
// ----- Look for extract by index rule
else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX]))
&& ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with rule 'ByIndex'");
// ----- Look if the index is in the list
for ($j=$j_start; ($j<sizeof($p_options[PCLZIP_OPT_BY_INDEX])) && (!$v_extract); $j++) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Look if index '$i' is in [".$p_options[PCLZIP_OPT_BY_INDEX][$j]['start'].",".$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']."]");
if (($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Found as part of an index range");
$v_extract = true;
}
if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Do not look this index range for next loop");
$j_start = $j+1;
}
if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Index range is greater than index, stop loop");
break;
}
}
}
// ----- Look for no rule, which means extract all the archive
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with no rule (extract all)");
$v_extract = true;
}
// ----- Check compression method
if ( ($v_extract)
&& ( ($v_header['compression'] != 8)
&& ($v_header['compression'] != 0))) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unsupported compression method (".$v_header['compression'].")");
$v_header['status'] = 'unsupported_compression';
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_STOP_ON_ERROR is selected, extraction will be stopped");
$this->privSwapBackMagicQuotes();
PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION,
"Filename '".$v_header['stored_filename']."' is "
."compressed by an unsupported compression "
."method (".$v_header['compression'].") ");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
}
// ----- Check encrypted files
if (($v_extract) && (($v_header['flag'] & 1) == 1)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unsupported file encryption");
$v_header['status'] = 'unsupported_encryption';
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_STOP_ON_ERROR is selected, extraction will be stopped");
$this->privSwapBackMagicQuotes();
PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION,
"Unsupported encryption for "
." filename '".$v_header['stored_filename']
."'");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
}
// ----- Look for real extraction
if (($v_extract) && ($v_header['status'] != 'ok')) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "No need for extract");
$v_result = $this->privConvertHeader2FileInfo($v_header,
$p_file_list[$v_nb_extracted++]);
if ($v_result != 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
$v_extract = false;
}
// ----- Look for real extraction
if ($v_extract)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting file '".$v_header['filename']."', index '$i'");
// ----- Go to the file position
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position before rewind : ".ftell($this->zip_fd)."'");
@rewind($this->zip_fd);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position after rewind : ".ftell($this->zip_fd)."'");
if (@fseek($this->zip_fd, $v_header['offset']))
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position after fseek : ".ftell($this->zip_fd)."'");
// ----- Look for extraction as string
if ($p_options[PCLZIP_OPT_EXTRACT_AS_STRING]) {
// ----- Extracting the file
$v_result1 = $this->privExtractFileAsString($v_header, $v_string);
if ($v_result1 < 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result1);
return $v_result1;
}
// ----- Get the only interesting attributes
if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Set the file content
$p_file_list[$v_nb_extracted]['content'] = $v_string;
// ----- Next extracted file
$v_nb_extracted++;
// ----- Look for user callback abort
if ($v_result1 == 2) {
break;
}
}
// ----- Look for extraction in standard output
elseif ( (isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT]))
&& ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) {
// ----- Extracting the file in standard output
$v_result1 = $this->privExtractFileInOutput($v_header, $p_options);
if ($v_result1 < 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result1);
return $v_result1;
}
// ----- Get the only interesting attributes
if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Look for user callback abort
if ($v_result1 == 2) {
break;
}
}
// ----- Look for normal extraction
else {
// ----- Extracting the file
$v_result1 = $this->privExtractFile($v_header,
$p_path, $p_remove_path,
$p_remove_all_path,
$p_options);
if ($v_result1 < 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result1);
return $v_result1;
}
// ----- Get the only interesting attributes
if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Look for user callback abort
if ($v_result1 == 2) {
break;
}
}
}
}
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractFile()
// Description :
// Parameters :
// Return Values :
//
// 1 : ... ?
// PCLZIP_ERR_USER_ABORTED(2) : User ask for extraction stop in callback
// --------------------------------------------------------------------------------
function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privExtractFile', "path='$p_path', remove_path='$p_remove_path', remove_all_path='".($p_remove_all_path?'true':'false')."'");
$v_result=1;
// ----- Read the file header
if (($v_result = $this->privReadFileHeader($v_header)) != 1)
{
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Found file '".$v_header['filename']."', size '".$v_header['size']."'");
// ----- Check that the file header is coherent with $p_entry info
if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
// TBC
}
// ----- Look for all path to remove
if ($p_remove_all_path == true) {
// ----- Look for folder entry that not need to be extracted
if (($p_entry['external']&0x00000010)==0x00000010) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "The entry is a folder : need to be filtered");
$p_entry['status'] = "filtered";
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "All path is removed");
// ----- Get the basename of the path
$p_entry['filename'] = basename($p_entry['filename']);
}
// ----- Look for path to remove
else if ($p_remove_path != "")
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Look for some path to remove");
if (PclZipUtilPathInclusion($p_remove_path, $p_entry['filename']) == 2)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "The folder is the same as the removed path '".$p_entry['filename']."'");
// ----- Change the file status
$p_entry['status'] = "filtered";
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
$p_remove_path_size = strlen($p_remove_path);
if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Found path '$p_remove_path' to remove in file '".$p_entry['filename']."'");
// ----- Remove the path
$p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Resulting file is '".$p_entry['filename']."'");
}
}
// ----- Add the path
if ($p_path != '') {
$p_entry['filename'] = $p_path."/".$p_entry['filename'];
}
// ----- Check a base_dir_restriction
if (isset($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Check the extract directory restriction");
$v_inclusion
= PclZipUtilPathInclusion($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION],
$p_entry['filename']);
if ($v_inclusion == 0) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_EXTRACT_DIR_RESTRICTION is selected, file is outside restriction");
PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION,
"Filename '".$p_entry['filename']."' is "
."outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
}
// ----- Look for pre-extract callback
if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "A pre-callback '".$p_options[PCLZIP_CB_PRE_EXTRACT]."()') is defined for the extraction");
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);');
if ($v_result == 0) {
// ----- Change the file status
$p_entry['status'] = "skipped";
$v_result = 1;
}
// ----- Look for abort result
if ($v_result == 2) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "User callback abort the extraction");
// ----- This status is internal and will be changed in 'skipped'
$p_entry['status'] = "aborted";
$v_result = PCLZIP_ERR_USER_ABORTED;
}
// ----- Update the informations
// Only some fields can be modified
$p_entry['filename'] = $v_local_header['filename'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "New filename is '".$p_entry['filename']."'");
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting file (with path) '".$p_entry['filename']."', size '$v_header[size]'");
// ----- Look if extraction should be done
if ($p_entry['status'] == 'ok') {
// ----- Look for specific actions while the file exist
if (file_exists($p_entry['filename']))
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File '".$p_entry['filename']."' already exists");
// ----- Look if file is a directory
if (is_dir($p_entry['filename']))
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Existing file '".$p_entry['filename']."' is a directory");
// ----- Change the file status
$p_entry['status'] = "already_a_directory";
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_STOP_ON_ERROR is selected, extraction will be stopped");
PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY,
"Filename '".$p_entry['filename']."' is "
."already used by an existing directory");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
}
// ----- Look if file is write protected
else if (!is_writeable($p_entry['filename']))
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Existing file '".$p_entry['filename']."' is write protected");
// ----- Change the file status
$p_entry['status'] = "write_protected";
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_STOP_ON_ERROR is selected, extraction will be stopped");
PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL,
"Filename '".$p_entry['filename']."' exists "
."and is write protected");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
}
// ----- Look if the extracted file is older
else if (filemtime($p_entry['filename']) > $p_entry['mtime'])
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Existing file '".$p_entry['filename']."' is newer (".date("l dS of F Y h:i:s A", filemtime($p_entry['filename'])).") than the extracted file (".date("l dS of F Y h:i:s A", $p_entry['mtime']).")");
// ----- Change the file status
if ( (isset($p_options[PCLZIP_OPT_REPLACE_NEWER]))
&& ($p_options[PCLZIP_OPT_REPLACE_NEWER]===true)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_REPLACE_NEWER is selected, file will be replaced");
}
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File will not be replaced");
$p_entry['status'] = "newer_exist";
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_STOP_ON_ERROR is selected, extraction will be stopped");
PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL,
"Newer version of '".$p_entry['filename']."' exists "
."and option PCLZIP_OPT_REPLACE_NEWER is not selected");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
}
}
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Existing file '".$p_entry['filename']."' is older than the extrated one - will be replaced by the extracted one (".date("l dS of F Y h:i:s A", filemtime($p_entry['filename'])).") than the extracted file (".date("l dS of F Y h:i:s A", $p_entry['mtime']).")");
}
}
// ----- Check the directory availability and create it if necessary
else {
if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/'))
$v_dir_to_check = $p_entry['filename'];
else if (!strstr($p_entry['filename'], "/"))
$v_dir_to_check = "";
else
$v_dir_to_check = dirname($p_entry['filename']);
if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unable to create path for '".$p_entry['filename']."'");
// ----- Change the file status
$p_entry['status'] = "path_creation_fail";
// ----- Return
////--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
//return $v_result;
$v_result = 1;
}
}
}
// ----- Look if extraction should be done
if ($p_entry['status'] == 'ok') {
// ----- Do the extraction (if not a folder)
if (!(($p_entry['external']&0x00000010)==0x00000010))
{
// ----- Look for not compressed file
if ($p_entry['compression'] == 0) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting an un-compressed file");
// ----- Opening destination file
if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Error while opening '".$p_entry['filename']."' in write binary mode");
// ----- Change the file status
$p_entry['status'] = "write_error";
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Read '".$p_entry['size']."' bytes");
// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
$v_size = $p_entry['compressed_size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Read $v_read_size bytes");
$v_buffer = @fread($this->zip_fd, $v_read_size);
/* Try to speed up the code
$v_binary_data = pack('a'.$v_read_size, $v_buffer);
@fwrite($v_dest_file, $v_binary_data, $v_read_size);
*/
@fwrite($v_dest_file, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Closing the destination file
fclose($v_dest_file);
// ----- Change the file mtime
touch($p_entry['filename'], $p_entry['mtime']);
}
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting a compressed file (Compression method ".$p_entry['compression'].")");
// ----- TBC
// Need to be finished
if (($p_entry['flag'] & 1) == 1) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File is encrypted");
/*
// ----- Read the encryption header
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Read 12 encryption header bytes");
$v_encryption_header = @fread($this->zip_fd, 12);
// ----- Read the encrypted & compressed file in a buffer
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Read '".($p_entry['compressed_size']-12)."' compressed & encrypted bytes");
$v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']-12);
// ----- Decrypt the buffer
$this->privDecrypt($v_encryption_header, $v_buffer,
$p_entry['compressed_size']-12, $p_entry['crc']);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Buffer is '".$v_buffer."'");
*/
}
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Read '".$p_entry['compressed_size']."' compressed bytes");
// ----- Read the compressed file in a buffer (one shot)
$v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
}
// ----- Decompress the file
$v_file_content = @gzinflate($v_buffer);
unset($v_buffer);
if ($v_file_content === FALSE) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unable to inflate compressed file");
// ----- Change the file status
// TBC
$p_entry['status'] = "error";
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Opening destination file
if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Error while opening '".$p_entry['filename']."' in write binary mode");
// ----- Change the file status
$p_entry['status'] = "write_error";
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Write the uncompressed data
@fwrite($v_dest_file, $v_file_content, $p_entry['size']);
unset($v_file_content);
// ----- Closing the destination file
@fclose($v_dest_file);
// ----- Change the file mtime
@touch($p_entry['filename'], $p_entry['mtime']);
}
// ----- Look for chmod option
if (isset($p_options[PCLZIP_OPT_SET_CHMOD])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "chmod option activated '".$p_options[PCLZIP_OPT_SET_CHMOD]."'");
// ----- Change the mode of the file
@chmod($p_entry['filename'], $p_options[PCLZIP_OPT_SET_CHMOD]);
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extraction done");
}
}
// ----- Change abort status
if ($p_entry['status'] == "aborted") {
$p_entry['status'] = "skipped";
}
// ----- Look for post-extract callback
elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "A post-callback '".$p_options[PCLZIP_CB_POST_EXTRACT]."()') is defined for the extraction");
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);');
// ----- Look for abort result
if ($v_result == 2) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "User callback abort the extraction");
$v_result = PCLZIP_ERR_USER_ABORTED;
}
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractFileInOutput()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privExtractFileInOutput(&$p_entry, &$p_options)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privExtractFileInOutput', "");
$v_result=1;
// ----- Read the file header
if (($v_result = $this->privReadFileHeader($v_header)) != 1) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Found file '".$v_header['filename']."', size '".$v_header['size']."'");
// ----- Check that the file header is coherent with $p_entry info
if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
// TBC
}
// ----- Look for pre-extract callback
if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "A pre-callback '".$p_options[PCLZIP_CB_PRE_EXTRACT]."()') is defined for the extraction");
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);');
if ($v_result == 0) {
// ----- Change the file status
$p_entry['status'] = "skipped";
$v_result = 1;
}
// ----- Look for abort result
if ($v_result == 2) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "User callback abort the extraction");
// ----- This status is internal and will be changed in 'skipped'
$p_entry['status'] = "aborted";
$v_result = PCLZIP_ERR_USER_ABORTED;
}
// ----- Update the informations
// Only some fields can be modified
$p_entry['filename'] = $v_local_header['filename'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "New filename is '".$p_entry['filename']."'");
}
// ----- Trace
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting file (with path) '".$p_entry['filename']."', size '$v_header[size]'");
// ----- Look if extraction should be done
if ($p_entry['status'] == 'ok') {
// ----- Do the extraction (if not a folder)
if (!(($p_entry['external']&0x00000010)==0x00000010)) {
// ----- Look for not compressed file
if ($p_entry['compressed_size'] == $p_entry['size']) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting an un-compressed file");
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Reading '".$p_entry['size']."' bytes");
// ----- Read the file in a buffer (one shot)
$v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
// ----- Send the file to the output
echo $v_buffer;
unset($v_buffer);
}
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting a compressed file");
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Reading '".$p_entry['size']."' bytes");
// ----- Read the compressed file in a buffer (one shot)
$v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
// ----- Decompress the file
$v_file_content = gzinflate($v_buffer);
unset($v_buffer);
// ----- Send the file to the output
echo $v_file_content;
unset($v_file_content);
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extraction done");
}
}
// ----- Change abort status
if ($p_entry['status'] == "aborted") {
$p_entry['status'] = "skipped";
}
// ----- Look for post-extract callback
elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "A post-callback '".$p_options[PCLZIP_CB_POST_EXTRACT]."()') is defined for the extraction");
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);');
// ----- Look for abort result
if ($v_result == 2) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "User callback abort the extraction");
$v_result = PCLZIP_ERR_USER_ABORTED;
}
}
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractFileAsString()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privExtractFileAsString(&$p_entry, &$p_string)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privExtractFileAsString', "p_entry['filename']='".$p_entry['filename']."'");
$v_result=1;
// ----- Read the file header
$v_header = array();
if (($v_result = $this->privReadFileHeader($v_header)) != 1)
{
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Found file '".$v_header['filename']."', size '".$v_header['size']."'");
// ----- Check that the file header is coherent with $p_entry info
if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
// TBC
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting file in string (with path) '".$p_entry['filename']."', size '$v_header[size]'");
// ----- Do the extraction (if not a folder)
if (!(($p_entry['external']&0x00000010)==0x00000010))
{
// ----- Look for not compressed file
// if ($p_entry['compressed_size'] == $p_entry['size'])
if ($p_entry['compression'] == 0) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting an un-compressed file");
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Reading '".$p_entry['size']."' bytes");
// ----- Reading the file
$p_string = @fread($this->zip_fd, $p_entry['compressed_size']);
}
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting a compressed file (compression method '".$p_entry['compression']."')");
// ----- Reading the file
$v_data = @fread($this->zip_fd, $p_entry['compressed_size']);
// ----- Decompress the file
if (($p_string = @gzinflate($v_data)) === FALSE) {
// TBC
}
}
// ----- Trace
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extraction done");
}
else {
// TBC : error : can not extract a folder in a string
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privReadFileHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privReadFileHeader(&$p_header)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privReadFileHeader", "");
$v_result=1;
// ----- Read the 4 bytes signature
$v_binary_data = @fread($this->zip_fd, 4);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Binary data is : '".sprintf("%08x", $v_binary_data)."'");
$v_data = unpack('Vid', $v_binary_data);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Binary signature is : '".sprintf("0x%08x", $v_data['id'])."'");
// ----- Check signature
if ($v_data['id'] != 0x04034b50)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Invalid File header");
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Read the first 42 bytes of the header
$v_binary_data = fread($this->zip_fd, 26);
// ----- Look for invalid block size
if (strlen($v_binary_data) != 26)
{
$p_header['filename'] = "";
$p_header['status'] = "invalid_header";
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Invalid block size : ".strlen($v_binary_data));
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data));
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Extract the values
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Header : '".$v_binary_data."'");
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Header (Hex) : '".bin2hex($v_binary_data)."'");
$v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data);
// ----- Get filename
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "File name length : ".$v_data['filename_len']);
$p_header['filename'] = fread($this->zip_fd, $v_data['filename_len']);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Filename : \''.$p_header['filename'].'\'');
// ----- Get extra_fields
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extra field length : ".$v_data['extra_len']);
if ($v_data['extra_len'] != 0) {
$p_header['extra'] = fread($this->zip_fd, $v_data['extra_len']);
}
else {
$p_header['extra'] = '';
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Extra field : \''.bin2hex($p_header['extra']).'\'');
// ----- Extract properties
$p_header['version_extracted'] = $v_data['version'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Version need to extract : ('.$p_header['version_extracted'].') \''.($p_header['version_extracted']/10).'.'.($p_header['version_extracted']%10).'\'');
$p_header['compression'] = $v_data['compression'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Compression method : \''.$p_header['compression'].'\'');
$p_header['size'] = $v_data['size'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Size : \''.$p_header['size'].'\'');
$p_header['compressed_size'] = $v_data['compressed_size'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Compressed Size : \''.$p_header['compressed_size'].'\'');
$p_header['crc'] = $v_data['crc'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'CRC : \''.sprintf("0x%X", $p_header['crc']).'\'');
$p_header['flag'] = $v_data['flag'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Flag : \''.$p_header['flag'].'\'');
$p_header['filename_len'] = $v_data['filename_len'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Filename_len : \''.$p_header['filename_len'].'\'');
// ----- Recuperate date in UNIX format
$p_header['mdate'] = $v_data['mdate'];
$p_header['mtime'] = $v_data['mtime'];
if ($p_header['mdate'] && $p_header['mtime'])
{
// ----- Extract time
$v_hour = ($p_header['mtime'] & 0xF800) >> 11;
$v_minute = ($p_header['mtime'] & 0x07E0) >> 5;
$v_seconde = ($p_header['mtime'] & 0x001F)*2;
// ----- Extract date
$v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980;
$v_month = ($p_header['mdate'] & 0x01E0) >> 5;
$v_day = $p_header['mdate'] & 0x001F;
// ----- Get UNIX date format
$p_header['mtime'] = mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Date : \''.date("d/m/y H:i:s", $p_header['mtime']).'\'');
}
else
{
$p_header['mtime'] = time();
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Date is actual : \''.date("d/m/y H:i:s", $p_header['mtime']).'\'');
}
// TBC
//for(reset($v_data); $key = key($v_data); next($v_data)) {
// //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Attribut[$key] = ".$v_data[$key]);
//}
// ----- Set the stored filename
$p_header['stored_filename'] = $p_header['filename'];
// ----- Set the status field
$p_header['status'] = "ok";
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privReadCentralFileHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privReadCentralFileHeader(&$p_header)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privReadCentralFileHeader", "");
$v_result=1;
// ----- Read the 4 bytes signature
$v_binary_data = @fread($this->zip_fd, 4);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Binary data is : '".sprintf("%08x", $v_binary_data)."'");
$v_data = unpack('Vid', $v_binary_data);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Binary signature is : '".sprintf("0x%08x", $v_data['id'])."'");
// ----- Check signature
if ($v_data['id'] != 0x02014b50)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Invalid Central Dir File signature");
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Read the first 42 bytes of the header
$v_binary_data = fread($this->zip_fd, 42);
// ----- Look for invalid block size
if (strlen($v_binary_data) != 42)
{
$p_header['filename'] = "";
$p_header['status'] = "invalid_header";
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Invalid block size : ".strlen($v_binary_data));
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data));
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Extract the values
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Header : '".$v_binary_data."'");
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Header (Hex) : '".bin2hex($v_binary_data)."'");
$p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data);
// ----- Get filename
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "File name length : ".$p_header['filename_len']);
if ($p_header['filename_len'] != 0)
$p_header['filename'] = fread($this->zip_fd, $p_header['filename_len']);
else
$p_header['filename'] = '';
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Filename : \''.$p_header['filename'].'\'');
// ----- Get extra
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Extra length : ".$p_header['extra_len']);
if ($p_header['extra_len'] != 0)
$p_header['extra'] = fread($this->zip_fd, $p_header['extra_len']);
else
$p_header['extra'] = '';
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Extra : \''.$p_header['extra'].'\'');
// ----- Get comment
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Comment length : ".$p_header['comment_len']);
if ($p_header['comment_len'] != 0)
$p_header['comment'] = fread($this->zip_fd, $p_header['comment_len']);
else
$p_header['comment'] = '';
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Comment : \''.$p_header['comment'].'\'');
// ----- Extract properties
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Version : \''.($p_header['version']/10).'.'.($p_header['version']%10).'\'');
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Version need to extract : \''.($p_header['version_extracted']/10).'.'.($p_header['version_extracted']%10).'\'');
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Size : \''.$p_header['size'].'\'');
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Compressed Size : \''.$p_header['compressed_size'].'\'');
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'CRC : \''.sprintf("0x%X", $p_header['crc']).'\'');
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Flag : \''.$p_header['flag'].'\'');
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Offset : \''.$p_header['offset'].'\'');
// ----- Recuperate date in UNIX format
//if ($p_header['mdate'] && $p_header['mtime'])
// TBC : bug : this was ignoring time with 0/0/0
if (1)
{
// ----- Extract time
$v_hour = ($p_header['mtime'] & 0xF800) >> 11;
$v_minute = ($p_header['mtime'] & 0x07E0) >> 5;
$v_seconde = ($p_header['mtime'] & 0x001F)*2;
// ----- Extract date
$v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980;
$v_month = ($p_header['mdate'] & 0x01E0) >> 5;
$v_day = $p_header['mdate'] & 0x001F;
// ----- Get UNIX date format
$p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Date : \''.date("d/m/y H:i:s", $p_header['mtime']).'\'');
}
else
{
$p_header['mtime'] = time();
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Date is actual : \''.date("d/m/y H:i:s", $p_header['mtime']).'\'');
}
// ----- Set the stored filename
$p_header['stored_filename'] = $p_header['filename'];
// ----- Set default status to ok
$p_header['status'] = 'ok';
// ----- Look if it is a directory
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Internal (Hex) : '".sprintf("Ox%04X", $p_header['internal'])."'");
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "External (Hex) : '".sprintf("Ox%04X", $p_header['external'])."' (".(($p_header['external']&0x00000010)==0x00000010?'is a folder':'is a file').')');
if (substr($p_header['filename'], -1) == '/') {
//$p_header['external'] = 0x41FF0010;
$p_header['external'] = 0x00000010;
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Force folder external : \''.sprintf("Ox%04X", $p_header['external']).'\'');
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Header of filename : \''.$p_header['filename'].'\'');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCheckFileHeaders()
// Description :
// Parameters :
// Return Values :
// 1 on success,
// 0 on error;
// --------------------------------------------------------------------------------
function privCheckFileHeaders(&$p_local_header, &$p_central_header)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privCheckFileHeaders", "");
$v_result=1;
// ----- Check the static values
// TBC
if ($p_local_header['filename'] != $p_central_header['filename']) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "filename" : TBC To Be Completed');
}
if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "version_extracted" : TBC To Be Completed');
}
if ($p_local_header['flag'] != $p_central_header['flag']) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "flag" : TBC To Be Completed');
}
if ($p_local_header['compression'] != $p_central_header['compression']) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "compression" : TBC To Be Completed');
}
if ($p_local_header['mtime'] != $p_central_header['mtime']) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "mtime" : TBC To Be Completed');
}
if ($p_local_header['filename_len'] != $p_central_header['filename_len']) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "filename_len" : TBC To Be Completed');
}
// ----- Look for flag bit 3
if (($p_local_header['flag'] & 8) == 8) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Purpose bit flag bit 3 set !');
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'File size, compression size and crc found in central header');
$p_local_header['size'] = $p_central_header['size'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Size : \''.$p_local_header['size'].'\'');
$p_local_header['compressed_size'] = $p_central_header['compressed_size'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Compressed Size : \''.$p_local_header['compressed_size'].'\'');
$p_local_header['crc'] = $p_central_header['crc'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'CRC : \''.sprintf("0x%X", $p_local_header['crc']).'\'');
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privReadEndCentralDir()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privReadEndCentralDir(&$p_central_dir)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privReadEndCentralDir", "");
$v_result=1;
// ----- Go to the end of the zip file
$v_size = filesize($this->zipname);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Size of the file :$v_size");
@fseek($this->zip_fd, $v_size);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Position at end of zip file : \''.ftell($this->zip_fd).'\'');
if (@ftell($this->zip_fd) != $v_size)
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \''.$this->zipname.'\'');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- First try : look if this is an archive with no commentaries (most of the time)
// in this case the end of central dir is at 22 bytes of the file end
$v_found = 0;
if ($v_size > 26) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Look for central dir with no comment');
@fseek($this->zip_fd, $v_size-22);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Position after min central position : \''.ftell($this->zip_fd).'\'');
if (($v_pos = @ftell($this->zip_fd)) != ($v_size-22))
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\'');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Read for bytes
$v_binary_data = @fread($this->zip_fd, 4);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Binary data is : '".sprintf("%08x", $v_binary_data)."'");
$v_data = @unpack('Vid', $v_binary_data);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Binary signature is : '".sprintf("0x%08x", $v_data['id'])."'");
// ----- Check signature
if ($v_data['id'] == 0x06054b50) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Found central dir at the default position.");
$v_found = 1;
}
$v_pos = ftell($this->zip_fd);
}
// ----- Go back to the maximum possible size of the Central Dir End Record
if (!$v_found) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Start extended search of end central dir');
$v_maximum_size = 65557; // 0xFFFF + 22;
if ($v_maximum_size > $v_size)
$v_maximum_size = $v_size;
@fseek($this->zip_fd, $v_size-$v_maximum_size);
if (@ftell($this->zip_fd) != ($v_size-$v_maximum_size))
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\'');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Position after max central position : \''.ftell($this->zip_fd).'\'');
// ----- Read byte per byte in order to find the signature
$v_pos = ftell($this->zip_fd);
$v_bytes = 0x00000000;
while ($v_pos < $v_size)
{
// ----- Read a byte
$v_byte = @fread($this->zip_fd, 1);
// ----- Add the byte
$v_bytes = ($v_bytes << 8) | Ord($v_byte);
// ----- Compare the bytes
if ($v_bytes == 0x504b0506)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Found End Central Dir signature at position : \''.ftell($this->zip_fd).'\'');
$v_pos++;
break;
}
$v_pos++;
}
// ----- Look if not found end of central dir
if ($v_pos == $v_size)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unable to find End of Central Dir Record signature");
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
}
// ----- Read the first 18 bytes of the header
$v_binary_data = fread($this->zip_fd, 18);
// ----- Look for invalid block size
if (strlen($v_binary_data) != 18)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Invalid End of Central Dir Record size : ".strlen($v_binary_data));
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : ".strlen($v_binary_data));
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Extract the values
////--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Central Dir Record : '".$v_binary_data."'");
////--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Central Dir Record (Hex) : '".bin2hex($v_binary_data)."'");
$v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data);
// ----- Check the global size
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Comment length : ".$v_data['comment_size']);
if (($v_pos + $v_data['comment_size'] + 18) != $v_size) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "The central dir is not at the end of the archive. Some trailing bytes exists after the archive.");
// ----- Removed in release 2.2 see readme file
// The check of the file size is a little too strict.
// Some bugs where found when a zip is encrypted/decrypted with 'crypt'.
// While decrypted, zip has training 0 bytes
if (0) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT,
'The central dir is not at the end of the archive.'
.' Some trailing bytes exists after the archive.');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
}
// ----- Get comment
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Comment size : \''.$v_data['comment_size'].'\'');
if ($v_data['comment_size'] != 0) {
$p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']);
}
else
$p_central_dir['comment'] = '';
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Comment : \''.$p_central_dir['comment'].'\'');
$p_central_dir['entries'] = $v_data['entries'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Nb of entries : \''.$p_central_dir['entries'].'\'');
$p_central_dir['disk_entries'] = $v_data['disk_entries'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Nb of entries for this disk : \''.$p_central_dir['disk_entries'].'\'');
$p_central_dir['offset'] = $v_data['offset'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Offset of Central Dir : \''.$p_central_dir['offset'].'\'');
$p_central_dir['size'] = $v_data['size'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Size of Central Dir : \''.$p_central_dir['size'].'\'');
$p_central_dir['disk'] = $v_data['disk'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Disk number : \''.$p_central_dir['disk'].'\'');
$p_central_dir['disk_start'] = $v_data['disk_start'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Start disk number : \''.$p_central_dir['disk_start'].'\'');
// TBC
//for(reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) {
// //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "central_dir[$key] = ".$p_central_dir[$key]);
//}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privDeleteByRule()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privDeleteByRule(&$p_result_list, &$p_options)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privDeleteByRule", "");
$v_result=1;
$v_list_detail = array();
// ----- Open the zip file
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode");
if (($v_result=$this->privOpenFd('rb')) != 1)
{
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Read the central directory informations
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
$this->privCloseFd();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Go to beginning of File
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in file : ".ftell($this->zip_fd)."'");
@rewind($this->zip_fd);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in file : ".ftell($this->zip_fd)."'");
// ----- Scan all the files
// ----- Start at beginning of Central Dir
$v_pos_entry = $v_central_dir['offset'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position before rewind : ".ftell($this->zip_fd)."'");
@rewind($this->zip_fd);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position after rewind : ".ftell($this->zip_fd)."'");
if (@fseek($this->zip_fd, $v_pos_entry))
{
// ----- Close the zip file
$this->privCloseFd();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position after fseek : ".ftell($this->zip_fd)."'");
// ----- Read each entry
$v_header_list = array();
$j_start = 0;
for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Read next file header entry (index '$i')");
// ----- Read the file header
$v_header_list[$v_nb_extracted] = array();
if (($v_result = $this->privReadCentralFileHeader($v_header_list[$v_nb_extracted])) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Filename (index '$i') : '".$v_header_list[$v_nb_extracted]['stored_filename']."'");
// ----- Store the index
$v_header_list[$v_nb_extracted]['index'] = $i;
// ----- Look for the specific extract rules
$v_found = false;
// ----- Look for extract by name rule
if ( (isset($p_options[PCLZIP_OPT_BY_NAME]))
&& ($p_options[PCLZIP_OPT_BY_NAME] != 0)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with rule 'ByName'");
// ----- Look if the filename is in the list
for ($j=0; ($j<sizeof($p_options[PCLZIP_OPT_BY_NAME])) && (!$v_found); $j++) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Compare with file '".$p_options[PCLZIP_OPT_BY_NAME][$j]."'");
// ----- Look for a directory
if (substr($p_options[PCLZIP_OPT_BY_NAME][$j], -1) == "/") {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The searched item is a directory");
// ----- Look if the directory is in the filename path
if ( (strlen($v_header_list[$v_nb_extracted]['stored_filename']) > strlen($p_options[PCLZIP_OPT_BY_NAME][$j]))
&& (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The directory is in the file path");
$v_found = true;
}
elseif ( (($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) /* Indicates a folder */
&& ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_options[PCLZIP_OPT_BY_NAME][$j])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The entry is the searched directory");
$v_found = true;
}
}
// ----- Look for a filename
elseif ($v_header_list[$v_nb_extracted]['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The file is the right one.");
$v_found = true;
}
}
}
// ----- Look for extract by ereg rule
else if ( (isset($p_options[PCLZIP_OPT_BY_EREG]))
&& ($p_options[PCLZIP_OPT_BY_EREG] != "")) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract by ereg '".$p_options[PCLZIP_OPT_BY_EREG]."'");
if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header_list[$v_nb_extracted]['stored_filename'])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Filename match the regular expression");
$v_found = true;
}
}
// ----- Look for extract by preg rule
else if ( (isset($p_options[PCLZIP_OPT_BY_PREG]))
&& ($p_options[PCLZIP_OPT_BY_PREG] != "")) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with rule 'ByEreg'");
if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header_list[$v_nb_extracted]['stored_filename'])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Filename match the regular expression");
$v_found = true;
}
}
// ----- Look for extract by index rule
else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX]))
&& ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with rule 'ByIndex'");
// ----- Look if the index is in the list
for ($j=$j_start; ($j<sizeof($p_options[PCLZIP_OPT_BY_INDEX])) && (!$v_found); $j++) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Look if index '$i' is in [".$p_options[PCLZIP_OPT_BY_INDEX][$j]['start'].",".$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']."]");
if (($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Found as part of an index range");
$v_found = true;
}
if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Do not look this index range for next loop");
$j_start = $j+1;
}
if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Index range is greater than index, stop loop");
break;
}
}
}
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "No argument mean remove all file");
$v_found = true;
}
// ----- Look for deletion
if ($v_found)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File '".$v_header_list[$v_nb_extracted]['stored_filename']."', index '$i' need to be deleted");
unset($v_header_list[$v_nb_extracted]);
}
else
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File '".$v_header_list[$v_nb_extracted]['stored_filename']."', index '$i' will not be deleted");
$v_nb_extracted++;
}
}
// ----- Look if something need to be deleted
if ($v_nb_extracted > 0) {
// ----- Creates a temporay file
$v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
// ----- Creates a temporary zip archive
$v_temp_zip = new PclZip($v_zip_temp_name);
// ----- Open the temporary zip file in write mode
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary write mode");
if (($v_result = $v_temp_zip->privOpenFd('wb')) != 1) {
$this->privCloseFd();
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Look which file need to be kept
for ($i=0; $i<sizeof($v_header_list); $i++) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Keep entry index '$i' : '".$v_header_list[$i]['filename']."'");
// ----- Calculate the position of the header
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Offset='". $v_header_list[$i]['offset']."'");
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position before rewind : ".ftell($this->zip_fd)."'");
@rewind($this->zip_fd);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position after rewind : ".ftell($this->zip_fd)."'");
if (@fseek($this->zip_fd, $v_header_list[$i]['offset'])) {
// ----- Close the zip file
$this->privCloseFd();
$v_temp_zip->privCloseFd();
@unlink($v_zip_temp_name);
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position after fseek : ".ftell($this->zip_fd)."'");
// ----- Read the file header
$v_local_header = array();
if (($v_result = $this->privReadFileHeader($v_local_header)) != 1) {
// ----- Close the zip file
$this->privCloseFd();
$v_temp_zip->privCloseFd();
@unlink($v_zip_temp_name);
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Check that local file header is same as central file header
if ($this->privCheckFileHeaders($v_local_header,
$v_header_list[$i]) != 1) {
// TBC
}
unset($v_local_header);
// ----- Write the file header
if (($v_result = $v_temp_zip->privWriteFileHeader($v_header_list[$i])) != 1) {
// ----- Close the zip file
$this->privCloseFd();
$v_temp_zip->privCloseFd();
@unlink($v_zip_temp_name);
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Offset for this file is '".$v_header_list[$i]['offset']."'");
// ----- Read/write the data block
if (($v_result = PclZipUtilCopyBlock($this->zip_fd, $v_temp_zip->zip_fd, $v_header_list[$i]['compressed_size'])) != 1) {
// ----- Close the zip file
$this->privCloseFd();
$v_temp_zip->privCloseFd();
@unlink($v_zip_temp_name);
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
}
// ----- Store the offset of the central dir
$v_offset = @ftell($v_temp_zip->zip_fd);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "New offset of central dir : $v_offset");
// ----- Re-Create the Central Dir files header
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Creates the new central directory");
for ($i=0; $i<sizeof($v_header_list); $i++) {
// ----- Create the file header
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Offset of file : ".$v_header_list[$i]['offset']);
if (($v_result = $v_temp_zip->privWriteCentralFileHeader($v_header_list[$i])) != 1) {
$v_temp_zip->privCloseFd();
$this->privCloseFd();
@unlink($v_zip_temp_name);
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Transform the header to a 'usable' info
$v_temp_zip->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Creates the central directory footer");
// ----- Zip file comment
$v_comment = '';
if (isset($p_options[PCLZIP_OPT_COMMENT])) {
$v_comment = $p_options[PCLZIP_OPT_COMMENT];
}
// ----- Calculate the size of the central header
$v_size = @ftell($v_temp_zip->zip_fd)-$v_offset;
// ----- Create the central dir footer
if (($v_result = $v_temp_zip->privWriteCentralHeader(sizeof($v_header_list), $v_size, $v_offset, $v_comment)) != 1) {
// ----- Reset the file list
unset($v_header_list);
$v_temp_zip->privCloseFd();
$this->privCloseFd();
@unlink($v_zip_temp_name);
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Close
$v_temp_zip->privCloseFd();
$this->privCloseFd();
// ----- Delete the zip file
// TBC : I should test the result ...
@unlink($this->zipname);
// ----- Rename the temporary file
// TBC : I should test the result ...
//@rename($v_zip_temp_name, $this->zipname);
PclZipUtilRename($v_zip_temp_name, $this->zipname);
// ----- Destroy the temporary archive
unset($v_temp_zip);
}
// ----- Remove every files : reset the file
else if ($v_central_dir['entries'] != 0) {
$this->privCloseFd();
if (($v_result = $this->privOpenFd('wb')) != 1) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
if (($v_result = $this->privWriteCentralHeader(0, 0, 0, '')) != 1) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
$this->privCloseFd();
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privDirCheck()
// Description :
// Check if a directory exists, if not it creates it and all the parents directory
// which may be useful.
// Parameters :
// $p_dir : Directory path to check.
// Return Values :
// 1 : OK
// -1 : Unable to create directory
// --------------------------------------------------------------------------------
function privDirCheck($p_dir, $p_is_dir=false)
{
$v_result = 1;
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privDirCheck", "entry='$p_dir', is_dir='".($p_is_dir?"true":"false")."'");
// ----- Remove the final '/'
if (($p_is_dir) && (substr($p_dir, -1)=='/'))
{
$p_dir = substr($p_dir, 0, strlen($p_dir)-1);
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Looking for entry '$p_dir'");
// ----- Check the directory availability
if ((is_dir($p_dir)) || ($p_dir == ""))
{
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, "'$p_dir' is a directory");
return 1;
}
// ----- Extract parent directory
$p_parent_dir = dirname($p_dir);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Parent directory is '$p_parent_dir'");
// ----- Just a check
if ($p_parent_dir != $p_dir)
{
// ----- Look for parent directory
if ($p_parent_dir != "")
{
if (($v_result = $this->privDirCheck($p_parent_dir)) != 1)
{
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
}
}
// ----- Create the directory
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Create directory '$p_dir'");
if (!@mkdir($p_dir, 0777))
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result, "Directory '$p_dir' created");
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privMerge()
// Description :
// If $p_archive_to_add does not exist, the function exit with a success result.
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privMerge(&$p_archive_to_add)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privMerge", "archive='".$p_archive_to_add->zipname."'");
$v_result=1;
// ----- Look if the archive_to_add exists
if (!is_file($p_archive_to_add->zipname))
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Archive to add does not exist. End of merge.");
// ----- Nothing to merge, so merge is a success
$v_result = 1;
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Look if the archive exists
if (!is_file($this->zipname))
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Archive does not exist, duplicate the archive_to_add.");
// ----- Do a duplicate
$v_result = $this->privDuplicate($p_archive_to_add->zipname);
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Open the zip file
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode");
if (($v_result=$this->privOpenFd('rb')) != 1)
{
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Read the central directory informations
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
$this->privCloseFd();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Go to beginning of File
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in zip : ".ftell($this->zip_fd)."'");
@rewind($this->zip_fd);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in zip : ".ftell($this->zip_fd)."'");
// ----- Open the archive_to_add file
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open archive_to_add in binary read mode");
if (($v_result=$p_archive_to_add->privOpenFd('rb')) != 1)
{
$this->privCloseFd();
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Read the central directory informations
$v_central_dir_to_add = array();
if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1)
{
$this->privCloseFd();
$p_archive_to_add->privCloseFd();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Go to beginning of File
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in archive_to_add : ".ftell($p_archive_to_add->zip_fd)."'");
@rewind($p_archive_to_add->zip_fd);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in archive_to_add : ".ftell($p_archive_to_add->zip_fd)."'");
// ----- Creates a temporay file
$v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
// ----- Open the temporary file in write mode
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode");
if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0)
{
$this->privCloseFd();
$p_archive_to_add->privCloseFd();
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Copy the files from the archive to the temporary file
// TBC : Here I should better append the file and go back to erase the central dir
$v_size = $v_central_dir['offset'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes");
$v_buffer = fread($this->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Copy the files from the archive_to_add into the temporary file
$v_size = $v_central_dir_to_add['offset'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes");
$v_buffer = fread($p_archive_to_add->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Store the offset of the central dir
$v_offset = @ftell($v_zip_temp_fd);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "New offset of central dir : $v_offset");
// ----- Copy the block of file headers from the old archive
$v_size = $v_central_dir['size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes");
$v_buffer = @fread($this->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Copy the block of file headers from the archive_to_add
$v_size = $v_central_dir_to_add['size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes");
$v_buffer = @fread($p_archive_to_add->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Merge the file comments
$v_comment = $v_central_dir['comment'].' '.$v_central_dir_to_add['comment'];
// ----- Calculate the size of the (new) central header
$v_size = @ftell($v_zip_temp_fd)-$v_offset;
// ----- Swap the file descriptor
// Here is a trick : I swap the temporary fd with the zip fd, in order to use
// the following methods on the temporary fil and not the real archive fd
$v_swap = $this->zip_fd;
$this->zip_fd = $v_zip_temp_fd;
$v_zip_temp_fd = $v_swap;
// ----- Create the central dir footer
if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries']+$v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1)
{
$this->privCloseFd();
$p_archive_to_add->privCloseFd();
@fclose($v_zip_temp_fd);
$this->zip_fd = null;
// ----- Reset the file list
unset($v_header_list);
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Swap back the file descriptor
$v_swap = $this->zip_fd;
$this->zip_fd = $v_zip_temp_fd;
$v_zip_temp_fd = $v_swap;
// ----- Close
$this->privCloseFd();
$p_archive_to_add->privCloseFd();
// ----- Close the temporary file
@fclose($v_zip_temp_fd);
// ----- Delete the zip file
// TBC : I should test the result ...
@unlink($this->zipname);
// ----- Rename the temporary file
// TBC : I should test the result ...
//@rename($v_zip_temp_name, $this->zipname);
PclZipUtilRename($v_zip_temp_name, $this->zipname);
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privDuplicate()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privDuplicate($p_archive_filename)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privDuplicate", "archive_filename='$p_archive_filename'");
$v_result=1;
// ----- Look if the $p_archive_filename exists
if (!is_file($p_archive_filename))
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Archive to duplicate does not exist. End of duplicate.");
// ----- Nothing to duplicate, so duplicate is a success.
$v_result = 1;
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Open the zip file
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode");
if (($v_result=$this->privOpenFd('wb')) != 1)
{
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Open the temporary file in write mode
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode");
if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0)
{
$this->privCloseFd();
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \''.$p_archive_filename.'\' in binary write mode');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Copy the files from the archive to the temporary file
// TBC : Here I should better append the file and go back to erase the central dir
$v_size = filesize($p_archive_filename);
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Read $v_read_size bytes");
$v_buffer = fread($v_zip_temp_fd, $v_read_size);
@fwrite($this->zip_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Close
$this->privCloseFd();
// ----- Close the temporary file
@fclose($v_zip_temp_fd);
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privErrorLog()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function privErrorLog($p_error_code=0, $p_error_string='')
{
if (PCLZIP_ERROR_EXTERNAL == 1) {
PclError($p_error_code, $p_error_string);
}
else {
$this->error_code = $p_error_code;
$this->error_string = $p_error_string;
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privErrorReset()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function privErrorReset()
{
if (PCLZIP_ERROR_EXTERNAL == 1) {
PclErrorReset();
}
else {
$this->error_code = 0;
$this->error_string = '';
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privDecrypt()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privDecrypt($p_encryption_header, &$p_buffer, $p_size, $p_crc)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privDecrypt', "size=".$p_size."");
$v_result=1;
// ----- To Be Modified ;-)
$v_pwd = "test";
$p_buffer = PclZipUtilZipDecrypt($p_buffer, $p_size, $p_encryption_header,
$p_crc, $v_pwd);
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privDisableMagicQuotes()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privDisableMagicQuotes()
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privDisableMagicQuotes', "");
$v_result=1;
// ----- Look if function exists
if ( (!function_exists("get_magic_quotes_runtime"))
|| (!function_exists("set_magic_quotes_runtime"))) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Functions *et_magic_quotes_runtime are not supported");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Look if already done
if ($this->magic_quotes_status != -1) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "magic_quote already disabled");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Get and memorize the magic_quote value
$this->magic_quotes_status = @get_magic_quotes_runtime();
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Current magic_quotes_runtime status is '".($this->magic_quotes_status==0?'disable':'enable')."'");
// ----- Disable magic_quotes
if ($this->magic_quotes_status == 1) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Disable magic_quotes");
@set_magic_quotes_runtime(0);
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privSwapBackMagicQuotes()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privSwapBackMagicQuotes()
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privSwapBackMagicQuotes', "");
$v_result=1;
// ----- Look if function exists
if ( (!function_exists("get_magic_quotes_runtime"))
|| (!function_exists("set_magic_quotes_runtime"))) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Functions *et_magic_quotes_runtime are not supported");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Look if something to do
if ($this->magic_quotes_status != -1) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "magic_quote not modified");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Swap back magic_quotes
if ($this->magic_quotes_status == 1) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Enable back magic_quotes");
@set_magic_quotes_runtime($this->magic_quotes_status);
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
}
// End of class
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclZipUtilPathReduction()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function PclZipUtilPathReduction($p_dir)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZipUtilPathReduction", "dir='$p_dir'");
$v_result = "";
// ----- Look for not empty path
if ($p_dir != "") {
// ----- Explode path by directory names
$v_list = explode("/", $p_dir);
// ----- Study directories from last to first
$v_skip = 0;
for ($i=sizeof($v_list)-1; $i>=0; $i--) {
// ----- Look for current path
if ($v_list[$i] == ".") {
// ----- Ignore this directory
// Should be the first $i=0, but no check is done
}
else if ($v_list[$i] == "..") {
$v_skip++;
}
else if ($v_list[$i] == "") {
// ----- First '/' i.e. root slash
if ($i == 0) {
$v_result = "/".$v_result;
if ($v_skip > 0) {
// ----- It is an invalid path, so the path is not modified
// TBC
$v_result = $p_dir;
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Invalid path is unchanged");
$v_skip = 0;
}
}
// ----- Last '/' i.e. indicates a directory
else if ($i == (sizeof($v_list)-1)) {
$v_result = $v_list[$i];
}
// ----- Double '/' inside the path
else {
// ----- Ignore only the double '//' in path,
// but not the first and last '/'
}
}
else {
// ----- Look for item to skip
if ($v_skip > 0) {
$v_skip--;
}
else {
$v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:"");
}
}
}
// ----- Look for skip
if ($v_skip > 0) {
while ($v_skip > 0) {
$v_result = '../'.$v_result;
$v_skip--;
}
}
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclZipUtilPathInclusion()
// Description :
// This function indicates if the path $p_path is under the $p_dir tree. Or,
// said in an other way, if the file or sub-dir $p_path is inside the dir
// $p_dir.
// The function indicates also if the path is exactly the same as the dir.
// This function supports path with duplicated '/' like '//', but does not
// support '.' or '..' statements.
// Parameters :
// Return Values :
// 0 if $p_path is not inside directory $p_dir
// 1 if $p_path is inside directory $p_dir
// 2 if $p_path is exactly the same as $p_dir
// --------------------------------------------------------------------------------
function PclZipUtilPathInclusion($p_dir, $p_path)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZipUtilPathInclusion", "dir='$p_dir', path='$p_path'");
$v_result = 1;
// ----- Look for path beginning by ./
if ( ($p_dir == '.')
|| ((strlen($p_dir) >=2) && (substr($p_dir, 0, 2) == './'))) {
$p_dir = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_dir, 1);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Replacing ./ by full path in p_dir '".$p_dir."'");
}
if ( ($p_path == '.')
|| ((strlen($p_path) >=2) && (substr($p_path, 0, 2) == './'))) {
$p_path = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_path, 1);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Replacing ./ by full path in p_path '".$p_path."'");
}
// ----- Explode dir and path by directory separator
$v_list_dir = explode("/", $p_dir);
$v_list_dir_size = sizeof($v_list_dir);
$v_list_path = explode("/", $p_path);
$v_list_path_size = sizeof($v_list_path);
// ----- Study directories paths
$i = 0;
$j = 0;
while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Working on dir($i)='".$v_list_dir[$i]."' and path($j)='".$v_list_path[$j]."'");
// ----- Look for empty dir (path reduction)
if ($v_list_dir[$i] == '') {
$i++;
continue;
}
if ($v_list_path[$j] == '') {
$j++;
continue;
}
// ----- Compare the items
if (($v_list_dir[$i] != $v_list_path[$j]) && ($v_list_dir[$i] != '') && ( $v_list_path[$j] != '')) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Items ($i,$j) are different");
$v_result = 0;
}
// ----- Next items
$i++;
$j++;
}
// ----- Look if everything seems to be the same
if ($v_result) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Look for tie break");
// ----- Skip all the empty items
while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) $j++;
while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) $i++;
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Looking on dir($i)='".($i < $v_list_dir_size?$v_list_dir[$i]:'')."' and path($j)='".($j < $v_list_path_size?$v_list_path[$j]:'')."'");
if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) {
// ----- There are exactly the same
$v_result = 2;
}
else if ($i < $v_list_dir_size) {
// ----- The path is shorter than the dir
$v_result = 0;
}
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclZipUtilCopyBlock()
// Description :
// Parameters :
// $p_mode : read/write compression mode
// 0 : src & dest normal
// 1 : src gzip, dest normal
// 2 : src normal, dest gzip
// 3 : src & dest gzip
// Return Values :
// --------------------------------------------------------------------------------
function PclZipUtilCopyBlock($p_src, $p_dest, $p_size, $p_mode=0)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZipUtilCopyBlock", "size=$p_size, mode=$p_mode");
$v_result = 1;
if ($p_mode==0)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Src offset before read :".(@ftell($p_src)));
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Dest offset before write :".(@ftell($p_dest)));
while ($p_size != 0)
{
$v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes");
$v_buffer = @fread($p_src, $v_read_size);
@fwrite($p_dest, $v_buffer, $v_read_size);
$p_size -= $v_read_size;
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Src offset after read :".(@ftell($p_src)));
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Dest offset after write :".(@ftell($p_dest)));
}
else if ($p_mode==1)
{
while ($p_size != 0)
{
$v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes");
$v_buffer = @gzread($p_src, $v_read_size);
@fwrite($p_dest, $v_buffer, $v_read_size);
$p_size -= $v_read_size;
}
}
else if ($p_mode==2)
{
while ($p_size != 0)
{
$v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes");
$v_buffer = @fread($p_src, $v_read_size);
@gzwrite($p_dest, $v_buffer, $v_read_size);
$p_size -= $v_read_size;
}
}
else if ($p_mode==3)
{
while ($p_size != 0)
{
$v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes");
$v_buffer = @gzread($p_src, $v_read_size);
@gzwrite($p_dest, $v_buffer, $v_read_size);
$p_size -= $v_read_size;
}
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclZipUtilRename()
// Description :
// This function tries to do a simple rename() function. If it fails, it
// tries to copy the $p_src file in a new $p_dest file and then unlink the
// first one.
// Parameters :
// $p_src : Old filename
// $p_dest : New filename
// Return Values :
// 1 on success, 0 on failure.
// --------------------------------------------------------------------------------
function PclZipUtilRename($p_src, $p_dest)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZipUtilRename", "source=$p_src, destination=$p_dest");
$v_result = 1;
// ----- Try to rename the files
if (!@rename($p_src, $p_dest)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Fail to rename file, try copy+unlink");
// ----- Try to copy & unlink the src
if (!@copy($p_src, $p_dest)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Fail to copy file");
$v_result = 0;
}
else if (!@unlink($p_src)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Fail to unlink old filename");
$v_result = 0;
}
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclZipUtilOptionText()
// Description :
// Translate option value in text. Mainly for debug purpose.
// Parameters :
// $p_option : the option value.
// Return Values :
// The option text value.
// --------------------------------------------------------------------------------
function PclZipUtilOptionText($p_option)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZipUtilOptionText", "option='".$p_option."'");
$v_list = get_defined_constants();
for (reset($v_list); $v_key = key($v_list); next($v_list)) {
$v_prefix = substr($v_key, 0, 10);
if (( ($v_prefix == 'PCLZIP_OPT')
|| ($v_prefix == 'PCLZIP_CB_')
|| ($v_prefix == 'PCLZIP_ATT'))
&& ($v_list[$v_key] == $p_option)) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_key);
return $v_key;
}
}
$v_result = 'Unknown';
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclZipUtilTranslateWinPath()
// Description :
// Translate windows path by replacing '\' by '/' and optionally removing
// drive letter.
// Parameters :
// $p_path : path to translate.
// $p_remove_disk_letter : true | false
// Return Values :
// The path translated.
// --------------------------------------------------------------------------------
function PclZipUtilTranslateWinPath($p_path, $p_remove_disk_letter=true)
{
if (stristr(php_uname(), 'windows')) {
// ----- Look for potential disk letter
if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) {
$p_path = substr($p_path, $v_position+1);
}
// ----- Change potential windows directory separator
if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) {
$p_path = strtr($p_path, '\\', '/');
}
}
return $p_path;
}
// --------------------------------------------------------------------------------
?>
| PHP |
<?php
define('IN_PHPSSO', true);
class phpsso {
public $db, $settings, $applist, $appid, $data;
/**
* 构造函数
*/
public function __construct() {
$this->db = pc_base::load_model('member_model');
pc_base::load_app_func('global');
/*获取系统配置*/
$this->settings = getcache('settings', 'admin');
$this->applist = getcache('applist', 'admin');
if(isset($_GET) && is_array($_GET) && count($_GET) > 0) {
foreach($_GET as $k=>$v) {
if(!in_array($k, array('m','c','a'))) {
$_POST[$k] = $v;
}
}
}
if(isset($_POST['appid'])) {
$this->appid = intval($_POST['appid']);
} else {
exit('0');
}
if(isset($_POST['data'])) {
parse_str(sys_auth($_POST['data'], 'DECODE', $this->applist[$this->appid]['authkey']), $this->data);
if(get_magic_quotes_gpc()) {
$this->data = new_stripslashes($this->data);
}
if(!is_array($this->data)) {
exit('0');
}
} else {
exit('0');
}
if(isset($GLOBALS['HTTP_RAW_POST_DATA'])) {
$this->data['avatardata'] = $GLOBALS['HTTP_RAW_POST_DATA'];
if($this->applist[$this->appid]['authkey'] != $this->data['ps_auth_key']) {
exit('0');
}
}
}
} | PHP |
<?php
/**
* 生成随机字符串
* @param string $lenth 长度
* @return string 字符串
*/
function create_randomstr($lenth = 6) {
return random($lenth, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
}
/**
*
* @param $password 密码
* @param $random 随机数
*/
function create_password($password='', $random='') {
if(empty($random)) {
$array['random'] = create_randomstr();
$array['password'] = md5(md5($password).$array['random']);
return $array;
}
return md5(md5($password).$random);
}
?> | PHP |
<?php
/**
* cache_factory.class.php 缓存工厂类
*
* @copyright (C) 2005-2010 PHPCMS
* @license http://www.phpcms.cn/license/
* @lastmodify 2010-6-1
*/
final class cache_factory {
/**
* 当前缓存工厂类静态实例
*/
private static $cache_factory;
/**
* 缓存配置列表
*/
protected $cache_config = array();
/**
* 缓存操作实例化列表
*/
protected $cache_list = array();
/**
* 构造函数
*/
function __construct() {
}
/**
* 返回当前终级类对象的实例
* @param $cache_config 缓存配置
* @return object
*/
public static function get_instance($cache_config = '') {
if(cache_factory::$cache_factory == '') {
cache_factory::$cache_factory = new cache_factory();
if(!empty($cache_config)) {
cache_factory::$cache_factory->cache_config = $cache_config;
}
}
return cache_factory::$cache_factory;
}
/**
* 获取缓存操作实例
* @param $cache_name 缓存配置名称
*/
public function get_cache($cache_name) {
if(!isset($this->cache_list[$cache_name]) || !is_object($this->cache_list[$cache_name])) {
$this->cache_list[$cache_name] = $this->load($cache_name);
}
return $this->cache_list[$cache_name];
}
/**
* 加载缓存驱动
* @param $cache_name 缓存配置名称
* @return object
*/
public function load($cache_name) {
$object = null;
if(isset($this->cache_config[$cache_name]['type'])) {
switch($this->cache_config[$cache_name]['type']) {
case 'file' :
$object = pc_base::load_sys_class('cache_file');
break;
case 'memcache' :
define('MEMCACHE_HOST', $this->cache_config[$cache_name]['hostname']);
define('MEMCACHE_PORT', $this->cache_config[$cache_name]['port']);
define('MEMCACHE_TIMEOUT', $this->cache_config[$cache_name]['timeout']);
define('MEMCACHE_DEBUG', $this->cache_config[$cache_name]['debug']);
$object = pc_base::load_sys_class('cache_memcache');
break;
case 'apc' :
$object = pc_base::load_sys_class('cache_apc');
break;
default :
$object = pc_base::load_sys_class('cache_file');
}
} else {
$object = pc_base::load_sys_class('cache_file');
}
return $object;
}
}
?> | PHP |
<?php
/**
* mysql.class.php 数据库实现类
*
* @copyright (C) 2005-2010 PHPCMS
* @license http://www.phpcms.cn/license/
* @lastmodify 2010-6-1
*/
final class mysql {
/**
* 数据库配置信息
*/
private $config = null;
/**
* 数据库连接资源句柄
*/
public $link = null;
/**
* 最近一次查询资源句柄
*/
public $lastqueryid = null;
/**
* 统计数据库查询次数
*/
public $querycount = 0;
public function __construct() {
}
/**
* 打开数据库连接,有可能不真实连接数据库
* @param $config 数据库连接参数
*
* @return void
*/
public function open($config) {
$this->config = $config;
if($config['autoconnect'] == 1) {
$this->connect();
}
}
/**
* 真正开启数据库连接
*
* @return void
*/
public function connect() {
$func = $this->config['pconnect'] == 1 ? 'mysql_pconnect' : 'mysql_connect';
if(!$this->link = @$func($this->config['hostname'], $this->config['username'], $this->config['password'], 1)) {
$this->halt('Can not connect to MySQL server');
return false;
}
if($this->version() > '4.1') {
$charset = isset($this->config['charset']) ? $this->config['charset'] : '';
$serverset = $charset ? "character_set_connection='$charset',character_set_results='$charset',character_set_client=binary" : '';
$serverset .= $this->version() > '5.0.1' ? ((empty($serverset) ? '' : ',')." sql_mode='' ") : '';
$serverset && mysql_query("SET $serverset", $this->link);
}
if($this->config['database'] && !@mysql_select_db($this->config['database'], $this->link)) {
$this->halt('Cannot use database '.$this->config['database']);
return false;
}
$this->database = $this->config['database'];
return $this->link;
}
/**
* 数据库查询执行方法
* @param $sql 要执行的sql语句
* @return 查询资源句柄
*/
private function execute($sql) {
if(!is_resource($this->link)) {
$this->connect();
}
$this->lastqueryid = mysql_query($sql, $this->link) or $this->halt(mysql_error());
$this->querycount++;
return $this->lastqueryid;
}
/**
* 执行sql查询
* @param $data 需要查询的字段值[例`name`,`gender`,`birthday`]
* @param $table 数据表
* @param $where 查询条件[例`name`='$name']
* @param $limit 返回结果范围[例:10或10,10 默认为空]
* @param $order 排序方式 [默认按数据库默认方式排序]
* @param $group 分组方式 [默认为空]
* @param $key 返回数组按键名排序
* @return array 查询结果集数组
*/
public function select($data, $table, $where = '', $limit = '', $order = '', $group = '', $key = '') {
$where = $where == '' ? '' : ' WHERE '.$where;
$order = $order == '' ? '' : ' ORDER BY '.$order;
$group = $group == '' ? '' : ' GROUP BY '.$group;
$limit = $limit == '' ? '' : ' LIMIT '.$limit;
$field = explode(',', $data);
array_walk($field, array($this, 'add_special_char'));
$data = implode(',', $field);
$sql = 'SELECT '.$data.' FROM `'.$this->config['database'].'`.`'.$table.'`'.$where.$group.$order.$limit;
$this->execute($sql);
if(!is_resource($this->lastqueryid)) {
return $this->lastqueryid;
}
$datalist = array();
while(($rs = $this->fetch_next()) != false) {
if($key) {
$datalist[$rs[$key]] = $rs;
} else {
$datalist[] = $rs;
}
}
$this->free_result();
return $datalist;
}
/**
* 获取单条记录查询
* @param $data 需要查询的字段值[例`name`,`gender`,`birthday`]
* @param $table 数据表
* @param $where 查询条件
* @param $order 排序方式 [默认按数据库默认方式排序]
* @param $group 分组方式 [默认为空]
* @return array/null 数据查询结果集,如果不存在,则返回空
*/
public function get_one($data, $table, $where = '', $order = '', $group = '') {
$where = $where == '' ? '' : ' WHERE '.$where;
$order = $order == '' ? '' : ' ORDER BY '.$order;
$group = $group == '' ? '' : ' GROUP BY '.$group;
$limit = ' LIMIT 1';
$field = explode( ',', $data);
array_walk($field, array($this, 'add_special_char'));
$data = implode(',', $field);
$sql = 'SELECT '.$data.' FROM `'.$this->config['database'].'`.`'.$table.'`'.$where.$group.$order.$limit;
$this->execute($sql);
$res = $this->fetch_next();
$this->free_result();
return $res;
}
/**
* 遍历查询结果集
* @param $type 返回结果集类型
* MYSQL_ASSOC,MYSQL_NUM 和 MYSQL_BOTH
* @return array
*/
public function fetch_next($type=MYSQL_ASSOC) {
$res = mysql_fetch_array($this->lastqueryid, $type);
if(!$res) {
$this->free_result();
}
return $res;
}
/**
* 释放查询资源
* @return void
*/
public function free_result() {
if(is_resource($this->lastqueryid)) {
mysql_free_result($this->lastqueryid);
$this->lastqueryid = null;
}
}
/**
* 直接执行sql查询
* @param $sql 查询sql语句
* @return boolean/query resource 如果为查询语句,返回资源句柄,否则返回true/false
*/
public function query($sql) {
return $this->execute($sql);
}
/**
* 执行添加记录操作
* @param $data 要增加的数据,参数为数组。数组key为字段值,数组值为数据取值
* @param $table 数据表
* @return boolean
*/
public function insert($data, $table, $return_insert_id = false, $replace = false) {
if(!is_array( $data ) || $table == '' || count($data) == 0) {
return false;
}
$fielddata = array_keys($data);
$valuedata = array_values($data);
array_walk($fielddata, array($this, 'add_special_char'));
array_walk($valuedata, array($this, 'escape_string'));
$field = implode (',', $fielddata);
$value = implode (',', $valuedata);
$cmd = $replace ? 'REPLACE INTO' : 'INSERT INTO';
$sql = $cmd.' `'.$this->config['database'].'`.`'.$table.'`('.$field.') VALUES ('.$value.')';
$return = $this->execute($sql);
return $return_insert_id ? $this->insert_id() : $return;
}
/**
* 获取最后一次添加记录的主键号
* @return int
*/
public function insert_id() {
return mysql_insert_id($this->link);
}
/**
* 执行更新记录操作
* @param $data 要更新的数据内容,参数可以为数组也可以为字符串,建议数组。
* 为数组时数组key为字段值,数组值为数据取值
* 为字符串时[例:`name`='phpcms',`hits`=`hits`+1]。
* 为数组时[例: array('name'=>'phpcms','password'=>'123456')]
* 数组可使用array('name'=>'+=1', 'base'=>'-=1');程序会自动解析为`name` = `name` + 1, `base` = `base` - 1
* @param $table 数据表
* @param $where 更新数据时的条件
* @return boolean
*/
public function update($data, $table, $where = '') {
if($table == '' or $where == '') {
return false;
}
$where = ' WHERE '.$where;
$field = '';
if(is_string($data) && $data != '') {
$field = $data;
} elseif (is_array($data) && count($data) > 0) {
$fields = array();
foreach($data as $k=>$v) {
switch (substr($v, 0, 2)) {
case '+=':
$v = substr($v,2);
if (is_numeric($v)) {
$fields[] = $this->add_special_char($k).'='.$this->add_special_char($k).'+'.$this->escape_string($v, '', false);
} else {
continue;
}
break;
case '-=':
$v = substr($v,2);
if (is_numeric($v)) {
$fields[] = $this->add_special_char($k).'='.$this->add_special_char($k).'-'.$this->escape_string($v, '', false);
} else {
continue;
}
break;
default:
$fields[] = $this->add_special_char($k).'='.$this->escape_string($v);
}
}
$field = implode(',', $fields);
} else {
return false;
}
$sql = 'UPDATE `'.$this->config['database'].'`.`'.$table.'` SET '.$field.$where;
return $this->execute($sql);
}
/**
* 执行删除记录操作
* @param $table 数据表
* @param $where 删除数据条件,不充许为空。
* 如果要清空表,使用empty方法
* @return boolean
*/
public function delete($table, $where) {
if ($table == '' || $where == '') {
return false;
}
$where = ' WHERE '.$where;
$sql = 'DELETE FROM `'.$this->config['database'].'`.`'.$table.'`'.$where;
return $this->execute($sql);
}
/**
* 获取最后数据库操作影响到的条数
* @return int
*/
public function affected_rows() {
return mysql_affected_rows($this->link);
}
/**
* 获取数据表主键
* @param $table 数据表
* @return array
*/
public function get_primary($table) {
$this->execute("SHOW COLUMNS FROM $table");
while($r = $this->fetch_next()) {
if($r['Key'] == 'PRI') break;
}
return $r['Field'];
}
/**
* 获取表字段
* @param $table 数据表
* @return array
*/
public function get_fields($table) {
$fields = array();
$this->execute("SHOW COLUMNS FROM $table");
while($r = $this->fetch_next()) {
$fields[$r['Field']] = $r['Type'];
}
return $fields;
}
/**
* 检查不存在的字段
* @param $table 表名
* @return array
*/
public function check_fields($table, $array) {
$fields = $this->get_fields($table);
$nofields = array();
foreach($array as $v) {
if(!array_key_exists($v, $fields)) {
$nofields[] = $v;
}
}
return $nofields;
}
/**
* 检查表是否存在
* @param $table 表名
* @return boolean
*/
public function table_exists($table) {
$tables = $this->list_tables();
return in_array($table, $tables) ? 1 : 0;
}
public function list_tables() {
$tables = array();
$this->execute("SHOW TABLES");
while($r = $this->fetch_next()) {
$tables[] = $r['Tables_in_'.$this->config['database']];
}
return $tables;
}
/**
* 检查字段是否存在
* @param $table 表名
* @return boolean
*/
public function field_exists($table, $field) {
$fields = $this->get_fields($table);
return in_array($field, $fields);
}
public function num_rows($sql) {
$this->lastqueryid = $this->execute($sql);
return mysql_num_rows($this->lastqueryid);
}
public function num_fields($sql) {
$this->lastqueryid = $this->execute($sql);
return mysql_num_fields($this->lastqueryid);
}
public function result($sql, $row) {
$this->lastqueryid = $this->execute($sql);
return @mysql_result($this->lastqueryid, $row);
}
public function error() {
return @mysql_error($this->link);
}
public function errno() {
return intval(@mysql_errno($this->link)) ;
}
public function version() {
if(!is_resource($this->link)) {
$this->connect();
}
return mysql_get_server_info($this->link);
}
public function close() {
if (is_resource($this->link)) {
@mysql_close($this->link);
}
}
public function halt($message = '', $sql = '') {
$this->errormsg = "<b>MySQL Query : </b>$sql <br /><b> MySQL Error : </b>".$this->error()." <br /> <b>MySQL Errno : </b>".$this->errno()." <br /><b> Message : </b> $message";
$msg = $this->errormsg;
echo '<div style="font-size:12px;text-align:left; border:1px solid #9cc9e0; padding:1px 4px;color:#000000;font-family:Arial, Helvetica,sans-serif;"><span>'.$msg.'</span></div>';
exit;
}
/**
* 对字段两边加反引号,以保证数据库安全
* @param $value 数组值
*/
public function add_special_char(&$value) {
if('*' == $value || false !== strpos($value, '(') || false !== strpos($value, '.') || false !== strpos ( $value, '`')) {
//不处理包含* 或者 使用了sql方法。
} else {
$value = '`'.trim($value).'`';
}
return $value;
}
/**
* 对字段值两边加引号,以保证数据库安全
* @param $value 数组值
* @param $key 数组key
* @param $quotation
*/
public function escape_string(&$value, $key='', $quotation = 1) {
if ($quotation) {
$q = '\'';
} else {
$q = '';
}
$value = $q.$value.$q;
return $value;
}
}
?> | PHP |
<?php
class cache_file {
/*缓存默认配置*/
protected $_setting = array(
'suf' => '.cache.php', /*缓存文件后缀*/
'type' => 'array', /*缓存格式:array数组,serialize序列化,null字符串*/
);
/*缓存路径*/
protected $filepath = '';
/**
* 构造函数
* @param array $setting 缓存配置
* @return void
*/
public function __construct($setting = '') {
$this->get_setting($setting);
}
/**
* 写入缓存
* @param string $name 缓存名称
* @param mixed $data 缓存数据
* @param array $setting 缓存配置
* @param string $type 缓存类型
* @param string $module 所属模型
* @return mixed 缓存路径/false
*/
public function set($name, $data, $setting = '', $type = 'data', $module = ROUTE_M) {
$this->get_setting($setting);
if(empty($type)) $type = 'data';
if(empty($module)) $module = ROUTE_M;
$filepath = CACHE_PATH.'caches_'.$module.'/caches_'.$type.'/';
$filename = $name.$this->_setting['suf'];
if(!is_dir($filepath)) {
mkdir($filepath, 0777, true);
}
if($this->_setting['type'] == 'array') {
$data = "<?php\nreturn ".var_export($data, true).";\n?>";
} elseif($this->_setting['type'] == 'serialize') {
$data = serialize($data);
}
$file_size = file_put_contents($filepath.$filename, $data, LOCK_EX);
return $file_size ? $file_size : 'false';
}
/**
* 获取缓存
* @param string $name 缓存名称
* @param array $setting 缓存配置
* @param string $type 缓存类型
* @param string $module 所属模型
* @return mixed $data 缓存数据
*/
public function get($name, $setting = '', $type = 'data', $module = ROUTE_M) {
$this->get_setting($setting);
if(empty($type)) $type = 'data';
if(empty($module)) $module = ROUTE_M;
$filepath = CACHE_PATH.'caches_'.$module.'/caches_'.$type.'/';
$filename = $name.$this->_setting['suf'];
if (!file_exists($filepath.$filename)) {
return false;
} else {
if($this->_setting['type'] == 'array') {
$data = @require($filepath.$filename);
} elseif($this->_setting['type'] == 'serialize') {
$data = unserialize(file_get_contents($filepath.$filename));
}
return $data;
}
}
/**
* 删除缓存
* @param string $name 缓存名称
* @param array $setting 缓存配置
* @param string $type 缓存类型
* @param string $module 所属模型
* @return bool
*/
public function delete($name, $setting = '', $type = 'data', $module = ROUTE_M) {
$this->get_setting($setting);
if(empty($type)) $type = 'data';
if(empty($module)) $module = ROUTE_M;
$filepath = CACHE_PATH.'caches_'.$module.'/caches_'.$type.'/';
$filename = $name.$this->_setting['suf'];
if(file_exists($filepath.$filename)) {
return @unlink($filepath.$filename) ? true : false;
} else {
return false;
}
}
/**
* 和系统缓存配置对比获取自定义缓存配置
* @param array $setting 自定义缓存配置
* @return array $setting 缓存配置
*/
public function get_setting($setting = '') {
if($setting) {
$this->_setting = array_merge($this->_setting, $setting);
}
}
public function cacheinfo($name, $setting = '', $type = 'data', $module = ROUTE_M) {
$this->get_setting($setting);
if(empty($type)) $type = 'data';
if(empty($module)) $module = ROUTE_M;
$filepath = CACHE_PATH.'caches_'.$module.'/caches_'.$type.'/';
$filename = $filepath.$name.$this->_setting['suf'];
if(file_exists($filepath)) {
$res['filename'] = $name.$this->_setting['suf'];
$res['filepath'] = $filepath;
$res['filectime'] = filectime($filename);
$res['filemtime'] = filemtime($filename);
$res['filesize'] = filesize($filename);
return $res;
} else {
return false;
}
}
}
?> | PHP |
<?php
class form {
/**
* 编辑器
* @param int $textareaid
* @param int $toolbar
* @param string $module 模块名称
* @param int $catid 栏目id
* @param int $color 编辑器颜色
* @param boole $allowupload 是否允许上传
* @param boole $allowbrowser 是否允许浏览文件
* @param string $alowuploadexts 允许上传类型
*/
public static function editor($textareaid = 'content', $toolbar = 'basic', $module='', $catid='', $color = '', $allowupload = 0, $allowbrowser = 1,$alowuploadexts = '') {
$str ='';
if(!defined('EDITOR_INIT')) {
$str = '<script type="text/javascript" src="statics/js/ckeditor/ckeditor.js"></script>';
define('EDITOR_INIT', 1);
}
if($toolbar=='basic') {
$toolbar = "['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink' ],\r\n";
} elseif($toolbar=='full') {
$toolbar = "['Source','-','Save','NewPage','Preview','-','Templates'],
['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print'],
['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],['ShowBlocks','Maximize'],
'/',
['Bold','Italic','Underline','Strike','-'],
['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
['Link','Unlink','Anchor'],
['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
'/',
['Styles','Format','Font','FontSize'],
['TextColor','BGColor'],
['attachment'],\r\n";
} else {
$toolbar = '';
}
$str .= "<script type=\"text/javascript\">\r\n";
$str .= "//<![CDATA[\r\n";
$str .= "CKEDITOR.replace( '$textareaid',{";
//$str .= "skin : 'v2',";
$str .="pages:true,subtitle:true,textareaid:'".$textareaid."',module:'".$module."',catid:'".$catid."',\r\n";
//if($allowbrowser) $str .= "filebrowserBrowseUrl : '/browser/browse.php',\r\n";
if($allowupload) $str .="flashupload:true,alowuploadexts:'".$alowuploadexts."',allowbrowser:'".$allowbrowser."',\r\n";
if($allowupload) $str .= "filebrowserUploadUrl : '?m=attachment&c=attachments&a=upload&dosubmit=1',\r\n";
if($color) {
$str .= "extraPlugins : 'uicolor',uiColor: '$color',";
}
$str .= "toolbar :\r\n";
$str .= "[\r\n";
$str .= $toolbar;
$str .= "]\r\n";
//$str .= "fullPage : true";
$str .= "});\r\n";
$str .= "//]]>\r\n";
$str .= '</script>';
$ext_str = "<div class='editor_bottom'>";
if(!defined('IMAGES_INIT')) {
$ext_str .= '<script type="text/javascript" src="statics/js/swfupload/swf2ckeditor.js"></script>';
define('IMAGES_INIT', 1);
}
$ext_str .= "<div id='page_title_div'>
<table cellpadding='0' cellspacing='1' border='0'><tr><td class='title'>".L('paging')."<span id='msg_page_title_value'></span></td><td>
<a class='close' href='javascript:;' onclick='javascript:$(\"#page_title_div\").hide();'><span>×</span></a></td>
<tr><td colspan='2'><input name='page_title_value' id='page_title_value' class='input-text' value='' size='40'> <input type='button' class='button' value='".L('submit')."' onclick=insert_page_title(\"$textareaid\",1)></td></tr>
</table></div>";
$ext_str .= "<div id=\"MM_file_list_".$textareaid."\" style=\"text-align:left\"></div><div id='FilePreview' style='Z-INDEX: 1000; LEFT: 0px; WIDTH: 10px; POSITION: absolute; TOP: 0px; HEIGHT: 10px; display: none;'></div><div id='".$textareaid."_save'></div>";
$ext_str .= "</div>";
$str .= $ext_str;
return $str;
}
/**
* 图片上传
* @param $name 表单名称
* @param $id 表单ID
* @param $value 表单值
* @param $size 表单size
* @param $class 表单风格
* @param $ext 表单扩展
* @param $modelid
* @param $fieldid
* @param $alowexts 允许附件类型
*/
public static function images($name, $id = '', $value = '', $moudle='', $catid='', $size = 50, $class = '', $ext = '', $alowexts = '') {
if(!$id) $id = $name;
if(!$size) $size= 50;
if(!$alowexts) $alowexts = 'jpg|jpeg|gif|bmp|png';
if(!defined('IMAGES_INIT')) {
$str = '<script type="text/javascript" src="statics/js/swfupload/swf2ckeditor.js"></script>';
define('IMAGES_INIT', 1);
}
return $str."<input type=\"text\" name=\"$name\" id=\"$id\" value=\"$value\" size=\"$size\" class=\"$class\" $ext/> <input type=\"button\" class=\"button\" onclick=\"javascript:flashupload('{$id}_images', '附件上传','{$id}',submit_images,'1,{$alowexts}','{$moudle}','{$catid}')\"/ value=\"上传图片\">";
}
public static function date($name, $value = '', $isdatetime = 0) {
if($value == '0000-00-00 00:00:00') $value = '';
$id = preg_match("/\[(.*)\]/", $name, $m) ? $m[1] : $name;
if($isdatetime) {
$size = 21;
$format = '%Y-%m-%d %H:%M:%S';
$showsTime = 'true';
} else {
$size = 10;
$format = '%Y-%m-%d';
$showsTime = 'false';
}
$str = '';
if(!defined('CALENDAR_INIT')) {
define('CALENDAR_INIT', 1);
$str .= '<link rel="stylesheet" type="text/css" href="statics/js/calendar/calendar-blue.css"/>
<script type="text/javascript" src="statics/js/calendar/calendar.js"></script>';
}
$str .= '<input type="text" name="'.$name.'" id="'.$id.'" value="'.$value.'" size="'.$size.'" class="date" readonly> ';
$str .= '<script language="javascript" type="text/javascript">
date = new Date();document.getElementById ("'.$id.'").value="'.$value.'";
Calendar.setup({
inputField : "'.$id.'",
ifFormat : "'.$format.'",
showsTime : '.$showsTime.',
timeFormat : "24"
});
</script>';
return $str;
}
/**
* 验证码
* @param string $id 生成的验证码ID
* @param integer $code_len 生成多少位验证码
* @param integer $font_size 验证码字体大小
* @param integer $width 验证图片的宽
* @param integer $height 验证码图片的高
* @param string $font 使用什么字体,设置字体的URL
* @param string $font_color 字体使用什么颜色
* @param string $background 背景使用什么颜色
*/
public static function checkcode($id = 'checkcode',$code_len = 4, $font_size = 20, $width = 130, $height = 50, $font = '', $font_color = '', $background = '') {
return "<img id='$id' onclick='this.src=this.src+\"&\"+Math.random()' src='".APP_PATH."api.php?op=checkcode&code_len=$code_len&font_size=$font_size&width=$width&height=$height&font=".urlencode($font)."&font_color=".urlencode($font_color)."&background=".urlencode($background)."'>";
}
/**
* 栏目选择
* @param string $file 栏目缓存文件名
* @param intval/array $catid 别选中的ID,多选是可以是数组
* @param string $str 属性
* @param string $default_option 默认选项
* @param intval $modelid 按所属模型筛选
*/
public static function select_category($file = 'category_content',$catid = 0, $str = '', $default_option = '', $modelid = 0) {
$tree = pc_base::load_sys_class('tree');
$result = getcache($file,'commons');
$string = '<select '.$str.'>';
if($default_option) $string .= "<option value='0'>$default_option</option>";
foreach($result as $r) {
if(is_array($catid)) {
$r['selected'] = in_array($r['catid'], $catid) ? 'selected' : '';
} elseif(is_numeric($catid)) {
$r['selected'] = $catid==$r['catid'] ? 'selected' : '';
}
$categorys[$r['catid']] = $r;
//$string .= '<option >'.$r['catname'].'</option>';
if($modelid && $r['modelid']!= $modelid ) unset($categorys[$r['catid']]);
}
$str = "<option value='\$catid' \$selected>\$spacer \$catname</option>";
$tree->init($categorys);
$string .= $tree->get_tree(0, $str);
$string .= '</select>';
return $string;
}
public static function select_linkage($keyid = 0, $parentid = 0, $name = 'parentid', $id ='', $alt = '', $linkageid = 0, $property = '') {
$tree = pc_base::load_sys_class('tree');
$result = getcache($keyid,'linkage');
$id = $id ? $id : $name;
$string = "<select name='$name' id='$id' $property>\n<option value='0'>$alt</option>\n";
if($result['data']) {
foreach($result['data'] as $area) {
$categorys[$area['linkageid']] = array('id'=>$area['linkageid'], 'parentid'=>$area['parentid'], 'name'=>$area['name']);
}
}
$str = "<option value='\$id' \$selected>\$spacer \$name</option>";
$tree->init($categorys);
$string .= $tree->get_tree($parentid, $str, $linkageid);
$string .= '</select>';
return $string;
}
/**
* 下拉选择框
*/
public static function select($array = array(), $id = 0, $str = '', $default_option = '') {
$string = '<select '.$str.'>';
$default_selected = (empty($id) && $default_option) ? 'selected' : '';
if($default_option) $string .= "<option value='' $default_selected>$default_option</option>";
foreach($array as $key=>$value) {
$selected = $id==$key ? 'selected' : '';
$string .= '<option value="'.$key.'" '.$selected.'>'.$value.'</option>';
}
$string .= '</select>';
return $string;
}
/**
* 复选框
*
* @param $array 选项 二维数组
* @param $id 默认选中值,多个用 '逗号'分割
* @param $str 属性
* @param $defaultvalue 是否增加默认值 默认值为 -99
* @param $width 宽度
*/
public static function checkbox($array = array(), $id = '', $str = '', $defaultvalue = '', $width = 0) {
$string = '';
if($id != '') $id = strpos($id, ',') ? explode(',', $id) : array($id);
if($defaultvalue) $string .= '<input type="hidden" '.$str.' value="-99">';
foreach($array as $key=>$value) {
$checked = ($id && in_array($key, $id)) ? 'checked' : '';
if($width) $string .= '<span class="ib" style="width:'.$width.'px"><label>';
$string .= '<input type="checkbox" '.$str.' '.$checked.' value="'.$key.'"> '.$value;
if($width) $string .= '</label></span>';
}
return $string;
}
/**
* 单选框
*
* @param $array 选项 二维数组
* @param $id 默认选中值
* @param $str 属性
*/
public static function radio($array = array(), $id = 0, $str = '') {
$string = '';
foreach($array as $key=>$value) {
$checked = $id==$key ? 'checked' : '';
$string .= '<input type="radio" '.$str.' '.$checked.' value="'.$key.'"> '.$value;
}
return $string;
}
/**
* 模板选择
*
* @param $module 模块
* @param $id 默认选中值
* @param $str 属性
* @param $pre 模板前缀
*/
public static function select_template($module, $id = '', $str = '', $pre = '') {
if(!$id) $id = $name;
$tpl_root = pc_base::load_config('system','tpl_root');
$tpl_name = pc_base::load_config('system','tpl_name');
$templatedir = PC_PATH.$tpl_root.DIRECTORY_SEPARATOR.$tpl_name.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR;
$files = @array_map('basename', glob($templatedir.$pre.'*.html'));
$names = array();
if(file_exists($templatedir.'name.inc.php')) $names = include $templatedir.'name.inc.php';
$templates = array();
if(is_array($files)) {
foreach($files as $file) {
$key = substr($file, 0, -5);
$templates[$key] = isset($names[$file]) ? $names[$file].'('.$file.')' : $file;
}
}
ksort($templates);
return self::select($templates, $id, $str,L('please_select'));
}
}
?> | PHP |
<?php
class cache_memcache {
private $memcache = null;
public function __construct() {
$this->memcache = new Memcache;
$this->memcache->connect(MEMCACHE_HOST, MEMCACHE_PORT, MEMCACHE_TIMEOUT);
}
public function memcache() {
$this->__construct();
}
public function get($name) {
$value = $this->memcache->get($name);
return $value;
}
public function set($name, $value, $ttl = 0, $ext1='', $ext2='') {
return $this->memcache->set($name, $value, false, $ttl);
}
public function delete($name) {
return $this->memcache->delete($name);
}
public function flush() {
return $this->memcache->flush();
}
}
?> | PHP |
<?php
/**
* 通用的树型类,可以生成任何树型结构
*/
class tree {
/**
* 生成树型结构所需要的2维数组
* @var array
*/
public $arr = array();
/**
* 生成树型结构所需修饰符号,可以换成图片
* @var array
*/
public $icon = array('│','├','└');
/**
* @access private
*/
public $ret = '';
/**
* 构造函数,初始化类
* @param array 2维数组,例如:
* array(
* 1 => array('id'=>'1','parentid'=>0,'name'=>'一级栏目一'),
* 2 => array('id'=>'2','parentid'=>0,'name'=>'一级栏目二'),
* 3 => array('id'=>'3','parentid'=>1,'name'=>'二级栏目一'),
* 4 => array('id'=>'4','parentid'=>1,'name'=>'二级栏目二'),
* 5 => array('id'=>'5','parentid'=>2,'name'=>'二级栏目三'),
* 6 => array('id'=>'6','parentid'=>3,'name'=>'三级栏目一'),
* 7 => array('id'=>'7','parentid'=>3,'name'=>'三级栏目二')
* )
*/
public function init($arr=array()){
$this->arr = $arr;
$this->ret = '';
return is_array($arr);
}
/**
* 得到父级数组
* @param int
* @return array
*/
public function get_parent($myid){
$newarr = array();
if(!isset($this->arr[$myid])) return false;
$pid = $this->arr[$myid]['parentid'];
$pid = $this->arr[$pid]['parentid'];
if(is_array($this->arr)){
foreach($this->arr as $id => $a){
if($a['parentid'] == $pid) $newarr[$id] = $a;
}
}
return $newarr;
}
/**
* 得到子级数组
* @param int
* @return array
*/
public function get_child($myid){
$a = $newarr = array();
if(is_array($this->arr)){
foreach($this->arr as $id => $a){
if($a['parentid'] == $myid) $newarr[$id] = $a;
}
}
return $newarr ? $newarr : false;
}
/**
* 得到当前位置数组
* @param int
* @return array
*/
public function get_pos($myid,&$newarr){
$a = array();
if(!isset($this->arr[$myid])) return false;
$newarr[] = $this->arr[$myid];
$pid = $this->arr[$myid]['parentid'];
if(isset($this->arr[$pid])){
$this->get_pos($pid,$newarr);
}
if(is_array($newarr)){
krsort($newarr);
foreach($newarr as $v){
$a[$v['id']] = $v;
}
}
return $a;
}
/**
* 得到树型结构
* @param int ID,表示获得这个ID下的所有子级
* @param string 生成树型结构的基本代码,例如:"<option value=\$id \$selected>\$spacer\$name</option>"
* @param int 被选中的ID,比如在做树型下拉框的时候需要用到
* @return string
*/
public function get_tree($myid, $str, $sid = 0, $adds = '', $str_group = ''){
$number=1;
$child = $this->get_child($myid);
if(is_array($child)){
$total = count($child);
foreach($child as $id=>$a){
$j=$k='';
if($number==$total){
$j .= $this->icon[2];
}else{
$j .= $this->icon[1];
$k = $adds ? $this->icon[0] : '';
}
$spacer = $adds ? $adds.$j : '';
$selected = $id==$sid ? 'selected' : '';
@extract($a);
$parentid == 0 && $str_group ? eval("\$nstr = \"$str_group\";") : eval("\$nstr = \"$str\";");
$this->ret .= $nstr;
$this->get_tree($id, $str, $sid, $adds.$k.' ',$str_group);
$number++;
}
}
return $this->ret;
}
/**
* 同上一方法类似,但允许多选
*/
public function get_tree_multi($myid, $str, $sid = 0, $adds = ''){
$number=1;
$child = $this->get_child($myid);
if(is_array($child)){
$total = count($child);
foreach($child as $id=>$a){
$j=$k='';
if($number==$total){
$j .= $this->icon[2];
}else{
$j .= $this->icon[1];
$k = $adds ? $this->icon[0] : '';
}
$spacer = $adds ? $adds.$j : '';
$selected = $this->have($sid,$id) ? 'selected' : '';
@extract($a);
eval("\$nstr = \"$str\";");
$this->ret .= $nstr;
$this->get_tree_multi($id, $str, $sid, $adds.$k.' ');
$number++;
}
}
return $this->ret;
}
private function have($list,$item){
return(strpos(',,'.$list.',',','.$item.','));
}
}
?> | PHP |
<?php
/**
* db_factory.class.php 数据库工厂类
*
* @copyright (C) 2005-2010 PHPCMS
* @license http://www.phpcms.cn/license/
* @lastmodify 2010-6-1
*/
final class db_factory {
/**
* 当前数据库工厂类静态实例
*/
private static $db_factory;
/**
* 数据库配置列表
*/
protected $db_config = array();
/**
* 数据库操作实例化列表
*/
protected $db_list = array();
/**
* 构造函数
*/
public function __construct() {
}
/**
* 返回当前终级类对象的实例
* @param $db_config 数据库配置
* @return object
*/
public static function get_instance($db_config = '') {
if($db_config == '') {
$db_config = pc_base::load_config('database');
}
if(db_factory::$db_factory == '') {
db_factory::$db_factory = new db_factory();
}
if($db_config != '' && $db_config != db_factory::$db_factory->db_config) db_factory::$db_factory->db_config = array_merge($db_config, db_factory::$db_factory->db_config);
return db_factory::$db_factory;
}
/**
* 获取数据库操作实例
* @param $db_name 数据库配置名称
*/
public function get_database($db_name) {
if(!isset($this->db_list[$db_name]) || !is_object($this->db_list[$db_name])) {
$this->db_list[$db_name] = $this->connect($db_name);
}
return $this->db_list[$db_name];
}
/**
* 加载数据库驱动
* @param $db_name 数据库配置名称
* @return object
*/
public function connect($db_name) {
$object = null;
switch($this->db_config[$db_name]['type']) {
case 'mysql' :
pc_base::load_sys_class('mysql', '', 0);
$object = new mysql();
break;
case 'mysqli' :
$object = pc_base::load_sys_class('mysqli');
break;
default :
pc_base::load_sys_class('mysql', '', 0);
$object = new mysql();
}
$object->open($this->db_config[$db_name]);
return $object;
}
/**
* 关闭数据库连接
* @return void
*/
protected function close() {
foreach($this->db_list as $db) {
$db->close();
}
}
/**
* 析构函数
*/
public function __destruct() {
$this->close();
}
}
?> | PHP |
<?php
/**
* 模板解析缓存
*/
final class template_cache {
/**
* 编译模板
*
* @param $module 模块名称
* @param $template 模板文件名
* @param $istag 是否为标签模板
* @return unknown
*/
public function template_compile($module, $template, $style = 'default') {
$tplfile = $_tpl = PC_PATH.'templates/'.$style.'/'.$module.'/'.$template.'.html';
if ($style != 'default' && ! file_exists ( $tplfile )) {
$tplfile = PC_PATH.'templates/default/'.$module.'/'.$template.'.html';
}
if (! file_exists ( $tplfile )) {
showmessage ( "$_tpl is not exists!" );
}
$content = @file_get_contents ( $tplfile );
$filepath = PHPCMS_PATH.'caches/caches_template/'.$module.'/';
if(!is_dir($filepath)) {
mkdir($filepath, 0777, true);
}
$compiledtplfile = $filepath.$template.'.'.$style.'.php';
$content = $this->template_parse($content);
$strlen = file_put_contents ( $compiledtplfile, $content );
chmod ( $compiledtplfile, 0777 );
return $strlen;
}
public function template_compile_admin($module, $template) {
$tplfile = $_tpl = PC_PATH.'templates/admin/'.$module.'/'.$template.'.html';
$content = @file_get_contents ( $tplfile );
$filepath = PHPCMS_PATH.'caches/caches_template/admintpl/'.$module.'/';
if(!is_dir($filepath)) {
mkdir($filepath, 0777, true);
}
$compiledtplfile = $filepath.$template.'.php';
$content = $this->template_parse($content);
$strlen = file_put_contents ( $compiledtplfile, $content );
chmod ( $compiledtplfile, 0777 );
return $strlen;
}
/**
* 更新模板缓存
*
* @param $tplfile 模板原文件路径
* @param $compiledtplfile 编译完成后,写入文件名
* @return $strlen 长度
*/
public function template_refresh($tplfile, $compiledtplfile) {
$str = @file_get_contents ($tplfile);
$str = $this->template_parse ($str);
$strlen = file_put_contents ($compiledtplfile, $str );
chmod ($compiledtplfile, 0777);
return $strlen;
}
/**
* 更新指定模块模板缓存
*
* @param $module 模块名称
* @return ture
*/
public function template_module($module) {
$files = glob ( TPL_ROOT . TPL_NAME . '/' . $module . '/*.html' );
if (is_array ( $files )) {
foreach ( $files as $tpl ) {
$template = str_replace ( '.html', '', basename ( $tpl ) );
$this->template_compile ( $module, $template );
}
}
return TRUE;
}
/**
* 更新所有模板缓存
*
* @return ture
*/
public function template_cache() {
global $MODULE;
if(!is_array($MODULE)) return FALSE;
foreach ( $MODULE as $module => $m ) {
$this->template_module ( $module );
}
return TRUE;
}
/**
* 解析模板
*
* @param $str 模板内容
* @param $istag 是否为标签模板
* @return ture
*/
public function template_parse($str, $istag = 0) {
$str = preg_replace ( "/([\n\r]+)\t+/s", "\\1", $str );
$str = preg_replace ( "/\<\!\-\-\{(.+?)\}\-\-\>/s", "{\\1}", $str );
$str = preg_replace ( "/\{template\s+(.+)\}/", "<?php include template(\\1); ?>", $str );
$str = preg_replace ( "/\{include\s+(.+)\}/", "<?php include \\1; ?>", $str );
$str = preg_replace ( "/\{php\s+(.+)\}/", "<?php \\1?>", $str );
$str = preg_replace ( "/\{if\s+(.+?)\}/", "<?php if(\\1) { ?>", $str );
$str = preg_replace ( "/\{else\}/", "<?php } else { ?>", $str );
$str = preg_replace ( "/\{elseif\s+(.+?)\}/", "<?php } elseif (\\1) { ?>", $str );
$str = preg_replace ( "/\{\/if\}/", "<?php } ?>", $str );
//for 循环
$str = preg_replace("/\{for\s+(.+?)\}/","<?php for(\\1) { ?>",$str);
$str = preg_replace("/\{\/for\}/","<?php } ?>",$str);
//++ --
$str = preg_replace("/\{\+\+(.+?)\}/","<?php ++\\1; ?>",$str);
$str = preg_replace("/\{\-\-(.+?)\}/","<?php ++\\1; ?>",$str);
$str = preg_replace("/\{(.+?)\+\+\}/","<?php \\1++; ?>",$str);
$str = preg_replace("/\{(.+?)\-\-\}/","<?php \\1--; ?>",$str);
$str = preg_replace ( "/\{loop\s+(\S+)\s+(\S+)\}/", "<?php if(is_array(\\1)) foreach(\\1 AS \\2) { ?>", $str );
$str = preg_replace ( "/\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}/", "<?php if(is_array(\\1)) foreach(\\1 AS \\2 => \\3) { ?>", $str );
$str = preg_replace ( "/\{\/loop\}/", "<?php } ?>", $str );
$str = preg_replace ( "/\{([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/", "<?php echo \\1;?>", $str );
$str = preg_replace ( "/\{\\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/", "<?php echo \\1;?>", $str );
$str = preg_replace ( "/\{(\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/", "<?php echo \\1;?>", $str );
$str = preg_replace("/\{(\\$[a-zA-Z0-9_\[\]\'\"\$\x7f-\xff]+)\}/es", "\$this->addquote('<?php echo \\1;?>')",$str);
$str = preg_replace ( "/\{([A-Z_\x7f-\xff][A-Z0-9_\x7f-\xff]*)\}/s", "<?php echo \\1;?>", $str );
if (! $istag)
$str = "<?php defined('IN_PHPCMS') or exit('No permission resources.'); ?>" . $str;
return $str;
}
/**
* 转义 // 为 /
*
* @param $var 转义的字符
* @return 转义后的字符
*/
public function addquote($var) {
return str_replace ( "\\\"", "\"", preg_replace ( "/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s", "['\\1']", $var ) );
}
}
?> | PHP |
<?php
/**
* param.class.php 参数处理类
*
* @copyright (C) 2005-2010 PHPCMS
* @license http://www.phpcms.cn/license/
* @lastmodify 2010-6-7
*/
class param {
//路由配置
private $route_config = '';
public function __construct() {
if(!get_magic_quotes_gpc()) {
$_POST = new_addslashes($_POST);
$_GET = new_addslashes($_GET);
$_COOKIE = new_addslashes($_COOKIE);
}
$this->route_config = pc_base::load_config('route', SITE_URL) ? pc_base::load_config('route', SITE_URL) : pc_base::load_config('route', 'default');
if(isset($this->route_config['data']['POST']) && is_array($this->route_config['data']['POST'])) {
foreach($this->route_config['data']['POST'] as $_key => $_value) {
if(!isset($_POST[$_key])) $_POST[$_key] = $_value;
}
}
if(isset($this->route_config['data']['GET']) && is_array($this->route_config['data']['GET'])) {
foreach($this->route_config['data']['GET'] as $_key => $_value) {
if(!isset($_GET[$_key])) $_GET[$_key] = $_value;
}
}
return true;
}
/**
* 获取模型
*/
public function route_m() {
$m = isset($_GET['m']) && !empty($_GET['m']) ? $_GET['m'] : (isset($_POST['m']) && !empty($_POST['m']) ? $_POST['m'] : '');
if (empty($m)) {
return $this->route_config['m'];
} else {
return $m;
}
}
/**
* 获取控制器
*/
public function route_c() {
$c = isset($_GET['c']) && !empty($_GET['c']) ? $_GET['c'] : (isset($_POST['c']) && !empty($_POST['c']) ? $_POST['c'] : '');
if (empty($c)) {
return $this->route_config['c'];
} else {
return $c;
}
}
/**
* 获取事件
*/
public function route_a() {
$a = isset($_GET['a']) && !empty($_GET['a']) ? $_GET['a'] : (isset($_POST['a']) && !empty($_POST['a']) ? $_POST['a'] : '');
if (empty($a)) {
return $this->route_config['a'];
} else {
return $a;
}
}
/**
* 设置 cookie
* @param string $var 变量名
* @param string $value 变量值
* @param int $time 过期时间
*/
public static function set_cookie($var, $value = '', $time = 0) {
$time = $time > 0 ? $time : ($value == '' ? SYS_TIME - 3600 : 0);
$s = $_SERVER['SERVER_PORT'] == '443' ? 1 : 0;
$var = pc_base::load_config('system','cookie_pre').$var;
$_COOKIE[$var] = $value;
if (is_array($value)) {
foreach($value as $k=>$v) {
setcookie($var.'['.$k.']', sys_auth($v, 'ENCODE'), $time, pc_base::load_config('system','cookie_path'), pc_base::load_config('system','cookie_domain'), $s);
}
} else {
setcookie($var, sys_auth($value, 'ENCODE'), $time, pc_base::load_config('system','cookie_path'), pc_base::load_config('system','cookie_domain'), $s);
}
}
/**
* 获取通过 set_cookie 设置的 cookie 变量
* @param string $var 变量名
* @return mixed 成功则返回cookie 值,否则返回 false
*/
public static function get_cookie($var) {
$var = pc_base::load_config('system','cookie_pre').$var;
return isset($_COOKIE[$var]) ? sys_auth($_COOKIE[$var], 'DECODE') : false;
}
}
?> | PHP |
<?php
/**
* application.class.php PHPCMS应用程序创建类
*
* @copyright (C) 2005-2010 PHPCMS
* @license http://www.phpcms.cn/license/
* @lastmodify 2010-6-7
*/
class application {
/**
* 构造函数
*/
public function __construct() {
$param = pc_base::load_sys_class('param');
define('ROUTE_M', $param->route_m());
define('ROUTE_C', $param->route_c());
define('ROUTE_A', $param->route_a());
$this->init();
}
/**
* 调用件事
*/
private function init() {
$controller = $this->load_controller();
if (method_exists($controller, ROUTE_A)) {
if (preg_match('/^[_]/i', ROUTE_A)) {
exit('You are visiting the action is to protect the private action');
} else {
call_user_func(array($controller, ROUTE_A));
}
} else {
exit('Action does not exist.');
}
}
/**
* 加载控制器
* @param string $filename
* @param string $m
* @return obj
*/
private function load_controller($filename = '', $m = '') {
if (empty($filename)) $filename = ROUTE_C;
if (empty($m)) $m = ROUTE_M;
$filepath = PC_PATH.'modules'.DIRECTORY_SEPARATOR.$m.DIRECTORY_SEPARATOR.$filename.'.php';
if (file_exists($filepath)) {
$classname = $filename;
include $filepath;
if ($mypath = pc_base::my_path($filepath)) {
$classname = 'MY_'.$filename;
include $mypath;
}
return new $classname;
} else {
exit('Controller does not exist.');
}
}
} | PHP |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.