code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTOQLDV
{
public class DTOTuKhoaDiaDiem
{
private int _maTuKhoatenDiaDiem;
public int MaTuKhoatenDiaDiem
{
get { return _maTuKhoatenDiaDiem; }
set { _maTuKhoatenDiaDiem = value; }
}
private String _tuKhoaTenDiaDiem;
public String TuKhoaTenDiaDiem
{
get { return _tuKhoaTenDiaDiem; }
set { _tuKhoaTenDiaDiem = value; }
}
private int _maTenDiaDiem;
public int MaTenDiaDiem
{
get { return _maTenDiaDiem; }
set { _maTenDiaDiem = value; }
}
public DTOTuKhoaDiaDiem()
{
_maTenDiaDiem = 0;
_maTuKhoatenDiaDiem = 0;
_tuKhoaTenDiaDiem = "";
}
}
}
|
10hca1-team4-qldv
|
trunk/ 10hca1-team4-qldv/DTOQLDV/DTOTuKhoaDiaDiem.cs
|
C#
|
asf20
| 919
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTOQLDV
{
public class DTOPhuong
{
private int _maPhuong;
public int MaPhuong
{
get { return _maPhuong; }
set { _maPhuong = value; }
}
private String _tenPhuong;
public String TenPhuong
{
get { return _tenPhuong; }
set { _tenPhuong = value; }
}
public DTOPhuong()
{
_maPhuong = 0;
_tenPhuong = "";
}
}
}
|
10hca1-team4-qldv
|
trunk/ 10hca1-team4-qldv/DTOQLDV/DTOPhuong.cs
|
C#
|
asf20
| 608
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTOQLDV
{
public class DTODiaDiem
{
private int _maDiaDiem;
public int MaDiaDiem
{
get { return _maDiaDiem; }
set { _maDiaDiem = value; }
}
private String _tenDiaDiem;
public String TenDiaDiem
{
get{ return _tenDiaDiem; }
set { _tenDiaDiem = value; }
}
public DTODiaDiem()
{
_maDiaDiem = 0;
_tenDiaDiem = "";
}
}
}
|
10hca1-team4-qldv
|
trunk/ 10hca1-team4-qldv/DTOQLDV/DTODiaDiem.cs
|
C#
|
asf20
| 627
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTOQLDV
{
public class DTOTuKhoaQuanHuyen
{
private int _maTuKhoaQuanHuyen;
public int MaTuKhoaQuanHuyen
{
get { return _maTuKhoaQuanHuyen; }
set { _maTuKhoaQuanHuyen = value; }
}
private String _tuKhoaQuanHuyen;
public String TuKhoaQuanHuyen
{
get { return _tuKhoaQuanHuyen; }
set { _tuKhoaQuanHuyen = value; }
}
private int _maQuanHuyen;
public int MaQuanHuyen
{
get { return _maQuanHuyen; }
set { _maQuanHuyen = value; }
}
public DTOTuKhoaQuanHuyen()
{
_maQuanHuyen = 0;
_maTuKhoaQuanHuyen = 0;
_tuKhoaQuanHuyen = "";
}
}
}
|
10hca1-team4-qldv
|
trunk/ 10hca1-team4-qldv/DTOQLDV/DTOTuKhoaQuanHuyen.cs
|
C#
|
asf20
| 908
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTOQLDV
{
public class DTODuLieuEX
{
private String _tenDichVu;
public String TenDichVu
{
get { return _tenDichVu; }
set { _tenDichVu = value; }
}
private String _tenDiaDiem;
public String TenDiaDiem
{
get { return _tenDiaDiem; }
set { _tenDiaDiem = value; }
}
private String _soNha;
public String SoNha
{
get { return _soNha; }
set { _soNha = value; }
}
private String _duong;
public String Duong
{
get { return _duong; }
set { _duong = value; }
}
private String _phuong;
public String Phuong
{
get { return _phuong; }
set { _phuong = value; }
}
private String _quanHuyen;
public String QuanHuyen
{
get { return _quanHuyen; }
set { _quanHuyen = value; }
}
private String _tinhThanh;
public String TinhThanh
{
get { return _tinhThanh; }
set { _tinhThanh = value; }
}
private String _kinhDo;
public String KinhDo
{
get { return _kinhDo; }
set { _kinhDo = value; }
}
private String _viDo;
public String ViDo
{
get { return _viDo; }
set { _viDo = value; }
}
private String _chuThich;
public String ChuThich
{
get { return _chuThich; }
set { _chuThich = value; }
}
public DTODuLieuEX()
{
_chuThich = "";
_duong = "";
_kinhDo = "";
_phuong = "";
_quanHuyen = "";
_soNha = "";
_tenDiaDiem = "";
_tenDichVu = "";
_tinhThanh = "";
_viDo = "";
}
}
}
|
10hca1-team4-qldv
|
trunk/ 10hca1-team4-qldv/DTOQLDV/DTODuLieuEX.cs
|
C#
|
asf20
| 2,161
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("QLDV_DA")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("QLDV_DA")]
[assembly: AssemblyCopyright("Copyright © 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9b2ae26b-3c91-4e88-a767-ecd62b8ce05d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
10hca1-team4-qldv
|
trunk/ 10hca1-team4-qldv/QLDV_DA/Properties/AssemblyInfo.cs
|
C#
|
asf20
| 1,426
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using CTLQLDV;
using BUSQLDV;
namespace QLDV_DA
{
public partial class frmThemMoi : DevExpress.XtraEditors.XtraForm
{
public frmThemMoi()
{
InitializeComponent();
this.StartPosition = FormStartPosition.CenterParent;
}
private CTLDuLieu _duLieu;
private void simpleButton5_Click(object sender, EventArgs e)
{
this.Close();
}
private void KhoiTao()
{
_duLieu = new CTLDuLieu();
_duLieu.Dock = DockStyle.Fill;
thThongTinChiTiet.Controls.Add(_duLieu);
}
private void cnThem_Click(object sender, EventArgs e)
{
try
{
if (BUSDuLieu.ThemDuLieu(_duLieu.LayDuLieu()))
{
MessageBox.Show("Đã thêm thành công", "Thông báo");
LoadChucNang(true);
}
else
{
MessageBox.Show("Xin vui lòng thử lại", "Thông báo");
}
}
catch (Exception ex)
{
MessageBox.Show("Xảy ra lỗi '"+ex.Message+"'");
}
}
private void frmThemMoi_Load(object sender, EventArgs e)
{
KhoiTao();
LoadChucNang(false);
}
private void LoadChucNang(bool tt)
{
cnCapNhat.Enabled = tt;
cnXoa.Enabled = tt;
}
private void cnCapNhat_Click(object sender, EventArgs e)
{
try
{
if (_duLieu.LayDuLieu().MaDuLieu > 0)
{
if (BUSDuLieu.CapNhatDuLieu(_duLieu.LayDuLieu()))
{
MessageBox.Show("Đã cập nhật thành công", "Thông báo");
}
else
{
MessageBox.Show("Xin vui lòng thử lại", "Thông báo");
}
}
else
{
MessageBox.Show("Chưa tồn tại dữ liệu đã cập nhật", "Thông báo");
}
}
catch (Exception ex)
{
MessageBox.Show("Xảy ra lỗi '" + ex.Message + "'");
}
}
private void cnXoa_Click(object sender, EventArgs e)
{
try
{
if (_duLieu.LayDuLieu().MaDuLieu > 0)
{
if (BUSDuLieu.XoaDuLieu(_duLieu.LayDuLieu()))
{
MessageBox.Show("Đã xóa thành công", "Thông báo");
_duLieu = new CTLDuLieu();
}
else
{
MessageBox.Show("Xin vui lòng thử lại", "Thông báo");
}
}
else
{
MessageBox.Show("Chưa có dữ liệu để xóa", "Thông báo");
}
}
catch (Exception ex)
{
MessageBox.Show("Xảy ra lỗi '" + ex.Message + "'");
}
}
private void cnThemMoi_Click(object sender, EventArgs e)
{
_duLieu = new CTLDuLieu();
}
}
}
|
10hca1-team4-qldv
|
trunk/ 10hca1-team4-qldv/QLDV_DA/frmThemMoi.cs
|
C#
|
asf20
| 3,751
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
namespace QLDV_DA
{
public partial class frmThongTin : DevExpress.XtraEditors.XtraForm
{
public frmThongTin()
{
InitializeComponent();
}
private void cnThoat_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
10hca1-team4-qldv
|
trunk/ 10hca1-team4-qldv/QLDV_DA/frmThongTin.cs
|
C#
|
asf20
| 520
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Threading;
namespace QLDV_DA
{
public partial class frmTienDo : DevExpress.XtraEditors.XtraForm
{
private Thread _thread;
public frmTienDo()
{
InitializeComponent();
}
private void XuLiThread()
{
this.StartPosition = FormStartPosition.CenterScreen;
this.TopMost = true;
Application.Run(this);
}
public void ThucHienThread()
{
if (_thread == null)
{
_thread = new Thread(new ThreadStart(XuLiThread));
_thread.IsBackground = true;
_thread.Start();
}
}
public void Thoat()
{
// Need to call on the thread that launched this splash
if (this.InvokeRequired)
this.Invoke(new MethodInvoker(Thoat));
else
Application.ExitThread();
}
}
}
|
10hca1-team4-qldv
|
trunk/ 10hca1-team4-qldv/QLDV_DA/frmTienDo.cs
|
C#
|
asf20
| 1,256
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace QLDV_DA
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMain());
}
}
}
|
10hca1-team4-qldv
|
trunk/ 10hca1-team4-qldv/QLDV_DA/Program.cs
|
C#
|
asf20
| 501
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DTOQLDV;
using BUSQLDV;
namespace QLDV_DA
{
public partial class frmXuLiTuDongDuLuLieuSai : DevExpress.XtraEditors.XtraForm
{
public frmXuLiTuDongDuLuLieuSai()
{
InitializeComponent();
_arrck = new bool[6];
}
public delegate void ThucHien(bool []arr);
public delegate void BoQua();
public ThucHien _thucHien;
public BoQua _boQua;
private void ChonTatCa(bool ch)
{
ckTuDongThemDiaDiem.Checked = ch;
ckTuDongThemMoiDichVu.Checked = ch;
ckTuDongThemMoiDuong.Checked = ch;
ckTuDongThemMoiPhuong.Checked = ch;
ckTuDongThemMoiQuanHuyen.Checked = ch;
ckTuDongThemMoiTinhThanh.Checked = ch;
}
private bool[] _arrck;
private bool XuLiChonLua()
{
_arrck[0] = ckTuDongThemDiaDiem.Checked;
_arrck[1] = ckTuDongThemMoiDichVu.Checked;
_arrck[2] = ckTuDongThemMoiDuong.Checked;
_arrck[3] = ckTuDongThemMoiPhuong.Checked;
_arrck[4] = ckTuDongThemMoiQuanHuyen.Checked;
_arrck[5] = ckTuDongThemMoiTinhThanh.Checked;
foreach (bool ck in _arrck)
{
if (ck == true)
{
return true;
}
}
return false;
}
private void frmXuLiTuDongDuLuLieuSai_Load(object sender, EventArgs e)
{
ckTuDongThemMoiTatCa.Checked = true;
}
private void cnThucHien_Click(object sender, EventArgs e)
{
try
{
if (XuLiChonLua())
{
_thucHien(_arrck);
this.Close();
}
else
{
MessageBox.Show("Xin chọn xử lí", "Thông báo");
}
}
catch (Exception ex)
{
}
}
private void cnBoQua_Click(object sender, EventArgs e)
{
try
{
_boQua();
this.Close();
}
catch (Exception ex)
{
}
}
private void cnHuy_Click(object sender, EventArgs e)
{
this.Close();
}
private void ckTuDongThemMoiTatCa_CheckedChanged_1(object sender, EventArgs e)
{
ChonTatCa(ckTuDongThemMoiTatCa.Checked);
}
}
}
|
10hca1-team4-qldv
|
trunk/ 10hca1-team4-qldv/QLDV_DA/frmXuLiTuDongDuLuLieuSai.cs
|
C#
|
asf20
| 2,885
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DTOQLDV;
using CTLQLDV;
using BUSQLDV;
namespace QLDV_DA
{
public partial class frmCapNhat : DevExpress.XtraEditors.XtraForm
{
private List<DTODuLieu> _dsDuLieu;
private List<CTLDuLieu> _dsCTLDuLieu;
public frmCapNhat(List<DTODuLieu> dsDuLieu)
{
_dsDuLieu = new List<DTODuLieu>();
_dsCTLDuLieu = new List<CTLDuLieu>();
InitializeComponent();
this.StartPosition = FormStartPosition.CenterScreen;
_dsDuLieu = dsDuLieu;
int i = 1;
foreach (DTODuLieu dtoDL in _dsDuLieu)
{
CTLDuLieu ctlDuLieu = new CTLDuLieu();
ctlDuLieu.GanDuLieu(dtoDL);
LabelControl lb = new LabelControl();
lb.ForeColor = Color.Black;
lb.Text = "Dữ liệu thứ " + i;
i++;
thDanhSachCapNhat.Controls.Add(lb);
thDanhSachCapNhat.Controls.Add(ctlDuLieu);
_dsCTLDuLieu.Add(ctlDuLieu);
}
_dsDuLieu = dsDuLieu;
}
private void simpleButton5_Click(object sender, EventArgs e)
{
this.Close();
}
private void cnDongY_Click(object sender, EventArgs e)
{
try
{
for (int i = 0; i < _dsCTLDuLieu.Count; i++)
{
_dsDuLieu[i] = _dsCTLDuLieu[i].LayDuLieu();
}
if (BUSDuLieu.CapNhatDanhSach(_dsDuLieu))
{
MessageBox.Show("Cập nhật thành công", "Thông báo");
}
else
{
MessageBox.Show("Cập nhật xảy ra lỗi, xin kiểm tra lại", "Thông báo");
}
}
catch (Exception ex)
{
MessageBox.Show("Xảy ra lỗi '" + ex.Message + "'");
}
}
}
}
|
10hca1-team4-qldv
|
trunk/ 10hca1-team4-qldv/QLDV_DA/frmCapNhat.cs
|
C#
|
asf20
| 2,273
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BUSQLDV;
using DTOQLDV;
using System.Configuration;
using System.Threading;
namespace QLDV_DA
{
public partial class frmMain : Form
{
#region Khai báo biến tham số
private List<DTODuLieu> _dsDuLieuDuocChon;
private List<String> _dsFil;
#endregion
public frmMain()
{
InitializeComponent();
_dsFil = new List<string>();
_dsDuLieuDuocChon = new List<DTODuLieu>();
}
#region Xử lí cài đặt dữ liệu
private void KhoiTao()
{
thKeyword.Properties.NullText = "<Xin nhập từ khóa>";
thDanhSachBoLocHienCo.Properties.NullText = "<Xin chọn bộ lọc>";
//Load tham số cho các cột dữ liệu
rclMaDiaDiem.DataSource = SESSION._dsDiaDiem;
rclMaDiaDiem.DisplayMember = "TenDiaDiem";
rclMaDiaDiem.ValueMember = "MaDiaDiem";
rclMaDichVu.DataSource = SESSION._dsDichVu;
rclMaDichVu.DisplayMember = "TenDichVu";
rclMaDichVu.ValueMember = "MaDichVu";
rclMaDuong.DataSource = SESSION._dsDuong;
rclMaDuong.DisplayMember = "TenDuong";
rclMaDuong.ValueMember = "MaDuong";
rclMaPhuong.DataSource = SESSION._dsPhuong;
rclMaPhuong.DisplayMember = "TenPhuong";
rclMaPhuong.ValueMember = "MaPhuong";
rclMaQuanHuyen.DataSource = SESSION._dsQuanHuyen;
rclMaQuanHuyen.DisplayMember = "TenQuanHuyen";
rclMaQuanHuyen.ValueMember = "MaQuanHuyen";
rclMaTinhThanh.DataSource = SESSION._dsTinhThanh;
rclMaTinhThanh.DisplayMember = "TenTinhThanh";
rclMaTinhThanh.ValueMember = "MaTinhThanh";
//Load danh sách dữ liệu cho bản chính
thGridDanhSachDuLieu.DataSource = SESSION._dsDuLieu;
//Tao cot check dau tien
_selection = new GridCheckMarksSelection(thGridviewDanhSachDuLieu);
_selection.CheckMarkColumn.VisibleIndex = 0;
}
private void CapNhatBoLoc(String fil)
{
thGridviewDanhSachDuLieu.ActiveFilterString = fil;
thDanhSachBoLocHienCo.SelectedIndex = -1;
thKeyword.Focus();
}
private String TaoChuoiLoc()
{
String fil = "1=1 ";
foreach (String s in _dsFil)
{
if (s != null && s != "")
{
fil += " And " + s;
}
}
return fil;
}
#endregion
#region Các hàm xử lí sự kiện
private void cnThemMoi_Click(object sender, EventArgs e)
{
try
{
frmThemMoi frmThemMoi = new frmThemMoi();
frmThemMoi.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show("Xảy ra lỗi " + ex.Message, "Thông báo");
}
finally
{
LamTuoi();
}
}
private void cnCapNhat_Click(object sender, EventArgs e)
{
if (_selection.SelectedCount > 0)
{
try
{
List<DTODuLieu> dsDuLieuDuocChon = new List<DTODuLieu>();
for (int i = 0; i < _selection.SelectedCount; i++)
{
dsDuLieuDuocChon.Add((DTODuLieu)_selection.GetSelectedRow(i));
}
frmCapNhat frmCapNhat = new frmCapNhat(dsDuLieuDuocChon);
frmCapNhat.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show("Xảy ra lỗi " + ex.Message, "Thông báo");
}
finally
{
_selection.ClearSelection();
LamTuoi();
}
}
else
{
MessageBox.Show("Xin chọn dữ liệu cần chỉnh sửa", "Thông báo");
}
}
private void frmMain_Load(object sender, EventArgs e)
{
try
{
frmsplash.ShowSplash();
if (CaiDatThamSo())
{
KhoiTao();
}
else
{
MessageBox.Show("Xin kiểm tra lại kết nối", "Thông báo");
}
}
catch (Exception ex)
{
MessageBox.Show("Xảy ra lỗi : '"+ex.Message+"'", "Thông báo");
}
finally
{
frmsplash.CloseSplash();
this.Activate();
this.WindowState = FormWindowState.Maximized;
}
}
private void LamTuoi()
{
thGridDanhSachDuLieu.RefreshDataSource();
}
private void cnXoa_Click(object sender, EventArgs e)
{
try
{
List<DTODuLieu> dsChon = new List<DTODuLieu>();
DialogResult dl = MessageBox.Show("Bạn có muốn tiếp tục xóa các dòng dữ liệu này", "Thông báo", MessageBoxButtons.OKCancel);
if (dl == DialogResult.OK)
{
for (int i = 0; i < _selection.SelectedCount; i++)
{
DTODuLieu dtoDuLieu = (DTODuLieu)_selection.GetSelectedRow(i);
dsChon.Add(dtoDuLieu);
SESSION._dsDuLieu.Remove(dtoDuLieu);
}
BUSThread._dsDuLieu = dsChon;
BUSThread.ThucHienThreadXoaDuLieu();
}
}
catch (Exception ex)
{
MessageBox.Show("Xảy ra lỗi " + ex.Message, "Thông báo");
}
finally
{
_selection.ClearSelection();
LamTuoi();
}
}
private void thTrangKe_Click(object sender, EventArgs e)
{
thGridDanhSachDuLieu.EmbeddedNavigator.Buttons.DoClick(thGridDanhSachDuLieu.EmbeddedNavigator.Buttons.NextPage);
}
private void thTrangCuoi_Click(object sender, EventArgs e)
{
thGridDanhSachDuLieu.EmbeddedNavigator.Buttons.DoClick(thGridDanhSachDuLieu.EmbeddedNavigator.Buttons.Last);
}
private void thTrangTruoc_Click(object sender, EventArgs e)
{
thGridDanhSachDuLieu.EmbeddedNavigator.Buttons.DoClick(thGridDanhSachDuLieu.EmbeddedNavigator.Buttons.PrevPage);
}
private void thTrangDau_Click(object sender, EventArgs e)
{
thGridDanhSachDuLieu.EmbeddedNavigator.Buttons.DoClick(thGridDanhSachDuLieu.EmbeddedNavigator.Buttons.First);
}
private void cnNhap_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog thChonFile = new OpenFileDialog();
thChonFile.Filter = "Excel 2003|*.xls|Excel 2007/2010|*.xlsx|All|*.*";
thChonFile.Title = "Chọn 1 file cần nhập";
DialogResult dg = thChonFile.ShowDialog();
if (dg == DialogResult.OK)
{
String fileName = thChonFile.FileName;
frmNhapDuLieu frmNL = new frmNhapDuLieu(fileName);
frmNL.ShowDialog();
}
}
catch (Exception ex)
{
MessageBox.Show("Xảy ra lỗi '" + ex.Message + "'", "Thông báo");
}
finally
{
LamTuoi();
}
}
private void cnThoat_Click(object sender, EventArgs e)
{
this.Close();
}
private void thDanhSachBoLocDuocChon_ItemCheck(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e)
{
if (thDanhSachBoLocDuocChon.Items[e.Index].CheckState == CheckState.Unchecked)
{
thDanhSachBoLocDuocChon.Items.RemoveAt(e.Index);
_dsFil.RemoveAt(e.Index);
CapNhatBoLoc(TaoChuoiLoc());
}
}
private void cnXoaLoc_Click(object sender, EventArgs e)
{
_dsFil.Clear();
thDanhSachBoLocDuocChon.Items.Clear();
CapNhatBoLoc("1=1");
}
private void thDanhSachBoLocHienCo_Properties_SelectedIndexChanged(object sender, EventArgs e)
{
int i = thDanhSachBoLocHienCo.SelectedIndex;
String kw = "";
if (thKeyword.EditValue != null)
{
kw = thKeyword.EditValue.ToString().Trim();
}
if (i >= 0 && kw.Length > 0)
{
_dsFil.Add(" [" + thGridviewDanhSachDuLieu.Columns[i + 2].FieldName + "] Like '%" + kw + "%'");
thDanhSachBoLocDuocChon.Items.Add(thDanhSachBoLocHienCo.SelectedItem + " = '" + kw + "'", true);
thDanhSachBoLocHienCo.SelectedIndex = -1;
thKeyword.EditValue = null;
CapNhatBoLoc(TaoChuoiLoc());
}
else
{
thDanhSachBoLocHienCo.SelectedIndex = -1;
}
}
#endregion
private void thGridviewDanhSachDuLieu_RowCountChanged(object sender, EventArgs e)
{
thTongSoDuLieu.Text = thGridviewDanhSachDuLieu.RowCount + "";
}
private bool CaiDatThamSo()
{
SESSION._cnnStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
bool kq = BUSXuLi.KiemTraKetNoi();
if (kq)
{
SESSION._dsDiaDiem = BUSDiaDiem.LayDanhSachDiaDiem();
SESSION._dsDichVu = BUSDichVu.LayDanhSachDichVu();
SESSION._dsDuLieu = BUSDuLieu.LayDanhSachDuLieu();
SESSION._dsDuong = BUSDuong.LayDanhSachDuong();
SESSION._dsPhuong = BUSPhuong.LayDanhSachPhuong();
SESSION._dsQuanHuyen = BUSQuanHuyen.LayDanhSachQuanHuyen();
SESSION._dsTinhThanh = BUSTinhThanh.LayDanhSachTinhThanh();
}
return kq;
}
private void cnThongTin_Click(object sender, EventArgs e)
{
frmThongTin frm = new frmThongTin();
frm.ShowDialog();
}
private void thGridviewDanhSachDuLieu_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
{
if (e.FocusedRowHandle > 0)
{
thDuLieuHienHanh.Text = e.FocusedRowHandle + "";
}
else
{
thDuLieuHienHanh.Text = "0";
}
}
}
}
|
10hca1-team4-qldv
|
trunk/ 10hca1-team4-qldv/QLDV_DA/frmMain.cs
|
C#
|
asf20
| 11,641
|
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
namespace QLDV_DA
{
public class GridCheckMarksSelection
{
protected GridView view;
protected ArrayList selection;
private GridColumn column;
private RepositoryItemCheckEdit edit;
public GridCheckMarksSelection(): base()
{
selection = new ArrayList();
}
public GridCheckMarksSelection(GridView view): this()
{
View = view;
}
protected virtual void Attach(GridView view)
{
if (view == null) return;
selection.Clear();
this.view = view;
edit = view.GridControl.RepositoryItems.Add("CheckEdit") as RepositoryItemCheckEdit;
edit.EditValueChanged += new EventHandler(edit_EditValueChanged);
column = view.Columns.Add();
column.OptionsColumn.AllowSort = DevExpress.Utils.DefaultBoolean.False;
column.VisibleIndex = int.MaxValue;
column.FieldName = "CheckMarkSelection";
column.Caption = "Mark";
column.OptionsColumn.ShowCaption = false;
column.UnboundType = DevExpress.Data.UnboundColumnType.Boolean;
column.ColumnEdit = edit;
view.CustomDrawColumnHeader += new ColumnHeaderCustomDrawEventHandler(View_CustomDrawColumnHeader);
view.CustomDrawGroupRow += new RowObjectCustomDrawEventHandler(View_CustomDrawGroupRow);
view.CustomUnboundColumnData += new CustomColumnDataEventHandler(view_CustomUnboundColumnData);
view.RowStyle += new RowStyleEventHandler(view_RowStyle);
view.MouseDown += new MouseEventHandler(view_MouseDown); // clear selection
}
protected virtual void Detach()
{
if (view == null) return;
if (column != null)
column.Dispose();
if (edit != null)
{
view.GridControl.RepositoryItems.Remove(edit);
edit.Dispose();
}
view.CustomDrawColumnHeader -= new ColumnHeaderCustomDrawEventHandler(View_CustomDrawColumnHeader);
view.CustomDrawGroupRow -= new RowObjectCustomDrawEventHandler(View_CustomDrawGroupRow);
view.CustomUnboundColumnData -= new CustomColumnDataEventHandler(view_CustomUnboundColumnData);
view.RowStyle -= new RowStyleEventHandler(view_RowStyle);
view.MouseDown -= new MouseEventHandler(view_MouseDown);
view = null;
}
protected void DrawCheckBox(Graphics g, Rectangle r, bool Checked)
{
DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo info;
DevExpress.XtraEditors.Drawing.CheckEditPainter painter;
DevExpress.XtraEditors.Drawing.ControlGraphicsInfoArgs args;
info = edit.CreateViewInfo() as DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo;
painter = edit.CreatePainter() as DevExpress.XtraEditors.Drawing.CheckEditPainter;
info.EditValue = Checked;
info.Bounds = r;
info.CalcViewInfo(g);
args = new DevExpress.XtraEditors.Drawing.ControlGraphicsInfoArgs(info, new
DevExpress.Utils.Drawing.GraphicsCache(g), r);
painter.Draw(args);
args.Cache.Dispose();
}
private void view_MouseDown(object sender, MouseEventArgs e)
{
if (e.Clicks == 1 && e.Button == MouseButtons.Left)
{
GridHitInfo info;
Point pt = view.GridControl.PointToClient(Control.MousePosition);
info = view.CalcHitInfo(pt);
if (info.InRow && info.Column == column && view.IsDataRow(info.RowHandle))
{
//Xử lí xóa ngay tại đây
//ClearSelection();
if (IsRowSelected(info.RowHandle))
{
SelectRow(info.RowHandle, false);
}
else
{
SelectRow(info.RowHandle, true);
}
}
if (info.InColumn && info.Column == column)
{
if (SelectedCount == view.DataRowCount)
ClearSelection();
else
SelectAll();
}
if (info.InRow && view.IsGroupRow(info.RowHandle) && info.HitTest != GridHitTest.RowGroupButton)
{
bool selected = IsGroupRowSelected(info.RowHandle);
SelectGroup(info.RowHandle, !selected);
}
}
}
private void View_CustomDrawColumnHeader(object sender, ColumnHeaderCustomDrawEventArgs e)
{
if (e.Column == column)
{
e.Info.InnerElements.Clear();
e.Painter.DrawObject(e.Info);
DrawCheckBox(e.Graphics, e.Bounds, SelectedCount == view.DataRowCount);
e.Handled = true;
}
}
private void View_CustomDrawGroupRow(object sender, RowObjectCustomDrawEventArgs e)
{
DevExpress.XtraGrid.Views.Grid.ViewInfo.GridGroupRowInfo info;
info = e.Info as DevExpress.XtraGrid.Views.Grid.ViewInfo.GridGroupRowInfo;
info.GroupText = " " + info.GroupText.TrimStart();
e.Info.Paint.FillRectangle(e.Graphics, e.Appearance.GetBackBrush(e.Cache), e.Bounds);
e.Painter.DrawObject(e.Info);
Rectangle r = info.ButtonBounds;
r.Offset(r.Width * 2, 0);
DrawCheckBox(e.Graphics, r, IsGroupRowSelected(e.RowHandle));
e.Handled = true;
}
private void view_RowStyle(object sender, RowStyleEventArgs e)
{
if (IsRowSelected(e.RowHandle))
{
e.Appearance.BackColor = SystemColors.Highlight;
e.Appearance.ForeColor = SystemColors.HighlightText;
}
}
public GridView View
{
get
{
return view;
}
set
{
if (view != value)
{
Detach();
Attach(value);
}
}
}
public GridColumn CheckMarkColumn
{
get
{
return column;
}
}
public int SelectedCount
{
get
{
return selection.Count;
}
}
public object GetSelectedRow(int index)
{
return selection[index];
}
public int GetSelectedIndex(object row)
{
return selection.IndexOf(row);
}
public void ClearSelection()
{
selection.Clear();
Invalidate();
}
private void Invalidate()
{
view.CloseEditor();
view.BeginUpdate();
view.EndUpdate();
}
public void SelectAll()
{
selection.Clear();
ICollection dataSource = view.DataSource as ICollection;
if (dataSource != null && dataSource.Count == view.DataRowCount)
selection.AddRange(dataSource); // fast
else
for (int i = 0; i < view.DataRowCount; i++) // slow
selection.Add(view.GetRow(i));
Invalidate();
}
public void SelectGroup(int rowHandle, bool select)
{
if (IsGroupRowSelected(rowHandle) && select) return;
for (int i = 0; i < view.GetChildRowCount(rowHandle); i++)
{
int childRowHandle = view.GetChildRowHandle(rowHandle, i);
if (view.IsGroupRow(childRowHandle))
SelectGroup(childRowHandle, select);
else
SelectRow(childRowHandle, select, false);
}
Invalidate();
}
public void SelectRow(int rowHandle, bool select)
{
SelectRow(rowHandle, select, true);
}
private void SelectRow(int rowHandle, bool select, bool invalidate)
{
if (IsRowSelected(rowHandle) == select) return;
object row = view.GetRow(rowHandle);
if (select)
selection.Add(row);
else
selection.Remove(row);
if (invalidate)
{
Invalidate();
}
}
public bool IsGroupRowSelected(int rowHandle)
{
for (int i = 0; i < view.GetChildRowCount(rowHandle); i++)
{
int row = view.GetChildRowHandle(rowHandle, i);
if (view.IsGroupRow(row))
{
if (!IsGroupRowSelected(row)) return false;
}
else
if (!IsRowSelected(row)) return false;
}
return true;
}
public bool IsRowSelected(int rowHandle)
{
if (view.IsGroupRow(rowHandle))
return IsGroupRowSelected(rowHandle);
object row = view.GetRow(rowHandle);
return GetSelectedIndex(row) != -1;
}
private void view_CustomUnboundColumnData(object sender, CustomColumnDataEventArgs e)
{
if (e.Column == CheckMarkColumn)
{
if (e.IsGetData)
e.Value = IsRowSelected(View.GetRowHandle(e.ListSourceRowIndex));
else
SelectRow(View.GetRowHandle(e.ListSourceRowIndex), (bool)e.Value);
}
}
private void edit_EditValueChanged(object sender, EventArgs e)
{
view.PostEditor();
}
}
}
|
10hca1-team4-qldv
|
trunk/ 10hca1-team4-qldv/QLDV_DA/GridCheckMarksSelection.cs
|
C#
|
asf20
| 10,607
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Threading;
using DTOQLDV;
using BUSQLDV;
using System.Configuration;
namespace QLDV_DA
{
public partial class frmsplash : DevExpress.XtraEditors.XtraForm
{
private static Thread _splashThread;
private static frmsplash _splashForm;
public frmsplash()
{
InitializeComponent();
}
public static void ShowSplash()
{
if (_splashThread == null)
{
// show the form in a new thread
_splashThread = new Thread(new ThreadStart(DoShowSplash));
_splashThread.IsBackground = true;
_splashThread.Start();
}
}
// Called by the thread
private static void DoShowSplash()
{
//CaiDatThamSo();
if (_splashForm == null)
{
_splashForm = new frmsplash();
_splashForm.StartPosition = FormStartPosition.CenterScreen;
_splashForm.TopMost = true;
}
// create a new message pump on this thread (started from ShowSplash)
Application.Run(_splashForm);
}
// Close the splash (Loading...) screen
public static void CloseSplash()
{
// Need to call on the thread that launched this splash
if (_splashForm.InvokeRequired)
_splashForm.Invoke(new MethodInvoker(CloseSplash));
else
Application.ExitThread();
}
}
}
|
10hca1-team4-qldv
|
trunk/ 10hca1-team4-qldv/QLDV_DA/frmsplash.cs
|
C#
|
asf20
| 1,917
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using BUSQLDV;
using DTOQLDV;
using System.Runtime.InteropServices;
using System.Globalization;
namespace QLDV_DA
{
public partial class frmNhapDuLieu : DevExpress.XtraEditors.XtraForm
{
public frmNhapDuLieu(String fileName)
{
InitializeComponent();
_fileName = fileName;
_dsDung = new List<DTODuLieu>();
_dsSai = new List<DTODuLieuEX>();
KhoiTao();
}
private String _fileName;
private List<DTODuLieu> _dsDung;
private List<DTODuLieuEX> _dsSai;
private void KhoiTao()
{
//Load cac cot du lieu
rclMaDiaDiem.DisplayMember = "TenDiaDiem";
rclMaDiaDiem.ValueMember = "MaDiaDiem";
rclMaDichVu.DisplayMember = "TenDichVu";
rclMaDichVu.ValueMember = "MaDichVu";
rclMaDuong.DisplayMember = "TenDuong";
rclMaDuong.ValueMember = "MaDuong";
rclMaPhuong.DisplayMember = "TenPhuong";
rclMaPhuong.ValueMember = "MaPhuong";
rclMaQuanHuyen.DisplayMember = "TenQuanHuyen";
rclMaQuanHuyen.ValueMember = "MaQuanHuyen";
rclMaTinhThanh.DisplayMember = "TenTinhThanh";
rclMaTinhThanh.ValueMember = "MaTinhThanh";
rclMaDichVu.DisplayMember = "TenDichVu";
rclMaDichVu.ValueMember = "MaDichVu";
rclMaDiaDiem.DataSource = SESSION._dsDiaDiem;
rclMaDichVu.DataSource = SESSION._dsDichVu;
rclMaDuong.DataSource = SESSION._dsDuong;
rclMaPhuong.DataSource = SESSION._dsPhuong;
rclMaQuanHuyen.DataSource = SESSION._dsQuanHuyen;
rclMaTinhThanh.DataSource = SESSION._dsTinhThanh;
rclMaDichVu.DataSource = SESSION._dsDichVu;
rclTenDiaDiem.DataSource = SESSION._dsDiaDiem;
rclTenDichVu.DataSource = SESSION._dsDichVu;
rclTenDuong.DataSource = SESSION._dsDuong;
rclTenPhuong.DataSource = SESSION._dsPhuong;
rclTenQuanHuyen.DataSource = SESSION._dsQuanHuyen;
rclTenTinhThanh.DataSource = SESSION._dsTinhThanh;
rclTenDichVu.DataSource = SESSION._dsDichVu;
thGridDanhSachDuLieuDung.DataSource = _dsDung;
thGridDanhSachDuLieuSai.DataSource = _dsSai;
}
private void XuLiDuLieu()
{
BUSXuLi.MapDuLieu(_dsDung, _dsSai);
LamTuoi();
}
private void LoadDuLieu()
{
frmTienDo frm = new frmTienDo();
try
{
_dsSai = BUSXuLi.DocDuLieuTuFileExcel(_fileName);
frm.ThucHienThread();
XuLiDuLieu();
}
catch (Exception ex)
{
MessageBox.Show("Xảy ra lỗi " + ex.Message, "Thông báo");
}
finally
{
frm.Thoat();
this.Activate();
}
}
private void frmNhapDuLieu_Load(object sender, EventArgs e)
{
LoadDuLieu();
}
private void thGridviewDuLieuBiSai_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
{
if (e.Column == fclSTT)
{
e.DisplayText = Convert.ToString(e.RowHandle + 1);
}
}
private void thgridDanhSach_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
{
if (e.Column == clSTT)
{
e.DisplayText = Convert.ToString(e.RowHandle + 1);
}
}
private void cnThoat_Click(object sender, EventArgs e)
{
this.Close();
}
/// <summary>
/// Gán dữ liệu vào datagridview
/// </summary>
private void LamTuoi()
{
thGridDanhSachDuLieuDung.RefreshDataSource();
thGridDanhSachDuLieuSai.RefreshDataSource();
}
/// <summary>
///Xử lí sự kiện nhấn nút chỉnh sữa thủ công
///</summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cnChinhSuaThuCong_Click(object sender, EventArgs e)
{
if (_dsSai.Count > 0)
{
frmTienDo frm = new frmTienDo();
try
{
frm.ThucHienThread();
XuLiDuLieu();
LamTuoi();
}
catch (Exception ex)
{
}
finally
{
frm.Thoat();
this.Activate();
}
}
}
/// <summary>
/// Hàm xử lí đồng ý fix dữ liêu =j tự động
/// </summary>
/// <param name="arr"></param>
private void ThucHien(bool[] arr)
{
if (_dsSai.Count > 0)
{
frmTienDo frm = new frmTienDo();
try
{
frm.ThucHienThread();
BUSXuLi.CaiDatDuLieuNhap(_dsSai, arr);
XuLiDuLieu();
LamTuoi();
}
catch (Exception ex)
{
MessageBox.Show("Xảy ra lỗi " + ex.Message, "Thông báo");
}
finally
{
frm.Thoat();
this.Activate();
}
}
else
{
MessageBox.Show("Không còn dòng nào sai", "Thông báo");
}
}
/// <summary>
/// Hàm xử lí bỏ qua các dòng xử lí sự kiện
/// </summary>
private void BoQua()
{
if (_dsSai.Count > 0)
{
_dsSai.Clear();
LamTuoi();
}
else
{
MessageBox.Show("Không có dòng nào sai","Thống báo");
}
}
private void cnDongY_Click(object sender, EventArgs e)
{
frmTienDo frm = new frmTienDo();
try
{
frm.ThucHienThread();
BUSDuLieu.ThemDanhSachDuLieu(_dsDung);
}
catch (Exception ex)
{
MessageBox.Show("Xảy ra lỗi " + ex.Message, "Thông báo");
}
finally
{
frm.Thoat();
this.Activate();
this.Close();
}
}
private void cnChinhSuaTuDong_Click(object sender, EventArgs e)
{
frmXuLiTuDongDuLuLieuSai frm = new frmXuLiTuDongDuLuLieuSai();
frm._thucHien = new frmXuLiTuDongDuLuLieuSai.ThucHien(ThucHien);
frm._boQua = new frmXuLiTuDongDuLuLieuSai.BoQua(BoQua);
frm.ShowDialog();
}
private void cnXoa_Click(object sender, EventArgs e)
{
try
{
MessageBox.Show("Quá đễ xử lí sau");
}
catch (Exception ex)
{
}
}
}
}
|
10hca1-team4-qldv
|
trunk/ 10hca1-team4-qldv/QLDV_DA/frmNhapDuLieu.cs
|
C#
|
asf20
| 8,045
|
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head><title>V9 JS站群跨域</title></head>
<body onload="a()">
<script type="text/javascript">
function a(){
var q = location.search.replace('?','').split('|');
if (top.document.getElementById('comment_iframe')) top.document.getElementById('comment_iframe').height=(q[0] ? q[0] : '0');
if (top.document.getElementById('comment')) top.document.getElementById('comment').innerHTML=(q[1] ? q[1] : '0');
}
</script>
</body>
</html>
|
108wo
|
js.html
|
HTML
|
asf20
| 523
|
<?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();
?>
|
108wo
|
phpsso_server/index.php
|
PHP
|
asf20
| 278
|
function confirmurl(url,message)
{
if(confirm(message)) redirect(url);
}
function redirect(url) {
if(url.indexOf('://') == -1 && url.substr(0, 1) != '/' && url.substr(0, 1) != '?') url = $('base').attr('href')+url;
location.href = url;
}
//滚动条
$(function(){
//inputStyle
$(":text").addClass('input-text');
})
/**
* 全选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;
});
}
}
|
108wo
|
phpsso_server/statics/js/admin_common.js
|
JavaScript
|
asf20
| 714
|
/* Copyright Mihai Bazon, 2002-2005 | www.bazon.net/mishoo
* The DHTML Calendar, version 1.0 "It is happening again"
* Details and latest version at:
* www.dynarch.com/projects/calendar
* This script is developed by Dynarch.com. Visit us at www.dynarch.com.
* This script is distributed under the GNU Lesser General Public License.
* Read the entire license text here: http://www.gnu.org/licenses/lgpl.html
// $Id: calendar.js,v 1.51 2005/03/07 16:44:31 mishoo Exp $
/** The Calendar object constructor. */
//document.createStyleSheet('/images/js/calendar/calendar-blue.css');
var head = document.getElementsByTagName('HEAD').item(0);
var style = document.createElement('link');
style.href = '/statics/js/calendar/calendar-blue.css';
style.rel = 'stylesheet';
style.type = 'text/css';
head.appendChild(style);
Calendar = function (firstDayOfWeek, dateStr, onSelected, onClose) {this.activeDiv = null;this.currentDateEl = null;this.getDateStatus = null;
this.getDateToolTip = null;this.getDateText = null;
this.timeout = null;this.onSelected = onSelected || null;
this.onClose = onClose || null;
this.dragging = false;
this.hidden = false;
this.minYear = 1970;
this.maxYear = 2050;
this.dateFormat = Calendar._TT["DEF_DATE_FORMAT"];
this.ttDateFormat = Calendar._TT["TT_DATE_FORMAT"];
this.isPopup = true;
this.weekNumbers = true;
this.firstDayOfWeek = typeof firstDayOfWeek == "number" ? firstDayOfWeek : Calendar._FD;
this.showsOtherMonths = false;
this.dateStr = dateStr;
this.ar_days = null;
this.showsTime = false;
this.time24 = true;
this.yearStep = 2;
this.hiliteToday = true;
this.multiple = null;this.table = null;
this.element = null;
this.tbody = null;this.firstdayname = null;this.monthsCombo = null;this.yearsCombo = null;this.hilitedMonth = null;this.activeMonth = null;this.hilitedYear = null;
this.activeYear = null;this.dateClicked = false;
if (typeof Calendar._SDN == "undefined") {if (typeof Calendar._SDN_len == "undefined")Calendar._SDN_len = 3;var ar = new Array();for (var i = 8; i > 0;) {ar[--i] = Calendar._DN[i].substr(0, Calendar._SDN_len);}Calendar._SDN = ar;if (typeof Calendar._SMN_len == "undefined")Calendar._SMN_len = 3;ar = new Array();for (var i = 12; i > 0;) {ar[--i] = Calendar._MN[i].substr(0, Calendar._SMN_len);}Calendar._SMN = ar;}};Calendar._C = null;Calendar.is_ie = ( /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent) );Calendar.is_ie5 = ( Calendar.is_ie && /msie 5\.0/i.test(navigator.userAgent) );Calendar.is_opera = /opera/i.test(navigator.userAgent);Calendar.is_khtml = /Konqueror|Safari|KHTML/i.test(navigator.userAgent);Calendar.getAbsolutePos = function(el) {var SL = 0, ST = 0;var is_div = /^div$/i.test(el.tagName);if (is_div && el.scrollLeft)SL = el.scrollLeft;if (is_div && el.scrollTop)ST = el.scrollTop;var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };if (el.offsetParent) {var tmp = this.getAbsolutePos(el.offsetParent);r.x += tmp.x;r.y += tmp.y;}return r;};Calendar.isRelated = function (el, evt) {var related = evt.relatedTarget;if (!related) {var type = evt.type;if (type == "mouseover") {related = evt.fromElement;} else if (type == "mouseout") {related = evt.toElement;}}while (related) {if (related == el) {return true;}related = related.parentNode;}return false;};Calendar.removeClass = function(el, className) {if (!(el && el.className)) {return;}var cls = el.className.split(" ");var ar = new Array();for (var i = cls.length; i > 0;) {if (cls[--i] != className) {ar[ar.length] = cls[i];}}el.className = ar.join(" ");};Calendar.addClass = function(el, className) {Calendar.removeClass(el, className);el.className += " " + className;};Calendar.getElement = function(ev) {var f = Calendar.is_ie ? window.event.srcElement : ev.currentTarget;while (f.nodeType != 1 || /^div$/i.test(f.tagName))f = f.parentNode;return f;};Calendar.getTargetElement = function(ev) {var f = Calendar.is_ie ? window.event.srcElement : ev.target;while (f.nodeType != 1)f = f.parentNode;return f;};Calendar.stopEvent = function(ev) {ev || (ev = window.event);if (Calendar.is_ie) {ev.cancelBubble = true;ev.returnValue = false;} else {ev.preventDefault();ev.stopPropagation();}return false;};Calendar.addEvent = function(el, evname, func) {if (el.attachEvent) { el.attachEvent("on" + evname, func);} else if (el.addEventListener) { el.addEventListener(evname, func, true);} else {el["on" + evname] = func;}};Calendar.removeEvent = function(el, evname, func) {if (el.detachEvent) { el.detachEvent("on" + evname, func);} else if (el.removeEventListener) { el.removeEventListener(evname, func, true);} else {el["on" + evname] = null;}};Calendar.createElement = function(type, parent) {var el = null;if (document.createElementNS) {el = document.createElementNS("http://www.w3.org/1999/xhtml", type);} else {el = document.createElement(type);}if (typeof parent != "undefined") {parent.appendChild(el);}return el;};Calendar._add_evs = function(el) {with (Calendar) {addEvent(el, "mouseover", dayMouseOver);addEvent(el, "mousedown", dayMouseDown);addEvent(el, "mouseout", dayMouseOut);if (is_ie) {addEvent(el, "dblclick", dayMouseDblClick);el.setAttribute("unselectable", true);}}};Calendar.findMonth = function(el) {if (typeof el.month != "undefined") {return el;} else if (typeof el.parentNode.month != "undefined") {return el.parentNode;}return null;};Calendar.findYear = function(el) {if (typeof el.year != "undefined") {return el;} else if (typeof el.parentNode.year != "undefined") {return el.parentNode;}return null;};Calendar.showMonthsCombo = function () {var cal = Calendar._C;if (!cal) {return false;}var cal = cal;var cd = cal.activeDiv;var mc = cal.monthsCombo;if (cal.hilitedMonth) {Calendar.removeClass(cal.hilitedMonth, "hilite");}if (cal.activeMonth) {Calendar.removeClass(cal.activeMonth, "active");}var mon = cal.monthsCombo.getElementsByTagName("div")[cal.date.getMonth()];Calendar.addClass(mon, "active");cal.activeMonth = mon;var s = mc.style;s.display = "block";if (cd.navtype < 0)s.left = cd.offsetLeft + "px";else {var mcw = mc.offsetWidth;if (typeof mcw == "undefined")mcw = 50;s.left = (cd.offsetLeft + cd.offsetWidth - mcw) + "px";}s.top = (cd.offsetTop + cd.offsetHeight) + "px";};Calendar.showYearsCombo = function (fwd) {var cal = Calendar._C;if (!cal) {return false;}var cal = cal;var cd = cal.activeDiv;var yc = cal.yearsCombo;if (cal.hilitedYear) {Calendar.removeClass(cal.hilitedYear, "hilite");}if (cal.activeYear) {Calendar.removeClass(cal.activeYear, "active");}cal.activeYear = null;var Y = cal.date.getFullYear() + (fwd ? 1 : -1);var yr = yc.firstChild;var show = false;for (var i = 12; i > 0; --i) {if (Y >= cal.minYear && Y <= cal.maxYear) {yr.innerHTML = Y;yr.year = Y;yr.style.display = "block";show = true;} else {yr.style.display = "none";}yr = yr.nextSibling;Y += fwd ? cal.yearStep : -cal.yearStep;}if (show) {var s = yc.style;s.display = "block";if (cd.navtype < 0)s.left = cd.offsetLeft + "px";else {var ycw = yc.offsetWidth;if (typeof ycw == "undefined")ycw = 50;s.left = (cd.offsetLeft + cd.offsetWidth - ycw) + "px";}s.top = (cd.offsetTop + cd.offsetHeight) + "px";}};Calendar.tableMouseUp = function(ev) {var cal = Calendar._C;if (!cal) {return false;}if (cal.timeout) {clearTimeout(cal.timeout);}var el = cal.activeDiv;if (!el) {return false;}var target = Calendar.getTargetElement(ev);ev || (ev = window.event);Calendar.removeClass(el, "active");if (target == el || target.parentNode == el) {Calendar.cellClick(el, ev);}var mon = Calendar.findMonth(target);var date = null;if (mon) {date = new Date(cal.date);if (mon.month != date.getMonth()) {date.setMonth(mon.month);cal.setDate(date);cal.dateClicked = false;cal.callHandler();}} else {var year = Calendar.findYear(target);if (year) {date = new Date(cal.date);if (year.year != date.getFullYear()) {date.setFullYear(year.year);cal.setDate(date);cal.dateClicked = false;cal.callHandler();}}}with (Calendar) {removeEvent(document, "mouseup", tableMouseUp);removeEvent(document, "mouseover", tableMouseOver);removeEvent(document, "mousemove", tableMouseOver);cal._hideCombos();_C = null;return stopEvent(ev);}};Calendar.tableMouseOver = function (ev) {var cal = Calendar._C;if (!cal) {return;}var el = cal.activeDiv;var target = Calendar.getTargetElement(ev);if (target == el || target.parentNode == el) {Calendar.addClass(el, "hilite active");Calendar.addClass(el.parentNode, "rowhilite");} else {if (typeof el.navtype == "undefined" || (el.navtype != 50 && (el.navtype == 0 || Math.abs(el.navtype) > 2)))Calendar.removeClass(el, "active");Calendar.removeClass(el, "hilite");Calendar.removeClass(el.parentNode, "rowhilite");}ev || (ev = window.event);if (el.navtype == 50 && target != el) {var pos = Calendar.getAbsolutePos(el);var w = el.offsetWidth;var x = ev.clientX;var dx;var decrease = true;if (x > pos.x + w) {dx = x - pos.x - w;decrease = false;} elsedx = pos.x - x;if (dx < 0) dx = 0;var range = el._range;var current = el._current;var count = Math.floor(dx / 10) % range.length;for (var i = range.length; --i >= 0;)if (range[i] == current)
break;
while (count-- > 0)
if (decrease) {
if (--i < 0)
i = range.length - 1;
} else if ( ++i >= range.length )
i = 0;
var newval = range[i];
el.innerHTML = newval;cal.onUpdateTime();
}
var mon = Calendar.findMonth(target);
if (mon) {
if (mon.month != cal.date.getMonth()) {
if (cal.hilitedMonth) {
Calendar.removeClass(cal.hilitedMonth, "hilite");
}
Calendar.addClass(mon, "hilite");
cal.hilitedMonth = mon;
} else if (cal.hilitedMonth) {
Calendar.removeClass(cal.hilitedMonth, "hilite");
}
} else {
if (cal.hilitedMonth) {Calendar.removeClass(cal.hilitedMonth, "hilite");}var year = Calendar.findYear(target);if (year) {if (year.year != cal.date.getFullYear()) {if (cal.hilitedYear) {Calendar.removeClass(cal.hilitedYear, "hilite");}Calendar.addClass(year, "hilite");cal.hilitedYear = year;} else if (cal.hilitedYear) {Calendar.removeClass(cal.hilitedYear, "hilite");}} else if (cal.hilitedYear) {Calendar.removeClass(cal.hilitedYear, "hilite");}}return Calendar.stopEvent(ev);};Calendar.tableMouseDown = function (ev) {if (Calendar.getTargetElement(ev) == Calendar.getElement(ev)) {return Calendar.stopEvent(ev);}};Calendar.calDragIt = function (ev) {var cal = Calendar._C;if (!(cal && cal.dragging)) {return false;}var posX;var posY;if (Calendar.is_ie) {posY = window.event.clientY + document.body.scrollTop;posX = window.event.clientX + document.body.scrollLeft;} else {posX = ev.pageX;posY = ev.pageY;}cal.hideShowCovered();var st = cal.element.style;st.left = (posX - cal.xOffs) + "px";st.top = (posY - cal.yOffs) + "px";return Calendar.stopEvent(ev);};Calendar.calDragEnd = function (ev) {var cal = Calendar._C;if (!cal) {return false;}cal.dragging = false;with (Calendar) {removeEvent(document, "mousemove", calDragIt);removeEvent(document, "mouseup", calDragEnd);tableMouseUp(ev);}cal.hideShowCovered();};Calendar.dayMouseDown = function(ev) {var el = Calendar.getElement(ev);
if (el.disabled) {
return false;
}
var cal = el.calendar;
cal.activeDiv = el;
Calendar._C = cal;
if (el.navtype != 300) with (Calendar) {
if (el.navtype == 50) {
el._current = el.innerHTML;
addEvent(document, "mousemove", tableMouseOver);
} else
addEvent(document, Calendar.is_ie5 ? "mousemove" : "mouseover", tableMouseOver);
addClass(el, "hilite active");
addEvent(document, "mouseup", tableMouseUp);
} else if (cal.isPopup) {
cal._dragStart(ev);
}
if (el.navtype == -1 || el.navtype == 1) {
if (cal.timeout) clearTimeout(cal.timeout);
cal.timeout = setTimeout("Calendar.showMonthsCombo()", 250);
} else if (el.navtype == -2 || el.navtype == 2) {
if (cal.timeout) clearTimeout(cal.timeout);
cal.timeout = setTimeout((el.navtype > 0) ? "Calendar.showYearsCombo(true)" : "Calendar.showYearsCombo(false)", 250);
} else {
cal.timeout = null;
}
return Calendar.stopEvent(ev);
};Calendar.dayMouseDblClick = function(ev) {
Calendar.cellClick(Calendar.getElement(ev), ev || window.event);
if (Calendar.is_ie) {
document.selection.empty();
}
};Calendar.dayMouseOver = function(ev) {
var el = Calendar.getElement(ev);
if (Calendar.isRelated(el, ev) || Calendar._C || el.disabled) {
return false;
}
if (el.ttip) {
if (el.ttip.substr(0, 1) == "_") {
el.ttip = el.caldate.print(el.calendar.ttDateFormat) + el.ttip.substr(1);
}
el.calendar.tooltips.innerHTML = el.ttip;
}
if (el.navtype != 300) {
Calendar.addClass(el, "hilite");
if (el.caldate) {
Calendar.addClass(el.parentNode, "rowhilite");
}
}
return Calendar.stopEvent(ev);
};Calendar.dayMouseOut = function(ev) {
with (Calendar) {
var el = getElement(ev);
if (isRelated(el, ev) || _C || el.disabled)
return false;
removeClass(el, "hilite");
if (el.caldate)
removeClass(el.parentNode, "rowhilite");
if (el.calendar)
el.calendar.tooltips.innerHTML = _TT["SEL_DATE"];
return stopEvent(ev);
}
};
Calendar.cellClick = function(el, ev) {
var cal = el.calendar;
var closing = false;
var newdate = false;
var date = null;
if (typeof el.navtype == "undefined") {
if (cal.currentDateEl) {
Calendar.removeClass(cal.currentDateEl, "selected");
Calendar.addClass(el, "selected");
closing = (cal.currentDateEl == el);
if (!closing) {
cal.currentDateEl = el;
}
}
cal.date.setDateOnly(el.caldate);
date = cal.date;
var other_month = !(cal.dateClicked = !el.otherMonth);
if (!other_month && !cal.currentDateEl)
cal._toggleMultipleDate(new Date(date));
else
newdate = !el.disabled;if (other_month)
cal._init(cal.firstDayOfWeek, date);
} else {
if (el.navtype == 200) {
Calendar.removeClass(el, "hilite");
cal.callCloseHandler();
return;
}
date = new Date(cal.date);
if (el.navtype == 0)
date.setDateOnly(new Date());
cal.dateClicked = false;
var year = date.getFullYear();
var mon = date.getMonth();
function setMonth(m) {
var day = date.getDate();
var max = date.getMonthDays(m);
if (day > max) {
date.setDate(max);
}
date.setMonth(m);
};
switch (el.navtype) {
case 400:
Calendar.removeClass(el, "hilite");
var text = Calendar._TT["ABOUT"];
if (typeof text != "undefined") {
text += cal.showsTime ? Calendar._TT["ABOUT_TIME"] : "";
} else {text = "Help and about box text is not translated into this language.\n" +
"If you know this language and you feel generous please update\n" +
"the corresponding file in \"lang\" subdir to match calendar-en.js\n" +
"and send it back to <mihai_bazon@yahoo.com> to get it into the distribution ;-)\n\n" +
"Thank you!\n" +
"http://dynarch.com/mishoo/calendar.epl\n";
}
alert(text);
return;
case -2:
if (year > cal.minYear) {
date.setFullYear(year - 1);
}
break;
case -1:
if (mon > 0) {
setMonth(mon - 1);
} else if (year-- > cal.minYear) {
date.setFullYear(year);
setMonth(11);
}
break;
case 1:
if (mon < 11) {
setMonth(mon + 1);
} else if (year < cal.maxYear) {
date.setFullYear(year + 1);
setMonth(0);
}
break;
case 2:
if (year < cal.maxYear) {
date.setFullYear(year + 1);
}
break;
case 100:
cal.setFirstDayOfWeek(el.fdow);
return;
case 50:
var range = el._range;
var current = el.innerHTML;
for (var i = range.length; --i >= 0;)
if (range[i] == current)
break;
if (ev && ev.shiftKey) {
if (--i < 0)
i = range.length - 1;
} else if ( ++i >= range.length )
i = 0;
var newval = range[i];
el.innerHTML = newval;
cal.onUpdateTime();
return;
case 0:if ((typeof cal.getDateStatus == "function") &&
cal.getDateStatus(date, date.getFullYear(), date.getMonth(), date.getDate())) {
return false;
}
break;
}
if (!date.equalsTo(cal.date)) {
cal.setDate(date);
newdate = true;
} else if (el.navtype == 0)
newdate = closing = true;
}
if (newdate) {
ev && cal.callHandler();
}
if (closing) {
Calendar.removeClass(el, "hilite");
ev && cal.callCloseHandler();
}
};
Calendar.prototype.create = function (_par) {
var parent = null;
if (! _par) {
parent = document.getElementsByTagName("body")[0];
this.isPopup = true;
} else {
parent = _par;
this.isPopup = false;
}
this.date = this.dateStr ? new Date(this.dateStr) : new Date();var table = Calendar.createElement("table");
this.table = table;
table.cellSpacing = 0;
table.cellPadding = 0;
table.calendar = this;
Calendar.addEvent(table, "mousedown", Calendar.tableMouseDown);var div = Calendar.createElement("div");
this.element = div;
div.className = "calendar";
if (this.isPopup) {
div.style.position = "absolute";
div.style.display = "none";
}
div.appendChild(table);var thead = Calendar.createElement("thead", table);
var cell = null;
var row = null;var cal = this;
var hh = function (text, cs, navtype) {
cell = Calendar.createElement("td", row);
cell.colSpan = cs;
cell.className = "button";
if (navtype != 0 && Math.abs(navtype) <= 2)
cell.className += " nav";
Calendar._add_evs(cell);
cell.calendar = cal;
cell.navtype = navtype;
cell.innerHTML = "<div unselectable='on'>" + text + "</div>";
return cell;
};row = Calendar.createElement("tr", thead);
var title_length = 6;
(this.isPopup) && --title_length;
(this.weekNumbers) && ++title_length;hh("<div>?</div>", 1, 400).ttip = Calendar._TT["INFO"];
this.title = hh("", title_length, 300);
this.title.className = "title";
if (this.isPopup) {
this.title.ttip = Calendar._TT["DRAG_TO_MOVE"];
this.title.style.cursor = "move";
hh("×", 1, 200).ttip = Calendar._TT["CLOSE"];
}row = Calendar.createElement("tr", thead);
row.className = "headrow";this._nav_py = hh("«", 1, -2);
this._nav_py.ttip = Calendar._TT["PREV_YEAR"];this._nav_pm = hh("‹", 1, -1);
this._nav_pm.ttip = Calendar._TT["PREV_MONTH"];this._nav_now = hh(Calendar._TT["TODAY"], this.weekNumbers ? 4 : 3, 0);
this._nav_now.ttip = Calendar._TT["GO_TODAY"];this._nav_nm = hh("›", 1, 1);
this._nav_nm.ttip = Calendar._TT["NEXT_MONTH"];this._nav_ny = hh("»", 1, 2);
this._nav_ny.ttip = Calendar._TT["NEXT_YEAR"];
row = Calendar.createElement("tr", thead);
row.className = "daynames";
if (this.weekNumbers) {
cell = Calendar.createElement("td", row);
cell.className = "name wn";
cell.innerHTML = "<div>"+Calendar._TT["WK"]+"</div>";
}
for (var i = 7; i > 0; --i) {
cell = Calendar.createElement("td", row);
if (!i) {
cell.navtype = 100;
cell.calendar = this;
Calendar._add_evs(cell);
}
}
this.firstdayname = (this.weekNumbers) ? row.firstChild.nextSibling : row.firstChild;
this._displayWeekdays();var tbody = Calendar.createElement("tbody", table);
this.tbody = tbody;for (i = 6; i > 0; --i) {
row = Calendar.createElement("tr", tbody);
if (this.weekNumbers) {
cell = Calendar.createElement("td", row);
}
for (var j = 7; j > 0; --j) {
cell = Calendar.createElement("td", row);
cell.calendar = this;
Calendar._add_evs(cell);
}
}if (this.showsTime) {
row = Calendar.createElement("tr", tbody);
row.className = "time";cell = Calendar.createElement("td", row);
cell.className = "time";
cell.colSpan = 2;
cell.innerHTML = Calendar._TT["TIME"] || " ";cell = Calendar.createElement("td", row);
cell.className = "time";
cell.colSpan = this.weekNumbers ? 4 : 3;(function(){
function makeTimePart(className, init, range_start, range_end) {
var part = Calendar.createElement("span", cell);
part.className = className;
part.innerHTML = init;
part.calendar = cal;
part.ttip = Calendar._TT["TIME_PART"];
part.navtype = 50;
part._range = [];
if (typeof range_start != "number")
part._range = range_start;
else {
for (var i = range_start; i <= range_end; ++i) {
var txt;
if (i < 10 && range_end >= 10) txt = '0' + i;
else txt = '' + i;
part._range[part._range.length] = txt;
}
}
Calendar._add_evs(part);
return part;
};
var hrs = cal.date.getHours();
var mins = cal.date.getMinutes();
var t12 = !cal.time24;
var pm = (hrs > 12);
if (t12 && pm) hrs -= 12;
var H = makeTimePart("hour", hrs, t12 ? 1 : 0, t12 ? 12 : 23);
var span = Calendar.createElement("span", cell);
span.innerHTML = ":";
span.className = "colon";
var M = makeTimePart("minute", mins, 0, 59);
var AP = null;
cell = Calendar.createElement("td", row);
cell.className = "time";
cell.colSpan = 2;
if (t12)
AP = makeTimePart("ampm", pm ? "pm" : "am", ["am", "pm"]);
else
cell.innerHTML = " ";cal.onSetTime = function() {
var pm, hrs = this.date.getHours(),
mins = this.date.getMinutes();
if (t12) {
pm = (hrs >= 12);
if (pm) hrs -= 12;
if (hrs == 0) hrs = 12;
AP.innerHTML = pm ? "pm" : "am";
}
H.innerHTML = (hrs < 10) ? ("0" + hrs) : hrs;
M.innerHTML = (mins < 10) ? ("0" + mins) : mins;
};cal.onUpdateTime = function() {
var date = this.date;
var h = parseInt(H.innerHTML, 10);
if (t12) {
if (/pm/i.test(AP.innerHTML) && h < 12)
h += 12;
else if (/am/i.test(AP.innerHTML) && h == 12)
h = 0;
}
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
date.setHours(h);
date.setMinutes(parseInt(M.innerHTML, 10));
date.setFullYear(y);
date.setMonth(m);
date.setDate(d);
this.dateClicked = false;
this.callHandler();
};
})();
} else {
this.onSetTime = this.onUpdateTime = function() {};
}var tfoot = Calendar.createElement("tfoot", table);row = Calendar.createElement("tr", tfoot);
row.className = "footrow";cell = hh(Calendar._TT["SEL_DATE"], this.weekNumbers ? 8 : 7, 300);
cell.className = "ttip";
if (this.isPopup) {
cell.ttip = Calendar._TT["DRAG_TO_MOVE"];
cell.style.cursor = "move";
}
this.tooltips = cell;div = Calendar.createElement("div", this.element);
this.monthsCombo = div;
div.className = "combo";
for (i = 0; i < Calendar._MN.length; ++i) {
var mn = Calendar.createElement("div");
mn.className = Calendar.is_ie ? "label-IEfix" : "label";
mn.month = i;
mn.innerHTML = Calendar._SMN[i];
div.appendChild(mn);
}div = Calendar.createElement("div", this.element);
this.yearsCombo = div;
div.className = "combo";
for (i = 12; i > 0; --i) {
var yr = Calendar.createElement("div");
yr.className = Calendar.is_ie ? "label-IEfix" : "label";
div.appendChild(yr);
}this._init(this.firstDayOfWeek, this.date);
parent.appendChild(this.element);
};
Calendar._keyEvent = function(ev) {
var cal = window._dynarch_popupCalendar;
if (!cal || cal.multiple)
return false;
(Calendar.is_ie) && (ev = window.event);
var act = (Calendar.is_ie || ev.type == "keypress"),
K = ev.keyCode;
if (ev.ctrlKey) {
switch (K) {
case 37:
act && Calendar.cellClick(cal._nav_pm);
break;
case 38:
act && Calendar.cellClick(cal._nav_py);
break;
case 39:
act && Calendar.cellClick(cal._nav_nm);
break;
case 40:
act && Calendar.cellClick(cal._nav_ny);
break;
default:
return false;
}
} else switch (K) {
case 32:
Calendar.cellClick(cal._nav_now);
break;
case 27:
act && cal.callCloseHandler();
break;
case 37:
case 38:
case 39:
case 40:
if (act) {
var prev, x, y, ne, el, step;
prev = K == 37 || K == 38;
step = (K == 37 || K == 39) ? 1 : 7;
function setVars() {
el = cal.currentDateEl;
var p = el.pos;
x = p & 15;
y = p >> 4;
ne = cal.ar_days[y][x];
};setVars();
function prevMonth() {
var date = new Date(cal.date);
date.setDate(date.getDate() - step);
cal.setDate(date);
};
function nextMonth() {
var date = new Date(cal.date);
date.setDate(date.getDate() + step);
cal.setDate(date);
};
while (1) {
switch (K) {
case 37:
if (--x >= 0)
ne = cal.ar_days[y][x];
else {
x = 6;
K = 38;
continue;
}
break;
case 38:
if (--y >= 0)
ne = cal.ar_days[y][x];
else {
prevMonth();
setVars();
}
break;
case 39:
if (++x < 7)
ne = cal.ar_days[y][x];
else {
x = 0;
K = 40;
continue;
}
break;
case 40:
if (++y < cal.ar_days.length)
ne = cal.ar_days[y][x];
else {
nextMonth();
setVars();
}
break;
}
break;
}
if (ne) {
if (!ne.disabled)
Calendar.cellClick(ne);
else if (prev)
prevMonth();
else
nextMonth();
}
}
break;
case 13:
if (act)
Calendar.cellClick(cal.currentDateEl, ev);
break;
default:
return false;
}
return Calendar.stopEvent(ev);
};
Calendar.prototype._init = function (firstDayOfWeek, date) {
var today = new Date(),
TY = today.getFullYear(),
TM = today.getMonth(),
TD = today.getDate();
this.table.style.visibility = "hidden";
var year = date.getFullYear();
if (year < this.minYear) {
year = this.minYear;
date.setFullYear(year);
} else if (year > this.maxYear) {
year = this.maxYear;
date.setFullYear(year);
}
this.firstDayOfWeek = firstDayOfWeek;
this.date = new Date(date);
var month = date.getMonth();
var mday = date.getDate();
var no_days = date.getMonthDays();
date.setDate(1);
var day1 = (date.getDay() - this.firstDayOfWeek) % 7;
if (day1 < 0)
day1 += 7;
date.setDate(-day1);
date.setDate(date.getDate() + 1);var row = this.tbody.firstChild;
var MN = Calendar._SMN[month];
var ar_days = this.ar_days = new Array();
var weekend = Calendar._TT["WEEKEND"];
var dates = this.multiple ? (this.datesCells = {}) : null;
for (var i = 0; i < 6; ++i, row = row.nextSibling) {
var cell = row.firstChild;
if (this.weekNumbers) {
cell.className = "day wn";
cell.innerHTML = "<div>"+date.getWeekNumber()+"</div>";
cell = cell.nextSibling;
}
row.className = "daysrow";
var hasdays = false, iday, dpos = ar_days[i] = [];
for (var j = 0; j < 7; ++j, cell = cell.nextSibling, date.setDate(iday + 1)) {
iday = date.getDate();
var wday = date.getDay();
cell.className = "day";
cell.pos = i << 4 | j;
dpos[j] = cell;
var current_month = (date.getMonth() == month);
if (!current_month) {
if (this.showsOtherMonths) {
cell.className += " othermonth";
cell.otherMonth = true;
} else {
cell.className = "emptycell";
cell.innerHTML = " ";
cell.disabled = true;
continue;
}
} else {
cell.otherMonth = false;
hasdays = true;
}
cell.disabled = false;
cell.innerHTML = this.getDateText ? this.getDateText(date, iday) : iday;
if (dates)
dates[date.print("%Y%m%d")] = cell;
if (this.getDateStatus) {
var status = this.getDateStatus(date, year, month, iday);
if (this.getDateToolTip) {
var toolTip = this.getDateToolTip(date, year, month, iday);
if (toolTip)
cell.title = toolTip;
}
if (status === true) {
cell.className += " disabled";
cell.disabled = true;
} else {
if (/disabled/i.test(status))
cell.disabled = true;
cell.className += " " + status;
}
}
if (!cell.disabled) {
cell.caldate = new Date(date);
cell.ttip = "_";
if (!this.multiple && current_month
&& iday == mday && this.hiliteToday) {
cell.className += " selected";
this.currentDateEl = cell;
}
if (date.getFullYear() == TY &&
date.getMonth() == TM &&
iday == TD) {
cell.className += " today";
cell.ttip += Calendar._TT["PART_TODAY"];
}
if (weekend.indexOf(wday.toString()) != -1)
cell.className += cell.otherMonth ? " oweekend" : " weekend";
}
}
if (!(hasdays || this.showsOtherMonths))
row.className = "emptyrow";
}
this.title.innerHTML = Calendar._MN[month] + ", " + year;
this.onSetTime();
this.table.style.visibility = "visible";
this._initMultipleDates();
};Calendar.prototype._initMultipleDates = function() {
if (this.multiple) {
for (var i in this.multiple) {
var cell = this.datesCells[i];
var d = this.multiple[i];
if (!d)
continue;
if (cell)
cell.className += " selected";
}
}
};Calendar.prototype._toggleMultipleDate = function(date) {
if (this.multiple) {
var ds = date.print("%Y%m%d");
var cell = this.datesCells[ds];
if (cell) {
var d = this.multiple[ds];
if (!d) {
Calendar.addClass(cell, "selected");
this.multiple[ds] = date;
} else {
Calendar.removeClass(cell, "selected");
delete this.multiple[ds];
}
}
}
};Calendar.prototype.setDateToolTipHandler = function (unaryFunction) {
this.getDateToolTip = unaryFunction;
};
Calendar.prototype.setDate = function (date) {
if (!date.equalsTo(this.date)) {
this._init(this.firstDayOfWeek, date);
}
};
Calendar.prototype.refresh = function () {
this._init(this.firstDayOfWeek, this.date);
};
Calendar.prototype.setFirstDayOfWeek = function (firstDayOfWeek) {
this._init(firstDayOfWeek, this.date);
this._displayWeekdays();
};
Calendar.prototype.setDateStatusHandler = Calendar.prototype.setDisabledHandler = function (unaryFunction) {
this.getDateStatus = unaryFunction;
};
Calendar.prototype.setRange = function (a, z) {
this.minYear = a;
this.maxYear = z;
};
Calendar.prototype.callHandler = function () {
if (this.onSelected) {
this.onSelected(this, this.date.print(this.dateFormat));
}
};
Calendar.prototype.callCloseHandler = function () {
if (this.onClose) {
this.onClose(this);
}
this.hideShowCovered();
};
Calendar.prototype.destroy = function () {
var el = this.element.parentNode;
el.removeChild(this.element);
Calendar._C = null;
window._dynarch_popupCalendar = null;
};
Calendar.prototype.reparent = function (new_parent) {
var el = this.element;
el.parentNode.removeChild(el);
new_parent.appendChild(el);
};
Calendar._checkCalendar = function(ev) {
var calendar = window._dynarch_popupCalendar;
if (!calendar) {
return false;
}
var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev);
for (; el != null && el != calendar.element; el = el.parentNode);
if (el == null) {window._dynarch_popupCalendar.callCloseHandler();
return Calendar.stopEvent(ev);
}
};
Calendar.prototype.show = function () {
var rows = this.table.getElementsByTagName("tr");
for (var i = rows.length; i > 0;) {
var row = rows[--i];
Calendar.removeClass(row, "rowhilite");
var cells = row.getElementsByTagName("td");
for (var j = cells.length; j > 0;) {
var cell = cells[--j];
Calendar.removeClass(cell, "hilite");
Calendar.removeClass(cell, "active");
}
}
this.element.style.display = "block";
this.hidden = false;
if (this.isPopup) {
window._dynarch_popupCalendar = this;
Calendar.addEvent(document, "keydown", Calendar._keyEvent);
Calendar.addEvent(document, "keypress", Calendar._keyEvent);
Calendar.addEvent(document, "mousedown", Calendar._checkCalendar);
}
this.hideShowCovered();
};
Calendar.prototype.hide = function () {
if (this.isPopup) {
Calendar.removeEvent(document, "keydown", Calendar._keyEvent);
Calendar.removeEvent(document, "keypress", Calendar._keyEvent);
Calendar.removeEvent(document, "mousedown", Calendar._checkCalendar);
}
this.element.style.display = "none";
this.hidden = true;
this.hideShowCovered();
};Calendar.prototype.showAt = function (x, y) {
var s = this.element.style;
s.left = x + "px";
s.top = y + "px";
this.show();
};
Calendar.prototype.showAtElement = function (el, opts) {
var self = this;
var p = Calendar.getAbsolutePos(el);
if (!opts || typeof opts != "string") {
this.showAt(p.x, p.y + el.offsetHeight);
return true;
}
function fixPosition(box) {
if (box.x < 0)
box.x = 0;
if (box.y < 0)
box.y = 0;
var cp = document.createElement("div");
var s = cp.style;
s.position = "absolute";
s.right = s.bottom = s.width = s.height = "0px";
document.body.appendChild(cp);
var br = Calendar.getAbsolutePos(cp);
document.body.removeChild(cp);
if (Calendar.is_ie) {
br.y += document.body.scrollTop;
br.x += document.body.scrollLeft;
} else {
br.y += window.scrollY;
br.x += window.scrollX;
}
var tmp = box.x + box.width - br.x;
if (tmp > 0) box.x -= tmp;
tmp = box.y + box.height - br.y;
if (tmp > 0) box.y -= tmp;
};
this.element.style.display = "block";
Calendar.continuation_for_the_fucking_khtml_browser = function() {
var w = self.element.offsetWidth;
var h = self.element.offsetHeight;
self.element.style.display = "none";
var valign = opts.substr(0, 1);
var halign = "l";
if (opts.length > 1) {
halign = opts.substr(1, 1);
}switch (valign) {
case "T": p.y -= h; break;
case "B": p.y += el.offsetHeight; break;
case "C": p.y += (el.offsetHeight - h) / 2; break;
case "t": p.y += el.offsetHeight - h; break;
case "b": break;
}switch (halign) {
case "L": p.x -= w; break;
case "R": p.x += el.offsetWidth; break;
case "C": p.x += (el.offsetWidth - w) / 2; break;
case "l": p.x += el.offsetWidth - w; break;
case "r": break;
}
p.width = w;
p.height = h + 40;
self.monthsCombo.style.display = "none";
fixPosition(p);
self.showAt(p.x, p.y);
};
if (Calendar.is_khtml)
setTimeout("Calendar.continuation_for_the_fucking_khtml_browser()", 10);
else
Calendar.continuation_for_the_fucking_khtml_browser();
};
Calendar.prototype.setDateFormat = function (str) {
this.dateFormat = str;
};
Calendar.prototype.setTtDateFormat = function (str) {
this.ttDateFormat = str;
};
Calendar.prototype.parseDate = function(str, fmt) {
if (!fmt)
fmt = this.dateFormat;
this.setDate(Date.parseDate(str, fmt));
};
Calendar.prototype.hideShowCovered = function () {
if (!Calendar.is_ie && !Calendar.is_opera)
return;
function getVisib(obj){
var value = obj.style.visibility;
if (!value) {
if (document.defaultView && typeof (document.defaultView.getComputedStyle) == "function") {
if (!Calendar.is_khtml)
value = document.defaultView.
getComputedStyle(obj, "").getPropertyValue("visibility");
else
value = '';
} else if (obj.currentStyle) {
value = obj.currentStyle.visibility;
} else
value = '';
}
return value;
};var tags = new Array("applet", "iframe", "select");
var el = this.element;var p = Calendar.getAbsolutePos(el);
var EX1 = p.x;
var EX2 = el.offsetWidth + EX1;
var EY1 = p.y;
var EY2 = el.offsetHeight + EY1;for (var k = tags.length; k > 0; ) {
var ar = document.getElementsByTagName(tags[--k]);
var cc = null;for (var i = ar.length; i > 0;) {
cc = ar[--i];p = Calendar.getAbsolutePos(cc);
var CX1 = p.x;
var CX2 = cc.offsetWidth + CX1;
var CY1 = p.y;
var CY2 = cc.offsetHeight + CY1;if (this.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) {
if (!cc.__msh_save_visibility) {
cc.__msh_save_visibility = getVisib(cc);
}
cc.style.visibility = cc.__msh_save_visibility;
} else {
if (!cc.__msh_save_visibility) {
cc.__msh_save_visibility = getVisib(cc);
}
cc.style.visibility = "hidden";
}
}
}
};
Calendar.prototype._displayWeekdays = function () {
var fdow = this.firstDayOfWeek;
var cell = this.firstdayname;
var weekend = Calendar._TT["WEEKEND"];
for (var i = 0; i < 7; ++i) {
cell.className = "day name";
var realday = (i + fdow) % 7;
if (i) {
cell.ttip = Calendar._TT["DAY_FIRST"].replace("%s", Calendar._DN[realday]);
cell.navtype = 100;
cell.calendar = this;
cell.fdow = realday;
Calendar._add_evs(cell);
}
if (weekend.indexOf(realday.toString()) != -1) {
Calendar.addClass(cell, "weekend");
}
cell.innerHTML = Calendar._SDN[(i + fdow) % 7];
cell = cell.nextSibling;
}
};
Calendar.prototype._hideCombos = function () {
this.monthsCombo.style.display = "none";
this.yearsCombo.style.display = "none";
};
Calendar.prototype._dragStart = function (ev) {
if (this.dragging) {
return;
}
this.dragging = true;
var posX;
var posY;
if (Calendar.is_ie) {
posY = window.event.clientY + document.body.scrollTop;
posX = window.event.clientX + document.body.scrollLeft;
} else {
posY = ev.clientY + window.scrollY;
posX = ev.clientX + window.scrollX;
}
var st = this.element.style;
this.xOffs = posX - parseInt(st.left);
this.yOffs = posY - parseInt(st.top);
with (Calendar) {
addEvent(document, "mousemove", calDragIt);
addEvent(document, "mouseup", calDragEnd);
}
};
Date._MD = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
Date.SECOND = 1000 /* milliseconds */;
Date.MINUTE = 60 * Date.SECOND;
Date.HOUR = 60 * Date.MINUTE;
Date.DAY = 24 * Date.HOUR;
Date.WEEK = 7 * Date.DAY;Date.parseDate = function(str, fmt) {
var today = new Date();
var y = 0;
var m = -1;
var d = 0;
var a = str.split(/\W+/);
var b = fmt.match(/%./g);
var i = 0, j = 0;
var hr = 0;
var min = 0;
for (i = 0; i < a.length; ++i) {
if (!a[i])
continue;
switch (b[i]) {
case "%d":
case "%e":
d = parseInt(a[i], 10);
break; case "%m":
m = parseInt(a[i], 10) - 1;
break; case "%Y":
case "%y":
y = parseInt(a[i], 10);
(y < 100) && (y += (y > 29) ? 1900 : 2000);
break; case "%b":
case "%B":
for (j = 0; j < 12; ++j) {
if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; }
}
break; case "%H":
case "%I":
case "%k":
case "%l":
hr = parseInt(a[i], 10);
break; case "%P":
case "%p":
if (/pm/i.test(a[i]) && hr < 12)
hr += 12;
else if (/am/i.test(a[i]) && hr >= 12)
hr -= 12;
break; case "%M":
min = parseInt(a[i], 10);
break;
}
}
if (isNaN(y)) y = today.getFullYear();
if (isNaN(m)) m = today.getMonth();
if (isNaN(d)) d = today.getDate();
if (isNaN(hr)) hr = today.getHours();
if (isNaN(min)) min = today.getMinutes();
if (y != 0 && m != -1 && d != 0)
return new Date(y, m, d, hr, min, 0);
y = 0; m = -1; d = 0;
for (i = 0; i < a.length; ++i) {
if (a[i].search(/[a-zA-Z]+/) != -1) {
var t = -1;
for (j = 0; j < 12; ++j) {
if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { t = j; break; }
}
if (t != -1) {
if (m != -1) {
d = m+1;
}
m = t;
}
} else if (parseInt(a[i], 10) <= 12 && m == -1) {
m = a[i]-1;
} else if (parseInt(a[i], 10) > 31 && y == 0) {
y = parseInt(a[i], 10);
(y < 100) && (y += (y > 29) ? 1900 : 2000);
} else if (d == 0) {
d = a[i];
}
}
if (y == 0)
y = today.getFullYear();
if (m != -1 && d != 0)
return new Date(y, m, d, hr, min, 0);
return today;
};
Date.prototype.getMonthDays = function(month) {
var year = this.getFullYear();
if (typeof month == "undefined") {
month = this.getMonth();
}
if (((0 == (year%4)) && ( (0 != (year%100)) || (0 == (year%400)))) && month == 1) {
return 29;
} else {
return Date._MD[month];
}
};
Date.prototype.getDayOfYear = function() {
var now = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
var then = new Date(this.getFullYear(), 0, 0, 0, 0, 0);
var time = now - then;
return Math.floor(time / Date.DAY);
};
Date.prototype.getWeekNumber = function() {
var d = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
var DoW = d.getDay();
d.setDate(d.getDate() - (DoW + 6) % 7 + 3);
var ms = d.valueOf();
d.setMonth(0);
d.setDate(4);
return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1;
};
Date.prototype.equalsTo = function(date) {
return ((this.getFullYear() == date.getFullYear()) &&
(this.getMonth() == date.getMonth()) &&
(this.getDate() == date.getDate()) &&
(this.getHours() == date.getHours()) &&
(this.getMinutes() == date.getMinutes()));
};
Date.prototype.setDateOnly = function(date) {
var tmp = new Date(date);
this.setDate(1);
this.setFullYear(tmp.getFullYear());
this.setMonth(tmp.getMonth());
this.setDate(tmp.getDate());
};
Date.prototype.print = function (str) {
var m = this.getMonth();
var d = this.getDate();
var y = this.getFullYear();
var wn = this.getWeekNumber();
var w = this.getDay();
var s = {};
var hr = this.getHours();
var pm = (hr >= 12);
var ir = (pm) ? (hr - 12) : hr;
var dy = this.getDayOfYear();
if (ir == 0)
ir = 12;
var min = this.getMinutes();
var sec = this.getSeconds();
s["%a"] = Calendar._SDN[w];s["%A"] = Calendar._DN[w];s["%b"] = Calendar._SMN[m];s["%B"] = Calendar._MN[m]; s["%C"] = 1 + Math.floor(y / 100);s["%d"] = (d < 10) ? ("0" + d) : d;s["%e"] = d;s["%H"] = (hr < 10) ? ("0" + hr) : hr;s["%I"] = (ir < 10) ? ("0" + ir) : ir;s["%j"] = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy;s["%k"] = hr;
s["%l"] = ir;
s["%m"] = (m < 9) ? ("0" + (1+m)) : (1+m);s["%M"] = (min < 10) ? ("0" + min) : min;s["%n"] = "\n";
s["%p"] = pm ? "PM" : "AM";
s["%P"] = pm ? "pm" : "am";
s["%s"] = Math.floor(this.getTime() / 1000);
s["%S"] = (sec < 10) ? ("0" + sec) : sec;s["%t"] = "\t";s["%U"] = s["%W"] = s["%V"] = (wn < 10) ? ("0" + wn) : wn;
s["%u"] = w + 1;
s["%w"] = w;
s["%y"] = ('' + y).substr(2, 2);s["%Y"] = y;
s["%%"] = "%";
var re = /%./g;
if (!Calendar.is_ie5 && !Calendar.is_khtml)
return str.replace(re, function (par) { return s[par] || par; });var a = str.match(re);
for (var i = 0; i < a.length; i++) {
var tmp = s[a[i]];
if (tmp) {
re = new RegExp(a[i], 'g');
str = str.replace(re, tmp);
}
}return str;
};Date.prototype.__msh_oldSetFullYear = Date.prototype.setFullYear;
Date.prototype.setFullYear = function(y) {
var d = new Date(this);
d.__msh_oldSetFullYear(y);
if (d.getMonth() != this.getMonth())
this.setDate(28);
this.__msh_oldSetFullYear(y);
};window._dynarch_popupCalendar = null;
Calendar._DN = new Array
("星期日","星期一","星期二","星期三","星期四","星期五","星期六","星期日");
Calendar._SDN = new Array
("日","一","二","三","四","五","六","日");
Calendar._FD = 0;
Calendar._MN = new Array
("一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月");
Calendar._SMN = new Array
("一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月");
Calendar._TT = {};
Calendar._TT["INFO"] = "帮助";
Calendar._TT["ABOUT"] =
"选择日期:\n" +
"- 点击 \xab, \xbb 按钮选择年份\n" +
"- 点击 " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " 按钮选择月份\n" +
"- 长按以上按钮可从菜单中快速选择年份或月份";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"选择时间:\n" +
"- 点击小时或分钟可使改数值加一\n" +
"- 按住Shift键点击小时或分钟可使改数值减一\n" +
"- 点击拖动鼠标可进行快速选择";
Calendar._TT["PREV_YEAR"] = "上一年 (按住出菜单)";
Calendar._TT["PREV_MONTH"] = "上一月 (按住出菜单)";
Calendar._TT["GO_TODAY"] = "转到今日";
Calendar._TT["NEXT_MONTH"] = "下一月 (按住出菜单)";
Calendar._TT["NEXT_YEAR"] = "下一年 (按住出菜单)";
Calendar._TT["SEL_DATE"] = "选择日期";
Calendar._TT["DRAG_TO_MOVE"] = "拖动";
Calendar._TT["PART_TODAY"] = " (今日)";
Calendar._TT["DAY_FIRST"] = "最左边显示%s";
Calendar._TT["WEEKEND"] = "0,6";
Calendar._TT["CLOSE"] = "关闭";
Calendar._TT["TODAY"] = "今日";
Calendar._TT["TIME_PART"] = "(Shift-)点击鼠标或拖动改变值";
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%A, %b %e日";
Calendar._TT["WK"] = "周";
Calendar._TT["TIME"] = "时间:";
Calendar.setup = function (params) {
function param_default(pname, def) { if (typeof params[pname] == "undefined") { params[pname] = def; } };
param_default("inputField", null);
param_default("displayArea", null);
param_default("button", null);
param_default("eventName", "click");
param_default("ifFormat", "%Y/%m/%d");
param_default("daFormat", "%Y/%m/%d");
param_default("singleClick", true);
param_default("disableFunc", null);
param_default("dateStatusFunc", params["disableFunc"]); // takes precedence if both are defined
param_default("dateText", null);
param_default("firstDay", null);
param_default("align", "Br");
param_default("range", [1900, 2999]);
param_default("weekNumbers", true);
param_default("flat", null);
param_default("flatCallback", null);
param_default("onSelect", null);
param_default("onClose", null);
param_default("onUpdate", null);
param_default("date", null);
param_default("showsTime", false);
param_default("timeFormat", "24");
param_default("electric", true);
param_default("step", 2);
param_default("position", null);
param_default("cache", false);
param_default("showOthers", false);
param_default("multiple", null);
var tmp = ["inputField", "displayArea", "button"];
for (var i in tmp) {
if (typeof params[tmp[i]] == "string") {
params[tmp[i]] = document.getElementById(params[tmp[i]]);
}
}
if (!(params.flat || params.multiple || params.inputField || params.displayArea || params.button)) {
alert("Calendar.setup:\n Nothing to setup (no fields found). Please check your code");
return false;
}
function onSelect(cal) {
var p = cal.params;
var update = (cal.dateClicked || p.electric);
if (update && p.inputField) {
p.inputField.value = cal.date.print(p.ifFormat);
if (typeof p.inputField.onchange == "function")
p.inputField.onchange();
}
if (update && p.displayArea)
p.displayArea.innerHTML = cal.date.print(p.daFormat);
if (update && typeof p.onUpdate == "function")
p.onUpdate(cal);
if (update && p.flat) {
if (typeof p.flatCallback == "function")
p.flatCallback(cal);
}
if (update && p.singleClick && cal.dateClicked)
cal.callCloseHandler();
};
if (params.flat != null) {
if (typeof params.flat == "string")
params.flat = document.getElementById(params.flat);
if (!params.flat) {
alert("Calendar.setup:\n Flat specified but can't find parent.");
return false;
}
var cal = new Calendar(params.firstDay, params.date, params.onSelect || onSelect);
cal.showsOtherMonths = params.showOthers;
cal.showsTime = params.showsTime;
cal.time24 = (params.timeFormat == "24");
cal.params = params;
cal.weekNumbers = params.weekNumbers;
cal.setRange(params.range[0], params.range[1]);
cal.setDateStatusHandler(params.dateStatusFunc);
cal.getDateText = params.dateText;
if (params.ifFormat) {
cal.setDateFormat(params.ifFormat);
}
if (params.inputField && typeof params.inputField.value == "string") {
cal.parseDate(params.inputField.value);
}
cal.create(params.flat);
cal.show();
return false;
}
var triggerEl = params.button || params.displayArea || params.inputField;
triggerEl["on" + params.eventName] = function() {
var dateEl = params.inputField || params.displayArea;
var dateFmt = params.inputField ? params.ifFormat : params.daFormat;
var mustCreate = false;
var cal = window.calendar;
if (dateEl)
params.date = Date.parseDate(dateEl.value || dateEl.innerHTML, dateFmt);
if (!(cal && params.cache)) {
window.calendar = cal = new Calendar(params.firstDay,
params.date,
params.onSelect || onSelect,
params.onClose || function(cal) { cal.hide(); });
cal.showsTime = params.showsTime;
cal.time24 = (params.timeFormat == "24");
cal.weekNumbers = params.weekNumbers;
mustCreate = true;
} else {
if (params.date)
cal.setDate(params.date);
cal.hide();
}
if (params.multiple) {
cal.multiple = {};
for (var i = params.multiple.length; --i >= 0;) {
var d = params.multiple[i];
var ds = d.print("%Y%m%d");
cal.multiple[ds] = d;
}
}
cal.showsOtherMonths = params.showOthers;
cal.yearStep = params.step;
cal.setRange(params.range[0], params.range[1]);
cal.params = params;
cal.setDateStatusHandler(params.dateStatusFunc);
cal.getDateText = params.dateText;
cal.setDateFormat(dateFmt);
if (mustCreate)
cal.create();
cal.refresh();
if (!params.position)
cal.showAtElement(params.button || params.displayArea || params.inputField, params.align);
else
cal.showAt(params.position[0], params.position[1]);
return false;
};
return cal;
};
|
108wo
|
phpsso_server/statics/js/calendar/calendar.js
|
JavaScript
|
asf20
| 47,290
|
/* The main calendar widget. DIV containing a table. */
div.calendar { position: relative; }
.calendar, .calendar table {
border: 1px solid #b3cbe4;
font-size: 11px;
color: #000;
cursor: default;
background: #F1F8FC;
font-family: tahoma,verdana,sans-serif;
}
.calendar table{border: 1px solid #fff;}
/* Header part -- contains navigation buttons and day names. */
.calendar table thead td{background:#d5e5f6; color:#6993c0; border-bottom:1px solid #fff; border-right:none; height:16px; width:18px}
.calendar table thead tr.headrow td{ background:#e0ecf9}
.headrow{border-top:1px solid #b3cbe4}
.calendar table thead td.button div div{
background-image: url(../../images/admin_img/question-balloon.png);
background-repeat: no-repeat; text-indent:-100px; overflow:hidden
}
.headrow .button { /* "<<", "<", ">", ">>" buttons have this class */
text-align: center; /* They are the navigation buttons */
border-right:1px solid #FFF; padding:0
}
.headrow .button div,.calendar table .wn div{border-right:1px solid #b3cbe4; height:23px; line-height:23px}
.calendar .nav {
}
.calendar thead .title { /* This holds the current "month, year" */
font-weight: bold; /* Pressing it will take you to the current date */
text-align: center;
padding: 2px;
color:#366699; width:auto
}
.calendar thead tr { /* Row <TR> containing navigation buttons */
background: #007ED1;
color: #fff;
}
.calendar thead .daynames { /* Row <TR> containing the day names */
background: #e0ecf9;
}
.calendar thead .name { /* Cells <TD> containing the day names */
border-bottom: 1px solid #b3cbe4;
padding: 2px;
text-align: center;
color: #000;
}
.calendar thead .weekend { /* How a weekend day name shows in header */
color: #a66;
}
.calendar thead .hilite { /* How do the buttons in header appear when hover */
background-color: #d5e5f6;
color: #366699;
}
/* The body part -- contains all the days in month. */
.calendar tbody .day { /* Cells <TD> containing month days dates */
width: 2em;
color: #456;
text-align: right;
padding: 2px 4px 2px 2px;
}
.calendar tbody .day div{ padding-right:5px}
.calendar tbody .day.othermonth {
font-size: 80%;
color: #bbb;
}
.calendar tbody .day.othermonth.oweekend {
color: #fbb;
}
.calendar table .wn {
border-right: 1px solid #fff;
background: #e0ecf9; padding:0
}
.calendar tbody .rowhilite td {
background: #def;
}
.calendar tbody .rowhilite td.wn {
background: #F1F8FC;
}
.calendar tbody td.hilite { /* Hovered cells <TD> */
background: #93b9e2;
padding: 1px 3px 1px 1px;
color:#fff
}
.calendar tbody td.active { /* Active (pressed) cells <TD> */
background: #cde;
padding: 2px 2px 0px 2px;
}
.calendar tbody td.selected { /* Cell showing today date */
font-weight: bold;
padding: 1px 3px 1px 1px;
background: #ff7200;
color: #fff;
}
.calendar tbody td.weekend { /* Cells showing weekend days */
color: #a66;
}
.calendar tbody td.today { /* Cell showing selected date */
font-weight: bold;
color: #D50000;
}
.calendar tbody .disabled { color: #999; }
.calendar tbody .emptycell { /* Empty cells (the best is to hide them) */
visibility: hidden;
}
.calendar tbody .emptyrow { /* Empty row (some months need less than 6 rows) */
display: none;
}
/* The footer part -- status bar and "Close" button */
.calendar tfoot .footrow { /* The <TR> in footer (only one right now) */
text-align: center;
background: #206A9B;
color: #fff;
}
.calendar tfoot .ttip { /* Tooltip (status bar) cell <TD> */
background: #e0ecf9;
color: #366699;
border-top: 1px solid #b3cbe4;
padding: 1px; height:24px
}
.calendar tfoot .hilite { /* Hover style for buttons in footer */
background: #B8DAF0;
border: 1px solid #178AEB;
color: #000;
padding: 1px;
}
.calendar tfoot .active { /* Active (pressed) style for buttons in footer */
background: #006AA9;
padding: 2px 0px 0px 2px;
}
/* Combo boxes (menus that display months/years for direct selection) */
.calendar .combo {
position: absolute;
display: none;
top: 0px;
left: 0px;
width: 4em;
cursor: default;
border: 1px solid #655;
background: #def;
color: #000;
font-size: 90%;
z-index: 9999999999999999999999999999;
}
.calendar .combo .label,
.calendar .combo .label-IEfix {
text-align: center;
padding: 1px;
}
.calendar .combo .label-IEfix {
width: 4em;
}
.calendar .combo .hilite {
background: #34ABFA;
border-top: 1px solid #46a;
border-bottom: 1px solid #46a;
font-weight: bold;
}
.calendar .combo .active {
border-top: 1px solid #46a;
border-bottom: 1px solid #46a;
background: #F1F8FC;
font-weight: bold;
}
.calendar td.time {
border-top: 1px solid #b3cbe4;
padding: 1px 0px;
text-align: center;
background-color: #E3F0F9;
height:24px
}
.calendar td.time .hour,
.calendar td.time .minute,
.calendar td.time .ampm {
padding: 0px 3px 0px 4px;
border: 1px solid #889;
font-weight: bold;
background-color: #F1F8FC;
}
.calendar td.time .ampm {
text-align: center;
}
.calendar td.time .colon {
padding: 0px 2px 0px 3px;
font-weight: bold;
}
.calendar td.time span.hilite {
border-color: #000;
background-color: #267DB7;
color: #fff;
}
.calendar td.time span.active {
border-color: red;
background-color: #000;
color: #A5FF00;
}
.calendar thead .active div{ /* Active (pressed) buttons in header */
background: #bdd2e8;
}
|
108wo
|
phpsso_server/statics/js/calendar/calendar-blue.css
|
CSS
|
asf20
| 5,645
|
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config )
{
// Define changes to default configuration here. For example:
// config.language = 'fr';
// config.uiColor = '#AADC6E';
};
|
108wo
|
phpsso_server/statics/js/ckeditor/config.js
|
JavaScript
|
asf20
| 331
|
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add('uicolor',{requires:['dialog'],lang:['en'],init:function(a){if(CKEDITOR.env.ie6Compat)return;a.addCommand('uicolor',new CKEDITOR.dialogCommand('uicolor'));a.ui.addButton('UIColor',{label:a.lang.uicolor.title,command:'uicolor',icon:this.path+'uicolor.gif'});CKEDITOR.dialog.add('uicolor',this.path+'dialogs/uicolor.js');CKEDITOR.scriptLoader.load(CKEDITOR.getUrl('plugins/uicolor/yui/yui.js'));a.element.getDocument().appendStyleSheet(CKEDITOR.getUrl('plugins/uicolor/yui/assets/yui.css'));}});
|
108wo
|
phpsso_server/statics/js/ckeditor/plugins/uicolor/plugin.js
|
JavaScript
|
asf20
| 670
|
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','en',{uicolor:{title:'UI Color Picker',preview:'Live preview',config:'Paste this string into your config.js file',predefined:'Predefined color sets'}});
|
108wo
|
phpsso_server/statics/js/ckeditor/plugins/uicolor/lang/en.js
|
JavaScript
|
asf20
| 343
|
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
|
108wo
|
phpsso_server/statics/js/ckeditor/plugins/dialog/dialogDefinition.js
|
JavaScript
|
asf20
| 152
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
<!--
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
-->
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function doLoadScript( url )
{
if ( !url )
return false ;
var s = document.createElement( "script" ) ;
s.type = "text/javascript" ;
s.src = url ;
document.getElementsByTagName( "head" )[ 0 ].appendChild( s ) ;
return true ;
}
var opener;
function tryLoad()
{
opener = window.parent;
// get access to global parameters
var oParams = window.opener.oldFramesetPageParams;
// make frameset rows string prepare
var sFramesetRows = ( parseInt( oParams.firstframeh, 10 ) || '30') + ",*," + ( parseInt( oParams.thirdframeh, 10 ) || '150' ) + ',0' ;
document.getElementById( 'itFrameset' ).rows = sFramesetRows ;
// dynamic including init frames and crossdomain transport code
// from config sproxy_js_frameset url
var addScriptUrl = oParams.sproxy_js_frameset ;
doLoadScript( addScriptUrl ) ;
}
</script>
</head>
<frameset id="itFrameset" onload="tryLoad();" border="0" rows="30,*,*,0">
<frame scrolling="no" framespacing="0" frameborder="0" noresize="noresize" marginheight="0" marginwidth="2" src="" name="navbar"></frame>
<frame scrolling="auto" framespacing="0" frameborder="0" noresize="noresize" marginheight="0" marginwidth="0" src="" name="mid"></frame>
<frame scrolling="no" framespacing="0" frameborder="0" noresize="noresize" marginheight="1" marginwidth="1" src="" name="bot"></frame>
<frame scrolling="no" framespacing="0" frameborder="0" noresize="noresize" marginheight="1" marginwidth="1" src="" name="spellsuggestall"></frame>
</frameset>
</html>
|
108wo
|
phpsso_server/statics/js/ckeditor/plugins/wsc/dialogs/tmpFrameset.html
|
HTML
|
asf20
| 1,935
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<!--
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
-->
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function gup( name )
{
name = name.replace( /[\[]/, '\\\[' ).replace( /[\]]/, '\\\]' ) ;
var regexS = '[\\?&]' + name + '=([^&#]*)' ;
var regex = new RegExp( regexS ) ;
var results = regex.exec( window.location.href ) ;
if ( results )
return results[ 1 ] ;
else
return '' ;
}
var interval;
function sendData2Master()
{
var destination = window.parent.parent ;
try
{
if ( destination.XDTMaster )
{
var t = destination.XDTMaster.read( [ gup( 'cmd' ), gup( 'data' ) ] ) ;
window.clearInterval( interval ) ;
}
}
catch (e) {}
}
function onLoad()
{
interval = window.setInterval( sendData2Master, 100 );
}
</script>
</head>
<body onload="onLoad()"><p></p></body>
</html>
|
108wo
|
phpsso_server/statics/js/ckeditor/plugins/wsc/dialogs/ciframe.html
|
HTML
|
asf20
| 1,120
|
var regexEnum =
{
intege:"^-?[1-9]\\d*$", //整数
intege1:"^[1-9]\\d*$", //正整数
intege2:"^-[1-9]\\d*$", //负整数
num:"^([+-]?)\\d*\\.?\\d+$", //数字
num1:"^[1-9]\\d*|0$", //正数(正整数 + 0)
num2:"^-[1-9]\\d*|0$", //负数(负整数 + 0)
decmal:"^([+-]?)\\d*\\.\\d+$", //浮点数
decmal1:"^[1-9]\\d*.\\d*|0.\\d*[1-9]\\d*$", //正浮点数
decmal2:"^-([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*)$", //负浮点数
decmal3:"^-?([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*|0?.0+|0)$", //浮点数
decmal4:"^[1-9]\\d*.\\d*|0.\\d*[1-9]\\d*|0?.0+|0$", //非负浮点数(正浮点数 + 0)
decmal5:"^(-([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*))|0?.0+|0$", //非正浮点数(负浮点数 + 0)
email:"^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$", //邮件
color:"^[a-fA-F0-9]{6}$", //颜色
url:"^http[s]?:\\/\\/([\\w-]+\\.)+[\\w-]+([\\w-./?%&=]*)?$", //url
chinese:"^[\\u4E00-\\u9FA5\\uF900-\\uFA2D]+$", //仅中文
ascii:"^[\\x00-\\xFF]+$", //仅ACSII字符
zipcode:"^\\d{6}$", //邮编
mobile:"^(13|15)[0-9]{9}$", //手机
ip4:"^(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)$", //ip地址
notempty:"^\\S+$", //非空
picture:"(.*)\\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$", //图片
rar:"(.*)\\.(rar|zip|7zip|tgz)$", //压缩文件
date:"^\\d{4}(\\-|\\/|\.)\\d{1,2}\\1\\d{1,2}$", //日期
qq:"^[1-9]*[1-9][0-9]*$", //QQ号码
tel:"^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$", //电话号码的函数(包括验证国内区号,国际区号,分机号)
username:"^\\w+$", //用来用户注册。匹配由数字、26个英文字母或者下划线组成的字符串
letter:"^[A-Za-z]+$", //字母
letter_u:"^[A-Z]+$", //大写字母
letter_l:"^[a-z]+$", //小写字母
idcard:"^[1-9]([0-9]{14}|[0-9]{17})$", //身份证
ps_username:"^[\\u4E00-\\u9FA5\\uF900-\\uFA2D_\\w]+$" //中文、字母、数字 _
}
function isCardID(sId){
var iSum=0 ;
var info="" ;
if(!/^\d{17}(\d|x)$/i.test(sId)) return "你输入的身份证长度或格式错误";
sId=sId.replace(/x$/i,"a");
if(aCity[parseInt(sId.substr(0,2))]==null) return "你的身份证地区非法";
sBirthday=sId.substr(6,4)+"-"+Number(sId.substr(10,2))+"-"+Number(sId.substr(12,2));
var d=new Date(sBirthday.replace(/-/g,"/")) ;
if(sBirthday!=(d.getFullYear()+"-"+ (d.getMonth()+1) + "-" + d.getDate()))return "身份证上的出生日期非法";
for(var i = 17;i>=0;i --) iSum += (Math.pow(2,i) % 11) * parseInt(sId.charAt(17 - i),11) ;
if(iSum%11!=1) return "你输入的身份证号非法";
return true;//aCity[parseInt(sId.substr(0,2))]+","+sBirthday+","+(sId.substr(16,1)%2?"男":"女")
}
//短时间,形如 (13:04:06)
function isTime(str)
{
var a = str.match(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/);
if (a == null) {return false}
if (a[1]>24 || a[3]>60 || a[4]>60)
{
return false;
}
return true;
}
//短日期,形如 (2003-12-05)
function isDate(str)
{
var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
if(r==null)return false;
var d= new Date(r[1], r[3]-1, r[4]);
return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]);
}
//长时间,形如 (2003-12-05 13:04:06)
function isDateTime(str)
{
var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
var r = str.match(reg);
if(r==null) return false;
var d= new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]);
return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]);
}
|
108wo
|
phpsso_server/statics/js/formvalidatorregex.js
|
JavaScript
|
asf20
| 3,840
|
/*! SWFObject v2.2 <http://code.google.com/p/swfobject/>
is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject = function() {
var UNDEF = "undefined",
OBJECT = "object",
SHOCKWAVE_FLASH = "Shockwave Flash",
SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
FLASH_MIME_TYPE = "application/x-shockwave-flash",
EXPRESS_INSTALL_ID = "SWFObjectExprInst",
ON_READY_STATE_CHANGE = "onreadystatechange",
win = window,
doc = document,
nav = navigator,
plugin = false,
domLoadFnArr = [main],
regObjArr = [],
objIdArr = [],
listenersArr = [],
storedAltContent,
storedAltContentId,
storedCallbackFn,
storedCallbackObj,
isDomLoaded = false,
isExpressInstallActive = false,
dynamicStylesheet,
dynamicStylesheetMedia,
autoHideShow = true,
/* Centralized function for browser feature detection
- User agent string detection is only used when no good alternative is possible
- Is executed directly for optimal performance
*/
ua = function() {
var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF,
u = nav.userAgent.toLowerCase(),
p = nav.platform.toLowerCase(),
windows = p ? /win/.test(p) : /win/.test(u),
mac = p ? /mac/.test(p) : /mac/.test(u),
webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html
playerVersion = [0,0,0],
d = null;
if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) {
d = nav.plugins[SHOCKWAVE_FLASH].description;
if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
plugin = true;
ie = false; // cascaded feature detection for Internet Explorer
d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0;
}
}
else if (typeof win.ActiveXObject != UNDEF) {
try {
var a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
if (a) { // a will return null when ActiveX is disabled
d = a.GetVariable("$version");
if (d) {
ie = true; // cascaded feature detection for Internet Explorer
d = d.split(" ")[1].split(",");
playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
}
}
catch(e) {}
}
return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac };
}(),
/* Cross-browser onDomLoad
- Will fire an event as soon as the DOM of a web page is loaded
- Internet Explorer workaround based on Diego Perini's solution: http://javascript.nwbox.com/IEContentLoaded/
- Regular onload serves as fallback
*/
onDomLoad = function() {
if (!ua.w3) { return; }
if ((typeof doc.readyState != UNDEF && doc.readyState == "complete") || (typeof doc.readyState == UNDEF && (doc.getElementsByTagName("body")[0] || doc.body))) { // function is fired after onload, e.g. when script is inserted dynamically
callDomLoadFunctions();
}
if (!isDomLoaded) {
if (typeof doc.addEventListener != UNDEF) {
doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, false);
}
if (ua.ie && ua.win) {
doc.attachEvent(ON_READY_STATE_CHANGE, function() {
if (doc.readyState == "complete") {
doc.detachEvent(ON_READY_STATE_CHANGE, arguments.callee);
callDomLoadFunctions();
}
});
if (win == top) { // if not inside an iframe
(function(){
if (isDomLoaded) { return; }
try {
doc.documentElement.doScroll("left");
}
catch(e) {
setTimeout(arguments.callee, 0);
return;
}
callDomLoadFunctions();
})();
}
}
if (ua.wk) {
(function(){
if (isDomLoaded) { return; }
if (!/loaded|complete/.test(doc.readyState)) {
setTimeout(arguments.callee, 0);
return;
}
callDomLoadFunctions();
})();
}
addLoadEvent(callDomLoadFunctions);
}
}();
function callDomLoadFunctions() {
if (isDomLoaded) { return; }
try { // test if we can really add/remove elements to/from the DOM; we don't want to fire it too early
var t = doc.getElementsByTagName("body")[0].appendChild(createElement("span"));
t.parentNode.removeChild(t);
}
catch (e) { return; }
isDomLoaded = true;
var dl = domLoadFnArr.length;
for (var i = 0; i < dl; i++) {
domLoadFnArr[i]();
}
}
function addDomLoadEvent(fn) {
if (isDomLoaded) {
fn();
}
else {
domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+
}
}
/* Cross-browser onload
- Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/
- Will fire an event as soon as a web page including all of its assets are loaded
*/
function addLoadEvent(fn) {
if (typeof win.addEventListener != UNDEF) {
win.addEventListener("load", fn, false);
}
else if (typeof doc.addEventListener != UNDEF) {
doc.addEventListener("load", fn, false);
}
else if (typeof win.attachEvent != UNDEF) {
addListener(win, "onload", fn);
}
else if (typeof win.onload == "function") {
var fnOld = win.onload;
win.onload = function() {
fnOld();
fn();
};
}
else {
win.onload = fn;
}
}
/* Main function
- Will preferably execute onDomLoad, otherwise onload (as a fallback)
*/
function main() {
if (plugin) {
testPlayerVersion();
}
else {
matchVersions();
}
}
/* Detect the Flash Player version for non-Internet Explorer browsers
- Detecting the plug-in version via the object element is more precise than using the plugins collection item's description:
a. Both release and build numbers can be detected
b. Avoid wrong descriptions by corrupt installers provided by Adobe
c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports
- Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available
*/
function testPlayerVersion() {
var b = doc.getElementsByTagName("body")[0];
var o = createElement(OBJECT);
o.setAttribute("type", FLASH_MIME_TYPE);
var t = b.appendChild(o);
if (t) {
var counter = 0;
(function(){
if (typeof t.GetVariable != UNDEF) {
var d = t.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
}
else if (counter < 10) {
counter++;
setTimeout(arguments.callee, 10);
return;
}
b.removeChild(o);
t = null;
matchVersions();
})();
}
else {
matchVersions();
}
}
/* Perform Flash Player and SWF version matching; static publishing only
*/
function matchVersions() {
var rl = regObjArr.length;
if (rl > 0) {
for (var i = 0; i < rl; i++) { // for each registered object element
var id = regObjArr[i].id;
var cb = regObjArr[i].callbackFn;
var cbObj = {success:false, id:id};
if (ua.pv[0] > 0) {
var obj = getElementById(id);
if (obj) {
if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match!
setVisibility(id, true);
if (cb) {
cbObj.success = true;
cbObj.ref = getObjectById(id);
cb(cbObj);
}
}
else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported
var att = {};
att.data = regObjArr[i].expressInstall;
att.width = obj.getAttribute("width") || "0";
att.height = obj.getAttribute("height") || "0";
if (obj.getAttribute("class")) { att.styleclass = obj.getAttribute("class"); }
if (obj.getAttribute("align")) { att.align = obj.getAttribute("align"); }
// parse HTML object param element's name-value pairs
var par = {};
var p = obj.getElementsByTagName("param");
var pl = p.length;
for (var j = 0; j < pl; j++) {
if (p[j].getAttribute("name").toLowerCase() != "movie") {
par[p[j].getAttribute("name")] = p[j].getAttribute("value");
}
}
showExpressInstall(att, par, id, cb);
}
else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF
displayAltContent(obj);
if (cb) { cb(cbObj); }
}
}
}
else { // if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content)
setVisibility(id, true);
if (cb) {
var o = getObjectById(id); // test whether there is an HTML object element or not
if (o && typeof o.SetVariable != UNDEF) {
cbObj.success = true;
cbObj.ref = o;
}
cb(cbObj);
}
}
}
}
}
function getObjectById(objectIdStr) {
var r = null;
var o = getElementById(objectIdStr);
if (o && o.nodeName == "OBJECT") {
if (typeof o.SetVariable != UNDEF) {
r = o;
}
else {
var n = o.getElementsByTagName(OBJECT)[0];
if (n) {
r = n;
}
}
}
return r;
}
/* Requirements for Adobe Express Install
- only one instance can be active at a time
- fp 6.0.65 or higher
- Win/Mac OS only
- no Webkit engines older than version 312
*/
function canExpressInstall() {
return !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac) && !(ua.wk && ua.wk < 312);
}
/* Show the Adobe Express Install dialog
- Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75
*/
function showExpressInstall(att, par, replaceElemIdStr, callbackFn) {
isExpressInstallActive = true;
storedCallbackFn = callbackFn || null;
storedCallbackObj = {success:false, id:replaceElemIdStr};
var obj = getElementById(replaceElemIdStr);
if (obj) {
if (obj.nodeName == "OBJECT") { // static publishing
storedAltContent = abstractAltContent(obj);
storedAltContentId = null;
}
else { // dynamic publishing
storedAltContent = obj;
storedAltContentId = replaceElemIdStr;
}
att.id = EXPRESS_INSTALL_ID;
if (typeof att.width == UNDEF || (!/%$/.test(att.width) && parseInt(att.width, 10) < 310)) { att.width = "310"; }
if (typeof att.height == UNDEF || (!/%$/.test(att.height) && parseInt(att.height, 10) < 137)) { att.height = "137"; }
doc.title = doc.title.slice(0, 47) + " - Flash Player Installation";
var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn",
fv = "MMredirectURL=" + win.location.toString().replace(/&/g,"%26") + "&MMplayerType=" + pt + "&MMdoctitle=" + doc.title;
if (typeof par.flashvars != UNDEF) {
par.flashvars += "&" + fv;
}
else {
par.flashvars = fv;
}
// IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it,
// because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
if (ua.ie && ua.win && obj.readyState != 4) {
var newObj = createElement("div");
replaceElemIdStr += "SWFObjectNew";
newObj.setAttribute("id", replaceElemIdStr);
obj.parentNode.insertBefore(newObj, obj); // insert placeholder div that will be replaced by the object element that loads expressinstall.swf
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
obj.parentNode.removeChild(obj);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
createSWF(att, par, replaceElemIdStr);
}
}
/* Functions to abstract and display alternative content
*/
function displayAltContent(obj) {
if (ua.ie && ua.win && obj.readyState != 4) {
// IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it,
// because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
var el = createElement("div");
obj.parentNode.insertBefore(el, obj); // insert placeholder div that will be replaced by the alternative content
el.parentNode.replaceChild(abstractAltContent(obj), el);
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
obj.parentNode.removeChild(obj);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
else {
obj.parentNode.replaceChild(abstractAltContent(obj), obj);
}
}
function abstractAltContent(obj) {
var ac = createElement("div");
if (ua.win && ua.ie) {
ac.innerHTML = obj.innerHTML;
}
else {
var nestedObj = obj.getElementsByTagName(OBJECT)[0];
if (nestedObj) {
var c = nestedObj.childNodes;
if (c) {
var cl = c.length;
for (var i = 0; i < cl; i++) {
if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) {
ac.appendChild(c[i].cloneNode(true));
}
}
}
}
}
return ac;
}
/* Cross-browser dynamic SWF creation
*/
function createSWF(attObj, parObj, id) {
var r, el = getElementById(id);
if (ua.wk && ua.wk < 312) { return r; }
if (el) {
if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content
attObj.id = id;
}
if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML
var att = "";
for (var i in attObj) {
if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries
if (i.toLowerCase() == "data") {
parObj.movie = attObj[i];
}
else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
att += ' class="' + attObj[i] + '"';
}
else if (i.toLowerCase() != "classid") {
att += ' ' + i + '="' + attObj[i] + '"';
}
}
}
var par = "";
for (var j in parObj) {
if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries
par += '<param name="' + j + '" value="' + parObj[j] + '" />';
}
}
el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';
objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only)
r = getElementById(attObj.id);
}
else { // well-behaving browsers
var o = createElement(OBJECT);
o.setAttribute("type", FLASH_MIME_TYPE);
for (var m in attObj) {
if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries
if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
o.setAttribute("class", attObj[m]);
}
else if (m.toLowerCase() != "classid") { // filter out IE specific attribute
o.setAttribute(m, attObj[m]);
}
}
}
for (var n in parObj) {
if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element
createObjParam(o, n, parObj[n]);
}
}
el.parentNode.replaceChild(o, el);
r = o;
}
}
return r;
}
function createObjParam(el, pName, pValue) {
var p = createElement("param");
p.setAttribute("name", pName);
p.setAttribute("value", pValue);
el.appendChild(p);
}
/* Cross-browser SWF removal
- Especially needed to safely and completely remove a SWF in Internet Explorer
*/
function removeSWF(id) {
var obj = getElementById(id);
if (obj && obj.nodeName == "OBJECT") {
if (ua.ie && ua.win) {
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
removeObjectInIE(id);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
else {
obj.parentNode.removeChild(obj);
}
}
}
function removeObjectInIE(id) {
var obj = getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
/* Functions to optimize JavaScript compression
*/
function getElementById(id) {
var el = null;
try {
el = doc.getElementById(id);
}
catch (e) {}
return el;
}
function createElement(el) {
return doc.createElement(el);
}
/* Updated attachEvent function for Internet Explorer
- Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks
*/
function addListener(target, eventType, fn) {
target.attachEvent(eventType, fn);
listenersArr[listenersArr.length] = [target, eventType, fn];
}
/* Flash Player and SWF content version matching
*/
function hasPlayerVersion(rv) {
var pv = ua.pv, v = rv.split(".");
v[0] = parseInt(v[0], 10);
v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0"
v[2] = parseInt(v[2], 10) || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
}
/* Cross-browser dynamic CSS creation
- Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php
*/
function createCSS(sel, decl, media, newStyle) {
if (ua.ie && ua.mac) { return; }
var h = doc.getElementsByTagName("head")[0];
if (!h) { return; } // to also support badly authored HTML pages that lack a head element
var m = (media && typeof media == "string") ? media : "screen";
if (newStyle) {
dynamicStylesheet = null;
dynamicStylesheetMedia = null;
}
if (!dynamicStylesheet || dynamicStylesheetMedia != m) {
// create dynamic stylesheet + get a global reference to it
var s = createElement("style");
s.setAttribute("type", "text/css");
s.setAttribute("media", m);
dynamicStylesheet = h.appendChild(s);
if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) {
dynamicStylesheet = doc.styleSheets[doc.styleSheets.length - 1];
}
dynamicStylesheetMedia = m;
}
// add style rule
if (ua.ie && ua.win) {
if (dynamicStylesheet && typeof dynamicStylesheet.addRule == OBJECT) {
dynamicStylesheet.addRule(sel, decl);
}
}
else {
if (dynamicStylesheet && typeof doc.createTextNode != UNDEF) {
dynamicStylesheet.appendChild(doc.createTextNode(sel + " {" + decl + "}"));
}
}
}
function setVisibility(id, isVisible) {
if (!autoHideShow) { return; }
var v = isVisible ? "visible" : "hidden";
if (isDomLoaded && getElementById(id)) {
getElementById(id).style.visibility = v;
}
else {
createCSS("#" + id, "visibility:" + v);
}
}
/* Filter to avoid XSS attacks
*/
function urlEncodeIfNecessary(s) {
var regex = /[\\\"<>\.;]/;
var hasBadChars = regex.exec(s) != null;
return hasBadChars && typeof encodeURIComponent != UNDEF ? encodeURIComponent(s) : s;
}
/* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only)
*/
var cleanup = function() {
if (ua.ie && ua.win) {
window.attachEvent("onunload", function() {
// remove listeners to avoid memory leaks
var ll = listenersArr.length;
for (var i = 0; i < ll; i++) {
listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]);
}
// cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect
var il = objIdArr.length;
for (var j = 0; j < il; j++) {
removeSWF(objIdArr[j]);
}
// cleanup library's main closures to avoid memory leaks
for (var k in ua) {
ua[k] = null;
}
ua = null;
for (var l in swfobject) {
swfobject[l] = null;
}
swfobject = null;
});
}
}();
return {
/* Public API
- Reference: http://code.google.com/p/swfobject/wiki/documentation
*/
registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr, callbackFn) {
if (ua.w3 && objectIdStr && swfVersionStr) {
var regObj = {};
regObj.id = objectIdStr;
regObj.swfVersion = swfVersionStr;
regObj.expressInstall = xiSwfUrlStr;
regObj.callbackFn = callbackFn;
regObjArr[regObjArr.length] = regObj;
setVisibility(objectIdStr, false);
}
else if (callbackFn) {
callbackFn({success:false, id:objectIdStr});
}
},
getObjectById: function(objectIdStr) {
if (ua.w3) {
return getObjectById(objectIdStr);
}
},
embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) {
var callbackObj = {success:false, id:replaceElemIdStr};
if (ua.w3 && !(ua.wk && ua.wk < 312) && swfUrlStr && replaceElemIdStr && widthStr && heightStr && swfVersionStr) {
setVisibility(replaceElemIdStr, false);
addDomLoadEvent(function() {
widthStr += ""; // auto-convert to string
heightStr += "";
var att = {};
if (attObj && typeof attObj === OBJECT) {
for (var i in attObj) { // copy object to avoid the use of references, because web authors often reuse attObj for multiple SWFs
att[i] = attObj[i];
}
}
att.data = swfUrlStr;
att.width = widthStr;
att.height = heightStr;
var par = {};
if (parObj && typeof parObj === OBJECT) {
for (var j in parObj) { // copy object to avoid the use of references, because web authors often reuse parObj for multiple SWFs
par[j] = parObj[j];
}
}
if (flashvarsObj && typeof flashvarsObj === OBJECT) {
for (var k in flashvarsObj) { // copy object to avoid the use of references, because web authors often reuse flashvarsObj for multiple SWFs
if (typeof par.flashvars != UNDEF) {
par.flashvars += "&" + k + "=" + flashvarsObj[k];
}
else {
par.flashvars = k + "=" + flashvarsObj[k];
}
}
}
if (hasPlayerVersion(swfVersionStr)) { // create SWF
var obj = createSWF(att, par, replaceElemIdStr);
if (att.id == replaceElemIdStr) {
setVisibility(replaceElemIdStr, true);
}
callbackObj.success = true;
callbackObj.ref = obj;
}
else if (xiSwfUrlStr && canExpressInstall()) { // show Adobe Express Install
att.data = xiSwfUrlStr;
showExpressInstall(att, par, replaceElemIdStr, callbackFn);
return;
}
else { // show alternative content
setVisibility(replaceElemIdStr, true);
}
if (callbackFn) { callbackFn(callbackObj); }
});
}
else if (callbackFn) { callbackFn(callbackObj); }
},
switchOffAutoHideShow: function() {
autoHideShow = false;
},
ua: ua,
getFlashPlayerVersion: function() {
return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] };
},
hasFlashPlayerVersion: hasPlayerVersion,
createSWF: function(attObj, parObj, replaceElemIdStr) {
if (ua.w3) {
return createSWF(attObj, parObj, replaceElemIdStr);
}
else {
return undefined;
}
},
showExpressInstall: function(att, par, replaceElemIdStr, callbackFn) {
if (ua.w3 && canExpressInstall()) {
showExpressInstall(att, par, replaceElemIdStr, callbackFn);
}
},
removeSWF: function(objElemIdStr) {
if (ua.w3) {
removeSWF(objElemIdStr);
}
},
createCSS: function(selStr, declStr, mediaStr, newStyleBoolean) {
if (ua.w3) {
createCSS(selStr, declStr, mediaStr, newStyleBoolean);
}
},
addDomLoadEvent: addDomLoadEvent,
addLoadEvent: addLoadEvent,
getQueryParamValue: function(param) {
var q = doc.location.search || doc.location.hash;
if (q) {
if (/\?/.test(q)) { q = q.split("?")[1]; } // strip question mark
if (param == null) {
return urlEncodeIfNecessary(q);
}
var pairs = q.split("&");
for (var i = 0; i < pairs.length; i++) {
if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1)));
}
}
}
return "";
},
// For internal usage only
expressInstallCallback: function() {
if (isExpressInstallActive) {
var obj = getElementById(EXPRESS_INSTALL_ID);
if (obj && storedAltContent) {
obj.parentNode.replaceChild(storedAltContent, obj);
if (storedAltContentId) {
setVisibility(storedAltContentId, true);
if (ua.ie && ua.win) { storedAltContent.style.display = "block"; }
}
if (storedCallbackFn) { storedCallbackFn(storedCallbackObj); }
}
isExpressInstallActive = false;
}
}
};
}();
|
108wo
|
phpsso_server/statics/js/swfobject.js
|
JavaScript
|
asf20
| 25,560
|
/* 2010-06-01 */
.ui_title_wrap, .ui_bottom button { font-size:12px 'Microsoft Yahei', Arial; }
.ui_content_wrap { min-width:9em; }/*设置对话框最小尺寸*/
.ui_overlay div { background:#000; filter:alpha(opacity=70); opacity:0.7; }/*设置遮罩颜色与透明度*/
.ui_loading_tip { width:16px; height:16px; margin:-8px 0 0 -8px; text-indent:-9999em; background:url(../images/msg_img/loading.gif) no-repeat center center; }/*iframe加载的loading动画*/
.ui_dialog_main { background:#FFF; }
.ui_title_wrap { _width:100px; }/*IE6下设置一个最小长度,防止关闭按钮错位*/
.ui_title { width:100%; height:26px; position:absolute; top:0; left:0; _left:auto; }
.ui_title_text { height:26px; line-height:25px; padding:0 60px 0 12px; _padding:0 90px 0 6px; color:#FFF; font-weight:700; text-shadow:0 1px 0 #000; }
.ui_td_00, .ui_td_02, .ui_td_10, .ui_td_12, .ui_td_20, .ui_td_22, .ui_close { background-image:url(../images/msg_img/chrome_s.png); background-repeat:no-repeat;}
.ui_td_00 { width:5px; height:26px; background-position: -46px -9px; }/*左上*/
.ui_td_02 { width:5px; height:26px; background-position: -53px -9px; }/*右上*/
.ui_td_10 { background-position:-62px 0; background-repeat:repeat-y; }/*左边*/
.ui_td_12 { background-position:-66px 0; background-repeat:repeat-y; }/*右边*/
.ui_td_20 { width:5px; height:5px; background-position: -46px -1px;}/*左下*/
.ui_td_22 { width:5px; height:5px; background-position: -53px -1px;}/*右下*/
.ui_close { top:4px; right:6px; _right:3px; width:18px; height:18px; background-position:0 0; _font-size:0; _line-height:0; text-indent:-9999em; }
.ui_close:hover { background-position:0 -19px; }
.ui_td_01, .ui_td_21 { background-image:url(../images/msg_img/border.png); background-repeat:repeat-x; }
.ui_td_01 { background-position:0 top; }
.ui_td_21 { background: none #FFF; border-bottom:1px solid #6296cf}
.ui_btns { background-color:#F6F6F6; border-top:solid 1px #DADEE5; }
.ui_btns span, .ui_btns button { background-color:transparent; background-image:url(../images/msg_img/btns.png); background-repeat:no-repeat; }
.ui_btns span { padding:0 0 0 5px; overflow:hidden; background-position:left -42px; }
.ui_btns button { height:21px; line-height:21px; padding:0 10px 0 5px; max-width:200px; border:none 0; background-position:right 0; }
.ui_btns span:hover { background-position:left -63px; }
.ui_btns span:hover button { background-position:right -21px; }
.ui_resize { width:10px; height:10px; }
html:hover .ui_btns button:focus { outline:none 0; }
.ui_move_temp div { background-color:#214FA3; filter:alpha(opacity=40); opacity:0.4; }/*拖动用的替身对话框*/
/*
主题拓展参数[可添加组合在'style'参数中]
可用来支持消息类型图标等
*/
.ui_dialog_icon { display:inline-block; *zoom:1; *display:inline; background-image:url(../images/msg_img/icons.png); background-repeat:no-repeat; }
/*警告消息*/
.alert .ui_dialog_icon { margin-right:10px; width:48px; height:48px; background-position:0 -96px; }
/*询问消息*/
.confirm .ui_dialog_icon { margin-right:10px; width:48px; height:48px; background-position:0 -144px; }
/*错误消息*/
.error .ui_dialog_icon { margin-right:10px; width:48px; height:48px; background-position:0 -48px; }
/*成功消息*/
.succeed .ui_dialog_icon { margin-right:10px; width:48px; height:48px; background-position:0 0; }
/*去除所有背景*/
.noSkin .ui_border, .noSkin .ui_title_wrap, .noSkin .ui_dialog_icon { display:none; }
.noSkin .ui_bottom_wrap { display:none; *display:block; *height:0; overflow:hidden; }
* html .noSkin .ui_btns { height:0; overflow:hidden; position:absolute; left:-99999em; }
.noSkin .ui_content { margin:0; }
.noSkin .ui_dialog_main { background:transparent; }
/*警告消息*/
.gb_tip_layer,
.gb_tip_layer .gtl_ico_succ,
.gb_tip_layer .gtl_ico_fail,
.gb_tip_layer .gtl_ico_hits,
.gb_tip_layer .gtl_ico_clear,
.gb_tip_layer .gtl_end{float: left;height:54px;line-height:54px;font-weight:bold;font-size:14px;color:#606060;background-image:url("../images/gb_tip_layer.png");_background-image:url("../images/gb_tip_layer_ie6.png");background-repeat:no-repeat;}
.gb_tip_layer{background-position:0 -161px;background-repeat:repeat-x;left:50%;position:absolute;top:40%;padding:0 18px 0 9px; margin-left:-130px}
.gb_tip_layer .gtl_ico_succ{background-position:-6px 0;left:-45px;top:0;width:45px;position:absolute;}
.gb_tip_layer .gtl_end{background-position:0 0;position:absolute;right:-6px;top:0;width:6px;}
.gb_tip_layer .gtl_ico_fail{background-position:-6px -108px;position:absolute;left:-45px;top:0;width:45px;}
.gb_tip_layer .gtl_ico_hits{background-position:-6px -54px;position:absolute;left:-45px;top:0;width:45px;}
.gb_tip_layer .gtl_ico_clear{background-position:-6px 0;left:-5px;width:5px;position:absolute;top:0;}
.gb_tip_layer img{float:left;margin:19px 10px 0 5px ;}
|
108wo
|
phpsso_server/statics/css/dialog.css
|
CSS
|
asf20
| 4,917
|
/*数据列表*/
.table-list td,.table-list th{padding-left:12px}
.table-list thead th{ height:30px; background:#eef3f7; border-bottom:1px solid #d5dfe8; font-weight:normal}
.table-list tbody td,.table-list .btn{border-bottom: #eee 1px solid; height:28px;}
.table-list .btn{background:#f6f6f6; padding:6px 0 0 12px; height:30px;}
.table-list tr:hover,.table-list table tbody tr:hover{ background:#fbffe4}
.table-list .input-text-c{ padding:0; height:18px}
.input-text-c{border:1px solid #A7A6AA;height:18px;padding:2px 0 0; text-align:center}
.td-line{border:1px solid #eee}
.td-line td,.td-line th{border-right:1px solid #eee}
/*通用表单*/
.common-form{}
.common-form div.contentWrap{padding-right:20px}
.common-form ul li{color:#444; clear:both; vertical-align:middle}
.common-form ul li span.text{width:60px}
.common-form .set{border:1px dashed #e0e7ed;zoom:1; background:#f2f7fb; padding:10px; font-size:12px; margin-bottom:10px}
.common-form .set table td,.common-form .set table th{padding-left:12px}
.common-form .set table th{font-weight:normal; text-align:left;padding:0 8px}
.common-form .set table td{ padding:3px 0 3px 5px}
.common-form .set table td.y-bg{background: url(../images/admin_img/set_y_line.png) repeat-y right top}
.common-form .set table td input{ background-image:none; height:18px; font-size:12px}
.input-text,input.date,textarea{border:1px solid #A7A6AA;height:18px;margin:0 5px 0 0;padding:2px 0 2px 5px;border: 1px solid #d0d0d0;background: #FFF url(../images/admin_img/input.png) repeat-x}
input.date,input.endDate{background: #fff url(../images/admin_img/input_date.png) no-repeat right 3px; padding-right:18px}
textarea{height:auto; padding:0; margin:0}
select{ vertical-align:middle;background:none repeat scroll 0 0 #F9F9F9;border-color:#666666 #CCCCCC #CCCCCC #666666;border-style:solid;border-width:1px;color:#333;padding:2px;}
.search-form{ margin-bottom:10px}
/*表格表单*/
.table_form input{}
.table_form td,.table_form th{padding-left:12px}
.table_form th{font-weight:normal; text-align:left;}
.table_form td label{ vertical-align:middle}
.table_form td,.table_form th{padding:8px 0 8px 8px}
.table_form tbody td,.table_form tbody th{border-bottom:1px solid #eee; }
.colorpanel tbody td,.colorpanel tbody th{ padding:0;border-bottom: none;}
/*select美化*/
:focus {outline:none;}
.js ul.newList {left:-9999px;}
ul.newList * {margin:0; padding:0;}
ul.newList {margin:0; padding:0; list-style:none; color:#000; background:#fff; position:absolute; border:1px solid #ccc; top:22px; left:0; overflow:auto; z-index:9999;}
.newListSelected {color:#000; height:22px; padding:4px 0 0 6px; float:left; background:url(../images/select-bg.png) no-repeat right 0; border-left:1px solid #dfdfdf}
.newListSelected span {display:block;}
ul.newList li a {padding:3px 8px;display:block;text-decoration: none;}
.selectedTxt {overflow:hidden; height:16px; padding:0 23px 0 0;}
.measure-input {background:url("../images/ruler.gif") repeat-x scroll 0 9px transparent}
.hiLite {background:#e0ebf4!important; color:#444!important;}
.newListHover {background:#f2f7fb!important; color:#000!important; cursor:default;}
.newListSelHover, .newListSelFocus {background-position:right -26px; cursor:default;}
.newListOptionTitle {font-weight:bold;}
.newListOptionTitle ul {margin:3px 0 0;}
.newListOptionTitle li {font-weight:normal; border-left:1px solid #ccc;}
/*表单验证*/
.onShow,.onFocus,.onError,.onCorrect,.onLoad{display:inline-block;display:-moz-inline-stack;zoom:1;*display:inline; vertical-align:middle;background:url(../images/msg_bg.png) no-repeat; color:#444;line-height:18px;padding:2px 10px 2px 23px; margin-left:10px;_margin-left:5px}
.onShow{background-position:3px -147px;border-color:#40B3FF;color:#959595}
.onFocus{background-position:3px -147px;border-color:#40B3FF;}
.onError{background-position:3px -47px;border-color:#40B3FF; color:red}
.onCorrect{background-position:3px -247px;border-color:#40B3FF;}
|
108wo
|
phpsso_server/statics/css/table_form.css
|
CSS
|
asf20
| 4,007
|
body{color:#666}
a{text-decoration:none; color:#666}
a:hover{text-decoration:underline;}
.pad_10{padding:10px}.pad-lr-6{padding:0 6px}
.pad-6{padding:6px; overflow:hidden}.pad-10{padding:10px; overflow:hidden}.pad-lr-10{padding:0 10px}
.white,.white a{color:#fff}
.blue,.blue a{color:#377abe}
.cut_line span{ color:#4d82bc; padding:0 8px}
.mr6{margin-right:6px}.mr8{margin-right:8px}.mr10{margin-right:10px}
.content-on{background: #e2e9ea url(../images/left_bg.png) repeat-y left top;overflow:hidden}
.content-off{background-image:none; overflow:hidden}
.button{background:#ddd;height:24px; border-top:0;border-left:0; border-bottom:1px solid #666; border-right:1px solid #666; padding:3px 6px; margin-right:5px}
.subnav{ padding:10px}
.subnav h2{ margin-bottom:6px}
/*提示框*/
.msg .error, .msg .stop, .msg .alert, .msg .attention, .msg .tips, .msg .ok, .msg .notice, .msg .question, .msg .help, .msg .small-help {
background:url("../images/msg_bg.png") no-repeat scroll 0 0 transparent;border:1px solid #DDD;color:#444;float:left;line-height:18px;
padding:2px 10px 2px 23px;}
.msg .attention {
background-color:#E5F5FF;
background-position:3px -147px;
border-color:#40B3FF; float:left
}
/*头部*/
.header .nav li.tab_web a span,.crumbs,.tab-web-panel li a{background: url(../images/icon_use.png) no-repeat}
.header {background:#3a6ea5 url(../images/h_bg.gif) repeat-x left bottom; height:80px}
.header .logo{float:left;width:176px;height:80px;margin-right:10px;_margin-right:7px;background: url(../images/logo_1.gif) no-repeat;}
.header .rt{float:right;width:230px}
.header .col-auto{height:80px}
.header .log{padding:16px 0 0 6px; height:20px}
.header .tab_style{padding:16px 14px 0 0}
#Skin{padding:14px 0 0 0}
#Skin li {cursor:pointer;float:right;height:11px;width:14px;background:url(../images/skinbt.png) no-repeat}
#Skin .s1 {background-position:-14px -66px}
#Skin .s2 {background-position:0 -55px}
#Skin .s3 {background-position:0 -33px}
#Skin .s4 {}
/*主体样式*/
.left_menu{ margin-right:10px}
.left_menu{padding:12px;_padding:12px 0 12px 12px;width:150px; position:relative; display:block}
.left_menu_on{ width:0; padding:0;}
.left_menu_on div{ visibility:hidden}
.left_menu h3{font-weight: 700;color: #275d96;border-bottom:1px solid #d9e4ea; line-height:24px;height:24px; }
.left_menu div.line-x{border-bottom:1px solid #d9e4ea; height:1px; font-size:1px;}
.left_menu ul{ padding:5px 0}
.left_menu ul li{width:160px; margin-right:4px;color:#666; line-height:24px; height:24px}
.left_menu ul li a{padding-left:8px; display:block;background-color:#F7FBFC; line-height:29px; height:29px;text-decoration: none;}
.left_menu ul li a:hover,
.left_menu ul li.on{background: url(../images/left_menu.png) no-repeat;text-decoration: none}
.left_menu ul li.on{width:140px;height:29px; padding-left:24px; line-height:29px; margin:3px 0 2px}
.left_menu ul li a:hover{background-position: left -36px;}
.left_menu ul li.on a{ height:29px; background:none; padding:0;_width:100px;}
.left_menu ul li.on a:hover{background:none}
.left_menu a.open,.left_menu a.close{background: url(../images/left_menu_openClose.png) no-repeat 3px center;width:10px; display:block; position:absolute; z-index:100; height:auto; right:-11px; top:0}
.left_menu a.open:hover,.left_menu a.close:hover{ background-color:#d6e1e4}
.left_menu a.close{background-position:right center}
/*当前位置*/
.crumbs{background-position:left -18px; height:22px; padding:6px 0 0 18px;*height:20px;*padding:8px 0 0 18px;}
/*容器1 蓝白色边框*/
.col-1{ border:1px solid #f4f6f5;zoom:1; background:#fff}
.col-1 div.content{border:1px solid #c2d1d8;zoom:1;}
/*栏目菜单*/
.cat-menu{ width:180px; margin:10px 10px 0 0}
/*收藏导航*/
.fav-nav{height:28px;line-height:28px;position:fixed;bottom:0px;width:100%;background: url(../images/fav-nav-bg.png) repeat-x left top;padding:0 0 0 12px}
/*内容菜单*/
.content-menu{ padding-bottom:6px}
.content-menu a.add,.content-menu a.add em,
.content-menu a.on,.content-menu a.on em{background: url(../images/bnt_bg.png) no-repeat;height:28px; line-height:26px;*line-height:28px}
.content-menu span{color:#ddd; padding:0 8px}
.content-menu a{cursor:pointer;}
.content-menu a em{display:inline-block;display:-moz-inline-stack;zoom:1;*display:inline;}
.content-menu a.add{ padding:0 0 0 5px;}
.content-menu a.add em{ padding:0 10px 0 5px;color:#fff;background-position: right top}
.content-menu a.on{background-position: left -40px;*background-position: left -41px; color:#fff; padding:0 0 0 5px}
.content-menu a.on em{background-position: right -40px;*background-position: right -41px; padding:0 10px 0 5px}
/*标题*/
.line-x{border-bottom:1px solid #eee;}
.title-1{border-bottom:1px solid #eee; padding-left:5px}
.title-2{text-align:left;height:34px;*height:33px;font:18px/31px "MicroSoft YaHei","SimHei";color:#333;*line-height:33px; margin:0; padding:8px 0 3px 20px}
/*数据列表*/
.table-list thead th{ height:30px; background:#eef3f7; border-bottom:1px solid #d5dfe8; font-weight:normal}
.table-list tbody td,.table-list .btn{border-bottom: #eee 1px solid; height:28px;border-collapse:show }
.table-list .btn{background:#f6f6f6; padding:6px 0 0 12px; height:30px;}
.table-list .wrap tr:hover{ background:#fbffe4}
/*通用表单*/
.common-form{padding-left:20px}
.common-form ul.content{ padding-right:20px}
.common-form ul li{color:#444; clear:both;}
.common-form ul li label{display:block; float:left; padding-right:8px}
.common-form ul li label.f1{display:block;float:left;font-size:12px;*padding:4px 0 0; line-height:24px}
.common-form .set{border:1px dashed #e0e7ed;zoom:1; background:#f2f7fb; padding:10px; font-size:12px; margin-bottom:10px}
.common-form .set table th{font-weight:normal; text-align:left; width:60px}
.common-form .set table td{ padding:3px 0}
.common-form .set table td.y-bg{background: url(../images/set_y_line.png) repeat-y right top}
.common-form .set table td input{ background-image:none; height:18px; font-size:12px}
.input-text{border:1px solid #A7A6AA;font-size:14px;height:20px;margin:0 5px 0 0;padding:2px;border: 1px solid #d0d0d0;background: #FFF url(../images/input.png) repeat-x}
/*分页*/
#pages { padding:14px 0; text-align: right; font-family:宋体 }
#pages a { display:inline-block; width:26px; height:22px; line-height:22px; background:#fff; border:1px solid #e3e3e3; text-align:center; color:#333}
#pages a.a1 { background:url(../images/pages.png) no-repeat 0 5px; width:56px; }
#pages a:hover { background:#f1f1f1; color:#000; text-decoration:none; }
#pages span { display:inline-block; width:26px; height:22px; line-height:22px; background:#5a85b2; border:1px solid #5a85b2; color:#fff; text-align:center; }
.page .noPage { display:inline-block; width:56px; height:22px; line-height:22px; background:url(../img/icu/titleBg.png) repeat-x 0 -55px ; border:1px solid #e3e3e3; text-align:center; color:#a4a4a4; }
|
108wo
|
phpsso_server/statics/css/system.css
|
CSS
|
asf20
| 7,011
|
body,h1,h2,h3,h4,h5,h6,hr,p,blockquote,dl,dt,dd,ul,ol,li,pre,form,fieldset,legend,button,input,textarea,th,td{margin:0;padding:0;word-wrap:break-word}
body,button,input,select,textarea{font:12px/1.5 tahoma,arial,\5b8b\4f53,sans-serif;}
table{border-collapse:collapse;border-spacing:0;}td,th{padding-left:12px}img{border:none}
h1,h2,h3,h4,h5,h6{font-size:100%;}
h1{font-size:34px;}h2{font-size:26px;}h3{font-size:18px; }h4{font-size:16px;}h5{font-size:14px;}h6{font-size:12px;}
input,label,img,td,th{vertical-align:middle;}
address,cite,dfn,em,var{font-style:normal;}
code,kbd,pre,samp{font-family:courier new,courier,monospace;}
ul,ol,li{list-style:none;}
a{text-decoration:none;}
a:hover{text-decoration:underline;}
.hidden{display:none;}.invisible{visibility:hidden;}
.clear:after{content:'\20';display:block;height:0;clear:both;}.clear{_zoom:1;}
.f12{font-size: 12px}.f14{font-size: 14px}.f16{font-size: 16px}.f18{font-size:18px}.f20{font-size:20px}
.lh20{line-height: 20px}.lh22{line-height: 22px}.lh24{line-height: 24px}.lh26{line-height: 26px}.lh28{line-height: 28px}
.fb{ font-weight:bold}.fn{ font-weight:normal}
.bk,.bk3,.bk6,.bk8,.bk10,.bk15,.bk20,.bk30{clear: both;font-size: 1px;height: 0;line-height: 1px}
.bk3{height: 3px;}.bk6{height: 6px}.bk8{height: 8px}.bk10{height: 10px}.bk15{height: 15px}.bk20{height: 20px}.bk30{height: 30px}
.cu,.cu-li li,.cu-span span {cursor: hand;!important;cursor: pointer}
.ib, .ib-li li, .ib-a a {display:inline-block;display:-moz-inline-stack;zoom:1;*display:inline;}
.text-c{text-align: center}.text-l{text-align: left}.text-r{text-align: right}
.lf{float: left}.rt{float: right}.pr{ position:relative}.pa{ position:absolute}
.m-auto{margin: 0 auto}
.col-left{float:left}
.col-auto{overflow:hidden;_zoom:1;_float:left;}
.col-right{float:right}
|
108wo
|
phpsso_server/statics/css/reset.css
|
CSS
|
asf20
| 1,816
|
/* 全局样式 */
*{margin:0;padding:0;border:0;}
body{background:#3a6ea5;}
.login_box{width:580px;height:320px;position:absolute;top:50%;left:50%;margin-left:-290px;margin-top:-160px;}
.login_box_top{background:url(../images/login_box_top.gif) no-repeat;width:580px;height:13px;}
.login_box_mid{background:url(../images/login_box_mid.gif) repeat-y;width:580px;height:289px;}
.login_box_bot{background:url(../images/login_box_bot.gif) no-repeat;width:580px;height:13px;}
.login_logo{float:left;display:inline; background:url(../images/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(../images/login_input.gif) no-repeat;width:178px;height:19px;border:1px solid #ccc;padding:3px 0px 0px 4px}
.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(../images/login_button.gif) no-repeat;width:60px;height:27px;border:none; text-align:center; cursor:pointer;font-size:14px;margin-left:55px;}
|
108wo
|
phpsso_server/statics/css/login.css
|
CSS
|
asf20
| 1,322
|
<?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;
}
}
}
|
108wo
|
phpsso_server/phpcms/base.php
|
PHP
|
asf20
| 6,393
|
<?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');
}
}
}
?>
|
108wo
|
phpsso_server/phpcms/modules/admin/messagequeue.php
|
PHP
|
asf20
| 3,531
|
<?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');
}
}
}
?>
|
108wo
|
phpsso_server/phpcms/modules/admin/member.php
|
PHP
|
asf20
| 9,207
|
<?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>
|
108wo
|
phpsso_server/phpcms/modules/admin/templates/credit_add.tpl.php
|
PHP
|
asf20
| 2,023
|
<?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>
|
108wo
|
phpsso_server/phpcms/modules/admin/templates/system_uc.tpl.php
|
PHP
|
asf20
| 4,452
|
<?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>
|
108wo
|
phpsso_server/phpcms/modules/admin/templates/applications_list.tpl.php
|
PHP
|
asf20
| 2,524
|
<?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>
|
108wo
|
phpsso_server/phpcms/modules/admin/templates/administrator_edit.tpl.php
|
PHP
|
asf20
| 1,813
|
<?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>
|
108wo
|
phpsso_server/phpcms/modules/admin/templates/login.tpl.php
|
PHP
|
asf20
| 3,109
|
<?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>
|
108wo
|
phpsso_server/phpcms/modules/admin/templates/right.tpl.php
|
PHP
|
asf20
| 2,156
|
<?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>
|
108wo
|
phpsso_server/phpcms/modules/admin/templates/cache.tpl.php
|
PHP
|
asf20
| 1,150
|
<?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>
|
108wo
|
phpsso_server/phpcms/modules/admin/templates/showmessage.tpl.php
|
PHP
|
asf20
| 2,604
|
<?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>
|
108wo
|
phpsso_server/phpcms/modules/admin/templates/index.tpl.php
|
PHP
|
asf20
| 5,801
|
<?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>
|
108wo
|
phpsso_server/phpcms/modules/admin/templates/member_list.tpl.php
|
PHP
|
asf20
| 3,866
|
<?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>
|
108wo
|
phpsso_server/phpcms/modules/admin/templates/applications_add.tpl.php
|
PHP
|
asf20
| 4,769
|
<?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>
|
108wo
|
phpsso_server/phpcms/modules/admin/templates/system.tpl.php
|
PHP
|
asf20
| 1,521
|
<?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>
|
108wo
|
phpsso_server/phpcms/modules/admin/templates/credit_list.tpl.php
|
PHP
|
asf20
| 1,906
|
<?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>
|
108wo
|
phpsso_server/phpcms/modules/admin/templates/administrator_list.tpl.php
|
PHP
|
asf20
| 1,793
|
<?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>
|
108wo
|
phpsso_server/phpcms/modules/admin/templates/member_edit.tpl.php
|
PHP
|
asf20
| 3,073
|
<?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)\"";}?>>
|
108wo
|
phpsso_server/phpcms/modules/admin/templates/header.tpl.php
|
PHP
|
asf20
| 2,255
|
<?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>
|
108wo
|
phpsso_server/phpcms/modules/admin/templates/messagequeue_list.tpl.php
|
PHP
|
asf20
| 3,071
|
<?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>
|
108wo
|
phpsso_server/phpcms/modules/admin/templates/applications_edit.tpl.php
|
PHP
|
asf20
| 5,430
|
<?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>
|
108wo
|
phpsso_server/phpcms/modules/admin/templates/member_add.tpl.php
|
PHP
|
asf20
| 3,330
|
<?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>
|
108wo
|
phpsso_server/phpcms/modules/admin/templates/password.tpl.php
|
PHP
|
asf20
| 2,272
|
<?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>
|
108wo
|
phpsso_server/phpcms/modules/admin/templates/administrator_add.tpl.php
|
PHP
|
asf20
| 2,458
|
<?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>
|
108wo
|
phpsso_server/phpcms/modules/admin/templates/system_sp4.tpl.php
|
PHP
|
asf20
| 1,697
|
<?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');
}
}
|
108wo
|
phpsso_server/phpcms/modules/admin/password.php
|
PHP
|
asf20
| 1,581
|
<?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');
}
}
}
|
108wo
|
phpsso_server/phpcms/modules/admin/applications.php
|
PHP
|
asf20
| 7,386
|
<?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');
}
}
?>
|
108wo
|
phpsso_server/phpcms/modules/admin/index.php
|
PHP
|
asf20
| 1,450
|
<?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';
}
}
|
108wo
|
phpsso_server/phpcms/modules/admin/classes/admin.class.php
|
PHP
|
asf20
| 3,409
|
<?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));
}
}
?>
|
108wo
|
phpsso_server/phpcms/modules/admin/classes/messagequeue.class.php
|
PHP
|
asf20
| 2,344
|
<?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();
}
}
}
|
108wo
|
phpsso_server/phpcms/modules/admin/administrator.php
|
PHP
|
asf20
| 4,165
|
<?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');
}
}
?>
|
108wo
|
phpsso_server/phpcms/modules/admin/system.php
|
PHP
|
asf20
| 3,643
|
<?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');
}
}
}
?>
|
108wo
|
phpsso_server/phpcms/modules/admin/credit.php
|
PHP
|
asf20
| 3,496
|
<?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));
}
}
?>
|
108wo
|
phpsso_server/phpcms/modules/admin/cache.php
|
PHP
|
asf20
| 938
|
<?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);
}
}
|
108wo
|
phpsso_server/phpcms/modules/admin/login.php
|
PHP
|
asf20
| 1,690
|
<?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);
}
}
?>
|
108wo
|
phpsso_server/phpcms/modules/admin/functions/global.func.php
|
PHP
|
asf20
| 4,710
|
<?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');
}
}
}
}
?>
|
108wo
|
phpsso_server/phpcms/modules/phpsso/index.php
|
PHP
|
asf20
| 20,850
|
<?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;
}
// --------------------------------------------------------------------------------
?>
|
108wo
|
phpsso_server/phpcms/modules/phpsso/classes/pclzip.class.php
|
PHP
|
asf20
| 254,403
|
<?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');
}
}
}
}
|
108wo
|
phpsso_server/phpcms/modules/phpsso/classes/phpsso.class.php
|
PHP
|
asf20
| 1,232
|
<?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);
}
?>
|
108wo
|
phpsso_server/phpcms/modules/phpsso/functions/global.func.php
|
PHP
|
asf20
| 561
|
<?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;
}
}
?>
|
108wo
|
phpsso_server/phpcms/libs/classes/cache_factory.class.php
|
PHP
|
asf20
| 2,318
|
<?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;
}
}
?>
|
108wo
|
phpsso_server/phpcms/libs/classes/mysql.class.php
|
PHP
|
asf20
| 12,363
|
<?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;
}
}
}
?>
|
108wo
|
phpsso_server/phpcms/libs/classes/cache_file.class.php
|
PHP
|
asf20
| 3,832
|
<?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'));
}
}
?>
|
108wo
|
phpsso_server/phpcms/libs/classes/form.class.php
|
PHP
|
asf20
| 11,489
|
<?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();
}
}
?>
|
108wo
|
phpsso_server/phpcms/libs/classes/cache_memcache.class.php
|
PHP
|
asf20
| 664
|
<?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.','));
}
}
?>
|
108wo
|
phpsso_server/phpcms/libs/classes/tree.class.php
|
PHP
|
asf20
| 4,139
|
<?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();
}
}
?>
|
108wo
|
phpsso_server/phpcms/libs/classes/db_factory.class.php
|
PHP
|
asf20
| 2,208
|
<?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 ) );
}
}
?>
|
108wo
|
phpsso_server/phpcms/libs/classes/template_cache.class.php
|
PHP
|
asf20
| 5,281
|
<?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;
}
}
?>
|
108wo
|
phpsso_server/phpcms/libs/classes/param.class.php
|
PHP
|
asf20
| 3,103
|
<?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.');
}
}
}
|
108wo
|
phpsso_server/phpcms/libs/classes/application.class.php
|
PHP
|
asf20
| 1,482
|
<?php
class format {
/**
* 日期格式化
*
* @param $timestamp
* @param $showtime
*/
public static function date($timestamp, $showtime = 0) {
if (empty($timestamp)) return false;
$times = intval($timestamp);
if(!$times) return true;
$lang = pc_base::load_config('system','lang');
if($lang == 'zh-cn') {
$str = $showtime ? date('Y-m-d H:i:s', $times) : date('Y-m-d', $times);
} else {
$str = $showtime ? date('m/d/Y H:i:s', $times) : date('m/d/Y', $times);
}
return $str;
}
/**
* 获取当前星期
*
* @param $timestamp
*/
public static function week($timestamp) {
$times = intval($timestamp);
if(!$times) return true;
$weekarray = array(L('Sunday'),L('Monday'),L('Tuesday'),L('Wednesday'),L('Thursday'),L('Friday'),L('Saturday'));
return $weekarray[date("w",$timestamp)];
}
}
?>
|
108wo
|
phpsso_server/phpcms/libs/classes/format.class.php
|
PHP
|
asf20
| 874
|
<?php
/**
* session mysql 数据库存储类
*
* @copyright (C) 2005-2010 PHPCMS
* @license http://www.phpcms.cn/license/
* @lastmodify 2010-6-8
*/
class session_mysql {
var $lifetime = 1800;
var $db;
var $table;
/**
* 构造函数
*
*/
public function __construct() {
$this->db = pc_base::load_model('session_model');
$this->lifetime = pc_base::load_config('system','session_ttl');
session_set_save_handler(array(&$this,'open'), array(&$this,'close'), array(&$this,'read'), array(&$this,'write'), array(&$this,'destroy'), array(&$this,'gc'));
session_start();
}
/**
* session_set_save_handler open方法
* @param $save_path
* @param $session_name
* @return true
*/
public function open($save_path, $session_name) {
return true;
}
/**
* session_set_save_handler close方法
* @return bool
*/
public function close() {
return $this->gc($this->lifetime);
}
/**
* 读取session_id
* session_set_save_handler read方法
* @return string 读取session_id
*/
public function read($id) {
$r = $this->db->get_one(array('sessionid'=>$id), 'data');
return $r ? $r['data'] : '';
}
/**
* 写入session_id 的值
*
* @param $id session
* @param $data 值
* @return mixed query 执行结果
*/
public function write($id, $data) {
$uid = isset($_SESSION['userid']) ? $_SESSION['userid'] : 0;
$roleid = isset($_SESSION['roleid']) ? $_SESSION['roleid'] : 0;
$groupid = isset($_SESSION['groupid']) ? $_SESSION['groupid'] : 0;
$m = defined('ROUTE_M') ? ROUTE_M : '';
$c = defined('ROUTE_C') ? ROUTE_C : '';
$a = defined('ROUTE_A') ? ROUTE_A : '';
if(strlen($data) > 255) $data = '';
$ip = ip();
$sessiondata = array(
'sessionid'=>$id,
'userid'=>uid,
'ip'=>ip,
'lastvisit'=>SYS_TIME,
'roleid'=>$roleid,
'groupid'=>$groupid,
'm'=>$m,
'c'=>$c,
'a'=>a,
'data'=>$data,
);
return $this->db->insert($sessiondata, 1, 1);
}
/**
* 删除指定的session_id
*
* @param $id session
* @return bool
*/
public function destroy($id) {
return $this->db->delete(array('sessionid'=>$id));
}
/**
* 删除过期的 session
*
* @param $maxlifetime 存活期时间
* @return bool
*/
public function gc($maxlifetime) {
$expiretime = SYS_TIME - $maxlifetime;
return $this->db->delete("`lastvisit`<$expiretime");
}
}
?>
|
108wo
|
phpsso_server/phpcms/libs/classes/session_mysql.class.php
|
PHP
|
asf20
| 2,527
|
<?php
class http {
var $method;
var $cookie;
var $post;
var $header;
var $ContentType;
var $errno;
var $errstr;
function __construct() {
$this->method = 'GET';
$this->cookie = '';
$this->post = '';
$this->header = '';
$this->errno = 0;
$this->errstr = '';
}
function post($url, $data = array(), $referer = '', $limit = 0, $timeout = 30, $block = TRUE) {
$this->method = 'POST';
$this->ContentType = "Content-Type: application/x-www-form-urlencoded\r\n";
if($data) {
$post = '';
foreach($data as $k=>$v) {
$post .= $k.'='.rawurlencode($v).'&';
}
$this->post .= substr($post, 0, -1);
}
return $this->request($url, $referer, $limit, $timeout, $block);
}
function get($url, $referer = '', $limit = 0, $timeout = 30, $block = TRUE) {
$this->method = 'GET';
return $this->request($url, $referer, $limit, $timeout, $block);
}
function upload($url, $data = array(), $files = array(), $referer = '', $limit = 0, $timeout = 30, $block = TRUE) {
$this->method = 'POST';
$boundary = "AaB03x";
$this->ContentType = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
if($data) {
foreach($data as $k => $v) {
$this->post .= "--$boundary\r\n";
$this->post .= "Content-Disposition: form-data; name=\"".$k."\"\r\n";
$this->post .= "\r\n".$v."\r\n";
$this->post .= "--$boundary\r\n";
}
}
foreach($files as $k=>$v) {
$this->post .= "--$boundary\r\n";
$this->post .= "Content-Disposition: file; name=\"$k\"; filename=\"".basename($v)."\"\r\n";
$this->post .= "Content-Type: ".$this->get_mime($v)."\r\n";
$this->post .= "\r\n".file_get_contents($v)."\r\n";
$this->post .= "--$boundary\r\n";
}
$this->post .= "--$boundary--\r\n";
return $this->request($url, $referer, $limit, $timeout, $block);
}
function request($url, $referer = '', $limit = 0, $timeout = 30, $block = TRUE) {
$matches = parse_url($url);
$host = $matches['host'];
$path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/';
$port = $matches['port'] ? $matches['port'] : 80;
if($referer == '') $referer = URL;
$out = "$this->method $path HTTP/1.1\r\n";
$out .= "Accept: */*\r\n";
$out .= "Referer: $referer\r\n";
$out .= "Accept-Language: zh-cn\r\n";
$out .= "User-Agent: ".$_SERVER['HTTP_USER_AGENT']."\r\n";
$out .= "Host: $host\r\n";
if($this->cookie) $out .= "Cookie: $this->cookie\r\n";
if($this->method == 'POST') {
$out .= $this->ContentType;
$out .= "Content-Length: ".strlen($this->post)."\r\n";
$out .= "Cache-Control: no-cache\r\n";
$out .= "Connection: Close\r\n\r\n";
$out .= $this->post;
} else {
$out .= "Connection: Close\r\n\r\n";
}
if($timeout > ini_get('max_execution_time')) @set_time_limit($timeout);
$fp = @fsockopen($host, $port, $errno, $errstr, $timeout);
if(!$fp) {
$this->errno = $errno;
$this->errstr = $errstr;
return false;
} else {
stream_set_blocking($fp, $block);
stream_set_timeout($fp, $timeout);
fwrite($fp, $out);
$this->data = '';
$status = stream_get_meta_data($fp);
if(!$status['timed_out']) {
$maxsize = min($limit, 1024000);
if($maxsize == 0) $maxsize = 1024000;
$start = false;
while(!feof($fp)) {
if($start) {
$line = fread($fp, $maxsize);
if(strlen($this->data) > $maxsize) break;
$this->data .= $line;
} else {
$line = fgets($fp);
$this->header .= $line;
if($line == "\r\n" || $line == "\n") $start = true;
}
}
}
fclose($fp);
return $this->is_ok();
}
}
function save($file) {
dir_create(dirname($file));
return file_put_contents($file, $this->data);
}
function set_cookie($name, $value) {
$this->cookie .= "$name=$value;";
}
function get_cookie() {
$cookies = array();
if(preg_match_all("|Set-Cookie: ([^;]*);|", $this->header, $m)) {
foreach($m[1] as $c) {
list($k, $v) = explode('=', $c);
$cookies[$k] = $v;
}
}
return $cookies;
}
function get_data() {
if (strpos($this->header,'chunk')) {
$data = explode(chr(13), $this->data);
return $data[1];
} else {
return $this->data;
}
}
function get_header() {
return $this->header;
}
function get_status() {
preg_match("|^HTTP/1.1 ([0-9]{3}) (.*)|", $this->header, $m);
return array($m[1], $m[2]);
}
function get_mime($file) {
$ext = strtolower(trim(substr(strrchr($file, '.'), 1, 10)));
if($ext == '') return '';
$mime_types = array (
'acx' => 'application/internet-property-stream',
'ai' => 'application/postscript',
'aif' => 'audio/x-aiff',
'aifc' => 'audio/x-aiff',
'aiff' => 'audio/x-aiff',
'asp' => 'text/plain',
'aspx' => 'text/plain',
'asf' => 'video/x-ms-asf',
'asr' => 'video/x-ms-asf',
'asx' => 'video/x-ms-asf',
'au' => 'audio/basic',
'avi' => 'video/x-msvideo',
'axs' => 'application/olescript',
'bas' => 'text/plain',
'bcpio' => 'application/x-bcpio',
'bin' => 'application/octet-stream',
'bmp' => 'image/bmp',
'c' => 'text/plain',
'cat' => 'application/vnd.ms-pkiseccat',
'cdf' => 'application/x-cdf',
'cer' => 'application/x-x509-ca-cert',
'class' => 'application/octet-stream',
'clp' => 'application/x-msclip',
'cmx' => 'image/x-cmx',
'cod' => 'image/cis-cod',
'cpio' => 'application/x-cpio',
'crd' => 'application/x-mscardfile',
'crl' => 'application/pkix-crl',
'crt' => 'application/x-x509-ca-cert',
'csh' => 'application/x-csh',
'css' => 'text/css',
'dcr' => 'application/x-director',
'der' => 'application/x-x509-ca-cert',
'dir' => 'application/x-director',
'dll' => 'application/x-msdownload',
'dms' => 'application/octet-stream',
'doc' => 'application/msword',
'dot' => 'application/msword',
'dvi' => 'application/x-dvi',
'dxr' => 'application/x-director',
'eps' => 'application/postscript',
'etx' => 'text/x-setext',
'evy' => 'application/envoy',
'exe' => 'application/octet-stream',
'fif' => 'application/fractals',
'flr' => 'x-world/x-vrml',
'flv' => 'video/x-flv',
'gif' => 'image/gif',
'gtar' => 'application/x-gtar',
'gz' => 'application/x-gzip',
'h' => 'text/plain',
'hdf' => 'application/x-hdf',
'hlp' => 'application/winhlp',
'hqx' => 'application/mac-binhex40',
'hta' => 'application/hta',
'htc' => 'text/x-component',
'htm' => 'text/html',
'html' => 'text/html',
'htt' => 'text/webviewhtml',
'ico' => 'image/x-icon',
'ief' => 'image/ief',
'iii' => 'application/x-iphone',
'ins' => 'application/x-internet-signup',
'isp' => 'application/x-internet-signup',
'jfif' => 'image/pipeg',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'js' => 'application/x-javascript',
'latex' => 'application/x-latex',
'lha' => 'application/octet-stream',
'lsf' => 'video/x-la-asf',
'lsx' => 'video/x-la-asf',
'lzh' => 'application/octet-stream',
'm13' => 'application/x-msmediaview',
'm14' => 'application/x-msmediaview',
'm3u' => 'audio/x-mpegurl',
'man' => 'application/x-troff-man',
'mdb' => 'application/x-msaccess',
'me' => 'application/x-troff-me',
'mht' => 'message/rfc822',
'mhtml' => 'message/rfc822',
'mid' => 'audio/mid',
'mny' => 'application/x-msmoney',
'mov' => 'video/quicktime',
'movie' => 'video/x-sgi-movie',
'mp2' => 'video/mpeg',
'mp3' => 'audio/mpeg',
'mpa' => 'video/mpeg',
'mpe' => 'video/mpeg',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpp' => 'application/vnd.ms-project',
'mpv2' => 'video/mpeg',
'ms' => 'application/x-troff-ms',
'mvb' => 'application/x-msmediaview',
'nws' => 'message/rfc822',
'oda' => 'application/oda',
'p10' => 'application/pkcs10',
'p12' => 'application/x-pkcs12',
'p7b' => 'application/x-pkcs7-certificates',
'p7c' => 'application/x-pkcs7-mime',
'p7m' => 'application/x-pkcs7-mime',
'p7r' => 'application/x-pkcs7-certreqresp',
'p7s' => 'application/x-pkcs7-signature',
'pbm' => 'image/x-portable-bitmap',
'pdf' => 'application/pdf',
'pfx' => 'application/x-pkcs12',
'pgm' => 'image/x-portable-graymap',
'php' => 'text/plain',
'pko' => 'application/ynd.ms-pkipko',
'pma' => 'application/x-perfmon',
'pmc' => 'application/x-perfmon',
'pml' => 'application/x-perfmon',
'pmr' => 'application/x-perfmon',
'pmw' => 'application/x-perfmon',
'png' => 'image/png',
'pnm' => 'image/x-portable-anymap',
'pot,' => 'application/vnd.ms-powerpoint',
'ppm' => 'image/x-portable-pixmap',
'pps' => 'application/vnd.ms-powerpoint',
'ppt' => 'application/vnd.ms-powerpoint',
'prf' => 'application/pics-rules',
'ps' => 'application/postscript',
'pub' => 'application/x-mspublisher',
'qt' => 'video/quicktime',
'ra' => 'audio/x-pn-realaudio',
'ram' => 'audio/x-pn-realaudio',
'ras' => 'image/x-cmu-raster',
'rgb' => 'image/x-rgb',
'rmi' => 'audio/mid',
'roff' => 'application/x-troff',
'rtf' => 'application/rtf',
'rtx' => 'text/richtext',
'scd' => 'application/x-msschedule',
'sct' => 'text/scriptlet',
'setpay' => 'application/set-payment-initiation',
'setreg' => 'application/set-registration-initiation',
'sh' => 'application/x-sh',
'shar' => 'application/x-shar',
'sit' => 'application/x-stuffit',
'snd' => 'audio/basic',
'spc' => 'application/x-pkcs7-certificates',
'spl' => 'application/futuresplash',
'src' => 'application/x-wais-source',
'sst' => 'application/vnd.ms-pkicertstore',
'stl' => 'application/vnd.ms-pkistl',
'stm' => 'text/html',
'svg' => 'image/svg+xml',
'sv4cpio' => 'application/x-sv4cpio',
'sv4crc' => 'application/x-sv4crc',
'swf' => 'application/x-shockwave-flash',
't' => 'application/x-troff',
'tar' => 'application/x-tar',
'tcl' => 'application/x-tcl',
'tex' => 'application/x-tex',
'texi' => 'application/x-texinfo',
'texinfo' => 'application/x-texinfo',
'tgz' => 'application/x-compressed',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'tr' => 'application/x-troff',
'trm' => 'application/x-msterminal',
'tsv' => 'text/tab-separated-values',
'txt' => 'text/plain',
'uls' => 'text/iuls',
'ustar' => 'application/x-ustar',
'vcf' => 'text/x-vcard',
'vrml' => 'x-world/x-vrml',
'wav' => 'audio/x-wav',
'wcm' => 'application/vnd.ms-works',
'wdb' => 'application/vnd.ms-works',
'wks' => 'application/vnd.ms-works',
'wmf' => 'application/x-msmetafile',
'wmv' => 'video/x-ms-wmv',
'wps' => 'application/vnd.ms-works',
'wri' => 'application/x-mswrite',
'wrl' => 'x-world/x-vrml',
'wrz' => 'x-world/x-vrml',
'xaf' => 'x-world/x-vrml',
'xbm' => 'image/x-xbitmap',
'xla' => 'application/vnd.ms-excel',
'xlc' => 'application/vnd.ms-excel',
'xlm' => 'application/vnd.ms-excel',
'xls' => 'application/vnd.ms-excel',
'xlt' => 'application/vnd.ms-excel',
'xlw' => 'application/vnd.ms-excel',
'xof' => 'x-world/x-vrml',
'xpm' => 'image/x-xpixmap',
'xwd' => 'image/x-xwindowdump',
'z' => 'application/x-compress',
'zip' => 'application/zip',
);
return isset($mime_types[$ext]) ? $mime_types[$ext] : '';
}
function is_ok() {
$status = $this->get_status();
if(intval($status[0]) != 200) {
$this->errno = $status[0];
$this->errstr = $status[1];
return false;
}
return true;
}
function errno() {
return $this->errno;
}
function errmsg() {
return $this->errstr;
}
}
?>
|
108wo
|
phpsso_server/phpcms/libs/classes/http.class.php
|
PHP
|
asf20
| 12,888
|
<?php
/**
* model.class.php 数据模型基类
*
* @copyright (C) 2005-2010 PHPCMS
* @license http://www.phpcms.cn/license/
* @lastmodify 2010-6-7
*/
pc_base::load_sys_class('db_factory', '', 0);
class model {
//数据库配置
protected $db_config = '';
//数据库连接
protected $db = '';
//调用数据库的配置项
protected $db_setting = 'default';
//数据表名
protected $table_name = '';
//表前缀
public $db_tablepre = '';
public function __construct() {
if (!isset($this->db_config[$this->db_setting])) {
$this->db_setting = 'default';
}
$this->table_name = $this->db_config[$this->db_setting]['tablepre'].$this->table_name;
$this->db_tablepre = $this->db_config[$this->db_setting]['tablepre'];
$this->db = db_factory::get_instance($this->db_config)->get_database($this->db_setting);
}
/**
* 执行sql查询
* @param $where 查询条件[例`name`='$name']
* @param $data 需要查询的字段值[例`name`,`gender`,`birthday`]
* @param $limit 返回结果范围[例:10或10,10 默认为空]
* @param $order 排序方式 [默认按数据库默认方式排序]
* @param $group 分组方式 [默认为空]
* @return array 查询结果集数组
*/
final public function select($where = '', $data = '*', $limit = '', $order = '', $group = '', $key='') {
if (is_array($where)) $where = $this->sqls($where);
return $this->db->select($data, $this->table_name, $where, $limit, $order, $group, $key);
}
/**
* 查询多条数据并分页
* @param $where
* @param $order
* @param $page
* @param $pagesize
* @return unknown_type
*/
final public function listinfo($where = '', $order = '', $page = 1, $pagesize = 20, $key='', $setpages = 10,$urlrule = '',$array = array()) {
$where = to_sqls($where);
$this->number = $this->count($where);
$page = max(intval($page), 1);
$offset = $pagesize*($page-1);
$this->pages = pages($this->number, $page, $pagesize, $urlrule, $array, $setpages);
$array = array();
return $this->select($where, '*', "$offset, $pagesize", $order, '', $key);
}
/**
* 获取单条记录查询
* @param $where 查询条件
* @param $data 需要查询的字段值[例`name`,`gender`,`birthday`]
* @param $order 排序方式 [默认按数据库默认方式排序]
* @param $group 分组方式 [默认为空]
* @return array/null 数据查询结果集,如果不存在,则返回空
*/
final public function get_one($where = '', $data = '*', $order = '', $group = '') {
if (is_array($where)) $where = $this->sqls($where);
return $this->db->get_one($data, $this->table_name, $where, $order, $group);
}
/**
* 直接执行sql查询
* @param $sql 查询sql语句
* @return boolean/query resource 如果为查询语句,返回资源句柄,否则返回true/false
*/
final public function query($sql) {
return $this->db->query($sql);
}
/**
* 执行添加记录操作
* @param $data 要增加的数据,参数为数组。数组key为字段值,数组值为数据取值
* @param $return_insert_id 是否返回新建ID号
* @param $replace 是否采用 replace into的方式添加数据
* @return boolean
*/
final public function insert($data, $return_insert_id = false, $replace = false) {
return $this->db->insert($data, $this->table_name, $return_insert_id, $replace);
}
/**
* 获取最后一次添加记录的主键号
* @return int
*/
final public function insert_id() {
return $this->db->insert_id();
}
/**
* 执行更新记录操作
* @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 $where 更新数据时的条件,可为数组或字符串
* @return boolean
*/
final public function update($data, $where = '') {
if (is_array($where)) $where = $this->sqls($where);
return $this->db->update($data, $this->table_name, $where);
}
/**
* 执行删除记录操作
* @param $where 删除数据条件,不充许为空。
* @return boolean
*/
final public function delete($where) {
if (is_array($where)) $where = $this->sqls($where);
return $this->db->delete($this->table_name, $where);
}
/**
* 计算记录数
* @param string/array $where 查询条件
*/
final public function count($where = '') {
$r = $this->get_one($where, "COUNT(*) AS num");
return $r['num'];
}
/**
* 将数组转换为SQL语句
* @param array $where 要生成的数组
* @param string $font 连接串。
*/
final public function sqls($where, $font = ' AND ') {
if (is_array($where)) {
$sql = '';
foreach ($where as $key=>$val) {
$sql .= $sql ? " $font `$key` = '$val' " : " `$key` = '$val'";
}
return $sql;
} else {
return $where;
}
}
/**
* 获取最后数据库操作影响到的条数
* @return int
*/
final public function affected_rows() {
return $this->db->affected_rows();
}
/**
* 获取数据表主键
* @return array
*/
final public function get_primary() {
return $this->db->get_primary($this->table_name);
}
/**
* 获取表字段
* @return array
*/
final public function get_fields() {
return $this->db->get_fields($this->table_name);
}
/**
* 检查表是否存在
* @param $table 表名
* @return boolean
*/
final public function table_exists($table){
return $this->db->table_exists($this->db_tablepre.$table);
}
final public function list_tables() {
return $this->db->list_tables();
}
/**
* 返回数据结果集
* @param $query (mysql_query返回值)
* @return array
*/
final public function fetch_array() {
$data = array();
while($r = $this->db->fetch_next()) {
$data[] = $r;
}
return $data;
}
/**
* 返回数据库版本号
*/
final public function version() {
return $this->db->version();
}
}
|
108wo
|
phpsso_server/phpcms/libs/classes/model.class.php
|
PHP
|
asf20
| 6,406
|
<?php
/**
* @author wangtiecheng(jim_@live.cn)
* @link http://www.phpcms.cn http://www.ku6.cn
* @copyright 2005-2009 PHPCMS/KU6 Software LLCS
* @license http://www.phpcms.cn/license/
* @datetime Wed Aug 05 18:37:10 CST 2009
* @lastmodify Wed Aug 05 18:37:10 CST 2009
* ------------------------------------------------------------
* $xml = new xml();
* $res = $xml->xml_unserialize($data);
*/
class xml {
var $parser;
var $document;
var $parent;
var $stack;
var $last_opened_tag;
public function xml() {
$this->parser = xml_parser_create();
xml_parser_set_option(&$this->parser, XML_OPTION_CASE_FOLDING, false);
xml_set_object(&$this->parser, &$this);
xml_set_element_handler(&$this->parser, 'open','close');
xml_set_character_data_handler(&$this->parser, 'data');
}
public function destruct() {
xml_parser_free(&$this->parser);
}
/**
* unserialize
* @param xml字符串
* @return array
*/
public function xml_unserialize($xml) {
$data = $this->parse($xml);
$this->destruct();
return $data;
}
/**
* serialize
* @param $data 数组
* @return string
*/
public function xml_serialize(&$data, $level = 0, $prior_key = NULL) {
if($level == 0) {
ob_start();
echo "<?xml version=\"1.0\" ?>\n<root>","\n";
}
while(list($key, $value) = each($data)) {
if(!strpos($key, ' attr')) {
if(is_array($value) and array_key_exists(0, $value)) {
$this->xml_serialize($value, $level, $key);
} else {
$tag = $prior_key ? $prior_key : $key;
echo str_repeat("\t", $level),'<',$tag;
if(array_key_exists("$key attr", $data)) {
while(list($attr_name, $attr_value) = each($data["$key attr"])) {
echo ' ',$attr_name,'="',htmlspecialchars($attr_value),'"';
}
reset($data["$key attr"]);
}
if(is_null($value)) {
echo " />\n";
} elseif(!is_array($value)) {
echo '>',htmlspecialchars($value),"</$tag>\n";
} else {
echo ">\n",$this->xml_serialize($value, $level+1),str_repeat("\t", $level),"</$tag>\n";
}
}
}
}
reset($data);
if($level == 0) {
$str = &ob_get_contents();
ob_end_clean();
return $str.'</root>';
}
}
public function parse(&$data){
$this->document = array();
$this->stack = array();
$this->parent = &$this->document;
return xml_parse(&$this->parser, &$data, true) ? $this->document : NULL;
}
public function open(&$parser, $tag, $attributes){
$this->data = '';
$this->last_opened_tag = $tag;
if(is_array($this->parent) && array_key_exists($tag, $this->parent)) {
if(is_array($this->parent[$tag]) && array_key_exists(0,$this->parent[$tag])) {
$key = $this->count_numeric_items($this->parent[$tag]);
} else {
if(array_key_exists("$tag attr", $this->parent)) {
$arr = array('0 attr'=>&$this->parent["$tag attr"], &$this->parent[$tag]);
unset($this->parent["$tag attr"]);
} else {
$arr = array(&$this->parent[$tag]);
}
$this->parent[$tag] = &$arr;
$key = 1;
}
$this->parent = &$this->parent[$tag];
} else {
$key = $tag;
}
if($attributes) {
$this->parent["$key attr"] = $attributes;
}
$this->parent = &$this->parent[$key];
$this->stack[] = &$this->parent;
}
public function data(&$parser, $data) {
if($this->last_opened_tag != NULL) {
$this->data .= $data;
}
}
public function close(&$parser, $tag) {
if($this->last_opened_tag == $tag) {
$this->parent = $this->data;
$this->last_opened_tag = NULL;
}
array_pop($this->stack);
if($this->stack) {
$this->parent = &$this->stack[count($this->stack)-1];
}
}
public function count_numeric_items(&$array) {
return is_array($array) ? count(array_filter(array_keys($array), 'is_numeric')) : 0;
}
}
?>
|
108wo
|
phpsso_server/phpcms/libs/classes/xml.class.php
|
PHP
|
asf20
| 4,354
|
<?php
/**
* 生成验证码
* @author chenzhouyu
* 类用法
* $checkcode = new checkcode();
* $checkcode->doimage();
* //取得验证
* $_SESSION['code']=$checkcode->get_code();
*/
class checkcode {
//验证码的宽度
public $width=130;
//验证码的高
public $height=50;
//设置字体的地址
public $font;
//设置字体色
public $font_color;
//设置随机生成因子
public $charset = 'abcdefghkmnprstuvwyzABCDEFGHKLMNPRSTUVWYZ23456789';
//设置背景色
public $background = '#EDF7FF';
//生成验证码字符数
public $code_len = 4;
//字体大小
public $font_size = 20;
//验证码
private $code;
//图片内存
private $img;
//文字X轴开始的地方
private $x_start;
function __construct() {
$this->font = PC_PATH.'libs'.DIRECTORY_SEPARATOR.'data'.DIRECTORY_SEPARATOR.'font'.DIRECTORY_SEPARATOR.'elephant.ttf';
}
/**
* 生成随机验证码。
*/
protected function creat_code() {
$code = '';
$charset_len = strlen($this->charset)-1;
for ($i=0; $i<$this->code_len; $i++) {
$code .= $this->charset[rand(1, $charset_len)];
}
$this->code = $code;
}
/**
* 获取验证码
*/
public function get_code() {
return strtolower($this->code);
}
/**
* 生成图片
*/
public function doimage() {
$this->creat_code();
$this->img = imagecreatetruecolor($this->width, $this->height);
if (!$this->font_color) {
$this->font_color = imagecolorallocate($this->img, rand(0,156), rand(0,156), rand(0,156));
} else {
$this->font_color = imagecolorallocate($this->img, hexdec(substr($this->font_color, 1,2)), hexdec(substr($this->font_color, 3,2)), hexdec(substr($this->font_color, 5,2)));
}
//设置背景色
$background = imagecolorallocate($this->img,hexdec(substr($this->background, 1,2)),hexdec(substr($this->background, 3,2)),hexdec(substr($this->background, 5,2)));
//画一个柜形,设置背景颜色。
imagefilledrectangle($this->img,0, $this->height, $this->width, 0, $background);
$this->creat_font();
$this->creat_line();
$this->output();
}
/**
* 生成文字
*/
private function creat_font() {
$x = $this->width/$this->code_len;
for ($i=0; $i<$this->code_len; $i++) {
imagettftext($this->img, $this->font_size, rand(-30,30), $x*$i+rand(0,5), $this->height/1.4, $this->font_color, $this->font, $this->code[$i]);
if($i==0)$this->x_start=$x*$i+5;
}
}
/**
* 画线
*/
private function creat_line() {
imagesetthickness($this->img, 3);
$xpos = ($this->font_size * 2) + rand(-5, 5);
$width = $this->width / 2.66 + rand(3, 10);
$height = $this->font_size * 2.14;
if ( rand(0,100) % 2 == 0 ) {
$start = rand(0,66);
$ypos = $this->height / 2 - rand(10, 30);
$xpos += rand(5, 15);
} else {
$start = rand(180, 246);
$ypos = $this->height / 2 + rand(10, 30);
}
$end = $start + rand(75, 110);
imagearc($this->img, $xpos, $ypos, $width, $height, $start, $end, $this->font_color);
$color = $colors[rand(0, sizeof($colors) - 1)];
if ( rand(1,75) % 2 == 0 ) {
$start = rand(45, 111);
$ypos = $this->height / 2 - rand(10, 30);
$xpos += rand(5, 15);
} else {
$start = rand(200, 250);
$ypos = $this->height / 2 + rand(10, 30);
}
$end = $start + rand(75, 100);
imagearc($this->img, $this->width * .75, $ypos, $width, $height, $start, $end, $this->font_color);
}
//输出图片
private function output() {
header("content-type:image/png\r\n");
imagepng($this->img);
imagedestroy($this->img);
}
}
|
108wo
|
phpsso_server/phpcms/libs/classes/checkcode.class.php
|
PHP
|
asf20
| 3,765
|
<?php
define('CODETABLEDIR', dirname(__FILE__).DIRECTORY_SEPARATOR.'encoding'.DIRECTORY_SEPARATOR);
function utf8_to_gbk($utfstr)
{
global $UC2GBTABLE;
$okstr = '';
if(empty($UC2GBTABLE))
{
$filename = CODETABLEDIR.'gb-unicode.table';
$fp = fopen($filename, 'rb');
while($l = fgets($fp,15))
{
$UC2GBTABLE[hexdec(substr($l, 7, 6))] = hexdec(substr($l, 0, 6));
}
fclose($fp);
}
$okstr = '';
$ulen = strlen($utfstr);
for($i=0; $i<$ulen; $i++)
{
$c = $utfstr[$i];
$cb = decbin(ord($utfstr[$i]));
if(strlen($cb)==8)
{
$csize = strpos(decbin(ord($cb)),'0');
for($j = 0; $j < $csize; $j++)
{
$i++;
$c .= $utfstr[$i];
}
$c = utf8_to_unicode($c);
if(isset($UC2GBTABLE[$c]))
{
$c = dechex($UC2GBTABLE[$c]+0x8080);
$okstr .= chr(hexdec($c[0].$c[1])).chr(hexdec($c[2].$c[3]));
}
else
{
$okstr .= '&#'.$c.';';
}
}
else
{
$okstr .= $c;
}
}
$okstr = trim($okstr);
return $okstr;
}
function gbk_to_utf8($gbstr)
{
global $CODETABLE;
if(empty($CODETABLE))
{
$filename = CODETABLEDIR.'gb-unicode.table';
$fp = fopen($filename, 'rb');
while($l = fgets($fp,15))
{
$CODETABLE[hexdec(substr($l, 0, 6))] = substr($l, 7, 6);
}
fclose($fp);
}
$ret = '';
$utf8 = '';
while($gbstr)
{
if(ord(substr($gbstr, 0, 1)) > 0x80)
{
$thisW = substr($gbstr, 0, 2);
$gbstr = substr($gbstr, 2, strlen($gbstr));
$utf8 = '';
@$utf8 = unicode_to_utf8(hexdec($CODETABLE[hexdec(bin2hex($thisW)) - 0x8080]));
if($utf8 != '')
{
for($i = 0; $i < strlen($utf8); $i += 3) $ret .= chr(substr($utf8, $i, 3));
}
}
else
{
$ret .= substr($gbstr, 0, 1);
$gbstr = substr($gbstr, 1, strlen($gbstr));
}
}
return $ret;
}
function big5_to_gbk($Text)
{
global $BIG5_DATA;
if(empty($BIG5_DATA))
{
$filename = CODETABLEDIR.'big5-gb.table';
$fp = fopen($filename, 'rb');
$BIG5_DATA = fread($fp, filesize($filename));
fclose($fp);
}
$max = strlen($Text)-1;
for($i = 0; $i < $max; $i++)
{
$h = ord($Text[$i]);
if($h >= 0x80)
{
$l = ord($Text[$i+1]);
if($h==161 && $l==64)
{
$gbstr = ' ';
}
else
{
$p = ($h-160)*510+($l-1)*2;
$gbstr = $BIG5_DATA[$p].$BIG5_DATA[$p+1];
}
$Text[$i] = $gbstr[0];
$Text[$i+1] = $gbstr[1];
$i++;
}
}
return $Text;
}
function gbk_to_big5($Text)
{
global $GB_DATA;
if(empty($GB_DATA))
{
$filename = CODETABLEDIR.'gb-big5.table';
$fp = fopen($filename, 'rb');
$gb = fread($fp, filesize($filename));
fclose($fp);
}
$max = strlen($Text)-1;
for($i = 0; $i < $max; $i++)
{
$h = ord($Text[$i]);
if($h >= 0x80)
{
$l = ord($Text[$i+1]);
if($h==161 && $l==64)
{
$big = ' ';
}
else
{
$p = ($h-160)*510+($l-1)*2;
$big = $GB_DATA[$p].$GB_DATA[$p+1];
}
$Text[$i] = $big[0];
$Text[$i+1] = $big[1];
$i++;
}
}
return $Text;
}
function unicode_to_utf8($c)
{
$str = '';
if($c < 0x80)
{
$str .= $c;
}
elseif($c < 0x800)
{
$str .= (0xC0 | $c >> 6);
$str .= (0x80 | $c & 0x3F);
}
elseif($c < 0x10000)
{
$str .= (0xE0 | $c >> 12);
$str .= (0x80 | $c >> 6 & 0x3F);
$str .= (0x80 | $c & 0x3F);
}
elseif($c < 0x200000)
{
$str .= (0xF0 | $c >> 18);
$str .= (0x80 | $c >> 12 & 0x3F);
$str .= (0x80 | $c >> 6 & 0x3F);
$str .= (0x80 | $c & 0x3F);
}
return $str;
}
function utf8_to_unicode($c)
{
switch(strlen($c))
{
case 1:
return ord($c);
case 2:
$n = (ord($c[0]) & 0x3f) << 6;
$n += ord($c[1]) & 0x3f;
return $n;
case 3:
$n = (ord($c[0]) & 0x1f) << 12;
$n += (ord($c[1]) & 0x3f) << 6;
$n += ord($c[2]) & 0x3f;
return $n;
case 4:
$n = (ord($c[0]) & 0x0f) << 18;
$n += (ord($c[1]) & 0x3f) << 12;
$n += (ord($c[2]) & 0x3f) << 6;
$n += ord($c[3]) & 0x3f;
return $n;
}
}
function asc_to_pinyin($asc,&$pyarr)
{
if($asc < 128)return chr($asc);
elseif(isset($pyarr[$asc]))return $pyarr[$asc];
else
{
foreach($pyarr as $id => $p)
{
if($id >= $asc)return $p;
}
}
}
function gbk_to_pinyin($txt)
{
$l = strlen($txt);
$i = 0;
$pyarr = array();
$py = array();
$filename = CODETABLEDIR.'gb-pinyin.table';
$fp = fopen($filename,'r');
while(!feof($fp))
{
$p = explode("-",fgets($fp,32));
$pyarr[intval($p[1])] = trim($p[0]);
}
fclose($fp);
ksort($pyarr);
while($i<$l)
{
$tmp = ord($txt[$i]);
if($tmp>=128)
{
$asc = abs($tmp*256+ord($txt[$i+1])-65536);
$i = $i+1;
}else $asc = $tmp;
$py[] = asc_to_pinyin($asc,$pyarr);
$i++;
}
return $py;
}
?>
|
108wo
|
phpsso_server/phpcms/libs/functions/iconv.func.php
|
PHP
|
asf20
| 4,781
|
<?php
/**
* global.func.php 公共函数库
*
* @copyright (C) 2005-2010 PHPCMS
* @license http://www.phpcms.cn/license/
* @lastmodify 2010-6-1
*/
/**
* 返回经addslashes处理过的字符串或数组
* @param $string 需要处理的字符串或数组
* @return mixed
*/
function new_addslashes($string) {
if(!is_array($string)) return addslashes($string);
foreach($string as $key => $val) $string[$key] = new_addslashes($val);
return $string;
}
/**
* 返回经stripslashes处理过的字符串或数组
* @param $string 需要处理的字符串或数组
* @return mixed
*/
function new_stripslashes($string) {
if(!is_array($string)) return stripslashes($string);
foreach($string as $key => $val) $string[$key] = new_stripslashes($val);
return $string;
}
/**
* 返回经addslashe处理过的字符串或数组
* @param $obj 需要处理的字符串或数组
* @return mixed
*/
function new_html_special_chars($string) {
if(!is_array($string)) return htmlspecialchars($string);
foreach($string as $key => $val) $string[$key] = new_html_special_chars($val);
return $string;
}
/**
* 安全过滤函数
*
* @param $string
* @return string
*/
function safe_replace($string) {
$string = str_replace('%20','',$string);
$string = str_replace('%27','',$string);
$string = str_replace('%2527','',$string);
$string = str_replace('*','',$string);
$string = str_replace('"','"',$string);
$string = str_replace("'",'',$string);
$string = str_replace('"','',$string);
$string = str_replace(';','',$string);
$string = str_replace('<','<',$string);
$string = str_replace('>','>',$string);
$string = str_replace("{",'',$string);
$string = str_replace('}','',$string);
return $string;
}
/**
* 过滤ASCII码从0-28的控制字符
* @return String
*/
function trim_unsafe_control_chars($str) {
$rule = '/[' . chr ( 1 ) . '-' . chr ( 8 ) . chr ( 11 ) . '-' . chr ( 12 ) . chr ( 14 ) . '-' . chr ( 31 ) . ']*/';
return str_replace ( chr ( 0 ), '', preg_replace ( $rule, '', $str ) );
}
/**
* 格式化文本域内容
*
* @param $string 文本域内容
* @return string
*/
function trim_textarea($string) {
$string = nl2br ( str_replace ( ' ', ' ', $string ) );
return $string;
}
/**
* 将文本格式成适合js输出的字符串
* @param string $string 需要处理的字符串
* @param intval $isjs 是否执行字符串格式化,默认为执行
* @return string 处理后的字符串
*/
function format_js($string, $isjs = 1) {
$string = addslashes(str_replace(array("\r", "\n"), array('', ''), $string));
return $isjs ? 'document.write("'.$string.'");' : $string;
}
/**
* 转义 javascript 代码标记
*
* @param $str
* @return mixed
*/
function trim_script($str) {
$str = preg_replace ( '/\<([\/]?)script([^\>]*?)\>/si', '<\\1script\\2>', $str );
$str = preg_replace ( '/\<([\/]?)iframe([^\>]*?)\>/si', '<\\1iframe\\2>', $str );
$str = preg_replace ( '/\<([\/]?)frame([^\>]*?)\>/si', '<\\1frame\\2>', $str );
$str = preg_replace ( '/]]\>/si', ']] >', $str );
return $str;
}
/**
* 获取当前页面完整URL地址
*/
function get_url() {
$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
$php_self = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']);
$path_info = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '';
$relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
}
/**
* 字符截取 支持UTF8/GBK
* @param $string
* @param $length
* @param $dot
*/
function str_cut($string, $length, $dot = '...') {
$strlen = strlen($string);
if($strlen <= $length) return $string;
$string = str_replace(array(' ', '&', '"', ''', '“', '”', '—', '<', '>', '·', '…'), array(' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
$strcut = '';
if(strtolower(CHARSET) == 'utf-8') {
$n = $tn = $noc = 0;
while($n < $strlen) {
$t = ord($string[$n]);
if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
$tn = 1; $n++; $noc++;
} elseif(194 <= $t && $t <= 223) {
$tn = 2; $n += 2; $noc += 2;
} elseif(224 <= $t && $t < 239) {
$tn = 3; $n += 3; $noc += 2;
} elseif(240 <= $t && $t <= 247) {
$tn = 4; $n += 4; $noc += 2;
} elseif(248 <= $t && $t <= 251) {
$tn = 5; $n += 5; $noc += 2;
} elseif($t == 252 || $t == 253) {
$tn = 6; $n += 6; $noc += 2;
} else {
$n++;
}
if($noc >= $length) break;
}
if($noc > $length) $n -= $tn;
$strcut = substr($string, 0, $n);
} else {
$dotlen = strlen($dot);
$maxi = $length - $dotlen - 1;
for($i = 0; $i < $maxi; $i++)
{
$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
}
}
$strcut = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $strcut);
return $strcut.$dot;
}
/**
* 获取请求ip
*
* @return ip地址
*/
function ip() {
if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
$ip = getenv('HTTP_CLIENT_IP');
} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
$ip = getenv('HTTP_X_FORWARDED_FOR');
} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
$ip = getenv('REMOTE_ADDR');
} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
$ip = $_SERVER['REMOTE_ADDR'];
}
return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
}
function get_cost_time() {
$microtime = microtime(TRUE);
return $microtime - SYS_START_TIME;
}
/**
* 程序执行时间
*
* @return int 单位ms
*/
function execute_time() {
$stime = explode ( ' ', SYS_START_TIME );
$etime = explode ( ' ', microtime () );
return number_format ( ($etime [1] + $etime [0] - $stime [1] - $stime [0]), 6 );
}
/**
* 产生随机字符串
*
* @param int $length 输出长度
* @param string $chars 可选的 ,默认为 0123456789
* @return string 字符串
*/
function random($length, $chars = '0123456789') {
$hash = '';
$max = strlen($chars) - 1;
for($i = 0; $i < $length; $i++) {
$hash .= $chars[mt_rand(0, $max)];
}
return $hash;
}
/**
* 将字符串转换为数组
*
* @param string $data 字符串
* @return array 返回数组格式,如果,data为空,则返回空数组
*/
function string2array($data) {
if($data == '') return array();
eval("\$array = $data;");
return $array;
}
/**
* 将数组转换为字符串
*
* @param array $data 数组
* @param bool $isformdata 如果为0,则不使用new_stripslashes处理,可选参数,默认为1
* @return string 返回字符串,如果,data为空,则返回空
*/
function array2string($data, $isformdata = 1) {
if($data == '') return '';
if($isformdata) $data = new_stripslashes($data);
return addslashes(var_export($data, TRUE));
}
/**
* 转换字节数为其他单位
*
*
* @param string $filesize 字节大小
* @return string 返回大小
*/
function sizecount($filesize) {
if ($filesize >= 1073741824) {
$filesize = round($filesize / 1073741824 * 100) / 100 .' GB';
} elseif ($filesize >= 1048576) {
$filesize = round($filesize / 1048576 * 100) / 100 .' MB';
} elseif($filesize >= 1024) {
$filesize = round($filesize / 1024 * 100) / 100 . ' KB';
} else {
$filesize = $filesize.' Bytes';
}
return $filesize;
}
/**
* 字符串加密、解密函数
*
*
* @param string $txt 字符串
* @param string $operation ENCODE为加密,DECODE为解密,可选参数,默认为ENCODE,
* @param string $key 密钥:数字、字母、下划线
* @return string
*/
function sys_auth($txt, $operation = 'ENCODE', $key = '') {
$key = $key ? $key : pc_base::load_config('system', 'auth_key');
$txt = $operation == 'ENCODE' ? (string)$txt : base64_decode($txt);
$len = strlen($key);
$code = '';
for($i=0; $i<strlen($txt); $i++){
$k = $i % $len;
$code .= $txt[$i] ^ $key[$k];
}
$code = $operation == 'DECODE' ? $code : base64_encode($code);
return $code;
}
/**
* 语言文件处理
*
* @param string $language 标示符
* @param array $pars 转义的数组,二维数组 ,'key1'=>'value1','key2'=>'value2',
* @param string $modules 多个模块之间用半角逗号隔开,如:member,guestbook
* @return string 语言字符
*/
function L($language = 'no_language',$pars = array(), $modules = '') {
static $LANG = array();
if(!$LANG) {
$lang = pc_base::load_config('system','lang');
require_once PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.'system.lang.php';
if(defined('IN_ADMIN')) require_once PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.'system_menu.lang.php';
if(file_exists(PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.ROUTE_M.'.lang.php')) require PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.ROUTE_M.'.lang.php';
if(!empty($modules)) {
$modules = explode(',',$modules);
foreach($modules AS $m) {
require PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.$m.'.lang.php';
}
}
}
if(!array_key_exists($language,$LANG)) {
return $LANG['no_language'].'['.$language.']';
} else {
$language = $LANG[$language];
if($pars) {
foreach($pars AS $_k=>$_v) {
$language = str_replace('{'.$_k.'}',$_v,$language);
}
}
return $language;
}
}
/**
* 模板调用
*
* @param $module
* @param $template
* @param $istag
* @return unknown_type
*/
function template($module = 'content', $template = 'index', $style = 'default') {
$template_cache = pc_base::load_sys_class('template_cache');
$compiledtplfile = PHPCMS_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.php';
if(file_exists(PC_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html')) {
if(!file_exists($compiledtplfile) || (@filemtime(PC_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') > @filemtime($compiledtplfile))) {
$template_cache->template_compile($module, $template, $style);
}
} else {
$compiledtplfile = PHPCMS_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.default.php';
if(file_exists(PC_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') && filemtime(PC_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') > filemtime($compiledtplfile)) {
$template_cache->template_compile($module, $template, 'default');
} else {
showmessage('Template does not exist.'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html');
}
}
return $compiledtplfile;
}
/**
* 输出自定义错误
*
* @param $errno 错误号
* @param $errstr 错误描述
* @param $errfile 报错文件地址
* @param $errline 错误行号
* @return string 错误提示
*/
function my_error_handler($errno, $errstr, $errfile, $errline) {
if($errno==8) return '';
$errfile = str_replace(PHPCMS_PATH,'',$errfile);
if(pc_base::load_config('system','errorlog')) {
error_log(date('m-d H:i:s',SYS_TIME).' | '.$errno.' | '.str_pad($errstr,30).' | '.$errfile.' | '.$errline."\r\n", 3, CACHE_PATH.'error_log.php');
} else {
$str = '<div style="font-size:12px;text-align:left; border-bottom:1px solid #9cc9e0; border-right:1px solid #9cc9e0;padding:1px 4px;color:#000000;font-family:Arial, Helvetica,sans-serif;"><span>errorno:' . $errno . ',str:' . $errstr . ',file:<font color="blue">' . $errfile . '</font>,line' . $errline .'<br /><a href="http://faq.phpcms.cn/?type=file&errno='.$errno.'&errstr='.urlencode($errstr).'&errfile='.urlencode($errfile).'&errline='.$errline.'" target="_blank" style="color:red">Need Help?</a></span></div>';
echo $str;
}
}
/**
* 提示信息页面跳转,跳转地址如果传入数组,页面会提示多个地址供用户选择,默认跳转地址为数组的第一个值,时间为5秒。
* showmessage('登录成功', array('默认跳转地址'=>'http://www.phpcms.cn'));
* @param string $msg 提示信息
* @param mixed(string/array) $url_forward 跳转地址
* @param int $ms 跳转等待时间
*/
function showmessage($msg, $url_forward = 'goback', $ms = 1250, $dialog = '') {
if(defined('IN_ADMIN')) {
include(admin::admin_tpl('showmessage', 'admin'));
} else {
include(template('content', 'message'));
}
exit;
}
/**
* 查询字符是否存在于某字符串
*
* @param $haystack 字符串
* @param $needle 要查找的字符
* @return bool
*/
function str_exists($haystack, $needle)
{
return !(strpos($haystack, $needle) === FALSE);
}
/**
* 取得文件扩展
*
* @param $filename 文件名
* @return 扩展名
*/
function fileext($filename) {
return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
}
/**
* 加载模板标签缓存
* @param string $name 缓存名
* @param integer $times 缓存时间
*/
function tpl_cache($name,$times = 0) {
$filepath = 'tpl_data';
$info = getcacheinfo($name, $filepath);
if (SYS_TIME - $info['filemtime'] >= $times) {
return false;
} else {
return getcache($name,$filepath);
}
}
/**
* 写入缓存,默认为文件缓存,不加载缓存配置。
* @param $name 缓存名称
* @param $data 缓存数据
* @param $filepath 数据路径(模块名称) caches/cache_$filepath/
* @param $type 缓存类型[file,memcache,apc]
* @param $config 配置名称
* @param $timeout 过期时间
*/
function setcache($name, $data, $filepath='', $type='file', $config='', $timeout='') {
pc_base::load_sys_class('cache_factory','',0);
if($config) {
$cacheconfig = pc_base::load_config('cache');
$cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
} else {
$cache = cache_factory::get_instance()->get_cache($type);
}
return $cache->set($name, $data, $timeout, '', $filepath);
}
/**
* 读取缓存,默认为文件缓存,不加载缓存配置。
* @param string $name 缓存名称
* @param $filepath 数据路径(模块名称) caches/cache_$filepath/
* @param string $config 配置名称
*/
function getcache($name, $filepath='', $type='file', $config='') {
pc_base::load_sys_class('cache_factory','',0);
if($config) {
$cacheconfig = pc_base::load_config('cache');
$cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
} else {
$cache = cache_factory::get_instance()->get_cache($type);
}
return $cache->get($name, '', '', $filepath);
}
/**
* 删除缓存,默认为文件缓存,不加载缓存配置。
* @param $name 缓存名称
* @param $filepath 数据路径(模块名称) caches/cache_$filepath/
* @param $type 缓存类型[file,memcache,apc]
* @param $config 配置名称
*/
function delcache($name, $filepath='', $type='file', $config='') {
pc_base::load_sys_class('cache_factory','',0);
if($config) {
$cacheconfig = pc_base::load_config('cache');
$cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
} else {
$cache = cache_factory::get_instance()->get_cache($type);
}
return $cache->delete($name, '', '', $filepath);
}
/**
* 读取缓存,默认为文件缓存,不加载缓存配置。
* @param string $name 缓存名称
* @param $filepath 数据路径(模块名称) caches/cache_$filepath/
* @param string $config 配置名称
*/
function getcacheinfo($name, $filepath='', $type='file', $config='') {
pc_base::load_sys_class('cache_factory');
if($config) {
$cacheconfig = pc_base::load_config('cache');
$cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
} else {
$cache = cache_factory::get_instance()->get_cache($type);
}
return $cache->cacheinfo($name, '', '', $filepath);
}
function url($url, $isabs = 0) {
if(strpos($url, '://') !== FALSE || $url[0] == '?') return $url;
$siteurl = get_url();
if($isabs || defined('SHOWJS')) {
$url = strpos($url, WEB_PATH) === 0 ? $siteurl.substr($url, strlen(WEB_PATH)) : $siteurl.$url;
} else {
$url = strpos($url, WEB_PATH) === 0 ? $url : WEB_PATH.$url;
}
return $url;
}
/**
* 生成sql语句,如果传入$in_cloumn 生成格式为 IN('a', 'b', 'c')
* @param $data 条件数组或者字符串
* @param $front 连接符
* @param $in_column 字段名称
* @return string
*/
function to_sqls($data, $front = ' AND ', $in_column = false) {
if($in_column && is_array($data)) {
$ids = '\''.implode('\',\'', $data).'\'';
$sql = "$in_column IN ($ids)";
return $sql;
} else {
if ($front == '') {
$front = ' AND ';
}
if(is_array($data) && count($data) > 0) {
$sql = '';
foreach ($data as $key => $val) {
$sql .= $sql ? " $front `$key` = '$val' " : " `$key` = '$val' ";
}
return $sql;
} else {
return $data;
}
}
}
/**
* 分页函数
*
* @param $num 信息总数
* @param $curr_page 当前分页
* @param $perpage 每页显示数
* @param $urlrule URL规则
* @param $array 需要传递的数组,用于增加额外的方法
* @return 分页
*/
function pages($num, $curr_page, $perpage = 20, $urlrule = '', $array = array()) {
if($urlrule == '') $urlrule = url_par('page={$page}');
$multipage = '';
if($num > $perpage) {
$page = 11;
$offset = 4;
$pages = ceil($num / $perpage);
$from = $curr_page - $offset;
$to = $curr_page + $offset;
$more = 0;
if($page >= $pages) {
$from = 2;
$to = $pages-1;
} else {
if($from <= 1) {
$to = $page-1;
$from = 2;
} elseif($to >= $pages) {
$from = $pages-($page-2);
$to = $pages-1;
}
$more = 1;
}
$multipage .= L('total').'<b>'.$num.'</b> ';
if($curr_page>0) {
$multipage .= ' <a href="'.pageurl($urlrule, $curr_page-1, $array).'" class="a1">'.L('previous').'</a>';
if($curr_page==1) {
$multipage .= ' <span>1</span>';
} elseif($curr_page>6 && $more) {
$multipage .= ' <a href="'.pageurl($urlrule, 1, $array).'">1</a>..';
} else {
$multipage .= ' <a href="'.pageurl($urlrule, 1, $array).'">1</a>';
}
}
for($i = $from; $i <= $to; $i++) {
if($i != $curr_page) {
$multipage .= ' <a href="'.pageurl($urlrule, $i, $array).'">'.$i.'</a>';
} else {
$multipage .= ' <span>'.$i.'</span>';
}
}
if($curr_page<$pages) {
if($curr_page<$pages-5 && $more) {
$multipage .= ' ..<a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.L('next').'</a>';
} else {
$multipage .= ' <a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.L('next').'</a>';
}
} elseif($curr_page==$pages) {
$multipage .= ' <span>'.$pages.'</span> <a href="'.pageurl($urlrule, $curr_page, $array).'" class="a1">'.L('next').'</a>';
} else {
$multipage .= ' <a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.L('next').'</a>'; }
}
return $multipage;
}
/**
* 返回分页路径
*
* @param $urlrule 分页规则
* @param $page 当前页
* @param $array 需要传递的数组,用于增加额外的方法
* @return 完整的URL路径
*/
function pageurl($urlrule, $page, $array = array()) {
if(strpos($urlrule, '#')) {
$urlrules = explode('#', $urlrule);
$urlrule = $page < 2 ? $urlrules[0] : $urlrules[1];
}
$findme = array('{$page}');
$replaceme = array($page);
if (is_array($array)) foreach ($array as $k=>$v) {
$findme[] = '{$'.$k.'}';
$replaceme[] = $v;
}
$url = str_replace($findme, $replaceme, $urlrule);
return $url;
}
/**
* URL路径解析,pages 函数的辅助函数
*
* @param $par 传入需要解析的变量 默认为,page={$page}
* @param $url URL地址
* @return URL
*/
function url_par($par, $url = '') {
if($url == '') $url = get_url();
$pos = strpos($url, '?');
if($pos === false) {
$url .= '?'.$par;
} else {
$querystring = substr(strstr($url, '?'), 1);
parse_str($querystring, $pars);
$query_array = array();
foreach($pars as $k=>$v) {
$query_array[$k] = $v;
}
$querystring = http_build_query($query_array).'&'.$par;
$url = substr($url, 0, $pos).'?'.$querystring;
}
return $url;
}
/**
* 判断email格式是否正确
* @param $email
*/
function is_email($email) {
return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}
/**
* iconv 编辑转换
*/
if (!function_exists('iconv')) {
function iconv($in_charset, $out_charset, $str) {
$in_charset = strtoupper($in_charset);
$out_charset = strtoupper($out_charset);
if (function_exists('mb_convert_encoding')) {
return mb_convert_encoding($str, $out_charset, $in_charset);
} else {
pc_base::load_sys_func('iconv');
$in_charset = strtoupper($in_charset);
$out_charset = strtoupper($out_charset);
if($in_charset == 'UTF-8' && ($out_charset == 'GBK' || $out_charset == 'GB2312')) {
return utf8_to_gbk($str);
}
if(($in_charset == 'GBK' || $in_charset == 'GB2312') && $out_charset == 'UTF-8') {
return gbk_to_utf8($str);
}
return $str;
}
}
}
/**
* 代码广告展示函数
* @param intval $siteid 所属站点
* @param intval $id 广告ID
* @return 返回广告代码
*/
function show_ad($siteid, $id) {
$siteid = intval($siteid);
$id = intval($id);
if(!$id || !$siteid) return false;
$p = pc_base::load_model('poster_model');
$r = $p->get_one(array('spaceid'=>$id, 'siteid'=>$siteid), 'setting', '`id` ASC');
if ($r['setting']) {
$c = string2array($r['setting']);
} else {
$r['code'] = '';
}
return $c['code'];
}
/**
* 获取当前的站点ID
*/
function get_siteid() {
static $siteid;
if (!empty($siteid)) return $siteid;
if (defined('IN_ADMIN')) {
if ($d = param::get_cookie('siteid')) {
$siteid = $d;
} else {
return '';
}
} else {
$data = getcache('sitelist', 'commons');
$site_url = SITE_PROTOCOL.SITE_URL;
foreach ($data as $v) {
if ($v['url'].'/' == $site_url) $siteid = $v['siteid'];
}
}
return $siteid;
}
/**
* 调用关联菜单
* @param $linkageid
* @param $id
* @param $defaultvalue
*/
function menu_linkage($linkageid = 0, $id = 'linkid', $defaultvalue = 0) {
$linkageid = intval($linkageid);
$datas = array();
$datas = getcache($linkageid,'linkage');
$infos = $datas['data'];
$title = $defaultvalue ? $infos[$defaultvalue]['name'] : $datas['title'];
$colObj = random(3).date('is');
$string = '';
if(!defined('LINKAGE_INIT')) {
define('LINKAGE_INIT', 1);
$string .= '<script type="text/javascript" src="'.JS_PATH.'linkage/js/mln.colselect.js"></script>';
if(defined('IN_ADMIN')) {
$string .= '<link href="'.JS_PATH.'linkage/style/admin.css" rel="stylesheet" type="text/css">';
} else {
$string .= '<link href="'.JS_PATH.'linkage/style/css.css" rel="stylesheet" type="text/css">';
}
}
$string .= '<input type="hidden" name="info['.$id.']" value="1"><div id="'.$id.'"></div>';
$string .= '<script type="text/javascript">';
$string .= 'var colObj'.$colObj.' = {"Items":[';
foreach($infos AS $k=>$v) {
$s .= '{"name":"'.$v['name'].'","topid":"'.$v['parentid'].'","colid":"'.$k.'","value":"'.$k.'","fun":function(){}},';
}
$string .= substr($s, 0, -1);
$string .= ']};';
$string .= '$("#'.$id.'").mlnColsel(colObj'.$colObj.',{';
$string .= 'title:"'.$title.'",';
$string .= 'value:"'.$defaultvalue.'",';
$string .= 'width:100';
$string .= '});';
$string .= '</script>';
return $string;
}
/**
* 判断字符串是否为utf8编码,英文和半角字符返回ture
* @param $string
* @return bool
*/
function is_utf8($string) {
return preg_match('%^(?:
[\x09\x0A\x0D\x20-\x7E] # ASCII
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)*$%xs', $string);
}
/**
* 获取UCenter数据库配置
*/
function get_uc_database() {
$config = pc_base::load_config('system');
return array (
'hostname' => $config['uc_dbhost'],
'database' => $config['uc_dbname'],
'username' => $config['uc_dbuser'],
'password' => $config['uc_dbpw'],
'tablepre' => $config['uc_dbtablepre'],
'charset' => $config['uc_dbcharset'],
'type' => 'mysql',
'debug' => true,
'pconnect' => 0,
'autoconnect' => 0
);
}
?>
|
108wo
|
phpsso_server/phpcms/libs/functions/global.func.php
|
PHP
|
asf20
| 25,869
|
<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_sys_class('model', '', 0);
class messagequeue_model extends model {
public function __construct() {
$this->db_config = pc_base::load_config('database');
$this->db_setting = 'default';
$this->table_name = 'messagequeue';
parent::__construct();
}
}
?>
|
108wo
|
phpsso_server/phpcms/model/messagequeue_model.class.php
|
PHP
|
asf20
| 348
|
<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_sys_class('model', '', 0);
class credit_model extends model {
public function __construct() {
$this->db_config = pc_base::load_config('database');
$this->db_setting = 'default';
$this->table_name = 'members';
parent::__construct();
}
}
?>
|
108wo
|
phpsso_server/phpcms/model/credit_model.class.php
|
PHP
|
asf20
| 338
|
<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_sys_class('model', '', 0);
class admin_model extends model {
public function __construct() {
$this->db_config = pc_base::load_config('database');
$this->db_setting = 'default';
$this->table_name = 'admin';
parent::__construct();
}
}
?>
|
108wo
|
phpsso_server/phpcms/model/admin_model.class.php
|
PHP
|
asf20
| 334
|
<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_sys_class('model', '', 0);
class session_model extends model {
public function __construct() {
$this->db_config = pc_base::load_config('database');
$this->db_setting = 'default';
$this->table_name = 'session';
parent::__construct();
}
}
?>
|
108wo
|
phpsso_server/phpcms/model/session_model.class.php
|
PHP
|
asf20
| 338
|
<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_sys_class('model', '', 0);
class uc_model extends model {
public function __construct($db_config) {
$this->db_config = array('ucenter'=>$db_config);
$this->db_setting = 'ucenter';
$this->table_name = 'members';
parent::__construct();
}
}
?>
|
108wo
|
phpsso_server/phpcms/model/uc_model.class.php
|
PHP
|
asf20
| 339
|
<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_sys_class('model', '', 0);
class member_model extends model {
public function __construct() {
$this->db_config = pc_base::load_config('database');
$this->db_setting = 'default';
$this->table_name = 'members';
parent::__construct();
}
public function get_version() {
return $this->db->version();
}
public function get_table_status() {
$this->db->query("SHOW TABLE STATUS LIKE '$this->db_tablepre%'");
$datalist = array();
while(($rs = $this->db->fetch_next()) != false) {
$datalist[] = $rs;
}
$this->db->free_result();
return $datalist;
}
}
?>
|
108wo
|
phpsso_server/phpcms/model/member_model.class.php
|
PHP
|
asf20
| 680
|
<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_sys_class('model', '', 0);
class member_model extends model {
public function __construct() {
$this->db_config = pc_base::load_config('database');
$this->db_setting = 'default';
$this->table_name = 'members';
parent::__construct();
}
}
?>
|
108wo
|
phpsso_server/phpcms/model/cache_model.class.php
|
PHP
|
asf20
| 337
|
<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_sys_class('model', '', 0);
class settings_model extends model {
public function __construct() {
$this->db_config = pc_base::load_config('database');
$this->db_setting = 'default';
$this->table_name = 'settings';
parent::__construct();
}
}
?>
|
108wo
|
phpsso_server/phpcms/model/settings_model.class.php
|
PHP
|
asf20
| 340
|